diff --git a/README.md b/README.md index 864b684..64f7b4b 100644 --- a/README.md +++ b/README.md @@ -201,7 +201,7 @@ pnpm publish --access public --no-git-checks > lifecycle 脚本要求 `node` 在 `PATH` 里。若报 `'node' is not recognized`,先把 DSH 运行时自带 node 的 `bin` 目录加进 `$env:Path` 再发布。 -## 统一管理卡(0.6.0) +## 统一管理卡(0.7.0) 「设置 → 云端记忆」现在是三个页签:**连接与上报 / 技能管理 / MCP 管理**。 diff --git a/client/index.js b/client/index.js index 63ecd80..cea5424 100644 --- a/client/index.js +++ b/client/index.js @@ -29,6 +29,8 @@ window.__ModuleLoader__.load({ skills: '/cloud-memory/skills', market: '/cloud-memory/market', sync: '/cloud-memory/sync', + clients: '/cloud-memory/clients', + migrate: '/cloud-memory/migrate', } // The MCP bridge is another plugin's public surface, not ours: it is probed @@ -1182,6 +1184,118 @@ window.__ModuleLoader__.load({ ) } + // ---- v1.1: cross-software / workspace inventory ---------------------- + function ClientScopeSection() { + var tuple = React.useState({ overview: null, software: 'dsh', scope: 'global', workspaceId: '', inventory: null, busy: '', notice: null, addPath: '', addName: '', brain: null }) + var s = tuple[0] + var set = tuple[1] + function patch(next) { set(function (prev) { return Object.assign({}, prev, next) }) } + React.useEffect(function () { + loadOverview() + request(API.migrate + '/brain', { method: 'GET' }).then(function (res) { + if (res.body !== null && res.body !== undefined && res.body.ok === true) patch({ brain: res.body }) + }) + }, []) + function loadOverview() { + request(API.clients + '/overview', { method: 'GET' }).then(function (res) { + if (res.body !== null && res.body !== undefined && res.body.ok === true) { + patch({ overview: res.body }) + loadInventory(s.software, s.scope, s.workspaceId) + } else patch({ notice: { tone: 'bad', text: bodyError(res, '读取软件清单失败') } }) + }, function (error) { patch({ notice: { tone: 'bad', text: messageOf(error) } }) }) + } + function loadInventory(software, scope, workspaceId) { + var url = API.clients + '/inventory?software=' + encodeURIComponent(software) + '&scope=' + encodeURIComponent(scope) + (workspaceId === '' ? '' : '&workspaceId=' + encodeURIComponent(workspaceId)) + request(url, { method: 'GET' }).then(function (res) { + if (res.body !== null && res.body !== undefined && res.body.ok === true) patch({ inventory: res.body }) + else patch({ inventory: { items: [], note: bodyError(res, '读取技能清单失败') } }) + }) + } + function chooseSoftware(id) { + patch({ software: id, scope: 'global', workspaceId: '', inventory: null }) + loadInventory(id, 'global', '') + } + function chooseScope(scope) { + patch({ scope: scope, workspaceId: '', inventory: null }) + if (scope === 'global') loadInventory(s.software, 'global', '') + } + function chooseWorkspace(id) { + patch({ workspaceId: id }) + loadInventory(s.software, 'workspace', id) + } + function addWorkspace() { + if (String(s.addPath).trim() === '') { patch({ notice: { tone: 'warn', text: '请填写工作区目录。' } }); return } + patch({ busy: 'add' }) + postJson(API.clients + '/workspaces/add', { software: s.software, path: String(s.addPath).trim(), name: String(s.addName).trim() }).then(function (res) { + if (res.body !== null && res.body !== undefined && res.body.ok === true) { + patch({ busy: '', addPath: '', addName: '', notice: { tone: 'ok', text: '已登记工作区:' + String(res.body.workspace.name) } }) + loadOverview() + } else patch({ busy: '', notice: { tone: 'bad', text: '登记失败:' + bodyError(res, '') } }) + }, function (error) { patch({ busy: '', notice: { tone: 'bad', text: messageOf(error) } }) }) + } + function migrateBrain() { + patch({ busy: 'migrate' }) + postJson(API.migrate + '/brain', {}).then(function (res) { + if (res.body !== null && res.body !== undefined && res.body.ok === true) { + var names = (res.body.copied || []).join('、') + patch({ busy: '', brain: { migrationNeeded: false, packageRename: 'pending-deploy' }, notice: { tone: 'ok', text: names === '' ? '没有需要迁移的旧文件(或目标已存在)。' : '已复制:' + names + '(旧文件保留,实际改名需部署重启)' } }) + } else patch({ busy: '', notice: { tone: 'bad', text: bodyError(res, '迁移失败') } }) + }, function (error) { patch({ busy: '', notice: { tone: 'bad', text: messageOf(error) } }) }) + } + var overview = s.overview + var adapters = overview === null ? [] : (overview.adapters || []) + var workspaces = overview === null ? {} : (overview.workspaces || {}) + var list = workspaces[s.software] || [] + var inventory = s.inventory + var items = inventory === null || !Array.isArray(inventory.items) ? [] : inventory.items + var selected = null + for (var i = 0; i < adapters.length; i += 1) if (adapters[i].id === s.software) selected = adapters[i] + var softwareRow = adapters.map(function (adapter) { + return h(Btn, { + key: adapter.id, + variant: adapter.id === s.software ? 'primary' : 'small', + label: adapter.label + (adapter.installed ? '' : '(未安装)'), + onClick: function () { chooseSoftware(adapter.id) }, + }) + }) + var scopeRow = selected !== null && selected.workspaceSupported + ? h(Switch, { + ariaLabel: '范围', + value: s.scope, + onChange: chooseScope, + options: [{ value: 'global', label: '通用' }, { value: 'workspace', label: '工作区' }], + }) + : h('span', { style: styles.hint }, '该软件没有可识别的工作区专属技能目录,仅展示通用。') + var workspaceSelect = s.scope === 'workspace' + ? itemSelect(list.map(function (w) { return { key: w.id, name: w.name, transport: w.path } }), s.workspaceId, chooseWorkspace) + : null + var itemRows = items.map(function (item) { + return h('div', { key: item.path, style: styles.rowHead }, + h('span', { style: styles.rowTitle }, item.name + '(' + item.folder + ')'), + h('span', { style: styles.hint }, (item.writable ? '可管理' : '只读') + (item.description === '' ? '' : ' · ' + item.description)), + ) + }) + return h(Section, { title: '软件与范围', hint: '按软件 → 通用/工作区查看技能清单。只有 DSH 可写,其他软件只读且绝不写通用配置冒充;工作区来自 DSH 登记与你手动添加的目录。', aside: h(Btn, { label: '刷新', variant: 'small', onClick: loadOverview }) }, + h('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px' } }, + h('div', { style: styles.actions }, softwareRow), + h('div', { style: styles.actions }, scopeRow), + workspaceSelect, + s.notice === null ? null : h(Banner, { tone: s.notice.tone }, s.notice.text), + inventory === null ? h('p', { style: styles.hint }, '正在读取清单…') : h('p', { style: styles.hint }, String(inventory.note || '')), + items.length === 0 ? h('p', { style: styles.hint }, '该范围没有技能。') : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '4px' } }, itemRows), + h('div', { style: styles.grid }, + h(Field, { label: '登记工作区目录(给当前软件)', value: s.addPath, placeholder: 'C:\\\\path\\\\to\\\\project', onChange: function (v) { patch({ addPath: v }) } }), + h(Field, { label: '显示名(可选)', value: s.addName, onChange: function (v) { patch({ addName: v }) } }), + ), + h('div', { style: styles.actions }, h(Btn, { label: s.busy === 'add' ? '登记中…' : '登记工作区', disabled: s.busy !== '', onClick: addWorkspace })), + s.brain === null ? null : h('div', { style: styles.nested }, + h('p', { style: styles.hint }, 'DSH Brain 迁移:产品名 ' + String(s.brain.product || 'DSH Brain') + ' → 包名 ' + String(s.brain.targetPackage || 'dsh-brain') + ';数据迁移' + (s.brain.migrationNeeded === true ? '待执行' : '已就绪/已复制') + ';实际改名需部署重启。'), + s.brain.migrationNeeded === true ? h('div', { style: styles.actions }, h(Btn, { label: s.busy === 'migrate' ? '迁移中…' : '复制数据到 dsh-brain', disabled: s.busy !== '', onClick: migrateBrain })) : null, + ), + ), + ) + } + function SettingsCard() { var snapshotState = React.useState(null) var snapshot = snapshotState[0] @@ -2629,6 +2743,8 @@ window.__ModuleLoader__.load({ 'div', { style: styles.root, key: 'skills' }, + h(ClientScopeSection, {}), + h( Section, { diff --git a/docs/management-surface.md b/docs/management-surface.md index d43ab27..e01e3ee 100644 --- a/docs/management-surface.md +++ b/docs/management-surface.md @@ -251,5 +251,42 @@ HTTP 层统一映射为 **409 `sync_running`**。`verify-concurrency.mjs`:8 - `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`(分类),**不执行全盘扫描、不读会话库**。 +- 其他软件的工作区只来自用户显式登记;路径失效会如实报告,不静默删除登记。 +- 工作区技能目录按该软件自己的约定探测:`/.dsh/skills`、`/.codex/skills`、`/.claude/skills`、`/.opencode/skills|skill`。找不到就是空,**绝不写通用目录冒充工作区配置**。 + +### 9.3 写入边界(诚实的能力缺口) + +- 只有 **DSH 的用户级技能目录可写**;工作区级写入和其他软件一律只读(`workspaceWrite=false` / item `writable=false`)。 +- 这满足「未支持项显式报告」,不把「只有通用管理」伪装成已适配工作区。 + +### 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 注册工作区+分类、工作区专属技能、手动登记/去重/未知工作区、路由、能力位、迁移幂等与原文件保留)。 + + diff --git a/lib/brain-migration.js b/lib/brain-migration.js new file mode 100644 index 0000000..ab0aafe --- /dev/null +++ b/lib/brain-migration.js @@ -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 }; +} diff --git a/lib/clients.js b/lib/clients.js new file mode 100644 index 0000000..5f4fc9f --- /dev/null +++ b/lib/clients.js @@ -0,0 +1,251 @@ +/** + * 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"; +/** 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, + workspaceWrite: false, + hotReload: adapter.id === 'dsh', + verify: true, + notes: adapter.notes, + })); + } + 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 = []; + // Only the DSH user-level root is writable in this build; workspace-level + // writes are reported as read-only rather than half-implemented. + const writable = software === 'dsh' && scope === 'global'; + 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'); + 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' }, + }; + } +} diff --git a/lib/index.js b/lib/index.js index fbbd53d..b12b4d7 100644 --- a/lib/index.js +++ b/lib/index.js @@ -19,13 +19,14 @@ 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.6.0'; +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. */ @@ -92,6 +93,8 @@ export function apply(ctx, config) { 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) { @@ -135,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, groups: skillGroups, market, sync: skillSync, updates: updater }); + 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}`); } diff --git a/lib/mnemon/index.js b/lib/mnemon/index.js index 80a50bc..c65a982 100644 --- a/lib/mnemon/index.js +++ b/lib/mnemon/index.js @@ -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.6.0'; +const PROVIDER_VERSION = '0.7.0'; export const definition = defineMemorySpaceProviderDefinition({ manifest: { apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION, diff --git a/lib/routes.js b/lib/routes.js index c6b2d6c..26a45cb 100644 --- a/lib/routes.js +++ b/lib/routes.js @@ -2,6 +2,7 @@ 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'; @@ -17,6 +18,8 @@ export const ROUTES = { 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; @@ -36,6 +39,8 @@ function capabilities(deps) { 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', @@ -48,6 +53,7 @@ function capabilities(deps) { ? ['技能更新/回退未启用。'] : ['更新/回退仅对带来源记录(.skill-source.json)的技能生效,更新前自动备份。']), ...(deps.sync === undefined ? [] : ['同步冲突可在技能页签逐项“保留本地 / 采用云端 / 手动合并”。']), + ...(deps.clients === undefined ? [] : ['跨软件与工作区技能清单为只读(DSH 之外不写目录);dsh-brain 数据迁移已就绪,实际改名需部署重启。']), 'MCP 管理由宿主 dsh-mcp-connector 插件提供,本卡通过其公开接口读写,不另建凭据库。', ], }; @@ -790,6 +796,88 @@ async function serveSync(deps, req, res) { 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; + } + fail(res, 404, 'unknown-clients-route'); + } + catch (error) { + const message = error instanceof Error ? error.message : String(error); + const known = ['invalid_software', 'invalid_path', 'duplicate', 'not_found', 'unknown_workspace']; + const code = known.includes(message) ? message : 'internal'; + const status = code === 'internal' ? 500 + : code === 'not_found' || code === 'unknown_workspace' ? 404 + : code === 'duplicate' ? 409 : 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 [ @@ -843,5 +931,15 @@ export function createRoutes(deps) { 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), + }, ]; } diff --git a/package.json b/package.json index 32e71c9..eaca81d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-cloud-memory", - "version": "0.6.0", + "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", diff --git a/src/brain-migration.ts b/src/brain-migration.ts new file mode 100644 index 0000000..22ebb77 --- /dev/null +++ b/src/brain-migration.ts @@ -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 { + 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 { + 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 } +} diff --git a/src/clients.ts b/src/clients.ts new file mode 100644 index 0000000..a6ecc74 --- /dev/null +++ b/src/clients.ts @@ -0,0 +1,318 @@ +/** + * 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' + +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 +} + +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 { + 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 = { + 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 { + 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, + workspaceWrite: false, + hotReload: adapter.id === 'dsh', + verify: true, + notes: adapter.notes, + })) + } + + private async readManual(): Promise { + 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 { + 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 { + 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')) as { assignments?: Record } + 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 } + const out: WorkspaceRecord[] = [] + 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: SoftwareId): Promise { + 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 { + 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 { + const out: ClientInventoryItem[] = [] + // Only the DSH user-level root is writable in this build; workspace-level + // writes are reported as read-only rather than half-implemented. + const writable = software === 'dsh' && scope === 'global' + 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') + 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; brain: { product: string; targetPackage: string; legacyPackage: string } }> { + const workspaces: Record = {} + 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' }, + } + } +} diff --git a/src/index.ts b/src/index.ts index 9442b71..289f40a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -20,6 +20,7 @@ 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. */ @@ -29,7 +30,7 @@ export const name = 'dsh-cloud-memory' export const inject = ['webServer'] /** Version reported by the status card. */ -const VERSION = '0.6.0' +const VERSION = '0.7.0' /** How often the skill directory is reconciled with the cloud center. */ const SKILL_SYNC_INTERVAL_MS = 15 * 60_000 @@ -106,6 +107,9 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void { 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) { @@ -154,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, groups: skillGroups, market, sync: skillSync, updates: updater }) + 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}`) } diff --git a/src/mnemon/index.ts b/src/mnemon/index.ts index a2a44df..afd7815 100644 --- a/src/mnemon/index.ts +++ b/src/mnemon/index.ts @@ -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.6.0' +const PROVIDER_VERSION = '0.7.0' export const definition = defineMemorySpaceProviderDefinition({ manifest: { diff --git a/src/routes.ts b/src/routes.ts index 75515fb..2a02ad0 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -32,6 +32,8 @@ 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' @@ -49,6 +51,8 @@ export const ROUTES = { 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). */ @@ -72,6 +76,8 @@ export interface RouteDeps { 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. */ @@ -91,6 +97,10 @@ export interface CapabilityReport { 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[] @@ -112,6 +122,8 @@ function capabilities(deps: RouteDeps): CapabilityReport { 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', @@ -124,6 +136,7 @@ function capabilities(deps: RouteDeps): CapabilityReport { ? ['技能更新/回退未启用。'] : ['更新/回退仅对带来源记录(.skill-source.json)的技能生效,更新前自动备份。']), ...(deps.sync === undefined ? [] : ['同步冲突可在技能页签逐项“保留本地 / 采用云端 / 手动合并”。']), + ...(deps.clients === undefined ? [] : ['跨软件与工作区技能清单为只读(DSH 之外不写目录);dsh-brain 数据迁移已就绪,实际改名需部署重启。']), 'MCP 管理由宿主 dsh-mcp-connector 插件提供,本卡通过其公开接口读写,不另建凭据库。', ], } @@ -862,6 +875,71 @@ async function serveSync(deps: RouteDeps, req: IncomingMessage, res: ServerRespo } } +/** Cross-software / workspace inventory routes. */ +async function serveClients(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise { + 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 + } + fail(res, 404, 'unknown-clients-route') + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + const known = ['invalid_software', 'invalid_path', 'duplicate', 'not_found', 'unknown_workspace'] + const code = known.includes(message) ? message : 'internal' + const status = code === 'internal' ? 500 + : code === 'not_found' || code === 'unknown_workspace' ? 404 + : code === 'duplicate' ? 409 : 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 { + 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 [ @@ -915,5 +993,15 @@ export function createRoutes(deps: RouteDeps): CloudMemoryWebRoute[] { 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), + }, ] } diff --git a/verify-clients.mjs b/verify-clients.mjs new file mode 100644 index 0000000..1c98658 --- /dev/null +++ b/verify-clients.mjs @@ -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) diff --git a/verify-upgrade.mjs b/verify-upgrade.mjs index 97efec6..cbbabd2 100644 --- a/verify-upgrade.mjs +++ b/verify-upgrade.mjs @@ -74,7 +74,7 @@ for (const name of readdirSync(libDir)) { } 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.6.0', pkg.version) +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`)