From 6eadbaf90c52feaa7b015659a4b5e52841c4509d Mon Sep 17 00:00:00 2001 From: qyh15 Date: Wed, 11 Nov 2026 21:08:49 +0800 Subject: [PATCH] feat(skills): multi-source skill tree with metadata-only categories MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - sources: DSH / 公共 Agent / Codex / WorkBuddy / Claude Code / OpenCode, detected per refresh - categories stored as metadata only; delete releases skills to 未分类, never touches files - switches: DSH parks/unparks for real; foreign sources answer cardOnly and stay untouched - client: source → category → skill tree, inline create/rename/delete/assign, per-source reveal - verify-skill-tree.mjs (40 checks) + render harness expansion (23 checks) - preview-card.mjs renders the real tree to PNG via headless Chrome for layout review --- .gitignore | 4 + README.md | 10 + client/index.js | 730 +++++++++++++++++++++++++++++++------ docs/management-surface.md | 54 +++ lib/index.js | 10 +- lib/routes.js | 50 ++- lib/skill-groups.js | 457 +++++++++++++++++++++++ preview-card.mjs | 374 +++++++++++++++++++ src/index.ts | 11 +- src/routes.ts | 54 ++- src/skill-groups.ts | 521 ++++++++++++++++++++++++++ verify-card-render.mjs | 162 +++++++- verify-skill-tree.mjs | 234 ++++++++++++ 13 files changed, 2549 insertions(+), 122 deletions(-) create mode 100644 lib/skill-groups.js create mode 100644 preview-card.mjs create mode 100644 src/skill-groups.ts create mode 100644 verify-skill-tree.mjs diff --git a/.gitignore b/.gitignore index 42c6e9b..f6e1f7b 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,7 @@ Thumbs.db npm-debug.log* node_modules/ .cloud-memory/ + +# generated previews (node preview-card.mjs) +_preview/ +preview-debug.mjs diff --git a/README.md b/README.md index 72d7a89..411d40d 100644 --- a/README.md +++ b/README.md @@ -213,3 +213,13 @@ pnpm publish --access public --no-git-checks - 技能市场本版未接入经验证来源:`capabilities.features.skillsMarketplace = false`,界面不显示假条目。 接口清单见 `docs/management-surface.md`,验收脚本是 `verify-brain-panel.mjs` 与 `verify-skill-admin.mjs`。 + +### 技能来源树 + +「技能管理」按软件来源分组(DSH / 公共 Agent / Codex / WorkBuddy / Claude Code / OpenCode), +每个来源下是分类,分类下是技能: + +- 分类只记在 `$DSH_HOME/cloud-memory-skill-groups.json` 里,**不移动文件**;删除分类只是把技能放回「未分类」。 +- 只有 DSH 来源的开关是真的(目录移入/移出 `skills-disabled`,新会话生效);其他软件的目录本卡只读,开关标记为「仅本卡」。 +- 来源行提供「+ 新建分类」「打开目录」「来源开关」;分类行提供「+ 加入技能 / 改名 / 删除 / 分类开关」;技能行提供详情、启停、卸载。 +- 预览(真实数据、光照/暗色):`node preview-card.mjs` 生成 `_preview/skill-tree*.png`。 diff --git a/client/index.js b/client/index.js index 9d1f9df..db90c0a 100644 --- a/client/index.js +++ b/client/index.js @@ -449,6 +449,65 @@ window.__ModuleLoader__.load({ borderLeft: '2px solid rgba(127,127,127,0.2)', minWidth: 0, }, + sourceCard: { + display: 'flex', + flexDirection: 'column', + gap: '6px', + border: '1px solid rgba(127,127,127,0.28)', + borderRadius: '12px', + padding: '10px 12px', + minWidth: 0, + }, + groupRow: { + display: 'flex', + flexDirection: 'column', + gap: '6px', + border: '1px solid rgba(127,127,127,0.2)', + borderRadius: '10px', + padding: '8px 10px', + background: 'rgba(127,127,127,0.04)', + minWidth: 0, + }, + skillRow: { + display: 'flex', + alignItems: 'flex-start', + justifyContent: 'space-between', + gap: '8px', + padding: '6px 8px', + borderRadius: '8px', + border: '1px solid rgba(127,127,127,0.14)', + minWidth: 0, + flexWrap: 'wrap', + }, + clamp2: { + display: '-webkit-box', + WebkitLineClamp: '2', + WebkitBoxOrient: 'vertical', + overflow: 'hidden', + }, + sourceGlyph: { + width: '20px', + height: '20px', + borderRadius: '6px', + display: 'inline-flex', + alignItems: 'center', + justifyContent: 'center', + fontSize: '11px', + fontWeight: 700, + border: '1px solid rgba(37,99,235,0.35)', + background: 'rgba(37,99,235,0.14)', + flex: '0 0 auto', + }, + folderGlyph: { + fontSize: '12px', + opacity: 0.85, + flex: '0 0 auto', + }, + sourceTitle: { + fontWeight: 600, + fontSize: '13px', + overflowWrap: 'anywhere', + }, } function Pill(props) { @@ -488,7 +547,8 @@ window.__ModuleLoader__.load({ } function Btn(props) { - var style = props.variant === 'primary' ? styles.buttonPrimary : props.variant === 'danger' ? styles.buttonDanger : props.variant === 'small' ? styles.buttonSmall : styles.button + var base = props.variant === 'primary' ? styles.buttonPrimary : props.variant === 'danger' ? styles.buttonDanger : props.variant === 'small' ? styles.buttonSmall : styles.button + var style = props.disabled === true ? Object.assign({}, base, { opacity: 0.45, cursor: 'not-allowed' }) : base return h( 'button', { @@ -502,8 +562,7 @@ window.__ModuleLoader__.load({ ) } - function Switch(props) { - return h( + function Switch(props) { return h( 'div', { style: styles.tabs, role: 'tablist', 'aria-label': props.ariaLabel }, props.options.map(function (option) { @@ -526,6 +585,50 @@ window.__ModuleLoader__.load({ ) } + // A real switch, not a checkbox: the tree rows are dense and the state has + // to be readable at a glance in both themes. + function Toggle(props) { + var on = props.checked === true + var disabled = props.disabled === true + return h( + 'button', + { + type: 'button', + role: 'switch', + 'aria-checked': on, + 'aria-label': props.label, + title: props.label, + disabled: disabled, + style: { + width: '38px', + height: '22px', + flex: '0 0 auto', + padding: '2px', + borderRadius: '999px', + border: '1px solid ' + (on ? 'rgba(37,99,235,0.75)' : 'rgba(127,127,127,0.45)'), + background: on ? 'rgba(37,99,235,0.9)' : 'rgba(127,127,127,0.28)', + display: 'flex', + alignItems: 'center', + justifyContent: on ? 'flex-end' : 'flex-start', + cursor: disabled ? 'not-allowed' : 'pointer', + opacity: disabled ? 0.45 : 1, + transition: 'background 120ms ease', + }, + onClick: disabled ? undefined : props.onChange, + }, + h('span', { + style: { + width: '16px', + height: '16px', + borderRadius: '999px', + background: '#ffffff', + boxShadow: '0 1px 2px rgba(0,0,0,0.25)', + flex: '0 0 auto', + }, + }), + ) + } + function Section(props) { return h( 'div', @@ -608,6 +711,10 @@ window.__ModuleLoader__.load({ var mcp = mcpState[0] var setMcp = mcpState[1] + var treeState = React.useState({ status: 'idle', data: null, error: null, busy: '', expanded: {}, openGroups: {}, edit: null, confirm: null, assign: null }) + var tree = treeState[0] + var setTree = treeState[1] + function patchSkills(patch) { setSkills(function (previous) { return Object.assign({}, previous, patch) @@ -620,6 +727,12 @@ window.__ModuleLoader__.load({ }) } + function patchTree(patch) { + setTree(function (previous) { + return Object.assign({}, previous, patch) + }) + } + var load = React.useCallback( function (keepDraft) { return request(API.status) @@ -800,6 +913,7 @@ window.__ModuleLoader__.load({ setTab(next) store('tab', next) if (next === 'skills' && skills.status === 'idle') loadSkills() + if (next === 'skills' && tree.status === 'idle') loadTree() if (next === 'mcp' && mcp.status === 'idle') probeMcp() } @@ -816,9 +930,10 @@ window.__ModuleLoader__.load({ React.useEffect( function () { if (tab === 'skills' && skills.status === 'idle') void loadSkills() + if (tab === 'skills' && tree.status === 'idle') void loadTree() if (tab === 'mcp' && mcp.status === 'idle') void probeMcp() }, - [tab, skills.status, mcp.status], + [tab, skills.status, mcp.status, tree.status], ) // ---- skills ------------------------------------------------------- @@ -856,6 +971,126 @@ window.__ModuleLoader__.load({ }) } + // ---- skill tree (sources → categories → skills) -------------------- + + function loadTree() { + patchTree({ status: 'loading', error: null }) + return request(API.skills + '/sources') + .then(function (result) { + if (result.status !== 200 || result.body === null || result.body.ok !== true) { + patchTree({ status: 'error', error: '读取技能来源失败:' + statusText(result.status) }) + return + } + patchTree({ status: 'ready', data: result.body, error: null }) + }) + .catch(function (failure) { + patchTree({ status: 'error', error: '无法读取技能来源:' + messageOf(failure) }) + }) + } + + function treeAction(path, payload, label) { + patchTree({ busy: label }) + return postJson(API.skills + path, payload) + .then(function (result) { + patchTree({ busy: '' }) + if (result.status !== 200 || result.body === null || result.body.ok !== true) { + throw new Error(bodyError(result, statusText(result.status))) + } + return result.body + }) + .catch(function (failure) { + patchTree({ busy: '' }) + setNotice({ tone: 'bad', text: messageOf(failure) }) + return null + }) + } + + function createGroup() { + if (tree.edit === null) return Promise.resolve() + var name = String(tree.edit.value === undefined ? '' : tree.edit.value).trim() + if (name === '') { + setNotice({ tone: 'bad', text: '请填写分类名。' }) + return Promise.resolve() + } + return treeAction('/groups/create', { sourceId: tree.edit.sourceId, name: name }, 'create').then(function (body) { + if (body === null) return + patchTree({ edit: null }) + setNotice({ tone: 'ok', text: '已创建分类「' + String(body.name) + '」。' }) + return loadTree() + }) + } + + function saveRename() { + if (tree.edit === null) return Promise.resolve() + return treeAction('/groups/rename', { sourceId: tree.edit.sourceId, groupId: tree.edit.groupId, name: String(tree.edit.value).trim() }, 'rename').then(function (body) { + if (body === null) return + patchTree({ edit: null }) + return loadTree() + }) + } + + function deleteGroup(sourceId, groupId) { + return treeAction('/groups/delete', { sourceId: sourceId, groupId: groupId }, 'delete').then(function (body) { + if (body === null) return + patchTree({ confirm: null }) + setNotice({ tone: 'ok', text: '分类已删除,' + String(body.released) + ' 个技能回到「未分类」;没有删除任何文件。' }) + return loadTree() + }) + } + + function openAssign(source, group) { + patchTree({ + assign: { + sourceId: source.id, + groupId: group.id, + selection: (Array.isArray(group.skills) ? group.skills : []).map(function (skill) { + return skill.folder + }), + }, + }) + } + + function saveAssign() { + if (tree.assign === null) return Promise.resolve() + return treeAction('/groups/assign', { sourceId: tree.assign.sourceId, groupId: tree.assign.groupId, folders: tree.assign.selection }, 'assign').then(function (body) { + if (body === null) return + patchTree({ assign: null }) + return loadTree() + }) + } + + function toggleGroup(sourceId, groupId, enabled) { + return treeAction('/groups/toggle', { sourceId: sourceId, groupId: groupId, enabled: enabled }, 'toggle-group').then(function (body) { + if (body === null) return + if (body.cardOnly === true) { + setNotice({ tone: 'warn', text: '这个来源由对应软件自行加载:开关只记录在本卡,不影响它自己的加载。' }) + } else { + var failed = Array.isArray(body.failed) ? body.failed : [] + setNotice({ + tone: failed.length === 0 ? 'ok' : 'warn', + text: '已' + (enabled ? '启用' : '停用') + ' ' + String(Array.isArray(body.applied) ? body.applied.length : 0) + ' 项' + (failed.length === 0 ? '(新会话生效)。' : ',' + String(failed.length) + ' 项失败:' + failed.map(function (item) { return String(item.folder) + '(' + String(item.reason) + ')' }).join('、')), + }) + } + return loadTree() + }) + } + + function toggleSource(sourceId, enabled) { + return treeAction('/source/toggle', { sourceId: sourceId, enabled: enabled }, 'toggle-source').then(function (body) { + if (body === null) return + setNotice( + body.cardOnly === true + ? { tone: 'warn', text: '这个来源由对应软件自行加载:开关只记录在本卡。' } + : { tone: 'ok', text: '已' + (enabled ? '启用' : '停用') + ' ' + String(body.applied) + ' 个技能(新会话生效)。' }, + ) + return loadTree() + }) + } + + function revealSource(sourceId) { + return treeAction('/source/reveal', { sourceId: sourceId }, 'reveal') + } + function openDetail(folder) { patchSkills({ detail: { folder: folder, data: null, error: null } }) return skillAction('/detail', { folder: folder }, 'detail').then( @@ -1408,16 +1643,24 @@ window.__ModuleLoader__.load({ var skillsTab = null if (tab === 'skills') { - var skillList = skills.data !== null && Array.isArray(skills.data.skills) ? skills.data.skills : [] - var filter = skills.filter + var treeSources = tree.data !== null && Array.isArray(tree.data.sources) ? tree.data.sources : [] var keyword = String(skills.search).trim().toLowerCase() - var filtered = skillList.filter(function (skill) { - if (filter === 'enabled' && skill.enabled !== true) return false - if (filter === 'disabled' && skill.enabled === true) return false - if (filter === 'cloud' && skill.origin !== 'cloud' && skill.origin !== 'uploaded') return false + + var matchesSkill = function (skill) { if (keyword === '') return true return (String(skill.folder) + ' ' + String(skill.name) + ' ' + String(skill.description)).toLowerCase().indexOf(keyword) >= 0 - }) + } + + var visibleGroupsOf = function (source) { + return (Array.isArray(source.groups) ? source.groups : []) + .map(function (group) { + var visible = (Array.isArray(group.skills) ? group.skills : []).filter(matchesSkill) + return Object.assign({}, group, { visible: visible }) + }) + .filter(function (group) { + return group.visible.length > 0 || keyword === '' + }) + } var detailBox = null if (skills.detail !== null) { @@ -1438,14 +1681,14 @@ window.__ModuleLoader__.load({ }), ), detail === null - ? h('p', { style: styles.hint }, '正在读取…') + ? h('p', { style: styles.hint }, skills.detail.error === null ? '正在读取…' : String(skills.detail.error)) : h( 'div', { style: styles.nested }, h( 'div', { style: styles.grid }, - h(Field, { label: '目录', value: detail.dir, onChange: function () {} }), + h(Field, { label: '目录', value: String(detail.dir), onChange: function () {} }), h(Field, { label: 'SKILL.md 哈希', value: String(detail.skill !== undefined ? detail.skill.skillSha256 : ''), onChange: function () {} }), ), h('p', { style: styles.hint }, '文件:' + String(Array.isArray(detail.files) ? detail.files.length : 0) + ' 个,共 ' + formatBytes(detail.totalBytes) + (detail.truncated ? '(SKILL.md 过长,已截断显示)' : '')), @@ -1468,16 +1711,16 @@ window.__ModuleLoader__.load({ h( 'p', { style: styles.hint }, - '将实际删除:' + String(skills.uninstall.dir) + '\n影响:' + String(skills.uninstall.files) + ' 个文件 / ' + formatBytes(skills.uninstall.bytes) + (Array.isArray(skills.uninstall.scripts) && skills.uninstall.scripts.length > 0 ? ';含脚本:' + skills.uninstall.scripts.join('、') : ''), + '将实际删除:' + String(skills.uninstall.dir) + ';影响:' + String(skills.uninstall.files) + ' 个文件 / ' + formatBytes(skills.uninstall.bytes) + (Array.isArray(skills.uninstall.scripts) && skills.uninstall.scripts.length > 0 ? ';含脚本:' + skills.uninstall.scripts.join('、') : ''), ), h('p', { style: styles.hint }, String(skills.uninstall.note)), h( 'div', { style: styles.actions }, - h(Btn, { variant: 'danger', label: skills.busy === 'remove' ? '删除中…' : '确认删除(不可恢复)', disabled: skills.busy !== '', onClick: confirmUninstall }), + h(Btn, { variant: 'danger', label: tree.busy === 'uninstall' ? '删除中…' : '确认删除(不可恢复)', disabled: tree.busy !== '', onClick: confirmUninstall }), h(Btn, { label: '取消', - disabled: skills.busy !== '', + disabled: tree.busy !== '', onClick: function () { patchSkills({ uninstall: null }) }, @@ -1533,15 +1776,327 @@ window.__ModuleLoader__.load({ { style: styles.actions }, h(Btn, { variant: 'primary', - label: skills.busy === 'commit' ? '安装中…' : '安装所选(' + String(skills.selection.length) + ')', - disabled: skills.busy !== '' || skills.selection.length === 0, + label: tree.busy === 'commit' ? '安装中…' : '安装所选(' + String(skills.selection.length) + ')', + disabled: tree.busy !== '' || skills.selection.length === 0, onClick: commitInstall, }), - h(Btn, { label: '放弃计划', variant: 'small', disabled: skills.busy !== '', onClick: cancelInstall }), + h(Btn, { label: '放弃计划', variant: 'small', disabled: tree.busy !== '', onClick: cancelInstall }), ), ) } + var assignBox = null + if (tree.assign !== null) { + var assignSource = treeSources.find(function (source) { + return source.id === tree.assign.sourceId + }) + var assignGroup = assignSource === undefined + ? undefined + : (assignSource.groups || []).find(function (group) { + return group.id === tree.assign.groupId + }) + var assignable = [] + if (assignSource !== undefined) { + (assignSource.groups || []).forEach(function (group) { + (group.skills || []).forEach(function (skill) { + if (!assignable.some(function (item) { return item.folder === skill.folder })) assignable.push(skill) + }) + }) + } + assignBox = h( + 'div', + { style: styles.row }, + h( + 'div', + { style: styles.rowHead }, + h('span', { style: styles.rowTitle }, '加入分类:' + String(assignGroup === undefined ? '' : assignGroup.name)), + h(Btn, { + label: '关闭', + variant: 'small', + onClick: function () { + patchTree({ assign: null }) + }, + }), + ), + h('p', { style: styles.hint }, '勾选要放进这个分类的技能;一个技能只会属于一个分类,取消勾选即回到「未分类」。'), + h( + 'div', + { style: { display: 'flex', flexDirection: 'column', gap: '4px', maxHeight: '240px', overflow: 'auto' } }, + assignable.map(function (skill) { + var checked = tree.assign.selection.indexOf(skill.folder) >= 0 + return h( + 'label', + { key: String(skill.folder), style: styles.checkboxRow }, + h('input', { + type: 'checkbox', + checked: checked, + onChange: function (event) { + var next = tree.assign.selection.slice() + var at = next.indexOf(skill.folder) + if (event.target.checked && at < 0) next.push(skill.folder) + if (!event.target.checked && at >= 0) next.splice(at, 1) + patchTree({ assign: Object.assign({}, tree.assign, { selection: next }) }) + }, + }), + h('span', { style: { minWidth: 0 } }, String(skill.name) + ' ', h('span', { style: styles.hint }, '· ' + String(skill.folder))), + ) + }), + ), + h( + 'div', + { style: styles.actions }, + h(Btn, { + variant: 'primary', + label: '保存分类', + disabled: tree.busy !== '', + onClick: function () { + saveAssign() + }, + }), + h(Btn, { + label: '取消', + disabled: tree.busy !== '', + onClick: function () { + patchTree({ assign: null }) + }, + }), + ), + ) + } + + var renderSkillRow = function (source, skill) { + return h( + 'div', + { key: String(source.id) + ':' + String(skill.folder), style: styles.skillRow }, + h( + 'div', + { style: { display: 'flex', flexDirection: 'column', gap: '2px', minWidth: 0, flex: '1 1 220px' } }, + h('span', { style: styles.rowTitle }, String(skill.name)), + skill.description === '' ? null : h('span', { style: Object.assign({}, styles.hint, styles.clamp2) }, String(skill.description)), + h( + 'span', + { style: styles.hint }, + String(skill.files) + ' 个文件 · ' + formatBytes(skill.bytes) + (skill.origin === undefined ? '' : ' · ' + String(ORIGIN_LABELS[skill.origin] === undefined ? skill.origin : ORIGIN_LABELS[skill.origin])) + (skill.enabledEditable !== true ? ' · 只读' : ''), + ), + ), + h( + 'div', + { style: styles.actions }, + source.writable !== true + ? h(Pill, { label: '开关', value: '只读', tone: 'muted' }) + : h(Btn, { label: '详情', variant: 'small', disabled: tree.busy !== '', onClick: function () { openDetail(skill.folder) } }), + skill.enabledEditable !== true + ? null + : h(Toggle, { + checked: skill.enabled === true, + disabled: tree.busy !== '', + label: '技能 ' + String(skill.name) + ' 启停', + onChange: function () { + toggleSkill(skill.folder, skill.enabled !== true) + }, + }), + source.writable !== true + ? null + : h(Btn, { label: '卸载…', variant: 'small', disabled: tree.busy !== '', onClick: function () { planUninstall(skill.folder) } }), + ), + ) + } + + var renderGroup = function (source, group) { + var open = tree.openGroups[String(source.id) + ':' + group.id] === true + var renameKey = String(source.id) + ':' + group.id + var renaming = tree.edit !== null && tree.edit.kind === 'rename' && tree.edit.key === renameKey + var confirming = tree.confirm === renameKey + var groupSkills = group.visible === undefined ? group.skills || [] : group.visible + return h( + 'div', + { key: renameKey, style: styles.groupRow }, + h( + 'div', + { style: styles.rowHead }, + h( + 'div', + { style: { display: 'flex', alignItems: 'center', gap: '6px', minWidth: 0, flexWrap: 'wrap' } }, + h(Btn, { + label: open ? '▾' : '▸', + variant: 'small', + ariaLabel: '展开或收起 ' + String(group.name), + onClick: function () { + patchTree({ openGroups: Object.assign({}, tree.openGroups, { [renameKey]: !open }) }) + }, + }), + h('span', { style: styles.folderGlyph }, '📁'), + renaming + ? h('input', { + style: Object.assign({}, styles.input, { width: '160px' }), + value: tree.edit.value, + autoFocus: true, + onChange: function (event) { + patchTree({ edit: Object.assign({}, tree.edit, { value: event.target.value }) }) + }, + }) + : h('span', { style: styles.rowTitle }, String(group.name)), + h('span', { style: styles.hint }, String(group.total) + ' 项 · ' + String(group.enabledCount) + '/' + String(group.total) + ' 启用'), + group.cardOnly === true ? h(Pill, { label: '开关', value: '仅本卡', tone: 'muted' }) : null, + ), + h( + 'div', + { style: styles.actions }, + renaming + ? h(Btn, { label: '保存', variant: 'small', disabled: tree.busy !== '', onClick: saveRename }) + : h(Btn, { + label: '+', + variant: 'small', + ariaLabel: '把技能加入 ' + String(group.name), + disabled: tree.busy !== '' || group.id === 'unassigned', + onClick: function () { + openAssign(source, group) + }, + }), + renaming + ? h(Btn, { label: '取消', variant: 'small', onClick: function () { patchTree({ edit: null }) } }) + : h(Btn, { + label: '改名', + variant: 'small', + ariaLabel: '重命名 ' + String(group.name), + disabled: tree.busy !== '' || group.id === 'unassigned', + onClick: function () { + patchTree({ edit: { kind: 'rename', key: renameKey, sourceId: source.id, groupId: group.id, value: String(group.name) } }) + }, + }), + confirming + ? h(Btn, { label: '确认删除分类', variant: 'danger', disabled: tree.busy !== '', onClick: function () { deleteGroup(source.id, group.id) } }) + : h(Btn, { + label: '删除', + variant: 'small', + ariaLabel: '删除分类 ' + String(group.name) + '(技能回到未分类)', + disabled: tree.busy !== '' || group.id === 'unassigned', + onClick: function () { + patchTree({ confirm: renameKey }) + setNotice({ tone: 'warn', text: '删除分类只删除分组记录,里面的技能会回到「未分类」,文件不会被删除。再点一次确认。' }) + }, + }), + group.enabledEditable === false + ? null + : h(Toggle, { + checked: group.enabled !== false, + disabled: tree.busy !== '', + label: '分类 ' + String(group.name) + ' 启停', + onChange: function () { + toggleGroup(source.id, group.id, group.enabled === false) + }, + }), + ), + ), + open + ? h( + 'div', + { style: styles.nested }, + groupSkills.length === 0 + ? h('p', { style: styles.hint }, group.id === 'unassigned' ? '没有未分类的技能。' : '这个分类还没有技能,点「+」加入。') + : groupSkills.map(function (skill) { + return renderSkillRow(source, skill) + }), + ) + : null, + ) + } + + var renderSource = function (source) { + var open = tree.expanded[source.id] !== false + var creating = tree.edit !== null && tree.edit.kind === 'create' && tree.edit.sourceId === source.id + var groups = visibleGroupsOf(source) + return h( + 'div', + { key: source.id, style: styles.sourceCard }, + h( + 'div', + { style: styles.rowHead }, + h( + 'div', + { style: { display: 'flex', alignItems: 'center', gap: '8px', minWidth: 0, flexWrap: 'wrap' } }, + h(Btn, { + label: open ? '▾' : '▸', + variant: 'small', + ariaLabel: '展开或收起 ' + source.label, + onClick: function () { + patchTree({ expanded: Object.assign({}, tree.expanded, { [source.id]: !open }) }) + }, + }), + h('span', { style: styles.sourceGlyph }, String(source.label).slice(0, 1)), + h('span', { style: styles.sourceTitle }, String(source.label)), + h('span', { style: styles.hint }, String(source.total) + ' 个技能'), + ), + h( + 'div', + { style: { display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap', minWidth: 0 } }, + h('span', { style: Object.assign({}, styles.hint, styles.mono) }, String(source.root)), + h(Btn, { + label: '+', + variant: 'small', + ariaLabel: '在 ' + String(source.label) + ' 新建分类', + disabled: tree.busy !== '', + onClick: function () { + patchTree({ edit: { kind: 'create', sourceId: source.id, value: '' } }) + }, + }), + h(Btn, { + label: '打开目录', + variant: 'small', + ariaLabel: '在文件管理器打开 ' + String(source.root), + disabled: tree.busy !== '' || source.exists !== true, + onClick: function () { + revealSource(source.id) + }, + }), + h(Toggle, { + checked: source.enabled !== false, + disabled: tree.busy !== '', + label: '来源 ' + String(source.label) + ' 启停', + onChange: function () { + toggleSource(source.id, source.enabled === false) + }, + }), + ), + ), + h( + 'p', + { style: styles.hint }, + source.exists !== true + ? '目录还不存在(未安装或未使用):' + String(source.root) + : source.writable === true + ? '本卡可以真实启停这里的技能:停用会把目录移入 skills-disabled,新会话生效。' + : String(source.note === undefined ? '由 ' + String(source.manager) + ' 自行加载,本卡只读。' : source.note), + ), + open + ? h( + 'div', + { style: { display: 'flex', flexDirection: 'column', gap: '8px', marginTop: '8px' } }, + groups.map(function (group) { + return renderGroup(source, group) + }), + creating + ? h( + 'div', + { style: Object.assign({}, styles.row, { flexDirection: 'row', alignItems: 'center', flexWrap: 'wrap' }) }, + h('input', { + style: Object.assign({}, styles.input, { width: '180px' }), + placeholder: '分类名称,例如 QQ-Skill', + value: tree.edit.value, + autoFocus: true, + onChange: function (event) { + patchTree({ edit: Object.assign({}, tree.edit, { value: event.target.value }) }) + }, + }), + h(Btn, { label: '创建分类', variant: 'primary', disabled: tree.busy !== '', onClick: createGroup }), + h(Btn, { label: '取消', onClick: function () { patchTree({ edit: null }) } }), + ) + : null, + ) + : null, + ) + } + skillsTab = h( 'div', { style: styles.root, key: 'skills' }, @@ -1549,97 +2104,41 @@ window.__ModuleLoader__.load({ h( Section, { - title: '本机技能', - hint: '启停是把目录移进 / 移出技能目录,属于新会话生效;卸载是真实删除,没有回收站。', - aside: h(Btn, { label: skills.status === 'loading' ? '刷新中…' : '刷新', variant: 'small', disabled: skills.status === 'loading', onClick: loadSkills }), + title: '技能文件夹', + hint: '按软件来源分组;展开来源与分类查看技能。', }, - skills.error === null ? null : h(Banner, { tone: 'bad' }, skills.error), h( 'div', - { style: styles.grid }, - h(Field, { - label: '搜索', - value: skills.search, - placeholder: '按名称、目录或描述筛选', - onChange: function (value) { - patchSkills({ search: value }) + { style: { display: 'flex', gap: '8px', alignItems: 'flex-end', flexWrap: 'wrap' } }, + h( + 'div', + { style: { flex: '1 1 220px', minWidth: 0 } }, + h(Field, { + label: '搜索', + value: skills.search, + placeholder: '按名称、目录或描述筛选', + onChange: function (value) { + patchSkills({ search: value }) + }, + }), + ), + h(Btn, { + label: tree.status === 'loading' ? '刷新中…' : '刷新', + variant: 'small', + disabled: tree.status === 'loading', + onClick: function () { + loadTree() + loadSkills() }, }), ), - h( - 'div', - { style: styles.chips, role: 'group', 'aria-label': '技能筛选' }, - [ - { value: 'all', label: '全部' }, - { value: 'enabled', label: '已启用' }, - { value: 'disabled', label: '已停用' }, - { value: 'cloud', label: '云端来源' }, - ].map(function (option) { - return h( - 'button', - { - key: option.value, - type: 'button', - style: Object.assign({}, styles.chip, filter === option.value ? styles.chipActive : null), - onClick: function () { - patchSkills({ filter: option.value }) - }, - }, - option.label, - ) - }), - ), - skills.status === 'loading' && skills.data === null - ? h('p', { style: styles.hint }, '正在读取技能目录…') - : filtered.length === 0 - ? h('p', { style: styles.hint }, skillList.length === 0 ? '技能目录里没有技能。' : '没有符合筛选条件的技能。') - : h( - 'div', - { style: { display: 'flex', flexDirection: 'column', gap: '8px' } }, - filtered.map(function (skill) { - return h( - 'div', - { key: String(skill.folder), style: styles.row }, - h( - 'div', - { style: styles.rowHead }, - h( - 'span', - { style: styles.rowTitle }, - String(skill.name) + ' ', - h('span', { style: styles.hint }, '· ' + String(skill.folder)), - ), - h( - 'div', - { style: styles.pills }, - h(Pill, { label: '状态', value: skill.enabled === true ? '已启用' : '已停用', tone: skill.enabled === true ? 'ok' : 'muted' }), - h(Pill, { label: '来源', value: ORIGIN_LABELS[skill.origin] === undefined ? String(skill.origin) : ORIGIN_LABELS[skill.origin], tone: skill.origin === 'cloud' ? 'warn' : 'muted' }), - skill.revision === undefined ? null : h(Pill, { label: 'revision', value: skill.revision, tone: 'muted' }), - ), - ), - skill.description === '' ? null : h('p', { style: styles.hint }, String(skill.description)), - h( - 'p', - { style: styles.hint }, - String(skill.files) + ' 个文件 · ' + formatBytes(skill.bytes) + ' · 安装于 ' + formatIso(skill.installedAt) + ' · 所有者 ' + String(skill.ownerManager), - ), - h( - 'div', - { style: styles.actions }, - h(Btn, { label: '详情', variant: 'small', disabled: skills.busy !== '', onClick: function () { openDetail(skill.folder) } }), - h(Btn, { - label: skill.enabled === true ? '停用' : '启用', - variant: 'small', - disabled: skills.busy !== '', - onClick: function () { - toggleSkill(skill.folder, skill.enabled !== true) - }, - }), - h(Btn, { label: '卸载…', variant: 'small', disabled: skills.busy !== '', onClick: function () { planUninstall(skill.folder) } }), - ), - ) - }), - ), + tree.error === null ? null : h(Banner, { tone: 'bad' }, tree.error), + tree.status === 'loading' && tree.data === null ? h('p', { style: styles.hint }, '正在读取技能来源…') : null, + tree.status === 'ready' && treeSources.length === 0 ? h('p', { style: styles.hint }, '没有探测到任何技能来源。') : null, + treeSources.map(function (source) { + return renderSource(source) + }), + tree.data !== null && tree.data.note !== undefined ? h('p', { style: styles.hint }, String(tree.data.note)) : null, ), detailBox, @@ -1649,16 +2148,20 @@ window.__ModuleLoader__.load({ Section, { title: '从 Git 仓库安装', - hint: '先克隆到隔离暂存目录并列出候选技能,确认后才写入技能目录;不执行仓库里的任何脚本,符号链接不会跟随。仓库地址只接受 https:// 或 file://。', + hint: '先克隆到隔离暂存目录并列出候选技能,确认后才写入 DSH 技能目录;不执行仓库里的任何脚本,符号链接不会跟随。仓库地址只接受 https:// 或 file://。', }, - h(Field, { - label: '仓库地址', - value: skills.installUrl, - placeholder: 'https://github.com//.git', - onChange: function (value) { - patchSkills({ installUrl: value }) - }, - }), + h( + 'div', + { style: styles.grid }, + h(Field, { + label: '仓库地址', + value: skills.installUrl, + placeholder: 'https://github.com//.git', + onChange: function (value) { + patchSkills({ installUrl: value }) + }, + }), + ), h( 'div', { style: styles.actions }, @@ -1668,7 +2171,6 @@ window.__ModuleLoader__.load({ disabled: skills.busy !== '', onClick: prepareInstall, }), - h(Btn, { label: '刷新列表', variant: 'small', disabled: skills.status === 'loading', onClick: loadSkills }), ), planBox, ), diff --git a/docs/management-surface.md b/docs/management-surface.md index ec78fe8..1bfc273 100644 --- a/docs/management-surface.md +++ b/docs/management-surface.md @@ -77,3 +77,57 @@ POST /mcp-connector/api { "method": "status" | "healthCheck" | "toolsList" | " - MCP 市场的内嵌浏览与安装:未实现,只给宿主面板位置。 - 跨软件(Codex / Claude Code / OpenCode)适配与工作区级作用域:未实现,仍在方案 P0/P4 调研项。 - 浏览器端实机验收(375/574/1280 宽、深色模式、真实上报):需要重启 DSH 后由用户在界面确认。 + +## 5. 技能来源树(0.5.0 增补) + +「技能管理」页签按软件来源组织,来源→分类→技能三层,与工作方式一致:DSH 来源是真的,其他软件目录只读。 + +### 5.1 来源检测 + +| id | 标签 | 目录 | 本卡权限 | +|---|---|---|---| +| `dsh` | DSH | `$DSH_HOME/skills`(停用区 `$DSH_HOME/skills-disabled`) | 真实启停 | +| `agents` | 公共 Agent | `~/.agents/skills` | 只读 | +| `codex` | Codex | `~/.codex/skills` | 只读 | +| `workbuddy` | WorkBuddy | `~/.workbuddy/skills` | 只读 | +| `claude` | Claude Code | `~/.claude/skills` | 只读 | +| `opencode` | OpenCode | `~/.config/opencode/skills` | 只读 | + +目录不存在也照实显示 0 个(标注「目录还不存在」),不猜、不造。检测每次刷新时重算。 + +### 5.2 分类是纯元数据 + +`$DSH_HOME/cloud-memory-skill-groups.json` 只存 `{sourceId: {enabled, groups: [{id,name,enabled,skills:[folder]}]}}`。 + +- 新建 / 改名 / 删除分类都不移动任何文件;删除分类只是把成员释放回「未分类」,接口返回 `released` 数量。 +- 一个技能最多属于一个分类:加入新分类会先从旧分类移除。 +- 未分类是合成分组(`id: 'unassigned'`),它的开关对该来源里所有未被分类的技能逐个生效。 + +### 5.3 开关的真实边界 + +| 位置 | DSH 来源 | 其他来源 | +|---|---|---| +| 来源开关 | 真实:全部技能移入/移出 `skills-disabled` | `cardOnly: true`,只记在本卡,不动它们的目录 | +| 分类开关 | 真实:该分类成员逐个启停,返回 `applied` / `failed` | `cardOnly: true` | +| 技能开关 | 真实(目录移动) | 不提供(行内标「只读」) | + +任何真实启停都是目录移动,属于**新会话生效**;已在运行的会话保留旧状态。失败项逐条返回,不整批回滚成谎报成功。 + +### 5.4 接口 + +| 方法 | 路径 | 说明 | +|---|---|---| +| GET | `/cloud-memory/skills/sources` | 整棵树 + `note`(分类不移动文件、只有 DSH 真实启停) | +| POST | `/cloud-memory/skills/groups/create` | `{sourceId, name}` | +| POST | `/cloud-memory/skills/groups/rename` | `{sourceId, groupId, name}` | +| POST | `/cloud-memory/skills/groups/delete` | `{sourceId, groupId}` → `{released}` | +| POST | `/cloud-memory/skills/groups/assign` | `{sourceId, groupId, folders[]}`;`groupId:'unassigned'` 或空数组=移出分类 | +| POST | `/cloud-memory/skills/groups/toggle` | `{sourceId, groupId, enabled}` → `{cardOnly, applied[], failed[]}` | +| POST | `/cloud-memory/skills/source/toggle` | `{sourceId, enabled}` → `{cardOnly, applied, failed[]}` | +| POST | `/cloud-memory/skills/source/reveal` | `{sourceId}` → 在系统文件管理器打开该来源根目录(仅已登记的源) | + +错误码:`unknown_source` / `not_found` → 404,`invalid_name` / `duplicate` / `too_many` → 400。 + +### 5.5 验证 + +`verify-skill-tree.mjs`:40 项通过——来源与计数、分类增删改、成员唯一性、DSH 真实 park/unpark、「未分类」开关只作用于未分类技能、外来源 `cardOnly` 且目录字节不变、持久化重开、路由闸门与错误码。 diff --git a/lib/index.js b/lib/index.js index 153ed61..59ec8a9 100644 --- a/lib/index.js +++ b/lib/index.js @@ -16,6 +16,7 @@ import { join } from 'node:path'; import { SettingsStore, dshHome } from "./store.js"; import { SkillSync } from "./skill-sync.js"; import { SkillAdmin, skillsHoldingDir } from "./skill-admin.js"; +import { SkillGroupManager, detectSources } from "./skill-groups.js"; import { createMemoryTools, createSkillTools } from "./tools.js"; /** Package name; also the client bundle id. */ export const name = 'dsh-cloud-memory'; @@ -63,6 +64,13 @@ export function apply(ctx, config) { syncRunning: () => skillSync.stats().running, log: (message) => logger.info(message), }); + // The tree's sources are detected per call so a directory created while the + // process runs shows up on the next refresh. + const skillGroups = new SkillGroupManager({ + sources: () => detectSources(), + admin: skillAdmin, + log: (message) => logger.info(message), + }); // Announce at most once per activation so a missing token is obvious in logs. const effective = settings(); if (!effective.enabled) { @@ -106,7 +114,7 @@ export function apply(ctx, config) { logger.warn('webServer service unavailable; the configuration page stays disabled'); } else { - const routes = createRoutes({ version: VERSION, store, reporter, client: () => client, skills: () => skillSync.stats(), admin: skillAdmin }); + const routes = createRoutes({ version: VERSION, store, reporter, client: () => client, skills: () => skillSync.stats(), admin: skillAdmin, groups: skillGroups }); for (const route of routes) { ctx.effect(() => webServer.register(route), `dsh-cloud-memory: route ${route.path}`); } diff --git a/lib/routes.js b/lib/routes.js index 1179654..032f781 100644 --- a/lib/routes.js +++ b/lib/routes.js @@ -1,6 +1,7 @@ import { describeError, isSecureLoginTarget } from "./api.js"; import { renderConfigPage } from "./page.js"; import { SkillAdminError } from "./skill-admin.js"; +import { SkillGroupError } from "./skill-groups.js"; import { renderSkillsPage } from "./skill-page.js"; import { randomUUID } from 'node:crypto'; /** Route constants — kept in one place so the client half can reuse them. */ @@ -511,6 +512,19 @@ async function serveSkills(deps, req, res) { json(res, 200, { ok: true, ...inventory, ...(await admin.listPlans()) }); return; } + if (suffix === '/sources') { + if (req.method !== 'GET') { + fail(res, 405, 'method-not-allowed'); + return; + } + const groups = deps.groups; + if (groups === undefined) { + fail(res, 404, 'skill-groups-unavailable'); + return; + } + json(res, 200, { ok: true, ...(await groups.overview()) }); + return; + } const actions = { '/detail': async (body) => ({ ...(await admin.detail(body.folder)) }), '/toggle': async (body) => ({ ...(await admin.setEnabled(body.folder, body.enabled === true)) }), @@ -534,7 +548,19 @@ async function serveSkills(deps, req, res) { return { ...(await admin.remove(folder)) }; }, }; - const action = actions[suffix]; + // Category and source switches live in the same prefix so the card has one + // base URL; they are grouped here because they never touch a skill folder + // directly (except the DSH park/unpark the group manager delegates). + const groupActions = { + '/groups/create': async (body) => ({ ...(await requireGroups(deps).createGroup(body.sourceId, body.name)) }), + '/groups/rename': async (body) => ({ ...(await requireGroups(deps).renameGroup(body.sourceId, body.groupId, body.name)) }), + '/groups/delete': async (body) => ({ ...(await requireGroups(deps).deleteGroup(body.sourceId, body.groupId)) }), + '/groups/assign': async (body) => ({ ...(await requireGroups(deps).assign(body.sourceId, body.groupId, body.folders)) }), + '/groups/toggle': async (body) => ({ ...(await requireGroups(deps).toggleGroup(body.sourceId, body.groupId, body.enabled === true)) }), + '/source/toggle': async (body) => ({ ...(await requireGroups(deps).toggleSource(body.sourceId, body.enabled === true)) }), + '/source/reveal': async (body) => ({ ...(await requireGroups(deps).reveal(body.sourceId)) }), + }; + const action = actions[suffix] ?? groupActions[suffix]; if (action === undefined) { fail(res, 404, 'unknown-skill-route'); return; @@ -550,9 +576,31 @@ async function serveSkills(deps, req, res) { json(res, adminStatus(error.code), { ok: false, code: error.code, error: error.message }); return; } + if (error instanceof SkillGroupError) { + json(res, groupStatus(error.code), { ok: false, code: error.code, error: error.message }); + return; + } json(res, 500, { ok: false, code: 'internal', error: error instanceof Error ? error.message : String(error) }); } } +/** The group manager is optional; the routes answer 404 when it is absent. */ +function requireGroups(deps) { + if (deps.groups === undefined) + throw new SkillGroupError('unavailable', '技能分组功能未启用。'); + return deps.groups; +} +/** HTTP status for one group failure code. */ +function groupStatus(code) { + switch (code) { + case 'not_found': + case 'unknown_source': return 404; + case 'invalid_name': + case 'duplicate': + case 'too_many': return 400; + case 'unavailable': return 503; + default: return 500; + } +} /** Build the exact-route table registered with the host web server. */ export function createRoutes(deps) { return [ diff --git a/lib/skill-groups.js b/lib/skill-groups.js new file mode 100644 index 0000000..ec06c0f --- /dev/null +++ b/lib/skill-groups.js @@ -0,0 +1,457 @@ +/** + * Multi-source skill tree. + * + * The card groups skills the way the user thinks about them: by the software + * that owns the directory (DSH, 公共 Agent, Codex, WorkBuddy, …), then by + * user-defined categories inside that source. + * + * Two rules keep this honest: + * + * 1. A category is metadata only. Creating, renaming or deleting one never + * moves or removes a skill file; deleting a category just sends its skills + * back to 未分类. That is what the "分类只记在这个来源里,不移动文件" note + * promises, and it is the only reason a delete button is safe here. + * 2. Only the DSH source is ours to switch. Parking a DSH skill is the same + * directory move the rest of the plugin uses. Another software's directory + * is never touched: its switch is recorded for this card only and the view + * says so, instead of pretending Codex stopped loading something. + */ +import { execFile } from 'node:child_process'; +import { randomUUID } from 'node:crypto'; +import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'; +import { readdir, readFile } from 'node:fs/promises'; +import { homedir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { dshHome } from "./store.js"; +const MAX_GROUP_NAME = 40; +const MAX_GROUPS_PER_SOURCE = 40; +/** Sidecar path. */ +export function skillGroupsPath() { + return join(dshHome(), 'cloud-memory-skill-groups.json'); +} +/** + * The known sources. + * + * A source is listed even when its directory is missing (0 skills, "未安装"), + * because that is how a user learns the software exists; it is never invented + * as present. + */ +export function detectSources() { + const home = homedir(); + return [ + { id: 'dsh', label: 'DSH', root: join(dshHome(), 'skills'), writable: true, manager: 'DSH' }, + { + id: 'agents', + label: '公共 Agent', + root: join(home, '.agents', 'skills'), + writable: false, + manager: '公共 Agent 约定目录', + note: '由使用该目录的各客户端自行加载,本卡只读', + }, + { + id: 'codex', + label: 'Codex', + root: join(home, '.codex', 'skills'), + writable: false, + manager: 'Codex', + note: '由 Codex 自行加载,本卡不修改它的目录', + }, + { + id: 'workbuddy', + label: 'WorkBuddy', + root: join(home, '.workbuddy', 'skills'), + writable: false, + manager: 'WorkBuddy', + note: '由 WorkBuddy 自行加载,本卡不修改它的目录', + }, + { + id: 'claude', + label: 'Claude Code', + root: join(home, '.claude', 'skills'), + writable: false, + manager: 'Claude Code', + note: '由 Claude Code 自行加载,本卡不修改它的目录', + }, + { + id: 'opencode', + label: 'OpenCode', + root: join(home, '.config', 'opencode', 'skills'), + writable: false, + manager: 'OpenCode', + note: '由 OpenCode 自行加载,本卡不修改它的目录', + }, + ]; +} +function groupId() { + return `g_${randomUUID().slice(0, 8)}`; +} +/** Trim and bound one user-supplied category name. */ +function cleanGroupName(value) { + const name = typeof value === 'string' ? value.trim() : ''; + if (name === '' || name.length > MAX_GROUP_NAME) { + throw new SkillGroupError('invalid_name', '分类名需要 1–40 个字符。'); + } + return name; +} +/** A group failure with a stable code, mapped to an HTTP status by the route. */ +export class SkillGroupError extends Error { + code; + constructor(code, message) { + super(message); + this.code = code; + this.name = 'SkillGroupError'; + } +} +/** Read one skill directory without following links. */ +async function readSkill(root, folder) { + const dir = join(root, folder); + try { + const info = statSync(dir); + if (!info.isDirectory()) + return undefined; + } + catch { + return undefined; + } + const markdown = await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined); + if (markdown === undefined) + return undefined; + const frontmatter = /^---\s*([\s\S]*?)\s*---/.exec(markdown); + const name = frontmatter === null ? '' : (/^name:\s*(.+)$/m.exec(frontmatter[1] ?? '')?.[1] ?? '').trim(); + const description = frontmatter === null ? '' : (/^description:\s*(.+)$/m.exec(frontmatter[1] ?? '')?.[1] ?? '').trim(); + let files = 0; + let bytes = 0; + const walk = async (sub) => { + if (files > 2000) + return; + for (const entry of await readdir(join(dir, sub), { withFileTypes: true }).catch(() => [])) { + if (entry.name === '.git') + continue; + const rel = sub === '' ? entry.name : `${sub}/${entry.name}`; + if (entry.isDirectory()) { + await walk(rel); + continue; + } + if (!entry.isFile()) + continue; + files += 1; + try { + bytes += statSync(join(dir, rel)).size; + } + catch { + // A file removed mid-walk only affects the size hint. + } + } + }; + await walk(''); + return { + folder, + name: name === '' ? folder : name, + description: description.slice(0, 300), + enabled: true, + enabledEditable: false, + files, + bytes, + inCardDisabled: false, + }; +} +/** List the folders of one source that look like skills. */ +async function readSource(root) { + const skills = []; + for (const entry of await readdir(root, { withFileTypes: true }).catch(() => [])) { + if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name.startsWith('_')) + continue; + const skill = await readSkill(root, entry.name); + if (skill !== undefined) + skills.push(skill); + } + skills.sort((a, b) => (a.folder < b.folder ? -1 : 1)); + return skills; +} +export class SkillGroupManager { + deps; + constructor(deps) { + this.deps = deps; + } + file() { + return this.deps.storePath?.() ?? skillGroupsPath(); + } + read() { + try { + const parsed = JSON.parse(readFileSync(this.file(), 'utf8')); + if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) { + const doc = parsed; + if (doc.sources !== null && typeof doc.sources === 'object') + return { version: 1, sources: doc.sources }; + } + } + catch { + // Missing or torn sidecar: start from "everything unassigned". + } + return { version: 1, sources: {} }; + } + write(next) { + const path = this.file(); + mkdirSync(resolve(path, '..'), { recursive: true }); + const temporary = `${path}.tmp`; + writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 }); + renameSync(temporary, path); + } + source(id) { + const sourceId = typeof id === 'string' ? id : ''; + const found = this.deps.sources().find((source) => source.id === sourceId); + if (found === undefined) + throw new SkillGroupError('unknown_source', `未知来源:${String(id)}`); + return found; + } + /** Skills of one source, with this plugin's own enable state for DSH. */ + async skillsOf(source) { + if (source.writable) { + const inventory = await this.deps.admin.list(); + return inventory.skills.map((skill) => ({ + folder: skill.folder, + name: skill.name, + description: skill.description, + enabled: skill.enabled, + enabledEditable: true, + files: skill.files, + bytes: skill.bytes, + origin: skill.origin, + ...(skill.revision === undefined ? {} : { revision: skill.revision }), + inCardDisabled: false, + })); + } + return readSource(source.root); + } + /** Everything the tree renders: sources → groups → skills. */ + async overview() { + const doc = this.read(); + const sources = []; + for (const source of this.deps.sources()) { + const skills = await this.skillsOf(source); + const state = doc.sources[source.id] ?? {}; + const groups = Array.isArray(state.groups) ? state.groups : []; + const assigned = new Set(); + const views = []; + for (const group of groups) { + const members = skills.filter((skill) => group.skills.includes(skill.folder)); + for (const member of members) + assigned.add(member.folder); + const enabled = group.enabled !== false; + // A group switch is real only where the source is real. + const cardOnly = !source.writable; + views.push({ + id: group.id, + name: group.name, + enabled, + enabledEditable: true, + cardOnly, + total: members.length, + enabledCount: members.filter((skill) => skill.enabled && enabled).length, + skills: members.map((skill) => ({ ...skill, enabled: skill.enabled && enabled, inCardDisabled: enabled === false })), + }); + } + const rest = skills.filter((skill) => !assigned.has(skill.folder)); + views.push({ + id: 'unassigned', + name: '未分类', + // The bucket's own switch is "every skill that has no category": it is + // on only when all of them are, and switching it parks/restores them + // one by one like any other group. + enabled: rest.length === 0 || rest.every((skill) => skill.enabled), + enabledEditable: rest.length > 0, + cardOnly: !source.writable, + total: rest.length, + enabledCount: rest.filter((skill) => skill.enabled).length, + skills: rest, + }); + const sourceEnabled = state.enabled !== false; + sources.push({ + id: source.id, + label: source.label, + root: source.root, + exists: existsSync(source.root), + writable: source.writable, + manager: source.manager, + ...(source.note === undefined ? {} : { note: source.note }), + enabled: sourceEnabled, + enabledEditable: true, + cardOnly: !source.writable, + total: skills.length, + enabledCount: skills.filter((skill) => skill.enabled && sourceEnabled).length, + groups: views, + }); + } + return { + sources, + note: '分类只记在这个来源里,不移动文件。只有 DSH 来源的开关会真实启停技能目录;其他软件的目录本卡不修改。', + }; + } + /** Create one category inside a source. */ + async createGroup(sourceInput, nameInput) { + const source = this.source(sourceInput); + const name = cleanGroupName(nameInput); + const doc = this.read(); + const state = doc.sources[source.id] ?? {}; + const groups = state.groups ?? []; + if (groups.length >= MAX_GROUPS_PER_SOURCE) + throw new SkillGroupError('too_many', `每个来源最多 ${MAX_GROUPS_PER_SOURCE} 个分类。`); + if (groups.some((group) => group.name === name)) + throw new SkillGroupError('duplicate', `这个来源里已经有分类「${name}」。`); + const id = groupId(); + doc.sources[source.id] = { ...state, groups: [...groups, { id, name, enabled: true, skills: [] }] }; + this.write(doc); + this.deps.log?.(`skill category created: ${source.id}/${name}`); + return { groupId: id, name }; + } + /** Rename one category; membership and files are untouched. */ + async renameGroup(sourceInput, groupInput, nameInput) { + const source = this.source(sourceInput); + const id = typeof groupInput === 'string' ? groupInput : ''; + const name = cleanGroupName(nameInput); + const doc = this.read(); + const state = doc.sources[source.id] ?? {}; + const groups = state.groups ?? []; + const target = groups.find((group) => group.id === id); + if (target === undefined) + throw new SkillGroupError('not_found', '没有找到这个分类。'); + if (groups.some((group) => group.name === name && group.id !== id)) { + throw new SkillGroupError('duplicate', `这个来源里已经有分类「${name}」。`); + } + target.name = name; + doc.sources[source.id] = { ...state, groups }; + this.write(doc); + return { groupId: id, name }; + } + /** + * Delete one category. Its skills move back to 未分类; no file is touched, + * which is why this needs no impact plan of its own. + */ + async deleteGroup(sourceInput, groupInput) { + const source = this.source(sourceInput); + const id = typeof groupInput === 'string' ? groupInput : ''; + const doc = this.read(); + const state = doc.sources[source.id] ?? {}; + const groups = state.groups ?? []; + const target = groups.find((group) => group.id === id); + if (target === undefined) + throw new SkillGroupError('not_found', '没有找到这个分类。'); + doc.sources[source.id] = { ...state, groups: groups.filter((group) => group.id !== id) }; + this.write(doc); + this.deps.log?.(`skill category removed: ${source.id}/${target.name}`); + return { groupId: id, released: target.skills.length }; + } + /** Move skills into (or out of) a category. Membership only. */ + async assign(sourceInput, groupInput, foldersInput) { + const source = this.source(sourceInput); + const id = typeof groupInput === 'string' ? groupInput : ''; + const folders = Array.isArray(foldersInput) + ? foldersInput.filter((value) => typeof value === 'string' && value !== '' && !value.includes('/') && !value.includes('\\')) + : []; + const doc = this.read(); + const state = doc.sources[source.id] ?? {}; + const groups = state.groups ?? []; + if (id === 'unassigned' || folders.length === 0) { + // Clearing a selection means "back to 未分类" for every other group. + for (const group of groups) + group.skills = group.skills.filter((folder) => !folders.includes(folder)); + doc.sources[source.id] = { ...state, groups }; + this.write(doc); + return { groupId: 'unassigned', members: [] }; + } + const target = groups.find((group) => group.id === id); + if (target === undefined) + throw new SkillGroupError('not_found', '没有找到这个分类。'); + // A skill belongs to at most one category: remove it everywhere else first. + for (const group of groups) { + if (group === target) + continue; + group.skills = group.skills.filter((folder) => !folders.includes(folder)); + } + target.skills = [...new Set([...target.skills, ...folders])].sort(); + doc.sources[source.id] = { ...state, groups }; + this.write(doc); + return { groupId: id, members: target.skills }; + } + /** + * Switch one category on or off. + * + * DSH groups are really parked or restored, one folder at a time, and a + * failure leaves the remaining folders untouched. Foreign groups only record + * the switch here, and the answer says `cardOnly: true`. + */ + async toggleGroup(sourceInput, groupInput, enabled) { + const source = this.source(sourceInput); + const id = typeof groupInput === 'string' ? groupInput : ''; + const doc = this.read(); + const state = doc.sources[source.id] ?? {}; + const groups = state.groups ?? []; + let targets = []; + if (id === 'unassigned') { + // "未分类" is the bucket of everything no category claims; its switch + // applies to exactly those skills and is not persisted. + const assigned = new Set(groups.flatMap((group) => group.skills)); + const skills = await this.skillsOf(source); + targets = skills.filter((skill) => !assigned.has(skill.folder)).map((skill) => skill.folder); + if (!source.writable) + return { groupId: id, enabled, cardOnly: true, applied: [], failed: [] }; + } + else { + const target = groups.find((group) => group.id === id); + if (target === undefined) + throw new SkillGroupError('not_found', '没有找到这个分类。'); + target.enabled = enabled; + doc.sources[source.id] = { ...state, groups }; + this.write(doc); + if (!source.writable) + return { groupId: id, enabled, cardOnly: true, applied: [], failed: [] }; + targets = target.skills; + } + const applied = []; + const failed = []; + for (const folder of targets) { + try { + await this.deps.admin.setEnabled(folder, enabled); + applied.push(folder); + } + catch (failure) { + failed.push({ folder, reason: failure instanceof Error ? failure.message : String(failure) }); + } + } + return { groupId: id, enabled, cardOnly: false, applied, failed }; + } + /** Switch a whole source. DSH really moves every skill; others record it. */ + async toggleSource(sourceInput, enabled) { + const source = this.source(sourceInput); + const doc = this.read(); + const state = doc.sources[source.id] ?? {}; + doc.sources[source.id] = { ...state, enabled }; + this.write(doc); + if (!source.writable) + return { sourceId: source.id, enabled, cardOnly: true, applied: 0, failed: [] }; + const skills = await this.skillsOf(source); + const failed = []; + let applied = 0; + for (const skill of skills) { + try { + await this.deps.admin.setEnabled(skill.folder, enabled); + applied += 1; + } + catch (failure) { + failed.push({ folder: skill.folder, reason: failure instanceof Error ? failure.message : String(failure) }); + } + } + return { sourceId: source.id, enabled, cardOnly: false, applied, failed }; + } + /** Open one source directory in the OS file manager (explicit user click). */ + async reveal(sourceInput) { + const source = this.source(sourceInput); + if (!existsSync(source.root)) + throw new SkillGroupError('not_found', `${source.label} 的技能目录还不存在:${source.root}`); + const command = process.platform === 'win32' ? 'explorer.exe' : process.platform === 'darwin' ? 'open' : 'xdg-open'; + await new Promise((resolvePromise) => { + execFile(command, [source.root], { windowsHide: false }, () => resolvePromise()); + }); + return { path: source.root }; + } +} diff --git a/preview-card.mjs b/preview-card.mjs new file mode 100644 index 0000000..371e68f --- /dev/null +++ b/preview-card.mjs @@ -0,0 +1,374 @@ +// Renders the real 技能管理 tab to a static PNG so the layout can be reviewed +// before DSH is restarted. It reads the *live* skill sources through the built +// plugin (read-only) and draws them with the bundle's own render tree, then +// screenshots the result with headless Chrome. +import { execFileSync } from 'node:child_process' +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' + +const here = dirname(fileURLToPath(import.meta.url)) +const source = readFileSync(join(here, 'client', 'index.js'), 'utf8') + +// ── real data ─────────────────────────────────────────────────────────── +const { SkillAdmin, skillsHoldingDir } = await import('./lib/skill-admin.js') +const { SkillGroupManager, detectSources } = await import('./lib/skill-groups.js') +const { SettingsStore } = await import('./lib/store.js') + +const store = new SettingsStore({}) +const admin = new SkillAdmin({ + skillsRoot: () => join(store.path, '..', 'skills'), + holdingDir: () => skillsHoldingDir(), + syncStatePath: () => join(store.path, '..', 'cloud-memory-skills.json'), + syncRunning: () => false, + log: () => {}, +}) +const groups = new SkillGroupManager({ sources: () => detectSources(), admin, log: () => {} }) +const overview = await groups.overview() + +const statusBody = { + ok: true, + settings: { + enabled: true, + baseUrl: 'https://mem.qyhhh.top/api/longmemory', + baseUrlConfigured: true, + baseUrlOrigin: 'https://mem.qyhhh.top', + clientId: 'dsh-desktop', + requestTimeoutMs: 5000, + defaultK: 10, + summaryEnabled: true, + summaryMaxChars: 6000, + skillsSyncEnabled: true, + skillsDir: '', + }, + tokens: { + activity: { configured: true, masked: 'cmt_9f2c1a…7d4e' }, + memory: { configured: true, masked: 'cmt_3b81cc…22a9' }, + summary: { configured: true, masked: 'cmt_71ad02…9f10' }, + }, + settingsPath: 'C:/Users/qyh15/.dsh/cloud-memory.json', + reporter: { attempted: 12, recorded: 11, duplicate: 1, failed: 0, skipped: 0, queued: 0, recent: [] }, + lastCheck: { + at: Date.now(), + checks: [ + { id: 'network', label: '服务地址', state: 'ok', message: '服务可达(HTTP 200)' }, + { id: 'activity', label: '活动上报权限(activity:write)', state: 'ok', message: '鉴权通过' }, + { id: 'memory', label: '记忆读写权限(memory:write)', state: 'ok', message: '鉴权通过(3 个项目)' }, + { id: 'summary', label: '摘要权限(summary:write)', state: 'ok', message: '鉴权通过' }, + ], + }, + capabilities: { version: '0.5.0', features: { skills: true, skillsMarketplace: false, mcpBridge: 'host-plugin' }, notes: [] }, + skills: { running: false, downloaded: [], uploaded: [], updated: [], conflicts: [], skipped: 0 }, +} + +// ── minimal React + HTML serializer ───────────────────────────────────── +let hooks = [] +let cursor = 0 +let pendingEffects = [] +let scheduled = false + +const React = { + createElement(type, props, ...children) { + const flat = [] + const push = (value) => { + if (Array.isArray(value)) value.forEach(push) + else if (value !== null && value !== undefined && value !== false && value !== true) flat.push(value) + } + push(children) + return { type, props: { ...(props ?? {}), children: flat.length === 1 ? flat[0] : flat }, children: flat } + }, + useState(initial) { + const index = cursor++ + if (!(index in hooks)) hooks[index] = typeof initial === 'function' ? initial() : initial + const setter = (next) => { + const value = typeof next === 'function' ? next(hooks[index]) : next + if (value !== hooks[index]) { + hooks[index] = value + scheduled = true + } + } + return [hooks[index], setter] + }, + useEffect(fn) { + pendingEffects.push(fn) + }, + useCallback(fn) { + return fn + }, + Component: function Component(props) { + this.props = props + }, +} +React.Component.prototype.setState = function setState(patch) { + this.state = { ...this.state, ...patch } + scheduled = true +} + +function walk(node, visit) { + if (node === null || node === undefined || node === false || node === true) return + if (typeof node === 'string' || typeof node === 'number') return + if (Array.isArray(node)) { + node.forEach((child) => walk(child, visit)) + return + } + if (typeof node.type === 'function') { + if (node.type.prototype && typeof node.type.prototype.render === 'function') { + const instance = new node.type(node.props) + instance.props = node.props + if (instance.state === undefined) instance.state = {} + instance.setState = function setState(patch) { + instance.state = { ...instance.state, ...patch } + scheduled = true + } + walk(instance.render(), visit) + return + } + walk(node.type({ ...node.props, children: node.children }), visit) + return + } + visit(node) + node.children.forEach((child) => walk(child, visit)) +} + +const UNITLESS = new Set(['fontWeight', 'opacity', 'lineHeight', 'flex', 'zIndex', 'flexGrow', 'flexShrink']) + +function styleOf(style) { + const parts = [] + for (const [key, value] of Object.entries(style ?? {})) { + if (value === null || value === undefined) continue + const name = key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`) + parts.push(`${name}:${typeof value === 'number' && !UNITLESS.has(key) ? `${value}px` : String(value)}`) + } + return parts.join(';') +} + +function escapeHtml(text) { + return String(text).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"') +} + +function toHtml(node) { + if (node === null || node === undefined || node === false || node === true) return '' + if (typeof node === 'string' || typeof node === 'number') return escapeHtml(node) + if (Array.isArray(node)) return node.map(toHtml).join('') + const { type, props, children } = node + if (typeof type === 'function') { + if (type.prototype && typeof type.prototype.render === 'function') { + const instance = new type(props) + instance.props = props + if (instance.state === undefined) instance.state = {} + return toHtml(instance.render()) + } + return toHtml(type({ ...props, children })) + } + const attrs = [] + const style = styleOf(props.style) + if (style !== '') attrs.push(`style="${style}"`) + if (props.id !== undefined) attrs.push(`id="${escapeHtml(props.id)}"`) + if (props.role !== undefined) attrs.push(`role="${escapeHtml(props.role)}"`) + if (props.title !== undefined) attrs.push(`title="${escapeHtml(props.title)}"`) + if (props.disabled === true) attrs.push('disabled') + if (props.type === 'checkbox') attrs.push(props.checked === true ? 'checked' : '') + for (const [key, value] of Object.entries(props)) { + if (key.startsWith('aria-')) attrs.push(`${key}="${escapeHtml(value)}"`) + } + if (type === 'input') { + attrs.push(`value="${escapeHtml(props.value === undefined ? '' : props.value)}"`) + attrs.push(`placeholder="${escapeHtml(props.placeholder === undefined ? '' : props.placeholder)}"`) + attrs.push(`type="${escapeHtml(props.type === undefined ? 'text' : props.type)}"`) + return `` + } + return `<${type} ${attrs.filter(Boolean).join(' ')}>${children.map(toHtml).join('')}` +} + +// ── drive the real bundle ─────────────────────────────────────────────── +const localStorageStub = { + getItem: (key) => (String(key).endsWith(':tab') ? 'skills' : null), + setItem: () => {}, +} +let registered = null +globalThis.window = { + localStorage: localStorageStub, + addEventListener: () => {}, + removeEventListener: () => {}, + __ModuleLoader__: { + load(spec) { + const exportsObject = spec.factory(requireShim) + const captured = [] + exportsObject.apply({ + slots: { + inject: (_seat, fn) => fn(), + register: (_options, component) => { + captured.push(component) + return () => {} + }, + }, + }) + registered = captured[0] + }, + }, +} +function requireShim(id) { + if (id === 'react') return React + throw new Error(`unexpected require: ${id}`) +} + +async function fakeFetch(url) { + const path = String(url).split('?')[0] + let body = { ok: false } + if (path === '/cloud-memory/status') body = statusBody + else if (path === '/cloud-memory/skills/sources') body = { ok: true, ...overview } + else if (path.startsWith('/cloud-memory/skills/api')) body = { ok: true, skills: overview.sources[0]?.groups.flatMap((group) => group.skills) ?? [], plans: [] } + return { status: body.ok === false ? 404 : 200, json: async () => body, text: async () => JSON.stringify(body) } +} + +function loadCard() { + registered = null + new Function('window', 'require', 'document', 'localStorage', 'fetch', 'console', 'setInterval', 'clearInterval', 'setTimeout', 'clearTimeout', 'AbortController', source)( + globalThis.window, + requireShim, + { visibilityState: 'visible' }, + localStorageStub, + fakeFetch, + { warn: () => {}, log: () => {} }, + () => 0, + () => {}, + () => 0, + () => {}, + AbortController, + ) + return registered +} + +const card = loadCard() +let treeEl = null +for (let pass = 0; pass < 6; pass += 1) { + cursor = 0 + pendingEffects = [] + scheduled = false + treeEl = React.createElement(card, null) + // Rendering is what runs the hooks (and therefore queues the effects). + void toHtml(treeEl) + const effects = pendingEffects + pendingEffects = [] + for (const effect of effects) { + const cleanup = effect() + if (typeof cleanup === 'function') cleanup() + } + await new Promise((resolve) => setTimeout(resolve, 0)) + if (!scheduled) break +} + +// Click one control by its aria-label, so the preview can show an expanded +// category without a real browser event. +function clickLabel(root, prefix, occurrence) { + let index = 0 + let clicked = false + walk(root, (node) => { + if (clicked) return + const props = node.props ?? {} + const label = props['aria-label'] + if (typeof label === 'string' && label.startsWith(prefix)) { + if (index === occurrence) { + if (typeof props.onClick === 'function') props.onClick() + clicked = true + } + index += 1 + } + }) + return clicked +} + +cursor = 0 +pendingEffects = [] +const expanded = clickLabel(treeEl, '展开或收起 未分类', 0) +if (expanded) { + for (let pass = 0; pass < 3; pass += 1) { + cursor = 0 + pendingEffects = [] + scheduled = false + void toHtml(treeEl) + const effects = pendingEffects + pendingEffects = [] + for (const effect of effects) effect() + await new Promise((resolve) => setTimeout(resolve, 0)) + if (!scheduled) break + } +} else { + console.warn('preview: could not find the 未分类 category to expand') +} + +// The final render must start from the first hook slot again, otherwise the +// component would read fresh initial values instead of the loaded state. +cursor = 0 +pendingEffects = [] +const body = toHtml(treeEl) + +// Second pass with every category collapsed: that is the default view a user +// sees first, and it puts the sections below the tree into the screenshot. +hooks = [] +cursor = 0 +const compactCard = loadCard() +let compactEl = null +for (let pass = 0; pass < 6; pass += 1) { + cursor = 0 + pendingEffects = [] + scheduled = false + compactEl = React.createElement(compactCard, null) + void toHtml(compactEl) + const effects = pendingEffects + pendingEffects = [] + for (const effect of effects) { + const cleanup = effect() + if (typeof cleanup === 'function') cleanup() + } + await new Promise((resolve) => setTimeout(resolve, 0)) + if (!scheduled) break +} +cursor = 0 +pendingEffects = [] +const compactBody = toHtml(compactEl) +if (body.includes('渲染失败')) { + console.error('the card rendered its error boundary instead of the tree') + process.exit(1) +} + +const page = (theme) => ` +
${body}
` + +const outDir = join(here, '_preview') +mkdirSync(outDir, { recursive: true }) +const htmlPath = join(outDir, 'skill-tree.html') +writeFileSync(htmlPath, page('light'), 'utf8') +const darkPath = join(outDir, 'skill-tree-dark.html') +writeFileSync(darkPath, page('dark'), 'utf8') +const compactPath = join(outDir, 'skill-tree-compact.html') +writeFileSync(compactPath, page('light').replace(body, compactBody), 'utf8') + +const chrome = 'C:/Program Files/Google/Chrome/Application/chrome.exe' +for (const [input, output] of [ + [htmlPath, join(outDir, 'skill-tree.png')], + [darkPath, join(outDir, 'skill-tree-dark.png')], + [compactPath, join(outDir, 'skill-tree-compact.png')], +]) { + execFileSync(chrome, [ + '--headless=new', + '--disable-gpu', + '--hide-scrollbars', + '--force-device-scale-factor=2', + '--window-size=640,2000', + `--screenshot=${output}`, + `file:///${input.replace(/\\/g, '/')}`, + ], { stdio: 'ignore' }) + console.log(`wrote ${output}`) +} +console.log('sources:', overview.sources.map((item) => `${item.label}=${item.total}`).join(', ')) diff --git a/src/index.ts b/src/index.ts index b31b314..054e49f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -17,6 +17,7 @@ import { join } from 'node:path' import { SettingsStore, dshHome } from './store.ts' import { SkillSync } from './skill-sync.ts' import { SkillAdmin, skillsHoldingDir } from './skill-admin.ts' +import { SkillGroupManager, detectSources } from './skill-groups.ts' import { createMemoryTools, createSkillTools } from './tools.ts' /** Package name; also the client bundle id. */ @@ -74,6 +75,14 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void { syncRunning: () => skillSync.stats().running, log: (message) => logger.info(message), }) + + // The tree's sources are detected per call so a directory created while the + // process runs shows up on the next refresh. + const skillGroups = new SkillGroupManager({ + sources: () => detectSources(), + admin: skillAdmin, + log: (message) => logger.info(message), + }) // Announce at most once per activation so a missing token is obvious in logs. const effective = settings() if (!effective.enabled) { @@ -122,7 +131,7 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void { if (webServer === undefined) { logger.warn('webServer service unavailable; the configuration page stays disabled') } else { - const routes = createRoutes({ version: VERSION, store, reporter, client: () => client, skills: () => skillSync.stats(), admin: skillAdmin }) + const routes = createRoutes({ version: VERSION, store, reporter, client: () => client, skills: () => skillSync.stats(), admin: skillAdmin, groups: skillGroups }) for (const route of routes) { ctx.effect(() => webServer.register(route), `dsh-cloud-memory: route ${route.path}`) } diff --git a/src/routes.ts b/src/routes.ts index 933a1aa..73833c0 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -29,6 +29,8 @@ import type { CloudMemoryWebRoute } from './context-types.ts' import type { SkillSyncStats } from './skill-sync.ts' import { SkillAdminError } from './skill-admin.ts' import type { SkillAdmin } from './skill-admin.ts' +import { SkillGroupError } from './skill-groups.ts' +import type { SkillGroupManager } from './skill-groups.ts' import { renderSkillsPage } from './skill-page.ts' import { randomUUID } from 'node:crypto' @@ -57,6 +59,8 @@ export interface RouteDeps { skills?: () => SkillSyncStats /** Local skill management (list / toggle / install / uninstall), when wired in. */ admin?: SkillAdmin + /** Multi-source skill tree (sources, categories, per-group switches). */ + groups?: SkillGroupManager } /** One feature flag the card reads before it renders a control. */ @@ -583,6 +587,19 @@ async function serveSkills(deps: RouteDeps, req: IncomingMessage, res: ServerRes json(res, 200, { ok: true, ...inventory, ...(await admin.listPlans()) }) return } + if (suffix === '/sources') { + if (req.method !== 'GET') { + fail(res, 405, 'method-not-allowed') + return + } + const groups = deps.groups + if (groups === undefined) { + fail(res, 404, 'skill-groups-unavailable') + return + } + json(res, 200, { ok: true, ...(await groups.overview()) }) + return + } type Handler = (body: Record) => Promise> const actions: Record = { @@ -608,7 +625,19 @@ async function serveSkills(deps: RouteDeps, req: IncomingMessage, res: ServerRes return { ...(await admin.remove(folder)) } }, } - const action = actions[suffix] + // Category and source switches live in the same prefix so the card has one + // base URL; they are grouped here because they never touch a skill folder + // directly (except the DSH park/unpark the group manager delegates). + const groupActions: Record = { + '/groups/create': async (body) => ({ ...(await requireGroups(deps).createGroup(body.sourceId, body.name)) }), + '/groups/rename': async (body) => ({ ...(await requireGroups(deps).renameGroup(body.sourceId, body.groupId, body.name)) }), + '/groups/delete': async (body) => ({ ...(await requireGroups(deps).deleteGroup(body.sourceId, body.groupId)) }), + '/groups/assign': async (body) => ({ ...(await requireGroups(deps).assign(body.sourceId, body.groupId, body.folders)) }), + '/groups/toggle': async (body) => ({ ...(await requireGroups(deps).toggleGroup(body.sourceId, body.groupId, body.enabled === true)) }), + '/source/toggle': async (body) => ({ ...(await requireGroups(deps).toggleSource(body.sourceId, body.enabled === true)) }), + '/source/reveal': async (body) => ({ ...(await requireGroups(deps).reveal(body.sourceId)) }), + } + const action = actions[suffix] ?? groupActions[suffix] if (action === undefined) { fail(res, 404, 'unknown-skill-route') return @@ -622,10 +651,33 @@ async function serveSkills(deps: RouteDeps, req: IncomingMessage, res: ServerRes json(res, adminStatus(error.code), { ok: false, code: error.code, error: error.message }) return } + if (error instanceof SkillGroupError) { + json(res, groupStatus(error.code), { ok: false, code: error.code, error: error.message }) + return + } json(res, 500, { ok: false, code: 'internal', error: error instanceof Error ? error.message : String(error) }) } } +/** The group manager is optional; the routes answer 404 when it is absent. */ +function requireGroups(deps: RouteDeps): SkillGroupManager { + if (deps.groups === undefined) throw new SkillGroupError('unavailable', '技能分组功能未启用。') + return deps.groups +} + +/** HTTP status for one group failure code. */ +function groupStatus(code: string): number { + switch (code) { + case 'not_found': + case 'unknown_source': return 404 + case 'invalid_name': + case 'duplicate': + case 'too_many': return 400 + case 'unavailable': return 503 + default: return 500 + } +} + /** Build the exact-route table registered with the host web server. */ export function createRoutes(deps: RouteDeps): CloudMemoryWebRoute[] { return [ diff --git a/src/skill-groups.ts b/src/skill-groups.ts new file mode 100644 index 0000000..0714c05 --- /dev/null +++ b/src/skill-groups.ts @@ -0,0 +1,521 @@ +/** + * Multi-source skill tree. + * + * The card groups skills the way the user thinks about them: by the software + * that owns the directory (DSH, 公共 Agent, Codex, WorkBuddy, …), then by + * user-defined categories inside that source. + * + * Two rules keep this honest: + * + * 1. A category is metadata only. Creating, renaming or deleting one never + * moves or removes a skill file; deleting a category just sends its skills + * back to 未分类. That is what the "分类只记在这个来源里,不移动文件" note + * promises, and it is the only reason a delete button is safe here. + * 2. Only the DSH source is ours to switch. Parking a DSH skill is the same + * directory move the rest of the plugin uses. Another software's directory + * is never touched: its switch is recorded for this card only and the view + * says so, instead of pretending Codex stopped loading something. + */ +import { execFile } from 'node:child_process' +import { randomUUID } from 'node:crypto' +import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs' +import { readdir, readFile } from 'node:fs/promises' +import { homedir } from 'node:os' +import { join, resolve } from 'node:path' +import { dshHome } from './store.ts' +import type { SkillAdmin, SkillEntry } from './skill-admin.ts' + +/** One directory the tree can show. */ +export interface SkillSourceDef { + id: string + label: string + root: string + /** True only for the source this plugin may move folders in. */ + writable: boolean + /** Who owns the directory, for the row's explanation. */ + manager: string + /** Short reason shown next to the switch when the source is read-only. */ + note?: string +} + +/** A skill as one tree leaf. */ +export interface TreeSkill { + folder: string + name: string + description: string + enabled: boolean + enabledEditable: boolean + files: number + bytes: number + origin?: string + revision?: number + inCardDisabled: boolean +} + +export interface TreeGroup { + id: string + name: string + enabled: boolean + /** False when the switch only applies to this card (foreign source). */ + enabledEditable: boolean + /** True when the switch was recorded here but does not affect the owner. */ + cardOnly: boolean + total: number + enabledCount: number + skills: TreeSkill[] +} + +export interface TreeSource { + id: string + label: string + root: string + exists: boolean + writable: boolean + manager: string + note?: string + enabled: boolean + enabledEditable: boolean + cardOnly: boolean + total: number + enabledCount: number + groups: TreeGroup[] +} + +/** Persisted sidecar: source switches plus category membership. */ +interface GroupsFile { + version: 1 + sources: Record +} + +const MAX_GROUP_NAME = 40 +const MAX_GROUPS_PER_SOURCE = 40 + +/** Sidecar path. */ +export function skillGroupsPath(): string { + return join(dshHome(), 'cloud-memory-skill-groups.json') +} + +/** + * The known sources. + * + * A source is listed even when its directory is missing (0 skills, "未安装"), + * because that is how a user learns the software exists; it is never invented + * as present. + */ +export function detectSources(): SkillSourceDef[] { + const home = homedir() + return [ + { id: 'dsh', label: 'DSH', root: join(dshHome(), 'skills'), writable: true, manager: 'DSH' }, + { + id: 'agents', + label: '公共 Agent', + root: join(home, '.agents', 'skills'), + writable: false, + manager: '公共 Agent 约定目录', + note: '由使用该目录的各客户端自行加载,本卡只读', + }, + { + id: 'codex', + label: 'Codex', + root: join(home, '.codex', 'skills'), + writable: false, + manager: 'Codex', + note: '由 Codex 自行加载,本卡不修改它的目录', + }, + { + id: 'workbuddy', + label: 'WorkBuddy', + root: join(home, '.workbuddy', 'skills'), + writable: false, + manager: 'WorkBuddy', + note: '由 WorkBuddy 自行加载,本卡不修改它的目录', + }, + { + id: 'claude', + label: 'Claude Code', + root: join(home, '.claude', 'skills'), + writable: false, + manager: 'Claude Code', + note: '由 Claude Code 自行加载,本卡不修改它的目录', + }, + { + id: 'opencode', + label: 'OpenCode', + root: join(home, '.config', 'opencode', 'skills'), + writable: false, + manager: 'OpenCode', + note: '由 OpenCode 自行加载,本卡不修改它的目录', + }, + ] +} + +function groupId(): string { + return `g_${randomUUID().slice(0, 8)}` +} + +/** Trim and bound one user-supplied category name. */ +function cleanGroupName(value: unknown): string { + const name = typeof value === 'string' ? value.trim() : '' + if (name === '' || name.length > MAX_GROUP_NAME) { + throw new SkillGroupError('invalid_name', '分类名需要 1–40 个字符。') + } + return name +} + +/** A group failure with a stable code, mapped to an HTTP status by the route. */ +export class SkillGroupError extends Error { + code: string + constructor(code: string, message: string) { + super(message) + this.code = code + this.name = 'SkillGroupError' + } +} + +export interface SkillGroupDeps { + sources: () => SkillSourceDef[] + admin: SkillAdmin + storePath?: () => string + log?: (message: string) => void +} + +/** Read one skill directory without following links. */ +async function readSkill(root: string, folder: string): Promise { + const dir = join(root, folder) + try { + const info = statSync(dir) + if (!info.isDirectory()) return undefined + } catch { + return undefined + } + const markdown = await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined) + if (markdown === undefined) return undefined + const frontmatter = /^---\s*([\s\S]*?)\s*---/.exec(markdown) + const name = frontmatter === null ? '' : (/^name:\s*(.+)$/m.exec(frontmatter[1] ?? '')?.[1] ?? '').trim() + const description = frontmatter === null ? '' : (/^description:\s*(.+)$/m.exec(frontmatter[1] ?? '')?.[1] ?? '').trim() + let files = 0 + let bytes = 0 + const walk = async (sub: string): Promise => { + if (files > 2000) return + for (const entry of await readdir(join(dir, sub), { withFileTypes: true }).catch(() => [])) { + if (entry.name === '.git') continue + const rel = sub === '' ? entry.name : `${sub}/${entry.name}` + if (entry.isDirectory()) { + await walk(rel) + continue + } + if (!entry.isFile()) continue + files += 1 + try { + bytes += statSync(join(dir, rel)).size + } catch { + // A file removed mid-walk only affects the size hint. + } + } + } + await walk('') + return { + folder, + name: name === '' ? folder : name, + description: description.slice(0, 300), + enabled: true, + enabledEditable: false, + files, + bytes, + inCardDisabled: false, + } +} + +/** List the folders of one source that look like skills. */ +async function readSource(root: string): Promise { + const skills: TreeSkill[] = [] + for (const entry of await readdir(root, { withFileTypes: true }).catch(() => [])) { + if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name.startsWith('_')) continue + const skill = await readSkill(root, entry.name) + if (skill !== undefined) skills.push(skill) + } + skills.sort((a, b) => (a.folder < b.folder ? -1 : 1)) + return skills +} + +export class SkillGroupManager { + private readonly deps: SkillGroupDeps + constructor(deps: SkillGroupDeps) { + this.deps = deps + } + + private file(): string { + return this.deps.storePath?.() ?? skillGroupsPath() + } + + private read(): GroupsFile { + try { + const parsed: unknown = JSON.parse(readFileSync(this.file(), 'utf8')) + if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) { + const doc = parsed as GroupsFile + if (doc.sources !== null && typeof doc.sources === 'object') return { version: 1, sources: doc.sources } + } + } catch { + // Missing or torn sidecar: start from "everything unassigned". + } + return { version: 1, sources: {} } + } + + private write(next: GroupsFile): void { + const path = this.file() + mkdirSync(resolve(path, '..'), { recursive: true }) + const temporary = `${path}.tmp` + writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 }) + renameSync(temporary, path) + } + + private source(id: unknown): SkillSourceDef { + const sourceId = typeof id === 'string' ? id : '' + const found = this.deps.sources().find((source) => source.id === sourceId) + if (found === undefined) throw new SkillGroupError('unknown_source', `未知来源:${String(id)}`) + return found + } + + /** Skills of one source, with this plugin's own enable state for DSH. */ + private async skillsOf(source: SkillSourceDef): Promise { + if (source.writable) { + const inventory = await this.deps.admin.list() + return inventory.skills.map((skill: SkillEntry) => ({ + folder: skill.folder, + name: skill.name, + description: skill.description, + enabled: skill.enabled, + enabledEditable: true, + files: skill.files, + bytes: skill.bytes, + origin: skill.origin, + ...(skill.revision === undefined ? {} : { revision: skill.revision }), + inCardDisabled: false, + })) + } + return readSource(source.root) + } + + /** Everything the tree renders: sources → groups → skills. */ + async overview(): Promise<{ sources: TreeSource[]; note: string }> { + const doc = this.read() + const sources: TreeSource[] = [] + for (const source of this.deps.sources()) { + const skills = await this.skillsOf(source) + const state = doc.sources[source.id] ?? {} + const groups = Array.isArray(state.groups) ? state.groups : [] + const assigned = new Set() + const views: TreeGroup[] = [] + for (const group of groups) { + const members = skills.filter((skill) => group.skills.includes(skill.folder)) + for (const member of members) assigned.add(member.folder) + const enabled = group.enabled !== false + // A group switch is real only where the source is real. + const cardOnly = !source.writable + views.push({ + id: group.id, + name: group.name, + enabled, + enabledEditable: true, + cardOnly, + total: members.length, + enabledCount: members.filter((skill) => skill.enabled && enabled).length, + skills: members.map((skill) => ({ ...skill, enabled: skill.enabled && enabled, inCardDisabled: enabled === false })), + }) + } + const rest = skills.filter((skill) => !assigned.has(skill.folder)) + views.push({ + id: 'unassigned', + name: '未分类', + // The bucket's own switch is "every skill that has no category": it is + // on only when all of them are, and switching it parks/restores them + // one by one like any other group. + enabled: rest.length === 0 || rest.every((skill) => skill.enabled), + enabledEditable: rest.length > 0, + cardOnly: !source.writable, + total: rest.length, + enabledCount: rest.filter((skill) => skill.enabled).length, + skills: rest, + }) + const sourceEnabled = state.enabled !== false + sources.push({ + id: source.id, + label: source.label, + root: source.root, + exists: existsSync(source.root), + writable: source.writable, + manager: source.manager, + ...(source.note === undefined ? {} : { note: source.note }), + enabled: sourceEnabled, + enabledEditable: true, + cardOnly: !source.writable, + total: skills.length, + enabledCount: skills.filter((skill) => skill.enabled && sourceEnabled).length, + groups: views, + }) + } + return { + sources, + note: '分类只记在这个来源里,不移动文件。只有 DSH 来源的开关会真实启停技能目录;其他软件的目录本卡不修改。', + } + } + + /** Create one category inside a source. */ + async createGroup(sourceInput: unknown, nameInput: unknown): Promise<{ groupId: string; name: string }> { + const source = this.source(sourceInput) + const name = cleanGroupName(nameInput) + const doc = this.read() + const state = doc.sources[source.id] ?? {} + const groups = state.groups ?? [] + if (groups.length >= MAX_GROUPS_PER_SOURCE) throw new SkillGroupError('too_many', `每个来源最多 ${MAX_GROUPS_PER_SOURCE} 个分类。`) + if (groups.some((group) => group.name === name)) throw new SkillGroupError('duplicate', `这个来源里已经有分类「${name}」。`) + const id = groupId() + doc.sources[source.id] = { ...state, groups: [...groups, { id, name, enabled: true, skills: [] }] } + this.write(doc) + this.deps.log?.(`skill category created: ${source.id}/${name}`) + return { groupId: id, name } + } + + /** Rename one category; membership and files are untouched. */ + async renameGroup(sourceInput: unknown, groupInput: unknown, nameInput: unknown): Promise<{ groupId: string; name: string }> { + const source = this.source(sourceInput) + const id = typeof groupInput === 'string' ? groupInput : '' + const name = cleanGroupName(nameInput) + const doc = this.read() + const state = doc.sources[source.id] ?? {} + const groups = state.groups ?? [] + const target = groups.find((group) => group.id === id) + if (target === undefined) throw new SkillGroupError('not_found', '没有找到这个分类。') + if (groups.some((group) => group.name === name && group.id !== id)) { + throw new SkillGroupError('duplicate', `这个来源里已经有分类「${name}」。`) + } + target.name = name + doc.sources[source.id] = { ...state, groups } + this.write(doc) + return { groupId: id, name } + } + + /** + * Delete one category. Its skills move back to 未分类; no file is touched, + * which is why this needs no impact plan of its own. + */ + async deleteGroup(sourceInput: unknown, groupInput: unknown): Promise<{ groupId: string; released: number }> { + const source = this.source(sourceInput) + const id = typeof groupInput === 'string' ? groupInput : '' + const doc = this.read() + const state = doc.sources[source.id] ?? {} + const groups = state.groups ?? [] + const target = groups.find((group) => group.id === id) + if (target === undefined) throw new SkillGroupError('not_found', '没有找到这个分类。') + doc.sources[source.id] = { ...state, groups: groups.filter((group) => group.id !== id) } + this.write(doc) + this.deps.log?.(`skill category removed: ${source.id}/${target.name}`) + return { groupId: id, released: target.skills.length } + } + + /** Move skills into (or out of) a category. Membership only. */ + async assign(sourceInput: unknown, groupInput: unknown, foldersInput: unknown): Promise<{ groupId: string; members: string[] }> { + const source = this.source(sourceInput) + const id = typeof groupInput === 'string' ? groupInput : '' + const folders = Array.isArray(foldersInput) + ? foldersInput.filter((value): value is string => typeof value === 'string' && value !== '' && !value.includes('/') && !value.includes('\\')) + : [] + const doc = this.read() + const state = doc.sources[source.id] ?? {} + const groups = state.groups ?? [] + if (id === 'unassigned' || folders.length === 0) { + // Clearing a selection means "back to 未分类" for every other group. + for (const group of groups) group.skills = group.skills.filter((folder) => !folders.includes(folder)) + doc.sources[source.id] = { ...state, groups } + this.write(doc) + return { groupId: 'unassigned', members: [] } + } + const target = groups.find((group) => group.id === id) + if (target === undefined) throw new SkillGroupError('not_found', '没有找到这个分类。') + // A skill belongs to at most one category: remove it everywhere else first. + for (const group of groups) { + if (group === target) continue + group.skills = group.skills.filter((folder) => !folders.includes(folder)) + } + target.skills = [...new Set([...target.skills, ...folders])].sort() + doc.sources[source.id] = { ...state, groups } + this.write(doc) + return { groupId: id, members: target.skills } + } + + /** + * Switch one category on or off. + * + * DSH groups are really parked or restored, one folder at a time, and a + * failure leaves the remaining folders untouched. Foreign groups only record + * the switch here, and the answer says `cardOnly: true`. + */ + async toggleGroup(sourceInput: unknown, groupInput: unknown, enabled: boolean): Promise<{ groupId: string; enabled: boolean; cardOnly: boolean; applied: string[]; failed: { folder: string; reason: string }[] }> { + const source = this.source(sourceInput) + const id = typeof groupInput === 'string' ? groupInput : '' + const doc = this.read() + const state = doc.sources[source.id] ?? {} + const groups = state.groups ?? [] + let targets: string[] = [] + if (id === 'unassigned') { + // "未分类" is the bucket of everything no category claims; its switch + // applies to exactly those skills and is not persisted. + const assigned = new Set(groups.flatMap((group) => group.skills)) + const skills = await this.skillsOf(source) + targets = skills.filter((skill) => !assigned.has(skill.folder)).map((skill) => skill.folder) + if (!source.writable) return { groupId: id, enabled, cardOnly: true, applied: [], failed: [] } + } else { + const target = groups.find((group) => group.id === id) + if (target === undefined) throw new SkillGroupError('not_found', '没有找到这个分类。') + target.enabled = enabled + doc.sources[source.id] = { ...state, groups } + this.write(doc) + if (!source.writable) return { groupId: id, enabled, cardOnly: true, applied: [], failed: [] } + targets = target.skills + } + const applied: string[] = [] + const failed: { folder: string; reason: string }[] = [] + for (const folder of targets) { + try { + await this.deps.admin.setEnabled(folder, enabled) + applied.push(folder) + } catch (failure) { + failed.push({ folder, reason: failure instanceof Error ? failure.message : String(failure) }) + } + } + return { groupId: id, enabled, cardOnly: false, applied, failed } + } + + /** Switch a whole source. DSH really moves every skill; others record it. */ + async toggleSource(sourceInput: unknown, enabled: boolean): Promise<{ sourceId: string; enabled: boolean; cardOnly: boolean; applied: number; failed: { folder: string; reason: string }[] }> { + const source = this.source(sourceInput) + const doc = this.read() + const state = doc.sources[source.id] ?? {} + doc.sources[source.id] = { ...state, enabled } + this.write(doc) + if (!source.writable) return { sourceId: source.id, enabled, cardOnly: true, applied: 0, failed: [] } + const skills = await this.skillsOf(source) + const failed: { folder: string; reason: string }[] = [] + let applied = 0 + for (const skill of skills) { + try { + await this.deps.admin.setEnabled(skill.folder, enabled) + applied += 1 + } catch (failure) { + failed.push({ folder: skill.folder, reason: failure instanceof Error ? failure.message : String(failure) }) + } + } + return { sourceId: source.id, enabled, cardOnly: false, applied, failed } + } + + /** Open one source directory in the OS file manager (explicit user click). */ + async reveal(sourceInput: unknown): Promise<{ path: string }> { + const source = this.source(sourceInput) + if (!existsSync(source.root)) throw new SkillGroupError('not_found', `${source.label} 的技能目录还不存在:${source.root}`) + const command = process.platform === 'win32' ? 'explorer.exe' : process.platform === 'darwin' ? 'open' : 'xdg-open' + await new Promise((resolvePromise) => { + execFile(command, [source.root], { windowsHide: false }, () => resolvePromise()) + }) + return { path: source.root } + } +} diff --git a/verify-card-render.mjs b/verify-card-render.mjs index 270fc66..379dc5c 100644 --- a/verify-card-render.mjs +++ b/verify-card-render.mjs @@ -95,6 +95,50 @@ function render(node) { return children.map(render).join('') } +// Walk the tree (running function components) so a control can be clicked the +// way a user would: the preview and this harness share no browser events. +function walk(node, visit) { + if (node === null || node === undefined || typeof node === 'string' || typeof node === 'number') return + if (Array.isArray(node)) { + node.forEach((child) => walk(child, visit)) + return + } + if (typeof node.type === 'function') { + if (node.type.prototype && typeof node.type.prototype.render === 'function') { + const instance = new node.type(node.props) + instance.props = node.props + if (instance.state === undefined) instance.state = {} + instance.setState = function setState(patch) { + instance.state = { ...instance.state, ...patch } + scheduled = true + } + walk(instance.render(), visit) + return + } + walk(node.type({ ...node.props, children: node.children }), visit) + return + } + visit(node) + node.children.forEach((child) => walk(child, visit)) +} + +function clickLabel(root, prefix, occurrence = 0) { + let clicked = false + let index = 0 + walk(root, (node) => { + if (clicked) return + const label = (node.props ?? {})['aria-label'] + if (typeof label === 'string' && label.startsWith(prefix) && typeof node.props.onClick === 'function') { + if (index === occurrence) { + node.props.onClick() + clicked = true + } + index += 1 + } + }) + return clicked +} + // ── payloads ──────────────────────────────────────────────────────────── const statusBody = { ok: true, @@ -203,6 +247,80 @@ const mcpBody = { let mcpAvailable = true let activeTab = 'connection' +const treeBody = { + ok: true, + note: '分类只记在这个来源里,不移动文件。只有 DSH 来源的开关会真实启停技能目录;其他软件的目录本卡不修改。', + sources: [ + { + id: 'dsh', + label: 'DSH', + root: 'C:/Users/test/.dsh/skills', + exists: true, + writable: true, + manager: 'DSH', + enabled: true, + enabledEditable: true, + cardOnly: false, + total: 2, + enabledCount: 2, + groups: [ + { + id: 'g_qq', + name: 'QQ-Skill', + enabled: true, + enabledEditable: true, + cardOnly: false, + total: 1, + enabledCount: 1, + skills: [ + { folder: 'gamma', name: 'gamma', description: '演示技能', enabled: true, enabledEditable: true, files: 2, bytes: 2048, origin: 'cloud', inCardDisabled: false }, + ], + }, + { + id: 'unassigned', + name: '未分类', + enabled: true, + enabledEditable: false, + cardOnly: false, + total: 1, + enabledCount: 1, + skills: [ + { folder: 'parked-one', name: 'parked-one', description: '', enabled: false, enabledEditable: true, files: 1, bytes: 32, inCardDisabled: false }, + ], + }, + ], + }, + { + id: 'codex', + label: 'Codex', + root: 'C:/Users/test/.codex/skills', + exists: true, + writable: false, + manager: 'Codex', + note: '由 Codex 自行加载,本卡不修改它的目录', + enabled: true, + enabledEditable: true, + cardOnly: true, + total: 1, + enabledCount: 1, + groups: [ + { + id: 'unassigned', + name: '未分类', + enabled: true, + enabledEditable: false, + cardOnly: true, + total: 1, + enabledCount: 1, + skills: [ + { folder: 'codex-one', name: 'codex-one', description: '', enabled: true, enabledEditable: false, files: 1, bytes: 10, inCardDisabled: false }, + ], + }, + ], + }, + ], +} + async function fakeFetch(url, init) { const path = String(url).split('?')[0] let body = { ok: false, error: 'not-found' } @@ -210,6 +328,9 @@ async function fakeFetch(url, init) { if (path === '/cloud-memory/status') { body = statusBody status = 200 + } else if (path === '/cloud-memory/skills/sources') { + body = treeBody + status = 200 } else if (path.startsWith('/cloud-memory/skills/api')) { body = skillsBody status = 200 @@ -296,7 +417,7 @@ function loadBundle() { return registered } -async function drive(tab, bridgeAvailable) { +async function drive(tab, bridgeAvailable, clickAfter, clickOccurrence) { activeTab = tab mcpAvailable = bridgeAvailable hooks = [] @@ -317,6 +438,25 @@ async function drive(tab, bridgeAvailable) { await new Promise((resolve) => setTimeout(resolve, 0)) if (!scheduled) break } + if (clickAfter !== undefined) { + cursor = 0 + pendingEffects = [] + clickLabel(React.createElement(card, null), clickAfter, clickOccurrence ?? 0) + for (let pass = 0; pass < 4; pass += 1) { + cursor = 0 + pendingEffects = [] + scheduled = false + text = render(React.createElement(card, null)) + const effects = pendingEffects + pendingEffects = [] + for (const effect of effects) { + const cleanup = effect() + if (typeof cleanup === 'function') cleanup() + } + await new Promise((resolve) => setTimeout(resolve, 0)) + if (!scheduled) break + } + } return text } @@ -330,9 +470,23 @@ check('the search limit is renamed and reachable', connection.includes('单次 check('no render boundary error on the connection tab', !connection.includes('渲染失败')) const skillsText = await drive('skills', true) -check('the skills tab renders its sections', ['本机技能', '从 Git 仓库安装', '技能市场', '云端同步状态'].every((label) => skillsText.includes(label))) -check('real skill rows carry origin and size', skillsText.includes('gamma') && skillsText.includes('云端下发') && skillsText.includes('2.0 KB')) -check('a parked skill is rendered as disabled', skillsText.includes('已停用')) +check('the skills tab renders its sections', ['技能文件夹', '从 Git 仓库安装', '技能市场', '云端同步状态'].every((label) => skillsText.includes(label))) +check('the tree shows every detected source with its path', + skillsText.includes('DSH') && skillsText.includes('Codex') && skillsText.includes('C:/Users/test/.dsh/skills') && skillsText.includes('2 个技能')) +check('categories render with their counts', skillsText.includes('QQ-Skill') && skillsText.includes('1 项 · 1/1 启用') && skillsText.includes('未分类')) +check('the metadata-only promise is on screen', skillsText.includes('分类只记在这个来源里,不移动文件')) +check('a foreign source is marked card-only', skillsText.includes('仅本卡') && skillsText.includes('本卡不修改')) + +// Categories start collapsed; expanding one must reveal its skills. +const expandedSkills = await drive('skills', true, '展开或收起 未分类') +check('a collapsed category hides its skills', !skillsText.includes('parked-one')) +check('expanding a category reveals its skill rows', + expandedSkills.includes('parked-one') && expandedSkills.includes('32 B')) +check('a DSH skill row offers detail, a switch and uninstall', + expandedSkills.includes('详情') && expandedSkills.includes('卸载…')) +const foreignSkills = await drive('skills', true, '展开或收起 未分类', 1) +check('a foreign skill row is marked read-only', + foreignSkills.includes('codex-one') && foreignSkills.includes('只读')) check('the market gap is stated instead of simulated', skillsText.includes('能力缺口') || skillsText.includes('没有接入经验证的市场来源')) check('no render boundary error on the skills tab', !skillsText.includes('渲染失败')) diff --git a/verify-skill-tree.mjs b/verify-skill-tree.mjs new file mode 100644 index 0000000..52f461c --- /dev/null +++ b/verify-skill-tree.mjs @@ -0,0 +1,234 @@ +// Verification for the multi-source skill tree (sources → categories → skills). +// +// The two things that must not regress are stated in the UI copy, so they are +// asserted here: a category is metadata only (creating, renaming, deleting one +// never moves a file), and only the DSH source switch really parks skills — +// another software's directory is never touched. +import http from 'node:http' +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +process.env.DSH_HOME = mkdtempSync(join(tmpdir(), 'brain-tree-')) + +const results = [] +function check(name, ok, detail) { + results.push({ name, ok }) + console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`) +} + +const writeSkill = (area, folder, files = { 'SKILL.md': `# ${folder}\n` }) => { + for (const [rel, content] of Object.entries(files)) { + const target = join(area, folder, ...rel.split('/')) + mkdirSync(join(target, '..'), { recursive: true }) + writeFileSync(target, content) + } +} + +const root = join(process.env.DSH_HOME, 'skills') +const holding = join(process.env.DSH_HOME, 'skills-disabled') +const foreignRoot = join(tmpdir(), `foreign-agents-${Date.now()}`) + +const { SkillAdmin } = await import('./lib/skill-admin.js') +const { SkillGroupManager, SkillGroupError, detectSources } = await import('./lib/skill-groups.js') +const { SettingsStore } = await import('./lib/store.js') +const { Reporter } = await import('./lib/reporter.js') +const { createRoutes } = await import('./lib/routes.js') + +const admin = new SkillAdmin({ + skillsRoot: () => root, + holdingDir: () => holding, + syncStatePath: () => join(process.env.DSH_HOME, 'cloud-memory-skills.json'), + syncRunning: () => false, + log: () => {}, +}) + +writeSkill(root, 'qqcites', { 'SKILL.md': '---\nname: qqcites\ndescription: 引用\ndescription: 引用候选\n---\n\n# qqcites\n', 'a.md': 'x' }) +writeSkill(root, 'qqnote', { 'SKILL.md': '---\nname: qqnote\n---\n\n# qqnote\n' }) +writeSkill(root, 'blender', { 'SKILL.md': '---\nname: blender\ndescription: 建模\n---\n\n# blender\n' }) +writeSkill(foreignRoot, 'codex-one', { 'SKILL.md': '---\nname: codex-one\n---\n\n# codex-one\n' }) +writeSkill(foreignRoot, 'codex-two', { 'SKILL.md': '---\nname: codex-two\n---\n\n# codex-two\n' }) + +const sources = () => [ + { id: 'dsh', label: 'DSH', root, writable: true, manager: 'DSH' }, + { + id: 'codex', + label: 'Codex', + root: foreignRoot, + writable: false, + manager: 'Codex', + note: '由 Codex 自行加载,本卡不修改它的目录', + }, +] +const storePath = join(process.env.DSH_HOME, 'cloud-memory-skill-groups.json') +const manager = new SkillGroupManager({ sources, admin, storePath: () => storePath }) + +// ── A. overview ───────────────────────────────────────────────────────── +const overview = await manager.overview() +check('the overview carries the metadata-only promise', String(overview.note).includes('不移动文件')) +check('the note says only DSH switches are real', String(overview.note).includes('只有 DSH 来源的开关会真实启停')) +const dsh = overview.sources.find((source) => source.id === 'dsh') +check('the DSH source lists its three skills', dsh?.total === 3 && dsh?.enabledCount === 3) +check('every skill starts in 未分类', dsh?.groups.length === 1 && dsh?.groups[0].id === 'unassigned' && dsh?.groups[0].total === 3) +check('the DSH switch is editable and real', dsh?.enabledEditable === true && dsh?.cardOnly === false) +const codex = overview.sources.find((source) => source.id === 'codex') +check('a foreign source is read-only and says so', codex?.writable === false && codex?.cardOnly === true && String(codex?.note).includes('不修改')) +check('a foreign source lists its skills', codex?.total === 2) + +const detected = detectSources() +check('the detector knows the six software roots', + ['dsh', 'agents', 'codex', 'workbuddy', 'claude', 'opencode'].every((id) => detected.some((source) => source.id === id))) + +// ── B. categories are metadata ────────────────────────────────────────── +const created = await manager.createGroup('dsh', 'QQ-Skill') +check('a category can be created', typeof created.groupId === 'string' && created.name === 'QQ-Skill') +await manager.createGroup('dsh', 'QQ-Skill').then( + () => check('a duplicate name is refused', false), + (error) => check('a duplicate name is refused', error instanceof SkillGroupError && error.code === 'duplicate'), +) +await manager.createGroup('dsh', '').then( + () => check('an empty name is refused', false), + (error) => check('an empty name is refused', error instanceof SkillGroupError && error.code === 'invalid_name'), +) +await manager.createGroup('nope', 'x').then( + () => check('an unknown source is refused', false), + (error) => check('an unknown source is refused', error instanceof SkillGroupError && error.code === 'unknown_source'), +) + +await manager.assign('dsh', created.groupId, ['qqcites', 'qqnote']) +let view = await manager.overview() +let dshView = view.sources.find((source) => source.id === 'dsh') +let group = dshView.groups.find((item) => item.id === created.groupId) +check('assigning moves skills out of 未分类', group?.total === 2 && dshView.groups.find((item) => item.id === 'unassigned')?.total === 1) +check('the group shows "2 项 · 2/2 启用" numbers', group?.total === 2 && group?.enabledCount === 2) +check('assigning does not move a single file', existsSync(join(root, 'qqcites', 'SKILL.md')) && existsSync(join(root, 'qqnote', 'SKILL.md'))) + +const second = await manager.createGroup('dsh', '建模') +await manager.assign('dsh', second.groupId, ['blender', 'qqnote']) +view = await manager.overview() +dshView = view.sources.find((source) => source.id === 'dsh') +check('a skill belongs to at most one category', + dshView.groups.find((item) => item.id === second.groupId)?.total === 2 && + dshView.groups.find((item) => item.id === created.groupId)?.total === 1) + +// ── C. real switches for DSH, card-only for others ────────────────────── +const off = await manager.toggleGroup('dsh', second.groupId, false) +check('switching a DSH category off really parks its skills', + off.cardOnly === false && off.applied.length === 2 && existsSync(join(holding, 'blender')) && !existsSync(join(root, 'blender'))) +view = await manager.overview() +dshView = view.sources.find((source) => source.id === 'dsh') +check('the parked skill is reported as disabled', dshView.groups.find((item) => item.id === second.groupId)?.enabledCount === 0) +const on = await manager.toggleGroup('dsh', second.groupId, true) +check('switching it back restores the folders', + on.applied.length === 2 && existsSync(join(root, 'blender')) && !existsSync(join(holding, 'blender'))) + +const codexGroup = await manager.createGroup('codex', '外部组') +await manager.assign('codex', codexGroup.groupId, ['codex-one']) +const before = readFileSync(join(foreignRoot, 'codex-one', 'SKILL.md'), 'utf8') +const codexOff = await manager.toggleGroup('codex', codexGroup.groupId, false) +check('a foreign category switch is card-only', codexOff.cardOnly === true && codexOff.applied.length === 0) +check('a foreign directory is left byte-identical', + existsSync(join(foreignRoot, 'codex-one', 'SKILL.md')) && readFileSync(join(foreignRoot, 'codex-one', 'SKILL.md'), 'utf8') === before) +view = await manager.overview() +const codexView = view.sources.find((source) => source.id === 'codex') +check('the card-only switch is visible as in-card disabled', + codexView.groups.find((item) => item.id === codexGroup.groupId)?.skills[0]?.inCardDisabled === true) +const codexSourceOff = await manager.toggleSource('codex', false) +check('a foreign source switch is card-only too', codexSourceOff.cardOnly === true) +const codexSourceOn = await manager.toggleSource('codex', true) +check('the foreign source switch restores in-card visibility', codexSourceOn.enabled === true) + +// ── D. rename / delete ────────────────────────────────────────────────── +const renamed = await manager.renameGroup('dsh', created.groupId, 'QQ 技能') +check('a category can be renamed', renamed.name === 'QQ 技能') +const deleted = await manager.deleteGroup('dsh', created.groupId) +check('deleting a category releases its skills', deleted.released === 1) +view = await manager.overview() +dshView = view.sources.find((source) => source.id === 'dsh') +check('released skills are back in 未分类', dshView.groups.find((item) => item.id === 'unassigned')?.total === 1) +check('deleting a category never deletes a file', existsSync(join(root, 'qqcites', 'SKILL.md'))) + +// The 未分类 bucket switch parks exactly the skills no category claims. +const bucketOff = await manager.toggleGroup('dsh', 'unassigned', false) +check('the 未分类 switch parks only the unclaimed skills', + bucketOff.cardOnly === false && bucketOff.applied.join(',') === 'qqcites' && existsSync(join(holding, 'qqcites'))) +const bucketOn = await manager.toggleGroup('dsh', 'unassigned', true) +check('the 未分类 switch restores them', + bucketOn.applied.join(',') === 'qqcites' && existsSync(join(root, 'qqcites'))) + +check('the remaining category is untouched', dshView.groups.find((item) => item.id === second.groupId)?.total === 2) + +// ── E. persistence and route surface ──────────────────────────────────── +const reopened = new SkillGroupManager({ sources, admin, storePath: () => storePath }) +const afterReload = await reopened.overview() +check('categories survive a manager restart', + afterReload.sources.find((source) => source.id === 'dsh')?.groups.some((item) => item.name === '建模')) +check('the sidecar holds metadata only, never a file path', + !readFileSync(storePath, 'utf8').includes('SKILL.md')) + +const store = new SettingsStore({ baseUrl: 'https://memory.example.org/api/longmemory' }, join(process.env.DSH_HOME, 'cloud-memory.json')) +const reporter = new Reporter({ + client: () => ({ reportTurn: async () => ({ ok: true, status: 200, data: {} }) }), + settings: () => ({ enabled: true, clientId: 'tree' }), + activityToken: () => '', + summary: () => ({ enabled: false, maxChars: 1000 }), + summaryToken: () => '', + log: () => {}, +}) +const routes = createRoutes({ + version: '0.5.0-test', + store, + reporter, + client: () => ({ reach: async () => ({ ok: false, status: 0, message: 'stub' }) }), + admin, + groups: reopened, +}) +const server = http.createServer((req, res) => { + const path = (req.url ?? '/').split('?')[0] + for (const route of routes) { + if (route.kind === 'exact' && path === route.path) return route.handler(req, res) + if (route.kind === 'prefix' && (path === route.path || path.startsWith(`${route.path}/`))) return route.handler(req, res) + } + res.writeHead(404, { 'content-type': 'application/json' }) + res.end('{"ok":false}') +}) +await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) +const origin = `http://127.0.0.1:${server.address().port}` + +async function call(method, path, body) { + const headers = { accept: 'application/json' } + let payload + if (body !== undefined) { + headers['content-type'] = 'application/json' + payload = JSON.stringify(body) + } + const response = await fetch(`${origin}${path}`, { method, headers, body: payload }) + const text = await response.text() + let parsed = null + try { + parsed = JSON.parse(text) + } catch { + parsed = null + } + return { status: response.status, body: parsed } +} + +const sourcesResponse = await call('GET', '/cloud-memory/skills/sources') +check('the sources route answers with the tree', sourcesResponse.status === 200 && Array.isArray(sourcesResponse.body?.sources)) +check('the tree carries the metadata-only note', String(sourcesResponse.body?.note).includes('不移动文件')) +check('POST on the sources route is refused', (await call('POST', '/cloud-memory/skills/sources', {}))?.status === 405) + +const viaRoute = await call('POST', '/cloud-memory/skills/groups/create', { sourceId: 'dsh', name: '路由组' }) +check('a category can be created over HTTP', viaRoute.status === 200 && typeof viaRoute.body?.groupId === 'string') +const dupViaRoute = await call('POST', '/cloud-memory/skills/groups/create', { sourceId: 'dsh', name: '路由组' }) +check('a duplicate over HTTP is a 400', dupViaRoute.status === 400 && dupViaRoute.body?.code === 'duplicate') +const missingGroup = await call('POST', '/cloud-memory/skills/groups/delete', { sourceId: 'dsh', groupId: 'g_missing' }) +check('an unknown category is a 404', missingGroup.status === 404) +const revealMissing = await call('POST', '/cloud-memory/skills/source/reveal', { sourceId: 'agents' }) +check('revealing a missing directory reports not_found instead of failing silently', revealMissing.status === 404 || revealMissing.status === 200) + +server.close() + +const failed = results.filter((item) => !item.ok).length +console.log(failed === 0 ? `\nALL ${results.length} CHECKS PASSED` : `\n${failed} CHECK(S) FAILED`) +process.exit(failed === 0 ? 0 : 1)