Compare commits

...

10 Commits

Author SHA1 Message Date
dsh-bot 122b249302 feat(v1.1): DSH workspace-level skill writes with project isolation 2026-11-11 23:27:15 +08:00
dsh-bot 01581beb0f test(v1.1): whole-plugin load smoke + route coverage 2026-11-11 23:23:31 +08:00
dsh-bot 33bbf5264c feat(v1.1): cross-software workspace inventory + dsh-brain data migration 2026-11-11 23:21:42 +08:00
dsh-bot 3b8f093d80 feat(p5): neutral default, theme/concurrency/upgrade guards, pack hygiene 2026-11-11 23:16:21 +08:00
dsh-bot 6c39eddf4a feat(p4): full MCP market, custom/import connections, scope and policy 2026-11-11 23:12:35 +08:00
dsh-bot 3336fa8d26 feat(p3): skill marketplace, sync conflict resolution, update/rollback 2026-11-11 23:07:22 +08:00
qyh15 6eadbaf90c feat(skills): multi-source skill tree with metadata-only categories
- sources: DSH / 公共 Agent / Codex / WorkBuddy / Claude Code / OpenCode, detected per refresh
- categories stored as metadata only; delete releases skills to 未分类, never touches files
- switches: DSH parks/unparks for real; foreign sources answer cardOnly and stay untouched
- client: source → category → skill tree, inline create/rename/delete/assign, per-source reveal
- verify-skill-tree.mjs (40 checks) + render harness expansion (23 checks)
- preview-card.mjs renders the real tree to PNG via headless Chrome for layout review
2026-11-11 21:09:08 +08:00
qyh15 a97cf03581 test: entry-point smoke test (apply/routes/tools/dispose) 2026-11-11 20:47:04 +08:00
qyh15 56ef643449 test: render-level smoke test for the client card; lazy-load tabs on reopen
- verify-card-render.mjs: minimal React runtime + stubbed fetch, renders all
  three tabs with real payloads and the missing-bridge case (17 checks)
- client: fetch skills/MCP when the tab is restored from local storage,
  not only on a click; keep the tools-vs-connection note always visible
- mnemon provider version follows the package (0.5.0)
2026-11-11 20:44:52 +08:00
qyh15 1a3a6fb23b feat: unified management card (tabs, auth switch, skill plans, MCP bridge)
- settings card: 连接与上报 / 技能管理 / MCP 管理 三页签,身份验证卡内切换
- config: 服务 origin 变更时清除旧令牌并返回 credentialsCleared
- status: capabilities、lastCheck、baseUrlConfigured/origin
- skills: detail / install plan+commit+cancel / uninstall plan + 一次性 token
- mcp: 通过宿主 /mcp-connector/api 读写连接,探测不到时明确缺口
- tests: verify-brain-panel.mjs (53) + verify-skill-admin.mjs (15) 全过
- docs: management-surface.md
2026-11-11 20:41:34 +08:00
49 changed files with 11548 additions and 760 deletions

4
.gitignore vendored
View File

@ -20,3 +20,7 @@ Thumbs.db
npm-debug.log*
node_modules/
.cloud-memory/
# generated previews (node preview-card.mjs)
_preview/
preview-debug.mjs

View File

@ -200,3 +200,28 @@ pnpm publish --access public --no-git-checks
`prepack` 会先重建 `lib/`,`prepublishOnly` 会先跑 `pack-guard`:包里一旦出现 `AGENTS.md`、`TODO.md`、`*.mjs` 探测脚本、`tsconfig*.json`、本机路径、个人域名或令牌原文,发布立刻中止。
> lifecycle 脚本要求 `node` 在 `PATH` 里。若报 `'node' is not recognized`,先把 DSH 运行时自带 node 的 `bin` 目录加进 `$env:Path` 再发布。
## 统一管理卡(0.7.0)
「设置 → 云端记忆」现在是三个页签:**连接与上报 / 技能管理 / MCP 管理**。
- 身份验证卡内切换「账号登录 / 手动令牌」,切换不清凭据、不发请求。
- 服务地址换 origin 时,旧令牌一律清除(`credentialsCleared`),要求重新认证。
- 技能安装是两步:`install/plan` 把仓库克隆到隔离暂存目录并列出候选(含冲突、脚本、体积),`install/commit` 只写入选中的目录;`.git` 与符号链接不复制,仓库脚本不执行。
- 卸载同样是两步:`uninstall/plan` 给出真实目录、文件数与不可恢复提示并签发一次性 token,`remove` 必须带 `confirmed: true` 与匹配 token。
- **技能市场(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` 提供两侧信息,逐项「保留本地 / 采用云端 / 手动合并」。
- **MCP 管理(P4)**:读取宿主 `dsh-mcp-connector` 的同源公开接口 `/mcp-connector/api`;覆盖连接、健康检查、工具、启停、重连、两段式移除、目录市场连接、自定义 HTTP/stdio、JSON 导入、配置编辑、作用域与治理策略。
接口清单见 `docs/management-surface.md`;验收脚本见 `verify-*.mjs`(含 `verify-market` / `verify-skill-update` / `verify-sync-resolve` / `verify-mcp-bridge` / `verify-upgrade` / `verify-concurrency` / `verify-theme`)。
### 技能来源树
「技能管理」按软件来源分组(DSH / 公共 Agent / Codex / WorkBuddy / Claude Code / OpenCode),
每个来源下是分类,分类下是技能:
- 分类只记在 `$DSH_HOME/cloud-memory-skill-groups.json` 里,**不移动文件**;删除分类只是把技能放回「未分类」。
- 只有 DSH 来源的开关是真的(目录移入/移出 `skills-disabled`,新会话生效);其他软件的目录本卡只读,开关标记为「仅本卡」。
- 来源行提供「+ 新建分类」「打开目录」「来源开关」;分类行提供「+ 加入技能 / 改名 / 删除 / 分类开关」;技能行提供详情、启停、卸载。
- 预览(真实数据、光照/暗色):`node preview-card.mjs` 生成 `_preview/skill-tree*.png`。

File diff suppressed because it is too large Load Diff

297
docs/management-surface.md Normal file
View File

@ -0,0 +1,297 @@
# 统一管理卡接口与契约(0.5.0)
本文件记录 0.5.0 交付的「连接与上报 / 技能管理 / MCP 管理」三页签所依赖的真实接口、约束与验证结果。凡是未实现的能力都在这里写明,不在界面上假装可用。
## 1. 路由
| 方法 | 路径 | 说明 |
|---|---|---|
| GET | `/cloud-memory` | 自带配置页(旧入口,保留) |
| GET | `/cloud-memory/status` | 设置 + 令牌掩码 + 上报计数 + `lastCheck` + `capabilities` |
| GET | `/cloud-memory/capabilities` | 能力清单与缺口说明 |
| PUT | `/cloud-memory/config` | 写配置;换 origin 时返回 `credentialsCleared` |
| POST | `/cloud-memory/login` | 账号一次性换取令牌 |
| POST | `/cloud-memory/test` | 只读分项检查:`network` / `activity` / `memory` / `summary` |
| POST | `/cloud-memory/flush` | 重试上报队列 |
| GET | `/cloud-memory/skills/api` | 技能清单 + `plans`(未完成安装计划) |
| POST | `/cloud-memory/skills/detail` | `{folder}` → SKILL.md、文件清单、哈希 |
| POST | `/cloud-memory/skills/toggle` | `{folder, enabled}` → 目录移动 + 生效范围说明 |
| POST | `/cloud-memory/skills/install/plan` | `{url}` → 暂存克隆 + 候选描述 |
| POST | `/cloud-memory/skills/install/commit` | `{planId, folders}` → 只装选中项 |
| POST | `/cloud-memory/skills/install/cancel` | `{planId}` → 丢弃暂存 |
| POST | `/cloud-memory/skills/install` | 旧页面用的一次性安装(等于 plan + 全部非冲突项) |
| POST | `/cloud-memory/skills/uninstall/plan` | `{folder}` → 影响预览 + 一次性 token |
| POST | `/cloud-memory/skills/remove` | `{folder, token, confirmed:true}` → 真实删除 |
## 2. 契约要点
### 2.1 服务地址与凭据
- `settings.baseUrlConfigured=false` 表示地址仍是打包占位符,界面必须显示「未配置服务」。
- 写入配置时若 `new origin != old origin`:本次请求没有显式提供新值的令牌全部删除,响应带 `credentialsCleared: ['activity','memory','summary']`。旧服务的 bearer token 绝不会被发往新 origin。
- 令牌只以掩码形式出现在 `status`;清除是独立动作(`clear*Token`)。
### 2.2 检查状态
`POST /test` 返回 `checks[]`,每项 `{id,label,state,message}`,`state ∈ ok | unconfigured | invalid | forbidden | unreachable | error`。鉴权通过与「已写入一条上报」分开显示;`:reach()` 只证明服务可达。
### 2.3 技能安装
1. `plan`:只接受 `https://` / `file://`;`git clone --depth 1` 到 `$DSH_HOME/.cloud-memory-staging/<planId>`;候选深度 ≤ 3、≤ 60 个;描述含 `files`、`bytes`、`scripts`、`conflict`、`problem`。
2. 计划记录只保存 `planId / url / createdAt / expiresAt / stagingDir / candidates` 元数据,TTL 30 分钟;过期计划连暂存目录一起清理。
3. `commit`:只安装 `folders` 里且计划中存在的候选;`conflict`/`problem` 一律跳过;`.git` 与符号链接在 `cp` filter 中被剔除;源与目标都校验在各自根目录内(`path_escape`)。
4. 不执行仓库里的任何脚本、钩子或依赖命令;需要执行时由用户另行决定。
### 2.4 技能卸载
`uninstall/plan` 返回真实目录、文件数、字节数、含脚本列表、`recoverable:false` 与提示,并签发绑定该目录的一次性 token(10 分钟);`remove` 必须同时满足 `confirmed:true` + 该 folder 的 token,token 用后即废,换目录无效。没有回收站,删除即不可恢复,界面必须原样说明。
### 2.5 启停
启停仍是把目录移进/移出 `$DSH_HOME/skills-disabled/`,属于**新会话生效**;已加载会话不受影响。接口在响应里带这条说明,界面不得宣称立即生效。
### 2.6 MCP 桥接
MCP 页签不新建凭据库,读取宿主 `dsh-mcp-connector`(0.2.88)同源公开接口:
```
POST /mcp-connector/api { "method": "status" | "healthCheck" | "toolsList" | "setEnabled" | "reconnect" | "disconnect" | ..., "params": {...} }
```
- 探测失败(404/超时/非 200)→ 界面显示能力缺口,并指向「设置 → 插件配置 → MCP 服务器配置」这一权威入口。
- 只展示 `name / transport / authMode / enabled / connectionState / injectionLabel / scope / healthCheckedAt / lastError`;不回显 stdio 启动命令、env、token 或敏感 header。
- 工具缓存与连接状态分开显示:工具可见 ≠ 业务可调用。
- 市场条目与远端文本视为不可信内容,不内嵌执行。
## 3. 已执行验证(Windows,本机 Node v24.21.0)
- `verify-brain-panel.mjs`:53 项全过(status/capabilities、config 换 origin 清凭据、方法/Origin/Content-Type 闸门、技能清单与详情、安装计划与选择、冲突跳过、计划过期、暂存清理、卸载预览与一次性 token、路径穿越拒绝)。
- `verify-skill-admin.mjs`:15 项全过(含与同步引擎的联动:已停用技能不被云端更新重新启用)。
- `tsc -p tsconfig.build.json` 与 `tsc -p tsconfig.json --noEmit`:无错误。
## 4. 明确未完成
- 技能市场:无经验证来源,`features.skillsMarketplace=false`。
- 云端同步冲突的交互式处理(保留本地/采用云端/手动合并):仍由现有引擎按原策略暂停冲突项,界面只读展示。
- 自动更新与版本回退:未实现(无来源清单与制品基线)。
- MCP 市场的内嵌浏览与安装:未实现,只给宿主面板位置。
- 跨软件(Codex / Claude Code / OpenCode)适配与工作区级作用域:未实现,仍在方案 P0/P4 调研项。
- 浏览器端实机验收(375/574/1280 宽、深色模式、真实上报):需要重启 DSH 后由用户在界面确认。
## 5. 技能来源树(0.5.0 增补)
「技能管理」页签按软件来源组织,来源→分类→技能三层,与工作方式一致:DSH 来源是真的,其他软件目录只读。
### 5.1 来源检测
| id | 标签 | 目录 | 本卡权限 |
|---|---|---|---|
| `dsh` | DSH | `$DSH_HOME/skills`(停用区 `$DSH_HOME/skills-disabled`) | 真实启停 |
| `agents` | 公共 Agent | `~/.agents/skills` | 只读 |
| `codex` | Codex | `~/.codex/skills` | 只读 |
| `workbuddy` | WorkBuddy | `~/.workbuddy/skills` | 只读 |
| `claude` | Claude Code | `~/.claude/skills` | 只读 |
| `opencode` | OpenCode | `~/.config/opencode/skills` | 只读 |
目录不存在也照实显示 0 个(标注「目录还不存在」),不猜、不造。检测每次刷新时重算。
### 5.2 分类是纯元数据
`$DSH_HOME/cloud-memory-skill-groups.json` 只存 `{sourceId: {enabled, groups: [{id,name,enabled,skills:[folder]}]}}`。
- 新建 / 改名 / 删除分类都不移动任何文件;删除分类只是把成员释放回「未分类」,接口返回 `released` 数量。
- 一个技能最多属于一个分类:加入新分类会先从旧分类移除。
- 未分类是合成分组(`id: 'unassigned'`),它的开关对该来源里所有未被分类的技能逐个生效。
### 5.3 开关的真实边界
| 位置 | DSH 来源 | 其他来源 |
|---|---|---|
| 来源开关 | 真实:全部技能移入/移出 `skills-disabled` | `cardOnly: true`,只记在本卡,不动它们的目录 |
| 分类开关 | 真实:该分类成员逐个启停,返回 `applied` / `failed` | `cardOnly: true` |
| 技能开关 | 真实(目录移动) | 不提供(行内标「只读」) |
任何真实启停都是目录移动,属于**新会话生效**;已在运行的会话保留旧状态。失败项逐条返回,不整批回滚成谎报成功。
### 5.4 接口
| 方法 | 路径 | 说明 |
|---|---|---|
| GET | `/cloud-memory/skills/sources` | 整棵树 + `note`(分类不移动文件、只有 DSH 真实启停) |
| POST | `/cloud-memory/skills/groups/create` | `{sourceId, name}` |
| POST | `/cloud-memory/skills/groups/rename` | `{sourceId, groupId, name}` |
| POST | `/cloud-memory/skills/groups/delete` | `{sourceId, groupId}` → `{released}` |
| POST | `/cloud-memory/skills/groups/assign` | `{sourceId, groupId, folders[]}`;`groupId:'unassigned'` 或空数组=移出分类 |
| POST | `/cloud-memory/skills/groups/toggle` | `{sourceId, groupId, enabled}` → `{cardOnly, applied[], failed[]}` |
| POST | `/cloud-memory/skills/source/toggle` | `{sourceId, enabled}` → `{cardOnly, applied, failed[]}` |
| POST | `/cloud-memory/skills/source/reveal` | `{sourceId}` → 在系统文件管理器打开该来源根目录(仅已登记的源) |
错误码:`unknown_source` / `not_found` → 404,`invalid_name` / `duplicate` / `too_many` → 400。
### 5.5 验证
`verify-skill-tree.mjs`:40 项通过——来源与计数、分类增删改、成员唯一性、DSH 真实 park/unpark、「未分类」开关只作用于未分类技能、外来源 `cardOnly` 且目录字节不变、持久化重开、路由闸门与错误码。
## 6. P3:技能市场 / 同步冲突 / 更新回退(0.6.0)
### 6.1 市场来源
首个经验证来源是 Anthropic 公开的 Claude 技能市场清单
`https://raw.githubusercontent.com/anthropics/skills/main/.claude-plugin/marketplace.json`。
客户端只传 `provider` 与条目 `id`,**从不传仓库地址**,因此宿主不会去拉取任意 URL。
| 方法 | 路径 | 说明 |
|---|---|---|
| GET | `/cloud-memory/market/providers` | 已配置来源(id/标签/仓库) |
| GET | `/cloud-memory/market/search` | `?provider=&q=&cursor=` → 条目分页 |
| POST | `/cloud-memory/market/detail` | `{provider,id}` → 逐技能 SKILL.md 元数据 |
| POST | `/cloud-memory/market/plan` | `{provider,id}` → 解析提交 + 克隆暂存计划(只列该条目技能) |
| POST | `/cloud-memory/market/commit` | `{planId,folders}` → 只装勾选项 |
| POST | `/cloud-memory/market/cancel` | `{planId}` → 丢弃暂存 |
`resolveArtifact` 通过 GitHub API 解析固定提交;克隆后以 `git rev-parse HEAD` 记录**实际**提交,安装失败不会留下半装目录。
### 6.2 来源记录与更新/回退
安装(Git 或市场)会在技能目录写入 `.skill-source.json`:`provider / repoUrl / ref / commit / sourcePath / entryId / installedAt`,不含任何凭据。
| 方法 | 路径 | 说明 |
|---|---|---|
| POST | `/cloud-memory/skills/update/check` | `{folder}` → 与来源最新提交比较,返回 added/removed/changed |
| POST | `/cloud-memory/skills/update/apply` | `{folder,expectedCommit}` → 更新前整目录备份,再切换并重写记录 |
| POST | `/cloud-memory/skills/rollback` | `{folder}` → 恢复最近一次更新前备份 |
安全点:只信任来源记录里的仓库地址;新克隆在 `$DSH_HOME/.cloud-memory-staging`,复制时剔除 `.git` 与符号链接;`expectedCommit` 过期返回 `stale_plan`,绝不覆盖;同步进行中拒绝写。
### 6.3 同步冲突交互
`SkillSync` 仍然只按原策略暂停冲突项,但会暴露两侧信息并允许人工处置:
| 方法 | 路径 | 说明 |
|---|---|---|
| GET | `/cloud-memory/sync/status` | 最近统计 + 每个冲突的本地/云端两侧 |
| POST | `/cloud-memory/sync/run` | 立即执行一次同步 |
| POST | `/cloud-memory/sync/resolve` | `{name,action}`:`keep_local` / `take_cloud` / `manual` |
- `keep_local`:用本地文件按当前云端 revision 上传为新版本;revision 过期返回 `stale_revision`。
- `take_cloud`:先把本地目录备份到 `$DSH_HOME/.cloud-memory-backups/sync/<name>/<时间>`,再写入云端 bundle。
- `manual`:只返回两侧信息,不改任何文件。
### 6.4 验证
- `verify-market.mjs`:19 项通过(清单解析、search/detail、未知来源 400、plan 固定提交、只装勾选项、来源记录)。
- `verify-skill-update.mjs`:15 项通过(真实 git 仓库的 check/apply/rollback、无来源拒绝、过期提交拒绝、备份存在)。
- `verify-sync-resolve.mjs`:12 项通过(一次真实 pass 产生 4 个冲突、take_cloud 备份并覆盖、keep_local 上传、manual 只读、stale 拒绝)。
## 7. P4:MCP 管理与市场(0.6.0)
MCP 页签不新建凭据库,全部读写都走宿主 **dsh-mcp-connector 0.2.88** 的同源公开接口
`POST /mcp-connector/api`。该接口是**方法白名单**(不是任意反射调用),已实测可用方法包括:
`versionStatus, governance, previewPolicy, applyPolicy, rollbackPolicy, scopeContext,
previewConnectionScope, applyConnectionScope, previewConnectionScopeRollback, rollbackConnectionScope,
connectionStatistics, catalog, status, healthCheck, connect, configure, importJson, exportConfig,
listSnapshots, createSnapshot, previewSnapshot, restoreSnapshot, installFromUrl, renameConnection,
editableConnectionConfig, reconfigureConnection, disconnect, setEnabled, reconnect, setInjectionMode,
refreshCatalog, toolsList, toolSearch, toolExplorer, toolDetail`
### 7.1 本卡实现
| 区块 | 能力 |
|---|---|
| 我的连接 | 读取连接(名称/传输/鉴权/启用/状态/注入方式/范围/健康时间/最近错误)、健康检查、工具缓存、启停、重连、两段式移除 |
| MCP 市场 | `catalog` 目录浏览与搜索;无认证直接 `connect`;OAuth 走浏览器授权 `connect`;bearer / api-key 通过 `configure` 填凭据(只写宿主,不回显) |
| 新增 / 导入 | 自定义 Streamable HTTP 与 stdio 连接(显示实际启动命令,云端不执行)、`importJson` 批量导入 |
| 配置编辑 | `editableConnectionConfig` 读取(敏感值以 `<KEEP_EXISTING>` 保留标记返回),`reconfigureConnection` 保存;空输入不清除已有密钥 |
| 范围 | `previewConnectionScope` → `applyConnectionScope`,带 `expectedRevision`,`mode=move`,凭据不复制 |
| 治理 | `governance` 读取 revision/规则/优先级;connection 级 `previewPolicy` → `applyPolicy`(allow / deny / inherit),同样带 `expectedRevision` |
### 7.2 明确的边界
- 本卡不保存、不回显 MCP 凭据与 stdio 环境变量;一切都写宿主。
- 目录条目、工具描述、示例与远端文本一律视为**不可信内容**,只展示、不执行。
- Host 不支持 `tools.guard` 时,`deny` 策略会被宿主拒绝并如实显示,不会假装已生效。
- 自定义 MCP Server 的权威位置仍是「设置 → 插件配置 → MCP 服务器配置」;本卡通过同一公开接口管理,不手改托管配置区块。
- 工具可见性 ≠ 会话级可调用:本卡展示连接与工具缓存,**按会话选择精确工具后激活**由宿主 `session-tools`/agent 工具负责(其不在 `/mcp-connector/api` 白名单内),本卡不伪造激活。
### 7.3 验证
- `verify-mcp-bridge.mjs`(连运行中的 DSH)实测 **8/8** 通过:versionStatus、catalog(116 个已上架连接器)、governance、scopeContext、status、connectionStatistics、listSnapshots 全部 `ok:true`。
- `verify-card-render.mjs` 覆盖 MCP 页签在无桥接时的能力缺口文案,以及存在桥接时的分区渲染。
## 8. P5:集成发布(0.6.0)
### 8.1 暗色 / 窄屏
- 卡片全部使用主题相对色(`rgba(127,127,127,…)` 中性色 + `rgba(37,99,235,…)` 蓝色强调),不硬编码浅色专用颜色;切换开关的白色圆点用 `rgba(255,255,255,0.96)`。
- 长行、页签与操作区声明 `flexWrap: 'wrap'`,窄设置面板不会出现横向滚动;不固定 375px 专用宽度。
- `verify-theme.mjs`:6 项通过(无纯白/纯黑硬编码、中性/强调 token 使用次数、换行行数、页签换行、无固定窄宽)。
### 8.2 并发保护
所有会改文件的入口在同步进行中一律拒绝,绝不半写:
| 入口 | 行为 |
|---|---|
| `skills/install/plan` `install/commit` | `sync_running` |
| `skills/toggle` `skills/remove` | `sync_running` |
| `skills/update/apply` `skills/rollback` | `sync_running` |
| `sync/resolve` | `sync_running` |
HTTP 层统一映射为 **409 `sync_running`**。`verify-concurrency.mjs`:8 项通过(六个入口 + 路由 409 + 同步结束后放行)。
### 8.3 升级迁移(UPGRADE-01)
- 配置 sidecar 仍是 `version:1`;0.4.1 写入的 `baseUrl / clientId / requestTimeoutMs / defaultK / 三个 token / summary` 全部按原值读回,未知的未来字段被忽略而不是致命。
- **默认地址改为中性占位符** `https://your-memory-host/api/longmemory`:新装显示「未配置服务」,已配置用户由 sidecar 中的真实地址覆盖,不受影响。个人域名不再随包外发。
- 二次构造 `SettingsStore` 模拟重启,读到相同值;损坏文件降级为默认值,不阻断激活。
- `verify-upgrade.mjs`:11 项通过。
### 8.4 制品校验与回退
- `node scripts/pack-guard.mjs`:按 `files` 白名单展开真实入包文件,文件名黑名单(笔记/工程文件/`*.mjs`/`tsconfig*`/锁文件)与内容黑名单(个人域名、`C:\Users\…`、`cmt_…` 令牌原文)全部通过。
- 回退:代码层用 Git 提交与分支回退;本机配置由 sidecar 原子写(tmp + rename)保护;MCP 连接由宿主快照(`listSnapshots/restoreSnapshot`)保护;技能更新前自动备份到 `$DSH_HOME/.cloud-memory-backups`,可 `skills/rollback` 恢复。
## 9. v1.1:跨软件与工作区分层(0.7.0)
### 9.1 ClientAdapter 与清单
`src/clients.ts` 为六个软件实例提供统一的只读清单:`dsh / agents / codex / workbuddy / claude / opencode`。
每个适配器声明 `installed / configRoot / globalSkillsRoot / writable / workspaceSupported`;能力契约另给出
`readGlobal / writeGlobal / workspaceRead / workspaceWrite / hotReload / verify`。
| 方法 | 路径 | 说明 |
|---|---|---|
| GET | `/cloud-memory/clients/overview` | 适配器、能力、每个软件的工作区、Brain 命名信息 |
| GET | `/cloud-memory/clients/inventory` | `?software=&scope=global|workspace&workspaceId=` |
| POST | `/cloud-memory/clients/workspaces/add` | `{software,path,name}` 登记工作区(只存元数据) |
| POST | `/cloud-memory/clients/workspaces/remove` | `{software,id}` |
### 9.2 工作区发现与有效配置
- DSH 工作区来自宿主自己的 `workspace-groups.folders.json`(成员路径)与 `workspace-groups.manual.json`(分类),**不执行全盘扫描、不读会话库**。
- 其他软件的工作区只来自用户显式登记;路径失效会如实报告,不静默删除登记。
- 工作区技能目录按该软件自己的约定探测:`<ws>/.dsh/skills`、`<ws>/.codex/skills`、`<ws>/.claude/skills`、`<ws>/.opencode/skills|skill`。找不到就是空,**绝不写通用目录冒充工作区配置**。
### 9.3 写入边界(能力与缺口)
- **DSH 用户级与 DSH 工作区级技能目录均可写**:工作区写使用工作区专属 `SkillAdmin`(根为 `<ws>/.dsh/skills`,停用区为 `$DSH_HOME/skills-workspace-disabled/<workspaceId>`,一个项目不会解停另一个项目的技能)。
- **其他软件一律只读**(`workspaceWrite=false`、item `writable=false`);不支持的组合显式标注,绝不写通用目录冒充。
- 工作区写路由:`GET /cloud-memory/clients/workspace/inventory`、`POST .../workspace/{detail,toggle,remove,install/plan,install/commit}`;非 DSH 返回 501。
### 9.4 dsh-brain 数据迁移(RENAME-01 数据半区)
- `GET /cloud-memory/migrate/brain` 报告旧文件与目标文件状态、`packageRename: pending-deploy`。
- `POST /cloud-memory/migrate/brain` 把 `cloud-memory.json / -skills.json / -skill-groups.json` 复制为 `dsh-brain*.json`,**保留旧文件、不覆盖已存在目标、幂等**。
- 实际包名、客户端模块 id 与 profile 加载入口的切换是**部署步骤**,需要完全重启 DSH;不在运行中的会话里静默改名,避免同时注册或丢配置。
### 9.5 验证
- `verify-clients.mjs`:19 项通过(六适配器、安装检测、只读边界、DSH 注册工作区+分类、工作区专属技能、手动登记/去重/未知工作区、路由、能力位、迁移幂等与原文件保留)。
- `verify-workspace-write.mjs`:14 项通过(DSH 工作区可写、只读判定、停用/启用/删除/安装的跨工作区与全局隔离、非 DSH 拒绝 501、路由)。
- `verify-full-load.mjs`:12 项通过——用真实 `apply()` 在宿主形状上下文加载 0.7.0,起真实 HTTP 服务后逐一查询 capabilities(0.7.0 + P3/P4/P5/v1.1 能力位)、market/providers、sync/status、clients/overview(6 适配器)、clients/inventory、migrate/brain、skills/api、status,全部返回正常。

View File

@ -115,6 +115,25 @@ export class CloudClient {
reportTurn(payload, token) {
return this.request('POST', '/activity/turn', payload, token);
}
/**
* Read-only reachability probe: any HTTP answer (even 401 or 404) proves the
* host is up. This is what separates "服务不可达" from "令牌无效" in the card,
* and it never sends a credential.
*/
async reach() {
try {
const response = await fetch(`${this.options.baseUrl()}/status`, {
method: 'GET',
headers: { Accept: 'application/json' },
signal: AbortSignal.timeout(this.options.timeoutMs()),
});
return { ok: true, status: response.status, message: `服务可达(HTTP ${response.status})` };
}
catch (error) {
const reason = error instanceof Error ? error.message : String(error);
return { ok: false, status: 0, message: `服务不可达:${reason}` };
}
}
/** Stage one turn summary as pending proposals (summary:write token). */
submitSummary(payload, token) {
return this.request('POST', '/activity/summary', payload, token);

70
lib/brain-migration.js Normal file
View File

@ -0,0 +1,70 @@
/**
* dsh-cloud-memory → dsh-brain naming migration (v1.1 §15.1, RENAME-01).
*
* This build still ships as `dsh-cloud-memory`; renaming the live package and
* its profile link is a deploy step that needs a full DSH restart, so it is not
* performed from inside a running session. What is implemented here is the
* *data* half, which is what RENAME-01 actually asserts:
*
* - copy the legacy sidecars to the `dsh-brain` names when the target is
* missing, never deleting or modifying the legacy files;
* - be idempotent: a second run is a no-op;
* - report what exists so the caller can drive the load-path switch safely.
*/
import { copyFile, mkdir, stat } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { dshHome } from "./store.js";
export const BRAIN = {
product: 'DSH Brain',
targetPackage: 'dsh-brain',
legacyPackage: 'dsh-cloud-memory',
};
/** Legacy sidecar → new-sidecar file name pairs. */
const PAIRS = [
['cloud-memory.json', 'dsh-brain.json'],
['cloud-memory-skills.json', 'dsh-brain-skills.json'],
['cloud-memory-skill-groups.json', 'dsh-brain-skill-groups.json'],
];
async function exists(path) {
return stat(path).then((value) => value.isFile()).catch(() => false);
}
export async function brainStatus() {
const home = dshHome();
const files = [];
for (const [legacyName, targetName] of PAIRS) {
const legacy = join(home, legacyName);
const target = join(home, targetName);
const legacyExists = await exists(legacy);
const targetExists = await exists(target);
files.push({ legacy, target, legacyExists, targetExists, needsMigration: legacyExists && !targetExists });
}
return {
home,
product: BRAIN.product,
targetPackage: BRAIN.targetPackage,
legacyPackage: BRAIN.legacyPackage,
files,
migrationNeeded: files.some((file) => file.needsMigration),
packageRename: 'pending-deploy',
};
}
/** Copy legacy sidecars to the new names. Existing targets are never overwritten. */
export async function migrateLegacyFiles() {
const home = dshHome();
const copied = [];
const skipped = [];
for (const [legacyName, targetName] of PAIRS) {
const legacy = join(home, legacyName);
const target = join(home, targetName);
if (!(await exists(legacy)))
continue;
if (await exists(target)) {
skipped.push(targetName);
continue;
}
await mkdir(dirname(target), { recursive: true });
await copyFile(legacy, target);
copied.push(targetName);
}
return { home, copied, skipped, product: BRAIN.product, targetPackage: BRAIN.targetPackage, legacyPackage: BRAIN.legacyPackage };
}

297
lib/clients.js Normal file
View File

@ -0,0 +1,297 @@
/**
* Cross-software / workspace skill inventory (v1.1 §15).
*
* One adapter per client. It only reads directories the client itself publishes
* (user-level skill roots and, when a workspace is known, that workspace's own
* client folder). Nothing here writes another client's directory: DSH is the
* only writable adapter in this build, and every other source is reported as
* read-only instead of pretending a toggle works.
*
* Workspaces come from two bounded sources:
* - the DSH workspace-group registry the host already keeps (member paths);
* - directories the user explicitly adds here (persisted metadata only).
* No full-disk scan, no chat history, no credential read.
*/
import { existsSync } from 'node:fs';
import { readFile, readdir, stat } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join, resolve, sep } from 'node:path';
import { dshHome } from "./store.js";
import { parseSkillFrontmatter } from "./skill-sync.js";
import { SkillAdmin } from "./skill-admin.js";
/** Manual workspace additions live in the plugin's own metadata file. */
export function manualWorkspacesPath() {
return join(dshHome(), 'cloud-memory-workspaces.json');
}
function rootsOf(home) {
return {
dsh: { configRoot: dshHome(), globalSkillsRoot: join(dshHome(), 'skills'), workspaceSubdirs: [join('.dsh', 'skills')] },
agents: { configRoot: join(home, '.agents'), globalSkillsRoot: join(home, '.agents', 'skills'), workspaceSubdirs: [] },
codex: { configRoot: join(home, '.codex'), globalSkillsRoot: join(home, '.codex', 'skills'), workspaceSubdirs: [join('.codex', 'skills')] },
workbuddy: { configRoot: join(home, '.workbuddy'), globalSkillsRoot: join(home, '.workbuddy', 'skills'), workspaceSubdirs: [] },
claude: { configRoot: join(home, '.claude'), globalSkillsRoot: join(home, '.claude', 'skills'), workspaceSubdirs: [join('.claude', 'skills')] },
opencode: { configRoot: join(home, '.config', 'opencode'), globalSkillsRoot: join(home, '.config', 'opencode', 'skills'), workspaceSubdirs: [join('.opencode', 'skills'), join('.opencode', 'skill')] },
};
}
const LABELS = {
dsh: 'DSH',
agents: '公共 Agent',
codex: 'Codex',
workbuddy: 'WorkBuddy',
claude: 'Claude Code',
opencode: 'OpenCode',
};
const SOFTWARE = ['dsh', 'agents', 'codex', 'workbuddy', 'claude', 'opencode'];
export class ClientRegistry {
deps;
constructor(deps = {}) {
this.deps = deps;
}
home() {
return this.deps.home?.() ?? homedir();
}
roots() {
return rootsOf(this.home());
}
adapters() {
const roots = this.roots();
return SOFTWARE.map((id) => {
const root = roots[id];
const installed = existsSync(root.configRoot);
const notes = [];
if (!installed)
notes.push('未检测到安装目录');
const writable = id === 'dsh';
if (!writable)
notes.push('本卡只读,不修改该软件的技能目录');
return {
id,
label: LABELS[id],
installed,
configRoot: root.configRoot,
globalSkillsRoot: root.globalSkillsRoot,
writable,
workspaceSupported: root.workspaceSubdirs.length > 0,
notes,
};
});
}
capabilities() {
return this.adapters().map((adapter) => ({
id: adapter.id,
label: adapter.label,
readGlobal: true,
writeGlobal: adapter.writable,
workspaceRead: adapter.workspaceSupported,
// Workspace-level writes are implemented for DSH only; every other client
// stays read-only so nothing is written into a format we cannot verify.
workspaceWrite: adapter.id === 'dsh' && adapter.workspaceSupported,
hotReload: adapter.id === 'dsh',
verify: true,
notes: adapter.notes,
}));
}
/**
* A workspace-scoped SkillAdmin for the DSH adapter. The skills root is the
* workspace's own `.dsh/skills`; parked skills go to a per-workspace holding
* area so one project can never unpark another's skill. Only DSH is allowed.
*/
async workspaceSkillAdmin(softwareInput, workspaceIdInput) {
const software = SOFTWARE.includes(softwareInput) ? softwareInput : undefined;
if (software !== 'dsh')
throw new Error('unsupported_workspace_write');
const workspaceId = typeof workspaceIdInput === 'string' ? workspaceIdInput : '';
const workspace = (await this.workspaces('dsh')).find((item) => item.id === workspaceId);
if (workspace === undefined)
throw new Error('unknown_workspace');
const skillsRoot = resolve(workspace.path, '.dsh', 'skills');
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({
skillsRoot: () => skillsRoot,
holdingDir: () => holdingDir,
syncStatePath: () => statePath,
syncRunning: () => false,
log: () => { },
});
return { admin, workspace };
}
async readManual() {
const path = this.deps.manualPath?.() ?? manualWorkspacesPath();
try {
const parsed = JSON.parse(await readFile(path, 'utf8'));
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
const raw = parsed;
const items = Array.isArray(raw.items)
? raw.items.filter((item) => (item !== null && typeof item === 'object'
&& typeof item.softwareId === 'string'
&& typeof item.path === 'string'))
: [];
return { version: 1, items };
}
}
catch {
// Missing sidecar: no manual workspaces yet.
}
return { version: 1, items: [] };
}
async writeManual(file) {
const path = this.deps.manualPath?.() ?? manualWorkspacesPath();
const { mkdir, writeFile } = await import('node:fs/promises');
await mkdir(join(path, '..'), { recursive: true });
await writeFile(path, `${JSON.stringify(file, null, 2)}\n`, 'utf8');
}
/** DSH workspaces come from the host's own workspace-group registry. */
async dshRegistryWorkspaces() {
const path = this.deps.dshRegistryPath?.() ?? join(dshHome(), 'workspace-groups.folders.json');
const categoriesPath = this.deps.dshManualPath?.() ?? join(dshHome(), 'workspace-groups.manual.json');
let categories = new Map();
try {
const raw = JSON.parse(await readFile(categoriesPath, 'utf8'));
if (raw.assignments !== null && typeof raw.assignments === 'object') {
categories = new Map(Object.entries(raw.assignments));
}
}
catch {
// No category mapping: names fall back to the folder name.
}
try {
const raw = JSON.parse(await readFile(path, 'utf8'));
const out = [];
const seen = new Set();
for (const [groupId, group] of Object.entries(raw.workspaces ?? {})) {
for (const member of group.members ?? []) {
if (typeof member.path !== 'string' || member.path === '' || seen.has(member.path))
continue;
seen.add(member.path);
const id = typeof member.workspaceId === 'string' && member.workspaceId !== '' ? member.workspaceId : groupId;
const parts = member.path.split(/[\\/]/).filter((part) => part !== '');
const category = categories.get(id);
out.push({ id, name: parts[parts.length - 1] ?? member.path, path: member.path, source: 'dsh-registry', ...(category === undefined ? {} : { category }) });
}
}
return out;
}
catch {
return [];
}
}
async workspaces(software) {
const manual = (await this.readManual()).items.filter((item) => item.softwareId === software);
const fromManual = manual.map((item) => ({ id: item.id, name: item.name, path: item.path, source: 'manual' }));
if (software === 'dsh') {
const registry = await this.dshRegistryWorkspaces();
const byPath = new Set(registry.map((item) => item.path));
return [...registry, ...fromManual.filter((item) => !byPath.has(item.path))];
}
return fromManual;
}
async addWorkspace(softwareInput, pathInput, nameInput) {
const software = SOFTWARE.includes(softwareInput) ? softwareInput : undefined;
if (software === undefined)
throw new Error('invalid_software');
const path = typeof pathInput === 'string' ? pathInput.trim() : '';
if (path === '' || !existsSync(path))
throw new Error('invalid_path');
const stats = await stat(path).catch(() => undefined);
if (stats === undefined || !stats.isDirectory())
throw new Error('invalid_path');
const resolved = resolve(path);
const file = await this.readManual();
if (file.items.some((item) => item.softwareId === software && resolve(item.path) === resolved))
throw new Error('duplicate');
const name = typeof nameInput === 'string' && nameInput.trim() !== '' ? nameInput.trim() : resolved.split(sep).filter((part) => part !== '').pop() ?? resolved;
const record = { id: `ws_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`, name, path: resolved, source: 'manual' };
file.items.push({ softwareId: software, id: record.id, name: record.name, path: record.path });
await this.writeManual(file);
return record;
}
async removeWorkspace(softwareInput, idInput) {
const software = SOFTWARE.includes(softwareInput) ? softwareInput : undefined;
const id = typeof idInput === 'string' ? idInput : '';
const file = await this.readManual();
const before = file.items.length;
file.items = file.items.filter((item) => !(item.softwareId === software && item.id === id));
if (file.items.length === before)
throw new Error('not_found');
await this.writeManual(file);
return { removed: id };
}
async inventoryOf(dir, software, scope, workspaceId) {
const out = [];
// DSH global and DSH workspace roots are writable by this build; every
// other client (and every non-DSH workspace) is read-only.
const writable = software === 'dsh';
for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
if (!entry.isDirectory() || entry.name.startsWith('.'))
continue;
const skillDir = join(dir, entry.name);
const markdown = await readFile(join(skillDir, 'SKILL.md'), 'utf8').catch(() => undefined);
if (markdown === undefined)
continue;
const frontmatter = parseSkillFrontmatter(markdown);
out.push({
folder: entry.name,
name: typeof frontmatter.name === 'string' && frontmatter.name !== '' ? frontmatter.name : entry.name,
description: String(frontmatter.description ?? '').slice(0, 300),
path: skillDir,
softwareId: software,
scope,
...(workspaceId === undefined ? {} : { workspaceId }),
writable,
});
}
out.sort((a, b) => (a.folder < b.folder ? -1 : 1));
return out;
}
async inventory(softwareInput, scopeInput, workspaceIdInput) {
const software = SOFTWARE.includes(softwareInput) ? softwareInput : undefined;
if (software === undefined)
throw new Error('invalid_software');
const scope = scopeInput === 'workspace' ? 'workspace' : 'global';
const roots = this.roots()[software];
if (scope === 'global') {
return { softwareId: software, scope, items: await this.inventoryOf(roots.globalSkillsRoot, software, 'global'), note: software === 'dsh' ? 'DSH 全局技能目录。' : '该软件的用户级技能目录,本卡只读。' };
}
const workspaceId = typeof workspaceIdInput === 'string' ? workspaceIdInput : '';
const workspace = (await this.workspaces(software)).find((item) => item.id === workspaceId);
if (workspace === undefined)
throw new Error('unknown_workspace');
// DSH workspace skills are enumerated through a workspace-scoped SkillAdmin
// so the list, the enabled flag and the inventory agree with the write path.
if (software === 'dsh') {
const { admin } = await this.workspaceSkillAdmin('dsh', workspace.id);
const listed = await admin.list();
const items = listed.skills.map((skill) => ({
folder: skill.folder,
name: skill.name,
description: skill.description,
path: join(skill.enabled ? listed.root : listed.holding, skill.folder),
softwareId: 'dsh',
scope: 'workspace',
workspaceId: workspace.id,
writable: true,
enabled: skill.enabled,
}));
return { softwareId: 'dsh', scope, workspace, items, note: `DSH 工作区技能目录:${join(workspace.path, '.dsh', 'skills')}` };
}
for (const sub of roots.workspaceSubdirs) {
const dir = resolve(workspace.path, sub);
if (existsSync(dir)) {
return { softwareId: software, scope, workspace, items: await this.inventoryOf(dir, software, 'workspace', workspace.id), note: `工作区专属目录:${dir}` };
}
}
return { softwareId: software, scope, workspace, items: [], note: `该工作区没有 ${LABELS[software]} 的专属技能目录;不会写通用配置替代。` };
}
async overview() {
const workspaces = {};
for (const id of SOFTWARE)
workspaces[id] = await this.workspaces(id);
return {
adapters: this.adapters(),
capabilities: this.capabilities(),
workspaces,
brain: { product: 'DSH Brain', targetPackage: 'dsh-brain', legacyPackage: 'dsh-cloud-memory' },
};
}
}

View File

@ -6,7 +6,7 @@
/** Defaults written into cordis.patch.yml; also the fallback for missing keys. */
export const DEFAULT_SETTINGS = {
enabled: true,
baseUrl: 'https://mem.qyhhh.top/api/longmemory',
baseUrl: 'https://your-memory-host/api/longmemory',
clientId: 'dsh-desktop',
requestTimeoutMs: 5000,
defaultK: 10,
@ -43,6 +43,34 @@ export function normalizeBaseUrl(value) {
return undefined;
}
}
/**
* A packaged default that was never replaced by a real service.
*
* `cordis.patch.yml` ships `https://your-memory-host/...` so a fresh profile
* boots without touching a production endpoint. Such an address must be shown
* as "未配置服务" — never as a healthy connection.
*/
export function isPlaceholderBaseUrl(value) {
const normalized = normalizeBaseUrl(value);
if (normalized === undefined)
return true;
try {
const host = new URL(normalized).hostname.toLowerCase();
return host === 'your-memory-host' || host === 'example.com';
}
catch {
return true;
}
}
/** Service origin of one base URL, or '' when it cannot be parsed. */
export function originOf(value) {
try {
return new URL(value).origin;
}
catch {
return '';
}
}
/** Clamp a numeric config value into an integer range, else undefined. */
function boundedInt(value, min, max) {
if (typeof value !== 'number' || !Number.isFinite(value))

View File

@ -16,13 +16,17 @@ 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. */
export const name = 'dsh-cloud-memory';
/** Services required before `apply` runs. */
export const inject = ['webServer'];
/** Version reported by the status card. */
const VERSION = '0.4.1';
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. */
@ -63,6 +67,34 @@ export function apply(ctx, config) {
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) {
@ -106,7 +138,7 @@ export function apply(ctx, config) {
logger.warn('webServer service unavailable; the configuration page stays disabled');
}
else {
const routes = createRoutes({ version: VERSION, store, reporter, client: () => client, skills: () => skillSync.stats(), admin: skillAdmin });
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}`);
}

217
lib/market.js Normal file
View File

@ -0,0 +1,217 @@
/**
* Skill market providers (P3).
*
* A provider answers `search` / `getDetail` / `resolveArtifact` for ONE
* configured, verified source. The browser half never passes a repository URL:
* it only names a provider id and an entry id, so no request can make the host
* fetch an arbitrary address or clone an arbitrary repository.
*
* First provider: the Claude Code plugin marketplace manifest that lives at
* `.claude-plugin/marketplace.json` in a public GitHub repository. That format
* lists plugins, each with a description and the relative folders of the skills
* it ships. Installing an entry reuses the same staged plan/commit pipeline as
* a manual git install, pinned to the commit resolved here.
*/
import { parseSkillFrontmatter } from "./skill-sync.js";
/** Typed failure so routes can map it to a status code. */
export class MarketError extends Error {
code;
constructor(code, message) {
super(message);
this.code = code;
this.name = 'MarketError';
}
}
/** Normalize a manifest skill path to a folder name (its basename). */
function folderOf(skillPath) {
const trimmed = skillPath.replace(/^\.\//, '').replace(/\/+$/, '');
const parts = trimmed.split('/');
return parts[parts.length - 1] ?? trimmed;
}
/** Provider over a Claude Code plugin marketplace manifest on GitHub. */
export class ClaudePluginMarketplaceProvider {
options;
cache = new Map();
fetchImpl;
constructor(options) {
this.options = options;
this.fetchImpl = options.fetchImpl ?? fetch;
}
info() {
return {
id: this.options.id,
label: this.options.label,
description: this.options.description,
source: this.options.repo,
homepage: this.options.homepage ?? `https://github.com/${this.options.repo}`,
};
}
ref() {
return this.options.ref ?? 'main';
}
timeoutMs() {
return this.options.timeoutMs ?? 8000;
}
rawUrl(path) {
const clean = path.replace(/^\.\//, '');
return `https://raw.githubusercontent.com/${this.options.repo}/${encodeURIComponent(this.ref())}/${clean}`;
}
async fetchText(url) {
let response;
try {
response = await this.fetchImpl(url, {
headers: { accept: 'application/json, text/plain, */*', 'user-agent': 'dsh-cloud-memory-market' },
signal: AbortSignal.timeout(this.timeoutMs()),
});
}
catch (error) {
throw new MarketError('unreachable', `市场来源不可达:${error instanceof Error ? error.message : String(error)}`);
}
if (!response.ok) {
throw new MarketError('http_' + String(response.status), `市场来源返回 HTTP ${response.status}`);
}
return response.text();
}
async fetchJson(url, ttlMs = 60_000) {
const hit = this.cache.get(url);
if (hit !== undefined && Date.now() - hit.at < ttlMs)
return hit.value;
const text = await this.fetchText(url);
let parsed;
try {
parsed = JSON.parse(text);
}
catch {
throw new MarketError('invalid_manifest', '市场清单不是合法 JSON。');
}
this.cache.set(url, { at: Date.now(), value: parsed });
return parsed;
}
async manifest() {
const parsed = await this.fetchJson(this.rawUrl('.claude-plugin/marketplace.json'));
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new MarketError('invalid_manifest', '市场清单结构不正确。');
}
return parsed;
}
entriesOf(manifest) {
const list = Array.isArray(manifest.plugins) ? manifest.plugins : [];
const version = manifest.metadata?.version;
const author = manifest.owner?.name;
const entries = [];
for (const plugin of list) {
const name = typeof plugin.name === 'string' ? plugin.name : '';
if (name === '')
continue;
const paths = Array.isArray(plugin.skills) ? plugin.skills.filter((p) => typeof p === 'string') : [];
const entry = {
id: name,
providerId: this.options.id,
name,
description: typeof plugin.description === 'string' ? plugin.description : '',
skills: paths.map(folderOf),
skillPaths: paths,
sourceRepo: this.options.repo,
sourceUrl: `https://github.com/${this.options.repo}`,
};
if (typeof version === 'string')
entry.version = version;
if (typeof author === 'string')
entry.author = author;
entries.push(entry);
}
return entries;
}
async search(query, cursor) {
const entries = this.entriesOf(await this.manifest());
const needle = query.trim().toLowerCase();
const filtered = needle === ''
? entries
: entries.filter((entry) => `${entry.name}\n${entry.description}\n${entry.skills.join(' ')}`.toLowerCase().includes(needle));
const pageSize = 10;
const start = Number.isFinite(cursor) && cursor > 0 ? Math.floor(cursor) : 0;
const page = filtered.slice(start, start + pageSize);
const next = start + pageSize < filtered.length ? start + pageSize : undefined;
return next === undefined ? { entries: page } : { entries: page, nextCursor: next };
}
findEntry(manifest, entryId) {
const entry = this.entriesOf(manifest).find((item) => item.id === entryId);
if (entry === undefined)
throw new MarketError('not_found', `市场里没有条目:${entryId}`);
return entry;
}
async getDetail(entryId) {
const entry = this.findEntry(await this.manifest(), entryId);
const skillDetails = [];
// Bound the fan-out: a manifest can list dozens of skills.
for (const path of entry.skillPaths.slice(0, 24)) {
const folder = folderOf(path);
try {
const markdown = await this.fetchText(this.rawUrl(`${path.replace(/^\.\//, '')}/SKILL.md`));
const frontmatter = parseSkillFrontmatter(markdown);
const detail = { folder, path, ok: true };
if (typeof frontmatter.name === 'string')
detail.name = frontmatter.name;
if (typeof frontmatter.description === 'string')
detail.description = frontmatter.description.slice(0, 300);
skillDetails.push(detail);
}
catch {
skillDetails.push({ folder, path, ok: false });
}
}
return { ...entry, skillDetails, fetchedAt: Date.now() };
}
async resolveArtifact(entryId, _version) {
const entry = this.findEntry(await this.manifest(), entryId);
let commit;
try {
const payload = await this.fetchJson(`https://api.github.com/repos/${this.options.repo}/commits/${encodeURIComponent(this.ref())}`, 30_000);
if (typeof payload.sha === 'string' && /^[0-9a-f]{7,40}$/i.test(payload.sha))
commit = payload.sha;
}
catch {
// Rate-limited or offline: fall back to the branch ref; git checkout pins
// the actual commit at clone time and the install records it.
}
const artifact = {
repoUrl: `https://github.com/${this.options.repo}.git`,
ref: commit ?? this.ref(),
folders: entry.skills,
};
if (commit !== undefined)
artifact.commit = commit;
if (entry.version !== undefined)
artifact.version = entry.version;
return artifact;
}
}
/** A small registry of providers; the browser can only ask for one by id. */
export class MarketService {
byId = new Map();
constructor(providers) {
for (const provider of providers)
this.byId.set(provider.info().id, provider);
}
list() {
return [...this.byId.values()].map((provider) => provider.info());
}
has(providerId) {
return this.byId.has(providerId);
}
get(providerId) {
const provider = this.byId.get(providerId);
if (provider === undefined)
throw new MarketError('unknown_provider', `未知的市场来源:${providerId}`);
return provider;
}
search(providerId, query, cursor) {
return this.get(providerId).search(query, cursor);
}
detail(providerId, entryId) {
return this.get(providerId).getDetail(entryId);
}
resolve(providerId, entryId, version) {
return this.get(providerId).resolveArtifact(entryId, version);
}
}

View File

@ -17,7 +17,7 @@ import { descriptor } from "./descriptor.js";
import { LongMemoryProvider } from "./driver.js";
export { LongMemoryProvider, descriptor };
/** Keep in sync with the package version (asserted by the verify script). */
const PROVIDER_VERSION = '0.4.1';
const PROVIDER_VERSION = '0.7.0';
export const definition = defineMemorySpaceProviderDefinition({
manifest: {
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,

View File

@ -118,7 +118,7 @@ code { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size
<div class="grid">
<div>
<label for="baseUrl">服务基址</label>
<input id="baseUrl" type="text" spellcheck="false" placeholder="https://mem.qyhhh.top/api/longmemory" />
<input id="baseUrl" type="text" spellcheck="false" placeholder="https://your-memory-host/api/longmemory" />
<div class="hint">不带结尾斜杠,路径为 /api/longmemory。</div>
</div>
<div>

View File

@ -1,19 +1,64 @@
import { describeError, isSecureLoginTarget } from "./api.js";
import { renderConfigPage } from "./page.js";
import { SkillAdminError } from "./skill-admin.js";
import { MarketError } from "./market.js";
import { brainStatus, migrateLegacyFiles } from "./brain-migration.js";
import { SkillGroupError } from "./skill-groups.js";
import { renderSkillsPage } from "./skill-page.js";
import { randomUUID } from 'node:crypto';
/** Route constants — kept in one place so the client half can reuse them. */
export const ROUTES = {
page: '/cloud-memory',
status: '/cloud-memory/status',
capabilities: '/cloud-memory/capabilities',
config: '/cloud-memory/config',
login: '/cloud-memory/login',
test: '/cloud-memory/test',
flush: '/cloud-memory/flush',
skills: '/cloud-memory/skills',
market: '/cloud-memory/market',
sync: '/cloud-memory/sync',
clients: '/cloud-memory/clients',
migrate: '/cloud-memory/migrate',
};
/** Largest request body we accept (a settings patch is tiny). */
const MAX_BODY_BYTES = 64 * 1024;
/** What this build actually implements, stated per feature. */
function capabilities(deps) {
const marketProviders = deps.market?.list().length ?? 0;
return {
version: deps.version,
features: {
connection: true,
identitySwitch: true,
skills: deps.admin !== undefined,
skillInstallPlans: deps.admin !== undefined,
skillUninstallPlan: deps.admin !== undefined,
skillsSync: deps.skills !== undefined,
skillsMarketplace: deps.market !== undefined,
marketProviders,
skillUpdate: deps.updates !== undefined,
syncResolve: deps.sync !== undefined,
multiClient: deps.clients !== undefined,
brainMigration: 'pending-deploy',
// The MCP bridge is provided by the host `dsh-mcp-connector` plugin over
// the same origin; the browser half probes it at runtime.
mcpBridge: 'host-plugin',
},
notes: [
...(deps.market === undefined
? ['技能市场未启用:没有配置市场来源。']
: [`技能市场已接入 ${marketProviders} 个来源;安装走暂存计划并固定提交。`]),
...(deps.updates === undefined
? ['技能更新/回退未启用。']
: ['更新/回退仅对带来源记录(.skill-source.json)的技能生效,更新前自动备份。']),
...(deps.sync === undefined ? [] : ['同步冲突可在技能页签逐项“保留本地 / 采用云端 / 手动合并”。']),
...(deps.clients === undefined ? [] : ['跨软件与工作区技能清单为只读(DSH 之外不写目录);dsh-brain 数据迁移已就绪,实际改名需部署重启。']),
'MCP 管理由宿主 dsh-mcp-connector 插件提供,本卡通过其公开接口读写,不另建凭据库。',
'MCP 工具可见性与会话级激活分属两层:本卡展示连接与工具缓存,会话级“选择精确工具后激活”由宿主 session-tools 负责,本卡不伪造激活。',
],
};
}
/** Collect a request body as UTF-8 text. */
async function readBody(req, maxBytes = MAX_BODY_BYTES) {
const chunks = [];
@ -56,6 +101,50 @@ function fail(res, status, message, asHtml = false) {
});
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.
*/
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;
}
/** Last test run, kept in memory so the card can show "最后检查". */
let lastCheck = null;
/**
* Uninstall confirmations.
*
* A preview issues a single-use token bound to one folder; the delete route
* refuses without it, so a stray click cannot remove a skill.
*/
const uninstallTokens = new Map();
const UNINSTALL_TOKEN_TTL_MS = 10 * 60_000;
/** The payload the page and the client card both consume. */
function statusPayload(deps) {
const view = deps.store.describe();
@ -67,6 +156,8 @@ function statusPayload(deps) {
const settings = {
enabled: view.enabled,
baseUrl: view.baseUrl,
baseUrlConfigured: view.baseUrlConfigured,
baseUrlOrigin: view.baseUrlOrigin,
clientId: view.clientId,
requestTimeoutMs: view.requestTimeoutMs,
defaultK: view.defaultK,
@ -76,7 +167,13 @@ function statusPayload(deps) {
skillsDir: view.skillsDir,
};
return {
ok: true, settings, tokens, settingsPath: view.statePath, reporter: deps.reporter.snapshot(),
ok: true,
settings,
tokens,
settingsPath: view.statePath,
reporter: deps.reporter.snapshot(),
lastCheck,
capabilities: capabilities(deps),
...(deps.skills === undefined ? {} : { skills: deps.skills() }),
};
}
@ -105,6 +202,14 @@ function serveStatus(deps, req, res) {
}
json(res, 200, statusPayload(deps));
}
/** `GET /cloud-memory/capabilities`. */
function serveCapabilities(deps, req, res) {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed');
return;
}
json(res, 200, { ok: true, ...capabilities(deps) });
}
/** `PUT /cloud-memory/config`. */
async function serveConfig(deps, req, res) {
if (req.method !== 'PUT' && req.method !== 'POST') {
@ -137,9 +242,22 @@ async function serveConfig(deps, req, res) {
fail(res, 400, result.error ?? 'invalid-patch');
return;
}
json(res, 200, statusPayload(deps));
json(res, 200, {
...statusPayload(deps),
...(result.clearedTokens === undefined ? {} : { credentialsCleared: result.clearedTokens }),
});
}
/** `POST /cloud-memory/test` — validate both tokens without recording anything. */
/** 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 /cloud-memory/test` — read-only checks, one per credential. */
async function serveTest(deps, req, res) {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
@ -150,36 +268,67 @@ async function serveTest(deps, req, res) {
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();
const activity = activityToken === ''
? { ok: false, message: '还没填令牌:把 activity:write 密钥粘到下面「活动上报令牌」再点保存' }
: await (async () => {
const probe = await client.probeActivity(activityToken);
return probe.ok
? { ok: true, message: '令牌有效(鉴权通过)' }
: { ok: false, message: describeError(probe.error) };
})();
const memory = memoryToken === ''
? { ok: false, message: '还没填令牌:把 memory:write 密钥粘到下面「记忆读写令牌」再点保存' }
: await (async () => {
const probe = await client.projects();
return probe.ok
? { ok: true, message: `令牌有效(${(probe.data.projects ?? []).length} 个项目)` }
: { ok: false, message: describeError(probe.error) };
})();
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();
const summary = !deps.store.settings().summaryEnabled
? { ok: false, message: '自动摘要已关闭(可在下方勾选开启)' }
: summaryToken === ''
? { ok: false, message: '未配置摘要令牌:留空则不做自动摘要' }
: await (async () => {
const probe = await client.probeSummary(summaryToken);
return probe.ok
? { ok: true, message: '摘要令牌有效(只进待确认队列)' }
: { ok: false, message: describeError(probe.error) };
})();
json(res, 200, { ok: true, activity, memory, summary });
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 /cloud-memory/flush`. */
async function serveFlush(deps, req, res) {
@ -194,7 +343,7 @@ async function serveFlush(deps, req, res) {
const result = await deps.reporter.flush();
json(res, 200, { ok: true, ...result });
}
/** Labels attached to the two tokens this plugin asks the dashboard to mint. */
/** Labels attached to the tokens this plugin asks the dashboard to mint. */
const TOKEN_LABELS = {
activity: 'DSH desktop 活动上报',
memory: 'DSH desktop 记忆读写',
@ -202,12 +351,12 @@ const TOKEN_LABELS = {
};
/**
* `POST /cloud-memory/login` — sign in with the cloud account and exchange it
* for the two scoped tokens.
* for the scoped tokens.
*
* The password is used once, in memory, and never written anywhere: the flow is
* password → short-lived session cookie → two `cmt_…` 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.
* 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') {
@ -304,28 +453,60 @@ function adminStatus(code) {
switch (code) {
case 'not_found': return 404;
case 'invalid_name':
case 'invalid_url': return 400;
case 'invalid_url':
case 'invalid_plan': return 400;
case 'collision':
case 'sync_running': return 409;
case 'sync_running':
case 'plan_expired':
case 'confirmation_required':
case 'no_source':
case 'up_to_date':
case 'stale_plan':
case 'unsupported': return 409;
case 'no_backup': return 404;
case 'no_skills_found': return 422;
case 'git_failed': return 502;
default: return 500;
}
}
/** Issue the single-use token a delete needs. */
function issueUninstallToken(folder) {
const token = `uninstall_${randomUUID()}`;
uninstallTokens.set(folder, { token, expiresAt: Date.now() + UNINSTALL_TOKEN_TTL_MS });
return token;
}
/** Consume one uninstall token; false when it is missing, stale or foreign. */
function useUninstallToken(folder, token) {
const record = uninstallTokens.get(folder);
if (record === undefined)
return false;
if (typeof token !== 'string' || token !== record.token)
return false;
if (record.expiresAt < Date.now()) {
uninstallTokens.delete(folder);
return false;
}
uninstallTokens.delete(folder);
return true;
}
/**
* The skill management surface, one prefix route:
* `GET /cloud-memory/skills` the management page
* `GET /cloud-memory/skills/api` inventory JSON (skills + trash)
* `POST /cloud-memory/skills/toggle` { folder, enabled }
* `POST /cloud-memory/skills/remove` { folder }
* `POST /cloud-memory/skills/install` { url }
* `GET /cloud-memory/skills` the management page
* `GET /cloud-memory/skills/api` inventory JSON (skills + plans)
* `POST /cloud-memory/skills/detail` { folder } — one skill with SKILL.md
* `POST /cloud-memory/skills/toggle` { folder, enabled }
* `POST /cloud-memory/skills/install/plan` { url } — stage the repository
* `POST /cloud-memory/skills/install/commit` { planId, folders }
* `POST /cloud-memory/skills/install/cancel` { planId }
* `POST /cloud-memory/skills/uninstall/plan` { folder } — impact preview
* `POST /cloud-memory/skills/remove` { folder, token, confirmed: true }
*/
async function serveSkills(deps, req, res) {
if (deps.admin === undefined) {
const admin = deps.admin;
if (admin === undefined) {
fail(res, 404, 'skills-admin-unavailable');
return;
}
const admin = deps.admin;
const suffix = (req.url ?? '').split('?')[0]?.slice(ROUTES.skills.length) ?? '';
if (suffix === '' || suffix === '/') {
if (req.method !== 'GET' && req.method !== 'HEAD') {
@ -349,56 +530,431 @@ async function serveSkills(deps, req, res) {
fail(res, 405, 'method-not-allowed');
return;
}
json(res, 200, { ok: true, ...(await admin.list()) });
const inventory = await admin.list();
json(res, 200, { ok: true, ...inventory, ...(await admin.listPlans()) });
return;
}
if (suffix === '/sources') {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed');
return;
}
const groups = deps.groups;
if (groups === undefined) {
fail(res, 404, 'skill-groups-unavailable');
return;
}
json(res, 200, { ok: true, ...(await groups.overview()) });
return;
}
const actions = {
'/toggle': async (body) => admin.setEnabled(body.folder, body.enabled === true),
'/remove': async (body) => admin.remove(body.folder),
'/install': async (body) => admin.installFromGit(body.url),
'/detail': async (body) => ({ ...(await admin.detail(body.folder)) }),
'/toggle': async (body) => ({ ...(await admin.setEnabled(body.folder, body.enabled === true)) }),
// One-shot install kept for the standalone page; the card uses plan/commit.
'/install': async (body) => ({ ...(await admin.installFromGit(body.url)) }),
'/install/plan': async (body) => ({ ...(await admin.prepareInstall(body.url)) }),
'/install/commit': async (body) => ({ ...(await admin.commitInstall({ planId: body.planId, folders: body.folders })) }),
'/install/cancel': async (body) => ({ ...(await admin.cancelInstall({ planId: body.planId })) }),
'/uninstall/plan': async (body) => {
const plan = await admin.uninstallPlan(body.folder);
return { ...plan, token: issueUninstallToken(plan.folder) };
},
'/remove': async (body) => {
if (body.confirmed !== true) {
throw new SkillAdminError('confirmation_required', '删除必须显式确认:先预览影响,再传 confirmed=true。');
}
const folder = typeof body.folder === 'string' ? body.folder : '';
if (!useUninstallToken(folder, body.token)) {
throw new SkillAdminError('confirmation_required', '卸载确认已过期或与该技能不匹配,请重新预览。');
}
return { ...(await admin.remove(folder)) };
},
};
const action = actions[suffix];
// Update/rollback operate on skills with a `.skill-source.json` record. They
// are optional: without the updater wired in the routes answer 404.
const updateActions = {
'/update/check': async (body) => ({ ...(await requireUpdates(deps).checkUpdate(body.folder)) }),
'/update/apply': async (body) => ({ ...(await requireUpdates(deps).applyUpdate(body.folder, body.expectedCommit)) }),
'/rollback': async (body) => ({ ...(await requireUpdates(deps).rollback(body.folder)) }),
};
// Category and source switches live in the same prefix so the card has one
// base URL; they are grouped here because they never touch a skill folder
// directly (except the DSH park/unpark the group manager delegates).
const groupActions = {
'/groups/create': async (body) => ({ ...(await requireGroups(deps).createGroup(body.sourceId, body.name)) }),
'/groups/rename': async (body) => ({ ...(await requireGroups(deps).renameGroup(body.sourceId, body.groupId, body.name)) }),
'/groups/delete': async (body) => ({ ...(await requireGroups(deps).deleteGroup(body.sourceId, body.groupId)) }),
'/groups/assign': async (body) => ({ ...(await requireGroups(deps).assign(body.sourceId, body.groupId, body.folders)) }),
'/groups/toggle': async (body) => ({ ...(await requireGroups(deps).toggleGroup(body.sourceId, body.groupId, body.enabled === true)) }),
'/source/toggle': async (body) => ({ ...(await requireGroups(deps).toggleSource(body.sourceId, body.enabled === true)) }),
'/source/reveal': async (body) => ({ ...(await requireGroups(deps).reveal(body.sourceId)) }),
};
const action = actions[suffix] ?? groupActions[suffix] ?? updateActions[suffix];
if (action === undefined) {
fail(res, 404, 'unknown-skill-route');
return;
}
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
const body = await jsonBody(req, res);
if (body === undefined)
return;
}
if (!sameOrigin(req)) {
fail(res, 403, 'origin-rejected');
return;
}
const type = (req.headers['content-type'] ?? '').toLowerCase();
if (!type.startsWith('application/json')) {
fail(res, 415, 'json-required');
return;
}
let body;
try {
body = JSON.parse(await readBody(req));
}
catch {
fail(res, 400, 'invalid-json');
return;
}
if (body === null || typeof body !== 'object' || Array.isArray(body)) {
fail(res, 400, 'invalid-body');
return;
}
try {
json(res, 200, { ok: true, ...(await action(body)) });
}
catch (error) {
if (error instanceof SkillAdminError) {
json(res, adminStatus(error.code), { ok: false, code: error.code, error: error.message });
return;
}
else {
json(res, 500, { ok: false, code: 'internal', error: error instanceof Error ? error.message : String(error) });
if (error instanceof SkillGroupError) {
json(res, groupStatus(error.code), { ok: false, code: error.code, error: error.message });
return;
}
json(res, 500, { ok: false, code: 'internal', error: error instanceof Error ? error.message : String(error) });
}
}
/** The group manager is optional; the routes answer 404 when it is absent. */
function requireGroups(deps) {
if (deps.groups === undefined)
throw new SkillGroupError('unavailable', '技能分组功能未启用。');
return deps.groups;
}
/** HTTP status for one group failure code. */
function groupStatus(code) {
switch (code) {
case 'not_found':
case 'unknown_source': return 404;
case 'invalid_name':
case 'duplicate':
case 'too_many': return 400;
case 'unavailable': return 503;
default: return 500;
}
}
/** The updater is optional; its routes answer 404 when it is absent. */
function requireUpdates(deps) {
if (deps.updates === undefined)
throw new SkillAdminError('unsupported', '技能更新/回退未启用。');
return deps.updates;
}
/** HTTP status for one market failure code. */
function marketStatus(code) {
switch (code) {
case 'unknown_provider':
case 'invalid_manifest': return 400;
case 'not_found': return 404;
case 'unreachable':
case 'unavailable': return 502;
default:
return code.startsWith('http_') ? 502 : 500;
}
}
/**
* Market surface, one prefix route:
* `GET /cloud-memory/market/providers` configured sources
* `GET /cloud-memory/market/search` ?provider=&q=&cursor=
* `POST /cloud-memory/market/detail` { provider, id }
* `POST /cloud-memory/market/plan` { provider, id } — pin commit + stage a plan
* `POST /cloud-memory/market/commit` { planId, folders }
* `POST /cloud-memory/market/cancel` { planId }
*/
async function serveMarket(deps, req, res) {
const market = deps.market;
if (market === undefined) {
fail(res, 404, 'market-unavailable');
return;
}
const url = new URL(req.url ?? '/', 'http://localhost');
const suffix = url.pathname.slice(ROUTES.market.length);
try {
if (suffix === '' || suffix === '/' || suffix === '/providers') {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed');
return;
}
json(res, 200, { ok: true, providers: market.list() });
return;
}
if (suffix === '/search') {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed');
return;
}
const providerId = url.searchParams.get('provider') ?? market.list()[0]?.id ?? '';
const query = url.searchParams.get('q') ?? '';
const cursorRaw = Number(url.searchParams.get('cursor') ?? '0');
const cursor = Number.isFinite(cursorRaw) && cursorRaw > 0 ? cursorRaw : 0;
const result = await market.search(providerId, query, cursor);
json(res, 200, { ok: true, provider: market.get(providerId).info(), ...result });
return;
}
const admin = deps.admin;
const requireAdmin = () => {
if (admin === undefined)
throw new MarketError('unavailable', '技能管理未启用,无法安装。');
return admin;
};
const actions = {
'/detail': async (body) => ({ ...(await market.detail(String(body.provider ?? ''), String(body.id ?? ''))) }),
'/plan': async (body) => {
const providerId = String(body.provider ?? '');
const id = String(body.id ?? '');
const artifact = await market.resolve(providerId, id, typeof body.version === 'string' ? body.version : undefined);
const plan = await requireAdmin().prepareInstall(artifact.repoUrl, {
ref: artifact.ref,
source: {
provider: providerId,
entryId: id,
...(artifact.version === undefined ? {} : { version: artifact.version }),
},
});
const wanted = new Set(artifact.folders);
return {
planId: plan.planId,
...(plan.commit === undefined ? {} : { commit: plan.commit }),
artifact,
candidates: plan.candidates.filter((candidate) => wanted.has(candidate.folder)),
totalInRepo: plan.candidates.length,
};
},
'/commit': async (body) => ({ ...(await requireAdmin().commitInstall({ planId: body.planId, folders: body.folders })) }),
'/cancel': async (body) => ({ ...(await requireAdmin().cancelInstall({ planId: body.planId })) }),
};
const action = actions[suffix];
if (action === undefined) {
fail(res, 404, 'unknown-market-route');
return;
}
const body = await jsonBody(req, res);
if (body === undefined)
return;
json(res, 200, { ok: true, ...(await action(body)) });
}
catch (error) {
if (error instanceof MarketError) {
json(res, marketStatus(error.code), { ok: false, code: error.code, error: error.message });
return;
}
if (error instanceof SkillAdminError) {
json(res, adminStatus(error.code), { ok: false, code: error.code, error: error.message });
return;
}
json(res, 500, { ok: false, code: 'internal', error: error instanceof Error ? error.message : String(error) });
}
}
/**
* Sync surface:
* `GET /cloud-memory/sync/status` latest stats + both sides of each conflict
* `POST /cloud-memory/sync/run` trigger one pass now
* `POST /cloud-memory/sync/resolve` { name, action: keep_local | take_cloud | manual }
*/
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(ROUTES.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') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
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);
json(res, 200, { ok: true, ...result, 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 });
}
}
/** Cross-software / workspace inventory routes. */
async function serveClients(deps, req, res) {
const registry = deps.clients;
if (registry === undefined) {
fail(res, 404, 'clients-unavailable');
return;
}
const url = new URL(req.url ?? '/', 'http://localhost');
const suffix = url.pathname.slice(ROUTES.clients.length);
try {
if (suffix === '' || suffix === '/' || suffix === '/overview') {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed');
return;
}
json(res, 200, { ok: true, ...(await registry.overview()) });
return;
}
if (suffix === '/inventory') {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed');
return;
}
const result = await registry.inventory(url.searchParams.get('software'), url.searchParams.get('scope'), url.searchParams.get('workspaceId') ?? undefined);
json(res, 200, { ok: true, ...result });
return;
}
if (suffix === '/workspaces/add') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res);
if (body === undefined)
return;
const workspace = await registry.addWorkspace(body.software, body.path, body.name);
json(res, 200, { ok: true, workspace });
return;
}
if (suffix === '/workspaces/remove') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res);
if (body === undefined)
return;
json(res, 200, { ok: true, ...(await registry.removeWorkspace(body.software, body.id)) });
return;
}
if (suffix === '/workspace/inventory') {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed');
return;
}
const { admin, workspace } = await registry.workspaceSkillAdmin(url.searchParams.get('software'), url.searchParams.get('workspaceId'));
json(res, 200, { ok: true, workspace, ...(await admin.list()) });
return;
}
if (suffix === '/workspace/detail') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res);
if (body === undefined)
return;
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId);
json(res, 200, { ok: true, ...(await admin.detail(body.folder)) });
return;
}
if (suffix === '/workspace/toggle') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res);
if (body === undefined)
return;
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId);
json(res, 200, { ok: true, ...(await admin.setEnabled(body.folder, body.enabled === true)) });
return;
}
if (suffix === '/workspace/remove') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res);
if (body === undefined)
return;
if (body.confirmed !== true)
throw new SkillAdminError('confirmation_required', '工作区技能删除必须显式 confirmed:true。');
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId);
json(res, 200, { ok: true, ...(await admin.remove(body.folder)) });
return;
}
if (suffix === '/workspace/install/plan') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res);
if (body === undefined)
return;
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId);
json(res, 200, { ok: true, ...(await admin.prepareInstall(body.url)) });
return;
}
if (suffix === '/workspace/install/commit') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res);
if (body === undefined)
return;
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId);
json(res, 200, { ok: true, ...(await admin.commitInstall({ planId: body.planId, folders: body.folders })) });
return;
}
fail(res, 404, 'unknown-clients-route');
}
catch (error) {
if (error instanceof SkillAdminError) {
json(res, adminStatus(error.code), { ok: false, code: error.code, error: error.message });
return;
}
const message = error instanceof Error ? error.message : String(error);
const known = ['invalid_software', 'invalid_path', 'duplicate', 'not_found', 'unknown_workspace', 'unsupported_workspace_write'];
const code = known.includes(message) ? message : 'internal';
const status = code === 'internal' ? 500
: code === 'not_found' || code === 'unknown_workspace' ? 404
: code === 'duplicate' ? 409
: code === 'unsupported_workspace_write' ? 501 : 400;
json(res, status, { ok: false, code, error: message });
}
}
/** dsh-brain data migration: GET status, POST run. */
async function serveMigrate(_deps, req, res) {
const url = new URL(req.url ?? '/', 'http://localhost');
const suffix = url.pathname.slice(ROUTES.migrate.length);
if (suffix === '' || suffix === '/' || suffix === '/brain') {
if (req.method === 'GET') {
const status = await brainStatus();
json(res, 200, { ok: true, ...status });
return;
}
if (req.method === 'POST') {
const result = await migrateLegacyFiles();
json(res, 200, { ok: true, ...result });
return;
}
fail(res, 405, 'method-not-allowed');
return;
}
fail(res, 404, 'unknown-migrate-route');
}
/** Build the exact-route table registered with the host web server. */
export function createRoutes(deps) {
return [
@ -412,6 +968,11 @@ export function createRoutes(deps) {
path: ROUTES.status,
handler: (req, res) => serveStatus(deps, req, res),
},
{
kind: 'exact',
path: ROUTES.capabilities,
handler: (req, res) => serveCapabilities(deps, req, res),
},
{
kind: 'exact',
path: ROUTES.config,
@ -437,5 +998,25 @@ export function createRoutes(deps) {
path: ROUTES.skills,
handler: (req, res) => serveSkills(deps, req, res),
},
{
kind: 'prefix',
path: ROUTES.market,
handler: (req, res) => serveMarket(deps, req, res),
},
{
kind: 'prefix',
path: ROUTES.sync,
handler: (req, res) => serveSync(deps, req, res),
},
{
kind: 'prefix',
path: ROUTES.clients,
handler: (req, res) => serveClients(deps, req, res),
},
{
kind: 'prefix',
path: ROUTES.migrate,
handler: (req, res) => serveMigrate(deps, req, res),
},
];
}

View File

@ -1,9 +1,9 @@
/**
* Local skill management, built into the plugin: list, enable/disable,
* real delete, and install from a git repository.
* Local skill management, built into the plugin: list, inspect, enable/disable,
* previewed install, previewed uninstall.
*
* This covers the everyday subset of a full skills manager. It manages
* only the DSH skills root (plus its own parking and trash areas) — the
* only the DSH skills root (plus its own parking and staging areas) — the
* cloud sync engine keeps owning everything beyond the local disk.
*
* Enable/disable is deliberately mechanical: a disabled skill's folder
@ -14,20 +14,36 @@
* mistaken for deletions, and a parked cloud skill still receives its
* cloud updates in place.
*
* Delete is a real delete: the folder is removed recursively. The
* cloud copy is unaffected — local deletion never propagates to the
* center (the sync engine remembers the removal, so the same cloud
* version is not pulled back down either).
* Delete is a real delete: the folder is removed recursively. It is only
* reachable through a two-step contract (plan → confirm) because there is no
* trash area and nothing can be restored. The cloud copy is unaffected —
* local deletion never propagates to the center.
*
* Installation is staged: the repository is cloned into an isolated scratch
* directory, candidates are enumerated and described, and nothing enters the
* skills root until the caller commits an explicit selection. Repository code
* is never executed (no hooks, no install scripts), symlinks are never
* followed, and a colliding folder is always skipped instead of overwritten.
*/
import { lstatSync } from 'node:fs';
import { execFile } from 'node:child_process';
import { cp, mkdir, readFile, readdir, rename, rm, stat } from 'node:fs/promises';
import { basename, join } from 'node:path';
import { createHash, randomUUID } from 'node:crypto';
import { cp, lstat, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
import { basename, dirname, join, relative, resolve, sep } from 'node:path';
import { parseSkillFrontmatter } from "./skill-sync.js";
import { dshHome } from "./store.js";
/** The parking area for disabled skills. */
export function skillsHoldingDir() {
return join(dshHome(), 'skills-disabled');
}
/** Isolated scratch space for staged installs; never inside the skills root. */
export function skillsStagingDir() {
return join(dshHome(), '.cloud-memory-staging');
}
/** Persisted plan records (metadata only: ids, counts, timestamps). */
export function skillPlansPath() {
return join(dshHome(), '.cloud-memory-plans.json');
}
/** A management failure with a stable machine-readable code. */
export class SkillAdminError extends Error {
code;
@ -37,30 +53,92 @@ export class SkillAdminError extends Error {
this.name = 'SkillAdminError';
}
}
/** Run git and return stdout (used for resolving the checked-out commit). */
function execFileText(file, args, timeoutMs = 120_000) {
return new Promise((resolvePromise, rejectPromise) => {
execFile(file, args, { timeout: timeoutMs, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' }, maxBuffer: 4 * 1024 * 1024 }, (error, stdout) => (error ? rejectPromise(error) : resolvePromise(String(stdout))));
});
}
function fail(code, message) {
throw new SkillAdminError(code, message);
}
/** Hard caps so one hostile repository cannot exhaust the disk. */
const MAX_SKILL_FILES = 1500;
const MAX_SKILL_BYTES = 4 * 1024 * 1024;
const MAX_CANDIDATES = 60;
const MAX_SKILL_MD_BYTES = 256 * 1024;
const PLAN_TTL_MS = 30 * 60_000;
async function isDirectory(path) {
return stat(path).then((s) => s.isDirectory()).catch(() => false);
}
/** Count files below a directory, capped so a stray tree cannot hang us. */
async function countFiles(dir, cap = 2000) {
let count = 0;
async function isSymlink(path) {
return lstat(path).then((s) => s.isSymbolicLink()).catch(() => false);
}
/** Synchronous variant, used inside `cp` filters where no await is possible. */
function isSymlinkSync(path) {
try {
return lstatSync(path).isSymbolicLink();
}
catch {
return true;
}
}
/** Read a skill's `.skill-source.json`, or undefined when absent/corrupt. */
export async function readSkillSourceRecord(dir) {
const raw = await readFile(join(dir, '.skill-source.json'), 'utf8').catch(() => undefined);
if (raw === undefined)
return undefined;
try {
const parsed = JSON.parse(raw);
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
return undefined;
const record = parsed;
if (typeof record.repoUrl !== 'string' || typeof record.commit !== 'string')
return undefined;
return {
version: 1,
provider: typeof record.provider === 'string' ? record.provider : 'git',
repoUrl: record.repoUrl,
ref: typeof record.ref === 'string' ? record.ref : record.commit,
commit: record.commit,
sourcePath: typeof record.sourcePath === 'string' ? record.sourcePath : '',
installedAt: typeof record.installedAt === 'string' ? record.installedAt : new Date(0).toISOString(),
...(typeof record.entryId === 'string' ? { entryId: record.entryId } : {}),
...(typeof record.marketVersion === 'string' ? { marketVersion: record.marketVersion } : {}),
};
}
catch {
return undefined;
}
}
/** Files under one skill folder, skipping `.git` and never following links. */
async function walkFiles(dir, cap = MAX_SKILL_FILES + 1) {
const out = [];
const walk = async (sub) => {
if (count > cap)
if (out.length > cap)
return;
for (const entry of await readdir(join(dir, sub), { withFileTypes: true }).catch(() => [])) {
if (entry.name === '.git')
continue;
const rel = sub === '' ? entry.name : `${sub}/${entry.name}`;
if (entry.isDirectory())
const abs = join(dir, rel);
if (entry.isSymbolicLink()) {
out.push({ path: rel, bytes: 0, script: false });
continue;
}
if (entry.isDirectory()) {
await walk(rel);
else if (entry.isFile())
count += 1;
continue;
}
if (!entry.isFile())
continue;
const size = await stat(abs).then((s) => s.size).catch(() => 0);
out.push({ path: rel, bytes: size, script: /\.(mjs|cjs|js|ts|ps1|sh|bat|cmd|py|rb|exe|dll)$/i.test(entry.name) });
}
};
await walk('');
return count;
out.sort((a, b) => (a.path < b.path ? -1 : 1));
return out;
}
/** A folder name we are willing to move around: one path segment, no tricks. */
function checkFolder(folder) {
@ -75,11 +153,17 @@ export class SkillAdmin {
constructor(deps) {
this.deps = deps;
}
plansFile() {
return this.deps.plansPath?.() ?? skillPlansPath();
}
stagingRoot() {
return this.deps.stagingRoot?.() ?? skillsStagingDir();
}
guardSync() {
if (this.deps.syncRunning())
fail('sync_running', '技能同步正在进行,请稍候再试。');
}
async syncUploaded() {
async uploaded() {
try {
const parsed = JSON.parse(await readFile(this.deps.syncStatePath(), 'utf8'));
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
@ -106,34 +190,60 @@ export class SkillAdmin {
origin = 'cloud';
try {
const parsed = JSON.parse(delivery);
const value = parsed.revision;
const value = parsed?.revision;
if (typeof value === 'number')
revision = value;
}
catch { /* a corrupt manifest still marks cloud origin */ }
catch {
// A corrupt manifest still marks cloud origin.
}
}
else {
for (const record of Object.values(uploaded)) {
if (record.folder === folder) {
origin = 'uploaded';
revision = record.revision;
if (typeof record.revision === 'number')
revision = record.revision;
break;
}
}
}
const files = await walkFiles(dir);
const bytes = files.reduce((sum, file) => sum + file.bytes, 0);
const installedAt = await stat(join(dir, 'SKILL.md')).then((s) => new Date(s.mtimeMs).toISOString()).catch(() => undefined);
const name = frontmatter.name;
const source = await readSkillSourceRecord(dir);
return {
folder,
name: frontmatter.name ?? folder,
description: (frontmatter.description ?? '').slice(0, 300),
name: typeof name === 'string' && name !== '' ? name : folder,
description: String(frontmatter.description ?? '').slice(0, 300),
enabled,
origin,
...(revision === undefined ? {} : { revision }),
files: await countFiles(dir),
files: files.length,
bytes,
...(installedAt === undefined ? {} : { installedAt }),
skillSha256: createHash('sha256').update(markdown).digest('hex'),
location: enabled ? 'root' : 'holding',
ownerManager: 'dsh-cloud-memory',
writable: true,
...(source === undefined
? {}
: {
source: {
provider: source.provider,
repoUrl: source.repoUrl,
ref: source.ref,
commit: source.commit,
...(source.entryId === undefined ? {} : { entryId: source.entryId }),
},
}),
updatable: source !== undefined,
};
}
/** Inventory of the skills root and the parking area. */
async list() {
const uploaded = await this.syncUploaded();
const uploaded = await this.uploaded();
const skills = [];
const scan = async (area, enabled) => {
for (const entry of await readdir(area, { withFileTypes: true }).catch(() => [])) {
@ -147,7 +257,7 @@ export class SkillAdmin {
await scan(this.deps.skillsRoot(), true);
await scan(this.deps.holdingDir(), false);
skills.sort((a, b) => (a.folder < b.folder ? -1 : 1));
return { skills };
return { skills, root: this.deps.skillsRoot(), holding: this.deps.holdingDir(), staging: this.stagingRoot() };
}
/** Locate a skill folder across the root and the parking area. */
async locate(folder) {
@ -159,6 +269,29 @@ export class SkillAdmin {
return { area: 'holding', dir: parkedDir };
return undefined;
}
/** Everything one skill panel needs, including its SKILL.md text. */
async detail(folderInput) {
const folder = checkFolder(folderInput);
const found = await this.locate(folder);
if (found === undefined)
fail('not_found', `没有找到技能:${folder}`);
if (await isSymlink(found.dir))
fail('unsupported', `技能目录是链接,不在这里管理:${folder}`);
const entry = await this.describe(folder, found.dir, found.area === 'root', await this.uploaded());
if (entry === undefined)
fail('not_found', `技能缺少 SKILL.md:${folder}`);
const files = await walkFiles(found.dir);
const raw = await readFile(join(found.dir, 'SKILL.md'), 'utf8').catch(() => '');
const truncated = Buffer.byteLength(raw) > MAX_SKILL_MD_BYTES;
return {
skill: entry,
dir: found.dir,
files,
totalBytes: files.reduce((sum, file) => sum + file.bytes, 0),
truncated,
skillMd: truncated ? Buffer.from(raw).subarray(0, MAX_SKILL_MD_BYTES).toString('utf8') : raw,
};
}
/** Enable (move back into the root) or disable (park) one skill. */
async setEnabled(folderInput, enabled) {
this.guardSync();
@ -168,33 +301,112 @@ export class SkillAdmin {
fail('not_found', `没有找到技能:${folder}`);
const targetArea = enabled ? 'root' : 'holding';
if (found.area === targetArea)
return { folder, enabled };
return { folder, enabled, note: this.effectNote(enabled) };
const targetRoot = enabled ? this.deps.skillsRoot() : this.deps.holdingDir();
await mkdir(targetRoot, { recursive: true });
const target = join(targetRoot, folder);
if (await isDirectory(target))
fail('collision', `目标位置已存在同名技能:${folder}`);
await rename(found.dir, target);
try {
await rename(found.dir, target);
}
catch (error) {
// A cross-device move must not leave the skill half-copied: fall back to a
// plain copy only for EXDEV, and only then remove the source.
if (error.code !== 'EXDEV')
throw error;
await cp(found.dir, target, { recursive: true, filter: (source) => !source.split(/[\\/]/).includes('.git') });
await rm(found.dir, { recursive: true, force: true });
}
this.deps.log(`skill ${enabled ? 'enabled' : 'disabled'}: ${folder}`);
return { folder, enabled };
return { folder, enabled, note: this.effectNote(enabled) };
}
/** Delete one skill for real: its folder is removed recursively. */
/** The enable/disable mechanism is a directory move, not a live switch. */
effectNote(enabled) {
return enabled
? '已放回技能目录:新会话可见;已在运行的会话可能仍保留旧状态。'
: '已移出技能目录:新会话不再加载;已经加载的会话不受影响。';
}
/** Preview of what an uninstall would remove. Nothing is deleted yet. */
async uninstallPlan(folderInput) {
const folder = checkFolder(folderInput);
const found = await this.locate(folder);
if (found === undefined)
fail('not_found', `没有找到技能:${folder}`);
if (await isSymlink(found.dir))
fail('unsupported', `技能目录是链接,不在这里删除:${folder}`);
const entry = await this.describe(folder, found.dir, found.area === 'root', await this.uploaded());
const files = await walkFiles(found.dir);
return {
folder,
dir: found.dir,
area: found.area,
files: files.length,
bytes: files.reduce((sum, file) => sum + file.bytes, 0),
scripts: files.filter((file) => file.script).map((file) => file.path).slice(0, 20),
origin: entry?.origin ?? 'unknown',
...(entry?.revision === undefined ? {} : { cloudRevision: entry.revision }),
recoverable: false,
note: '本机删除不可恢复(没有回收站)。云端副本不受影响,同步引擎也不会把同一版本再次拉回。',
};
}
/**
* Delete one skill for real: its folder is removed recursively.
*
* The route layer requires a plan token plus `confirmed: true`; this method
* itself stays usable by the verification harness and by trusted callers.
*/
async remove(folderInput) {
this.guardSync();
const folder = checkFolder(folderInput);
const found = await this.locate(folder);
if (found === undefined)
fail('not_found', `没有找到技能:${folder}`);
const files = await walkFiles(found.dir);
const bytes = files.reduce((sum, file) => sum + file.bytes, 0);
await rm(found.dir, { recursive: true, force: true });
this.deps.log(`skill deleted: ${folder}`);
return { folder };
return { folder, dir: found.dir, files: files.length, bytes };
}
async readPlans() {
try {
const parsed = JSON.parse(await readFile(this.plansFile(), 'utf8'));
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
const plans = parsed.plans;
if (Array.isArray(plans))
return { version: 1, plans: plans };
}
}
catch {
// Missing or torn file: no plans.
}
return { version: 1, plans: [] };
}
async writePlans(file) {
const path = this.plansFile();
await mkdir(dirname(path), { recursive: true });
const temporary = `${path}.tmp`;
await writeFile(temporary, `${JSON.stringify(file, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
await rename(temporary, path);
}
/** Drop expired plans and their staging trees. */
async sweepPlans(file) {
const now = Date.now();
const live = [];
for (const plan of file.plans) {
if (plan.expiresAt > now) {
live.push(plan);
continue;
}
await rm(plan.stagingDir, { recursive: true, force: true }).catch(() => { });
}
return { version: 1, plans: live };
}
/**
* Install every skill found in a git repository (https:// or file://).
* The clone is shallow and never executes repository code; folders
* that collide with existing skills are skipped, never overwritten.
* Stage a git repository and describe its skills. Nothing enters the skills
* root here; the caller picks folders and commits.
*/
async installFromGit(urlInput) {
async prepareInstall(urlInput, options = {}) {
this.guardSync();
if (typeof urlInput !== 'string')
fail('invalid_url', '请提供仓库地址。');
@ -202,61 +414,236 @@ export class SkillAdmin {
if (!/^(https:\/\/|file:\/\/)/.test(url) || /[\s"'`]/.test(url) || url.length > 512) {
fail('invalid_url', '只接受 https:// 或 file:// 的 git 仓库地址。');
}
const scratch = join(dshHome(), `.cloud-memory-clone-${process.pid}-${Date.now().toString(36)}`);
const stagingRoot = this.stagingRoot();
await mkdir(stagingRoot, { recursive: true });
const planId = `plan_${Date.now().toString(36)}_${randomUUID().slice(0, 8)}`;
const stagingDir = join(stagingRoot, planId);
try {
await new Promise((resolvePromise, rejectPromise) => {
execFile('git', ['clone', '--depth', '1', '--no-tags', '--', url, scratch], { timeout: 120_000, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' }, maxBuffer: 4 * 1024 * 1024 }, (error) => (error ? rejectPromise(error) : resolvePromise()));
});
}
catch {
await rm(scratch, { recursive: true, force: true }).catch(() => { });
fail('git_failed', '仓库克隆失败(地址不可达、需要登录,或本机没有 git)。');
}
try {
const repoName = basename(url.replace(/\/$/, '').replace(/\.git$/, '')) || 'skill';
const candidates = [];
const collect = async (dir, depth) => {
if (await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined) !== undefined) {
candidates.push({ folder: dir === scratch ? repoName : basename(dir), dir });
return;
}
if (depth >= 3)
return;
for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
if (entry.isDirectory() && entry.name !== '.git')
await collect(join(dir, entry.name), depth + 1);
}
};
await collect(scratch, 0);
if (candidates.length === 0)
fail('no_skills_found', '仓库里没有找到技能(包含 SKILL.md 的文件夹)。');
const installed = [];
const skipped = [];
await mkdir(this.deps.skillsRoot(), { recursive: true });
for (const candidate of candidates) {
let folder = candidate.folder;
await execFileText('git', ['clone', '--depth', '1', '--no-tags', '--', url, stagingDir]);
if (typeof options.ref === 'string' && options.ref !== '') {
try {
folder = checkFolder(folder);
await execFileText('git', ['-C', stagingDir, 'fetch', '--depth', '1', 'origin', options.ref]);
await execFileText('git', ['-C', stagingDir, 'checkout', '--detach', 'FETCH_HEAD']);
}
catch {
skipped.push({ name: candidate.folder, reason: 'invalid_name' });
continue;
// The default-branch clone is still usable; the recorded commit below
// is whatever was actually checked out, so an install stays auditable.
}
if ((await this.locate(folder)) !== undefined) {
skipped.push({ name: folder, reason: 'already_exists' });
continue;
}
await cp(candidate.dir, join(this.deps.skillsRoot(), folder), {
recursive: true,
filter: (source) => !source.split(/[\\/]/).includes('.git'),
});
installed.push(folder);
this.deps.log(`skill installed from git: ${folder}`);
}
return { installed, skipped };
}
finally {
await rm(scratch, { recursive: true, force: true }).catch(() => { });
catch (error) {
await rm(stagingDir, { recursive: true, force: true }).catch(() => { });
const code = error.code;
fail('git_failed', code === 'ENOENT'
? '本机没有 git 命令,无法从仓库安装技能。'
: '仓库克隆失败(地址不可达、需要登录,或不是 git 仓库)。');
}
let commit = '';
try {
commit = (await execFileText('git', ['-C', stagingDir, 'rev-parse', 'HEAD'], 20_000)).trim();
}
catch {
commit = '';
}
const repoName = basename(url.replace(/\/$/, '').replace(/\.git$/, '')) || 'skill';
const found = [];
const collect = async (dir, depth) => {
if (found.length >= MAX_CANDIDATES)
return;
const markdown = await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined);
if (markdown !== undefined) {
found.push({ folder: dir === stagingDir ? repoName : basename(dir), dir });
return;
}
if (depth >= 3)
return;
for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
if (entry.isDirectory() && entry.name !== '.git' && !entry.isSymbolicLink()) {
await collect(join(dir, entry.name), depth + 1);
}
}
};
await collect(stagingDir, 0);
if (found.length === 0) {
await rm(stagingDir, { recursive: true, force: true }).catch(() => { });
fail('no_skills_found', '仓库里没有找到技能(包含 SKILL.md 的文件夹)。');
}
const candidates = [];
for (const candidate of found) {
const markdown = await readFile(join(candidate.dir, 'SKILL.md'), 'utf8').catch(() => '');
const frontmatter = parseSkillFrontmatter(markdown);
const files = await walkFiles(candidate.dir);
const bytes = files.reduce((sum, file) => sum + file.bytes, 0);
const existing = await this.locate(candidate.folder);
let problem;
try {
checkFolder(candidate.folder);
}
catch {
problem = '目录名不合法,不能作为技能目录';
}
if (problem === undefined && files.length > MAX_SKILL_FILES)
problem = `文件过多(>${MAX_SKILL_FILES})`;
if (problem === undefined && bytes > MAX_SKILL_BYTES)
problem = `体积过大(>${MAX_SKILL_BYTES} 字节)`;
const name = frontmatter.name;
candidates.push({
folder: candidate.folder,
name: typeof name === 'string' && name !== '' ? name : candidate.folder,
description: String(frontmatter.description ?? '').slice(0, 300),
files: files.length,
bytes,
scripts: files.filter((file) => file.script).map((file) => file.path).slice(0, 20),
conflict: existing !== undefined,
...(existing === undefined ? {} : { conflictLocation: existing.area }),
...(problem === undefined ? {} : { problem }),
rel: relative(stagingDir, candidate.dir),
});
}
const plan = {
id: planId,
kind: 'install',
url,
createdAt: Date.now(),
expiresAt: Date.now() + PLAN_TTL_MS,
stagingDir,
candidates,
...(commit === '' ? {} : { commit }),
...(typeof options.ref === 'string' && options.ref !== '' ? { ref: options.ref } : {}),
...(options.source === undefined ? {} : { source: options.source }),
};
const file = await this.sweepPlans(await this.readPlans());
file.plans.push(plan);
await this.writePlans(file);
this.deps.log(`skill install staged: ${url} -> ${planId} (${candidates.length} candidates)`);
return {
planId,
url,
expiresAt: plan.expiresAt,
...(commit === '' ? {} : { commit }),
candidates: candidates.map((candidate) => ({ ...candidate, id: candidate.folder })),
};
}
/** Install the folders the user picked from a staged plan. */
async commitInstall(planInput) {
this.guardSync();
const planId = typeof planInput.planId === 'string' ? planInput.planId : '';
if (planId === '')
fail('invalid_plan', '缺少安装计划 id。');
const selection = Array.isArray(planInput.folders) ? planInput.folders : [];
const file = await this.sweepPlans(await this.readPlans());
const plan = file.plans.find((item) => item.id === planId);
if (plan === undefined) {
await this.writePlans(file);
fail('plan_expired', '安装计划已过期或不存在,请重新拉取仓库。');
}
const wanted = selection.map((value) => checkFolder(value));
const installed = [];
const skipped = [];
const skillsRoot = resolve(this.deps.skillsRoot());
await mkdir(skillsRoot, { recursive: true });
for (const candidate of plan.candidates) {
if (!wanted.includes(candidate.folder))
continue;
if (candidate.problem !== undefined) {
skipped.push({ folder: candidate.folder, reason: candidate.problem });
continue;
}
const existing = await this.locate(candidate.folder);
if (existing !== undefined) {
skipped.push({ folder: candidate.folder, reason: existing.area === 'holding' ? 'already_exists_disabled' : 'already_exists' });
continue;
}
const stagingRoot = resolve(plan.stagingDir);
const source = candidate.rel !== undefined && candidate.rel !== ''
? resolve(stagingRoot, candidate.rel)
: candidate.folder === basename(plan.stagingDir) ? stagingRoot : resolve(stagingRoot, candidate.folder);
const target = resolve(skillsRoot, candidate.folder);
// Both sides must stay inside their own root: a crafted plan file cannot
// make this write outside the skills directory.
if (!source.startsWith(stagingRoot) || !target.startsWith(`${skillsRoot}${sep}`)) {
skipped.push({ folder: candidate.folder, reason: 'path_escape' });
continue;
}
await cp(source, target, {
recursive: true,
// `.git` never travels with a skill, and a link could point outside the
// repository: both are dropped rather than copied.
filter: (sourcePath) => !sourcePath.split(/[\\/]/).includes('.git') && !isSymlinkSync(sourcePath),
});
// Record provenance so the skill can later be diffed, updated and rolled
// back without the cloud center. The file holds no credentials.
if (plan.commit !== undefined && plan.commit !== '') {
const record = {
version: 1,
provider: plan.source?.provider ?? 'git',
repoUrl: plan.url,
ref: plan.ref ?? plan.commit,
commit: plan.commit,
sourcePath: candidate.rel ?? candidate.folder,
installedAt: new Date().toISOString(),
...(plan.source?.entryId === undefined ? {} : { entryId: plan.source.entryId }),
...(plan.source?.version === undefined ? {} : { marketVersion: plan.source.version }),
};
await writeFile(join(target, '.skill-source.json'), `${JSON.stringify(record, null, 2)}\n`, 'utf8').catch(() => { });
}
installed.push(candidate.folder);
this.deps.log(`skill installed from git: ${candidate.folder}`);
}
const remaining = plan.candidates
.filter((candidate) => !installed.includes(candidate.folder))
.map((candidate) => candidate.folder);
file.plans = file.plans.filter((item) => item.id !== planId);
await this.writePlans(file);
await rm(plan.stagingDir, { recursive: true, force: true }).catch(() => { });
return { installed, skipped, remaining };
}
/** Throw away a staged plan and its clone. */
async cancelInstall(planInput) {
const planId = typeof planInput.planId === 'string' ? planInput.planId : '';
if (planId === '')
fail('invalid_plan', '缺少安装计划 id。');
const file = await this.sweepPlans(await this.readPlans());
const plan = file.plans.find((item) => item.id === planId);
file.plans = file.plans.filter((item) => item.id !== planId);
await this.writePlans(file);
if (plan !== undefined)
await rm(plan.stagingDir, { recursive: true, force: true }).catch(() => { });
return { cancelled: planId };
}
/**
* Legacy one-shot install, kept for the standalone `/cloud-memory/skills`
* page: stage the repository, then install every candidate that neither
* collides with an existing skill nor trips a limit. It still never
* overwrites and never executes repository content.
*/
async installFromGit(urlInput) {
const plan = await this.prepareInstall(urlInput);
const folders = plan.candidates
.filter((candidate) => candidate.conflict !== true && candidate.problem === undefined)
.map((candidate) => candidate.folder);
const result = await this.commitInstall({ planId: plan.planId, folders });
const skipped = plan.candidates
.filter((candidate) => !result.installed.includes(candidate.folder))
.map((candidate) => ({
name: candidate.folder,
reason: candidate.conflict === true
? (candidate.conflictLocation === 'holding' ? 'already_exists_disabled' : 'already_exists')
: candidate.problem ?? 'skipped',
}));
return { installed: result.installed, skipped };
}
/** Pending plans, so a reloaded page can resume a staged install. */
async listPlans() {
const file = await this.sweepPlans(await this.readPlans());
await this.writePlans(file);
return {
plans: file.plans.map((plan) => ({
planId: plan.id,
url: plan.url,
expiresAt: plan.expiresAt,
folders: plan.candidates.map((candidate) => candidate.folder),
})),
};
}
}

457
lib/skill-groups.js Normal file
View File

@ -0,0 +1,457 @@
/**
* Multi-source skill tree.
*
* The card groups skills the way the user thinks about them: by the software
* that owns the directory (DSH, 公共 Agent, Codex, WorkBuddy, …), then by
* user-defined categories inside that source.
*
* Two rules keep this honest:
*
* 1. A category is metadata only. Creating, renaming or deleting one never
* moves or removes a skill file; deleting a category just sends its skills
* back to 未分类. That is what the "分类只记在这个来源里,不移动文件" note
* promises, and it is the only reason a delete button is safe here.
* 2. Only the DSH source is ours to switch. Parking a DSH skill is the same
* directory move the rest of the plugin uses. Another software's directory
* is never touched: its switch is recorded for this card only and the view
* says so, instead of pretending Codex stopped loading something.
*/
import { execFile } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
import { readdir, readFile } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join, resolve } from 'node:path';
import { dshHome } from "./store.js";
const MAX_GROUP_NAME = 40;
const MAX_GROUPS_PER_SOURCE = 40;
/** Sidecar path. */
export function skillGroupsPath() {
return join(dshHome(), 'cloud-memory-skill-groups.json');
}
/**
* The known sources.
*
* A source is listed even when its directory is missing (0 skills, "未安装"),
* because that is how a user learns the software exists; it is never invented
* as present.
*/
export function detectSources() {
const home = homedir();
return [
{ id: 'dsh', label: 'DSH', root: join(dshHome(), 'skills'), writable: true, manager: 'DSH' },
{
id: 'agents',
label: '公共 Agent',
root: join(home, '.agents', 'skills'),
writable: false,
manager: '公共 Agent 约定目录',
note: '由使用该目录的各客户端自行加载,本卡只读',
},
{
id: 'codex',
label: 'Codex',
root: join(home, '.codex', 'skills'),
writable: false,
manager: 'Codex',
note: '由 Codex 自行加载,本卡不修改它的目录',
},
{
id: 'workbuddy',
label: 'WorkBuddy',
root: join(home, '.workbuddy', 'skills'),
writable: false,
manager: 'WorkBuddy',
note: '由 WorkBuddy 自行加载,本卡不修改它的目录',
},
{
id: 'claude',
label: 'Claude Code',
root: join(home, '.claude', 'skills'),
writable: false,
manager: 'Claude Code',
note: '由 Claude Code 自行加载,本卡不修改它的目录',
},
{
id: 'opencode',
label: 'OpenCode',
root: join(home, '.config', 'opencode', 'skills'),
writable: false,
manager: 'OpenCode',
note: '由 OpenCode 自行加载,本卡不修改它的目录',
},
];
}
function groupId() {
return `g_${randomUUID().slice(0, 8)}`;
}
/** Trim and bound one user-supplied category name. */
function cleanGroupName(value) {
const name = typeof value === 'string' ? value.trim() : '';
if (name === '' || name.length > MAX_GROUP_NAME) {
throw new SkillGroupError('invalid_name', '分类名需要 1–40 个字符。');
}
return name;
}
/** A group failure with a stable code, mapped to an HTTP status by the route. */
export class SkillGroupError extends Error {
code;
constructor(code, message) {
super(message);
this.code = code;
this.name = 'SkillGroupError';
}
}
/** Read one skill directory without following links. */
async function readSkill(root, folder) {
const dir = join(root, folder);
try {
const info = statSync(dir);
if (!info.isDirectory())
return undefined;
}
catch {
return undefined;
}
const markdown = await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined);
if (markdown === undefined)
return undefined;
const frontmatter = /^---\s*([\s\S]*?)\s*---/.exec(markdown);
const name = frontmatter === null ? '' : (/^name:\s*(.+)$/m.exec(frontmatter[1] ?? '')?.[1] ?? '').trim();
const description = frontmatter === null ? '' : (/^description:\s*(.+)$/m.exec(frontmatter[1] ?? '')?.[1] ?? '').trim();
let files = 0;
let bytes = 0;
const walk = async (sub) => {
if (files > 2000)
return;
for (const entry of await readdir(join(dir, sub), { withFileTypes: true }).catch(() => [])) {
if (entry.name === '.git')
continue;
const rel = sub === '' ? entry.name : `${sub}/${entry.name}`;
if (entry.isDirectory()) {
await walk(rel);
continue;
}
if (!entry.isFile())
continue;
files += 1;
try {
bytes += statSync(join(dir, rel)).size;
}
catch {
// A file removed mid-walk only affects the size hint.
}
}
};
await walk('');
return {
folder,
name: name === '' ? folder : name,
description: description.slice(0, 300),
enabled: true,
enabledEditable: false,
files,
bytes,
inCardDisabled: false,
};
}
/** List the folders of one source that look like skills. */
async function readSource(root) {
const skills = [];
for (const entry of await readdir(root, { withFileTypes: true }).catch(() => [])) {
if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name.startsWith('_'))
continue;
const skill = await readSkill(root, entry.name);
if (skill !== undefined)
skills.push(skill);
}
skills.sort((a, b) => (a.folder < b.folder ? -1 : 1));
return skills;
}
export class SkillGroupManager {
deps;
constructor(deps) {
this.deps = deps;
}
file() {
return this.deps.storePath?.() ?? skillGroupsPath();
}
read() {
try {
const parsed = JSON.parse(readFileSync(this.file(), 'utf8'));
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
const doc = parsed;
if (doc.sources !== null && typeof doc.sources === 'object')
return { version: 1, sources: doc.sources };
}
}
catch {
// Missing or torn sidecar: start from "everything unassigned".
}
return { version: 1, sources: {} };
}
write(next) {
const path = this.file();
mkdirSync(resolve(path, '..'), { recursive: true });
const temporary = `${path}.tmp`;
writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
renameSync(temporary, path);
}
source(id) {
const sourceId = typeof id === 'string' ? id : '';
const found = this.deps.sources().find((source) => source.id === sourceId);
if (found === undefined)
throw new SkillGroupError('unknown_source', `未知来源:${String(id)}`);
return found;
}
/** Skills of one source, with this plugin's own enable state for DSH. */
async skillsOf(source) {
if (source.writable) {
const inventory = await this.deps.admin.list();
return inventory.skills.map((skill) => ({
folder: skill.folder,
name: skill.name,
description: skill.description,
enabled: skill.enabled,
enabledEditable: true,
files: skill.files,
bytes: skill.bytes,
origin: skill.origin,
...(skill.revision === undefined ? {} : { revision: skill.revision }),
inCardDisabled: false,
}));
}
return readSource(source.root);
}
/** Everything the tree renders: sources → groups → skills. */
async overview() {
const doc = this.read();
const sources = [];
for (const source of this.deps.sources()) {
const skills = await this.skillsOf(source);
const state = doc.sources[source.id] ?? {};
const groups = Array.isArray(state.groups) ? state.groups : [];
const assigned = new Set();
const views = [];
for (const group of groups) {
const members = skills.filter((skill) => group.skills.includes(skill.folder));
for (const member of members)
assigned.add(member.folder);
const enabled = group.enabled !== false;
// A group switch is real only where the source is real.
const cardOnly = !source.writable;
views.push({
id: group.id,
name: group.name,
enabled,
enabledEditable: true,
cardOnly,
total: members.length,
enabledCount: members.filter((skill) => skill.enabled && enabled).length,
skills: members.map((skill) => ({ ...skill, enabled: skill.enabled && enabled, inCardDisabled: enabled === false })),
});
}
const rest = skills.filter((skill) => !assigned.has(skill.folder));
views.push({
id: 'unassigned',
name: '未分类',
// The bucket's own switch is "every skill that has no category": it is
// on only when all of them are, and switching it parks/restores them
// one by one like any other group.
enabled: rest.length === 0 || rest.every((skill) => skill.enabled),
enabledEditable: rest.length > 0,
cardOnly: !source.writable,
total: rest.length,
enabledCount: rest.filter((skill) => skill.enabled).length,
skills: rest,
});
const sourceEnabled = state.enabled !== false;
sources.push({
id: source.id,
label: source.label,
root: source.root,
exists: existsSync(source.root),
writable: source.writable,
manager: source.manager,
...(source.note === undefined ? {} : { note: source.note }),
enabled: sourceEnabled,
enabledEditable: true,
cardOnly: !source.writable,
total: skills.length,
enabledCount: skills.filter((skill) => skill.enabled && sourceEnabled).length,
groups: views,
});
}
return {
sources,
note: '分类只记在这个来源里,不移动文件。只有 DSH 来源的开关会真实启停技能目录;其他软件的目录本卡不修改。',
};
}
/** Create one category inside a source. */
async createGroup(sourceInput, nameInput) {
const source = this.source(sourceInput);
const name = cleanGroupName(nameInput);
const doc = this.read();
const state = doc.sources[source.id] ?? {};
const groups = state.groups ?? [];
if (groups.length >= MAX_GROUPS_PER_SOURCE)
throw new SkillGroupError('too_many', `每个来源最多 ${MAX_GROUPS_PER_SOURCE} 个分类。`);
if (groups.some((group) => group.name === name))
throw new SkillGroupError('duplicate', `这个来源里已经有分类「${name}」。`);
const id = groupId();
doc.sources[source.id] = { ...state, groups: [...groups, { id, name, enabled: true, skills: [] }] };
this.write(doc);
this.deps.log?.(`skill category created: ${source.id}/${name}`);
return { groupId: id, name };
}
/** Rename one category; membership and files are untouched. */
async renameGroup(sourceInput, groupInput, nameInput) {
const source = this.source(sourceInput);
const id = typeof groupInput === 'string' ? groupInput : '';
const name = cleanGroupName(nameInput);
const doc = this.read();
const state = doc.sources[source.id] ?? {};
const groups = state.groups ?? [];
const target = groups.find((group) => group.id === id);
if (target === undefined)
throw new SkillGroupError('not_found', '没有找到这个分类。');
if (groups.some((group) => group.name === name && group.id !== id)) {
throw new SkillGroupError('duplicate', `这个来源里已经有分类「${name}」。`);
}
target.name = name;
doc.sources[source.id] = { ...state, groups };
this.write(doc);
return { groupId: id, name };
}
/**
* Delete one category. Its skills move back to 未分类; no file is touched,
* which is why this needs no impact plan of its own.
*/
async deleteGroup(sourceInput, groupInput) {
const source = this.source(sourceInput);
const id = typeof groupInput === 'string' ? groupInput : '';
const doc = this.read();
const state = doc.sources[source.id] ?? {};
const groups = state.groups ?? [];
const target = groups.find((group) => group.id === id);
if (target === undefined)
throw new SkillGroupError('not_found', '没有找到这个分类。');
doc.sources[source.id] = { ...state, groups: groups.filter((group) => group.id !== id) };
this.write(doc);
this.deps.log?.(`skill category removed: ${source.id}/${target.name}`);
return { groupId: id, released: target.skills.length };
}
/** Move skills into (or out of) a category. Membership only. */
async assign(sourceInput, groupInput, foldersInput) {
const source = this.source(sourceInput);
const id = typeof groupInput === 'string' ? groupInput : '';
const folders = Array.isArray(foldersInput)
? foldersInput.filter((value) => typeof value === 'string' && value !== '' && !value.includes('/') && !value.includes('\\'))
: [];
const doc = this.read();
const state = doc.sources[source.id] ?? {};
const groups = state.groups ?? [];
if (id === 'unassigned' || folders.length === 0) {
// Clearing a selection means "back to 未分类" for every other group.
for (const group of groups)
group.skills = group.skills.filter((folder) => !folders.includes(folder));
doc.sources[source.id] = { ...state, groups };
this.write(doc);
return { groupId: 'unassigned', members: [] };
}
const target = groups.find((group) => group.id === id);
if (target === undefined)
throw new SkillGroupError('not_found', '没有找到这个分类。');
// A skill belongs to at most one category: remove it everywhere else first.
for (const group of groups) {
if (group === target)
continue;
group.skills = group.skills.filter((folder) => !folders.includes(folder));
}
target.skills = [...new Set([...target.skills, ...folders])].sort();
doc.sources[source.id] = { ...state, groups };
this.write(doc);
return { groupId: id, members: target.skills };
}
/**
* Switch one category on or off.
*
* DSH groups are really parked or restored, one folder at a time, and a
* failure leaves the remaining folders untouched. Foreign groups only record
* the switch here, and the answer says `cardOnly: true`.
*/
async toggleGroup(sourceInput, groupInput, enabled) {
const source = this.source(sourceInput);
const id = typeof groupInput === 'string' ? groupInput : '';
const doc = this.read();
const state = doc.sources[source.id] ?? {};
const groups = state.groups ?? [];
let targets = [];
if (id === 'unassigned') {
// "未分类" is the bucket of everything no category claims; its switch
// applies to exactly those skills and is not persisted.
const assigned = new Set(groups.flatMap((group) => group.skills));
const skills = await this.skillsOf(source);
targets = skills.filter((skill) => !assigned.has(skill.folder)).map((skill) => skill.folder);
if (!source.writable)
return { groupId: id, enabled, cardOnly: true, applied: [], failed: [] };
}
else {
const target = groups.find((group) => group.id === id);
if (target === undefined)
throw new SkillGroupError('not_found', '没有找到这个分类。');
target.enabled = enabled;
doc.sources[source.id] = { ...state, groups };
this.write(doc);
if (!source.writable)
return { groupId: id, enabled, cardOnly: true, applied: [], failed: [] };
targets = target.skills;
}
const applied = [];
const failed = [];
for (const folder of targets) {
try {
await this.deps.admin.setEnabled(folder, enabled);
applied.push(folder);
}
catch (failure) {
failed.push({ folder, reason: failure instanceof Error ? failure.message : String(failure) });
}
}
return { groupId: id, enabled, cardOnly: false, applied, failed };
}
/** Switch a whole source. DSH really moves every skill; others record it. */
async toggleSource(sourceInput, enabled) {
const source = this.source(sourceInput);
const doc = this.read();
const state = doc.sources[source.id] ?? {};
doc.sources[source.id] = { ...state, enabled };
this.write(doc);
if (!source.writable)
return { sourceId: source.id, enabled, cardOnly: true, applied: 0, failed: [] };
const skills = await this.skillsOf(source);
const failed = [];
let applied = 0;
for (const skill of skills) {
try {
await this.deps.admin.setEnabled(skill.folder, enabled);
applied += 1;
}
catch (failure) {
failed.push({ folder: skill.folder, reason: failure instanceof Error ? failure.message : String(failure) });
}
}
return { sourceId: source.id, enabled, cardOnly: false, applied, failed };
}
/** Open one source directory in the OS file manager (explicit user click). */
async reveal(sourceInput) {
const source = this.source(sourceInput);
if (!existsSync(source.root))
throw new SkillGroupError('not_found', `${source.label} 的技能目录还不存在:${source.root}`);
const command = process.platform === 'win32' ? 'explorer.exe' : process.platform === 'darwin' ? 'open' : 'xdg-open';
await new Promise((resolvePromise) => {
execFile(command, [source.root], { windowsHide: false }, () => resolvePromise());
});
return { path: source.root };
}
}

View File

@ -30,7 +30,7 @@
* silently trimmed.
*/
import { createHash, randomUUID } from 'node:crypto';
import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
import { mkdir, cp, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
import { dirname, join, resolve } from 'node:path';
import { describeError } from "./api.js";
import { dshHome } from "./store.js";
@ -516,4 +516,192 @@ export class SkillSync {
hasScripts: files.some((file) => file.rel.startsWith('scripts/')),
};
}
/** Encode local files exactly the way the upload path does. */
toUploadFiles(files) {
return files.map((file) => {
const ext = file.rel.slice(file.rel.lastIndexOf('.')).toLowerCase();
return TEXT_EXT.has(ext)
? { path: file.rel, content: file.buffer.toString('utf8') }
: { path: file.rel, base64: file.buffer.toString('base64') };
});
}
/** Drop one name from the in-memory conflict list after it is resolved. */
dropConflict(name) {
this.current = { ...this.current, conflicts: this.current.conflicts.filter((conflict) => conflict.name !== name) };
}
/**
* Both sides of every conflict from the last pass, so a human can decide.
* Read-only: it never changes a file or uploads anything.
*/
async conflictDetails() {
const conflicts = this.current.conflicts;
if (conflicts.length === 0)
return [];
let cloudItems = [];
try {
const listing = await this.deps.client().listSkills();
if (listing.ok) {
cloudItems = (listing.data.items ?? []).filter((item) => typeof item.name === 'string');
}
}
catch {
// Listing failed: still show the local side with a null cloud side.
}
const byName = new Map(cloudItems.map((item) => [item.name, item]));
const out = [];
for (const conflict of conflicts) {
const rootDir = join(this.skillsRoot(), conflict.name);
const parkedDir = join(this.holdingRoot(), conflict.name);
let location = 'none';
let dir = '';
if (await isDirectory(rootDir)) {
location = 'root';
dir = rootDir;
}
else if (await isDirectory(parkedDir)) {
location = 'holding';
dir = parkedDir;
}
let files = 0;
let bytes = 0;
let modified = false;
if (dir !== '') {
try {
const local = await this.readSkillFiles(dir);
files = local.length;
bytes = local.reduce((sum, file) => sum + file.buffer.length, 0);
const delivery = await this.readDelivery(dir);
modified = delivery === undefined ? true : !(await this.deliveredIntact(dir, delivery));
}
catch {
// Unreadable folder: report zeroed counts, never throw the list away.
}
}
const cloudItem = byName.get(conflict.name);
out.push({
name: conflict.name,
reason: conflict.reason,
local: { exists: location !== 'none', location, files, bytes, modified },
cloud: cloudItem === undefined
? null
: {
...(cloudItem.revision === undefined ? {} : { revision: cloudItem.revision }),
...(cloudItem.manifest_sha256 === undefined ? {} : { manifest: cloudItem.manifest_sha256 }),
...(cloudItem.files === undefined ? {} : { files: cloudItem.files }),
...(cloudItem.bytes === undefined ? {} : { bytes: cloudItem.bytes }),
...(cloudItem.enabled === undefined ? {} : { enabled: cloudItem.enabled }),
},
canKeepLocal: location !== 'none',
canTakeCloud: cloudItem !== undefined,
note: '“保留本地”把本地版本上传成新的云端版本;“采用云端”先备份本地再覆盖;“手动合并”只返回两侧信息,不改文件。',
});
}
return out;
}
/** Resolve one conflict: keep local / take cloud / manual (no write). */
async resolveConflict(nameInput, actionInput) {
const name = typeof nameInput === 'string' ? nameInput : '';
if (name === '' || !CLOUD_SKILL_NAME.test(name))
throw new Error('invalid_name');
const action = actionInput === 'keep_local' || actionInput === 'take_cloud' || actionInput === 'manual' ? actionInput : '';
if (action === '')
throw new Error('invalid_action');
if (this.running)
throw new Error('sync_running');
const root = this.skillsRoot();
const rootDir = join(root, name);
const parkedDir = join(this.holdingRoot(), name);
const inRoot = await isDirectory(rootDir);
const parked = !inRoot && (await isDirectory(parkedDir));
const dir = inRoot ? rootDir : parked ? parkedDir : '';
const client = this.deps.client();
const listing = await client.listSkills();
if (!listing.ok)
throw new Error(`skill listing failed: ${describeError(listing.error)}`);
const cloud = (listing.data.items ?? []).find((item) => item.name === name);
const state = await this.loadState();
if (action === 'manual') {
return {
name,
action,
applied: false,
note: '已返回两侧信息,未改动任何文件;手工编辑后在下次同步前保存即可。',
...(cloud?.revision === undefined ? {} : { revision: cloud.revision }),
};
}
if (action === 'keep_local') {
if (dir === '')
throw new Error('no_local_copy');
const skill = await this.readLocalSkill(dir, name);
if (skill === undefined)
throw new Error('not_a_skill');
if (typeof skill === 'string')
throw new Error(skill);
const files = this.toUploadFiles(skill.files);
const operationId = `dsh-skill-${randomUUID()}`;
if (cloud === undefined) {
const created = await client.createSkill({
name: skill.name,
description: skill.description,
execution_mode: skill.hasScripts ? 'local-bundle' : 'prompt-only',
files,
expected_revision: 0,
operation_id: operationId,
});
if (!created.ok)
throw new Error(`upload_failed: ${describeError(created.error)}`);
const revision = created.data.skill?.revision ?? created.data.revision ?? 1;
state.uploaded[name] = { folder: name, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() };
delete state.removed[name];
await this.saveState(state);
this.dropConflict(name);
return { name, action, applied: true, revision, note: '已把本地版本新建到云端。' };
}
const updated = await client.updateSkill(name, {
description: skill.description,
files,
expected_revision: cloud.revision ?? 0,
operation_id: operationId,
});
if (!updated.ok) {
if (updated.error.code === 'revision_conflict')
throw new Error('stale_revision');
throw new Error(`upload_failed: ${describeError(updated.error)}`);
}
const revision = updated.data.skill?.revision ?? updated.data.revision ?? (cloud.revision ?? 0) + 1;
state.uploaded[name] = { folder: name, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() };
delete state.removed[name];
await this.saveState(state);
this.dropConflict(name);
return { name, action, applied: true, revision, note: '已用本地版本覆盖云端(revision 已更新)。' };
}
// take_cloud
if (cloud === undefined)
throw new Error('no_cloud_copy');
const bundle = await client.skillBundle(name);
if (!bundle.ok)
throw new Error(`bundle_failed: ${describeError(bundle.error)}`);
if (linkedSkillManifest(bundle.data.files) !== bundle.data.manifest_sha256)
throw new Error('manifest_mismatch');
let backup = '';
if (dir !== '') {
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
backup = join(dshHome(), '.cloud-memory-backups', 'sync', name, stamp);
await mkdir(join(backup, '..'), { recursive: true });
await cp(dir, backup, { recursive: true, filter: (p) => !p.split(/[\\/]/).includes('.git') });
}
await this.install(cloud, bundle.data, parked ? this.holdingRoot() : root);
state.delivered[name] = { manifest: bundle.data.manifest_sha256 };
delete state.removed[name];
await this.saveState(state);
this.dropConflict(name);
return {
name,
action,
applied: true,
revision: bundle.data.revision,
...(backup === '' ? {} : { backup }),
note: '已采用云端版本覆盖本地(本地已备份)。',
};
}
}

289
lib/skill-update.js Normal file
View File

@ -0,0 +1,289 @@
/**
* Skill update & rollback (P3).
*
* Works only for skills that carry a `.skill-source.json` provenance record
* (written by the market / git install pipeline). Nothing here talks to the
* cloud center: it re-reads the pinned git source, shows a diff, keeps a local
* backup before touching the folder, and restores that backup on rollback.
*
* Safety rules baked in:
* - the source record is the only thing trusted for a repository URL;
* - a fresh clone happens in `$DSH_HOME/.cloud-memory-staging` and the copy is
* filtered (no `.git`, no symlinks);
* - a backup is always taken before an update so rollback is possible even
* when the update is interrupted;
* - a repository in-flight sync blocks any write.
*/
import { execFile } from 'node:child_process';
import { lstatSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { cp, lstat, mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
import { join, resolve } from 'node:path';
import { tmpdir } from 'node:os';
import { readSkillSourceRecord, SkillAdminError } from "./skill-admin.js";
import { dshHome } from "./store.js";
/** Where pre-update backups are kept (one folder per skill, one dir per run). */
export function skillBackupsDir() {
return join(dshHome(), '.cloud-memory-backups');
}
/** Run git and return stdout. */
function git(args, timeoutMs = 120_000) {
return new Promise((resolvePromise, rejectPromise) => {
execFile('git', args, { timeout: timeoutMs, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' }, maxBuffer: 8 * 1024 * 1024 }, (error, stdout) => (error ? rejectPromise(error) : resolvePromise(String(stdout))));
});
}
async function isSymlink(path) {
return lstat(path).then((s) => s.isSymbolicLink()).catch(() => true);
}
/** Hash every regular file under one directory (skips `.git` and symlinks). */
async function hashTree(dir) {
const out = new Map();
const walk = async (sub) => {
for (const entry of await readdir(join(dir, sub), { withFileTypes: true }).catch(() => [])) {
if (entry.name === '.git')
continue;
const rel = sub === '' ? entry.name : `${sub}/${entry.name}`;
const abs = join(dir, rel);
if (entry.isSymbolicLink())
continue;
if (entry.isDirectory()) {
await walk(rel);
continue;
}
if (!entry.isFile())
continue;
const buffer = await readFile(abs).catch(() => undefined);
if (buffer === undefined)
continue;
out.set(rel, { path: rel, sha256: createHash('sha256').update(buffer).digest('hex'), bytes: buffer.byteLength });
}
};
await walk('');
return out;
}
/** A short human bucket for what changed. */
function diffTrees(before, after) {
const added = [];
const removed = [];
const changed = [];
for (const [path, file] of after) {
const old = before.get(path);
if (old === undefined)
added.push(path);
else if (old.sha256 !== file.sha256)
changed.push(path);
}
for (const path of before.keys())
if (!after.has(path))
removed.push(path);
added.sort();
removed.sort();
changed.sort();
return { added, removed, changed };
}
/** Copy a skill tree, dropping `.git` and symlinks (same rule as install). */
async function copySkillTree(source, target) {
await cp(source, target, {
recursive: true,
filter: (path) => !path.split(/[\\/]/).includes('.git') && (() => {
try {
return !lstatSync(path).isSymbolicLink();
}
catch {
return false;
}
})(),
});
}
export class SkillUpdater {
deps;
constructor(deps) {
this.deps = deps;
}
backupsRoot() {
return this.deps.backupsDir?.() ?? skillBackupsDir();
}
guard() {
if (this.deps.syncRunning())
throw new SkillAdminError('sync_running', '技能同步正在进行,请稍候再试。');
}
async find(folder) {
const found = await this.deps.admin.locate(folder);
if (found === undefined)
throw new SkillAdminError('not_found', `没有找到技能:${folder}`);
const source = await readSkillSourceRecord(found.dir);
if (source === undefined) {
throw new SkillAdminError('no_source', `该技能没有来源记录(不是从 Git 或市场安装的),无法更新或回退。`);
}
return { dir: found.dir, source };
}
/** Clone the pinned source at its latest commit into a scratch directory. */
async cloneLatest(source) {
const root = join(dshHome(), '.cloud-memory-staging');
await mkdir(root, { recursive: true });
const dir = join(root, `update_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`);
try {
await git(['clone', '--depth', '1', '--no-tags', '--', source.repoUrl, dir]);
// A commit SHA is a pin, not a moving ref: leave the default-branch head
// in place so an update check compares against the latest upstream. A
// branch/tag name is fetched and checked out instead.
const isSha = /^[0-9a-f]{7,40}$/i.test(source.ref);
if (!isSha && source.ref !== '') {
try {
await git(['-C', dir, 'fetch', '--depth', '1', 'origin', source.ref]);
await git(['-C', dir, 'checkout', '--detach', 'FETCH_HEAD']);
}
catch {
// Fall back to the default branch head.
}
}
}
catch (error) {
await rm(dir, { recursive: true, force: true }).catch(() => { });
const code = error.code;
throw new SkillAdminError('git_failed', code === 'ENOENT'
? '本机没有 git 命令,无法检查更新。'
: '无法读取来源仓库(地址不可达、需要登录,或仓库已删除)。');
}
const commit = (await git(['-C', dir, 'rev-parse', 'HEAD'], 20_000)).trim();
return { dir, commit, cleanup: () => rm(dir, { recursive: true, force: true }).catch(() => { }) };
}
/** Compare the installed folder against the source's latest commit. */
async checkUpdate(folderInput) {
const folder = typeof folderInput === 'string' ? folderInput : '';
if (folder === '')
throw new SkillAdminError('invalid_name', '缺少技能目录名。');
const fetchedAt = Date.now();
const found = await this.deps.admin.locate(folder);
if (found === undefined)
throw new SkillAdminError('not_found', `没有找到技能:${folder}`);
const source = await readSkillSourceRecord(found.dir);
if (source === undefined) {
return { folder, updatable: false, reason: 'no_source', available: false, fetchedAt };
}
const clone = await this.cloneLatest(source);
try {
if (clone.commit === source.commit) {
return {
folder, updatable: true, available: false, provider: source.provider,
repoUrl: source.repoUrl, currentCommit: source.commit, remoteCommit: clone.commit, fetchedAt,
};
}
const remoteDir = source.sourcePath === '' ? clone.dir : resolve(clone.dir, source.sourcePath);
const before = await hashTree(found.dir);
const after = await hashTree(remoteDir);
// The provenance file is ours, not the source's: never show it as removed.
before.delete('.skill-source.json');
const diff = diffTrees(before, after);
return {
folder, updatable: true, available: true, provider: source.provider,
repoUrl: source.repoUrl, currentCommit: source.commit, remoteCommit: clone.commit,
...diff, fetchedAt,
};
}
finally {
await clone.cleanup();
}
}
/** Back up the current folder, then replace it with the source's latest. */
async applyUpdate(folderInput, expectedCommit) {
this.guard();
const folder = typeof folderInput === 'string' ? folderInput : '';
if (folder === '')
throw new SkillAdminError('invalid_name', '缺少技能目录名。');
const { dir, source } = await this.find(folder);
const check = await this.checkUpdate(folder);
if (!check.available)
throw new SkillAdminError('up_to_date', '已经是最新版本,无需更新。');
if (typeof expectedCommit === 'string' && expectedCommit !== '' && check.remoteCommit !== expectedCommit) {
throw new SkillAdminError('stale_plan', '来源在上次检查后已更新,请重新检查差异再更新。');
}
return this.replaceWith(dir, source, { commit: check.remoteCommit ?? source.commit, ref: source.ref });
}
/** Restore the most recent pre-update backup. */
async rollback(folderInput) {
this.guard();
const folder = typeof folderInput === 'string' ? folderInput : '';
if (folder === '')
throw new SkillAdminError('invalid_name', '缺少技能目录名。');
const { dir, source } = await this.find(folder);
const root = join(this.backupsRoot(), folder);
const entries = (await readdir(root, { withFileTypes: true }).catch(() => []))
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name)
.sort();
const latest = entries[entries.length - 1];
if (latest === undefined)
throw new SkillAdminError('no_backup', '没有可回退的备份。');
const backupDir = join(root, latest);
const restored = await readSkillSourceRecord(backupDir);
// Restore in place: move the current aside, copy the backup over, then drop
// the aside copy only after the backup has landed.
const aside = `${dir}.rollbacking-${Date.now().toString(36)}`;
await mkdir(join(dir, '..'), { recursive: true });
await rename(dir, aside);
try {
await copySkillTree(backupDir, dir);
}
catch (error) {
await rm(dir, { recursive: true, force: true }).catch(() => { });
await rename(aside, dir).catch(() => { });
throw new SkillAdminError('rollback_failed', `回退失败,原目录已尽量还原:${error instanceof Error ? error.message : String(error)}`);
}
await rm(aside, { recursive: true, force: true }).catch(() => { });
this.deps.log(`skill rolled back: ${folder} <- ${latest}`);
const beforeFiles = await hashTree(backupDir);
beforeFiles.delete('.skill-source.json');
const nowFiles = await hashTree(dir);
nowFiles.delete('.skill-source.json');
const diff = diffTrees(nowFiles, beforeFiles);
return {
folder,
from: source.commit,
to: restored?.commit ?? source.commit,
backup: backupDir,
...diff,
};
}
/** Shared write path: backup, copy new tree, rewrite provenance. */
async replaceWith(dir, source, next) {
const clone = await this.cloneLatest({ ...source, ref: next.ref });
let newDir = source.sourcePath === '' ? clone.dir : resolve(clone.dir, source.sourcePath);
try {
if (clone.commit !== next.commit) {
// A different head landed between check and apply: refuse, never guess.
throw new SkillAdminError('stale_plan', '来源在更新过程中已变化,请重新检查。');
}
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
const backupDir = join(this.backupsRoot(), this.lastSegment(dir), stamp);
await mkdir(join(backupDir, '..'), { recursive: true });
await copySkillTree(dir, backupDir);
const before = await hashTree(dir);
const after = await hashTree(newDir);
const diff = diffTrees(before, after);
const aside = `${dir}.updating-${Date.now().toString(36)}`;
await rename(dir, aside);
try {
await copySkillTree(newDir, dir);
await writeFile(join(dir, '.skill-source.json'), `${JSON.stringify({
...source, commit: next.commit, ref: next.ref, installedAt: new Date().toISOString(),
}, null, 2)}\n`, 'utf8');
}
catch (error) {
await rm(dir, { recursive: true, force: true }).catch(() => { });
await rename(aside, dir).catch(() => { });
throw new SkillAdminError('update_failed', `更新失败,原目录已还原:${error instanceof Error ? error.message : String(error)}`);
}
await rm(aside, { recursive: true, force: true }).catch(() => { });
this.deps.log(`skill updated: ${this.lastSegment(dir)} -> ${next.commit}`);
return { folder: this.lastSegment(dir), from: source.commit, to: next.commit, backup: backupDir, ...diff };
}
finally {
await clone.cleanup();
}
}
lastSegment(path) {
const parts = path.split(/[\\/]/).filter((part) => part !== '');
return parts[parts.length - 1] ?? path;
}
}

View File

@ -14,7 +14,7 @@
import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync, chmodSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { homedir } from 'node:os';
import { DEFAULT_SETTINGS, normalizeBaseUrl, settingsFromConfig } from "./config.js";
import { DEFAULT_SETTINGS, isPlaceholderBaseUrl, normalizeBaseUrl, originOf, settingsFromConfig } from "./config.js";
/** `$DSH_HOME` (or `~/.dsh`) — the same resolution DSH core uses. */
export function dshHome() {
const fromEnv = process.env.DSH_HOME;
@ -179,6 +179,8 @@ export class SettingsStore {
memoryToken: { configured: memory !== '', masked: memory === '' ? '' : maskToken(memory) },
summaryToken: { configured: summary !== '', masked: summary === '' ? '' : maskToken(summary) },
statePath: this.file,
baseUrlConfigured: !isPlaceholderBaseUrl(settings.baseUrl),
baseUrlOrigin: originOf(settings.baseUrl),
};
}
/**
@ -190,6 +192,9 @@ export class SettingsStore {
*/
patch(patch) {
const next = { ...this.state };
const beforeOrigin = originOf(this.settings().baseUrl);
/** Tokens this very request supplied; they survive an address change. */
const provided = [];
if (patch.enabled !== undefined) {
if (typeof patch.enabled !== 'boolean')
return { ok: false, error: 'enabled must be a boolean' };
@ -212,12 +217,14 @@ export class SettingsStore {
if (!activityToken.startsWith('cmt_'))
return { ok: false, error: 'activity token must start with cmt_' };
next.activityToken = activityToken;
provided.push('activity');
}
const memoryToken = cleanString(patch.memoryToken);
if (memoryToken !== undefined) {
if (!memoryToken.startsWith('cmt_'))
return { ok: false, error: 'memory token must start with cmt_' };
next.memoryToken = memoryToken;
provided.push('memory');
}
if (patch.requestTimeoutMs !== undefined) {
const requestTimeoutMs = clampInt(patch.requestTimeoutMs, 1000, 60_000);
@ -247,6 +254,7 @@ export class SettingsStore {
if (!summaryToken.startsWith('cmt_'))
return { ok: false, error: 'summary token must start with cmt_' };
next.summaryToken = summaryToken;
provided.push('summary');
}
if (patch.clearSummaryToken === true)
delete next.summaryToken;
@ -254,9 +262,29 @@ export class SettingsStore {
delete next.activityToken;
if (patch.clearMemoryToken === true)
delete next.memoryToken;
// Switching the service origin must not hand the previous service's
// bearer tokens to the new one: everything this request did not explicitly
// replace is dropped, and the caller is told so it can ask to re-authenticate.
const afterOrigin = originOf(next.baseUrl ?? this.configDefaults.baseUrl);
const clearedTokens = [];
if (beforeOrigin !== '' && afterOrigin !== '' && beforeOrigin !== afterOrigin) {
const credentials = [
['activity', 'activityToken'],
['memory', 'memoryToken'],
['summary', 'summaryToken'],
];
for (const [label, key] of credentials) {
if (next[key] === undefined)
continue;
if (provided.includes(label))
continue;
delete next[key];
clearedTokens.push(label);
}
}
this.write(next);
this.state = next;
return { ok: true };
return clearedTokens.length === 0 ? { ok: true } : { ok: true, clearedTokens };
}
/** File size in bytes, for a "sidecar exists" hint in the card. */
size() {

View File

@ -1,6 +1,6 @@
{
"name": "dsh-cloud-memory",
"version": "0.4.1",
"version": "0.7.0",
"description": "Cloud memory for DSH: report one activity turn per conversation round and expose memory_search / memory_read / memory_add tools against a LongMemory cloud endpoint.",
"type": "module",
"license": "MIT",

374
preview-card.mjs Normal file
View File

@ -0,0 +1,374 @@
// Renders the real 技能管理 tab to a static PNG so the layout can be reviewed
// before DSH is restarted. It reads the *live* skill sources through the built
// plugin (read-only) and draws them with the bundle's own render tree, then
// screenshots the result with headless Chrome.
import { execFileSync } from 'node:child_process'
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
const here = dirname(fileURLToPath(import.meta.url))
const source = readFileSync(join(here, 'client', 'index.js'), 'utf8')
// ── real data ───────────────────────────────────────────────────────────
const { SkillAdmin, skillsHoldingDir } = await import('./lib/skill-admin.js')
const { SkillGroupManager, detectSources } = await import('./lib/skill-groups.js')
const { SettingsStore } = await import('./lib/store.js')
const store = new SettingsStore({})
const admin = new SkillAdmin({
skillsRoot: () => join(store.path, '..', 'skills'),
holdingDir: () => skillsHoldingDir(),
syncStatePath: () => join(store.path, '..', 'cloud-memory-skills.json'),
syncRunning: () => false,
log: () => {},
})
const groups = new SkillGroupManager({ sources: () => detectSources(), admin, log: () => {} })
const overview = await groups.overview()
const statusBody = {
ok: true,
settings: {
enabled: true,
baseUrl: 'https://mem.qyhhh.top/api/longmemory',
baseUrlConfigured: true,
baseUrlOrigin: 'https://mem.qyhhh.top',
clientId: 'dsh-desktop',
requestTimeoutMs: 5000,
defaultK: 10,
summaryEnabled: true,
summaryMaxChars: 6000,
skillsSyncEnabled: true,
skillsDir: '',
},
tokens: {
activity: { configured: true, masked: 'cmt_9f2c1a…7d4e' },
memory: { configured: true, masked: 'cmt_3b81cc…22a9' },
summary: { configured: true, masked: 'cmt_71ad02…9f10' },
},
settingsPath: 'C:/Users/qyh15/.dsh/cloud-memory.json',
reporter: { attempted: 12, recorded: 11, duplicate: 1, failed: 0, skipped: 0, queued: 0, recent: [] },
lastCheck: {
at: Date.now(),
checks: [
{ id: 'network', label: '服务地址', state: 'ok', message: '服务可达(HTTP 200)' },
{ id: 'activity', label: '活动上报权限(activity:write)', state: 'ok', message: '鉴权通过' },
{ id: 'memory', label: '记忆读写权限(memory:write)', state: 'ok', message: '鉴权通过(3 个项目)' },
{ id: 'summary', label: '摘要权限(summary:write)', state: 'ok', message: '鉴权通过' },
],
},
capabilities: { version: '0.5.0', features: { skills: true, skillsMarketplace: false, mcpBridge: 'host-plugin' }, notes: [] },
skills: { running: false, downloaded: [], uploaded: [], updated: [], conflicts: [], skipped: 0 },
}
// ── minimal React + HTML serializer ─────────────────────────────────────
let hooks = []
let cursor = 0
let pendingEffects = []
let scheduled = false
const React = {
createElement(type, props, ...children) {
const flat = []
const push = (value) => {
if (Array.isArray(value)) value.forEach(push)
else if (value !== null && value !== undefined && value !== false && value !== true) flat.push(value)
}
push(children)
return { type, props: { ...(props ?? {}), children: flat.length === 1 ? flat[0] : flat }, children: flat }
},
useState(initial) {
const index = cursor++
if (!(index in hooks)) hooks[index] = typeof initial === 'function' ? initial() : initial
const setter = (next) => {
const value = typeof next === 'function' ? next(hooks[index]) : next
if (value !== hooks[index]) {
hooks[index] = value
scheduled = true
}
}
return [hooks[index], setter]
},
useEffect(fn) {
pendingEffects.push(fn)
},
useCallback(fn) {
return fn
},
Component: function Component(props) {
this.props = props
},
}
React.Component.prototype.setState = function setState(patch) {
this.state = { ...this.state, ...patch }
scheduled = true
}
function walk(node, visit) {
if (node === null || node === undefined || node === false || node === true) return
if (typeof node === 'string' || typeof node === 'number') return
if (Array.isArray(node)) {
node.forEach((child) => walk(child, visit))
return
}
if (typeof node.type === 'function') {
if (node.type.prototype && typeof node.type.prototype.render === 'function') {
const instance = new node.type(node.props)
instance.props = node.props
if (instance.state === undefined) instance.state = {}
instance.setState = function setState(patch) {
instance.state = { ...instance.state, ...patch }
scheduled = true
}
walk(instance.render(), visit)
return
}
walk(node.type({ ...node.props, children: node.children }), visit)
return
}
visit(node)
node.children.forEach((child) => walk(child, visit))
}
const UNITLESS = new Set(['fontWeight', 'opacity', 'lineHeight', 'flex', 'zIndex', 'flexGrow', 'flexShrink'])
function styleOf(style) {
const parts = []
for (const [key, value] of Object.entries(style ?? {})) {
if (value === null || value === undefined) continue
const name = key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)
parts.push(`${name}:${typeof value === 'number' && !UNITLESS.has(key) ? `${value}px` : String(value)}`)
}
return parts.join(';')
}
function escapeHtml(text) {
return String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
}
function toHtml(node) {
if (node === null || node === undefined || node === false || node === true) return ''
if (typeof node === 'string' || typeof node === 'number') return escapeHtml(node)
if (Array.isArray(node)) return node.map(toHtml).join('')
const { type, props, children } = node
if (typeof type === 'function') {
if (type.prototype && typeof type.prototype.render === 'function') {
const instance = new type(props)
instance.props = props
if (instance.state === undefined) instance.state = {}
return toHtml(instance.render())
}
return toHtml(type({ ...props, children }))
}
const attrs = []
const style = styleOf(props.style)
if (style !== '') attrs.push(`style="${style}"`)
if (props.id !== undefined) attrs.push(`id="${escapeHtml(props.id)}"`)
if (props.role !== undefined) attrs.push(`role="${escapeHtml(props.role)}"`)
if (props.title !== undefined) attrs.push(`title="${escapeHtml(props.title)}"`)
if (props.disabled === true) attrs.push('disabled')
if (props.type === 'checkbox') attrs.push(props.checked === true ? 'checked' : '')
for (const [key, value] of Object.entries(props)) {
if (key.startsWith('aria-')) attrs.push(`${key}="${escapeHtml(value)}"`)
}
if (type === 'input') {
attrs.push(`value="${escapeHtml(props.value === undefined ? '' : props.value)}"`)
attrs.push(`placeholder="${escapeHtml(props.placeholder === undefined ? '' : props.placeholder)}"`)
attrs.push(`type="${escapeHtml(props.type === undefined ? 'text' : props.type)}"`)
return `<input ${attrs.filter(Boolean).join(' ')}>`
}
return `<${type} ${attrs.filter(Boolean).join(' ')}>${children.map(toHtml).join('')}</${type}>`
}
// ── drive the real bundle ───────────────────────────────────────────────
const localStorageStub = {
getItem: (key) => (String(key).endsWith(':tab') ? 'skills' : null),
setItem: () => {},
}
let registered = null
globalThis.window = {
localStorage: localStorageStub,
addEventListener: () => {},
removeEventListener: () => {},
__ModuleLoader__: {
load(spec) {
const exportsObject = spec.factory(requireShim)
const captured = []
exportsObject.apply({
slots: {
inject: (_seat, fn) => fn(),
register: (_options, component) => {
captured.push(component)
return () => {}
},
},
})
registered = captured[0]
},
},
}
function requireShim(id) {
if (id === 'react') return React
throw new Error(`unexpected require: ${id}`)
}
async function fakeFetch(url) {
const path = String(url).split('?')[0]
let body = { ok: false }
if (path === '/cloud-memory/status') body = statusBody
else if (path === '/cloud-memory/skills/sources') body = { ok: true, ...overview }
else if (path.startsWith('/cloud-memory/skills/api')) body = { ok: true, skills: overview.sources[0]?.groups.flatMap((group) => group.skills) ?? [], plans: [] }
return { status: body.ok === false ? 404 : 200, json: async () => body, text: async () => JSON.stringify(body) }
}
function loadCard() {
registered = null
new Function('window', 'require', 'document', 'localStorage', 'fetch', 'console', 'setInterval', 'clearInterval', 'setTimeout', 'clearTimeout', 'AbortController', source)(
globalThis.window,
requireShim,
{ visibilityState: 'visible' },
localStorageStub,
fakeFetch,
{ warn: () => {}, log: () => {} },
() => 0,
() => {},
() => 0,
() => {},
AbortController,
)
return registered
}
const card = loadCard()
let treeEl = null
for (let pass = 0; pass < 6; pass += 1) {
cursor = 0
pendingEffects = []
scheduled = false
treeEl = React.createElement(card, null)
// Rendering is what runs the hooks (and therefore queues the effects).
void toHtml(treeEl)
const effects = pendingEffects
pendingEffects = []
for (const effect of effects) {
const cleanup = effect()
if (typeof cleanup === 'function') cleanup()
}
await new Promise((resolve) => setTimeout(resolve, 0))
if (!scheduled) break
}
// Click one control by its aria-label, so the preview can show an expanded
// category without a real browser event.
function clickLabel(root, prefix, occurrence) {
let index = 0
let clicked = false
walk(root, (node) => {
if (clicked) return
const props = node.props ?? {}
const label = props['aria-label']
if (typeof label === 'string' && label.startsWith(prefix)) {
if (index === occurrence) {
if (typeof props.onClick === 'function') props.onClick()
clicked = true
}
index += 1
}
})
return clicked
}
cursor = 0
pendingEffects = []
const expanded = clickLabel(treeEl, '展开或收起 未分类', 0)
if (expanded) {
for (let pass = 0; pass < 3; pass += 1) {
cursor = 0
pendingEffects = []
scheduled = false
void toHtml(treeEl)
const effects = pendingEffects
pendingEffects = []
for (const effect of effects) effect()
await new Promise((resolve) => setTimeout(resolve, 0))
if (!scheduled) break
}
} else {
console.warn('preview: could not find the 未分类 category to expand')
}
// The final render must start from the first hook slot again, otherwise the
// component would read fresh initial values instead of the loaded state.
cursor = 0
pendingEffects = []
const body = toHtml(treeEl)
// Second pass with every category collapsed: that is the default view a user
// sees first, and it puts the sections below the tree into the screenshot.
hooks = []
cursor = 0
const compactCard = loadCard()
let compactEl = null
for (let pass = 0; pass < 6; pass += 1) {
cursor = 0
pendingEffects = []
scheduled = false
compactEl = React.createElement(compactCard, null)
void toHtml(compactEl)
const effects = pendingEffects
pendingEffects = []
for (const effect of effects) {
const cleanup = effect()
if (typeof cleanup === 'function') cleanup()
}
await new Promise((resolve) => setTimeout(resolve, 0))
if (!scheduled) break
}
cursor = 0
pendingEffects = []
const compactBody = toHtml(compactEl)
if (body.includes('渲染失败')) {
console.error('the card rendered its error boundary instead of the tree')
process.exit(1)
}
const page = (theme) => `<!doctype html><html><head><meta charset="utf-8">
<style>
html,body{margin:0;padding:0}
body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei",system-ui,sans-serif;
background:${theme === 'dark' ? '#101216' : '#f3f5f9'};color:${theme === 'dark' ? '#e8eaee' : '#1a1d21'}}
.frame{width:600px;margin:0 auto;padding:18px 20px 24px}
.panel{border-radius:14px;padding:16px;
background:${theme === 'dark' ? '#191c22' : '#ffffff'};
box-shadow:0 10px 30px rgba(0,0,0,${theme === 'dark' ? '0.45' : '0.10'})}
button{font-family:inherit}
input{font-family:inherit;color:inherit}
</style></head><body><div class="frame"><div class="panel">${body}</div></div></body></html>`
const outDir = join(here, '_preview')
mkdirSync(outDir, { recursive: true })
const htmlPath = join(outDir, 'skill-tree.html')
writeFileSync(htmlPath, page('light'), 'utf8')
const darkPath = join(outDir, 'skill-tree-dark.html')
writeFileSync(darkPath, page('dark'), 'utf8')
const compactPath = join(outDir, 'skill-tree-compact.html')
writeFileSync(compactPath, page('light').replace(body, compactBody), 'utf8')
const chrome = 'C:/Program Files/Google/Chrome/Application/chrome.exe'
for (const [input, output] of [
[htmlPath, join(outDir, 'skill-tree.png')],
[darkPath, join(outDir, 'skill-tree-dark.png')],
[compactPath, join(outDir, 'skill-tree-compact.png')],
]) {
execFileSync(chrome, [
'--headless=new',
'--disable-gpu',
'--hide-scrollbars',
'--force-device-scale-factor=2',
'--window-size=640,2000',
`--screenshot=${output}`,
`file:///${input.replace(/\\/g, '/')}`,
], { stdio: 'ignore' })
console.log(`wrote ${output}`)
}
console.log('sources:', overview.sources.map((item) => `${item.label}=${item.total}`).join(', '))

View File

@ -301,6 +301,25 @@ export class CloudClient {
return this.request<TurnAck>('POST', '/activity/turn', payload, token)
}
/**
* Read-only reachability probe: any HTTP answer (even 401 or 404) proves the
* host is up. This is what separates "服务不可达" from "令牌无效" in the card,
* and it never sends a credential.
*/
async reach(): Promise<{ ok: boolean; status: number; message: string }> {
try {
const response = await fetch(`${this.options.baseUrl()}/status`, {
method: 'GET',
headers: { Accept: 'application/json' },
signal: AbortSignal.timeout(this.options.timeoutMs()),
})
return { ok: true, status: response.status, message: `服务可达(HTTP ${response.status})` }
} catch (error) {
const reason = error instanceof Error ? error.message : String(error)
return { ok: false, status: 0, message: `服务不可达:${reason}` }
}
}
/** Stage one turn summary as pending proposals (summary:write token). */
submitSummary(payload: SummaryPayload, token: string): Promise<CloudResult<SummaryAck>> {
return this.request<SummaryAck>('POST', '/activity/summary', payload, token)

82
src/brain-migration.ts Normal file
View File

@ -0,0 +1,82 @@
/**
* dsh-cloud-memory → dsh-brain naming migration (v1.1 §15.1, RENAME-01).
*
* This build still ships as `dsh-cloud-memory`; renaming the live package and
* its profile link is a deploy step that needs a full DSH restart, so it is not
* performed from inside a running session. What is implemented here is the
* *data* half, which is what RENAME-01 actually asserts:
*
* - copy the legacy sidecars to the `dsh-brain` names when the target is
* missing, never deleting or modifying the legacy files;
* - be idempotent: a second run is a no-op;
* - report what exists so the caller can drive the load-path switch safely.
*/
import { copyFile, mkdir, stat } from 'node:fs/promises'
import { dirname, join } from 'node:path'
import { dshHome } from './store.ts'
export const BRAIN = {
product: 'DSH Brain',
targetPackage: 'dsh-brain',
legacyPackage: 'dsh-cloud-memory',
} as const
/** Legacy sidecar → new-sidecar file name pairs. */
const PAIRS: [string, string][] = [
['cloud-memory.json', 'dsh-brain.json'],
['cloud-memory-skills.json', 'dsh-brain-skills.json'],
['cloud-memory-skill-groups.json', 'dsh-brain-skill-groups.json'],
]
async function exists(path: string): Promise<boolean> {
return stat(path).then((value) => value.isFile()).catch(() => false)
}
export interface BrainMigrationStatus {
home: string
product: string
targetPackage: string
legacyPackage: string
files: { legacy: string; target: string; legacyExists: boolean; targetExists: boolean; needsMigration: boolean }[]
migrationNeeded: boolean
/** The package rename itself is a deploy step, not done in-session. */
packageRename: 'pending-deploy'
}
export async function brainStatus(): Promise<BrainMigrationStatus> {
const home = dshHome()
const files = []
for (const [legacyName, targetName] of PAIRS) {
const legacy = join(home, legacyName)
const target = join(home, targetName)
const legacyExists = await exists(legacy)
const targetExists = await exists(target)
files.push({ legacy, target, legacyExists, targetExists, needsMigration: legacyExists && !targetExists })
}
return {
home,
product: BRAIN.product,
targetPackage: BRAIN.targetPackage,
legacyPackage: BRAIN.legacyPackage,
files,
migrationNeeded: files.some((file) => file.needsMigration),
packageRename: 'pending-deploy',
}
}
/** Copy legacy sidecars to the new names. Existing targets are never overwritten. */
export async function migrateLegacyFiles(): Promise<{ home: string; copied: string[]; skipped: string[]; product: string; targetPackage: string; legacyPackage: string }> {
const home = dshHome()
const copied: string[] = []
const skipped: string[] = []
for (const [legacyName, targetName] of PAIRS) {
const legacy = join(home, legacyName)
const target = join(home, targetName)
if (!(await exists(legacy))) continue
if (await exists(target)) { skipped.push(targetName); continue }
await mkdir(dirname(target), { recursive: true })
await copyFile(legacy, target)
copied.push(targetName)
}
return { home, copied, skipped, product: BRAIN.product, targetPackage: BRAIN.targetPackage, legacyPackage: BRAIN.legacyPackage }
}

364
src/clients.ts Normal file
View File

@ -0,0 +1,364 @@
/**
* Cross-software / workspace skill inventory (v1.1 §15).
*
* One adapter per client. It only reads directories the client itself publishes
* (user-level skill roots and, when a workspace is known, that workspace's own
* client folder). Nothing here writes another client's directory: DSH is the
* only writable adapter in this build, and every other source is reported as
* read-only instead of pretending a toggle works.
*
* Workspaces come from two bounded sources:
* - the DSH workspace-group registry the host already keeps (member paths);
* - directories the user explicitly adds here (persisted metadata only).
* No full-disk scan, no chat history, no credential read.
*/
import { existsSync } from 'node:fs'
import { readFile, readdir, stat } from 'node:fs/promises'
import { homedir } from 'node:os'
import { join, resolve, sep } from 'node:path'
import { dshHome } from './store.ts'
import { parseSkillFrontmatter } from './skill-sync.ts'
import { SkillAdmin } from './skill-admin.ts'
export type SoftwareId = 'dsh' | 'agents' | 'codex' | 'workbuddy' | 'claude' | 'opencode'
export interface SoftwareAdapterInfo {
id: SoftwareId
label: string
installed: boolean
configRoot: string
globalSkillsRoot: string
writable: boolean
workspaceSupported: boolean
notes: string[]
}
export interface WorkspaceRecord {
id: string
name: string
path: string
source: 'dsh-registry' | 'manual'
category?: string
}
export interface ClientInventoryItem {
folder: string
name: string
description: string
path: string
softwareId: SoftwareId
scope: 'global' | 'workspace'
workspaceId?: string
writable: boolean
enabled?: boolean
}
export interface ClientCapabilityView {
id: SoftwareId
label: string
readGlobal: boolean
writeGlobal: boolean
workspaceRead: boolean
workspaceWrite: boolean
hotReload: boolean
verify: boolean
notes: string[]
}
interface Roots {
configRoot: string
globalSkillsRoot: string
/** Workspace-relative skill directories, first existing wins. */
workspaceSubdirs: string[]
}
/** Manual workspace additions live in the plugin's own metadata file. */
export function manualWorkspacesPath(): string {
return join(dshHome(), 'cloud-memory-workspaces.json')
}
interface ManualFile {
version: 1
items: { softwareId: SoftwareId; id: string; name: string; path: string }[]
}
function rootsOf(home: string): Record<SoftwareId, Roots> {
return {
dsh: { configRoot: dshHome(), globalSkillsRoot: join(dshHome(), 'skills'), workspaceSubdirs: [join('.dsh', 'skills')] },
agents: { configRoot: join(home, '.agents'), globalSkillsRoot: join(home, '.agents', 'skills'), workspaceSubdirs: [] },
codex: { configRoot: join(home, '.codex'), globalSkillsRoot: join(home, '.codex', 'skills'), workspaceSubdirs: [join('.codex', 'skills')] },
workbuddy: { configRoot: join(home, '.workbuddy'), globalSkillsRoot: join(home, '.workbuddy', 'skills'), workspaceSubdirs: [] },
claude: { configRoot: join(home, '.claude'), globalSkillsRoot: join(home, '.claude', 'skills'), workspaceSubdirs: [join('.claude', 'skills')] },
opencode: { configRoot: join(home, '.config', 'opencode'), globalSkillsRoot: join(home, '.config', 'opencode', 'skills'), workspaceSubdirs: [join('.opencode', 'skills'), join('.opencode', 'skill')] },
}
}
const LABELS: Record<SoftwareId, string> = {
dsh: 'DSH',
agents: '公共 Agent',
codex: 'Codex',
workbuddy: 'WorkBuddy',
claude: 'Claude Code',
opencode: 'OpenCode',
}
const SOFTWARE: SoftwareId[] = ['dsh', 'agents', 'codex', 'workbuddy', 'claude', 'opencode']
export interface ClientRegistryDeps {
home?: () => string
manualPath?: () => string
dshRegistryPath?: () => string
dshManualPath?: () => string
}
export class ClientRegistry {
private readonly deps: ClientRegistryDeps
constructor(deps: ClientRegistryDeps = {}) {
this.deps = deps
}
private home(): string {
return this.deps.home?.() ?? homedir()
}
private roots(): Record<SoftwareId, Roots> {
return rootsOf(this.home())
}
adapters(): SoftwareAdapterInfo[] {
const roots = this.roots()
return SOFTWARE.map((id) => {
const root = roots[id]
const installed = existsSync(root.configRoot)
const notes: string[] = []
if (!installed) notes.push('未检测到安装目录')
const writable = id === 'dsh'
if (!writable) notes.push('本卡只读,不修改该软件的技能目录')
return {
id,
label: LABELS[id],
installed,
configRoot: root.configRoot,
globalSkillsRoot: root.globalSkillsRoot,
writable,
workspaceSupported: root.workspaceSubdirs.length > 0,
notes,
}
})
}
capabilities(): ClientCapabilityView[] {
return this.adapters().map((adapter) => ({
id: adapter.id,
label: adapter.label,
readGlobal: true,
writeGlobal: adapter.writable,
workspaceRead: adapter.workspaceSupported,
// Workspace-level writes are implemented for DSH only; every other client
// stays read-only so nothing is written into a format we cannot verify.
workspaceWrite: adapter.id === 'dsh' && adapter.workspaceSupported,
hotReload: adapter.id === 'dsh',
verify: true,
notes: adapter.notes,
}))
}
/**
* A workspace-scoped SkillAdmin for the DSH adapter. The skills root is the
* workspace's own `.dsh/skills`; parked skills go to a per-workspace holding
* area so one project can never unpark another's skill. Only DSH is allowed.
*/
async workspaceSkillAdmin(softwareInput: unknown, workspaceIdInput: unknown): Promise<{ admin: SkillAdmin; workspace: WorkspaceRecord }> {
const software = SOFTWARE.includes(softwareInput as SoftwareId) ? softwareInput as SoftwareId : undefined
if (software !== 'dsh') throw new Error('unsupported_workspace_write')
const workspaceId = typeof workspaceIdInput === 'string' ? workspaceIdInput : ''
const workspace = (await this.workspaces('dsh')).find((item) => item.id === workspaceId)
if (workspace === undefined) throw new Error('unknown_workspace')
const skillsRoot = resolve(workspace.path, '.dsh', 'skills')
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({
skillsRoot: () => skillsRoot,
holdingDir: () => holdingDir,
syncStatePath: () => statePath,
syncRunning: () => false,
log: () => {},
})
return { admin, workspace }
}
private async readManual(): Promise<ManualFile> {
const path = this.deps.manualPath?.() ?? manualWorkspacesPath()
try {
const parsed: unknown = JSON.parse(await readFile(path, 'utf8'))
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
const raw = parsed as { items?: unknown }
const items = Array.isArray(raw.items)
? raw.items.filter((item): item is ManualFile['items'][number] => (
item !== null && typeof item === 'object'
&& typeof (item as ManualFile['items'][number]).softwareId === 'string'
&& typeof (item as ManualFile['items'][number]).path === 'string'
))
: []
return { version: 1, items }
}
} catch {
// Missing sidecar: no manual workspaces yet.
}
return { version: 1, items: [] }
}
private async writeManual(file: ManualFile): Promise<void> {
const path = this.deps.manualPath?.() ?? manualWorkspacesPath()
const { mkdir, writeFile } = await import('node:fs/promises')
await mkdir(join(path, '..'), { recursive: true })
await writeFile(path, `${JSON.stringify(file, null, 2)}\n`, 'utf8')
}
/** DSH workspaces come from the host's own workspace-group registry. */
private async dshRegistryWorkspaces(): Promise<WorkspaceRecord[]> {
const path = this.deps.dshRegistryPath?.() ?? join(dshHome(), 'workspace-groups.folders.json')
const categoriesPath = this.deps.dshManualPath?.() ?? join(dshHome(), 'workspace-groups.manual.json')
let categories = new Map<string, string>()
try {
const raw = JSON.parse(await readFile(categoriesPath, 'utf8')) as { assignments?: Record<string, string> }
if (raw.assignments !== null && typeof raw.assignments === 'object') {
categories = new Map(Object.entries(raw.assignments))
}
} catch {
// No category mapping: names fall back to the folder name.
}
try {
const raw = JSON.parse(await readFile(path, 'utf8')) as { workspaces?: Record<string, { members?: { path?: unknown; workspaceId?: unknown }[] }> }
const out: WorkspaceRecord[] = []
const seen = new Set<string>()
for (const [groupId, group] of Object.entries(raw.workspaces ?? {})) {
for (const member of group.members ?? []) {
if (typeof member.path !== 'string' || member.path === '' || seen.has(member.path)) continue
seen.add(member.path)
const id = typeof member.workspaceId === 'string' && member.workspaceId !== '' ? member.workspaceId : groupId
const parts = member.path.split(/[\\/]/).filter((part) => part !== '')
const category = categories.get(id)
out.push({ id, name: parts[parts.length - 1] ?? member.path, path: member.path, source: 'dsh-registry', ...(category === undefined ? {} : { category }) })
}
}
return out
} catch {
return []
}
}
async workspaces(software: SoftwareId): Promise<WorkspaceRecord[]> {
const manual = (await this.readManual()).items.filter((item) => item.softwareId === software)
const fromManual: WorkspaceRecord[] = manual.map((item) => ({ id: item.id, name: item.name, path: item.path, source: 'manual' }))
if (software === 'dsh') {
const registry = await this.dshRegistryWorkspaces()
const byPath = new Set(registry.map((item) => item.path))
return [...registry, ...fromManual.filter((item) => !byPath.has(item.path))]
}
return fromManual
}
async addWorkspace(softwareInput: unknown, pathInput: unknown, nameInput: unknown): Promise<WorkspaceRecord> {
const software = SOFTWARE.includes(softwareInput as SoftwareId) ? softwareInput as SoftwareId : undefined
if (software === undefined) throw new Error('invalid_software')
const path = typeof pathInput === 'string' ? pathInput.trim() : ''
if (path === '' || !existsSync(path)) throw new Error('invalid_path')
const stats = await stat(path).catch(() => undefined)
if (stats === undefined || !stats.isDirectory()) throw new Error('invalid_path')
const resolved = resolve(path)
const file = await this.readManual()
if (file.items.some((item) => item.softwareId === software && resolve(item.path) === resolved)) throw new Error('duplicate')
const name = typeof nameInput === 'string' && nameInput.trim() !== '' ? nameInput.trim() : resolved.split(sep).filter((part) => part !== '').pop() ?? resolved
const record: WorkspaceRecord = { id: `ws_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`, name, path: resolved, source: 'manual' }
file.items.push({ softwareId: software, id: record.id, name: record.name, path: record.path })
await this.writeManual(file)
return record
}
async removeWorkspace(softwareInput: unknown, idInput: unknown): Promise<{ removed: string }> {
const software = SOFTWARE.includes(softwareInput as SoftwareId) ? softwareInput as SoftwareId : undefined
const id = typeof idInput === 'string' ? idInput : ''
const file = await this.readManual()
const before = file.items.length
file.items = file.items.filter((item) => !(item.softwareId === software && item.id === id))
if (file.items.length === before) throw new Error('not_found')
await this.writeManual(file)
return { removed: id }
}
private async inventoryOf(dir: string, software: SoftwareId, scope: 'global' | 'workspace', workspaceId?: string): Promise<ClientInventoryItem[]> {
const out: ClientInventoryItem[] = []
// DSH global and DSH workspace roots are writable by this build; every
// other client (and every non-DSH workspace) is read-only.
const writable = software === 'dsh'
for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
if (!entry.isDirectory() || entry.name.startsWith('.')) continue
const skillDir = join(dir, entry.name)
const markdown = await readFile(join(skillDir, 'SKILL.md'), 'utf8').catch(() => undefined)
if (markdown === undefined) continue
const frontmatter = parseSkillFrontmatter(markdown)
out.push({
folder: entry.name,
name: typeof frontmatter.name === 'string' && frontmatter.name !== '' ? frontmatter.name : entry.name,
description: String(frontmatter.description ?? '').slice(0, 300),
path: skillDir,
softwareId: software,
scope,
...(workspaceId === undefined ? {} : { workspaceId }),
writable,
})
}
out.sort((a, b) => (a.folder < b.folder ? -1 : 1))
return out
}
async inventory(softwareInput: unknown, scopeInput: unknown, workspaceIdInput?: unknown): Promise<{ softwareId: SoftwareId; scope: 'global' | 'workspace'; workspace?: WorkspaceRecord; items: ClientInventoryItem[]; note: string }> {
const software = SOFTWARE.includes(softwareInput as SoftwareId) ? softwareInput as SoftwareId : undefined
if (software === undefined) throw new Error('invalid_software')
const scope = scopeInput === 'workspace' ? 'workspace' : 'global'
const roots = this.roots()[software]
if (scope === 'global') {
return { softwareId: software, scope, items: await this.inventoryOf(roots.globalSkillsRoot, software, 'global'), note: software === 'dsh' ? 'DSH 全局技能目录。' : '该软件的用户级技能目录,本卡只读。' }
}
const workspaceId = typeof workspaceIdInput === 'string' ? workspaceIdInput : ''
const workspace = (await this.workspaces(software)).find((item) => item.id === workspaceId)
if (workspace === undefined) throw new Error('unknown_workspace')
// DSH workspace skills are enumerated through a workspace-scoped SkillAdmin
// so the list, the enabled flag and the inventory agree with the write path.
if (software === 'dsh') {
const { admin } = await this.workspaceSkillAdmin('dsh', workspace.id)
const listed = await admin.list()
const items: ClientInventoryItem[] = listed.skills.map((skill) => ({
folder: skill.folder,
name: skill.name,
description: skill.description,
path: join(skill.enabled ? listed.root : listed.holding, skill.folder),
softwareId: 'dsh',
scope: 'workspace',
workspaceId: workspace.id,
writable: true,
enabled: skill.enabled,
}))
return { softwareId: 'dsh', scope, workspace, items, note: `DSH 工作区技能目录:${join(workspace.path, '.dsh', 'skills')}` }
}
for (const sub of roots.workspaceSubdirs) {
const dir = resolve(workspace.path, sub)
if (existsSync(dir)) {
return { softwareId: software, scope, workspace, items: await this.inventoryOf(dir, software, 'workspace', workspace.id), note: `工作区专属目录:${dir}` }
}
}
return { softwareId: software, scope, workspace, items: [], note: `该工作区没有 ${LABELS[software]} 的专属技能目录;不会写通用配置替代。` }
}
async overview(): Promise<{ adapters: SoftwareAdapterInfo[]; capabilities: ClientCapabilityView[]; workspaces: Record<string, WorkspaceRecord[]>; brain: { product: string; targetPackage: string; legacyPackage: string } }> {
const workspaces: Record<string, WorkspaceRecord[]> = {}
for (const id of SOFTWARE) workspaces[id] = await this.workspaces(id)
return {
adapters: this.adapters(),
capabilities: this.capabilities(),
workspaces,
brain: { product: 'DSH Brain', targetPackage: 'dsh-brain', legacyPackage: 'dsh-cloud-memory' },
}
}
}

View File

@ -7,7 +7,7 @@
/** Defaults written into cordis.patch.yml; also the fallback for missing keys. */
export const DEFAULT_SETTINGS: Settings = {
enabled: true,
baseUrl: 'https://mem.qyhhh.top/api/longmemory',
baseUrl: 'https://your-memory-host/api/longmemory',
clientId: 'dsh-desktop',
requestTimeoutMs: 5000,
defaultK: 10,
@ -68,6 +68,33 @@ export function normalizeBaseUrl(value: unknown): string | undefined {
}
}
/**
* A packaged default that was never replaced by a real service.
*
* `cordis.patch.yml` ships `https://your-memory-host/...` so a fresh profile
* boots without touching a production endpoint. Such an address must be shown
* as "未配置服务" — never as a healthy connection.
*/
export function isPlaceholderBaseUrl(value: string): boolean {
const normalized = normalizeBaseUrl(value)
if (normalized === undefined) return true
try {
const host = new URL(normalized).hostname.toLowerCase()
return host === 'your-memory-host' || host === 'example.com'
} catch {
return true
}
}
/** Service origin of one base URL, or '' when it cannot be parsed. */
export function originOf(value: string): string {
try {
return new URL(value).origin
} catch {
return ''
}
}
/** Clamp a numeric config value into an integer range, else undefined. */
function boundedInt(value: unknown, min: number, max: number): number | undefined {
if (typeof value !== 'number' || !Number.isFinite(value)) return undefined

View File

@ -17,6 +17,10 @@ import { join } from 'node:path'
import { SettingsStore, dshHome } from './store.ts'
import { SkillSync } from './skill-sync.ts'
import { SkillAdmin, skillsHoldingDir } from './skill-admin.ts'
import { SkillGroupManager, detectSources } from './skill-groups.ts'
import { ClaudePluginMarketplaceProvider, MarketService } from './market.ts'
import { SkillUpdater } from './skill-update.ts'
import { ClientRegistry } from './clients.ts'
import { createMemoryTools, createSkillTools } from './tools.ts'
/** Package name; also the client bundle id. */
@ -26,7 +30,7 @@ export const name = 'dsh-cloud-memory'
export const inject = ['webServer']
/** Version reported by the status card. */
const VERSION = '0.4.1'
const VERSION = '0.7.0'
/** How often the skill directory is reconciled with the cloud center. */
const SKILL_SYNC_INTERVAL_MS = 15 * 60_000
@ -74,6 +78,38 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
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) {
@ -122,7 +158,7 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
if (webServer === undefined) {
logger.warn('webServer service unavailable; the configuration page stays disabled')
} else {
const routes = createRoutes({ version: VERSION, store, reporter, client: () => client, skills: () => skillSync.stats(), admin: skillAdmin })
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}`)
}

306
src/market.ts Normal file
View File

@ -0,0 +1,306 @@
/**
* Skill market providers (P3).
*
* A provider answers `search` / `getDetail` / `resolveArtifact` for ONE
* configured, verified source. The browser half never passes a repository URL:
* it only names a provider id and an entry id, so no request can make the host
* fetch an arbitrary address or clone an arbitrary repository.
*
* First provider: the Claude Code plugin marketplace manifest that lives at
* `.claude-plugin/marketplace.json` in a public GitHub repository. That format
* lists plugins, each with a description and the relative folders of the skills
* it ships. Installing an entry reuses the same staged plan/commit pipeline as
* a manual git install, pinned to the commit resolved here.
*/
import { parseSkillFrontmatter } from './skill-sync.ts'
/** One provider as the card lists it (no credentials, no local paths). */
export interface MarketProviderInfo {
id: string
label: string
description: string
/** `owner/repo` the manifest is read from. */
source: string
homepage: string
}
/** One normalized marketplace entry. */
export interface MarketEntry {
id: string
providerId: string
name: string
description: string
version?: string
author?: string
/** Skill folder names (basename of each skill path). */
skills: string[]
/** Relative paths as written in the manifest, e.g. `./skills/xlsx`. */
skillPaths: string[]
sourceRepo: string
sourceUrl: string
}
/** Detail adds per-skill metadata read from each SKILL.md (best effort). */
export interface MarketDetail extends MarketEntry {
skillDetails: { folder: string; path: string; name?: string; description?: string; ok: boolean }[]
fetchedAt: number
}
/** What an install plan needs to clone a pinned artifact. */
export interface MarketArtifact {
repoUrl: string
/** A ref git can fetch (branch, tag or commit SHA). */
ref: string
/** Resolved commit SHA when the host could look it up. */
commit?: string
version?: string
folders: string[]
}
export interface MarketProvider {
info(): MarketProviderInfo
search(query: string, cursor: number): Promise<{ entries: MarketEntry[]; nextCursor?: number }>
getDetail(entryId: string): Promise<MarketDetail>
resolveArtifact(entryId: string, version?: string): Promise<MarketArtifact>
}
/** Typed failure so routes can map it to a status code. */
export class MarketError extends Error {
constructor(public readonly code: string, message: string) {
super(message)
this.name = 'MarketError'
}
}
/** Row shape of `.claude-plugin/marketplace.json`. */
interface MarketplaceManifest {
name?: string
owner?: { name?: string }
metadata?: { version?: string; description?: string }
plugins?: {
name?: string
description?: string
source?: string
skills?: string[]
}[]
}
/** Normalize a manifest skill path to a folder name (its basename). */
function folderOf(skillPath: string): string {
const trimmed = skillPath.replace(/^\.\//, '').replace(/\/+$/, '')
const parts = trimmed.split('/')
return parts[parts.length - 1] ?? trimmed
}
/** Small TTL cache so one search + one detail does not refetch the manifest. */
interface CacheEntry {
at: number
value: unknown
}
/** Provider over a Claude Code plugin marketplace manifest on GitHub. */
export class ClaudePluginMarketplaceProvider implements MarketProvider {
private readonly cache = new Map<string, CacheEntry>()
private readonly fetchImpl: typeof fetch
constructor(
private readonly options: {
id: string
label: string
description: string
repo: string
ref?: string
homepage?: string
timeoutMs?: number
fetchImpl?: typeof fetch
},
) {
this.fetchImpl = options.fetchImpl ?? fetch
}
info(): MarketProviderInfo {
return {
id: this.options.id,
label: this.options.label,
description: this.options.description,
source: this.options.repo,
homepage: this.options.homepage ?? `https://github.com/${this.options.repo}`,
}
}
private ref(): string {
return this.options.ref ?? 'main'
}
private timeoutMs(): number {
return this.options.timeoutMs ?? 8000
}
private rawUrl(path: string): string {
const clean = path.replace(/^\.\//, '')
return `https://raw.githubusercontent.com/${this.options.repo}/${encodeURIComponent(this.ref())}/${clean}`
}
private async fetchText(url: string): Promise<string> {
let response: Response
try {
response = await this.fetchImpl(url, {
headers: { accept: 'application/json, text/plain, */*', 'user-agent': 'dsh-cloud-memory-market' },
signal: AbortSignal.timeout(this.timeoutMs()),
})
} catch (error) {
throw new MarketError('unreachable', `市场来源不可达:${error instanceof Error ? error.message : String(error)}`)
}
if (!response.ok) {
throw new MarketError('http_' + String(response.status), `市场来源返回 HTTP ${response.status}`)
}
return response.text()
}
private async fetchJson<T>(url: string, ttlMs = 60_000): Promise<T> {
const hit = this.cache.get(url)
if (hit !== undefined && Date.now() - hit.at < ttlMs) return hit.value as T
const text = await this.fetchText(url)
let parsed: unknown
try {
parsed = JSON.parse(text)
} catch {
throw new MarketError('invalid_manifest', '市场清单不是合法 JSON。')
}
this.cache.set(url, { at: Date.now(), value: parsed })
return parsed as T
}
private async manifest(): Promise<MarketplaceManifest> {
const parsed = await this.fetchJson<unknown>(this.rawUrl('.claude-plugin/marketplace.json'))
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new MarketError('invalid_manifest', '市场清单结构不正确。')
}
return parsed as MarketplaceManifest
}
private entriesOf(manifest: MarketplaceManifest): MarketEntry[] {
const list = Array.isArray(manifest.plugins) ? manifest.plugins : []
const version = manifest.metadata?.version
const author = manifest.owner?.name
const entries: MarketEntry[] = []
for (const plugin of list) {
const name = typeof plugin.name === 'string' ? plugin.name : ''
if (name === '') continue
const paths = Array.isArray(plugin.skills) ? plugin.skills.filter((p): p is string => typeof p === 'string') : []
const entry: MarketEntry = {
id: name,
providerId: this.options.id,
name,
description: typeof plugin.description === 'string' ? plugin.description : '',
skills: paths.map(folderOf),
skillPaths: paths,
sourceRepo: this.options.repo,
sourceUrl: `https://github.com/${this.options.repo}`,
}
if (typeof version === 'string') entry.version = version
if (typeof author === 'string') entry.author = author
entries.push(entry)
}
return entries
}
async search(query: string, cursor: number): Promise<{ entries: MarketEntry[]; nextCursor?: number }> {
const entries = this.entriesOf(await this.manifest())
const needle = query.trim().toLowerCase()
const filtered = needle === ''
? entries
: entries.filter((entry) =>
`${entry.name}\n${entry.description}\n${entry.skills.join(' ')}`.toLowerCase().includes(needle),
)
const pageSize = 10
const start = Number.isFinite(cursor) && cursor > 0 ? Math.floor(cursor) : 0
const page = filtered.slice(start, start + pageSize)
const next = start + pageSize < filtered.length ? start + pageSize : undefined
return next === undefined ? { entries: page } : { entries: page, nextCursor: next }
}
private findEntry(manifest: MarketplaceManifest, entryId: string): MarketEntry {
const entry = this.entriesOf(manifest).find((item) => item.id === entryId)
if (entry === undefined) throw new MarketError('not_found', `市场里没有条目:${entryId}`)
return entry
}
async getDetail(entryId: string): Promise<MarketDetail> {
const entry = this.findEntry(await this.manifest(), entryId)
const skillDetails: MarketDetail['skillDetails'] = []
// Bound the fan-out: a manifest can list dozens of skills.
for (const path of entry.skillPaths.slice(0, 24)) {
const folder = folderOf(path)
try {
const markdown = await this.fetchText(this.rawUrl(`${path.replace(/^\.\//, '')}/SKILL.md`))
const frontmatter = parseSkillFrontmatter(markdown)
const detail: MarketDetail['skillDetails'][number] = { folder, path, ok: true }
if (typeof frontmatter.name === 'string') detail.name = frontmatter.name
if (typeof frontmatter.description === 'string') detail.description = frontmatter.description.slice(0, 300)
skillDetails.push(detail)
} catch {
skillDetails.push({ folder, path, ok: false })
}
}
return { ...entry, skillDetails, fetchedAt: Date.now() }
}
async resolveArtifact(entryId: string, _version?: string): Promise<MarketArtifact> {
const entry = this.findEntry(await this.manifest(), entryId)
let commit: string | undefined
try {
const payload = await this.fetchJson<{ sha?: unknown }>(
`https://api.github.com/repos/${this.options.repo}/commits/${encodeURIComponent(this.ref())}`,
30_000,
)
if (typeof payload.sha === 'string' && /^[0-9a-f]{7,40}$/i.test(payload.sha)) commit = payload.sha
} catch {
// Rate-limited or offline: fall back to the branch ref; git checkout pins
// the actual commit at clone time and the install records it.
}
const artifact: MarketArtifact = {
repoUrl: `https://github.com/${this.options.repo}.git`,
ref: commit ?? this.ref(),
folders: entry.skills,
}
if (commit !== undefined) artifact.commit = commit
if (entry.version !== undefined) artifact.version = entry.version
return artifact
}
}
/** A small registry of providers; the browser can only ask for one by id. */
export class MarketService {
private readonly byId = new Map<string, MarketProvider>()
constructor(providers: MarketProvider[]) {
for (const provider of providers) this.byId.set(provider.info().id, provider)
}
list(): MarketProviderInfo[] {
return [...this.byId.values()].map((provider) => provider.info())
}
has(providerId: string): boolean {
return this.byId.has(providerId)
}
get(providerId: string): MarketProvider {
const provider = this.byId.get(providerId)
if (provider === undefined) throw new MarketError('unknown_provider', `未知的市场来源:${providerId}`)
return provider
}
search(providerId: string, query: string, cursor: number): ReturnType<MarketProvider['search']> {
return this.get(providerId).search(query, cursor)
}
detail(providerId: string, entryId: string): ReturnType<MarketProvider['getDetail']> {
return this.get(providerId).getDetail(entryId)
}
resolve(providerId: string, entryId: string, version?: string): ReturnType<MarketProvider['resolveArtifact']> {
return this.get(providerId).resolveArtifact(entryId, version)
}
}

View File

@ -23,7 +23,7 @@ import { LongMemoryProvider } from './driver.ts'
export { LongMemoryProvider, descriptor }
/** Keep in sync with the package version (asserted by the verify script). */
const PROVIDER_VERSION = '0.4.1'
const PROVIDER_VERSION = '0.7.0'
export const definition = defineMemorySpaceProviderDefinition({
manifest: {

View File

@ -120,7 +120,7 @@ code { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size
<div class="grid">
<div>
<label for="baseUrl">服务基址</label>
<input id="baseUrl" type="text" spellcheck="false" placeholder="https://mem.qyhhh.top/api/longmemory" />
<input id="baseUrl" type="text" spellcheck="false" placeholder="https://your-memory-host/api/longmemory" />
<div class="hint">不带结尾斜杠,路径为 /api/longmemory。</div>
</div>
<div>

View File

@ -2,16 +2,22 @@
* HTTP surface served by the host web server.
*
* All routes live under `/cloud-memory`:
* - `GET /cloud-memory` configuration page (HTML)
* - `GET /cloud-memory/status` settings + reporter counters (JSON)
* - `PUT /cloud-memory/config` apply a settings patch (JSON)
* - `POST /cloud-memory/login` password sign-in, mints both tokens (JSON)
* - `POST /cloud-memory/test` validate both tokens (JSON)
* - `POST /cloud-memory/flush` retry the queued reports (JSON)
* - `GET /cloud-memory` configuration page (HTML)
* - `GET /cloud-memory/status` settings + reporter counters + capabilities
* - `GET /cloud-memory/capabilities` what this build can and cannot do
* - `PUT /cloud-memory/config` apply a settings patch
* - `POST /cloud-memory/login` password sign-in, mints the tokens
* - `POST /cloud-memory/test` read-only checks, per credential
* - `POST /cloud-memory/flush` retry the queued reports
* - `GET /cloud-memory/skills/api` skill inventory + pending plans
* - `POST /cloud-memory/skills/*` detail / toggle / install plan / commit / uninstall
*
* Every JSON route is same-origin only: the tokens are read from the local file
* and never echoed back, but a cross-site `PUT` could still be used to redirect
* reports to an attacker's base URL, so the origin check stays on.
*
* Skill writes follow a plan → commit contract: a destructive operation is
* never reachable in one request, and a client-supplied path is never trusted.
*/
import type { IncomingMessage, ServerResponse } from 'node:http'
import type { CloudClient } from './api.ts'
@ -20,20 +26,33 @@ import type { SettingsView, SettingsStore, TokenView } from './store.ts'
import type { Reporter } from './reporter.ts'
import { renderConfigPage } from './page.ts'
import type { CloudMemoryWebRoute } from './context-types.ts'
import type { SkillSyncStats } from './skill-sync.ts'
import type { SkillSync, SkillSyncStats } from './skill-sync.ts'
import { SkillAdminError } from './skill-admin.ts'
import type { SkillAdmin } from './skill-admin.ts'
import { MarketError } from './market.ts'
import type { MarketService } from './market.ts'
import type { SkillUpdater } from './skill-update.ts'
import type { ClientRegistry } from './clients.ts'
import { brainStatus, migrateLegacyFiles } from './brain-migration.ts'
import { SkillGroupError } from './skill-groups.ts'
import type { SkillGroupManager } from './skill-groups.ts'
import { renderSkillsPage } from './skill-page.ts'
import { randomUUID } from 'node:crypto'
/** Route constants — kept in one place so the client half can reuse them. */
export const ROUTES = {
page: '/cloud-memory',
status: '/cloud-memory/status',
capabilities: '/cloud-memory/capabilities',
config: '/cloud-memory/config',
login: '/cloud-memory/login',
test: '/cloud-memory/test',
flush: '/cloud-memory/flush',
skills: '/cloud-memory/skills',
market: '/cloud-memory/market',
sync: '/cloud-memory/sync',
clients: '/cloud-memory/clients',
migrate: '/cloud-memory/migrate',
} as const
/** Largest request body we accept (a settings patch is tiny). */
@ -47,8 +66,81 @@ export interface RouteDeps {
client: () => CloudClient
/** Latest skill-sync stats, when the engine is wired in. */
skills?: () => SkillSyncStats
/** Local skill management (list / toggle / trash / install), when wired in. */
/** Local skill management (list / toggle / install / uninstall), when wired in. */
admin?: SkillAdmin
/** Multi-source skill tree (sources, categories, per-group switches). */
groups?: SkillGroupManager
/** Skill market providers (search / detail / resolve artifact). */
market?: MarketService
/** The sync engine itself, for conflict details and interactive resolution. */
sync?: SkillSync
/** Update / rollback over a recorded git or market source. */
updates?: SkillUpdater
/** Cross-software / workspace inventory (v1.1 §15). */
clients?: ClientRegistry
}
/** One feature flag the card reads before it renders a control. */
export interface CapabilityReport {
version: string
features: {
connection: boolean
identitySwitch: boolean
skills: boolean
skillInstallPlans: boolean
skillUninstallPlan: boolean
skillsSync: boolean
skillsMarketplace: boolean
/** Market search/detail/install is wired to a real provider. */
marketProviders?: number
/** Update/rollback is available for skills with a source record. */
skillUpdate?: boolean
/** Interactive sync conflict resolution is available. */
syncResolve?: boolean
/** Cross-software and workspace skill inventory is available. */
multiClient?: boolean
/** dsh-brain data migration status (package rename stays a deploy step). */
brainMigration?: 'ready' | 'pending-deploy'
mcpBridge: 'host-plugin' | 'unavailable'
}
notes: string[]
}
/** What this build actually implements, stated per feature. */
function capabilities(deps: RouteDeps): CapabilityReport {
const marketProviders = deps.market?.list().length ?? 0
return {
version: deps.version,
features: {
connection: true,
identitySwitch: true,
skills: deps.admin !== undefined,
skillInstallPlans: deps.admin !== undefined,
skillUninstallPlan: deps.admin !== undefined,
skillsSync: deps.skills !== undefined,
skillsMarketplace: deps.market !== undefined,
marketProviders,
skillUpdate: deps.updates !== undefined,
syncResolve: deps.sync !== undefined,
multiClient: deps.clients !== undefined,
brainMigration: 'pending-deploy',
// The MCP bridge is provided by the host `dsh-mcp-connector` plugin over
// the same origin; the browser half probes it at runtime.
mcpBridge: 'host-plugin',
},
notes: [
...(deps.market === undefined
? ['技能市场未启用:没有配置市场来源。']
: [`技能市场已接入 ${marketProviders} 个来源;安装走暂存计划并固定提交。`]),
...(deps.updates === undefined
? ['技能更新/回退未启用。']
: ['更新/回退仅对带来源记录(.skill-source.json)的技能生效,更新前自动备份。']),
...(deps.sync === undefined ? [] : ['同步冲突可在技能页签逐项“保留本地 / 采用云端 / 手动合并”。']),
...(deps.clients === undefined ? [] : ['跨软件与工作区技能清单为只读(DSH 之外不写目录);dsh-brain 数据迁移已就绪,实际改名需部署重启。']),
'MCP 管理由宿主 dsh-mcp-connector 插件提供,本卡通过其公开接口读写,不另建凭据库。',
'MCP 工具可见性与会话级激活分属两层:本卡展示连接与工具缓存,会话级“选择精确工具后激活”由宿主 session-tools 负责,本卡不伪造激活。',
],
}
}
/** Collect a request body as UTF-8 text. */
@ -95,17 +187,75 @@ function fail(res: ServerResponse, status: number, message: string, asHtml = fal
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.
*/
async function jsonBody(req: IncomingMessage, res: ServerResponse): Promise<Record<string, unknown> | undefined> {
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: unknown
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 as Record<string, unknown>
}
/** One credential check as the card renders it. */
type CheckState = 'ok' | 'unconfigured' | 'invalid' | 'forbidden' | 'unreachable' | 'error'
interface CheckItem {
id: string
label: string
state: CheckState
message: string
}
/** Last test run, kept in memory so the card can show "最后检查". */
let lastCheck: { at: number; checks: CheckItem[] } | null = null
/**
* Uninstall confirmations.
*
* A preview issues a single-use token bound to one folder; the delete route
* refuses without it, so a stray click cannot remove a skill.
*/
const uninstallTokens = new Map<string, { token: string; expiresAt: number }>()
const UNINSTALL_TOKEN_TTL_MS = 10 * 60_000
/** The payload the page and the client card both consume. */
function statusPayload(deps: RouteDeps): Record<string, unknown> {
const view = deps.store.describe()
const tokens: Record<'activity' | 'memory' | 'summary', TokenView> = {
activity: view.activityToken,
memory: view.memoryToken,
summary: view.summaryToken,
const view: SettingsView = deps.store.describe()
const tokens = {
activity: view.activityToken as TokenView,
memory: view.memoryToken as TokenView,
summary: view.summaryToken as TokenView,
}
const settings = {
enabled: view.enabled,
baseUrl: view.baseUrl,
baseUrlConfigured: view.baseUrlConfigured,
baseUrlOrigin: view.baseUrlOrigin,
clientId: view.clientId,
requestTimeoutMs: view.requestTimeoutMs,
defaultK: view.defaultK,
@ -115,7 +265,13 @@ function statusPayload(deps: RouteDeps): Record<string, unknown> {
skillsDir: view.skillsDir,
}
return {
ok: true, settings, tokens, settingsPath: view.statePath, reporter: deps.reporter.snapshot(),
ok: true,
settings,
tokens,
settingsPath: view.statePath,
reporter: deps.reporter.snapshot(),
lastCheck,
capabilities: capabilities(deps),
...(deps.skills === undefined ? {} : { skills: deps.skills() }),
}
}
@ -145,6 +301,15 @@ function serveStatus(deps: RouteDeps, req: IncomingMessage, res: ServerResponse)
json(res, 200, statusPayload(deps))
}
/** `GET /cloud-memory/capabilities`. */
function serveCapabilities(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): void {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed')
return
}
json(res, 200, { ok: true, ...capabilities(deps) })
}
/** `PUT /cloud-memory/config`. */
async function serveConfig(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
if (req.method !== 'PUT' && req.method !== 'POST') {
@ -176,10 +341,21 @@ async function serveConfig(deps: RouteDeps, req: IncomingMessage, res: ServerRes
fail(res, 400, result.error ?? 'invalid-patch')
return
}
json(res, 200, statusPayload(deps))
json(res, 200, {
...statusPayload(deps),
...(result.clearedTokens === undefined ? {} : { credentialsCleared: result.clearedTokens }),
})
}
/** `POST /cloud-memory/test` — validate both tokens without recording anything. */
/** Map one failed credential probe onto a check state. */
function checkState(error: { status: number; code: string }): CheckState {
if (error.status === 0) return 'unreachable'
if (error.status === 401) return 'invalid'
if (error.status === 403) return 'forbidden'
return 'error'
}
/** `POST /cloud-memory/test` — read-only checks, one per credential. */
async function serveTest(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed')
@ -190,40 +366,68 @@ async function serveTest(deps: RouteDeps, req: IncomingMessage, res: ServerRespo
return
}
const client = deps.client()
const checks: CheckItem[] = []
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()
const activity: { ok: boolean; message: string } = activityToken === ''
? { ok: false, message: '还没填令牌:把 activity:write 密钥粘到下面「活动上报令牌」再点保存' }
: await (async () => {
const probe = await client.probeActivity(activityToken)
return probe.ok
? { ok: true, message: '令牌有效(鉴权通过)' }
: { ok: false, message: describeError(probe.error) }
})()
const memory: { ok: boolean; message: string } = memoryToken === ''
? { ok: false, message: '还没填令牌:把 memory:write 密钥粘到下面「记忆读写令牌」再点保存' }
: await (async () => {
const probe = await client.projects()
return probe.ok
? { ok: true, message: `令牌有效(${(probe.data.projects ?? []).length} 个项目)` }
: { ok: false, message: describeError(probe.error) }
})()
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()
const summary = !deps.store.settings().summaryEnabled
? { ok: false, message: '自动摘要已关闭(可在下方勾选开启)' }
: summaryToken === ''
? { ok: false, message: '未配置摘要令牌:留空则不做自动摘要' }
: await (async () => {
const probe = await client.probeSummary(summaryToken)
return probe.ok
? { ok: true, message: '摘要令牌有效(只进待确认队列)' }
: { ok: false, message: describeError(probe.error) }
})()
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),
})
}
json(res, 200, { ok: true, activity, memory, summary })
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 /cloud-memory/flush`. */
@ -240,21 +444,21 @@ async function serveFlush(deps: RouteDeps, req: IncomingMessage, res: ServerResp
json(res, 200, { ok: true, ...result })
}
/** Labels attached to the two tokens this plugin asks the dashboard to mint. */
/** Labels attached to the tokens this plugin asks the dashboard to mint. */
const TOKEN_LABELS = {
activity: 'DSH desktop 活动上报',
memory: 'DSH desktop 记忆读写',
summary: 'DSH desktop 对话摘要',
} as const
}
/**
* `POST /cloud-memory/login` — sign in with the cloud account and exchange it
* for the two scoped tokens.
* for the scoped tokens.
*
* The password is used once, in memory, and never written anywhere: the flow is
* password → short-lived session cookie → two `cmt_…` 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.
* 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: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
if (req.method !== 'POST') {
@ -297,7 +501,6 @@ async function serveLogin(deps: RouteDeps, req: IncomingMessage, res: ServerResp
json(res, 400, { ok: false, error: '用户名或密码过长' })
return
}
const client = deps.client()
const session = await client.login(username, password)
if (!session.ok) {
@ -305,7 +508,6 @@ async function serveLogin(deps: RouteDeps, req: IncomingMessage, res: ServerResp
json(res, status, { ok: false, error: describeError(session.error) })
return
}
const activity = await client.mintToken(session.data.sessionCookie, 'activity:write', TOKEN_LABELS.activity)
const memory = await client.mintToken(session.data.sessionCookie, 'memory:write', TOKEN_LABELS.memory)
const summary = await client.mintToken(session.data.sessionCookie, 'summary:write', TOKEN_LABELS.summary)
@ -315,8 +517,7 @@ async function serveLogin(deps: RouteDeps, req: IncomingMessage, res: ServerResp
json(res, 400, { ok: false, error: `登录成功,但创建令牌失败:${reason}` })
return
}
const patch: Parameters<SettingsStore['patch']>[0] = {}
const patch: Record<string, unknown> = {}
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
@ -325,7 +526,6 @@ async function serveLogin(deps: RouteDeps, req: IncomingMessage, res: ServerResp
json(res, 500, { ok: false, error: applied.error })
return
}
const failed = activity.ok ? memory : activity
const partial = !activity.ok || !memory.ok
json(res, 200, {
@ -345,35 +545,66 @@ async function serveLogin(deps: RouteDeps, req: IncomingMessage, res: ServerResp
})
}
/** HTTP status for one skill-admin failure code. */
function adminStatus(code: string): number {
switch (code) {
case 'not_found': return 404
case 'invalid_name':
case 'invalid_url': return 400
case 'invalid_url':
case 'invalid_plan': return 400
case 'collision':
case 'sync_running': return 409
case 'sync_running':
case 'plan_expired':
case 'confirmation_required':
case 'no_source':
case 'up_to_date':
case 'stale_plan':
case 'unsupported': return 409
case 'no_backup': return 404
case 'no_skills_found': return 422
case 'git_failed': return 502
default: return 500
}
}
/** Issue the single-use token a delete needs. */
function issueUninstallToken(folder: string): string {
const token = `uninstall_${randomUUID()}`
uninstallTokens.set(folder, { token, expiresAt: Date.now() + UNINSTALL_TOKEN_TTL_MS })
return token
}
/** Consume one uninstall token; false when it is missing, stale or foreign. */
function useUninstallToken(folder: string, token: unknown): boolean {
const record = uninstallTokens.get(folder)
if (record === undefined) return false
if (typeof token !== 'string' || token !== record.token) return false
if (record.expiresAt < Date.now()) {
uninstallTokens.delete(folder)
return false
}
uninstallTokens.delete(folder)
return true
}
/**
* The skill management surface, one prefix route:
* `GET /cloud-memory/skills` the management page
* `GET /cloud-memory/skills/api` inventory JSON (skills + trash)
* `POST /cloud-memory/skills/toggle` { folder, enabled }
* `POST /cloud-memory/skills/remove` { folder }
* `POST /cloud-memory/skills/install` { url }
* `GET /cloud-memory/skills` the management page
* `GET /cloud-memory/skills/api` inventory JSON (skills + plans)
* `POST /cloud-memory/skills/detail` { folder } — one skill with SKILL.md
* `POST /cloud-memory/skills/toggle` { folder, enabled }
* `POST /cloud-memory/skills/install/plan` { url } — stage the repository
* `POST /cloud-memory/skills/install/commit` { planId, folders }
* `POST /cloud-memory/skills/install/cancel` { planId }
* `POST /cloud-memory/skills/uninstall/plan` { folder } — impact preview
* `POST /cloud-memory/skills/remove` { folder, token, confirmed: true }
*/
async function serveSkills(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
if (deps.admin === undefined) {
const admin = deps.admin
if (admin === undefined) {
fail(res, 404, 'skills-admin-unavailable')
return
}
const admin = deps.admin
const suffix = (req.url ?? '').split('?')[0]?.slice(ROUTES.skills.length) ?? ''
if (suffix === '' || suffix === '/') {
if (req.method !== 'GET' && req.method !== 'HEAD') {
@ -395,54 +626,373 @@ async function serveSkills(deps: RouteDeps, req: IncomingMessage, res: ServerRes
fail(res, 405, 'method-not-allowed')
return
}
json(res, 200, { ok: true, ...(await admin.list()) })
const inventory = await admin.list()
json(res, 200, { ok: true, ...inventory, ...(await admin.listPlans()) })
return
}
const actions: Record<string, (body: Record<string, unknown>) => Promise<Record<string, unknown>>> = {
'/toggle': async (body) => admin.setEnabled(body.folder, body.enabled === true),
'/remove': async (body) => admin.remove(body.folder),
'/install': async (body) => admin.installFromGit(body.url),
if (suffix === '/sources') {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed')
return
}
const groups = deps.groups
if (groups === undefined) {
fail(res, 404, 'skill-groups-unavailable')
return
}
json(res, 200, { ok: true, ...(await groups.overview()) })
return
}
const action = actions[suffix]
type Handler = (body: Record<string, unknown>) => Promise<Record<string, unknown>>
const actions: Record<string, Handler> = {
'/detail': async (body) => ({ ...(await admin.detail(body.folder)) }),
'/toggle': async (body) => ({ ...(await admin.setEnabled(body.folder, body.enabled === true)) }),
// One-shot install kept for the standalone page; the card uses plan/commit.
'/install': async (body) => ({ ...(await admin.installFromGit(body.url)) }),
'/install/plan': async (body) => ({ ...(await admin.prepareInstall(body.url)) }),
'/install/commit': async (body) => ({ ...(await admin.commitInstall({ planId: body.planId, folders: body.folders })) }),
'/install/cancel': async (body) => ({ ...(await admin.cancelInstall({ planId: body.planId })) }),
'/uninstall/plan': async (body) => {
const plan = await admin.uninstallPlan(body.folder)
return { ...plan, token: issueUninstallToken(plan.folder) }
},
'/remove': async (body) => {
if (body.confirmed !== true) {
throw new SkillAdminError('confirmation_required', '删除必须显式确认:先预览影响,再传 confirmed=true。')
}
const folder = typeof body.folder === 'string' ? body.folder : ''
if (!useUninstallToken(folder, body.token)) {
throw new SkillAdminError('confirmation_required', '卸载确认已过期或与该技能不匹配,请重新预览。')
}
return { ...(await admin.remove(folder)) }
},
}
// Update/rollback operate on skills with a `.skill-source.json` record. They
// are optional: without the updater wired in the routes answer 404.
const updateActions: Record<string, Handler> = {
'/update/check': async (body) => ({ ...(await requireUpdates(deps).checkUpdate(body.folder)) }),
'/update/apply': async (body) => ({ ...(await requireUpdates(deps).applyUpdate(body.folder, body.expectedCommit)) }),
'/rollback': async (body) => ({ ...(await requireUpdates(deps).rollback(body.folder)) }),
}
// Category and source switches live in the same prefix so the card has one
// base URL; they are grouped here because they never touch a skill folder
// directly (except the DSH park/unpark the group manager delegates).
const groupActions: Record<string, Handler> = {
'/groups/create': async (body) => ({ ...(await requireGroups(deps).createGroup(body.sourceId, body.name)) }),
'/groups/rename': async (body) => ({ ...(await requireGroups(deps).renameGroup(body.sourceId, body.groupId, body.name)) }),
'/groups/delete': async (body) => ({ ...(await requireGroups(deps).deleteGroup(body.sourceId, body.groupId)) }),
'/groups/assign': async (body) => ({ ...(await requireGroups(deps).assign(body.sourceId, body.groupId, body.folders)) }),
'/groups/toggle': async (body) => ({ ...(await requireGroups(deps).toggleGroup(body.sourceId, body.groupId, body.enabled === true)) }),
'/source/toggle': async (body) => ({ ...(await requireGroups(deps).toggleSource(body.sourceId, body.enabled === true)) }),
'/source/reveal': async (body) => ({ ...(await requireGroups(deps).reveal(body.sourceId)) }),
}
const action = actions[suffix] ?? groupActions[suffix] ?? updateActions[suffix]
if (action === undefined) {
fail(res, 404, 'unknown-skill-route')
return
}
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed')
return
}
if (!sameOrigin(req)) {
fail(res, 403, 'origin-rejected')
return
}
const type = (req.headers['content-type'] ?? '').toLowerCase()
if (!type.startsWith('application/json')) {
fail(res, 415, 'json-required')
return
}
let body: unknown
const body = await jsonBody(req, res)
if (body === undefined) return
try {
body = JSON.parse(await readBody(req))
} catch {
fail(res, 400, 'invalid-json')
return
}
if (body === null || typeof body !== 'object' || Array.isArray(body)) {
fail(res, 400, 'invalid-body')
return
}
try {
json(res, 200, { ok: true, ...(await action(body as Record<string, unknown>)) })
json(res, 200, { ok: true, ...(await action(body)) })
} catch (error) {
if (error instanceof SkillAdminError) {
json(res, adminStatus(error.code), { ok: false, code: error.code, error: error.message })
} else {
json(res, 500, { ok: false, code: 'internal', error: error instanceof Error ? error.message : String(error) })
return
}
if (error instanceof SkillGroupError) {
json(res, groupStatus(error.code), { ok: false, code: error.code, error: error.message })
return
}
json(res, 500, { ok: false, code: 'internal', error: error instanceof Error ? error.message : String(error) })
}
}
/** The group manager is optional; the routes answer 404 when it is absent. */
function requireGroups(deps: RouteDeps): SkillGroupManager {
if (deps.groups === undefined) throw new SkillGroupError('unavailable', '技能分组功能未启用。')
return deps.groups
}
/** HTTP status for one group failure code. */
function groupStatus(code: string): number {
switch (code) {
case 'not_found':
case 'unknown_source': return 404
case 'invalid_name':
case 'duplicate':
case 'too_many': return 400
case 'unavailable': return 503
default: return 500
}
}
/** The updater is optional; its routes answer 404 when it is absent. */
function requireUpdates(deps: RouteDeps): SkillUpdater {
if (deps.updates === undefined) throw new SkillAdminError('unsupported', '技能更新/回退未启用。')
return deps.updates
}
/** HTTP status for one market failure code. */
function marketStatus(code: string): number {
switch (code) {
case 'unknown_provider':
case 'invalid_manifest': return 400
case 'not_found': return 404
case 'unreachable':
case 'unavailable': return 502
default:
return code.startsWith('http_') ? 502 : 500
}
}
/**
* Market surface, one prefix route:
* `GET /cloud-memory/market/providers` configured sources
* `GET /cloud-memory/market/search` ?provider=&q=&cursor=
* `POST /cloud-memory/market/detail` { provider, id }
* `POST /cloud-memory/market/plan` { provider, id } — pin commit + stage a plan
* `POST /cloud-memory/market/commit` { planId, folders }
* `POST /cloud-memory/market/cancel` { planId }
*/
async function serveMarket(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
const market = deps.market
if (market === undefined) {
fail(res, 404, 'market-unavailable')
return
}
const url = new URL(req.url ?? '/', 'http://localhost')
const suffix = url.pathname.slice(ROUTES.market.length)
try {
if (suffix === '' || suffix === '/' || suffix === '/providers') {
if (req.method !== 'GET') { fail(res, 405, 'method-not-allowed'); return }
json(res, 200, { ok: true, providers: market.list() })
return
}
if (suffix === '/search') {
if (req.method !== 'GET') { fail(res, 405, 'method-not-allowed'); return }
const providerId = url.searchParams.get('provider') ?? market.list()[0]?.id ?? ''
const query = url.searchParams.get('q') ?? ''
const cursorRaw = Number(url.searchParams.get('cursor') ?? '0')
const cursor = Number.isFinite(cursorRaw) && cursorRaw > 0 ? cursorRaw : 0
const result = await market.search(providerId, query, cursor)
json(res, 200, { ok: true, provider: market.get(providerId).info(), ...result })
return
}
type Handler = (body: Record<string, unknown>) => Promise<Record<string, unknown>>
const admin = deps.admin
const requireAdmin = (): SkillAdmin => {
if (admin === undefined) throw new MarketError('unavailable', '技能管理未启用,无法安装。')
return admin
}
const actions: Record<string, Handler> = {
'/detail': async (body) => ({ ...(await market.detail(String(body.provider ?? ''), String(body.id ?? ''))) }),
'/plan': async (body) => {
const providerId = String(body.provider ?? '')
const id = String(body.id ?? '')
const artifact = await market.resolve(providerId, id, typeof body.version === 'string' ? body.version : undefined)
const plan = await requireAdmin().prepareInstall(artifact.repoUrl, {
ref: artifact.ref,
source: {
provider: providerId,
entryId: id,
...(artifact.version === undefined ? {} : { version: artifact.version }),
},
})
const wanted = new Set(artifact.folders)
return {
planId: plan.planId,
...(plan.commit === undefined ? {} : { commit: plan.commit }),
artifact,
candidates: plan.candidates.filter((candidate) => wanted.has(candidate.folder)),
totalInRepo: plan.candidates.length,
}
},
'/commit': async (body) => ({ ...(await requireAdmin().commitInstall({ planId: body.planId, folders: body.folders })) }),
'/cancel': async (body) => ({ ...(await requireAdmin().cancelInstall({ planId: body.planId })) }),
}
const action = actions[suffix]
if (action === undefined) { fail(res, 404, 'unknown-market-route'); return }
const body = await jsonBody(req, res)
if (body === undefined) return
json(res, 200, { ok: true, ...(await action(body)) })
} catch (error) {
if (error instanceof MarketError) {
json(res, marketStatus(error.code), { ok: false, code: error.code, error: error.message })
return
}
if (error instanceof SkillAdminError) {
json(res, adminStatus(error.code), { ok: false, code: error.code, error: error.message })
return
}
json(res, 500, { ok: false, code: 'internal', error: error instanceof Error ? error.message : String(error) })
}
}
/**
* Sync surface:
* `GET /cloud-memory/sync/status` latest stats + both sides of each conflict
* `POST /cloud-memory/sync/run` trigger one pass now
* `POST /cloud-memory/sync/resolve` { name, action: keep_local | take_cloud | manual }
*/
async function serveSync(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
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(ROUTES.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') {
if (req.method !== 'POST') { fail(res, 405, 'method-not-allowed'); 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)
json(res, 200, { ok: true, ...result, 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 })
}
}
/** Cross-software / workspace inventory routes. */
async function serveClients(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
const registry = deps.clients
if (registry === undefined) {
fail(res, 404, 'clients-unavailable')
return
}
const url = new URL(req.url ?? '/', 'http://localhost')
const suffix = url.pathname.slice(ROUTES.clients.length)
try {
if (suffix === '' || suffix === '/' || suffix === '/overview') {
if (req.method !== 'GET') { fail(res, 405, 'method-not-allowed'); return }
json(res, 200, { ok: true, ...(await registry.overview()) })
return
}
if (suffix === '/inventory') {
if (req.method !== 'GET') { fail(res, 405, 'method-not-allowed'); return }
const result = await registry.inventory(
url.searchParams.get('software'),
url.searchParams.get('scope'),
url.searchParams.get('workspaceId') ?? undefined,
)
json(res, 200, { ok: true, ...result })
return
}
if (suffix === '/workspaces/add') {
if (req.method !== 'POST') { fail(res, 405, 'method-not-allowed'); return }
const body = await jsonBody(req, res)
if (body === undefined) return
const workspace = await registry.addWorkspace(body.software, body.path, body.name)
json(res, 200, { ok: true, workspace })
return
}
if (suffix === '/workspaces/remove') {
if (req.method !== 'POST') { fail(res, 405, 'method-not-allowed'); return }
const body = await jsonBody(req, res)
if (body === undefined) return
json(res, 200, { ok: true, ...(await registry.removeWorkspace(body.software, body.id)) })
return
}
if (suffix === '/workspace/inventory') {
if (req.method !== 'GET') { fail(res, 405, 'method-not-allowed'); return }
const { admin, workspace } = await registry.workspaceSkillAdmin(url.searchParams.get('software'), url.searchParams.get('workspaceId'))
json(res, 200, { ok: true, workspace, ...(await admin.list()) })
return
}
if (suffix === '/workspace/detail') {
if (req.method !== 'POST') { fail(res, 405, 'method-not-allowed'); return }
const body = await jsonBody(req, res)
if (body === undefined) return
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId)
json(res, 200, { ok: true, ...(await admin.detail(body.folder)) })
return
}
if (suffix === '/workspace/toggle') {
if (req.method !== 'POST') { fail(res, 405, 'method-not-allowed'); return }
const body = await jsonBody(req, res)
if (body === undefined) return
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId)
json(res, 200, { ok: true, ...(await admin.setEnabled(body.folder, body.enabled === true)) })
return
}
if (suffix === '/workspace/remove') {
if (req.method !== 'POST') { fail(res, 405, 'method-not-allowed'); return }
const body = await jsonBody(req, res)
if (body === undefined) return
if (body.confirmed !== true) throw new SkillAdminError('confirmation_required', '工作区技能删除必须显式 confirmed:true。')
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId)
json(res, 200, { ok: true, ...(await admin.remove(body.folder)) })
return
}
if (suffix === '/workspace/install/plan') {
if (req.method !== 'POST') { fail(res, 405, 'method-not-allowed'); return }
const body = await jsonBody(req, res)
if (body === undefined) return
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId)
json(res, 200, { ok: true, ...(await admin.prepareInstall(body.url)) })
return
}
if (suffix === '/workspace/install/commit') {
if (req.method !== 'POST') { fail(res, 405, 'method-not-allowed'); return }
const body = await jsonBody(req, res)
if (body === undefined) return
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId)
json(res, 200, { ok: true, ...(await admin.commitInstall({ planId: body.planId, folders: body.folders })) })
return
}
fail(res, 404, 'unknown-clients-route')
} catch (error) {
if (error instanceof SkillAdminError) {
json(res, adminStatus(error.code), { ok: false, code: error.code, error: error.message })
return
}
const message = error instanceof Error ? error.message : String(error)
const known = ['invalid_software', 'invalid_path', 'duplicate', 'not_found', 'unknown_workspace', 'unsupported_workspace_write']
const code = known.includes(message) ? message : 'internal'
const status = code === 'internal' ? 500
: code === 'not_found' || code === 'unknown_workspace' ? 404
: code === 'duplicate' ? 409
: code === 'unsupported_workspace_write' ? 501 : 400
json(res, status, { ok: false, code, error: message })
}
}
/** dsh-brain data migration: GET status, POST run. */
async function serveMigrate(_deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
const url = new URL(req.url ?? '/', 'http://localhost')
const suffix = url.pathname.slice(ROUTES.migrate.length)
if (suffix === '' || suffix === '/' || suffix === '/brain') {
if (req.method === 'GET') { const status = await brainStatus(); json(res, 200, { ok: true, ...status }); return }
if (req.method === 'POST') { const result = await migrateLegacyFiles(); json(res, 200, { ok: true, ...result }); return }
fail(res, 405, 'method-not-allowed')
return
}
fail(res, 404, 'unknown-migrate-route')
}
/** Build the exact-route table registered with the host web server. */
export function createRoutes(deps: RouteDeps): CloudMemoryWebRoute[] {
return [
@ -456,6 +1006,11 @@ export function createRoutes(deps: RouteDeps): CloudMemoryWebRoute[] {
path: ROUTES.status,
handler: (req, res) => serveStatus(deps, req, res),
},
{
kind: 'exact',
path: ROUTES.capabilities,
handler: (req, res) => serveCapabilities(deps, req, res),
},
{
kind: 'exact',
path: ROUTES.config,
@ -481,5 +1036,25 @@ export function createRoutes(deps: RouteDeps): CloudMemoryWebRoute[] {
path: ROUTES.skills,
handler: (req, res) => serveSkills(deps, req, res),
},
{
kind: 'prefix',
path: ROUTES.market,
handler: (req, res) => serveMarket(deps, req, res),
},
{
kind: 'prefix',
path: ROUTES.sync,
handler: (req, res) => serveSync(deps, req, res),
},
{
kind: 'prefix',
path: ROUTES.clients,
handler: (req, res) => serveClients(deps, req, res),
},
{
kind: 'prefix',
path: ROUTES.migrate,
handler: (req, res) => serveMigrate(deps, req, res),
},
]
}

View File

@ -1,9 +1,9 @@
/**
* Local skill management, built into the plugin: list, enable/disable,
* real delete, and install from a git repository.
* Local skill management, built into the plugin: list, inspect, enable/disable,
* previewed install, previewed uninstall.
*
* This covers the everyday subset of a full skills manager. It manages
* only the DSH skills root (plus its own parking and trash areas) — the
* only the DSH skills root (plus its own parking and staging areas) — the
* cloud sync engine keeps owning everything beyond the local disk.
*
* Enable/disable is deliberately mechanical: a disabled skill's folder
@ -14,14 +14,22 @@
* mistaken for deletions, and a parked cloud skill still receives its
* cloud updates in place.
*
* Delete is a real delete: the folder is removed recursively. The
* cloud copy is unaffected — local deletion never propagates to the
* center (the sync engine remembers the removal, so the same cloud
* version is not pulled back down either).
* Delete is a real delete: the folder is removed recursively. It is only
* reachable through a two-step contract (plan → confirm) because there is no
* trash area and nothing can be restored. The cloud copy is unaffected —
* local deletion never propagates to the center.
*
* Installation is staged: the repository is cloned into an isolated scratch
* directory, candidates are enumerated and described, and nothing enters the
* skills root until the caller commits an explicit selection. Repository code
* is never executed (no hooks, no install scripts), symlinks are never
* followed, and a colliding folder is always skipped instead of overwritten.
*/
import { lstatSync } from 'node:fs'
import { execFile } from 'node:child_process'
import { cp, mkdir, readFile, readdir, rename, rm, stat } from 'node:fs/promises'
import { basename, join } from 'node:path'
import { createHash, randomUUID } from 'node:crypto'
import { cp, lstat, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'
import { basename, dirname, join, relative, resolve, sep } from 'node:path'
import { parseSkillFrontmatter } from './skill-sync.ts'
import { dshHome } from './store.ts'
@ -30,20 +38,186 @@ export function skillsHoldingDir(): string {
return join(dshHome(), 'skills-disabled')
}
/** Isolated scratch space for staged installs; never inside the skills root. */
export function skillsStagingDir(): string {
return join(dshHome(), '.cloud-memory-staging')
}
/** Persisted plan records (metadata only: ids, counts, timestamps). */
export function skillPlansPath(): string {
return join(dshHome(), '.cloud-memory-plans.json')
}
/** A management failure with a stable machine-readable code. */
export class SkillAdminError extends Error {
constructor(readonly code: string, message: string) {
code: string
constructor(code: string, message: string) {
super(message)
this.code = code
this.name = 'SkillAdminError'
}
}
/** Run git and return stdout (used for resolving the checked-out commit). */
function execFileText(file: string, args: string[], timeoutMs = 120_000): Promise<string> {
return new Promise<string>((resolvePromise, rejectPromise) => {
execFile(
file,
args,
{ timeout: timeoutMs, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' }, maxBuffer: 4 * 1024 * 1024 },
(error, stdout) => (error ? rejectPromise(error) : resolvePromise(String(stdout))),
)
})
}
function fail(code: string, message: string): never {
throw new SkillAdminError(code, message)
}
/** One skill as the management page shows it. */
export interface AdminSkill {
/** Hard caps so one hostile repository cannot exhaust the disk. */
const MAX_SKILL_FILES = 1500
const MAX_SKILL_BYTES = 4 * 1024 * 1024
const MAX_CANDIDATES = 60
const MAX_SKILL_MD_BYTES = 256 * 1024
const PLAN_TTL_MS = 30 * 60_000
async function isDirectory(path: string): Promise<boolean> {
return stat(path).then((s) => s.isDirectory()).catch(() => false)
}
async function isSymlink(path: string): Promise<boolean> {
return lstat(path).then((s) => s.isSymbolicLink()).catch(() => false)
}
/** Synchronous variant, used inside `cp` filters where no await is possible. */
function isSymlinkSync(path: string): boolean {
try {
return lstatSync(path).isSymbolicLink()
} catch {
return true
}
}
/** Read a skill's `.skill-source.json`, or undefined when absent/corrupt. */
export async function readSkillSourceRecord(dir: string): Promise<SkillSourceRecord | undefined> {
const raw = await readFile(join(dir, '.skill-source.json'), 'utf8').catch(() => undefined)
if (raw === undefined) return undefined
try {
const parsed: unknown = JSON.parse(raw)
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return undefined
const record = parsed as Partial<SkillSourceRecord>
if (typeof record.repoUrl !== 'string' || typeof record.commit !== 'string') return undefined
return {
version: 1,
provider: typeof record.provider === 'string' ? record.provider : 'git',
repoUrl: record.repoUrl,
ref: typeof record.ref === 'string' ? record.ref : record.commit,
commit: record.commit,
sourcePath: typeof record.sourcePath === 'string' ? record.sourcePath : '',
installedAt: typeof record.installedAt === 'string' ? record.installedAt : new Date(0).toISOString(),
...(typeof record.entryId === 'string' ? { entryId: record.entryId } : {}),
...(typeof record.marketVersion === 'string' ? { marketVersion: record.marketVersion } : {}),
}
} catch {
return undefined
}
}
/** Files under one skill folder, skipping `.git` and never following links. */
async function walkFiles(dir: string, cap = MAX_SKILL_FILES + 1): Promise<{ path: string; bytes: number; script: boolean }[]> {
const out: { path: string; bytes: number; script: boolean }[] = []
const walk = async (sub: string): Promise<void> => {
if (out.length > cap) return
for (const entry of await readdir(join(dir, sub), { withFileTypes: true }).catch(() => [])) {
if (entry.name === '.git') continue
const rel = sub === '' ? entry.name : `${sub}/${entry.name}`
const abs = join(dir, rel)
if (entry.isSymbolicLink()) {
out.push({ path: rel, bytes: 0, script: false })
continue
}
if (entry.isDirectory()) {
await walk(rel)
continue
}
if (!entry.isFile()) continue
const size = await stat(abs).then((s) => s.size).catch(() => 0)
out.push({ path: rel, bytes: size, script: /\.(mjs|cjs|js|ts|ps1|sh|bat|cmd|py|rb|exe|dll)$/i.test(entry.name) })
}
}
await walk('')
out.sort((a, b) => (a.path < b.path ? -1 : 1))
return out
}
/** A folder name we are willing to move around: one path segment, no tricks. */
function checkFolder(folder: unknown): string {
if (typeof folder !== 'string' || folder === '' || folder.length > 128 ||
folder.startsWith('.') || folder.includes('/') || folder.includes('\\') || folder.includes('\0')) {
fail('invalid_name', `技能目录名无效:${String(folder)}`)
}
return folder
}
/** Where a skill came from, recorded next to it so it can be updated/rolled back. */
export interface SkillInstallSource {
/** `git` for a manual repository install, or a market provider id. */
provider: string
/** Market entry id, when the install came from a marketplace. */
entryId?: string
version?: string
}
/** On-disk record written into an installed skill as `.skill-source.json`. */
export interface SkillSourceRecord {
version: 1
provider: string
repoUrl: string
ref: string
commit: string
/** Path inside the repository the folder was copied from. */
sourcePath: string
entryId?: string
marketVersion?: string
installedAt: string
}
/** One planned install candidate (metadata only). */
interface InstallPlanCandidate {
folder: string
name: string
description: string
files: number
bytes: number
scripts: string[]
conflict: boolean
conflictLocation?: 'root' | 'holding'
problem?: string
/** Path of the candidate relative to the staging clone root. */
rel?: string
}
interface InstallPlan {
id: string
kind: 'install'
url: string
createdAt: number
expiresAt: number
stagingDir: string
candidates: InstallPlanCandidate[]
/** Commit the clone was pinned to (recorded for update/rollback). */
commit?: string
ref?: string
source?: SkillInstallSource
}
interface PlansFile {
version: 1
plans: InstallPlan[]
}
/** The inventory row the card renders. */
export interface SkillEntry {
folder: string
name: string
description: string
@ -51,58 +225,55 @@ export interface AdminSkill {
origin: 'cloud' | 'uploaded' | 'local'
revision?: number
files: number
bytes: number
installedAt?: string
skillSha256?: string
location: 'root' | 'holding'
ownerManager: string
writable: boolean
/** Present when the folder carries a `.skill-source.json` record. */
source?: {
provider: string
repoUrl: string
ref: string
commit: string
entryId?: string
}
/** True when a source record exists, so update/rollback can be offered. */
updatable?: boolean
}
/** Dependencies of one admin instance. */
export interface SkillAdminDeps {
skillsRoot: () => string
holdingDir: () => string
/** The sync sidecar (read-only here) for origin and revision facts. */
syncStatePath: () => string
/** True while a sync pass is running; mutations refuse meanwhile. */
syncRunning: () => boolean
log: (message: string) => void
}
async function isDirectory(path: string): Promise<boolean> {
return stat(path).then((s) => s.isDirectory()).catch(() => false)
}
/** Count files below a directory, capped so a stray tree cannot hang us. */
async function countFiles(dir: string, cap = 2000): Promise<number> {
let count = 0
const walk = async (sub: string): Promise<void> => {
if (count > cap) return
for (const entry of await readdir(join(dir, sub), { withFileTypes: true }).catch(() => [])) {
if (entry.name === '.git') continue
const rel = sub === '' ? entry.name : `${sub}/${entry.name}`
if (entry.isDirectory()) await walk(rel)
else if (entry.isFile()) count += 1
}
}
await walk('')
return count
}
/** A folder name we are willing to move around: one path segment, no tricks. */
function checkFolder(folder: unknown): string {
if (
typeof folder !== 'string' || folder === '' || folder.length > 128 ||
folder.startsWith('.') || folder.includes('/') || folder.includes('\\') || folder.includes('\0')
) {
fail('invalid_name', `技能目录名无效:${String(folder)}`)
}
return folder
/** Where plan metadata is persisted; defaults to `$DSH_HOME/.cloud-memory-plans.json`. */
plansPath?: () => string
/** Where staged clones live; defaults to `$DSH_HOME/.cloud-memory-staging`. */
stagingRoot?: () => string
}
export class SkillAdmin {
constructor(private readonly deps: SkillAdminDeps) {}
private readonly deps: SkillAdminDeps
constructor(deps: SkillAdminDeps) {
this.deps = deps
}
private plansFile(): string {
return this.deps.plansPath?.() ?? skillPlansPath()
}
private stagingRoot(): string {
return this.deps.stagingRoot?.() ?? skillsStagingDir()
}
private guardSync(): void {
if (this.deps.syncRunning()) fail('sync_running', '技能同步正在进行,请稍候再试。')
}
private async syncUploaded(): Promise<Record<string, { folder?: string; revision?: number }>> {
private async uploaded(): Promise<Record<string, { folder?: string; revision?: number }>> {
try {
const parsed: unknown = JSON.parse(await readFile(this.deps.syncStatePath(), 'utf8'))
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
@ -117,44 +288,74 @@ export class SkillAdmin {
return {}
}
private async describe(folder: string, dir: string, enabled: boolean, uploaded: Record<string, { folder?: string; revision?: number }>): Promise<AdminSkill | undefined> {
private async describe(
folder: string,
dir: string,
enabled: boolean,
uploaded: Record<string, { folder?: string; revision?: number }>,
): Promise<SkillEntry | undefined> {
const markdown = await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined)
if (markdown === undefined) return undefined
const frontmatter = parseSkillFrontmatter(markdown)
let origin: AdminSkill['origin'] = 'local'
let origin: SkillEntry['origin'] = 'local'
let revision: number | undefined
const delivery = await readFile(join(dir, '.manifest.json'), 'utf8').catch(() => undefined)
if (delivery !== undefined) {
origin = 'cloud'
try {
const parsed: unknown = JSON.parse(delivery)
const value = (parsed as { revision?: unknown }).revision
const value = (parsed as { revision?: unknown } | null)?.revision
if (typeof value === 'number') revision = value
} catch { /* a corrupt manifest still marks cloud origin */ }
} catch {
// A corrupt manifest still marks cloud origin.
}
} else {
for (const record of Object.values(uploaded)) {
if (record.folder === folder) {
origin = 'uploaded'
revision = record.revision
if (typeof record.revision === 'number') revision = record.revision
break
}
}
}
const files = await walkFiles(dir)
const bytes = files.reduce((sum, file) => sum + file.bytes, 0)
const installedAt = await stat(join(dir, 'SKILL.md')).then((s) => new Date(s.mtimeMs).toISOString()).catch(() => undefined)
const name = frontmatter.name
const source = await readSkillSourceRecord(dir)
return {
folder,
name: frontmatter.name ?? folder,
description: (frontmatter.description ?? '').slice(0, 300),
name: typeof name === 'string' && name !== '' ? name : folder,
description: String(frontmatter.description ?? '').slice(0, 300),
enabled,
origin,
...(revision === undefined ? {} : { revision }),
files: await countFiles(dir),
files: files.length,
bytes,
...(installedAt === undefined ? {} : { installedAt }),
skillSha256: createHash('sha256').update(markdown).digest('hex'),
location: enabled ? 'root' : 'holding',
ownerManager: 'dsh-cloud-memory',
writable: true,
...(source === undefined
? {}
: {
source: {
provider: source.provider,
repoUrl: source.repoUrl,
ref: source.ref,
commit: source.commit,
...(source.entryId === undefined ? {} : { entryId: source.entryId }),
},
}),
updatable: source !== undefined,
}
}
/** Inventory of the skills root and the parking area. */
async list(): Promise<{ skills: AdminSkill[] }> {
const uploaded = await this.syncUploaded()
const skills: AdminSkill[] = []
async list(): Promise<{ skills: SkillEntry[]; root: string; holding: string; staging: string }> {
const uploaded = await this.uploaded()
const skills: SkillEntry[] = []
const scan = async (area: string, enabled: boolean): Promise<void> => {
for (const entry of await readdir(area, { withFileTypes: true }).catch(() => [])) {
if (!entry.isDirectory() || entry.name.startsWith('.')) continue
@ -165,11 +366,11 @@ export class SkillAdmin {
await scan(this.deps.skillsRoot(), true)
await scan(this.deps.holdingDir(), false)
skills.sort((a, b) => (a.folder < b.folder ? -1 : 1))
return { skills }
return { skills, root: this.deps.skillsRoot(), holding: this.deps.holdingDir(), staging: this.stagingRoot() }
}
/** Locate a skill folder across the root and the parking area. */
private async locate(folder: string): Promise<{ area: 'root' | 'holding'; dir: string } | undefined> {
async locate(folder: string): Promise<{ area: 'root' | 'holding'; dir: string } | undefined> {
const rootDir = join(this.deps.skillsRoot(), folder)
if (await isDirectory(rootDir)) return { area: 'root', dir: rootDir }
const parkedDir = join(this.deps.holdingDir(), folder)
@ -177,100 +378,394 @@ export class SkillAdmin {
return undefined
}
/** Everything one skill panel needs, including its SKILL.md text. */
async detail(folderInput: unknown): Promise<{
skill: SkillEntry
dir: string
files: { path: string; bytes: number; script: boolean }[]
totalBytes: number
truncated: boolean
skillMd: string
}> {
const folder = checkFolder(folderInput)
const found = await this.locate(folder)
if (found === undefined) fail('not_found', `没有找到技能:${folder}`)
if (await isSymlink(found.dir)) fail('unsupported', `技能目录是链接,不在这里管理:${folder}`)
const entry = await this.describe(folder, found.dir, found.area === 'root', await this.uploaded())
if (entry === undefined) fail('not_found', `技能缺少 SKILL.md:${folder}`)
const files = await walkFiles(found.dir)
const raw = await readFile(join(found.dir, 'SKILL.md'), 'utf8').catch(() => '')
const truncated = Buffer.byteLength(raw) > MAX_SKILL_MD_BYTES
return {
skill: entry,
dir: found.dir,
files,
totalBytes: files.reduce((sum, file) => sum + file.bytes, 0),
truncated,
skillMd: truncated ? Buffer.from(raw).subarray(0, MAX_SKILL_MD_BYTES).toString('utf8') : raw,
}
}
/** Enable (move back into the root) or disable (park) one skill. */
async setEnabled(folderInput: unknown, enabled: boolean): Promise<{ folder: string; enabled: boolean }> {
async setEnabled(folderInput: unknown, enabled: boolean): Promise<{ folder: string; enabled: boolean; note: string }> {
this.guardSync()
const folder = checkFolder(folderInput)
const found = await this.locate(folder)
if (found === undefined) fail('not_found', `没有找到技能:${folder}`)
const targetArea = enabled ? 'root' : 'holding'
if (found.area === targetArea) return { folder, enabled }
const targetArea: 'root' | 'holding' = enabled ? 'root' : 'holding'
if (found.area === targetArea) return { folder, enabled, note: this.effectNote(enabled) }
const targetRoot = enabled ? this.deps.skillsRoot() : this.deps.holdingDir()
await mkdir(targetRoot, { recursive: true })
const target = join(targetRoot, folder)
if (await isDirectory(target)) fail('collision', `目标位置已存在同名技能:${folder}`)
await rename(found.dir, target)
try {
await rename(found.dir, target)
} catch (error) {
// A cross-device move must not leave the skill half-copied: fall back to a
// plain copy only for EXDEV, and only then remove the source.
if ((error as NodeJS.ErrnoException).code !== 'EXDEV') throw error
await cp(found.dir, target, { recursive: true, filter: (source) => !source.split(/[\\/]/).includes('.git') })
await rm(found.dir, { recursive: true, force: true })
}
this.deps.log(`skill ${enabled ? 'enabled' : 'disabled'}: ${folder}`)
return { folder, enabled }
return { folder, enabled, note: this.effectNote(enabled) }
}
/** Delete one skill for real: its folder is removed recursively. */
async remove(folderInput: unknown): Promise<{ folder: string }> {
/** The enable/disable mechanism is a directory move, not a live switch. */
private effectNote(enabled: boolean): string {
return enabled
? '已放回技能目录:新会话可见;已在运行的会话可能仍保留旧状态。'
: '已移出技能目录:新会话不再加载;已经加载的会话不受影响。'
}
/** Preview of what an uninstall would remove. Nothing is deleted yet. */
async uninstallPlan(folderInput: unknown): Promise<{
folder: string
dir: string
area: 'root' | 'holding'
files: number
bytes: number
scripts: string[]
origin: SkillEntry['origin'] | 'unknown'
cloudRevision?: number
recoverable: false
note: string
}> {
const folder = checkFolder(folderInput)
const found = await this.locate(folder)
if (found === undefined) fail('not_found', `没有找到技能:${folder}`)
if (await isSymlink(found.dir)) fail('unsupported', `技能目录是链接,不在这里删除:${folder}`)
const entry = await this.describe(folder, found.dir, found.area === 'root', await this.uploaded())
const files = await walkFiles(found.dir)
return {
folder,
dir: found.dir,
area: found.area,
files: files.length,
bytes: files.reduce((sum, file) => sum + file.bytes, 0),
scripts: files.filter((file) => file.script).map((file) => file.path).slice(0, 20),
origin: entry?.origin ?? 'unknown',
...(entry?.revision === undefined ? {} : { cloudRevision: entry.revision }),
recoverable: false,
note: '本机删除不可恢复(没有回收站)。云端副本不受影响,同步引擎也不会把同一版本再次拉回。',
}
}
/**
* Delete one skill for real: its folder is removed recursively.
*
* The route layer requires a plan token plus `confirmed: true`; this method
* itself stays usable by the verification harness and by trusted callers.
*/
async remove(folderInput: unknown): Promise<{ folder: string; dir: string; files: number; bytes: number }> {
this.guardSync()
const folder = checkFolder(folderInput)
const found = await this.locate(folder)
if (found === undefined) fail('not_found', `没有找到技能:${folder}`)
const files = await walkFiles(found.dir)
const bytes = files.reduce((sum, file) => sum + file.bytes, 0)
await rm(found.dir, { recursive: true, force: true })
this.deps.log(`skill deleted: ${folder}`)
return { folder }
return { folder, dir: found.dir, files: files.length, bytes }
}
private async readPlans(): Promise<PlansFile> {
try {
const parsed: unknown = JSON.parse(await readFile(this.plansFile(), 'utf8'))
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
const plans = (parsed as { plans?: unknown }).plans
if (Array.isArray(plans)) return { version: 1, plans: plans as InstallPlan[] }
}
} catch {
// Missing or torn file: no plans.
}
return { version: 1, plans: [] }
}
private async writePlans(file: PlansFile): Promise<void> {
const path = this.plansFile()
await mkdir(dirname(path), { recursive: true })
const temporary = `${path}.tmp`
await writeFile(temporary, `${JSON.stringify(file, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
await rename(temporary, path)
}
/** Drop expired plans and their staging trees. */
private async sweepPlans(file: PlansFile): Promise<PlansFile> {
const now = Date.now()
const live: InstallPlan[] = []
for (const plan of file.plans) {
if (plan.expiresAt > now) {
live.push(plan)
continue
}
await rm(plan.stagingDir, { recursive: true, force: true }).catch(() => {})
}
return { version: 1, plans: live }
}
/**
* Install every skill found in a git repository (https:// or file://).
* The clone is shallow and never executes repository code; folders
* that collide with existing skills are skipped, never overwritten.
* Stage a git repository and describe its skills. Nothing enters the skills
* root here; the caller picks folders and commits.
*/
async installFromGit(urlInput: unknown): Promise<{ installed: string[]; skipped: { name: string; reason: string }[] }> {
async prepareInstall(urlInput: unknown, options: { ref?: string; source?: SkillInstallSource } = {}): Promise<{
planId: string
url: string
expiresAt: number
commit?: string
candidates: (InstallPlanCandidate & { id: string })[]
}> {
this.guardSync()
if (typeof urlInput !== 'string') fail('invalid_url', '请提供仓库地址。')
const url = urlInput.trim()
if (!/^(https:\/\/|file:\/\/)/.test(url) || /[\s"'`]/.test(url) || url.length > 512) {
fail('invalid_url', '只接受 https:// 或 file:// 的 git 仓库地址。')
}
const scratch = join(dshHome(), `.cloud-memory-clone-${process.pid}-${Date.now().toString(36)}`)
const stagingRoot = this.stagingRoot()
await mkdir(stagingRoot, { recursive: true })
const planId = `plan_${Date.now().toString(36)}_${randomUUID().slice(0, 8)}`
const stagingDir = join(stagingRoot, planId)
try {
await new Promise<void>((resolvePromise, rejectPromise) => {
execFile(
'git',
['clone', '--depth', '1', '--no-tags', '--', url, scratch],
{ timeout: 120_000, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' }, maxBuffer: 4 * 1024 * 1024 },
(error) => (error ? rejectPromise(error) : resolvePromise()),
)
})
} catch {
await rm(scratch, { recursive: true, force: true }).catch(() => {})
fail('git_failed', '仓库克隆失败(地址不可达、需要登录,或本机没有 git)。')
}
try {
const repoName = basename(url.replace(/\/$/, '').replace(/\.git$/, '')) || 'skill'
const candidates: { folder: string; dir: string }[] = []
const collect = async (dir: string, depth: number): Promise<void> => {
if (await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined) !== undefined) {
candidates.push({ folder: dir === scratch ? repoName : basename(dir), dir })
return
}
if (depth >= 3) return
for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
if (entry.isDirectory() && entry.name !== '.git') await collect(join(dir, entry.name), depth + 1)
}
}
await collect(scratch, 0)
if (candidates.length === 0) fail('no_skills_found', '仓库里没有找到技能(包含 SKILL.md 的文件夹)。')
const installed: string[] = []
const skipped: { name: string; reason: string }[] = []
await mkdir(this.deps.skillsRoot(), { recursive: true })
for (const candidate of candidates) {
let folder = candidate.folder
await execFileText('git', ['clone', '--depth', '1', '--no-tags', '--', url, stagingDir])
if (typeof options.ref === 'string' && options.ref !== '') {
try {
folder = checkFolder(folder)
await execFileText('git', ['-C', stagingDir, 'fetch', '--depth', '1', 'origin', options.ref])
await execFileText('git', ['-C', stagingDir, 'checkout', '--detach', 'FETCH_HEAD'])
} catch {
skipped.push({ name: candidate.folder, reason: 'invalid_name' })
continue
// The default-branch clone is still usable; the recorded commit below
// is whatever was actually checked out, so an install stays auditable.
}
if ((await this.locate(folder)) !== undefined) {
skipped.push({ name: folder, reason: 'already_exists' })
continue
}
await cp(candidate.dir, join(this.deps.skillsRoot(), folder), {
recursive: true,
filter: (source) => !source.split(/[\\/]/).includes('.git'),
})
installed.push(folder)
this.deps.log(`skill installed from git: ${folder}`)
}
return { installed, skipped }
} finally {
await rm(scratch, { recursive: true, force: true }).catch(() => {})
} catch (error) {
await rm(stagingDir, { recursive: true, force: true }).catch(() => {})
const code = (error as NodeJS.ErrnoException).code
fail('git_failed', code === 'ENOENT'
? '本机没有 git 命令,无法从仓库安装技能。'
: '仓库克隆失败(地址不可达、需要登录,或不是 git 仓库)。')
}
let commit = ''
try {
commit = (await execFileText('git', ['-C', stagingDir, 'rev-parse', 'HEAD'], 20_000)).trim()
} catch {
commit = ''
}
const repoName = basename(url.replace(/\/$/, '').replace(/\.git$/, '')) || 'skill'
const found: { folder: string; dir: string }[] = []
const collect = async (dir: string, depth: number): Promise<void> => {
if (found.length >= MAX_CANDIDATES) return
const markdown = await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined)
if (markdown !== undefined) {
found.push({ folder: dir === stagingDir ? repoName : basename(dir), dir })
return
}
if (depth >= 3) return
for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
if (entry.isDirectory() && entry.name !== '.git' && !entry.isSymbolicLink()) {
await collect(join(dir, entry.name), depth + 1)
}
}
}
await collect(stagingDir, 0)
if (found.length === 0) {
await rm(stagingDir, { recursive: true, force: true }).catch(() => {})
fail('no_skills_found', '仓库里没有找到技能(包含 SKILL.md 的文件夹)。')
}
const candidates: InstallPlanCandidate[] = []
for (const candidate of found) {
const markdown = await readFile(join(candidate.dir, 'SKILL.md'), 'utf8').catch(() => '')
const frontmatter = parseSkillFrontmatter(markdown)
const files = await walkFiles(candidate.dir)
const bytes = files.reduce((sum, file) => sum + file.bytes, 0)
const existing = await this.locate(candidate.folder)
let problem: string | undefined
try {
checkFolder(candidate.folder)
} catch {
problem = '目录名不合法,不能作为技能目录'
}
if (problem === undefined && files.length > MAX_SKILL_FILES) problem = `文件过多(>${MAX_SKILL_FILES})`
if (problem === undefined && bytes > MAX_SKILL_BYTES) problem = `体积过大(>${MAX_SKILL_BYTES} 字节)`
const name = frontmatter.name
candidates.push({
folder: candidate.folder,
name: typeof name === 'string' && name !== '' ? name : candidate.folder,
description: String(frontmatter.description ?? '').slice(0, 300),
files: files.length,
bytes,
scripts: files.filter((file) => file.script).map((file) => file.path).slice(0, 20),
conflict: existing !== undefined,
...(existing === undefined ? {} : { conflictLocation: existing.area }),
...(problem === undefined ? {} : { problem }),
rel: relative(stagingDir, candidate.dir),
})
}
const plan: InstallPlan = {
id: planId,
kind: 'install',
url,
createdAt: Date.now(),
expiresAt: Date.now() + PLAN_TTL_MS,
stagingDir,
candidates,
...(commit === '' ? {} : { commit }),
...(typeof options.ref === 'string' && options.ref !== '' ? { ref: options.ref } : {}),
...(options.source === undefined ? {} : { source: options.source }),
}
const file = await this.sweepPlans(await this.readPlans())
file.plans.push(plan)
await this.writePlans(file)
this.deps.log(`skill install staged: ${url} -> ${planId} (${candidates.length} candidates)`)
return {
planId,
url,
expiresAt: plan.expiresAt,
...(commit === '' ? {} : { commit }),
candidates: candidates.map((candidate) => ({ ...candidate, id: candidate.folder })) as (InstallPlanCandidate & { id: string })[],
}
}
/** Install the folders the user picked from a staged plan. */
async commitInstall(planInput: { planId?: unknown; folders?: unknown }): Promise<{
installed: string[]
skipped: { folder: string; reason: string }[]
remaining: string[]
}> {
this.guardSync()
const planId = typeof planInput.planId === 'string' ? planInput.planId : ''
if (planId === '') fail('invalid_plan', '缺少安装计划 id。')
const selection = Array.isArray(planInput.folders) ? planInput.folders : []
const file = await this.sweepPlans(await this.readPlans())
const plan = file.plans.find((item) => item.id === planId)
if (plan === undefined) {
await this.writePlans(file)
fail('plan_expired', '安装计划已过期或不存在,请重新拉取仓库。')
}
const wanted = selection.map((value) => checkFolder(value))
const installed: string[] = []
const skipped: { folder: string; reason: string }[] = []
const skillsRoot = resolve(this.deps.skillsRoot())
await mkdir(skillsRoot, { recursive: true })
for (const candidate of plan.candidates) {
if (!wanted.includes(candidate.folder)) continue
if (candidate.problem !== undefined) {
skipped.push({ folder: candidate.folder, reason: candidate.problem })
continue
}
const existing = await this.locate(candidate.folder)
if (existing !== undefined) {
skipped.push({ folder: candidate.folder, reason: existing.area === 'holding' ? 'already_exists_disabled' : 'already_exists' })
continue
}
const stagingRoot = resolve(plan.stagingDir)
const source = candidate.rel !== undefined && candidate.rel !== ''
? resolve(stagingRoot, candidate.rel)
: candidate.folder === basename(plan.stagingDir) ? stagingRoot : resolve(stagingRoot, candidate.folder)
const target = resolve(skillsRoot, candidate.folder)
// Both sides must stay inside their own root: a crafted plan file cannot
// make this write outside the skills directory.
if (!source.startsWith(stagingRoot) || !target.startsWith(`${skillsRoot}${sep}`)) {
skipped.push({ folder: candidate.folder, reason: 'path_escape' })
continue
}
await cp(source, target, {
recursive: true,
// `.git` never travels with a skill, and a link could point outside the
// repository: both are dropped rather than copied.
filter: (sourcePath) => !sourcePath.split(/[\\/]/).includes('.git') && !isSymlinkSync(sourcePath),
})
// Record provenance so the skill can later be diffed, updated and rolled
// back without the cloud center. The file holds no credentials.
if (plan.commit !== undefined && plan.commit !== '') {
const record: SkillSourceRecord = {
version: 1,
provider: plan.source?.provider ?? 'git',
repoUrl: plan.url,
ref: plan.ref ?? plan.commit,
commit: plan.commit,
sourcePath: candidate.rel ?? candidate.folder,
installedAt: new Date().toISOString(),
...(plan.source?.entryId === undefined ? {} : { entryId: plan.source.entryId }),
...(plan.source?.version === undefined ? {} : { marketVersion: plan.source.version }),
}
await writeFile(join(target, '.skill-source.json'), `${JSON.stringify(record, null, 2)}\n`, 'utf8').catch(() => {})
}
installed.push(candidate.folder)
this.deps.log(`skill installed from git: ${candidate.folder}`)
}
const remaining = plan.candidates
.filter((candidate) => !installed.includes(candidate.folder))
.map((candidate) => candidate.folder)
file.plans = file.plans.filter((item) => item.id !== planId)
await this.writePlans(file)
await rm(plan.stagingDir, { recursive: true, force: true }).catch(() => {})
return { installed, skipped, remaining }
}
/** Throw away a staged plan and its clone. */
async cancelInstall(planInput: { planId?: unknown }): Promise<{ cancelled: string }> {
const planId = typeof planInput.planId === 'string' ? planInput.planId : ''
if (planId === '') fail('invalid_plan', '缺少安装计划 id。')
const file = await this.sweepPlans(await this.readPlans())
const plan = file.plans.find((item) => item.id === planId)
file.plans = file.plans.filter((item) => item.id !== planId)
await this.writePlans(file)
if (plan !== undefined) await rm(plan.stagingDir, { recursive: true, force: true }).catch(() => {})
return { cancelled: planId }
}
/**
* Legacy one-shot install, kept for the standalone `/cloud-memory/skills`
* page: stage the repository, then install every candidate that neither
* collides with an existing skill nor trips a limit. It still never
* overwrites and never executes repository content.
*/
async installFromGit(urlInput: unknown): Promise<{ installed: string[]; skipped: { name: string; reason: string }[] }> {
const plan = await this.prepareInstall(urlInput)
const folders = plan.candidates
.filter((candidate) => candidate.conflict !== true && candidate.problem === undefined)
.map((candidate) => candidate.folder)
const result = await this.commitInstall({ planId: plan.planId, folders })
const skipped = plan.candidates
.filter((candidate) => !result.installed.includes(candidate.folder))
.map((candidate) => ({
name: candidate.folder,
reason: candidate.conflict === true
? (candidate.conflictLocation === 'holding' ? 'already_exists_disabled' : 'already_exists')
: candidate.problem ?? 'skipped',
}))
return { installed: result.installed, skipped }
}
/** Pending plans, so a reloaded page can resume a staged install. */
async listPlans(): Promise<{ plans: { planId: string; url: string; expiresAt: number; folders: string[] }[] }> { const file = await this.sweepPlans(await this.readPlans())
await this.writePlans(file)
return {
plans: file.plans.map((plan) => ({
planId: plan.id,
url: plan.url,
expiresAt: plan.expiresAt,
folders: plan.candidates.map((candidate) => candidate.folder),
})),
}
}
}

521
src/skill-groups.ts Normal file
View File

@ -0,0 +1,521 @@
/**
* Multi-source skill tree.
*
* The card groups skills the way the user thinks about them: by the software
* that owns the directory (DSH, 公共 Agent, Codex, WorkBuddy, …), then by
* user-defined categories inside that source.
*
* Two rules keep this honest:
*
* 1. A category is metadata only. Creating, renaming or deleting one never
* moves or removes a skill file; deleting a category just sends its skills
* back to 未分类. That is what the "分类只记在这个来源里,不移动文件" note
* promises, and it is the only reason a delete button is safe here.
* 2. Only the DSH source is ours to switch. Parking a DSH skill is the same
* directory move the rest of the plugin uses. Another software's directory
* is never touched: its switch is recorded for this card only and the view
* says so, instead of pretending Codex stopped loading something.
*/
import { execFile } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
import { readdir, readFile } from 'node:fs/promises'
import { homedir } from 'node:os'
import { join, resolve } from 'node:path'
import { dshHome } from './store.ts'
import type { SkillAdmin, SkillEntry } from './skill-admin.ts'
/** One directory the tree can show. */
export interface SkillSourceDef {
id: string
label: string
root: string
/** True only for the source this plugin may move folders in. */
writable: boolean
/** Who owns the directory, for the row's explanation. */
manager: string
/** Short reason shown next to the switch when the source is read-only. */
note?: string
}
/** A skill as one tree leaf. */
export interface TreeSkill {
folder: string
name: string
description: string
enabled: boolean
enabledEditable: boolean
files: number
bytes: number
origin?: string
revision?: number
inCardDisabled: boolean
}
export interface TreeGroup {
id: string
name: string
enabled: boolean
/** False when the switch only applies to this card (foreign source). */
enabledEditable: boolean
/** True when the switch was recorded here but does not affect the owner. */
cardOnly: boolean
total: number
enabledCount: number
skills: TreeSkill[]
}
export interface TreeSource {
id: string
label: string
root: string
exists: boolean
writable: boolean
manager: string
note?: string
enabled: boolean
enabledEditable: boolean
cardOnly: boolean
total: number
enabledCount: number
groups: TreeGroup[]
}
/** Persisted sidecar: source switches plus category membership. */
interface GroupsFile {
version: 1
sources: Record<string, { enabled?: boolean; groups?: { id: string; name: string; enabled?: boolean; skills: string[] }[] }>
}
const MAX_GROUP_NAME = 40
const MAX_GROUPS_PER_SOURCE = 40
/** Sidecar path. */
export function skillGroupsPath(): string {
return join(dshHome(), 'cloud-memory-skill-groups.json')
}
/**
* The known sources.
*
* A source is listed even when its directory is missing (0 skills, "未安装"),
* because that is how a user learns the software exists; it is never invented
* as present.
*/
export function detectSources(): SkillSourceDef[] {
const home = homedir()
return [
{ id: 'dsh', label: 'DSH', root: join(dshHome(), 'skills'), writable: true, manager: 'DSH' },
{
id: 'agents',
label: '公共 Agent',
root: join(home, '.agents', 'skills'),
writable: false,
manager: '公共 Agent 约定目录',
note: '由使用该目录的各客户端自行加载,本卡只读',
},
{
id: 'codex',
label: 'Codex',
root: join(home, '.codex', 'skills'),
writable: false,
manager: 'Codex',
note: '由 Codex 自行加载,本卡不修改它的目录',
},
{
id: 'workbuddy',
label: 'WorkBuddy',
root: join(home, '.workbuddy', 'skills'),
writable: false,
manager: 'WorkBuddy',
note: '由 WorkBuddy 自行加载,本卡不修改它的目录',
},
{
id: 'claude',
label: 'Claude Code',
root: join(home, '.claude', 'skills'),
writable: false,
manager: 'Claude Code',
note: '由 Claude Code 自行加载,本卡不修改它的目录',
},
{
id: 'opencode',
label: 'OpenCode',
root: join(home, '.config', 'opencode', 'skills'),
writable: false,
manager: 'OpenCode',
note: '由 OpenCode 自行加载,本卡不修改它的目录',
},
]
}
function groupId(): string {
return `g_${randomUUID().slice(0, 8)}`
}
/** Trim and bound one user-supplied category name. */
function cleanGroupName(value: unknown): string {
const name = typeof value === 'string' ? value.trim() : ''
if (name === '' || name.length > MAX_GROUP_NAME) {
throw new SkillGroupError('invalid_name', '分类名需要 1–40 个字符。')
}
return name
}
/** A group failure with a stable code, mapped to an HTTP status by the route. */
export class SkillGroupError extends Error {
code: string
constructor(code: string, message: string) {
super(message)
this.code = code
this.name = 'SkillGroupError'
}
}
export interface SkillGroupDeps {
sources: () => SkillSourceDef[]
admin: SkillAdmin
storePath?: () => string
log?: (message: string) => void
}
/** Read one skill directory without following links. */
async function readSkill(root: string, folder: string): Promise<TreeSkill | undefined> {
const dir = join(root, folder)
try {
const info = statSync(dir)
if (!info.isDirectory()) return undefined
} catch {
return undefined
}
const markdown = await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined)
if (markdown === undefined) return undefined
const frontmatter = /^---\s*([\s\S]*?)\s*---/.exec(markdown)
const name = frontmatter === null ? '' : (/^name:\s*(.+)$/m.exec(frontmatter[1] ?? '')?.[1] ?? '').trim()
const description = frontmatter === null ? '' : (/^description:\s*(.+)$/m.exec(frontmatter[1] ?? '')?.[1] ?? '').trim()
let files = 0
let bytes = 0
const walk = async (sub: string): Promise<void> => {
if (files > 2000) return
for (const entry of await readdir(join(dir, sub), { withFileTypes: true }).catch(() => [])) {
if (entry.name === '.git') continue
const rel = sub === '' ? entry.name : `${sub}/${entry.name}`
if (entry.isDirectory()) {
await walk(rel)
continue
}
if (!entry.isFile()) continue
files += 1
try {
bytes += statSync(join(dir, rel)).size
} catch {
// A file removed mid-walk only affects the size hint.
}
}
}
await walk('')
return {
folder,
name: name === '' ? folder : name,
description: description.slice(0, 300),
enabled: true,
enabledEditable: false,
files,
bytes,
inCardDisabled: false,
}
}
/** List the folders of one source that look like skills. */
async function readSource(root: string): Promise<TreeSkill[]> {
const skills: TreeSkill[] = []
for (const entry of await readdir(root, { withFileTypes: true }).catch(() => [])) {
if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name.startsWith('_')) continue
const skill = await readSkill(root, entry.name)
if (skill !== undefined) skills.push(skill)
}
skills.sort((a, b) => (a.folder < b.folder ? -1 : 1))
return skills
}
export class SkillGroupManager {
private readonly deps: SkillGroupDeps
constructor(deps: SkillGroupDeps) {
this.deps = deps
}
private file(): string {
return this.deps.storePath?.() ?? skillGroupsPath()
}
private read(): GroupsFile {
try {
const parsed: unknown = JSON.parse(readFileSync(this.file(), 'utf8'))
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
const doc = parsed as GroupsFile
if (doc.sources !== null && typeof doc.sources === 'object') return { version: 1, sources: doc.sources }
}
} catch {
// Missing or torn sidecar: start from "everything unassigned".
}
return { version: 1, sources: {} }
}
private write(next: GroupsFile): void {
const path = this.file()
mkdirSync(resolve(path, '..'), { recursive: true })
const temporary = `${path}.tmp`
writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
renameSync(temporary, path)
}
private source(id: unknown): SkillSourceDef {
const sourceId = typeof id === 'string' ? id : ''
const found = this.deps.sources().find((source) => source.id === sourceId)
if (found === undefined) throw new SkillGroupError('unknown_source', `未知来源:${String(id)}`)
return found
}
/** Skills of one source, with this plugin's own enable state for DSH. */
private async skillsOf(source: SkillSourceDef): Promise<TreeSkill[]> {
if (source.writable) {
const inventory = await this.deps.admin.list()
return inventory.skills.map((skill: SkillEntry) => ({
folder: skill.folder,
name: skill.name,
description: skill.description,
enabled: skill.enabled,
enabledEditable: true,
files: skill.files,
bytes: skill.bytes,
origin: skill.origin,
...(skill.revision === undefined ? {} : { revision: skill.revision }),
inCardDisabled: false,
}))
}
return readSource(source.root)
}
/** Everything the tree renders: sources → groups → skills. */
async overview(): Promise<{ sources: TreeSource[]; note: string }> {
const doc = this.read()
const sources: TreeSource[] = []
for (const source of this.deps.sources()) {
const skills = await this.skillsOf(source)
const state = doc.sources[source.id] ?? {}
const groups = Array.isArray(state.groups) ? state.groups : []
const assigned = new Set<string>()
const views: TreeGroup[] = []
for (const group of groups) {
const members = skills.filter((skill) => group.skills.includes(skill.folder))
for (const member of members) assigned.add(member.folder)
const enabled = group.enabled !== false
// A group switch is real only where the source is real.
const cardOnly = !source.writable
views.push({
id: group.id,
name: group.name,
enabled,
enabledEditable: true,
cardOnly,
total: members.length,
enabledCount: members.filter((skill) => skill.enabled && enabled).length,
skills: members.map((skill) => ({ ...skill, enabled: skill.enabled && enabled, inCardDisabled: enabled === false })),
})
}
const rest = skills.filter((skill) => !assigned.has(skill.folder))
views.push({
id: 'unassigned',
name: '未分类',
// The bucket's own switch is "every skill that has no category": it is
// on only when all of them are, and switching it parks/restores them
// one by one like any other group.
enabled: rest.length === 0 || rest.every((skill) => skill.enabled),
enabledEditable: rest.length > 0,
cardOnly: !source.writable,
total: rest.length,
enabledCount: rest.filter((skill) => skill.enabled).length,
skills: rest,
})
const sourceEnabled = state.enabled !== false
sources.push({
id: source.id,
label: source.label,
root: source.root,
exists: existsSync(source.root),
writable: source.writable,
manager: source.manager,
...(source.note === undefined ? {} : { note: source.note }),
enabled: sourceEnabled,
enabledEditable: true,
cardOnly: !source.writable,
total: skills.length,
enabledCount: skills.filter((skill) => skill.enabled && sourceEnabled).length,
groups: views,
})
}
return {
sources,
note: '分类只记在这个来源里,不移动文件。只有 DSH 来源的开关会真实启停技能目录;其他软件的目录本卡不修改。',
}
}
/** Create one category inside a source. */
async createGroup(sourceInput: unknown, nameInput: unknown): Promise<{ groupId: string; name: string }> {
const source = this.source(sourceInput)
const name = cleanGroupName(nameInput)
const doc = this.read()
const state = doc.sources[source.id] ?? {}
const groups = state.groups ?? []
if (groups.length >= MAX_GROUPS_PER_SOURCE) throw new SkillGroupError('too_many', `每个来源最多 ${MAX_GROUPS_PER_SOURCE} 个分类。`)
if (groups.some((group) => group.name === name)) throw new SkillGroupError('duplicate', `这个来源里已经有分类「${name}」。`)
const id = groupId()
doc.sources[source.id] = { ...state, groups: [...groups, { id, name, enabled: true, skills: [] }] }
this.write(doc)
this.deps.log?.(`skill category created: ${source.id}/${name}`)
return { groupId: id, name }
}
/** Rename one category; membership and files are untouched. */
async renameGroup(sourceInput: unknown, groupInput: unknown, nameInput: unknown): Promise<{ groupId: string; name: string }> {
const source = this.source(sourceInput)
const id = typeof groupInput === 'string' ? groupInput : ''
const name = cleanGroupName(nameInput)
const doc = this.read()
const state = doc.sources[source.id] ?? {}
const groups = state.groups ?? []
const target = groups.find((group) => group.id === id)
if (target === undefined) throw new SkillGroupError('not_found', '没有找到这个分类。')
if (groups.some((group) => group.name === name && group.id !== id)) {
throw new SkillGroupError('duplicate', `这个来源里已经有分类「${name}」。`)
}
target.name = name
doc.sources[source.id] = { ...state, groups }
this.write(doc)
return { groupId: id, name }
}
/**
* Delete one category. Its skills move back to 未分类; no file is touched,
* which is why this needs no impact plan of its own.
*/
async deleteGroup(sourceInput: unknown, groupInput: unknown): Promise<{ groupId: string; released: number }> {
const source = this.source(sourceInput)
const id = typeof groupInput === 'string' ? groupInput : ''
const doc = this.read()
const state = doc.sources[source.id] ?? {}
const groups = state.groups ?? []
const target = groups.find((group) => group.id === id)
if (target === undefined) throw new SkillGroupError('not_found', '没有找到这个分类。')
doc.sources[source.id] = { ...state, groups: groups.filter((group) => group.id !== id) }
this.write(doc)
this.deps.log?.(`skill category removed: ${source.id}/${target.name}`)
return { groupId: id, released: target.skills.length }
}
/** Move skills into (or out of) a category. Membership only. */
async assign(sourceInput: unknown, groupInput: unknown, foldersInput: unknown): Promise<{ groupId: string; members: string[] }> {
const source = this.source(sourceInput)
const id = typeof groupInput === 'string' ? groupInput : ''
const folders = Array.isArray(foldersInput)
? foldersInput.filter((value): value is string => typeof value === 'string' && value !== '' && !value.includes('/') && !value.includes('\\'))
: []
const doc = this.read()
const state = doc.sources[source.id] ?? {}
const groups = state.groups ?? []
if (id === 'unassigned' || folders.length === 0) {
// Clearing a selection means "back to 未分类" for every other group.
for (const group of groups) group.skills = group.skills.filter((folder) => !folders.includes(folder))
doc.sources[source.id] = { ...state, groups }
this.write(doc)
return { groupId: 'unassigned', members: [] }
}
const target = groups.find((group) => group.id === id)
if (target === undefined) throw new SkillGroupError('not_found', '没有找到这个分类。')
// A skill belongs to at most one category: remove it everywhere else first.
for (const group of groups) {
if (group === target) continue
group.skills = group.skills.filter((folder) => !folders.includes(folder))
}
target.skills = [...new Set([...target.skills, ...folders])].sort()
doc.sources[source.id] = { ...state, groups }
this.write(doc)
return { groupId: id, members: target.skills }
}
/**
* Switch one category on or off.
*
* DSH groups are really parked or restored, one folder at a time, and a
* failure leaves the remaining folders untouched. Foreign groups only record
* the switch here, and the answer says `cardOnly: true`.
*/
async toggleGroup(sourceInput: unknown, groupInput: unknown, enabled: boolean): Promise<{ groupId: string; enabled: boolean; cardOnly: boolean; applied: string[]; failed: { folder: string; reason: string }[] }> {
const source = this.source(sourceInput)
const id = typeof groupInput === 'string' ? groupInput : ''
const doc = this.read()
const state = doc.sources[source.id] ?? {}
const groups = state.groups ?? []
let targets: string[] = []
if (id === 'unassigned') {
// "未分类" is the bucket of everything no category claims; its switch
// applies to exactly those skills and is not persisted.
const assigned = new Set(groups.flatMap((group) => group.skills))
const skills = await this.skillsOf(source)
targets = skills.filter((skill) => !assigned.has(skill.folder)).map((skill) => skill.folder)
if (!source.writable) return { groupId: id, enabled, cardOnly: true, applied: [], failed: [] }
} else {
const target = groups.find((group) => group.id === id)
if (target === undefined) throw new SkillGroupError('not_found', '没有找到这个分类。')
target.enabled = enabled
doc.sources[source.id] = { ...state, groups }
this.write(doc)
if (!source.writable) return { groupId: id, enabled, cardOnly: true, applied: [], failed: [] }
targets = target.skills
}
const applied: string[] = []
const failed: { folder: string; reason: string }[] = []
for (const folder of targets) {
try {
await this.deps.admin.setEnabled(folder, enabled)
applied.push(folder)
} catch (failure) {
failed.push({ folder, reason: failure instanceof Error ? failure.message : String(failure) })
}
}
return { groupId: id, enabled, cardOnly: false, applied, failed }
}
/** Switch a whole source. DSH really moves every skill; others record it. */
async toggleSource(sourceInput: unknown, enabled: boolean): Promise<{ sourceId: string; enabled: boolean; cardOnly: boolean; applied: number; failed: { folder: string; reason: string }[] }> {
const source = this.source(sourceInput)
const doc = this.read()
const state = doc.sources[source.id] ?? {}
doc.sources[source.id] = { ...state, enabled }
this.write(doc)
if (!source.writable) return { sourceId: source.id, enabled, cardOnly: true, applied: 0, failed: [] }
const skills = await this.skillsOf(source)
const failed: { folder: string; reason: string }[] = []
let applied = 0
for (const skill of skills) {
try {
await this.deps.admin.setEnabled(skill.folder, enabled)
applied += 1
} catch (failure) {
failed.push({ folder: skill.folder, reason: failure instanceof Error ? failure.message : String(failure) })
}
}
return { sourceId: source.id, enabled, cardOnly: false, applied, failed }
}
/** Open one source directory in the OS file manager (explicit user click). */
async reveal(sourceInput: unknown): Promise<{ path: string }> {
const source = this.source(sourceInput)
if (!existsSync(source.root)) throw new SkillGroupError('not_found', `${source.label} 的技能目录还不存在:${source.root}`)
const command = process.platform === 'win32' ? 'explorer.exe' : process.platform === 'darwin' ? 'open' : 'xdg-open'
await new Promise<void>((resolvePromise) => {
execFile(command, [source.root], { windowsHide: false }, () => resolvePromise())
})
return { path: source.root }
}
}

View File

@ -30,7 +30,7 @@
* silently trimmed.
*/
import { createHash, randomUUID } from 'node:crypto'
import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'
import { mkdir, cp, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'
import { dirname, join, resolve } from 'node:path'
import type { CloudClient, SkillBundle, SkillSummary, SkillUploadFile } from './api.ts'
import { describeError } from './api.ts'
@ -562,4 +562,201 @@ export class SkillSync {
hasScripts: files.some((file) => file.rel.startsWith('scripts/')),
}
}
/** Encode local files exactly the way the upload path does. */
private toUploadFiles(files: LocalFile[]): SkillUploadFile[] {
return files.map((file) => {
const ext = file.rel.slice(file.rel.lastIndexOf('.')).toLowerCase()
return TEXT_EXT.has(ext)
? { path: file.rel, content: file.buffer.toString('utf8') }
: { path: file.rel, base64: file.buffer.toString('base64') }
})
}
/** Drop one name from the in-memory conflict list after it is resolved. */
private dropConflict(name: string): void {
this.current = { ...this.current, conflicts: this.current.conflicts.filter((conflict) => conflict.name !== name) }
}
/**
* Both sides of every conflict from the last pass, so a human can decide.
* Read-only: it never changes a file or uploads anything.
*/
async conflictDetails(): Promise<SyncConflictDetail[]> {
const conflicts = this.current.conflicts
if (conflicts.length === 0) return []
let cloudItems: (SkillSummary & { name: string })[] = []
try {
const listing = await this.deps.client().listSkills()
if (listing.ok) {
cloudItems = (listing.data.items ?? []).filter(
(item): item is SkillSummary & { name: string } => typeof item.name === 'string',
)
}
} catch {
// Listing failed: still show the local side with a null cloud side.
}
const byName = new Map(cloudItems.map((item) => [item.name, item]))
const out: SyncConflictDetail[] = []
for (const conflict of conflicts) {
const rootDir = join(this.skillsRoot(), conflict.name)
const parkedDir = join(this.holdingRoot(), conflict.name)
let location: 'root' | 'holding' | 'none' = 'none'
let dir = ''
if (await isDirectory(rootDir)) { location = 'root'; dir = rootDir }
else if (await isDirectory(parkedDir)) { location = 'holding'; dir = parkedDir }
let files = 0
let bytes = 0
let modified = false
if (dir !== '') {
try {
const local = await this.readSkillFiles(dir)
files = local.length
bytes = local.reduce((sum, file) => sum + file.buffer.length, 0)
const delivery = await this.readDelivery(dir)
modified = delivery === undefined ? true : !(await this.deliveredIntact(dir, delivery))
} catch {
// Unreadable folder: report zeroed counts, never throw the list away.
}
}
const cloudItem = byName.get(conflict.name)
out.push({
name: conflict.name,
reason: conflict.reason,
local: { exists: location !== 'none', location, files, bytes, modified },
cloud: cloudItem === undefined
? null
: {
...(cloudItem.revision === undefined ? {} : { revision: cloudItem.revision }),
...(cloudItem.manifest_sha256 === undefined ? {} : { manifest: cloudItem.manifest_sha256 }),
...(cloudItem.files === undefined ? {} : { files: cloudItem.files }),
...(cloudItem.bytes === undefined ? {} : { bytes: cloudItem.bytes }),
...(cloudItem.enabled === undefined ? {} : { enabled: cloudItem.enabled }),
},
canKeepLocal: location !== 'none',
canTakeCloud: cloudItem !== undefined,
note: '“保留本地”把本地版本上传成新的云端版本;“采用云端”先备份本地再覆盖;“手动合并”只返回两侧信息,不改文件。',
})
}
return out
}
/** Resolve one conflict: keep local / take cloud / manual (no write). */
async resolveConflict(nameInput: unknown, actionInput: unknown): Promise<SyncResolveResult> {
const name = typeof nameInput === 'string' ? nameInput : ''
if (name === '' || !CLOUD_SKILL_NAME.test(name)) throw new Error('invalid_name')
const action = actionInput === 'keep_local' || actionInput === 'take_cloud' || actionInput === 'manual' ? actionInput : ''
if (action === '') throw new Error('invalid_action')
if (this.running) throw new Error('sync_running')
const root = this.skillsRoot()
const rootDir = join(root, name)
const parkedDir = join(this.holdingRoot(), name)
const inRoot = await isDirectory(rootDir)
const parked = !inRoot && (await isDirectory(parkedDir))
const dir = inRoot ? rootDir : parked ? parkedDir : ''
const client = this.deps.client()
const listing = await client.listSkills()
if (!listing.ok) throw new Error(`skill listing failed: ${describeError(listing.error)}`)
const cloud = (listing.data.items ?? []).find((item) => item.name === name)
const state = await this.loadState()
if (action === 'manual') {
return {
name,
action,
applied: false,
note: '已返回两侧信息,未改动任何文件;手工编辑后在下次同步前保存即可。',
...(cloud?.revision === undefined ? {} : { revision: cloud.revision }),
}
}
if (action === 'keep_local') {
if (dir === '') throw new Error('no_local_copy')
const skill = await this.readLocalSkill(dir, name)
if (skill === undefined) throw new Error('not_a_skill')
if (typeof skill === 'string') throw new Error(skill)
const files = this.toUploadFiles(skill.files)
const operationId = `dsh-skill-${randomUUID()}`
if (cloud === undefined) {
const created = await client.createSkill({
name: skill.name,
description: skill.description,
execution_mode: skill.hasScripts ? 'local-bundle' : 'prompt-only',
files,
expected_revision: 0,
operation_id: operationId,
})
if (!created.ok) throw new Error(`upload_failed: ${describeError(created.error)}`)
const revision = created.data.skill?.revision ?? created.data.revision ?? 1
state.uploaded[name] = { folder: name, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() }
delete state.removed[name]
await this.saveState(state)
this.dropConflict(name)
return { name, action, applied: true, revision, note: '已把本地版本新建到云端。' }
}
const updated = await client.updateSkill(name, {
description: skill.description,
files,
expected_revision: cloud.revision ?? 0,
operation_id: operationId,
})
if (!updated.ok) {
if (updated.error.code === 'revision_conflict') throw new Error('stale_revision')
throw new Error(`upload_failed: ${describeError(updated.error)}`)
}
const revision = updated.data.skill?.revision ?? updated.data.revision ?? (cloud.revision ?? 0) + 1
state.uploaded[name] = { folder: name, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() }
delete state.removed[name]
await this.saveState(state)
this.dropConflict(name)
return { name, action, applied: true, revision, note: '已用本地版本覆盖云端(revision 已更新)。' }
}
// take_cloud
if (cloud === undefined) throw new Error('no_cloud_copy')
const bundle = await client.skillBundle(name)
if (!bundle.ok) throw new Error(`bundle_failed: ${describeError(bundle.error)}`)
if (linkedSkillManifest(bundle.data.files) !== bundle.data.manifest_sha256) throw new Error('manifest_mismatch')
let backup = ''
if (dir !== '') {
const stamp = new Date().toISOString().replace(/[:.]/g, '-')
backup = join(dshHome(), '.cloud-memory-backups', 'sync', name, stamp)
await mkdir(join(backup, '..'), { recursive: true })
await cp(dir, backup, { recursive: true, filter: (p) => !p.split(/[\\/]/).includes('.git') })
}
await this.install(cloud, bundle.data, parked ? this.holdingRoot() : root)
state.delivered[name] = { manifest: bundle.data.manifest_sha256 }
delete state.removed[name]
await this.saveState(state)
this.dropConflict(name)
return {
name,
action,
applied: true,
revision: bundle.data.revision,
...(backup === '' ? {} : { backup }),
note: '已采用云端版本覆盖本地(本地已备份)。',
}
}
}
/** One conflict with both sides, for the resolve UI. */
export interface SyncConflictDetail {
name: string
reason: string
local: { exists: boolean; location: 'root' | 'holding' | 'none'; files: number; bytes: number; modified: boolean }
cloud: { revision?: number; manifest?: string; files?: number; bytes?: number; enabled?: boolean } | null
canKeepLocal: boolean
canTakeCloud: boolean
note: string
}
/** Outcome of one conflict resolution. */
export interface SyncResolveResult {
name: string
action: 'keep_local' | 'take_cloud' | 'manual'
applied: boolean
revision?: number
backup?: string
note: string
}

329
src/skill-update.ts Normal file
View File

@ -0,0 +1,329 @@
/**
* Skill update & rollback (P3).
*
* Works only for skills that carry a `.skill-source.json` provenance record
* (written by the market / git install pipeline). Nothing here talks to the
* cloud center: it re-reads the pinned git source, shows a diff, keeps a local
* backup before touching the folder, and restores that backup on rollback.
*
* Safety rules baked in:
* - the source record is the only thing trusted for a repository URL;
* - a fresh clone happens in `$DSH_HOME/.cloud-memory-staging` and the copy is
* filtered (no `.git`, no symlinks);
* - a backup is always taken before an update so rollback is possible even
* when the update is interrupted;
* - a repository in-flight sync blocks any write.
*/
import { execFile } from 'node:child_process'
import { lstatSync } from 'node:fs'
import { createHash } from 'node:crypto'
import { cp, lstat, mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises'
import { join, resolve } from 'node:path'
import { tmpdir } from 'node:os'
import type { SkillAdmin, SkillSourceRecord } from './skill-admin.ts'
import { readSkillSourceRecord, SkillAdminError } from './skill-admin.ts'
import { dshHome } from './store.ts'
/** Where pre-update backups are kept (one folder per skill, one dir per run). */
export function skillBackupsDir(): string {
return join(dshHome(), '.cloud-memory-backups')
}
/** One file on disk with its hash, used for diffing two trees. */
interface FileHash {
path: string
sha256: string
bytes: number
}
/** Result of comparing the installed folder to the source's latest commit. */
export interface UpdateCheck {
folder: string
updatable: boolean
reason?: string
provider?: string
repoUrl?: string
currentCommit?: string
remoteCommit?: string
available: boolean
added?: string[]
removed?: string[]
changed?: string[]
fetchedAt: number
}
/** Result of applying an update or a rollback. */
export interface UpdateResult {
folder: string
from: string
to: string
backup: string
added: string[]
removed: string[]
changed: string[]
}
/** Run git and return stdout. */
function git(args: string[], timeoutMs = 120_000): Promise<string> {
return new Promise<string>((resolvePromise, rejectPromise) => {
execFile(
'git',
args,
{ timeout: timeoutMs, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' }, maxBuffer: 8 * 1024 * 1024 },
(error, stdout) => (error ? rejectPromise(error) : resolvePromise(String(stdout))),
)
})
}
async function isSymlink(path: string): Promise<boolean> {
return lstat(path).then((s) => s.isSymbolicLink()).catch(() => true)
}
/** Hash every regular file under one directory (skips `.git` and symlinks). */
async function hashTree(dir: string): Promise<Map<string, FileHash>> {
const out = new Map<string, FileHash>()
const walk = async (sub: string): Promise<void> => {
for (const entry of await readdir(join(dir, sub), { withFileTypes: true }).catch(() => [])) {
if (entry.name === '.git') continue
const rel = sub === '' ? entry.name : `${sub}/${entry.name}`
const abs = join(dir, rel)
if (entry.isSymbolicLink()) continue
if (entry.isDirectory()) {
await walk(rel)
continue
}
if (!entry.isFile()) continue
const buffer = await readFile(abs).catch(() => undefined)
if (buffer === undefined) continue
out.set(rel, { path: rel, sha256: createHash('sha256').update(buffer).digest('hex'), bytes: buffer.byteLength })
}
}
await walk('')
return out
}
/** A short human bucket for what changed. */
function diffTrees(before: Map<string, FileHash>, after: Map<string, FileHash>): { added: string[]; removed: string[]; changed: string[] } {
const added: string[] = []
const removed: string[] = []
const changed: string[] = []
for (const [path, file] of after) {
const old = before.get(path)
if (old === undefined) added.push(path)
else if (old.sha256 !== file.sha256) changed.push(path)
}
for (const path of before.keys()) if (!after.has(path)) removed.push(path)
added.sort(); removed.sort(); changed.sort()
return { added, removed, changed }
}
/** Copy a skill tree, dropping `.git` and symlinks (same rule as install). */
async function copySkillTree(source: string, target: string): Promise<void> {
await cp(source, target, {
recursive: true,
filter: (path) => !path.split(/[\\/]/).includes('.git') && (() => {
try {
return !lstatSync(path).isSymbolicLink()
} catch {
return false
}
})(),
})
}
export interface SkillUpdaterDeps {
admin: SkillAdmin
skillsRoot: () => string
holdingDir: () => string
backupsDir?: () => string
syncRunning: () => boolean
log: (message: string) => void
}
export class SkillUpdater {
private readonly deps: SkillUpdaterDeps
constructor(deps: SkillUpdaterDeps) {
this.deps = deps
}
private backupsRoot(): string {
return this.deps.backupsDir?.() ?? skillBackupsDir()
}
private guard(): void {
if (this.deps.syncRunning()) throw new SkillAdminError('sync_running', '技能同步正在进行,请稍候再试。')
}
private async find(folder: string): Promise<{ dir: string; source: SkillSourceRecord }> {
const found = await this.deps.admin.locate(folder)
if (found === undefined) throw new SkillAdminError('not_found', `没有找到技能:${folder}`)
const source = await readSkillSourceRecord(found.dir)
if (source === undefined) {
throw new SkillAdminError('no_source', `该技能没有来源记录(不是从 Git 或市场安装的),无法更新或回退。`)
}
return { dir: found.dir, source }
}
/** Clone the pinned source at its latest commit into a scratch directory. */
private async cloneLatest(source: SkillSourceRecord): Promise<{ dir: string; commit: string; cleanup: () => Promise<void> }> {
const root = join(dshHome(), '.cloud-memory-staging')
await mkdir(root, { recursive: true })
const dir = join(root, `update_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`)
try {
await git(['clone', '--depth', '1', '--no-tags', '--', source.repoUrl, dir])
// A commit SHA is a pin, not a moving ref: leave the default-branch head
// in place so an update check compares against the latest upstream. A
// branch/tag name is fetched and checked out instead.
const isSha = /^[0-9a-f]{7,40}$/i.test(source.ref)
if (!isSha && source.ref !== '') {
try {
await git(['-C', dir, 'fetch', '--depth', '1', 'origin', source.ref])
await git(['-C', dir, 'checkout', '--detach', 'FETCH_HEAD'])
} catch {
// Fall back to the default branch head.
}
}
} catch (error) {
await rm(dir, { recursive: true, force: true }).catch(() => {})
const code = (error as NodeJS.ErrnoException).code
throw new SkillAdminError('git_failed', code === 'ENOENT'
? '本机没有 git 命令,无法检查更新。'
: '无法读取来源仓库(地址不可达、需要登录,或仓库已删除)。')
}
const commit = (await git(['-C', dir, 'rev-parse', 'HEAD'], 20_000)).trim()
return { dir, commit, cleanup: () => rm(dir, { recursive: true, force: true }).catch(() => {}) }
}
/** Compare the installed folder against the source's latest commit. */
async checkUpdate(folderInput: unknown): Promise<UpdateCheck> {
const folder = typeof folderInput === 'string' ? folderInput : ''
if (folder === '') throw new SkillAdminError('invalid_name', '缺少技能目录名。')
const fetchedAt = Date.now()
const found = await this.deps.admin.locate(folder)
if (found === undefined) throw new SkillAdminError('not_found', `没有找到技能:${folder}`)
const source = await readSkillSourceRecord(found.dir)
if (source === undefined) {
return { folder, updatable: false, reason: 'no_source', available: false, fetchedAt }
}
const clone = await this.cloneLatest(source)
try {
if (clone.commit === source.commit) {
return {
folder, updatable: true, available: false, provider: source.provider,
repoUrl: source.repoUrl, currentCommit: source.commit, remoteCommit: clone.commit, fetchedAt,
}
}
const remoteDir = source.sourcePath === '' ? clone.dir : resolve(clone.dir, source.sourcePath)
const before = await hashTree(found.dir)
const after = await hashTree(remoteDir)
// The provenance file is ours, not the source's: never show it as removed.
before.delete('.skill-source.json')
const diff = diffTrees(before, after)
return {
folder, updatable: true, available: true, provider: source.provider,
repoUrl: source.repoUrl, currentCommit: source.commit, remoteCommit: clone.commit,
...diff, fetchedAt,
}
} finally {
await clone.cleanup()
}
}
/** Back up the current folder, then replace it with the source's latest. */
async applyUpdate(folderInput: unknown, expectedCommit?: unknown): Promise<UpdateResult> {
this.guard()
const folder = typeof folderInput === 'string' ? folderInput : ''
if (folder === '') throw new SkillAdminError('invalid_name', '缺少技能目录名。')
const { dir, source } = await this.find(folder)
const check = await this.checkUpdate(folder)
if (!check.available) throw new SkillAdminError('up_to_date', '已经是最新版本,无需更新。')
if (typeof expectedCommit === 'string' && expectedCommit !== '' && check.remoteCommit !== expectedCommit) {
throw new SkillAdminError('stale_plan', '来源在上次检查后已更新,请重新检查差异再更新。')
}
return this.replaceWith(dir, source, { commit: check.remoteCommit ?? source.commit, ref: source.ref })
}
/** Restore the most recent pre-update backup. */
async rollback(folderInput: unknown): Promise<UpdateResult> {
this.guard()
const folder = typeof folderInput === 'string' ? folderInput : ''
if (folder === '') throw new SkillAdminError('invalid_name', '缺少技能目录名。')
const { dir, source } = await this.find(folder)
const root = join(this.backupsRoot(), folder)
const entries = (await readdir(root, { withFileTypes: true }).catch(() => []))
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name)
.sort()
const latest = entries[entries.length - 1]
if (latest === undefined) throw new SkillAdminError('no_backup', '没有可回退的备份。')
const backupDir = join(root, latest)
const restored = await readSkillSourceRecord(backupDir)
// Restore in place: move the current aside, copy the backup over, then drop
// the aside copy only after the backup has landed.
const aside = `${dir}.rollbacking-${Date.now().toString(36)}`
await mkdir(join(dir, '..'), { recursive: true })
await rename(dir, aside)
try {
await copySkillTree(backupDir, dir)
} catch (error) {
await rm(dir, { recursive: true, force: true }).catch(() => {})
await rename(aside, dir).catch(() => {})
throw new SkillAdminError('rollback_failed', `回退失败,原目录已尽量还原:${error instanceof Error ? error.message : String(error)}`)
}
await rm(aside, { recursive: true, force: true }).catch(() => {})
this.deps.log(`skill rolled back: ${folder} <- ${latest}`)
const beforeFiles = await hashTree(backupDir)
beforeFiles.delete('.skill-source.json')
const nowFiles = await hashTree(dir)
nowFiles.delete('.skill-source.json')
const diff = diffTrees(nowFiles, beforeFiles)
return {
folder,
from: source.commit,
to: restored?.commit ?? source.commit,
backup: backupDir,
...diff,
}
}
/** Shared write path: backup, copy new tree, rewrite provenance. */
private async replaceWith(dir: string, source: SkillSourceRecord, next: { commit: string; ref: string }): Promise<UpdateResult> {
const clone = await this.cloneLatest({ ...source, ref: next.ref })
let newDir = source.sourcePath === '' ? clone.dir : resolve(clone.dir, source.sourcePath)
try {
if (clone.commit !== next.commit) {
// A different head landed between check and apply: refuse, never guess.
throw new SkillAdminError('stale_plan', '来源在更新过程中已变化,请重新检查。')
}
const stamp = new Date().toISOString().replace(/[:.]/g, '-')
const backupDir = join(this.backupsRoot(), this.lastSegment(dir), stamp)
await mkdir(join(backupDir, '..'), { recursive: true })
await copySkillTree(dir, backupDir)
const before = await hashTree(dir)
const after = await hashTree(newDir)
const diff = diffTrees(before, after)
const aside = `${dir}.updating-${Date.now().toString(36)}`
await rename(dir, aside)
try {
await copySkillTree(newDir, dir)
await writeFile(join(dir, '.skill-source.json'), `${JSON.stringify({
...source, commit: next.commit, ref: next.ref, installedAt: new Date().toISOString(),
} satisfies SkillSourceRecord, null, 2)}\n`, 'utf8')
} catch (error) {
await rm(dir, { recursive: true, force: true }).catch(() => {})
await rename(aside, dir).catch(() => {})
throw new SkillAdminError('update_failed', `更新失败,原目录已还原:${error instanceof Error ? error.message : String(error)}`)
}
await rm(aside, { recursive: true, force: true }).catch(() => {})
this.deps.log(`skill updated: ${this.lastSegment(dir)} -> ${next.commit}`)
return { folder: this.lastSegment(dir), from: source.commit, to: next.commit, backup: backupDir, ...diff }
} finally {
await clone.cleanup()
}
}
private lastSegment(path: string): string {
const parts = path.split(/[\\/]/).filter((part) => part !== '')
return parts[parts.length - 1] ?? path
}
}

View File

@ -14,7 +14,7 @@
import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync, chmodSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { homedir } from 'node:os'
import { DEFAULT_SETTINGS, normalizeBaseUrl, settingsFromConfig, type Settings } from './config.ts'
import { DEFAULT_SETTINGS, isPlaceholderBaseUrl, normalizeBaseUrl, originOf, settingsFromConfig, type Settings } from './config.ts'
/** Persisted document schema. */
export interface PersistedState {
@ -43,6 +43,10 @@ export interface SettingsView extends Settings {
memoryToken: TokenView
summaryToken: TokenView
statePath: string
/** False when the address is still the packaged placeholder. */
baseUrlConfigured: boolean
/** Origin of the effective address, for the change-confirmation UI. */
baseUrlOrigin: string
}
/** `$DSH_HOME` (or `~/.dsh`) — the same resolution DSH core uses. */
@ -199,6 +203,8 @@ export class SettingsStore {
memoryToken: { configured: memory !== '', masked: memory === '' ? '' : maskToken(memory) },
summaryToken: { configured: summary !== '', masked: summary === '' ? '' : maskToken(summary) },
statePath: this.file,
baseUrlConfigured: !isPlaceholderBaseUrl(settings.baseUrl),
baseUrlOrigin: originOf(settings.baseUrl),
}
}
@ -209,8 +215,11 @@ export class SettingsStore {
* stored token, and an explicit boolean `clear*` flag removes one. That way
* the browser never has to round-trip a secret it cannot read.
*/
patch(patch: Record<string, unknown>): { ok: boolean; error?: string } {
patch(patch: Record<string, unknown>): { ok: boolean; error?: string; clearedTokens?: string[] } {
const next: PersistedState = { ...this.state }
const beforeOrigin = originOf(this.settings().baseUrl)
/** Tokens this very request supplied; they survive an address change. */
const provided: string[] = []
if (patch.enabled !== undefined) {
if (typeof patch.enabled !== 'boolean') return { ok: false, error: 'enabled must be a boolean' }
next.enabled = patch.enabled
@ -229,11 +238,13 @@ export class SettingsStore {
if (activityToken !== undefined) {
if (!activityToken.startsWith('cmt_')) return { ok: false, error: 'activity token must start with cmt_' }
next.activityToken = activityToken
provided.push('activity')
}
const memoryToken = cleanString(patch.memoryToken)
if (memoryToken !== undefined) {
if (!memoryToken.startsWith('cmt_')) return { ok: false, error: 'memory token must start with cmt_' }
next.memoryToken = memoryToken
provided.push('memory')
}
if (patch.requestTimeoutMs !== undefined) {
const requestTimeoutMs = clampInt(patch.requestTimeoutMs, 1000, 60_000)
@ -258,13 +269,33 @@ export class SettingsStore {
if (summaryToken !== undefined) {
if (!summaryToken.startsWith('cmt_')) return { ok: false, error: 'summary token must start with cmt_' }
next.summaryToken = summaryToken
provided.push('summary')
}
if (patch.clearSummaryToken === true) delete next.summaryToken
if (patch.clearActivityToken === true) delete next.activityToken
if (patch.clearMemoryToken === true) delete next.memoryToken
// Switching the service origin must not hand the previous service's
// bearer tokens to the new one: everything this request did not explicitly
// replace is dropped, and the caller is told so it can ask to re-authenticate.
const afterOrigin = originOf(next.baseUrl ?? this.configDefaults.baseUrl)
const clearedTokens: string[] = []
if (beforeOrigin !== '' && afterOrigin !== '' && beforeOrigin !== afterOrigin) {
const credentials = [
['activity', 'activityToken'],
['memory', 'memoryToken'],
['summary', 'summaryToken'],
] as const
for (const [label, key] of credentials) {
if (next[key] === undefined) continue
if (provided.includes(label)) continue
delete next[key]
clearedTokens.push(label)
}
}
this.write(next)
this.state = next
return { ok: true }
return clearedTokens.length === 0 ? { ok: true } : { ok: true, clearedTokens }
}
/** File size in bytes, for a "sidecar exists" hint in the card. */

238
verify-brain-panel.mjs Normal file
View File

@ -0,0 +1,238 @@
// Runtime verification for the v0.5 management surface (P1 + P2):
// * status / capabilities payloads the card renders
// * config writes: origin change must not hand old tokens to a new service
// * skill inventory / detail / toggle
// * staged install: preview, explicit selection, conflict skip, plan expiry
// * uninstall: impact preview + single-use confirmation token
// * route gates: method, origin, content-type, path traversal
//
// Everything runs against the real route table wired to a real HTTP server and
// a throwaway $DSH_HOME; nothing touches the user's skills or config.
import http from 'node:http'
import { execFileSync } from 'node:child_process'
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
process.env.DSH_HOME = mkdtempSync(join(tmpdir(), 'brain-home-'))
const results = []
function check(name, ok, detail) {
results.push({ name, ok })
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`)
}
const root = join(process.env.DSH_HOME, 'skills')
const holding = join(process.env.DSH_HOME, 'skills-disabled')
const writeSkill = (area, folder, files) => {
for (const [rel, content] of Object.entries(files)) {
const target = join(area, folder, ...rel.split('/'))
mkdirSync(join(target, '..'), { recursive: true })
writeFileSync(target, content)
}
}
const { SettingsStore } = await import('./lib/store.js')
const { Reporter } = await import('./lib/reporter.js')
const { SkillAdmin } = await import('./lib/skill-admin.js')
const { createRoutes } = await import('./lib/routes.js')
// A placeholder address the packaged patch ships: the card must call it
// "未配置服务", never a healthy connection.
const store = new SettingsStore(
{ baseUrl: 'https://your-memory-host/api/longmemory', clientId: 'test-client', requestTimeoutMs: 2000, defaultK: 7 },
join(process.env.DSH_HOME, 'cloud-memory.json'),
)
const reporter = new Reporter({
client: () => ({
reportTurn: async () => ({ ok: true, status: 200, data: {} }),
submitSummary: async () => ({ ok: true, status: 200, data: {} }),
}),
settings: () => ({ enabled: true, clientId: 'test-client' }),
activityToken: () => '',
summary: () => ({ enabled: false, maxChars: 1000 }),
summaryToken: () => '',
log: () => {},
})
const admin = new SkillAdmin({
skillsRoot: () => root,
holdingDir: () => holding,
syncStatePath: () => join(process.env.DSH_HOME, 'cloud-memory-skills.json'),
syncRunning: () => false,
log: () => {},
})
const routes = createRoutes({
version: '0.5.0-test',
store,
reporter,
client: () => ({
reach: async () => ({ ok: false, status: 0, message: 'stub' }),
probeActivity: async () => ({ ok: false, error: { status: 0, code: 'network_error', message: 'stub' } }),
projects: async () => ({ ok: false, error: { status: 0, code: 'network_error', message: 'stub' } }),
probeSummary: async () => ({ ok: false, error: { status: 0, code: 'network_error', message: 'stub' } }),
login: async () => ({ ok: false, error: { status: 401, code: 'unauthorized', message: 'stub' } }),
}),
skills: () => ({ running: false, downloaded: [], uploaded: [], updated: [], conflicts: [], skipped: 0 }),
admin,
})
const server = http.createServer((req, res) => {
const path = (req.url ?? '/').split('?')[0]
for (const route of routes) {
if (route.kind === 'exact' && path === route.path) return route.handler(req, res)
if (route.kind === 'prefix' && (path === route.path || path.startsWith(`${route.path}/`))) return route.handler(req, res)
}
res.writeHead(404, { 'content-type': 'application/json' })
res.end('{"ok":false,"error":"no-route"}')
})
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
const origin = `http://127.0.0.1:${server.address().port}`
async function call(method, path, body, extraHeaders) {
const headers = { accept: 'application/json', ...(extraHeaders ?? {}) }
let payload
if (body !== undefined) {
headers['content-type'] = headers['content-type'] ?? 'application/json'
payload = typeof body === 'string' ? body : JSON.stringify(body)
}
const response = await fetch(`${origin}${path}`, { method, headers, body: payload })
const text = await response.text()
let parsed = null
try {
parsed = JSON.parse(text)
} catch {
parsed = null
}
return { status: response.status, body: parsed, text }
}
// ── A. status / capabilities ────────────────────────────────────────────
let status = await call('GET', '/cloud-memory/status')
check('status is 200 with ok:true', status.status === 200 && status.body?.ok === true)
check('a placeholder address is reported as unconfigured', status.body?.settings?.baseUrlConfigured === false, String(status.body?.settings?.baseUrlConfigured))
check('the effective origin is exposed for the change warning', status.body?.settings?.baseUrlOrigin === 'https://your-memory-host')
check('capabilities carry the plugin version', status.body?.capabilities?.version === '0.5.0-test')
check('the market is reported unavailable instead of faked off', status.body?.capabilities?.features?.skillsMarketplace === false)
check('the MCP bridge is declared as a host-plugin surface', status.body?.capabilities?.features?.mcpBridge === 'host-plugin')
check('no check has run yet', status.body?.lastCheck === null)
const caps = await call('GET', '/cloud-memory/capabilities')
check('capabilities route answers on its own', caps.status === 200 && caps.body?.features?.skills === true)
check('capabilities notes state the gaps', Array.isArray(caps.body?.notes) && caps.body.notes.length >= 2)
// ── B. config writes ────────────────────────────────────────────────────
check('GET on the config route is refused', (await call('GET', '/cloud-memory/config')).status === 405)
const evil = await call('PUT', '/cloud-memory/config', { clientId: 'x' }, { origin: 'https://evil.example' })
check('a foreign Origin is rejected', evil.status === 403 && evil.body?.error === 'origin-rejected')
const plain = await call('PUT', '/cloud-memory/config', 'clientId=x', { 'content-type': 'text/plain' })
check('a non-JSON body is refused', plain.status === 415)
store.patch({ activityToken: 'cmt_activity_token_1', memoryToken: 'cmt_memory_token_1', summaryToken: 'cmt_summary_token_1' })
const switched = await call('PUT', '/cloud-memory/config', { baseUrl: 'https://memory.example.org/api/longmemory' }, { origin })
check('changing the service origin is accepted', switched.status === 200 && switched.body?.ok === true)
check('the old origin tokens are cleared on a service switch',
Array.isArray(switched.body?.credentialsCleared) && switched.body.credentialsCleared.sort().join(',') === 'activity,memory,summary',
JSON.stringify(switched.body?.credentialsCleared))
check('the cleared tokens are really gone from the store',
store.activityToken() === '' && store.memoryToken() === '' && store.summaryToken() === '')
const sameOriginSave = await call('PUT', '/cloud-memory/config', { activityToken: 'cmt_new_activity' }, { origin })
check('a token supplied with the new origin is kept', sameOriginSave.status === 200 && store.activityToken() === 'cmt_new_activity')
const noChange = await call('PUT', '/cloud-memory/config', { defaultK: 25 }, { origin })
check('an ordinary save does not touch credentials', noChange.body?.credentialsCleared === undefined && store.activityToken() === 'cmt_new_activity')
check('defaultK is renamed in the payload but still bounded', store.settings().defaultK === 25)
// ── C. skill inventory / detail / toggle ────────────────────────────────
writeSkill(root, 'gamma', { 'SKILL.md': '---\nname: gamma\ndescription: 演示技能\n---\n\n# gamma\n', 'references/a.md': '说明' })
writeSkill(holding, 'parked-one', { 'SKILL.md': '# parked-one\n' })
let inventory = await call('GET', '/cloud-memory/skills/api')
check('inventory lists root and parked skills', inventory.body?.skills?.length === 2)
const gamma = inventory.body?.skills?.find((skill) => skill.folder === 'gamma')
check('inventory carries owner, hash and install time',
gamma?.ownerManager === 'dsh-cloud-memory' && typeof gamma?.skillSha256 === 'string' && typeof gamma?.installedAt === 'string')
check('inventory carries a byte size and file count', gamma?.files === 2 && gamma?.bytes > 0)
check('parked skills are marked disabled', inventory.body?.skills?.find((skill) => skill.folder === 'parked-one')?.enabled === false)
check('pending plans come with the inventory', Array.isArray(inventory.body?.plans))
const detail = await call('POST', '/cloud-memory/skills/detail', { folder: 'gamma' })
check('detail returns the SKILL.md text', detail.status === 200 && String(detail.body?.skillMd).includes('# gamma'))
check('detail returns the file list', Array.isArray(detail.body?.files) && detail.body.files.length === 2)
const traversal = await call('POST', '/cloud-memory/skills/toggle', { folder: '../escape', enabled: false })
check('a traversal folder name is refused', traversal.status === 400 && traversal.body?.code === 'invalid_name')
const toggled = await call('POST', '/cloud-memory/skills/toggle', { folder: 'gamma', enabled: false })
check('disable parks the folder', toggled.status === 200 && existsSync(join(holding, 'gamma')) && !existsSync(join(root, 'gamma')))
check('the toggle answer explains the effect scope', String(toggled.body?.note).includes('新会话'))
const enabled = await call('POST', '/cloud-memory/skills/toggle', { folder: 'gamma', enabled: true })
check('enable brings it back', enabled.status === 200 && existsSync(join(root, 'gamma')))
// ── D. staged install ───────────────────────────────────────────────────
const repo = mkdtempSync(join(tmpdir(), 'brain-repo-'))
writeSkill(repo, 'alpha', { 'SKILL.md': '# alpha\n', 'run.mjs': 'console.log(1)' })
writeSkill(repo, 'beta', { 'SKILL.md': '# beta\n' })
writeSkill(repo, 'gamma', { 'SKILL.md': '# gamma from repo\n' })
execFileSync('git', ['init', '-q', repo])
execFileSync('git', ['-C', repo, 'add', '-A'])
execFileSync('git', ['-C', repo, '-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-qm', 'fixture'])
const badPlan = await call('POST', '/cloud-memory/skills/install/plan', { url: 'javascript:alert(1)' })
check('a non-git URL never reaches the stager', badPlan.status === 400 && badPlan.body?.code === 'invalid_url')
const plan = await call('POST', '/cloud-memory/skills/install/plan', { url: `file://${repo}` })
check('staging a repository answers with a plan', plan.status === 200 && typeof plan.body?.planId === 'string')
const candidates = Array.isArray(plan.body?.candidates) ? plan.body.candidates : []
check('every candidate is described before it is installed',
candidates.length === 3 && candidates.every((item) => typeof item.files === 'number' && typeof item.id === 'string'))
check('an existing skill shows up as a conflict',
candidates.find((item) => item.folder === 'gamma')?.conflict === true)
check('candidates list the scripts they carry',
Array.isArray(candidates.find((item) => item.folder === 'alpha')?.scripts) &&
candidates.find((item) => item.folder === 'alpha').scripts.includes('run.mjs'))
check('staging does not write into the skills root yet',
!existsSync(join(root, 'alpha')) && !existsSync(join(root, 'beta')))
const committed = await call('POST', '/cloud-memory/skills/install/commit', { planId: plan.body.planId, folders: ['alpha'] })
check('only the selected folder is installed',
committed.status === 200 && committed.body?.installed?.join(',') === 'alpha' && !existsSync(join(root, 'beta')))
check('the unselected candidate stays pending', committed.body?.remaining?.includes('beta'))
check('the staged clone is removed after the commit',
readdirSync(join(process.env.DSH_HOME, '.cloud-memory-staging')).length === 0)
const again = await call('POST', '/cloud-memory/skills/install/plan', { url: `file://${repo}` })
const collide = await call('POST', '/cloud-memory/skills/install/commit', { planId: again.body.planId, folders: ['alpha'] })
check('a second install of the same folder is skipped, never overwritten',
collide.body?.installed?.length === 0 && collide.body?.skipped?.[0]?.reason === 'already_exists')
const expired = await call('POST', '/cloud-memory/skills/install/commit', { planId: 'plan_missing', folders: ['alpha'] })
check('an unknown plan id is refused with plan_expired', expired.status === 409 && expired.body?.code === 'plan_expired')
check('the second plan was cleaned up as well',
readdirSync(join(process.env.DSH_HOME, '.cloud-memory-staging')).length === 0)
// ── E. uninstall: preview then single-use token ─────────────────────────
const noConfirm = await call('POST', '/cloud-memory/skills/remove', { folder: 'alpha' })
check('remove without confirmation is refused', noConfirm.status === 409 && noConfirm.body?.code === 'confirmation_required')
const noToken = await call('POST', '/cloud-memory/skills/remove', { folder: 'alpha', confirmed: true })
check('remove without a preview token is refused', noToken.status === 409 && noToken.body?.code === 'confirmation_required')
const impact = await call('POST', '/cloud-memory/skills/uninstall/plan', { folder: 'alpha' })
check('the impact preview names the real directory and files',
impact.status === 200 && impact.body.dir === join(root, 'alpha') && impact.body.files >= 2)
check('the preview states that deletion is irreversible', impact.body.recoverable === false && String(impact.body.note).includes('不可恢复'))
check('the preview names the scripts that would be deleted', impact.body.scripts.includes('run.mjs'))
const wrongFolder = await call('POST', '/cloud-memory/skills/remove', { folder: 'beta', token: impact.body.token, confirmed: true })
check('a token issued for one skill cannot delete another', wrongFolder.status === 409)
const removed = await call('POST', '/cloud-memory/skills/remove', { folder: 'alpha', token: impact.body.token, confirmed: true })
check('a confirmed remove with the right token deletes the folder', removed.status === 200 && !existsSync(join(root, 'alpha')))
const reused = await call('POST', '/cloud-memory/skills/remove', { folder: 'gamma', token: impact.body.token, confirmed: true })
check('the confirmation token is single-use', reused.status === 409)
check('deleting one skill leaves the others alone', existsSync(join(root, 'gamma')) && existsSync(join(holding, 'parked-one')))
// ── F. route gates on the skills prefix ─────────────────────────────────
const wrongMethod = await call('GET', '/cloud-memory/skills/toggle')
check('a GET on a write action is refused', wrongMethod.status === 405)
const wrongType = await call('POST', '/cloud-memory/skills/detail', 'folder=gamma', { 'content-type': 'text/plain' })
check('a form-encoded write is refused', wrongType.status === 415)
const unknown = await call('POST', '/cloud-memory/skills/nope', {})
check('an unknown skill subroute is a 404', unknown.status === 404)
server.close()
const failed = results.filter((item) => !item.ok).length
console.log(failed === 0 ? `\nALL ${results.length} CHECKS PASSED` : `\n${failed} CHECK(S) FAILED`)
process.exit(failed === 0 ? 0 : 1)

353
verify-card-debug.mjs Normal file
View File

@ -0,0 +1,353 @@
// Render-level smoke test for the hand-written client bundle.
//
// The client half has no bundler and no typecheck, so this harness supplies a
// minimal React-shaped runtime (createElement + useState/useEffect/useCallback +
// a class error boundary), a stubbed fetch, and renders the card once per tab
// with realistic payloads. It catches the failure modes a restart would
// otherwise surface as a blank panel: an undefined identifier, a broken hook
// order, a component that throws while rendering real data.
import { readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
const here = dirname(fileURLToPath(import.meta.url))
const source = readFileSync(join(here, 'client', 'index.js'), 'utf8')
const results = []
function check(name, ok, detail) {
results.push({ name, ok })
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`)
}
// ── a very small React ──────────────────────────────────────────────────
let hooks = []
let cursor = 0
let pendingEffects = []
let scheduled = false
const React = {
createElement(type, props, ...children) {
const flat = []
const push = (value) => {
if (Array.isArray(value)) value.forEach(push)
else if (value !== null && value !== undefined && value !== false && value !== true) flat.push(value)
}
push(children)
return { type, props: props ?? {}, children: flat }
},
useState(initial) {
const index = cursor++
if (!(index in hooks)) hooks[index] = typeof initial === 'function' ? initial() : initial
const setter = (next) => {
const value = typeof next === 'function' ? next(hooks[index]) : next
if (value !== hooks[index]) {
hooks[index] = value
scheduled = true
}
}
return [hooks[index], setter]
},
useEffect(fn) {
pendingEffects.push(fn)
},
useCallback(fn) {
return fn
},
Component: function Component(props) {
this.props = props
},
}
React.Component.prototype.setState = function setState(patch) {
this.state = { ...this.state, ...patch }
scheduled = true
}
function render(node) {
if (node === null || node === undefined || node === false || node === true) return ''
if (typeof node === 'string' || typeof node === 'number') return String(node)
if (Array.isArray(node)) return node.map(render).join('')
const { type, props, children } = node
if (typeof type === 'function') {
if (type.prototype && typeof type.prototype.render === 'function') {
const instance = new type(props)
instance.props = props
if (instance.state === undefined) instance.state = {}
instance.setState = function setState(patch) {
instance.state = { ...instance.state, ...patch }
scheduled = true
}
try {
return render(instance.render())
} catch (failure) {
if (typeof type.getDerivedStateFromError === 'function') {
instance.state = { ...instance.state, ...type.getDerivedStateFromError(failure) }
return render(instance.render())
}
throw failure
}
}
const savedCursor = cursor
const savedHooks = hooks
const out = render(type({ ...props, children }))
cursor = savedCursor
hooks = savedHooks
return out
}
return children.map(render).join('')
}
// ── payloads ────────────────────────────────────────────────────────────
const statusBody = {
ok: true,
settings: {
enabled: true,
baseUrl: 'https://your-memory-host/api/longmemory',
baseUrlConfigured: false,
baseUrlOrigin: 'https://your-memory-host',
clientId: 'dsh-desktop',
requestTimeoutMs: 5000,
defaultK: 10,
summaryEnabled: true,
summaryMaxChars: 6000,
skillsSyncEnabled: true,
skillsDir: '',
},
tokens: {
activity: { configured: false, masked: '' },
memory: { configured: true, masked: 'cmt_abc…9f2c' },
summary: { configured: false, masked: '' },
},
settingsPath: 'C:/Users/test/.dsh/cloud-memory.json',
reporter: {
attempted: 3,
recorded: 2,
duplicate: 0,
failed: 1,
skipped: 0,
queued: 1,
recent: [{ turnId: 'turn-1', outcome: 'recorded', status: 'completed', at: Date.now() }],
},
lastCheck: {
at: Date.now(),
checks: [
{ id: 'network', label: '服务地址', state: 'ok', message: '服务可达(HTTP 401)' },
{ id: 'activity', label: '活动上报权限(activity:write)', state: 'unconfigured', message: '未配置令牌' },
{ id: 'memory', label: '记忆读写权限(memory:write)', state: 'ok', message: '鉴权通过(2 个项目)' },
{ id: 'summary', label: '摘要权限(summary:write)', state: 'unconfigured', message: '未配置摘要令牌(可选)' },
],
},
capabilities: { version: '0.5.0', features: { skills: true, skillsMarketplace: false, mcpBridge: 'host-plugin' }, notes: [] },
skills: { running: false, downloaded: [], uploaded: [], conflicts: [], skipped: 0 },
}
const skillsBody = {
ok: true,
skills: [
{
folder: 'gamma',
name: 'gamma',
description: '演示技能',
enabled: true,
origin: 'cloud',
revision: 5,
files: 2,
bytes: 2048,
installedAt: new Date().toISOString(),
skillSha256: 'abcdef0123456789',
location: 'root',
ownerManager: 'dsh-cloud-memory',
writable: true,
},
{
folder: 'parked-one',
name: 'parked-one',
description: '',
enabled: false,
origin: 'local',
files: 1,
bytes: 32,
installedAt: new Date().toISOString(),
skillSha256: 'ffeedd00112233',
location: 'holding',
ownerManager: 'dsh-cloud-memory',
writable: true,
},
],
root: 'C:/Users/test/.dsh/skills',
holding: 'C:/Users/test/.dsh/skills-disabled',
staging: 'C:/Users/test/.dsh/.cloud-memory-staging',
plans: [],
}
const mcpBody = {
ok: true,
detail: {
items: [
{
key: 'mcp-key-1',
name: 'demo-mcp',
connectorId: 'demo',
transport: 'http',
authMode: 'bearer',
enabled: true,
connectionState: 'connected',
injectionLabel: '始终注入',
scope: { visibility: 'global' },
healthCheckedAt: Date.now(),
lastError: null,
},
],
},
}
// ── host shims ──────────────────────────────────────────────────────────
let mcpAvailable = true
let activeTab = 'connection'
async function fakeFetch(url, init) {
const path = String(url).split('?')[0]
let body = { ok: false, error: 'not-found' }
let status = 404
if (path === '/cloud-memory/status') {
body = statusBody
status = 200
} else if (path.startsWith('/cloud-memory/skills/api')) {
body = skillsBody
status = 200
} else if (path === '/mcp-connector/api') {
if (mcpAvailable) {
body = mcpBody
status = 200
} else {
body = { ok: false, message: 'no bridge' }
status = 404
}
}
void init
return { status, json: async () => body, text: async () => JSON.stringify(body) }
}
const localStorageStub = {
getItem: (key) => (String(key).endsWith(':tab') ? activeTab : null),
setItem: () => {},
}
let registered = null
globalThis.window = {
localStorage: localStorageStub,
addEventListener: () => {},
removeEventListener: () => {},
__ModuleLoader__: {
load(spec) {
if (spec.id !== 'dsh-cloud-memory') throw new Error(`unexpected module id ${spec.id}`)
const exportsObject = spec.factory(requireShim)
const captured = []
exportsObject.apply({
slots: {
inject(_seat, fn) {
return fn()
},
register(_options, component) {
captured.push(component)
return () => {}
},
},
})
registered = captured[0]
},
},
}
function requireShim(id) {
if (id === 'react') return React
throw new Error(`unexpected require: ${id}`)
}
// Evaluate the bundle once; it self-registers through window.__ModuleLoader__.
function loadBundle() {
registered = null
const factory = new Function(
'window',
'require',
'document',
'localStorage',
'fetch',
'console',
'setInterval',
'clearInterval',
'setTimeout',
'clearTimeout',
'AbortController',
source,
)
factory(
globalThis.window,
requireShim,
{ visibilityState: 'visible' },
localStorageStub,
fakeFetch,
{ warn: () => {}, log: () => {} },
() => 0,
() => {},
() => 0,
() => {},
typeof AbortController === 'function' ? AbortController : undefined,
)
if (registered === null) throw new Error('the bundle did not register a card')
return registered
}
async function drive(tab, bridgeAvailable) {
activeTab = tab
mcpAvailable = bridgeAvailable
hooks = []
cursor = 0
const card = loadBundle()
let text = ''
for (let pass = 0; pass < 6; pass += 1) {
cursor = 0
pendingEffects = []
scheduled = false
text = render(React.createElement(card, null))
const effects = pendingEffects
pendingEffects = []
for (const effect of effects) {
const cleanup = effect()
if (typeof cleanup === 'function') cleanup()
}
await new Promise((resolve) => setTimeout(resolve, 0))
if (!scheduled) break
}
return text
}
// ── assertions ──────────────────────────────────────────────────────────
const dbgCard = loadBundle(); console.log("DBG", typeof dbgCard, dbgCard.length, dbgCard.toString().slice(0,80)); const el = React.createElement(dbgCard, null); console.log("DBG_EL", typeof el, JSON.stringify(Object.keys(el))); console.log("DBG_RENDER", JSON.stringify(render(el).slice(0,200)));
const connection = await drive('connection', true)
check('the connection tab renders its sections', ['连接与上报', '身份验证', '服务地址', '连接与权限检查', '最近上报'].every((label) => connection.includes(label)))
check('a placeholder address shows as unconfigured', connection.includes('未配置服务'))
check('check results are rendered per credential', connection.includes('活动上报权限') && connection.includes('记忆读写权限'))
check('the reporter row survives a real payload', connection.includes('turn-1'))
check('the search limit is renamed and reachable', connection.includes('单次搜索返回上限') || connection.includes('高级设置'))
check('no render boundary error on the connection tab', !connection.includes('渲染失败'))
const skillsText = await drive('skills', true)
check('the skills tab renders its sections', ['本机技能', '从 Git 仓库安装', '技能市场', '云端同步状态'].every((label) => skillsText.includes(label)))
check('real skill rows carry origin and size', skillsText.includes('gamma') && skillsText.includes('云端下发') && skillsText.includes('2.0 KB'))
check('a parked skill is rendered as disabled', skillsText.includes('已停用'))
check('the market gap is stated instead of simulated', skillsText.includes('能力缺口') || skillsText.includes('没有接入经验证的市场来源'))
check('no render boundary error on the skills tab', !skillsText.includes('渲染失败'))
const mcpText = await drive('mcp', true)
check('the MCP tab renders the host connection', mcpText.includes('我的连接') && mcpText.includes('demo-mcp'))
check('MCP state, transport and auth are shown', mcpText.includes('已连接') && mcpText.includes('http') && mcpText.includes('bearer'))
check('MCP actions are offered', mcpText.includes('健康检查') && mcpText.includes('工具列表') && mcpText.includes('移除连接'))
check('the injected tools cache starts empty', mcpText.includes('工具可见不等于业务可调用'))
const missing = await drive('mcp', false)
check('a missing bridge becomes a stated capability gap', missing.includes('MCP 管理当前不可用') && missing.includes('MCP 服务器配置'))
check('no render boundary error without the bridge', !missing.includes('渲染失败'))
const failed = results.filter((item) => !item.ok).length
console.log(failed === 0 ? `\nALL ${results.length} CHECKS PASSED` : `\n${failed} CHECK(S) FAILED`)
process.exit(failed === 0 ? 0 : 1)

505
verify-card-render.mjs Normal file
View File

@ -0,0 +1,505 @@
// Render-level smoke test for the hand-written client bundle.
//
// The client half has no bundler and no typecheck, so this harness supplies a
// minimal React-shaped runtime (createElement + useState/useEffect/useCallback +
// a class error boundary), a stubbed fetch, and renders the card once per tab
// with realistic payloads. It catches the failure modes a restart would
// otherwise surface as a blank panel: an undefined identifier, a broken hook
// order, a component that throws while rendering real data.
import { readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
const here = dirname(fileURLToPath(import.meta.url))
const source = readFileSync(join(here, 'client', 'index.js'), 'utf8')
const results = []
function check(name, ok, detail) {
results.push({ name, ok })
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`)
}
// ── a very small React ──────────────────────────────────────────────────
let hooks = []
let cursor = 0
let pendingEffects = []
let scheduled = false
const React = {
createElement(type, props, ...children) {
const flat = []
const push = (value) => {
if (Array.isArray(value)) value.forEach(push)
else if (value !== null && value !== undefined && value !== false && value !== true) flat.push(value)
}
push(children)
// Real React puts children on props; the card relies on that for its
// error boundary (`this.props.children`).
return { type, props: { ...(props ?? {}), children: flat.length === 1 ? flat[0] : flat }, children: flat }
},
useState(initial) {
const index = cursor++
if (!(index in hooks)) hooks[index] = typeof initial === 'function' ? initial() : initial
const setter = (next) => {
const value = typeof next === 'function' ? next(hooks[index]) : next
if (value !== hooks[index]) {
hooks[index] = value
scheduled = true
}
}
return [hooks[index], setter]
},
useEffect(fn) {
pendingEffects.push(fn)
},
useCallback(fn) {
return fn
},
Component: function Component(props) {
this.props = props
},
}
React.Component.prototype.setState = function setState(patch) {
this.state = { ...this.state, ...patch }
scheduled = true
}
function render(node) {
if (node === null || node === undefined || node === false || node === true) return ''
if (typeof node === 'string' || typeof node === 'number') return String(node)
if (Array.isArray(node)) return node.map(render).join('')
const { type, props, children } = node
if (typeof type === 'function') {
if (type.prototype && typeof type.prototype.render === 'function') {
const instance = new type(props)
instance.props = props
if (instance.state === undefined) instance.state = {}
instance.setState = function setState(patch) {
instance.state = { ...instance.state, ...patch }
scheduled = true
}
try {
return render(instance.render())
} catch (failure) {
if (typeof type.getDerivedStateFromError === 'function') {
instance.state = { ...instance.state, ...type.getDerivedStateFromError(failure) }
return render(instance.render())
}
throw failure
}
}
// One hook array is shared by the whole tree: only the card itself calls
// hooks, and keeping a single array is what lets a setter re-render.
return render(type({ ...props, children }))
}
return children.map(render).join('')
}
// Walk the tree (running function components) so a control can be clicked the
// way a user would: the preview and this harness share no browser events.
function walk(node, visit) {
if (node === null || node === undefined || typeof node === 'string' || typeof node === 'number') return
if (Array.isArray(node)) {
node.forEach((child) => walk(child, visit))
return
}
if (typeof node.type === 'function') {
if (node.type.prototype && typeof node.type.prototype.render === 'function') {
const instance = new node.type(node.props)
instance.props = node.props
if (instance.state === undefined) instance.state = {}
instance.setState = function setState(patch) {
instance.state = { ...instance.state, ...patch }
scheduled = true
}
walk(instance.render(), visit)
return
}
walk(node.type({ ...node.props, children: node.children }), visit)
return
}
visit(node)
node.children.forEach((child) => walk(child, visit))
}
function clickLabel(root, prefix, occurrence = 0) {
let clicked = false
let index = 0
walk(root, (node) => {
if (clicked) return
const label = (node.props ?? {})['aria-label']
if (typeof label === 'string' && label.startsWith(prefix) && typeof node.props.onClick === 'function') {
if (index === occurrence) {
node.props.onClick()
clicked = true
}
index += 1
}
})
return clicked
}
// ── payloads ────────────────────────────────────────────────────────────
const statusBody = {
ok: true,
settings: {
enabled: true,
baseUrl: 'https://your-memory-host/api/longmemory',
baseUrlConfigured: false,
baseUrlOrigin: 'https://your-memory-host',
clientId: 'dsh-desktop',
requestTimeoutMs: 5000,
defaultK: 10,
summaryEnabled: true,
summaryMaxChars: 6000,
skillsSyncEnabled: true,
skillsDir: '',
},
tokens: {
activity: { configured: false, masked: '' },
memory: { configured: true, masked: 'cmt_abc…9f2c' },
summary: { configured: false, masked: '' },
},
settingsPath: 'C:/Users/test/.dsh/cloud-memory.json',
reporter: {
attempted: 3,
recorded: 2,
duplicate: 0,
failed: 1,
skipped: 0,
queued: 1,
recent: [{ turnId: 'turn-1', outcome: 'recorded', status: 'completed', at: Date.now() }],
},
lastCheck: {
at: Date.now(),
checks: [
{ id: 'network', label: '服务地址', state: 'ok', message: '服务可达(HTTP 401)' },
{ id: 'activity', label: '活动上报权限(activity:write)', state: 'unconfigured', message: '未配置令牌' },
{ id: 'memory', label: '记忆读写权限(memory:write)', state: 'ok', message: '鉴权通过(2 个项目)' },
{ id: 'summary', label: '摘要权限(summary:write)', state: 'unconfigured', message: '未配置摘要令牌(可选)' },
],
},
capabilities: { version: '0.5.0', features: { skills: true, skillsMarketplace: false, mcpBridge: 'host-plugin' }, notes: [] },
skills: { running: false, downloaded: [], uploaded: [], conflicts: [], skipped: 0 },
}
const skillsBody = {
ok: true,
skills: [
{
folder: 'gamma',
name: 'gamma',
description: '演示技能',
enabled: true,
origin: 'cloud',
revision: 5,
files: 2,
bytes: 2048,
installedAt: new Date().toISOString(),
skillSha256: 'abcdef0123456789',
location: 'root',
ownerManager: 'dsh-cloud-memory',
writable: true,
},
{
folder: 'parked-one',
name: 'parked-one',
description: '',
enabled: false,
origin: 'local',
files: 1,
bytes: 32,
installedAt: new Date().toISOString(),
skillSha256: 'ffeedd00112233',
location: 'holding',
ownerManager: 'dsh-cloud-memory',
writable: true,
},
],
root: 'C:/Users/test/.dsh/skills',
holding: 'C:/Users/test/.dsh/skills-disabled',
staging: 'C:/Users/test/.dsh/.cloud-memory-staging',
plans: [],
}
const mcpBody = {
ok: true,
detail: {
items: [
{
key: 'mcp-key-1',
name: 'demo-mcp',
connectorId: 'demo',
transport: 'http',
authMode: 'bearer',
enabled: true,
connectionState: 'connected',
injectionLabel: '始终注入',
scope: { visibility: 'global' },
healthCheckedAt: Date.now(),
lastError: null,
},
],
},
}
// ── host shims ──────────────────────────────────────────────────────────
let mcpAvailable = true
let activeTab = 'connection'
const treeBody = {
ok: true,
note: '分类只记在这个来源里,不移动文件。只有 DSH 来源的开关会真实启停技能目录;其他软件的目录本卡不修改。',
sources: [
{
id: 'dsh',
label: 'DSH',
root: 'C:/Users/test/.dsh/skills',
exists: true,
writable: true,
manager: 'DSH',
enabled: true,
enabledEditable: true,
cardOnly: false,
total: 2,
enabledCount: 2,
groups: [
{
id: 'g_qq',
name: 'QQ-Skill',
enabled: true,
enabledEditable: true,
cardOnly: false,
total: 1,
enabledCount: 1,
skills: [
{ folder: 'gamma', name: 'gamma', description: '演示技能', enabled: true, enabledEditable: true, files: 2, bytes: 2048, origin: 'cloud', inCardDisabled: false },
],
},
{
id: 'unassigned',
name: '未分类',
enabled: true,
enabledEditable: false,
cardOnly: false,
total: 1,
enabledCount: 1,
skills: [
{ folder: 'parked-one', name: 'parked-one', description: '', enabled: false, enabledEditable: true, files: 1, bytes: 32, inCardDisabled: false },
],
},
],
},
{
id: 'codex',
label: 'Codex',
root: 'C:/Users/test/.codex/skills',
exists: true,
writable: false,
manager: 'Codex',
note: '由 Codex 自行加载,本卡不修改它的目录',
enabled: true,
enabledEditable: true,
cardOnly: true,
total: 1,
enabledCount: 1,
groups: [
{
id: 'unassigned',
name: '未分类',
enabled: true,
enabledEditable: false,
cardOnly: true,
total: 1,
enabledCount: 1,
skills: [
{ folder: 'codex-one', name: 'codex-one', description: '', enabled: true, enabledEditable: false, files: 1, bytes: 10, inCardDisabled: false },
],
},
],
},
],
}
async function fakeFetch(url, init) {
const path = String(url).split('?')[0]
let body = { ok: false, error: 'not-found' }
let status = 404
if (path === '/cloud-memory/status') {
body = statusBody
status = 200
} else if (path === '/cloud-memory/skills/sources') {
body = treeBody
status = 200
} else if (path.startsWith('/cloud-memory/skills/api')) {
body = skillsBody
status = 200
} else if (path === '/mcp-connector/api') {
if (mcpAvailable) {
body = mcpBody
status = 200
} else {
body = { ok: false, message: 'no bridge' }
status = 404
}
}
void init
return { status, json: async () => body, text: async () => JSON.stringify(body) }
}
const localStorageStub = {
getItem: (key) => (String(key).endsWith(':tab') ? activeTab : null),
setItem: () => {},
}
let registered = null
globalThis.window = {
localStorage: localStorageStub,
addEventListener: () => {},
removeEventListener: () => {},
__ModuleLoader__: {
load(spec) {
if (spec.id !== 'dsh-cloud-memory') throw new Error(`unexpected module id ${spec.id}`)
const exportsObject = spec.factory(requireShim)
const captured = []
exportsObject.apply({
slots: {
inject(_seat, fn) {
return fn()
},
register(_options, component) {
captured.push(component)
return () => {}
},
},
})
registered = captured[0]
},
},
}
function requireShim(id) {
if (id === 'react') return React
throw new Error(`unexpected require: ${id}`)
}
// Evaluate the bundle once; it self-registers through window.__ModuleLoader__.
function loadBundle() {
registered = null
const factory = new Function(
'window',
'require',
'document',
'localStorage',
'fetch',
'console',
'setInterval',
'clearInterval',
'setTimeout',
'clearTimeout',
'AbortController',
source,
)
factory(
globalThis.window,
requireShim,
{ visibilityState: 'visible' },
localStorageStub,
fakeFetch,
{ warn: () => {}, log: () => {} },
() => 0,
() => {},
() => 0,
() => {},
typeof AbortController === 'function' ? AbortController : undefined,
)
if (registered === null) throw new Error('the bundle did not register a card')
return registered
}
async function drive(tab, bridgeAvailable, clickAfter, clickOccurrence) {
activeTab = tab
mcpAvailable = bridgeAvailable
hooks = []
cursor = 0
const card = loadBundle()
let text = ''
for (let pass = 0; pass < 6; pass += 1) {
cursor = 0
pendingEffects = []
scheduled = false
text = render(React.createElement(card, null))
const effects = pendingEffects
pendingEffects = []
for (const effect of effects) {
const cleanup = effect()
if (typeof cleanup === 'function') cleanup()
}
await new Promise((resolve) => setTimeout(resolve, 0))
if (!scheduled) break
}
if (clickAfter !== undefined) {
cursor = 0
pendingEffects = []
clickLabel(React.createElement(card, null), clickAfter, clickOccurrence ?? 0)
for (let pass = 0; pass < 4; pass += 1) {
cursor = 0
pendingEffects = []
scheduled = false
text = render(React.createElement(card, null))
const effects = pendingEffects
pendingEffects = []
for (const effect of effects) {
const cleanup = effect()
if (typeof cleanup === 'function') cleanup()
}
await new Promise((resolve) => setTimeout(resolve, 0))
if (!scheduled) break
}
}
return text
}
// ── assertions ──────────────────────────────────────────────────────────
const connection = await drive('connection', true)
check('the connection tab renders its sections', ['连接与上报', '身份验证', '服务地址', '连接与权限检查', '最近上报'].every((label) => connection.includes(label)))
check('a placeholder address shows as unconfigured', connection.includes('未配置服务'))
check('check results are rendered per credential', connection.includes('活动上报权限') && connection.includes('记忆读写权限'))
check('the reporter row survives a real payload', connection.includes('turn-1'))
check('the search limit is renamed and reachable', connection.includes('单次搜索返回上限') || connection.includes('高级设置'))
check('no render boundary error on the connection tab', !connection.includes('渲染失败'))
const skillsText = await drive('skills', true)
check('the skills tab renders its sections', ['技能文件夹', '从 Git 仓库安装', '技能市场', '云端同步与冲突'].every((label) => skillsText.includes(label)))
check('the tree shows every detected source with its path',
skillsText.includes('DSH') && skillsText.includes('Codex') && skillsText.includes('C:/Users/test/.dsh/skills') && skillsText.includes('2 个技能'))
check('categories render with their counts', skillsText.includes('QQ-Skill') && skillsText.includes('1 项 · 1/1 启用') && skillsText.includes('未分类'))
check('the metadata-only promise is on screen', skillsText.includes('分类只记在这个来源里,不移动文件'))
check('a foreign source is marked card-only', skillsText.includes('仅本卡') && skillsText.includes('本卡不修改'))
// Categories start collapsed; expanding one must reveal its skills.
const expandedSkills = await drive('skills', true, '展开或收起 未分类')
check('a collapsed category hides its skills', !skillsText.includes('parked-one'))
check('expanding a category reveals its skill rows',
expandedSkills.includes('parked-one') && expandedSkills.includes('32 B'))
check('a DSH skill row offers detail, a switch and uninstall',
expandedSkills.includes('详情') && expandedSkills.includes('卸载…'))
const foreignSkills = await drive('skills', true, '展开或收起 未分类', 1)
check('a foreign skill row is marked read-only',
foreignSkills.includes('codex-one') && foreignSkills.includes('只读'))
check('the market gap is stated instead of simulated', skillsText.includes('能力缺口') || skillsText.includes('没有接入经验证的市场来源'))
check('no render boundary error on the skills tab', !skillsText.includes('渲染失败'))
const mcpText = await drive('mcp', true)
check('the MCP tab renders the host connection', mcpText.includes('我的连接') && mcpText.includes('demo-mcp'))
check('MCP state, transport and auth are shown', mcpText.includes('已连接') && mcpText.includes('http') && mcpText.includes('bearer'))
check('MCP actions are offered', mcpText.includes('健康检查') && mcpText.includes('工具列表') && mcpText.includes('移除连接'))
check('the injected tools cache starts empty', mcpText.includes('工具可见不等于业务可调用'))
const missing = await drive('mcp', false)
check('a missing bridge becomes a stated capability gap', missing.includes('MCP 管理当前不可用') && missing.includes('MCP 服务器配置'))
check('no render boundary error without the bridge', !missing.includes('渲染失败'))
const failed = results.filter((item) => !item.ok).length
console.log(failed === 0 ? `\nALL ${results.length} CHECKS PASSED` : `\n${failed} CHECK(S) FAILED`)
process.exit(failed === 0 ? 0 : 1)

107
verify-clients.mjs Normal file
View File

@ -0,0 +1,107 @@
// v1.1 verification: cross-software / workspace inventory + dsh-brain migration.
import http from 'node:http'
import { mkdirSync, mkdtempSync, readFileSync, writeFileSync, existsSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const HOME = mkdtempSync(join(tmpdir(), 'brain-homev11-'))
process.env.DSH_HOME = mkdtempSync(join(tmpdir(), 'brain-v11-'))
const DSH = process.env.DSH_HOME
const results = []
function check(name, ok, detail) {
results.push({ name, ok })
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`)
}
function writeSkill(dir, folder, md) {
mkdirSync(join(dir, folder), { recursive: true })
writeFileSync(join(dir, folder, 'SKILL.md'), md)
}
// Global skills for DSH + Codex.
writeSkill(join(DSH, 'skills'), 'dsh-one', '---\nname: dsh-one\ndescription: dsh\n---\n# dsh-one\n')
writeSkill(join(HOME, '.codex', 'skills'), 'cx-one', '---\nname: cx-one\ndescription: codex skill\n---\n# cx-one\n')
// A DSH registry workspace with a workspace-local DSH skills folder.
const wsPath = join(HOME, 'proj-a')
writeSkill(join(wsPath, '.dsh', 'skills'), 'ws-skill', '---\nname: ws-skill\n---\n# ws\n')
writeFileSync(join(DSH, 'workspace-groups.folders.json'), JSON.stringify({ version: 1, workspaces: { group1: { folders: [], members: [{ path: wsPath, workspaceId: 'ws-a', kind: 'local' }] } } }))
writeFileSync(join(DSH, 'workspace-groups.manual.json'), JSON.stringify({ assignments: { 'ws-a': '开发' } }))
const { ClientRegistry } = await import('./lib/clients.js')
const registry = new ClientRegistry({
home: () => HOME,
manualPath: () => join(DSH, 'cloud-memory-workspaces.json'),
dshRegistryPath: () => join(DSH, 'workspace-groups.folders.json'),
dshManualPath: () => join(DSH, 'workspace-groups.manual.json'),
})
const adapters = registry.adapters()
check('six software adapters are reported', adapters.length === 6)
check('installed flags follow the config roots', adapters.find((a) => a.id === 'codex')?.installed === true && adapters.find((a) => a.id === 'opencode')?.installed === false)
check('only DSH is writable', adapters.filter((a) => a.writable).map((a) => a.id).join(',') === 'dsh')
const codexGlobal = await registry.inventory('codex', 'global')
check('codex global inventory is read-only', codexGlobal.items.length === 1 && codexGlobal.items[0].writable === false && codexGlobal.items[0].name === 'cx-one')
const dshWorkspaces = await registry.workspaces('dsh')
check('DSH registry workspace is discovered with its category', dshWorkspaces.some((w) => w.path === wsPath && w.category === '开发'), JSON.stringify(dshWorkspaces))
const wsInv = await registry.inventory('dsh', 'workspace', 'ws-a')
check('DSH workspace inventory finds the workspace-only skill', wsInv.items.length === 1 && wsInv.items[0].folder === 'ws-skill', JSON.stringify(wsInv))
// Manual workspace for Claude Code.
const claudeWs = join(HOME, 'proj-claude')
writeSkill(join(claudeWs, '.claude', 'skills'), 'cl-one', '---\nname: cl-one\n---\n# cl\n')
const added = await registry.addWorkspace('claude', claudeWs, 'ProjC')
check('manual workspace is registered', added.path === claudeWs && added.source === 'manual')
const clInv = await registry.inventory('claude', 'workspace', added.id)
check('manual workspace inventory finds its skill', clInv.items.length === 1 && clInv.items[0].folder === 'cl-one')
check('workspace writes stay read-only for claude', clInv.items[0].writable === false)
let dup = false
try { await registry.addWorkspace('claude', claudeWs, 'again') } catch (e) { dup = e.message === 'duplicate' }
check('duplicate workspace is refused', dup)
let unknown = false
try { await registry.inventory('dsh', 'workspace', 'nope') } catch (e) { unknown = e.message === 'unknown_workspace' }
check('unknown workspace is refused', unknown)
// Routes expose the same data.
const { createRoutes } = await import('./lib/routes.js')
const { SettingsStore } = await import('./lib/store.js')
const { Reporter } = await import('./lib/reporter.js')
const store = new SettingsStore({ clientId: 't' }, join(DSH, 'c.json'))
const reporter = new Reporter({ client: () => ({ reportTurn: async () => ({ ok: true, status: 200, data: {} }), submitSummary: async () => ({ ok: true, status: 200, data: {} }) }), settings: () => ({ enabled: true, clientId: 't' }), activityToken: () => '', summary: () => ({ enabled: false, maxChars: 1 }), summaryToken: () => '', log: () => {} })
const routes = createRoutes({ version: '0.7.0', store, reporter, client: () => ({ reach: async () => ({ ok: false, status: 0, message: 'x' }), listSkills: async () => ({ ok: true, status: 200, data: { items: [] } }) }), clients: registry })
const server = http.createServer((req, res) => {
const path = (req.url ?? '/').split('?')[0]
for (const route of routes) {
if (route.kind === 'exact' && path === route.path) return route.handler(req, res)
if (route.kind === 'prefix' && (path === route.path || path.startsWith(`${route.path}/`))) return route.handler(req, res)
}
res.writeHead(404); res.end('{"ok":false}')
})
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
const origin = `http://127.0.0.1:${server.address().port}`
const capsRes = await fetch(`${origin}/cloud-memory/capabilities`).then((r) => r.json())
check('capabilities advertise multiClient', capsRes.features?.multiClient === true && capsRes.features?.brainMigration === 'pending-deploy')
const overview = await fetch(`${origin}/cloud-memory/clients/overview`).then((r) => r.json())
check('overview route lists adapters and workspaces', overview.ok === true && overview.adapters.length === 6 && Array.isArray(overview.workspaces.dsh))
const invRoute = await fetch(`${origin}/cloud-memory/clients/inventory?software=codex&scope=global`).then((r) => r.json())
check('inventory route returns codex skills', invRoute.ok === true && invRoute.items.length === 1)
await new Promise((resolve) => server.close(resolve))
// dsh-brain migration.
const { brainStatus, migrateLegacyFiles } = await import('./lib/brain-migration.js')
writeFileSync(join(DSH, 'cloud-memory.json'), JSON.stringify({ version: 1, baseUrl: 'https://x/api/longmemory', activityToken: 'cmt_aaaaaaaaaaaaaaaaaaaa' }))
const st = await brainStatus()
check('migration is needed when only legacy files exist', st.migrationNeeded === true && st.packageRename === 'pending-deploy')
const onceRun = await migrateLegacyFiles()
check('legacy config is copied to dsh-brain.json', onceRun.copied.includes('dsh-brain.json') && existsSync(join(DSH, 'dsh-brain.json')))
check('legacy file is retained', existsSync(join(DSH, 'cloud-memory.json')))
const target = JSON.parse(readFileSync(join(DSH, 'dsh-brain.json'), 'utf8'))
check('migrated data matches the legacy token', target.activityToken === 'cmt_aaaaaaaaaaaaaaaaaaaa')
const twiceRun = await migrateLegacyFiles()
check('migration is idempotent', twiceRun.copied.length === 0 && twiceRun.skipped.includes('dsh-brain.json'))
const passed = results.filter((r) => r.ok).length
console.log(`\n${passed}/${results.length} passed`)
process.exit(passed === results.length ? 0 : 1)

70
verify-concurrency.mjs Normal file
View File

@ -0,0 +1,70 @@
// P5 concurrency / mutex verification.
//
// Every mutating skill path must refuse to run while a sync pass is running:
// install staging, install commit, toggle, remove, update apply and rollback.
// The refusal is a typed 409 at the route layer, never a silent partial write.
import http from 'node:http'
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
process.env.DSH_HOME = mkdtempSync(join(tmpdir(), 'brain-conc-'))
const results = []
function check(name, ok, detail) {
results.push({ name, ok })
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`)
}
const { SkillAdmin } = await import('./lib/skill-admin.js')
const { SkillUpdater } = await import('./lib/skill-update.js')
const { SettingsStore } = await import('./lib/store.js')
const { Reporter } = await import('./lib/reporter.js')
const { createRoutes } = await import('./lib/routes.js')
const root = join(process.env.DSH_HOME, 'skills')
const holding = join(process.env.DSH_HOME, 'skills-disabled')
mkdirSync(join(root, 'alpha'), { recursive: true })
writeFileSync(join(root, 'alpha', 'SKILL.md'), '# alpha\n')
let running = true
const admin = new SkillAdmin({ skillsRoot: () => root, holdingDir: () => holding, syncStatePath: () => join(process.env.DSH_HOME, 'cloud-memory-skills.json'), syncRunning: () => running, log: () => {} })
const updater = new SkillUpdater({ admin, skillsRoot: () => root, holdingDir: () => holding, syncRunning: () => running, log: () => {} })
async function expectCode(fn, code) {
try { await fn(); return false } catch (error) { return error.code === code || error.message === code }
}
check('prepareInstall refuses while sync runs', await expectCode(() => admin.prepareInstall('https://example.org/x.git'), 'sync_running'))
check('commitInstall refuses while sync runs', await expectCode(() => admin.commitInstall({ planId: 'x', folders: [] }), 'sync_running'))
check('setEnabled refuses while sync runs', await expectCode(() => admin.setEnabled('alpha', false), 'sync_running'))
check('remove refuses while sync runs', await expectCode(() => admin.remove('alpha'), 'sync_running'))
check('applyUpdate refuses while sync runs', await expectCode(() => updater.applyUpdate('alpha', 'deadbeef'), 'sync_running'))
check('rollback refuses while sync runs', await expectCode(() => updater.rollback('alpha'), 'sync_running'))
// Route layer maps the refusal to 409.
const store = new SettingsStore({ clientId: 't' }, join(process.env.DSH_HOME, 'c.json'))
const reporter = new Reporter({ client: () => ({ reportTurn: async () => ({ ok: true, status: 200, data: {} }), submitSummary: async () => ({ ok: true, status: 200, data: {} }) }), settings: () => ({ enabled: true, clientId: 't' }), activityToken: () => '', summary: () => ({ enabled: false, maxChars: 1 }), summaryToken: () => '', log: () => {} })
const routes = createRoutes({ version: '0.6.0', store, reporter, client: () => ({ reach: async () => ({ ok: false, status: 0, message: 'x' }), listSkills: async () => ({ ok: true, status: 200, data: { items: [] } }) }), admin, updates: updater })
const server = http.createServer((req, res) => {
const path = (req.url ?? '/').split('?')[0]
for (const route of routes) {
if (route.kind === 'exact' && path === route.path) return route.handler(req, res)
if (route.kind === 'prefix' && (path === route.path || path.startsWith(`${route.path}/`))) return route.handler(req, res)
}
res.writeHead(404); res.end('{"ok":false}')
})
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
const origin = `http://127.0.0.1:${server.address().port}`
const response = await fetch(`${origin}/cloud-memory/skills/toggle`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ folder: 'alpha', enabled: false }) })
const body = await response.json()
check('route answers 409 sync_running during a sync', response.status === 409 && body.code === 'sync_running', JSON.stringify(body))
await new Promise((resolve) => server.close(resolve))
// After the sync ends, the same toggle succeeds.
running = false
const enabled = await admin.setEnabled('alpha', false)
check('after the sync ends the mutation is allowed', enabled.folder === 'alpha' && enabled.enabled === false)
const passed = results.filter((r) => r.ok).length
console.log(`\n${passed}/${results.length} passed`)
process.exit(passed === results.length ? 0 : 1)

85
verify-full-load.mjs Normal file
View File

@ -0,0 +1,85 @@
// Whole-plugin load test: activate the real `apply()` against a host-shaped
// context, then serve the exact routes it registered over a real HTTP server and
// query them. This proves the 0.7.0 build loads and serves every surface a DSH
// restart will expose, without needing to restart the desktop app.
import http from 'node:http'
import { mkdtempSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
process.env.DSH_HOME = mkdtempSync(join(tmpdir(), 'brain-load-'))
const results = []
function check(name, ok, detail) {
results.push({ name, ok })
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`)
}
const { apply } = await import('./lib/index.js')
const routes = []
const disposers = []
const ctx = {
logger: () => ({ info: () => {}, warn: () => {} }),
effect: (fn) => { const result = fn(); if (typeof result === 'function') disposers.push(result); return () => {} },
on: () => () => {},
inject: (_deps, fn) => fn({ tools: { register: () => () => {} }, effect: (inner) => { inner(); return () => {} } }),
webServer: { register: (route) => { routes.push(route); return () => {} } },
}
let applied = true
try {
apply(ctx, { baseUrl: 'https://your-memory-host/api/longmemory', clientId: 'load-test' })
} catch (failure) {
applied = false
console.log('apply threw:', failure)
}
check('apply() loads against a host-shaped context', applied)
const server = http.createServer((req, res) => {
const path = (req.url ?? '/').split('?')[0]
for (const route of routes) {
if (route.kind === 'exact' && path === route.path) return route.handler(req, res)
if (route.kind === 'prefix' && (path === route.path || path.startsWith(`${route.path}/`))) return route.handler(req, res)
}
res.writeHead(404, { 'content-type': 'application/json' })
res.end('{"ok":false,"error":"no-route"}')
})
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
const origin = `http://127.0.0.1:${server.address().port}`
async function get(path) {
const response = await fetch(`${origin}${path}`)
return { status: response.status, body: await response.json().catch(() => null) }
}
async function post(path, body) {
const response = await fetch(`${origin}${path}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body ?? {}) })
return { status: response.status, body: await response.json().catch(() => null) }
}
const caps = await get('/cloud-memory/capabilities')
check('capabilities answers with 0.7.0', caps.body?.version === '0.7.0', String(caps.body?.version))
check('P3 market is advertised with one provider', caps.body?.features?.skillsMarketplace === true && caps.body?.features?.marketProviders === 1)
check('P3 update and sync-resolve are advertised', caps.body?.features?.skillUpdate === true && caps.body?.features?.syncResolve === true)
check('P4/P5/v1.1 flags are advertised', caps.body?.features?.multiClient === true && caps.body?.features?.brainMigration === 'pending-deploy')
const providers = await get('/cloud-memory/market/providers')
check('market providers route lists the verified source', providers.body?.providers?.[0]?.id === 'anthropic-skills', JSON.stringify(providers.body?.providers))
const sync = await get('/cloud-memory/sync/status')
check('sync status route answers', sync.body?.ok === true && Array.isArray(sync.body?.conflicts))
const clients = await get('/cloud-memory/clients/overview')
check('clients overview lists six adapters', clients.body?.ok === true && clients.body?.adapters?.length === 6)
const brain = await get('/cloud-memory/migrate/brain')
check('brain migration status answers', brain.body?.ok === true && brain.body?.product === 'DSH Brain' && brain.body?.packageRename === 'pending-deploy')
const inv = await get('/cloud-memory/clients/inventory?software=dsh&scope=global')
check('inventory route answers for DSH', inv.body?.ok === true && Array.isArray(inv.body?.items))
const skills = await get('/cloud-memory/skills/api')
check('skill inventory route answers', skills.body?.ok === true && Array.isArray(skills.body?.skills))
const status = await get('/cloud-memory/status')
check('status route answers', status.body?.ok === true && status.body?.settings?.baseUrlConfigured === false)
await new Promise((resolve) => server.close(resolve))
for (const dispose of disposers) { try { dispose() } catch { /* teardown noise */ } }
const failed = results.filter((item) => !item.ok).length
console.log(failed === 0 ? `\nALL ${results.length} CHECKS PASSED` : `\n${failed} CHECK(S) FAILED`)
process.exit(failed === 0 ? 0 : 1)

153
verify-market.mjs Normal file
View File

@ -0,0 +1,153 @@
// Verification for P3 market: provider parsing + the market plan/commit routes.
//
// Two layers:
// 1. the Claude plugin marketplace provider is exercised with a stubbed
// fetch, so the manifest/search/detail/resolve contract is deterministic;
// 2. the routes are exercised against a real HTTP server, a real SkillAdmin
// and a real throwaway git repository (file://), so an install genuinely
// clones, pins the commit and writes `.skill-source.json`.
import http from 'node:http'
import { execFileSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, readFileSync, writeFileSync, existsSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
process.env.DSH_HOME = mkdtempSync(join(tmpdir(), 'brain-market-'))
const results = []
function check(name, ok, detail) {
results.push({ name, ok })
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`)
}
// ── 1. Provider parsing with a stubbed fetch ────────────────────────────
const { ClaudePluginMarketplaceProvider, MarketService, MarketError } = await import('./lib/market.js')
const manifest = {
name: 'anthropic-agent-skills',
owner: { name: 'Anthropic' },
metadata: { version: '1.0.0' },
plugins: [
{ name: 'document-skills', description: 'Excel/Word/PPT/PDF', source: './', skills: ['./skills/xlsx', './skills/docx'] },
{ name: 'example-skills', description: 'creative examples', source: './', skills: ['./skills/algorithmic-art'] },
],
}
const skillMd = {
'skills/xlsx/SKILL.md': '---\nname: xlsx\ndescription: Spreadsheet skill\n---\n# xlsx\n',
'skills/docx/SKILL.md': '---\nname: docx\ndescription: Word skill\n---\n# docx\n',
'skills/algorithmic-art/SKILL.md': '---\nname: algorithmic-art\ndescription: art\n---\n# art\n',
}
const stubFetch = async (url) => {
const path = String(url)
if (path.includes('/.claude-plugin/marketplace.json')) return { ok: true, status: 200, text: async () => JSON.stringify(manifest) }
if (path.includes('/commits/')) return { ok: true, status: 200, text: async () => JSON.stringify({ sha: 'f00dbabe1234567890abcdef1234567890abcdef' }) }
for (const [rel, body] of Object.entries(skillMd)) {
if (path.includes(`/${rel}`)) return { ok: true, status: 200, text: async () => body }
}
return { ok: false, status: 404, text: async () => 'not found' }
}
const provider = new ClaudePluginMarketplaceProvider({
id: 'anthropic-skills', label: 'Anthropic', description: 'test', repo: 'anthropics/skills', ref: 'main', fetchImpl: stubFetch,
})
const all = await provider.search('', 0)
check('provider lists all manifest plugins', all.entries.length === 2, String(all.entries.length))
check('entries carry normalized skill folder names', all.entries[0].skills.join(',') === 'xlsx,docx', all.entries[0].skills.join(','))
const filtered = await provider.search('word', 0)
check('search filters by description/skill text', filtered.entries.length === 1 && filtered.entries[0].id === 'document-skills')
const detail = await provider.getDetail('document-skills')
check('detail reads SKILL.md frontmatter per skill', detail.skillDetails.length === 2 && detail.skillDetails[0].name === 'xlsx', JSON.stringify(detail.skillDetails.map((s) => s.name)))
const artifact = await provider.resolveArtifact('example-skills')
check('resolveArtifact pins the resolved commit', artifact.commit === 'f00dbabe1234567890abcdef1234567890abcdef', String(artifact.commit))
check('resolveArtifact returns the entry folders', artifact.folders.join(',') === 'algorithmic-art')
// A provider that fails must surface a typed MarketError, not a raw throw.
let typed = false
try { await new MarketService([]).search('nope', '', 0) } catch (error) { typed = error instanceof MarketError && error.code === 'unknown_provider' }
check('unknown provider raises a typed MarketError', typed)
// ── 2. Routes against a real git repo ───────────────────────────────────
const root = join(process.env.DSH_HOME, 'skills')
const holding = join(process.env.DSH_HOME, 'skills-disabled')
const repoDir = join(process.env.DSH_HOME, 'src-repo')
mkdirSync(join(repoDir, 'skills', 'alpha'), { recursive: true })
mkdirSync(join(repoDir, 'skills', 'beta'), { recursive: true })
writeFileSync(join(repoDir, 'skills', 'alpha', 'SKILL.md'), '---\nname: alpha\ndescription: alpha skill\n---\n# alpha\n')
mkdirSync(join(repoDir, 'skills', 'alpha', 'references'), { recursive: true })
writeFileSync(join(repoDir, 'skills', 'alpha', 'references', 'a.md'), 'note')
writeFileSync(join(repoDir, 'skills', 'beta', 'SKILL.md'), '---\nname: beta\n---\n# beta\n')
execFileSync('git', ['init', '-b', 'main'], { cwd: repoDir })
execFileSync('git', ['-C', repoDir, 'add', '-A'])
execFileSync('git', ['-C', repoDir, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-m', 'init'])
const commit = execFileSync('git', ['-C', repoDir, 'rev-parse', 'HEAD']).toString().trim()
const repoUrl = 'file://' + repoDir.replace(/\\/g, '/')
const { SettingsStore } = await import('./lib/store.js')
const { Reporter } = await import('./lib/reporter.js')
const { SkillAdmin } = await import('./lib/skill-admin.js')
const { createRoutes } = await import('./lib/routes.js')
const store = new SettingsStore({ clientId: 'test', requestTimeoutMs: 2000, defaultK: 10 }, join(process.env.DSH_HOME, 'cloud-memory.json'))
const reporter = new Reporter({
client: () => ({ reportTurn: async () => ({ ok: true, status: 200, data: {} }), submitSummary: async () => ({ ok: true, status: 200, data: {} }) }),
settings: () => ({ enabled: true, clientId: 'test' }), activityToken: () => '', summary: () => ({ enabled: false, maxChars: 1 }), summaryToken: () => '', log: () => {},
})
const admin = new SkillAdmin({ skillsRoot: () => root, holdingDir: () => holding, syncStatePath: () => join(process.env.DSH_HOME, 'cloud-memory-skills.json'), syncRunning: () => false, log: () => {} })
const entry = { id: 'alpha', providerId: 'fake', name: 'alpha', description: 'fake alpha', skills: ['alpha'], skillPaths: ['./skills/alpha'], sourceRepo: 'local/repo', sourceUrl: 'file://x' }
const fakeProvider = {
info: () => ({ id: 'fake', label: 'Fake', description: 'local', source: 'local/repo', homepage: 'https://example' }),
search: async () => ({ entries: [entry] }),
getDetail: async () => ({ ...entry, skillDetails: [{ folder: 'alpha', path: './skills/alpha', name: 'alpha', ok: true }], fetchedAt: Date.now() }),
resolveArtifact: async () => ({ repoUrl, ref: 'main', commit, folders: ['alpha'] }),
}
const market = new MarketService([fakeProvider])
const routes = createRoutes({
version: '0.6.0-test', store, reporter,
client: () => ({ reach: async () => ({ ok: false, status: 0, message: 'stub' }), listSkills: async () => ({ ok: true, status: 200, data: { items: [] } }), skillBundle: async () => ({ ok: false, error: { status: 404, code: 'x', message: 'x' } }) }),
admin, market,
})
const server = http.createServer((req, res) => {
const path = (req.url ?? '/').split('?')[0]
for (const route of routes) {
if (route.kind === 'exact' && path === route.path) return route.handler(req, res)
if (route.kind === 'prefix' && (path === route.path || path.startsWith(`${route.path}/`))) return route.handler(req, res)
}
res.writeHead(404); res.end('{"ok":false}')
})
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
const origin = `http://127.0.0.1:${server.address().port}`
async function call(method, path, body) {
const headers = { accept: 'application/json' }
let payload
if (body !== undefined) { headers['content-type'] = 'application/json'; payload = JSON.stringify(body) }
const response = await fetch(`${origin}${path}`, { method, headers, body: payload })
return { status: response.status, body: await response.json().catch(() => null) }
}
const caps = await call('GET', '/cloud-memory/capabilities')
check('capabilities advertise the wired market', caps.body?.features?.skillsMarketplace === true && caps.body?.features?.marketProviders === 1)
const providers = await call('GET', '/cloud-memory/market/providers')
check('providers route lists the provider', providers.body?.providers?.[0]?.id === 'fake')
const search = await call('GET', '/cloud-memory/market/search?provider=fake&q=alp')
check('search route returns entries', search.status === 200 && search.body?.entries?.length === 1)
const unknown = await call('GET', '/cloud-memory/market/search?provider=nope&q=')
check('unknown provider is a 400', unknown.status === 400 && unknown.body?.code === 'unknown_provider')
const det = await call('POST', '/cloud-memory/market/detail', { provider: 'fake', id: 'alpha' })
check('detail route returns skill metadata', det.status === 200 && det.body?.skillDetails?.[0]?.name === 'alpha')
const plan = await call('POST', '/cloud-memory/market/plan', { provider: 'fake', id: 'alpha' })
check('plan route returns a staged plan', plan.status === 200 && typeof plan.body?.planId === 'string', JSON.stringify(plan.body).slice(0, 120))
check('plan pins the resolved commit', plan.body?.commit === commit)
check('plan only exposes the entry folders (beta excluded)', Array.isArray(plan.body?.candidates) && plan.body.candidates.length === 1 && plan.body.candidates[0].folder === 'alpha')
const commitRes = await call('POST', '/cloud-memory/market/commit', { planId: plan.body?.planId, folders: ['alpha'] })
check('commit installs the selected skill', commitRes.status === 200 && commitRes.body?.installed?.includes('alpha'), JSON.stringify(commitRes.body))
check('installed skill has a SKILL.md', existsSync(join(root, 'alpha', 'SKILL.md')))
check('beta was never installed', !existsSync(join(root, 'beta')))
const source = JSON.parse(readFileSync(join(root, 'alpha', '.skill-source.json'), 'utf8'))
check('provenance records provider/commit/sourcePath', source.provider === 'fake' && source.commit === commit && source.sourcePath.includes('alpha'), JSON.stringify(source))
await new Promise((resolve) => server.close(resolve))
const passed = results.filter((r) => r.ok).length
console.log(`\n${passed}/${results.length} passed`)
process.exit(passed === results.length ? 0 : 1)

54
verify-mcp-bridge.mjs Normal file
View File

@ -0,0 +1,54 @@
// Live probe of the host dsh-mcp-connector public bridge (P4 evidence).
//
// Not a unit test: it talks to a running DSH web server. If the server or the
// connector plugin is absent it prints SKIP and exits 0 so it never blocks CI.
// Usage: node verify-mcp-bridge.mjs [http://127.0.0.1:4503]
const base = process.argv[2] ?? process.env.DSH_WEB_URL ?? 'http://127.0.0.1:4503'
async function call(method, params) {
const response = await fetch(`${base}/mcp-connector/api`, {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify({ method, params: params ?? {} }),
})
return { status: response.status, body: await response.json().catch(() => null) }
}
let reachable = true
try {
const probe = await call('status', {})
if (probe.status === 404) reachable = false
} catch {
reachable = false
}
if (!reachable) {
console.log(`SKIP no dsh-mcp-connector bridge at ${base}`)
process.exit(0)
}
const results = []
function check(name, ok, detail) {
results.push({ name, ok })
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`)
}
const version = await call('versionStatus', {})
check('versionStatus answers', version.body?.ok === true)
const catalog = await call('catalog', { keyword: '' })
const items = Array.isArray(catalog.body?.detail?.items) ? catalog.body.detail.items : []
check('catalog lists published connectors', catalog.body?.ok === true && items.length > 0, `${items.length} items`)
check('catalog entries carry authMode + connection state', items.length > 0 && typeof items[0].authMode === 'string' && typeof items[0].connectionState === 'string')
const gov = await call('governance', {})
check('governance returns a revision + rules', gov.body?.ok === true && gov.body?.detail?.revision !== undefined && Array.isArray(gov.body?.detail?.rules))
const scope = await call('scopeContext', {})
check('scopeContext returns the scope document', scope.body?.ok === true && scope.body?.detail?.revision !== undefined)
const status = await call('status', {})
check('status returns connections + scope', status.body?.ok === true && Array.isArray(status.body?.detail?.items))
const stats = await call('connectionStatistics', {})
check('connectionStatistics answers', stats.body?.ok === true)
const snapshots = await call('listSnapshots', {})
check('snapshots list answers', snapshots.body?.ok === true)
const passed = results.filter((r) => r.ok).length
console.log(`\n${passed}/${results.length} live bridge checks passed`)
process.exit(passed === results.length ? 0 : 1)

92
verify-plugin-entry.mjs Normal file
View File

@ -0,0 +1,92 @@
// Entry-point smoke test: a plugin that throws from `apply` takes the whole web
// boot down, so the cheapest insurance is to activate the real entry against a
// fake host context and check the route table it registers.
//
// Deliberately not a unit test of every timer: it proves `apply` runs, wires the
// expected routes, and tears everything down through the disposers it returned.
import { mkdtempSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
process.env.DSH_HOME = mkdtempSync(join(tmpdir(), 'brain-entry-'))
const results = []
function check(name, ok, detail) {
results.push({ name, ok })
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`)
}
const { apply } = await import('./lib/index.js')
const routes = []
const disposers = []
const tools = []
const ctx = {
logger: () => ({ info: () => {}, warn: () => {} }),
effect: (fn) => {
const result = fn()
if (typeof result === 'function') disposers.push(result)
return () => {}
},
on: () => () => {},
inject: (deps, fn) => {
fn({
tools: {
register: (tool) => {
tools.push(tool)
return () => {}
},
},
effect: (inner) => {
inner()
return () => {}
},
})
},
webServer: {
register: (route) => {
routes.push(route)
return () => {}
},
},
}
let applied = true
try {
apply(ctx, { baseUrl: 'https://your-memory-host/api/longmemory', clientId: 'smoke' })
} catch (failure) {
applied = false
console.log('apply threw:', failure)
}
check('apply() completes against a host-shaped context', applied)
const expected = [
'exact:/cloud-memory',
'exact:/cloud-memory/status',
'exact:/cloud-memory/capabilities',
'exact:/cloud-memory/config',
'exact:/cloud-memory/login',
'exact:/cloud-memory/test',
'exact:/cloud-memory/flush',
'prefix:/cloud-memory/skills',
'prefix:/cloud-memory/market',
'prefix:/cloud-memory/sync',
'prefix:/cloud-memory/clients',
'prefix:/cloud-memory/migrate',
]
const actual = routes.map((route) => `${route.kind}:${route.path}`)
check('every route the card depends on is registered', expected.every((item) => actual.includes(item)), actual.join(' | '))
check('the memory tools are still registered', tools.length >= 3, `${tools.length} tools`)
let disposed = true
try {
for (const dispose of disposers) dispose()
} catch (failure) {
disposed = false
console.log('dispose threw:', failure)
}
check('every registered effect is disposable', disposed)
const failed = results.filter((item) => !item.ok).length
console.log(failed === 0 ? `\nALL ${results.length} CHECKS PASSED` : `\n${failed} CHECK(S) FAILED`)
process.exit(failed === 0 ? 0 : 1)

234
verify-skill-tree.mjs Normal file
View File

@ -0,0 +1,234 @@
// Verification for the multi-source skill tree (sources → categories → skills).
//
// The two things that must not regress are stated in the UI copy, so they are
// asserted here: a category is metadata only (creating, renaming, deleting one
// never moves a file), and only the DSH source switch really parks skills —
// another software's directory is never touched.
import http from 'node:http'
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
process.env.DSH_HOME = mkdtempSync(join(tmpdir(), 'brain-tree-'))
const results = []
function check(name, ok, detail) {
results.push({ name, ok })
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`)
}
const writeSkill = (area, folder, files = { 'SKILL.md': `# ${folder}\n` }) => {
for (const [rel, content] of Object.entries(files)) {
const target = join(area, folder, ...rel.split('/'))
mkdirSync(join(target, '..'), { recursive: true })
writeFileSync(target, content)
}
}
const root = join(process.env.DSH_HOME, 'skills')
const holding = join(process.env.DSH_HOME, 'skills-disabled')
const foreignRoot = join(tmpdir(), `foreign-agents-${Date.now()}`)
const { SkillAdmin } = await import('./lib/skill-admin.js')
const { SkillGroupManager, SkillGroupError, detectSources } = await import('./lib/skill-groups.js')
const { SettingsStore } = await import('./lib/store.js')
const { Reporter } = await import('./lib/reporter.js')
const { createRoutes } = await import('./lib/routes.js')
const admin = new SkillAdmin({
skillsRoot: () => root,
holdingDir: () => holding,
syncStatePath: () => join(process.env.DSH_HOME, 'cloud-memory-skills.json'),
syncRunning: () => false,
log: () => {},
})
writeSkill(root, 'qqcites', { 'SKILL.md': '---\nname: qqcites\ndescription: 引用\ndescription: 引用候选\n---\n\n# qqcites\n', 'a.md': 'x' })
writeSkill(root, 'qqnote', { 'SKILL.md': '---\nname: qqnote\n---\n\n# qqnote\n' })
writeSkill(root, 'blender', { 'SKILL.md': '---\nname: blender\ndescription: 建模\n---\n\n# blender\n' })
writeSkill(foreignRoot, 'codex-one', { 'SKILL.md': '---\nname: codex-one\n---\n\n# codex-one\n' })
writeSkill(foreignRoot, 'codex-two', { 'SKILL.md': '---\nname: codex-two\n---\n\n# codex-two\n' })
const sources = () => [
{ id: 'dsh', label: 'DSH', root, writable: true, manager: 'DSH' },
{
id: 'codex',
label: 'Codex',
root: foreignRoot,
writable: false,
manager: 'Codex',
note: '由 Codex 自行加载,本卡不修改它的目录',
},
]
const storePath = join(process.env.DSH_HOME, 'cloud-memory-skill-groups.json')
const manager = new SkillGroupManager({ sources, admin, storePath: () => storePath })
// ── A. overview ─────────────────────────────────────────────────────────
const overview = await manager.overview()
check('the overview carries the metadata-only promise', String(overview.note).includes('不移动文件'))
check('the note says only DSH switches are real', String(overview.note).includes('只有 DSH 来源的开关会真实启停'))
const dsh = overview.sources.find((source) => source.id === 'dsh')
check('the DSH source lists its three skills', dsh?.total === 3 && dsh?.enabledCount === 3)
check('every skill starts in 未分类', dsh?.groups.length === 1 && dsh?.groups[0].id === 'unassigned' && dsh?.groups[0].total === 3)
check('the DSH switch is editable and real', dsh?.enabledEditable === true && dsh?.cardOnly === false)
const codex = overview.sources.find((source) => source.id === 'codex')
check('a foreign source is read-only and says so', codex?.writable === false && codex?.cardOnly === true && String(codex?.note).includes('不修改'))
check('a foreign source lists its skills', codex?.total === 2)
const detected = detectSources()
check('the detector knows the six software roots',
['dsh', 'agents', 'codex', 'workbuddy', 'claude', 'opencode'].every((id) => detected.some((source) => source.id === id)))
// ── B. categories are metadata ──────────────────────────────────────────
const created = await manager.createGroup('dsh', 'QQ-Skill')
check('a category can be created', typeof created.groupId === 'string' && created.name === 'QQ-Skill')
await manager.createGroup('dsh', 'QQ-Skill').then(
() => check('a duplicate name is refused', false),
(error) => check('a duplicate name is refused', error instanceof SkillGroupError && error.code === 'duplicate'),
)
await manager.createGroup('dsh', '').then(
() => check('an empty name is refused', false),
(error) => check('an empty name is refused', error instanceof SkillGroupError && error.code === 'invalid_name'),
)
await manager.createGroup('nope', 'x').then(
() => check('an unknown source is refused', false),
(error) => check('an unknown source is refused', error instanceof SkillGroupError && error.code === 'unknown_source'),
)
await manager.assign('dsh', created.groupId, ['qqcites', 'qqnote'])
let view = await manager.overview()
let dshView = view.sources.find((source) => source.id === 'dsh')
let group = dshView.groups.find((item) => item.id === created.groupId)
check('assigning moves skills out of 未分类', group?.total === 2 && dshView.groups.find((item) => item.id === 'unassigned')?.total === 1)
check('the group shows "2 项 · 2/2 启用" numbers', group?.total === 2 && group?.enabledCount === 2)
check('assigning does not move a single file', existsSync(join(root, 'qqcites', 'SKILL.md')) && existsSync(join(root, 'qqnote', 'SKILL.md')))
const second = await manager.createGroup('dsh', '建模')
await manager.assign('dsh', second.groupId, ['blender', 'qqnote'])
view = await manager.overview()
dshView = view.sources.find((source) => source.id === 'dsh')
check('a skill belongs to at most one category',
dshView.groups.find((item) => item.id === second.groupId)?.total === 2 &&
dshView.groups.find((item) => item.id === created.groupId)?.total === 1)
// ── C. real switches for DSH, card-only for others ──────────────────────
const off = await manager.toggleGroup('dsh', second.groupId, false)
check('switching a DSH category off really parks its skills',
off.cardOnly === false && off.applied.length === 2 && existsSync(join(holding, 'blender')) && !existsSync(join(root, 'blender')))
view = await manager.overview()
dshView = view.sources.find((source) => source.id === 'dsh')
check('the parked skill is reported as disabled', dshView.groups.find((item) => item.id === second.groupId)?.enabledCount === 0)
const on = await manager.toggleGroup('dsh', second.groupId, true)
check('switching it back restores the folders',
on.applied.length === 2 && existsSync(join(root, 'blender')) && !existsSync(join(holding, 'blender')))
const codexGroup = await manager.createGroup('codex', '外部组')
await manager.assign('codex', codexGroup.groupId, ['codex-one'])
const before = readFileSync(join(foreignRoot, 'codex-one', 'SKILL.md'), 'utf8')
const codexOff = await manager.toggleGroup('codex', codexGroup.groupId, false)
check('a foreign category switch is card-only', codexOff.cardOnly === true && codexOff.applied.length === 0)
check('a foreign directory is left byte-identical',
existsSync(join(foreignRoot, 'codex-one', 'SKILL.md')) && readFileSync(join(foreignRoot, 'codex-one', 'SKILL.md'), 'utf8') === before)
view = await manager.overview()
const codexView = view.sources.find((source) => source.id === 'codex')
check('the card-only switch is visible as in-card disabled',
codexView.groups.find((item) => item.id === codexGroup.groupId)?.skills[0]?.inCardDisabled === true)
const codexSourceOff = await manager.toggleSource('codex', false)
check('a foreign source switch is card-only too', codexSourceOff.cardOnly === true)
const codexSourceOn = await manager.toggleSource('codex', true)
check('the foreign source switch restores in-card visibility', codexSourceOn.enabled === true)
// ── D. rename / delete ──────────────────────────────────────────────────
const renamed = await manager.renameGroup('dsh', created.groupId, 'QQ 技能')
check('a category can be renamed', renamed.name === 'QQ 技能')
const deleted = await manager.deleteGroup('dsh', created.groupId)
check('deleting a category releases its skills', deleted.released === 1)
view = await manager.overview()
dshView = view.sources.find((source) => source.id === 'dsh')
check('released skills are back in 未分类', dshView.groups.find((item) => item.id === 'unassigned')?.total === 1)
check('deleting a category never deletes a file', existsSync(join(root, 'qqcites', 'SKILL.md')))
// The 未分类 bucket switch parks exactly the skills no category claims.
const bucketOff = await manager.toggleGroup('dsh', 'unassigned', false)
check('the 未分类 switch parks only the unclaimed skills',
bucketOff.cardOnly === false && bucketOff.applied.join(',') === 'qqcites' && existsSync(join(holding, 'qqcites')))
const bucketOn = await manager.toggleGroup('dsh', 'unassigned', true)
check('the 未分类 switch restores them',
bucketOn.applied.join(',') === 'qqcites' && existsSync(join(root, 'qqcites')))
check('the remaining category is untouched', dshView.groups.find((item) => item.id === second.groupId)?.total === 2)
// ── E. persistence and route surface ────────────────────────────────────
const reopened = new SkillGroupManager({ sources, admin, storePath: () => storePath })
const afterReload = await reopened.overview()
check('categories survive a manager restart',
afterReload.sources.find((source) => source.id === 'dsh')?.groups.some((item) => item.name === '建模'))
check('the sidecar holds metadata only, never a file path',
!readFileSync(storePath, 'utf8').includes('SKILL.md'))
const store = new SettingsStore({ baseUrl: 'https://memory.example.org/api/longmemory' }, join(process.env.DSH_HOME, 'cloud-memory.json'))
const reporter = new Reporter({
client: () => ({ reportTurn: async () => ({ ok: true, status: 200, data: {} }) }),
settings: () => ({ enabled: true, clientId: 'tree' }),
activityToken: () => '',
summary: () => ({ enabled: false, maxChars: 1000 }),
summaryToken: () => '',
log: () => {},
})
const routes = createRoutes({
version: '0.5.0-test',
store,
reporter,
client: () => ({ reach: async () => ({ ok: false, status: 0, message: 'stub' }) }),
admin,
groups: reopened,
})
const server = http.createServer((req, res) => {
const path = (req.url ?? '/').split('?')[0]
for (const route of routes) {
if (route.kind === 'exact' && path === route.path) return route.handler(req, res)
if (route.kind === 'prefix' && (path === route.path || path.startsWith(`${route.path}/`))) return route.handler(req, res)
}
res.writeHead(404, { 'content-type': 'application/json' })
res.end('{"ok":false}')
})
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
const origin = `http://127.0.0.1:${server.address().port}`
async function call(method, path, body) {
const headers = { accept: 'application/json' }
let payload
if (body !== undefined) {
headers['content-type'] = 'application/json'
payload = JSON.stringify(body)
}
const response = await fetch(`${origin}${path}`, { method, headers, body: payload })
const text = await response.text()
let parsed = null
try {
parsed = JSON.parse(text)
} catch {
parsed = null
}
return { status: response.status, body: parsed }
}
const sourcesResponse = await call('GET', '/cloud-memory/skills/sources')
check('the sources route answers with the tree', sourcesResponse.status === 200 && Array.isArray(sourcesResponse.body?.sources))
check('the tree carries the metadata-only note', String(sourcesResponse.body?.note).includes('不移动文件'))
check('POST on the sources route is refused', (await call('POST', '/cloud-memory/skills/sources', {}))?.status === 405)
const viaRoute = await call('POST', '/cloud-memory/skills/groups/create', { sourceId: 'dsh', name: '路由组' })
check('a category can be created over HTTP', viaRoute.status === 200 && typeof viaRoute.body?.groupId === 'string')
const dupViaRoute = await call('POST', '/cloud-memory/skills/groups/create', { sourceId: 'dsh', name: '路由组' })
check('a duplicate over HTTP is a 400', dupViaRoute.status === 400 && dupViaRoute.body?.code === 'duplicate')
const missingGroup = await call('POST', '/cloud-memory/skills/groups/delete', { sourceId: 'dsh', groupId: 'g_missing' })
check('an unknown category is a 404', missingGroup.status === 404)
const revealMissing = await call('POST', '/cloud-memory/skills/source/reveal', { sourceId: 'agents' })
check('revealing a missing directory reports not_found instead of failing silently', revealMissing.status === 404 || revealMissing.status === 200)
server.close()
const failed = results.filter((item) => !item.ok).length
console.log(failed === 0 ? `\nALL ${results.length} CHECKS PASSED` : `\n${failed} CHECK(S) FAILED`)
process.exit(failed === 0 ? 0 : 1)

79
verify-skill-update.mjs Normal file
View File

@ -0,0 +1,79 @@
// Verification for P3 skill update/rollback.
//
// Uses a real throwaway git repository and the real install pipeline, so the
// `.skill-source.json` provenance, the diff, the pre-update backup and the
// rollback restore are all exercised end to end.
import { execFileSync } from 'node:child_process'
import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
process.env.DSH_HOME = mkdtempSync(join(tmpdir(), 'brain-update-'))
const results = []
function check(name, ok, detail) {
results.push({ name, ok })
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`)
}
const { SkillAdmin } = await import('./lib/skill-admin.js')
const { SkillUpdater } = await import('./lib/skill-update.js')
const root = join(process.env.DSH_HOME, 'skills')
const holding = join(process.env.DSH_HOME, 'skills-disabled')
const repoDir = join(process.env.DSH_HOME, 'repo')
mkdirSync(join(repoDir, 'alpha'), { recursive: true })
writeFileSync(join(repoDir, 'alpha', 'SKILL.md'), '---\nname: alpha\ndescription: v1\n---\n# alpha v1\n')
execFileSync('git', ['init', '-b', 'main'], { cwd: repoDir })
execFileSync('git', ['-C', repoDir, 'add', '-A'])
execFileSync('git', ['-C', repoDir, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-m', 'v1'])
const c1 = execFileSync('git', ['-C', repoDir, 'rev-parse', 'HEAD']).toString().trim()
const repoUrl = 'file://' + repoDir.replace(/\\/g, '/')
const admin = new SkillAdmin({ skillsRoot: () => root, holdingDir: () => holding, syncStatePath: () => join(process.env.DSH_HOME, 'cloud-memory-skills.json'), syncRunning: () => false, log: () => {} })
const updater = new SkillUpdater({ admin, skillsRoot: () => root, holdingDir: () => holding, syncRunning: () => false, log: () => {} })
// Install alpha from the repo.
const plan = await admin.prepareInstall(repoUrl)
await admin.commitInstall({ planId: plan.planId, folders: ['alpha'] })
check('installed alpha with provenance', existsSync(join(root, 'alpha', '.skill-source.json')))
check('installed content is v1', readFileSync(join(root, 'alpha', 'SKILL.md'), 'utf8').includes('v1'))
// A skill without a source record cannot be updated.
mkdirSync(join(root, 'plain'), { recursive: true })
writeFileSync(join(root, 'plain', 'SKILL.md'), '# plain\n')
const plain = await updater.checkUpdate('plain')
check('no source record → updatable:false', plain.updatable === false && plain.reason === 'no_source')
// Publish v2 upstream.
writeFileSync(join(repoDir, 'alpha', 'SKILL.md'), '---\nname: alpha\ndescription: v2\n---\n# alpha v2\n')
writeFileSync(join(repoDir, 'alpha', 'extra.md'), 'new file')
execFileSync('git', ['-C', repoDir, 'add', '-A'])
execFileSync('git', ['-C', repoDir, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-m', 'v2'])
const c2 = execFileSync('git', ['-C', repoDir, 'rev-parse', 'HEAD']).toString().trim()
const check1 = await updater.checkUpdate('alpha')
check('checkUpdate sees a new commit', check1.available === true && check1.currentCommit === c1 && check1.remoteCommit === c2, JSON.stringify(check1))
check('checkUpdate lists the changed SKILL.md', Array.isArray(check1.changed) && check1.changed.includes('SKILL.md'), JSON.stringify(check1.changed))
check('checkUpdate lists the added file', Array.isArray(check1.added) && check1.added.includes('extra.md'), JSON.stringify(check1.added))
const applied = await updater.applyUpdate('alpha', c2)
check('applyUpdate moves the folder to v2', readFileSync(join(root, 'alpha', 'SKILL.md'), 'utf8').includes('v2'), JSON.stringify(applied))
check('applyUpdate adds the new file', existsSync(join(root, 'alpha', 'extra.md')))
check('applyUpdate took a backup', existsSync(applied.backup) && existsSync(join(applied.backup, 'SKILL.md')))
check('provenance now records the new commit', JSON.parse(readFileSync(join(root, 'alpha', '.skill-source.json'), 'utf8')).commit === c2)
const after = await updater.checkUpdate('alpha')
check('after update, no further change is pending', after.available === false)
const rolled = await updater.rollback('alpha')
check('rollback restores v1', readFileSync(join(root, 'alpha', 'SKILL.md'), 'utf8').includes('v1'), JSON.stringify(rolled))
check('rollback removes the file that v2 added', !existsSync(join(root, 'alpha', 'extra.md')))
check('rollback provenance points back to c1', JSON.parse(readFileSync(join(root, 'alpha', '.skill-source.json'), 'utf8')).commit === c1)
let stale = false
try { await updater.applyUpdate('alpha', 'deadbeef') } catch (error) { stale = error.code === 'stale_plan' }
check('applyUpdate refuses a stale expected commit', stale)
const passed = results.filter((r) => r.ok).length
console.log(`\n${passed}/${results.length} passed`)
process.exit(passed === results.length ? 0 : 1)

98
verify-sync-resolve.mjs Normal file
View File

@ -0,0 +1,98 @@
// Verification for P3 interactive sync conflict resolution.
//
// One real SkillSync pass against a stub cloud client produces four conflicts;
// then each resolution action is exercised: take_cloud (backup + overwrite),
// keep_local (upload), manual (read-only) and a stale-revision refusal.
import { mkdirSync, mkdtempSync, readFileSync, writeFileSync, existsSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
process.env.DSH_HOME = mkdtempSync(join(tmpdir(), 'brain-sync-'))
const results = []
function check(name, ok, detail) {
results.push({ name, ok })
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`)
}
const { SkillSync, linkedSkillManifest, sha256Hex } = await import('./lib/skill-sync.js')
const root = join(process.env.DSH_HOME, 'skills')
mkdirSync(root, { recursive: true })
function makeLocal(folder, markdown) {
mkdirSync(join(root, folder), { recursive: true })
writeFileSync(join(root, folder, 'SKILL.md'), markdown)
// A delivery manifest whose recorded hash does not match → "locally_modified".
writeFileSync(join(root, folder, '.manifest.json'), JSON.stringify({
name: folder, revision: 1, manifest_sha256: 'old', files: [{ path: 'SKILL.md', sha256: 'deadbeef' }],
}))
}
for (const folder of ['demo', 'demo2', 'demo3', 'demo4']) {
makeLocal(folder, `---\nname: ${folder}\n---\n# ${folder} local\n`)
}
const cloudBody = '---\nname: demo\n---\n# demo CLOUD\n'
const cloudFiles = [{ path: 'SKILL.md', sha256: sha256Hex(cloudBody), data: Buffer.from(cloudBody).toString('base64') }]
const cloudManifest = linkedSkillManifest(cloudFiles)
const items = [
{ name: 'demo', enabled: true, revision: 3, manifest_sha256: cloudManifest, files: 1, bytes: cloudBody.length },
{ name: 'demo2', enabled: true, revision: 5, manifest_sha256: 'm2', files: 1, bytes: 10 },
{ name: 'demo3', enabled: true, revision: 4, manifest_sha256: 'm3', files: 1, bytes: 10 },
{ name: 'demo4', enabled: true, revision: 7, manifest_sha256: 'm4', files: 1, bytes: 10 },
]
let updateCalls = []
const client = {
listSkills: async () => ({ ok: true, status: 200, data: { items } }),
skillBundle: async (name) => name === 'demo'
? { ok: true, status: 200, data: { name, revision: 3, manifest_sha256: cloudManifest, files: cloudFiles } }
: { ok: false, error: { status: 404, code: 'not_found', message: 'no bundle' } },
createSkill: async () => ({ ok: true, status: 200, data: { skill: { revision: 1 } } }),
updateSkill: async (name, body) => {
updateCalls.push({ name, expected: body.expected_revision })
if (name === 'demo4') return { ok: false, error: { status: 409, code: 'revision_conflict', message: 'stale' } }
return { ok: true, status: 200, data: { skill: { revision: 6 } } }
},
}
const sync = new SkillSync({
client: () => client,
settings: () => ({ enabled: true, skillsSyncEnabled: true, skillsDir: '' }),
log: () => {},
})
const stats = await sync.syncOnce()
check('one pass reports four conflicts', stats.conflicts.length === 4, JSON.stringify(stats.conflicts))
const details = await sync.conflictDetails()
check('conflictDetails returns both sides', details.length === 4)
const demoDetail = details.find((d) => d.name === 'demo')
check('detail exposes local files and cloud revision', demoDetail?.local?.exists === true && demoDetail?.cloud?.revision === 3, JSON.stringify(demoDetail))
// take_cloud
const take = await sync.resolveConflict('demo', 'take_cloud')
check('take_cloud applies and backs up', take.applied === true && typeof take.backup === 'string' && existsSync(take.backup), JSON.stringify(take))
check('take_cloud overwrote SKILL.md with the cloud copy', readFileSync(join(root, 'demo', 'SKILL.md'), 'utf8').includes('CLOUD'))
check('take_cloud backup holds the old file', readFileSync(join(take.backup, 'SKILL.md'), 'utf8').includes('local'))
// keep_local
const keep = await sync.resolveConflict('demo2', 'keep_local')
check('keep_local uploads and bumps revision', keep.applied === true && keep.revision === 6, JSON.stringify(keep))
check('keep_local used the cloud revision as expected_revision', updateCalls.some((c) => c.name === 'demo2' && c.expected === 5), JSON.stringify(updateCalls))
const state = JSON.parse(readFileSync(join(process.env.DSH_HOME, 'cloud-memory-skills.json'), 'utf8'))
check('keep_local recorded the upload in the sidecar', state.uploaded?.demo2?.revision === 6)
// manual
const manual = await sync.resolveConflict('demo3', 'manual')
check('manual reports both sides without writing', manual.applied === false && manual.action === 'manual')
// stale revision
let stale = false
try { await sync.resolveConflict('demo4', 'keep_local') } catch (error) { stale = error.message === 'stale_revision' }
check('keep_local refuses a stale cloud revision', stale)
const remaining = await sync.conflictDetails()
check('resolved conflicts drop out of the list', remaining.some((d) => d.name === 'demo') === false && remaining.some((d) => d.name === 'demo2') === false)
const passed = results.filter((r) => r.ok).length
console.log(`\n${passed}/${results.length} passed`)
process.exit(passed === results.length ? 0 : 1)

34
verify-theme.mjs Normal file
View File

@ -0,0 +1,34 @@
// P5 theme / narrow-panel structural guard.
//
// This is a static guard, not a screenshot: it fails if the hand-written card
// reintroduces a hard-coded light-only colour or drops the wrapping that keeps
// a narrow settings panel from scrolling sideways. It also asserts the tab bar
// and the two long action rows declare flexWrap.
import { readFileSync } from 'node:fs'
const results = []
function check(name, ok, detail) {
results.push({ name, ok })
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`)
}
const source = readFileSync('./client/index.js', 'utf8')
const hardcoded = source.match(/(?:background|color|borderColor)\s*:\s*['"]#(?:fff(?:fff)?|000(?:000)?)['"]/gi)
check('no hard-coded pure white/black colours', hardcoded === null, hardcoded === null ? '' : hardcoded.join(','))
const neutralTokens = (source.match(/rgba\(127,127,127/gi) ?? []).length
check('theme-neutral colour tokens are used throughout', neutralTokens >= 5, `${neutralTokens} uses`)
const accentTokens = (source.match(/rgba\(37,99,235/gi) ?? []).length
check('accent colour is the shared blue token', accentTokens >= 2, `${accentTokens} uses`)
const wrapCount = (source.match(/flexWrap\s*:\s*['"]wrap['"]/g) ?? []).length
check('long rows wrap instead of scrolling sideways', wrapCount >= 4, `${wrapCount} wrapping rows`)
check('tabs and actions declare wrapping', /tabBar[\s\S]{0,400}?flexWrap/.test(source) || /styles\.tabs/.test(source))
check('no fixed 375px-only width is pinned', !/minWidth\s*:\s*['"]?375/.test(source))
const passed = results.filter((r) => r.ok).length
console.log(`\n${passed}/${results.length} passed`)
process.exit(passed === results.length ? 0 : 1)

81
verify-upgrade.mjs Normal file
View File

@ -0,0 +1,81 @@
// P5 upgrade / migration verification.
//
// A 0.4.1 sidecar must survive an in-place upgrade: the schema is unchanged, so
// base URL, tokens, client id and numeric overrides are read back verbatim and
// survive a second "restart". Unknown keys are ignored rather than fatal. The
// packaged default must be a neutral placeholder, and no personal domain may
// remain in the shipped lib/.
import { mkdtempSync, readFileSync, writeFileSync, readdirSync, statSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
process.env.DSH_HOME = mkdtempSync(join(tmpdir(), 'brain-upgrade-'))
const results = []
function check(name, ok, detail) {
results.push({ name, ok })
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`)
}
const { SettingsStore } = await import('./lib/store.js')
const { DEFAULT_SETTINGS } = await import('./lib/config.js')
// ── 1. A 0.4.1-shaped sidecar survives the upgrade ──────────────────────
const file = join(process.env.DSH_HOME, 'cloud-memory.json')
const old = {
version: 1,
enabled: true,
baseUrl: 'https://memory.example.org/api/longmemory',
clientId: 'dsh-desktop',
requestTimeoutMs: 5000,
defaultK: 12,
activityToken: 'cmt_old_activity_0123456789abcdef',
memoryToken: 'cmt_old_memory_0123456789abcdef',
summaryEnabled: true,
summaryMaxChars: 6000,
summaryToken: 'cmt_old_summary_0123456789abcdef',
someFutureField: 'ignore-me',
}
writeFileSync(file, JSON.stringify(old, null, 2))
const store = new SettingsStore(null, file)
const s = store.settings()
check('base URL survives the upgrade', s.baseUrl === old.baseUrl, s.baseUrl)
check('client id survives the upgrade', s.clientId === 'dsh-desktop')
check('numeric overrides survive', s.requestTimeoutMs === 5000 && s.defaultK === 12)
check('all three tokens survive', store.activityToken() === old.activityToken && store.memoryToken() === old.memoryToken && store.summaryToken() === old.summaryToken)
check('an unknown future key is ignored, not fatal', store.describe().baseUrlConfigured === true)
// A second construction models a restart over the same file.
const reopened = new SettingsStore(null, file)
check('a restart reads the same values back', reopened.settings().baseUrl === old.baseUrl && reopened.activityToken() === old.activityToken)
// ── 2. Fresh installs default to a neutral placeholder ──────────────────
const emptyFile = join(process.env.DSH_HOME, 'empty.json')
const fresh = new SettingsStore(null, emptyFile)
check('fresh install uses the packaged placeholder', DEFAULT_SETTINGS.baseUrl === 'https://your-memory-host/api/longmemory', DEFAULT_SETTINGS.baseUrl)
check('a placeholder is reported as unconfigured', fresh.describe().baseUrlConfigured === false)
// ── 3. A corrupt file degrades to defaults instead of breaking boot ─────
const corrupt = join(process.env.DSH_HOME, 'corrupt.json')
writeFileSync(corrupt, '{not json')
let survived = true
try { new SettingsStore(null, corrupt) } catch { survived = false }
check('a torn sidecar does not break activation', survived)
// ── 4. Artifact hygiene: no personal domain in shipped lib/ ─────────────
const libDir = join(process.cwd(), 'lib')
let leaked = []
for (const name of readdirSync(libDir)) {
const full = join(libDir, name)
if (!statSync(full).isFile() || !name.endsWith('.js')) continue
const text = readFileSync(full, 'utf8')
if (/qyhhh/i.test(text)) leaked.push(name)
}
check('no personal domain remains in shipped lib/', leaked.length === 0, leaked.join(','))
const pkg = JSON.parse(readFileSync(join(process.cwd(), 'package.json'), 'utf8'))
check('package version is the delivery version', pkg.version === '0.7.0', pkg.version)
const passed = results.filter((r) => r.ok).length
console.log(`\n${passed}/${results.length} passed`)
process.exit(passed === results.length ? 0 : 1)

109
verify-workspace-write.mjs Normal file
View File

@ -0,0 +1,109 @@
// v1.1 workspace-write verification (MULTI-04 / MULTI-07).
//
// DSH workspace skills are writable through a workspace-scoped SkillAdmin. The
// test proves isolation: changing one workspace never touches the global DSH
// root or another workspace, and non-DSH workspace writes are refused.
import http from 'node:http'
import { execFileSync } from 'node:child_process'
import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const HOME = mkdtempSync(join(tmpdir(), 'brain-wswrite-home-'))
process.env.DSH_HOME = mkdtempSync(join(tmpdir(), 'brain-wswrite-'))
const DSH = process.env.DSH_HOME
const results = []
function check(name, ok, detail) {
results.push({ name, ok })
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`)
}
function writeSkill(root, folder) {
mkdirSync(join(root, folder), { recursive: true })
writeFileSync(join(root, folder, 'SKILL.md'), `---\nname: ${folder}\n---\n# ${folder}\n`)
}
const wsA = join(HOME, 'proj-a')
const wsB = join(HOME, 'proj-b')
writeSkill(join(wsA, '.dsh', 'skills'), 'a-skill')
writeSkill(join(wsA, '.dsh', 'skills'), 'a-extra')
writeSkill(join(wsB, '.dsh', 'skills'), 'b-skill')
writeSkill(join(DSH, 'skills'), 'g-skill')
writeFileSync(join(DSH, 'workspace-groups.folders.json'), JSON.stringify({
version: 1,
workspaces: {
g: { folders: [], members: [{ path: wsA, workspaceId: 'ws-a' }, { path: wsB, workspaceId: 'ws-b' }] },
},
}))
writeFileSync(join(DSH, 'workspace-groups.manual.json'), JSON.stringify({ assignments: {} }))
const { ClientRegistry } = await import('./lib/clients.js')
const registry = new ClientRegistry({
home: () => HOME,
manualPath: () => join(DSH, 'cloud-memory-workspaces.json'),
dshRegistryPath: () => join(DSH, 'workspace-groups.folders.json'),
dshManualPath: () => join(DSH, 'workspace-groups.manual.json'),
})
const caps = registry.capabilities()
check('workspace write is enabled for DSH only', caps.find((c) => c.id === 'dsh')?.workspaceWrite === true && caps.find((c) => c.id === 'codex')?.workspaceWrite === false)
const invA0 = await registry.inventory('dsh', 'workspace', 'ws-a')
check('workspace inventory lists its skills as writable', invA0.items.length === 2 && invA0.items.every((item) => item.writable === true), JSON.stringify(invA0.items.map((i) => [i.folder, i.writable])))
const { admin } = await registry.workspaceSkillAdmin('dsh', 'ws-a')
const off = await admin.setEnabled('a-skill', false)
check('disabling a workspace skill parks it', off.enabled === false && !existsSync(join(wsA, '.dsh', 'skills', 'a-skill')))
check('parking keeps the global root and project B untouched', existsSync(join(DSH, 'skills', 'g-skill')) && existsSync(join(wsB, '.dsh', 'skills', 'b-skill')) && !existsSync(join(DSH, 'skills', 'a-skill')))
const invA1 = await registry.inventory('dsh', 'workspace', 'ws-a')
check('inventory reflects the disabled state', invA1.items.find((i) => i.folder === 'a-skill')?.enabled === false)
await admin.setEnabled('a-skill', true)
check('re-enabling restores the workspace skill', existsSync(join(wsA, '.dsh', 'skills', 'a-skill')))
await admin.remove('a-extra')
check('removing one workspace skill leaves the others', !existsSync(join(wsA, '.dsh', 'skills', 'a-extra')) && existsSync(join(wsA, '.dsh', 'skills', 'a-skill')))
check('removal never touched project B', existsSync(join(wsB, '.dsh', 'skills', 'b-skill')))
// Install from a git repo into the workspace root.
const repoDir = join(HOME, 'repo')
writeSkill(repoDir, 'new-skill')
execFileSync('git', ['init', '-b', 'main'], { cwd: repoDir })
execFileSync('git', ['-C', repoDir, 'add', '-A'])
execFileSync('git', ['-C', repoDir, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-m', 'init'])
const plan = await admin.prepareInstall('file://' + repoDir.replace(/\\/g, '/'))
const committed = await admin.commitInstall({ planId: plan.planId, folders: ['new-skill'] })
check('workspace install commits into the workspace root', committed.installed.includes('new-skill') && existsSync(join(wsA, '.dsh', 'skills', 'new-skill', 'SKILL.md')))
check('workspace install leaves global and B unchanged', !existsSync(join(DSH, 'skills', 'new-skill')) && !existsSync(join(wsB, '.dsh', 'skills', 'new-skill')))
let refused = false
try { await registry.workspaceSkillAdmin('codex', 'ws-a') } catch (e) { refused = e.message === 'unsupported_workspace_write' }
check('non-DSH workspace writes are refused', refused)
// Route layer.
const { createRoutes } = await import('./lib/routes.js')
const { SettingsStore } = await import('./lib/store.js')
const { Reporter } = await import('./lib/reporter.js')
const store = new SettingsStore({ clientId: 't' }, join(DSH, 'c.json'))
const reporter = new Reporter({ client: () => ({ reportTurn: async () => ({ ok: true, status: 200, data: {} }), submitSummary: async () => ({ ok: true, status: 200, data: {} }) }), settings: () => ({ enabled: true, clientId: 't' }), activityToken: () => '', summary: () => ({ enabled: false, maxChars: 1 }), summaryToken: () => '', log: () => {} })
const routes = createRoutes({ version: '0.7.0', store, reporter, client: () => ({ reach: async () => ({ ok: false, status: 0, message: 'x' }), listSkills: async () => ({ ok: true, status: 200, data: { items: [] } }) }), clients: registry })
const server = http.createServer((req, res) => {
const path = (req.url ?? '/').split('?')[0]
for (const route of routes) {
if (route.kind === 'exact' && path === route.path) return route.handler(req, res)
if (route.kind === 'prefix' && (path === route.path || path.startsWith(`${route.path}/`))) return route.handler(req, res)
}
res.writeHead(404); res.end('{"ok":false}')
})
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
const origin = `http://127.0.0.1:${server.address().port}`
const invRoute = await fetch(`${origin}/cloud-memory/clients/workspace/inventory?software=dsh&workspaceId=ws-a`).then((r) => r.json())
check('workspace inventory route answers', invRoute.ok === true && Array.isArray(invRoute.skills))
const toggle = await fetch(`${origin}/cloud-memory/clients/workspace/toggle`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ software: 'dsh', workspaceId: 'ws-a', folder: 'a-skill', enabled: false }) }).then((r) => r.json())
check('workspace toggle route applies', toggle.ok === true && toggle.enabled === false)
const cross = await fetch(`${origin}/cloud-memory/clients/workspace/toggle`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ software: 'codex', workspaceId: 'ws-a', folder: 'x', enabled: false }) })
check('workspace write route rejects non-DSH with 501', cross.status === 501)
await new Promise((resolve) => server.close(resolve))
const passed = results.filter((r) => r.ok).length
console.log(`\n${passed}/${results.length} passed`)
process.exit(passed === results.length ? 0 : 1)