feat(v1.1): DSH workspace-level skill writes with project isolation
This commit is contained in:
parent
01581beb0f
commit
122b249302
|
|
@ -1269,10 +1269,37 @@ window.__ModuleLoader__.load({
|
|||
var workspaceSelect = s.scope === 'workspace'
|
||||
? itemSelect(list.map(function (w) { return { key: w.id, name: w.name, transport: w.path } }), s.workspaceId, chooseWorkspace)
|
||||
: null
|
||||
function wsToggle(item) {
|
||||
patch({ busy: item.folder })
|
||||
postJson(API.clients + '/workspace/toggle', { software: s.software, workspaceId: s.workspaceId, folder: item.folder, enabled: item.enabled !== true }).then(function (res) {
|
||||
if (res.body !== null && res.body !== undefined && res.body.ok === true) {
|
||||
patch({ busy: '', notice: { tone: 'ok', text: item.folder + ':' + String(res.body.note || (item.enabled === true ? '已停用' : '已启用')) } })
|
||||
loadInventory(s.software, 'workspace', s.workspaceId)
|
||||
} else patch({ busy: '', notice: { tone: 'bad', text: '启停失败:' + bodyError(res, '') } })
|
||||
}, function (error) { patch({ busy: '', notice: { tone: 'bad', text: messageOf(error) } }) })
|
||||
}
|
||||
function wsRemove(item) {
|
||||
if (typeof window !== 'undefined' && typeof window.confirm === 'function' && !window.confirm('删除工作区技能「' + item.name + '」?此操作不可恢复。')) return
|
||||
patch({ busy: item.folder })
|
||||
postJson(API.clients + '/workspace/remove', { software: s.software, workspaceId: s.workspaceId, folder: item.folder, confirmed: true }).then(function (res) {
|
||||
if (res.body !== null && res.body !== undefined && res.body.ok === true) {
|
||||
patch({ busy: '', notice: { tone: 'ok', text: '已删除 ' + item.folder } })
|
||||
loadInventory(s.software, 'workspace', s.workspaceId)
|
||||
} else patch({ busy: '', notice: { tone: 'bad', text: '删除失败:' + bodyError(res, '') } })
|
||||
}, function (error) { patch({ busy: '', notice: { tone: 'bad', text: messageOf(error) } }) })
|
||||
}
|
||||
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('div', { key: item.path, style: styles.row },
|
||||
h('div', { style: styles.rowHead },
|
||||
h('span', { style: styles.rowTitle }, item.name + '(' + item.folder + ')'),
|
||||
h('span', { style: styles.hint }, (item.writable ? (item.enabled === false ? '已停用' : '启用中') : '只读') + (item.description === '' ? '' : ' · ' + item.description)),
|
||||
),
|
||||
item.writable
|
||||
? h('div', { style: styles.actions },
|
||||
h(Btn, { label: item.enabled === false ? '启用' : '停用', variant: 'small', disabled: s.busy !== '', onClick: function () { wsToggle(item) } }),
|
||||
h(Btn, { label: '卸载', variant: 'small', disabled: s.busy !== '', onClick: function () { wsRemove(item) } }),
|
||||
)
|
||||
: null,
|
||||
)
|
||||
})
|
||||
return h(Section, { title: '软件与范围', hint: '按软件 → 通用/工作区查看技能清单。只有 DSH 可写,其他软件只读且绝不写通用配置冒充;工作区来自 DSH 登记与你手动添加的目录。', aside: h(Btn, { label: '刷新', variant: 'small', onClick: loadOverview }) },
|
||||
|
|
|
|||
|
|
@ -212,6 +212,7 @@ refreshCatalog, toolsList, toolSearch, toolExplorer, toolDetail`
|
|||
- 目录条目、工具描述、示例与远端文本一律视为**不可信内容**,只展示、不执行。
|
||||
- Host 不支持 `tools.guard` 时,`deny` 策略会被宿主拒绝并如实显示,不会假装已生效。
|
||||
- 自定义 MCP Server 的权威位置仍是「设置 → 插件配置 → MCP 服务器配置」;本卡通过同一公开接口管理,不手改托管配置区块。
|
||||
- 工具可见性 ≠ 会话级可调用:本卡展示连接与工具缓存,**按会话选择精确工具后激活**由宿主 `session-tools`/agent 工具负责(其不在 `/mcp-connector/api` 白名单内),本卡不伪造激活。
|
||||
|
||||
### 7.3 验证
|
||||
|
||||
|
|
@ -272,10 +273,11 @@ HTTP 层统一映射为 **409 `sync_running`**。`verify-concurrency.mjs`:8
|
|||
- 其他软件的工作区只来自用户显式登记;路径失效会如实报告,不静默删除登记。
|
||||
- 工作区技能目录按该软件自己的约定探测:`<ws>/.dsh/skills`、`<ws>/.codex/skills`、`<ws>/.claude/skills`、`<ws>/.opencode/skills|skill`。找不到就是空,**绝不写通用目录冒充工作区配置**。
|
||||
|
||||
### 9.3 写入边界(诚实的能力缺口)
|
||||
### 9.3 写入边界(能力与缺口)
|
||||
|
||||
- 只有 **DSH 的用户级技能目录可写**;工作区级写入和其他软件一律只读(`workspaceWrite=false` / item `writable=false`)。
|
||||
- 这满足「未支持项显式报告」,不把「只有通用管理」伪装成已适配工作区。
|
||||
- **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 数据半区)
|
||||
|
||||
|
|
@ -286,6 +288,7 @@ HTTP 层统一映射为 **409 `sync_running`**。`verify-concurrency.mjs`:8
|
|||
### 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,全部返回正常。
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ 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');
|
||||
|
|
@ -82,12 +83,39 @@ export class ClientRegistry {
|
|||
readGlobal: true,
|
||||
writeGlobal: adapter.writable,
|
||||
workspaceRead: adapter.workspaceSupported,
|
||||
workspaceWrite: false,
|
||||
// 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 {
|
||||
|
|
@ -191,9 +219,9 @@ export class ClientRegistry {
|
|||
}
|
||||
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';
|
||||
// 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;
|
||||
|
|
@ -229,6 +257,24 @@ export class ClientRegistry {
|
|||
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)) {
|
||||
|
|
|
|||
|
|
@ -55,6 +55,7 @@ function capabilities(deps) {
|
|||
...(deps.sync === undefined ? [] : ['同步冲突可在技能页签逐项“保留本地 / 采用云端 / 手动合并”。']),
|
||||
...(deps.clients === undefined ? [] : ['跨软件与工作区技能清单为只读(DSH 之外不写目录);dsh-brain 数据迁移已就绪,实际改名需部署重启。']),
|
||||
'MCP 管理由宿主 dsh-mcp-connector 插件提供,本卡通过其公开接口读写,不另建凭据库。',
|
||||
'MCP 工具可见性与会话级激活分属两层:本卡展示连接与工具缓存,会话级“选择精确工具后激活”由宿主 session-tools 负责,本卡不伪造激活。',
|
||||
],
|
||||
};
|
||||
}
|
||||
|
|
@ -846,15 +847,91 @@ async function serveClients(deps, req, res) {
|
|||
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'];
|
||||
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 : 400;
|
||||
: code === 'duplicate' ? 409
|
||||
: code === 'unsupported_workspace_write' ? 501 : 400;
|
||||
json(res, status, { ok: false, code, error: message });
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ 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'
|
||||
|
||||
|
|
@ -49,6 +50,7 @@ export interface ClientInventoryItem {
|
|||
scope: 'global' | 'workspace'
|
||||
workspaceId?: string
|
||||
writable: boolean
|
||||
enabled?: boolean
|
||||
}
|
||||
|
||||
export interface ClientCapabilityView {
|
||||
|
|
@ -152,13 +154,39 @@ export class ClientRegistry {
|
|||
readGlobal: true,
|
||||
writeGlobal: adapter.writable,
|
||||
workspaceRead: adapter.workspaceSupported,
|
||||
workspaceWrite: false,
|
||||
// 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 {
|
||||
|
|
@ -261,9 +289,9 @@ export class ClientRegistry {
|
|||
|
||||
private async inventoryOf(dir: string, software: SoftwareId, scope: 'global' | 'workspace', workspaceId?: string): Promise<ClientInventoryItem[]> {
|
||||
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'
|
||||
// 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)
|
||||
|
|
@ -296,6 +324,24 @@ export class ClientRegistry {
|
|||
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)) {
|
||||
|
|
|
|||
|
|
@ -138,6 +138,7 @@ function capabilities(deps: RouteDeps): CapabilityReport {
|
|||
...(deps.sync === undefined ? [] : ['同步冲突可在技能页签逐项“保留本地 / 采用云端 / 手动合并”。']),
|
||||
...(deps.clients === undefined ? [] : ['跨软件与工作区技能清单为只读(DSH 之外不写目录);dsh-brain 数据迁移已就绪,实际改名需部署重启。']),
|
||||
'MCP 管理由宿主 dsh-mcp-connector 插件提供,本卡通过其公开接口读写,不另建凭据库。',
|
||||
'MCP 工具可见性与会话级激活分属两层:本卡展示连接与工具缓存,会话级“选择精确工具后激活”由宿主 session-tools 负责,本卡不伪造激活。',
|
||||
],
|
||||
}
|
||||
}
|
||||
|
|
@ -915,14 +916,66 @@ async function serveClients(deps: RouteDeps, req: IncomingMessage, res: ServerRe
|
|||
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']
|
||||
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 : 400
|
||||
: code === 'duplicate' ? 409
|
||||
: code === 'unsupported_workspace_write' ? 501 : 400
|
||||
json(res, status, { ok: false, code, error: message })
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
Loading…
Reference in New Issue