Compare commits

...

7 Commits
v0.9.7 ... main

Author SHA1 Message Date
newbie 8e5145349d Revert "docs(readme): 重写为清爽入口页,详情迁移到 docs/(0.9.10)"
This reverts commit 6d868abb28.
2026-11-19 10:06:25 +08:00
newbie 6d868abb28 docs(readme): 重写为清爽入口页,详情迁移到 docs/(0.9.10) 2026-11-19 09:52:17 +08:00
QQ 7d053b2fe9 Merge pull request 'feat(skills): 同步冲突支持批量处理(0.9.10)' (#3) from feat/sync-batch-resolve into main 2026-11-14 16:05:20 +08:00
newbie d2bd955aa9 feat(skills): batch resolve all sync conflicts (0.9.10)
Adds POST /dsh-brain/sync/resolve-all {action: keep_local|take_cloud} and 全部保留本地 / 全部采用云端 buttons with an inline confirmation step. Partial failures are reported per item (resolved / failed lists) instead of aborting the batch; per-item resolution stays available.
2026-11-14 16:05:09 +08:00
QQ 4123d9de9e Merge pull request 'feat(skills): 同步冲突按内容与时间自动取较新(0.9.9)' (#2) from feat/skill-sync-auto-newer into main 2026-11-14 14:24:57 +08:00
newbie dbf39339c2 feat(skills): auto-resolve sync conflicts by content and newer timestamp (0.9.9)
Same-name skills no longer always stop for a human: identical bytes adopt the delivery marker in place, differing bytes compare local file mtime with the center updated_at and the newer side wins (cloud overwrite backs the local folder up first). Equal or missing timestamps, unsupported upload layouts and script-review flags still surface as per-item conflicts, so there is no batch action.
2026-11-14 14:24:36 +08:00
newbie 881f822c69 refactor(mcp): skeleton connection rows with details toggle, collapse the two heavy sections (0.9.8) 2026-11-13 11:50:17 +08:00
18 changed files with 923 additions and 149 deletions

View File

@ -125,17 +125,20 @@ v1 范围:支持 发现 / 状态 / 搜索 / 浏览 / 写入 / 按 id 读取;
端;之后的修改以新修订发布,带 `expected_revision` 守卫,云端被 端;之后的修改以新修订发布,带 `expected_revision` 守卫,云端被
别人先改过就报冲突、不强行覆盖。 别人先改过就报冲突、不强行覆盖。
防事故的规矩:云端交付的技能从不回传,本地改动它只报 防事故的规矩:先比内容,本地与云端逐字节一致时直接补交付记录,不传
`locally_modified` 冲突、原样不动;本地删除不删云端,且同版本不会 不覆盖;内容不同时按时间自动取较新的一边——云端 `updated_at` 更新就
被重新拉回(云端出了新版才会再下来);同名技能两边都有时互不抢占, 先备份本地再覆盖,本地文件 mtime 更新就发布新修订;只有时间相同或缺
报 `name_collision`。云端只接受固定布局(根目录只有 `SKILL.md`, 失时才报冲突(`locally_modified` / `name_collision` / `cloud_newer`),
等面板里逐项确认。本地删除不删云端,且同版本不会被重新拉回(云端出
了新版才会再下来)。面板里可逐项处理,也可用「全部保留本地 / 全部采用
云端」批量处理(有二次确认,失败项会逐条汇总)。云端只接受固定布局(根目录只有 `SKILL.md`,
其余文件进 `references/`、`scripts/`、`assets/`,扩展名有白名单, 其余文件进 `references/`、`scripts/`、`assets/`,扩展名有白名单,
单文件 ≤512 KiB、整包 ≤2 MiB、≤100 个文件),不符合的本地技能报 单文件 ≤512 KiB、整包 ≤2 MiB、≤100 个文件),不符合的本地技能报
`unsupported_layout`,不会为了迁就而裁剪文件。 `unsupported_layout`,不会为了迁就而裁剪文件。
验证:`node verify-skills-sync.mjs`(对本地 stub 技能中心跑通 验证:`node verify-skills-sync.mjs`(对本地 stub 技能中心跑通
下行安装、上行发布与修订、改云端技能报冲突、同名冲突、脚本待审、 下行安装、上行发布与修订、按时间自动上行/下行、内容一致自动认领、
布局拒绝、删除不传播全流程)。 同名同时间保留冲突、脚本待审、布局拒绝、删除不传播全流程)。
## 技能管理(内置) ## 技能管理(内置)
@ -219,7 +222,7 @@ pnpm publish --access public --no-git-checks
- 卸载同样是两步:`uninstall/plan` 给出真实目录、文件数与不可恢复提示并签发一次性 token,`remove` 必须带 `confirmed: true` 与匹配 token。 - 卸载同样是两步:`uninstall/plan` 给出真实目录、文件数与不可恢复提示并签发一次性 token,`remove` 必须带 `confirmed: true` 与匹配 token。
- **技能市场(P3)**:接入经验证来源 `anthropics/skills` 的 `.claude-plugin/marketplace.json`;搜索→详情→`market/plan`(固定提交)→勾选安装。客户端只传 provider/id,从不传 URL。 - **技能市场(P3)**:接入经验证来源 `anthropics/skills` 的 `.claude-plugin/marketplace.json`;搜索→详情→`market/plan`(固定提交)→勾选安装。客户端只传 provider/id,从不传 URL。
- **更新/回退(P3)**:安装写 `.skill-source.json`;`skills/update/check|apply` 与 `skills/rollback` 更新前整目录备份,过期提交拒绝。 - **更新/回退(P3)**:安装写 `.skill-source.json`;`skills/update/check|apply` 与 `skills/rollback` 更新前整目录备份,过期提交拒绝。
- **同步冲突(P3)**:`sync/status|run|resolve` 提供两侧信息,逐项「保留本地 / 采用云端 / 手动合并」。 - **同步冲突(P3)**:`sync/status|run|resolve|resolve-all` 提供两侧信息;面板支持逐项「保留本地 / 采用云端 / 手动合并」,也支持「全部保留本地 / 全部采用云端」批量处理(二次确认,逐项失败会汇总提示)。
- **MCP 管理(P4)**:读取宿主 `dsh-mcp-connector` 的同源公开接口 `/mcp-connector/api`;覆盖连接、健康检查、工具、启停、重连、两段式移除、目录市场连接、自定义 HTTP/stdio、JSON 导入、配置编辑、作用域与治理策略。 - **MCP 管理(P4)**:读取宿主 `dsh-mcp-connector` 的同源公开接口 `/mcp-connector/api`;覆盖连接、健康检查、工具、启停、重连、两段式移除、目录市场连接、自定义 HTTP/stdio、JSON 导入、配置编辑、作用域与治理策略。
接口清单见 `docs/management-surface.md`;验收脚本见 `verify-*.mjs`(含 `verify-market` / `verify-skill-update` / `verify-sync-resolve` / `verify-mcp-bridge` / `verify-upgrade` / `verify-concurrency` / `verify-theme`)。 接口清单见 `docs/management-surface.md`;验收脚本见 `verify-*.mjs`(含 `verify-market` / `verify-skill-update` / `verify-sync-resolve` / `verify-mcp-bridge` / `verify-upgrade` / `verify-concurrency` / `verify-theme`)。

View File

@ -915,7 +915,7 @@ window.__ModuleLoader__.load({
// ---- P3: interactive sync conflict resolution ------------------------- // ---- P3: interactive sync conflict resolution -------------------------
function SyncResolveSection(props) { function SyncResolveSection(props) {
var tuple = React.useState({ status: 'idle', data: null, busy: '', error: null, notice: null }) var tuple = React.useState({ status: 'idle', data: null, busy: '', error: null, notice: null, pendingAll: null })
var state = tuple[0] var state = tuple[0]
var setState = tuple[1] var setState = tuple[1]
function patch(next) { setState(function (prev) { return Object.assign({}, prev, next) }) } function patch(next) { setState(function (prev) { return Object.assign({}, prev, next) }) }
@ -944,6 +944,19 @@ window.__ModuleLoader__.load({
else patch({ busy: '', notice: { tone: 'bad', text: bodyError(res, '同步失败') } }) else patch({ busy: '', notice: { tone: 'bad', text: bodyError(res, '同步失败') } })
}, function (error) { patch({ busy: '', notice: { tone: 'bad', text: messageOf(error) } }) }) }, function (error) { patch({ busy: '', notice: { tone: 'bad', text: messageOf(error) } }) })
} }
function resolveAll(action) {
if (conflicts.length === 0) { patch({ pendingAll: null }); return }
patch({ busy: 'all:' + action, notice: null })
postJson(API.sync + '/resolve-all', { action: action }).then(function (res) {
if (res.body !== null && res.body !== undefined && res.body.ok === true) {
var resolved = Array.isArray(res.body.resolved) ? res.body.resolved : []
var failed = Array.isArray(res.body.failed) ? res.body.failed : []
var text = '批量处理完成:成功 ' + resolved.length + ' 项' + (failed.length === 0 ? '。' : ',失败 ' + failed.length + ' 项(' + failed.map(function (item) { return item.name + ':' + item.error }).join('、') + ')。')
patch({ busy: '', pendingAll: null, data: { stats: res.body.stats, conflicts: res.body.conflicts || [] }, notice: { tone: failed.length === 0 ? 'ok' : 'warn', text: text } })
if (typeof props.onResolved === 'function') props.onResolved()
} else patch({ busy: '', notice: { tone: 'bad', text: bodyError(res, '批量处理冲突失败') } })
}, function (error) { patch({ busy: '', notice: { tone: 'bad', text: messageOf(error) } }) })
}
var data = state.data var data = state.data
var stats = data === null || data === undefined ? null : data.stats var stats = data === null || data === undefined ? null : data.stats
var conflicts = data === null || data === undefined || !Array.isArray(data.conflicts) ? [] : data.conflicts var conflicts = data === null || data === undefined || !Array.isArray(data.conflicts) ? [] : data.conflicts
@ -974,11 +987,31 @@ window.__ModuleLoader__.load({
), ),
) )
}) })
return h(Section, { title: '云端同步与冲突', hint: '同步冲突不会被静默覆盖;逐项选择保留本地(上传为新版本)、采用云端(先备份本地)或手动合并。', aside: h(Btn, { label: state.busy === 'run' ? '同步中…' : '立即同步', variant: 'small', disabled: state.busy !== '', onClick: runNow }) }, var batchRow = null
if (conflicts.length > 0) {
batchRow = h('div', { style: styles.actions },
h(Btn, { label: '全部保留本地', variant: 'small', disabled: state.busy !== '' || !conflicts.some(function (item) { return item.canKeepLocal === true }), onClick: function () { patch({ pendingAll: 'keep_local', notice: null }) } }),
h(Btn, { label: '全部采用云端', variant: 'small', disabled: state.busy !== '' || !conflicts.some(function (item) { return item.canTakeCloud === true }), onClick: function () { patch({ pendingAll: 'take_cloud', notice: null }) } }),
)
}
var confirmAllRow = null
if (state.pendingAll !== null && conflicts.length > 0) {
var pendingText = state.pendingAll === 'keep_local' ? '把全部本地版本上传为新版本' : '用云端版本覆盖全部本地(覆盖前自动备份)'
confirmAllRow = h('div', { style: styles.nested },
h('p', { style: styles.hint }, '确认' + pendingText + '?共 ' + conflicts.length + ' 项。'),
h('div', { style: styles.actions },
h(Btn, { variant: 'primary', label: state.busy === 'all:keep_local' || state.busy === 'all:take_cloud' ? '处理中…' : '确认批量', disabled: state.busy !== '', onClick: function () { resolveAll(state.pendingAll) } }),
h(Btn, { variant: 'small', label: '取消', disabled: state.busy !== '', onClick: function () { patch({ pendingAll: null }) } }),
),
)
}
return h(Section, { title: '云端同步与冲突', hint: '同步先比内容与更新时间:一致直接认领,不同则自动采用较新的一边(覆盖云端前先备份本地);只有时间相同/缺失或目录结构不支持时才逐项询问,也可用批量按钮一次处理。', aside: h(Btn, { label: state.busy === 'run' ? '同步中…' : '立即同步', variant: 'small', disabled: state.busy !== '', onClick: runNow }) },
h('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px' } }, h('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px' } },
state.error === null ? null : h(Banner, { tone: 'bad' }, state.error), state.error === null ? null : h(Banner, { tone: 'bad' }, state.error),
state.notice === null ? null : h(Banner, { tone: state.notice.tone }, state.notice.text), state.notice === null ? null : h(Banner, { tone: state.notice.tone }, state.notice.text),
statPills, statPills,
batchRow,
confirmAllRow,
conflicts.length === 0 ? h('p', { style: styles.hint }, '当前没有待处理冲突。') : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } }, conflictRows), conflicts.length === 0 ? h('p', { style: styles.hint }, '当前没有待处理冲突。') : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } }, conflictRows),
), ),
) )
@ -991,6 +1024,7 @@ window.__ModuleLoader__.load({
// plugin market instead of a broken embedded panel. // plugin market instead of a broken embedded panel.
function McpCustomSection(props) { function McpCustomSection(props) {
var open = React.useState(false)
var tuple = React.useState({ transport: 'streamable-http', name: '', serverName: '', url: '', command: '', args: '', cwd: '', authMode: 'none', bearerToken: '', apiKeyHeader: 'X-Api-Key', apiKeyValue: '', importJson: '', busy: '', notice: null }) var tuple = React.useState({ transport: 'streamable-http', name: '', serverName: '', url: '', command: '', args: '', cwd: '', authMode: 'none', bearerToken: '', apiKeyHeader: 'X-Api-Key', apiKeyValue: '', importJson: '', busy: '', notice: null })
var s = tuple[0] var s = tuple[0]
var set = tuple[1] var set = tuple[1]
@ -1025,8 +1059,17 @@ window.__ModuleLoader__.load({
if (ok && typeof props.onChanged === 'function') props.onChanged() if (ok && typeof props.onChanged === 'function') props.onChanged()
}) })
} }
return h(Section, { title: '新增 / 导入连接', hint: 'HTTP 与 stdio 都由宿主校验并保存凭据;本卡不回显已有密钥。stdio 的启动命令由你显式填写,云端不会执行任何本机命令。' }, return h(Section, {
h('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px' } }, title: '新增 / 导入连接',
hint: 'HTTP 与 stdio 都由宿主校验并保存凭据;本卡不回显已有密钥。stdio 的启动命令由你显式填写,云端不会执行任何本机命令。',
aside: h(Btn, {
label: open[0] ? '收起' : '展开',
ariaLabel: '展开新增连接',
variant: 'small',
onClick: function () { open[1](!open[0]) },
}),
},
open[0] ? h('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px' } },
h('div', { style: styles.grid }, h('div', { style: styles.grid },
h(Field, { label: '名称', value: s.name, onChange: function (v) { patch({ name: v }) } }), h(Field, { label: '名称', value: s.name, onChange: function (v) { patch({ name: v }) } }),
h(Field, { label: 'Server 名(可选)', value: s.serverName, onChange: function (v) { patch({ serverName: v }) } }), h(Field, { label: 'Server 名(可选)', value: s.serverName, onChange: function (v) { patch({ serverName: v }) } }),
@ -1065,12 +1108,13 @@ window.__ModuleLoader__.load({
h('textarea', { value: s.importJson, rows: 5, style: Object.assign({}, styles.input, { fontFamily: 'monospace', resize: 'vertical' }), placeholder: '{"mcpServers":{"name":{"url":"…"}}}', onChange: function (e) { patch({ importJson: e.target.value }) } }), h('textarea', { value: s.importJson, rows: 5, style: Object.assign({}, styles.input, { fontFamily: 'monospace', resize: 'vertical' }), placeholder: '{"mcpServers":{"name":{"url":"…"}}}', onChange: function (e) { patch({ importJson: e.target.value }) } }),
h('div', { style: styles.actions }, h(Btn, { label: s.busy === 'import' ? '导入中…' : '导入 JSON', disabled: s.busy !== '', onClick: importJson })), h('div', { style: styles.actions }, h(Btn, { label: s.busy === 'import' ? '导入中…' : '导入 JSON', disabled: s.busy !== '', onClick: importJson })),
s.notice === null ? null : h(Banner, { tone: s.notice.tone }, s.notice.text), s.notice === null ? null : h(Banner, { tone: s.notice.tone }, s.notice.text),
), ) : null,
) )
} }
function McpConfigSection(props) { function McpConfigSection(props) {
var items = Array.isArray(props.items) ? props.items : [] var items = Array.isArray(props.items) ? props.items : []
var open = React.useState(false)
var tuple = React.useState({ key: '', json: '', busy: '', notice: null, scopePreview: null, targetScope: 'global', workspaceId: '', gov: null, policyPreview: null }) var tuple = React.useState({ key: '', json: '', busy: '', notice: null, scopePreview: null, targetScope: 'global', workspaceId: '', gov: null, policyPreview: null })
var s = tuple[0] var s = tuple[0]
var set = tuple[1] var set = tuple[1]
@ -1139,8 +1183,17 @@ window.__ModuleLoader__.load({
}) })
} }
var gov = s.gov var gov = s.gov
return h(Section, { title: '连接配置、范围与治理', hint: '配置编辑使用宿主的保留标记合并,空输入不会清空已有密钥;作用域与策略都带 revision 预览后再提交。' }, return h(Section, {
h('div', { style: { display: 'flex', flexDirection: 'column', gap: '12px' } }, title: '连接配置、范围与治理',
hint: '配置编辑使用宿主的保留标记合并,空输入不会清空已有密钥;作用域与策略都带 revision 预览后再提交。',
aside: h(Btn, {
label: open[0] ? '收起' : '展开',
ariaLabel: '展开连接配置',
variant: 'small',
onClick: function () { open[1](!open[0]) },
}),
},
open[0] ? h('div', { style: { display: 'flex', flexDirection: 'column', gap: '12px' } },
itemSelect(items, s.key, choose), itemSelect(items, s.key, choose),
s.key === '' ? h('p', { style: styles.hint }, '选择一条连接后可编辑配置、调整范围或设置治理策略。') : h('div', { style: styles.nested }, s.key === '' ? h('p', { style: styles.hint }, '选择一条连接后可编辑配置、调整范围或设置治理策略。') : h('div', { style: styles.nested },
h('p', { style: styles.hint }, '可编辑配置(保留标记 <KEEP_EXISTING> 表示保留原密钥):'), h('p', { style: styles.hint }, '可编辑配置(保留标记 <KEEP_EXISTING> 表示保留原密钥):'),
@ -1176,7 +1229,7 @@ window.__ModuleLoader__.load({
), ),
), ),
s.notice === null ? null : h(Banner, { tone: s.notice.tone }, s.notice.text), s.notice === null ? null : h(Banner, { tone: s.notice.tone }, s.notice.text),
), ) : null,
) )
} }
@ -1536,7 +1589,7 @@ window.__ModuleLoader__.load({
var skills = skillsState[0] var skills = skillsState[0]
var setSkills = skillsState[1] var setSkills = skillsState[1]
var mcpState = React.useState({ status: 'idle', items: [], error: null, tools: {}, busy: '', confirm: null, search: '', filter: 'all', selection: [], bulk: null, confirmBulk: false }) var mcpState = React.useState({ status: 'idle', items: [], error: null, tools: {}, busy: '', confirm: null, search: '', filter: 'all', selection: [], bulk: null, confirmBulk: false, details: {} })
var mcp = mcpState[0] var mcp = mcpState[0]
var setMcp = mcpState[1] var setMcp = mcpState[1]
@ -3378,8 +3431,11 @@ window.__ModuleLoader__.load({
mcpBulk === null ? null : h('p', { style: styles.hint }, String(mcpBulk.label) + ' 进行中:' + String(mcpBulk.done) + ' / ' + String(mcpBulk.total)), mcpBulk === null ? null : h('p', { style: styles.hint }, String(mcpBulk.label) + ' 进行中:' + String(mcpBulk.done) + ' / ' + String(mcpBulk.total)),
visibleItems.length === 0 ? h('p', { style: styles.hint }, '没有匹配「' + mcpSearch + '」的连接。换个关键词或切回「全部」筛选。') : null, visibleItems.length === 0 ? h('p', { style: styles.hint }, '没有匹配「' + mcpSearch + '」的连接。换个关键词或切回「全部」筛选。') : null,
visibleItems.map(function (item) { visibleItems.map(function (item) {
var state = String(item.connectionState === undefined ? 'unknown' : item.connectionState) var state = stateOf(item)
var tools = mcp.tools[item.key] var tools = mcp.tools[item.key]
var details = mcp.details === null || mcp.details === undefined ? {} : mcp.details
var open = details[item.key] === true
var label = String(item.name === undefined ? item.key : item.name)
return h( return h(
'div', 'div',
{ key: String(item.key), style: styles.row }, { key: String(item.key), style: styles.row },
@ -3388,101 +3444,117 @@ window.__ModuleLoader__.load({
{ style: styles.rowHead }, { style: styles.rowHead },
h( h(
'label', 'label',
{ style: { display: 'inline-flex', alignItems: 'center', gap: '8px', minWidth: 0 } }, { style: { display: 'inline-flex', alignItems: 'center', gap: '8px', minWidth: 0, flex: '1 1 auto' } },
h('input', { h('input', {
type: 'checkbox', type: 'checkbox',
checked: mcpChosen.indexOf(item.key) >= 0, checked: mcpChosen.indexOf(item.key) >= 0,
'aria-label': '选择连接 ' + String(item.name === undefined ? item.key : item.name), 'aria-label': '选择连接 ' + label,
onChange: function (event) { onChange: function (event) {
selectMcpMany([item], event.target.checked === true) selectMcpMany([item], event.target.checked === true)
}, },
}), }),
h('span', { style: styles.rowTitle }, String(item.name === undefined ? item.key : item.name)), h('span', { style: styles.rowTitle }, label),
),
h(
'div',
{ style: styles.pills },
h(Pill, { label: '状态', value: MCP_STATE_LABELS[state] === undefined ? state : MCP_STATE_LABELS[state], tone: state === 'connected' ? 'ok' : state === 'disabled' ? 'muted' : 'warn' }), h(Pill, { label: '状态', value: MCP_STATE_LABELS[state] === undefined ? state : MCP_STATE_LABELS[state], tone: state === 'connected' ? 'ok' : state === 'disabled' ? 'muted' : 'warn' }),
h(Pill, { label: '传输', value: String(item.transport === undefined ? '—' : item.transport), tone: 'muted' }), h(Pill, { label: '传输', value: String(item.transport === undefined ? '—' : item.transport), tone: 'muted' }),
h(Pill, { label: '鉴权', value: String(item.authMode === undefined ? 'none' : item.authMode), tone: 'muted' }),
h(Pill, { label: '注入', value: String(item.injectionLabel === undefined ? '—' : item.injectionLabel), tone: 'muted' }),
), ),
h(Btn, {
label: open ? '收起' : '详情',
ariaLabel: (open ? '收起详情 ' : '详情 ') + label,
variant: 'small',
onClick: function () {
patchMcp({ details: Object.assign({}, details, { [String(item.key)]: !open }) })
},
}),
), ),
h( open
'p', ? h(
{ style: styles.hint },
'范围:' + (item.scope === undefined || item.scope === null ? '未知' : String(item.scope.visibility === undefined ? JSON.stringify(item.scope) : item.scope.visibility)) + ' · 健康检查:' + formatIso(item.healthCheckedAt) + (item.lastError === null || item.lastError === undefined ? '' : ' · 最近错误:' + String(item.lastError)),
),
h(
'div',
{ style: styles.actions },
h(Btn, {
label: '健康检查',
variant: 'small',
disabled: mcp.busy !== '',
onClick: function () {
mcpAction('健康检查 ' + String(item.name), 'healthCheck', { connectorId: item.connectorId }).then(function () {
probeMcp()
})
},
}),
h(Btn, {
label: '工具列表',
variant: 'small',
disabled: mcp.busy !== '',
onClick: function () {
loadTools(item)
},
}),
h(Btn, {
label: item.enabled === false ? '启用' : '停用',
variant: 'small',
disabled: mcp.busy !== '',
onClick: function () {
mcpAction(item.enabled === false ? '启用连接' : '停用连接', 'setEnabled', { key: item.key, enabled: item.enabled === false }).then(function () {
probeMcp()
})
},
}),
h(Btn, {
label: '重连',
variant: 'small',
disabled: mcp.busy !== '',
onClick: function () {
mcpAction('重连', 'reconnect', { key: item.key }).then(function () {
probeMcp()
})
},
}),
mcp.confirm === item.key
? h(Btn, {
label: '确认移除',
variant: 'danger',
disabled: mcp.busy !== '',
onClick: function () {
mcpAction('移除连接', 'disconnect', { key: item.key }).then(function () {
patchMcp({ confirm: null })
probeMcp()
})
},
})
: h(Btn, {
label: '移除连接…',
variant: 'small',
disabled: mcp.busy !== '',
onClick: function () {
patchMcp({ confirm: item.key })
setNotice({ tone: 'warn', text: '再次点击「确认移除」才会断开该连接定义。' })
},
}),
),
tools === undefined
? null
: h(
'div', 'div',
{ style: styles.nested }, { style: { display: 'flex', flexDirection: 'column', gap: '6px' } },
h('p', { style: styles.hint }, '工具缓存(' + formatTime(tools.at) + '):' + (tools.items.length === 0 ? '空' : tools.items.map(function (tool) { return String(tool.name === undefined ? tool : tool.name) }).join('、'))), h(
), 'div',
{ style: styles.pills },
h(Pill, { label: '鉴权', value: String(item.authMode === undefined ? 'none' : item.authMode), tone: 'muted' }),
h(Pill, { label: '注入', value: String(item.injectionLabel === undefined ? '—' : item.injectionLabel), tone: 'muted' }),
h(Pill, { label: '范围', value: item.scope === undefined || item.scope === null ? '未知' : String(item.scope.visibility === undefined ? JSON.stringify(item.scope) : item.scope.visibility), tone: 'muted' }),
h(Pill, { label: '健康检查', value: formatIso(item.healthCheckedAt), tone: 'muted' }),
),
item.lastError === null || item.lastError === undefined
? null
: h('p', { style: styles.hint }, '最近错误:' + String(item.lastError)),
h(
'div',
{ style: styles.actions },
h(Btn, {
label: '健康检查',
ariaLabel: '健康检查 ' + label,
variant: 'small',
disabled: mcp.busy !== '',
onClick: function () {
mcpAction('健康检查 ' + label, 'healthCheck', { connectorId: item.connectorId }).then(function () {
probeMcp()
})
},
}),
h(Btn, {
label: '工具列表',
ariaLabel: '工具列表 ' + label,
variant: 'small',
disabled: mcp.busy !== '',
onClick: function () {
loadTools(item)
},
}),
h(Btn, {
label: item.enabled === false ? '启用' : '停用',
ariaLabel: '启停 ' + label,
variant: 'small',
disabled: mcp.busy !== '',
onClick: function () {
mcpAction(item.enabled === false ? '启用连接' : '停用连接', 'setEnabled', { key: item.key, enabled: item.enabled === false }).then(function () {
probeMcp()
})
},
}),
h(Btn, {
label: '重连',
ariaLabel: '重连 ' + label,
variant: 'small',
disabled: mcp.busy !== '',
onClick: function () {
mcpAction('重连', 'reconnect', { key: item.key }).then(function () {
probeMcp()
})
},
}),
mcp.confirm === item.key
? h(Btn, {
label: '确认移除',
ariaLabel: '确认移除 ' + label,
variant: 'danger',
disabled: mcp.busy !== '',
onClick: function () {
mcpAction('移除连接', 'disconnect', { key: item.key }).then(function () {
patchMcp({ confirm: null })
probeMcp()
})
},
})
: h(Btn, {
label: '移除连接…',
ariaLabel: '移除连接 ' + label,
variant: 'small',
disabled: mcp.busy !== '',
onClick: function () {
patchMcp({ confirm: item.key })
setNotice({ tone: 'warn', text: '再次点击「确认移除」才会断开该连接定义。' })
},
}),
),
tools === undefined
? null
: h('p', { style: styles.hint }, '工具缓存(' + formatTime(tools.at) + '):' + (tools.items.length === 0 ? '空' : tools.items.map(function (tool) { return String(tool.name === undefined ? tool : tool.name) }).join('、'))),
)
: null,
) )
}), }),
h('p', { style: styles.hint }, '工具可见不等于业务可调用:连接状态与工具缓存分开显示。'), h('p', { style: styles.hint }, '工具可见不等于业务可调用:连接状态与工具缓存分开显示。'),

View File

@ -165,23 +165,24 @@ POST /mcp-connector/api { "method": "status" | "healthCheck" | "toolsList" | "
### 6.3 同步冲突交互 ### 6.3 同步冲突交互
`SkillSync` 仍然只按原策略暂停冲突项,但会暴露两侧信息并允许人工处置: `SkillSync` 先自动处置:内容一致直接认领,内容不同按「本地文件 mtime vs 云端 `updated_at`」自动采用较新的一边(下行覆盖前备份到 `$DSH_HOME/.dsh-brain-backups/sync/`);只有时间相同/缺失、或本地布局无法上传时才留下冲突,并暴露两侧信息允许人工处置:
| 方法 | 路径 | 说明 | | 方法 | 路径 | 说明 |
|---|---|---| |---|---|---|
| GET | `/cloud-memory/sync/status` | 最近统计 + 每个冲突的本地/云端两侧 | | GET | `/cloud-memory/sync/status` | 最近统计 + 每个冲突的本地/云端两侧 |
| POST | `/cloud-memory/sync/run` | 立即执行一次同步 | | POST | `/cloud-memory/sync/run` | 立即执行一次同步 |
| POST | `/cloud-memory/sync/resolve` | `{name,action}`:`keep_local` / `take_cloud` / `manual` | | POST | `/cloud-memory/sync/resolve` | `{name,action}`:`keep_local` / `take_cloud` / `manual` |
| POST | `/cloud-memory/sync/resolve-all` | `{action}`:对当前全部冲突批量 `keep_local` / `take_cloud`,返回 `{resolved[], failed[{name,error}]}` |
- `keep_local`:用本地文件按当前云端 revision 上传为新版本;revision 过期返回 `stale_revision`。 - `keep_local`:用本地文件按当前云端 revision 上传为新版本;revision 过期返回 `stale_revision`。
- `take_cloud`:先把本地目录备份到 `$DSH_HOME/.cloud-memory-backups/sync/<name>/<时间>`,再写入云端 bundle。 - `take_cloud`:先把本地目录备份到 `$DSH_HOME/.dsh-brain-backups/sync/<name>/<时间>`,再写入云端 bundle。
- `manual`:只返回两侧信息,不改任何文件。 - `manual`:只返回两侧信息,不改任何文件。
### 6.4 验证 ### 6.4 验证
- `verify-market.mjs`:19 项通过(清单解析、search/detail、未知来源 400、plan 固定提交、只装勾选项、来源记录)。 - `verify-market.mjs`:19 项通过(清单解析、search/detail、未知来源 400、plan 固定提交、只装勾选项、来源记录)。
- `verify-skill-update.mjs`:15 项通过(真实 git 仓库的 check/apply/rollback、无来源拒绝、过期提交拒绝、备份存在)。 - `verify-skill-update.mjs`:15 项通过(真实 git 仓库的 check/apply/rollback、无来源拒绝、过期提交拒绝、备份存在)。
- `verify-sync-resolve.mjs`:12 项通过(一次真实 pass 产生 4 个冲突、take_cloud 备份并覆盖、keep_local 上传、manual 只读、stale 拒绝)。 - `verify-sync-resolve.mjs`:23 项通过(一次真实 pass 产生 4 个冲突、take_cloud 备份并覆盖、keep_local 上传、manual 只读、stale 拒绝、批量成功与部分失败)。
## 7. P4:MCP 管理与市场(0.6.0) ## 7. P4:MCP 管理与市场(0.6.0)
@ -199,7 +200,7 @@ refreshCatalog, toolsList, toolSearch, toolExplorer, toolDetail`
| 区块 | 能力 | | 区块 | 能力 |
|---|---| |---|---|
| 我的连接 | 搜索(名称/key/传输/鉴权/状态/最近错误)、状态筛选、多选与全选、批量健康检查/启用/停用/重连/两段式批量移除;单条连接的读取、健康检查、工具缓存、启停、重连、两段式移除 | | 我的连接 | 默认一行骨架(名称 + 状态 + 传输 + 「详情」),展开后才显示鉴权/注入/范围/健康检查/最近错误与单条操作;上方有搜索、状态筛选、多选与全选、批量健康检查/启用/停用/重连/两段式批量移除 |
| ~~MCP 市场~~ | **0.9.6 已删除**:宿主的 `catalog` 方法在当前 dsh-mcp-connector 上返回 `HTTP 405`,内嵌面板只能显示错误条。目录浏览与安装回到宿主自己的插件市场,本卡不再渲染该区块 | | ~~MCP 市场~~ | **0.9.6 已删除**:宿主的 `catalog` 方法在当前 dsh-mcp-connector 上返回 `HTTP 405`,内嵌面板只能显示错误条。目录浏览与安装回到宿主自己的插件市场,本卡不再渲染该区块 |
| 新增 / 导入 | 自定义 Streamable HTTP 与 stdio 连接(显示实际启动命令,云端不执行)、`importJson` 批量导入 | | 新增 / 导入 | 自定义 Streamable HTTP 与 stdio 连接(显示实际启动命令,云端不执行)、`importJson` 批量导入 |
| 配置编辑 | `editableConnectionConfig` 读取(敏感值以 `<KEEP_EXISTING>` 保留标记返回),`reconfigureConnection` 保存;空输入不清除已有密钥 | | 配置编辑 | `editableConnectionConfig` 读取(敏感值以 `<KEEP_EXISTING>` 保留标记返回),`reconfigureConnection` 保存;空输入不清除已有密钥 |
@ -236,7 +237,7 @@ refreshCatalog, toolsList, toolSearch, toolExplorer, toolDetail`
| `skills/install/plan` `install/commit` | `sync_running` | | `skills/install/plan` `install/commit` | `sync_running` |
| `skills/toggle` `skills/remove` | `sync_running` | | `skills/toggle` `skills/remove` | `sync_running` |
| `skills/update/apply` `skills/rollback` | `sync_running` | | `skills/update/apply` `skills/rollback` | `sync_running` |
| `sync/resolve` | `sync_running` | | `sync/resolve` `sync/resolve-all` | `sync_running` |
HTTP 层统一映射为 **409 `sync_running`**。`verify-concurrency.mjs`:8 项通过(六个入口 + 路由 409 + 同步结束后放行)。 HTTP 层统一映射为 **409 `sync_running`**。`verify-concurrency.mjs`:8 项通过(六个入口 + 路由 409 + 同步结束后放行)。

View File

@ -26,7 +26,7 @@ export const name = 'dsh-brain';
/** Services required before `apply` runs. */ /** Services required before `apply` runs. */
export const inject = ['webServer']; export const inject = ['webServer'];
/** Version reported by the status card. */ /** Version reported by the status card. */
const VERSION = '0.9.7'; const VERSION = '0.9.10';
/** How often the skill directory is reconciled with the cloud center. */ /** How often the skill directory is reconciled with the cloud center. */
const SKILL_SYNC_INTERVAL_MS = 15 * 60_000; const SKILL_SYNC_INTERVAL_MS = 15 * 60_000;
/** How often queued reports are retried. */ /** How often queued reports are retried. */

View File

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

View File

@ -749,6 +749,7 @@ async function serveMarket(deps, req, res) {
* `GET /dsh-brain/sync/status` latest stats + both sides of each conflict * `GET /dsh-brain/sync/status` latest stats + both sides of each conflict
* `POST /dsh-brain/sync/run` trigger one pass now * `POST /dsh-brain/sync/run` trigger one pass now
* `POST /dsh-brain/sync/resolve` { name, action: keep_local | take_cloud | manual } * `POST /dsh-brain/sync/resolve` { name, action: keep_local | take_cloud | manual }
* `POST /dsh-brain/sync/resolve-all` { action: keep_local | take_cloud } for every conflict
*/ */
async function serveSync(deps, req, res) { async function serveSync(deps, req, res) {
const sync = deps.sync; const sync = deps.sync;
@ -788,6 +789,18 @@ async function serveSync(deps, req, res) {
json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() }); json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() });
return; return;
} }
if (suffix === '/resolve-all') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res);
if (body === undefined)
return;
const result = await sync.resolveConflicts(body.action);
json(res, 200, { ok: true, ...result, stats: sync.stats(), conflicts: await sync.conflictDetails() });
return;
}
fail(res, 404, 'unknown-sync-route'); fail(res, 404, 'unknown-sync-route');
} }
catch (error) { catch (error) {

View File

@ -15,12 +15,14 @@
* revisions, guarded by the center's `expected_revision` check. * revisions, guarded by the center's `expected_revision` check.
* *
* Safety rules (deliberate, in order): * Safety rules (deliberate, in order):
* 1. A cloud-delivered skill is never re-uploaded. If its local files no * 1. A cloud-delivered skill is never re-uploaded unless its local copy is
* longer match the delivery manifest, the skill is flagged as a * newer than the center's `updated_at`; before any cloud overwrite the
* conflict and left completely alone. * local folder is copied to `$DSH_HOME/.dsh-brain-backups/sync/`.
* 2. A local deletion never deletes the cloud copy. * 2. A local deletion never deletes the cloud copy.
* 3. A name that already exists on the other side is never hijacked; * 3. A same-name skill is never hijacked silently: byte-identical copies are
* it is reported as a conflict for a human to resolve. * adopted in place, otherwise the newer side (local file mtime vs center
* `updated_at`) wins; only equal or missing timestamps are reported as a
* conflict for a human to resolve.
* 4. Bundles whose scripts changed on the cloud side are not installed * 4. Bundles whose scripts changed on the cloud side are not installed
* until the change is acknowledged in the dashboard, mirroring the * until the change is acknowledged in the dashboard, mirroring the
* center's own review flag. * center's own review flag.
@ -59,6 +61,24 @@ export function linkedSkillManifest(files) {
const lines = files.map((file) => `${file.path}\0${file.sha256}`).sort(); const lines = files.map((file) => `${file.path}\0${file.sha256}`).sort();
return sha256Hex(Buffer.from(`cloud-memory-skill-v1\n${lines.join('\n')}\n`, 'utf8')); return sha256Hex(Buffer.from(`cloud-memory-skill-v1\n${lines.join('\n')}\n`, 'utf8'));
} }
/** Epoch milliseconds from a center timestamp (ISO string or epoch seconds/ms). */
function timestampMs(value) {
if (typeof value === 'number' && Number.isFinite(value))
return value < 1e12 ? value * 1000 : value;
if (typeof value === 'string' && value !== '') {
const parsed = Date.parse(value);
return Number.isFinite(parsed) ? parsed : undefined;
}
return undefined;
}
/** Newest local file mtime in one skill folder (0 when the folder has no files). */
function newestMtime(files) {
let newest = 0;
for (const file of files)
if (file.mtimeMs > newest)
newest = file.mtimeMs;
return newest;
}
/** True when the cloud center would accept this relative file path. */ /** True when the cloud center would accept this relative file path. */
export function isCloudSkillPath(rel) { export function isCloudSkillPath(rel) {
if (rel === '' || rel.length > 200 || rel.startsWith('/') || rel.includes('\\') || rel.includes('//')) if (rel === '' || rel.length > 200 || rel.startsWith('/') || rel.includes('\\') || rel.includes('//'))
@ -197,7 +217,10 @@ export class SkillSync {
await walk(rel); await walk(rel);
} }
else if (entry.isFile()) { else if (entry.isFile()) {
out.push({ rel, buffer: await readFile(join(dir, rel)) }); const absolute = join(dir, rel);
const buffer = await readFile(absolute);
const info = await stat(absolute);
out.push({ rel, buffer, mtimeMs: info.mtimeMs });
} }
} }
}; };
@ -263,6 +286,145 @@ export class SkillSync {
} }
return undefined; return undefined;
} }
/** Center's last-change time for one listed skill (ISO string or epoch). */
cloudUpdatedAt(item) {
return timestampMs(item.updated_at) ?? timestampMs(item.created_at);
}
/** Manifest over every local file, including files the center would reject. */
localManifest(files) {
return linkedSkillManifest(files.map((file) => ({ path: file.rel, sha256: sha256Hex(file.buffer) })));
}
/** Copy a local skill aside before an automatic cloud overwrite. */
async backupLocal(dir, name) {
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
const backup = join(dshHome(), '.dsh-brain-backups', 'sync', name, stamp);
await mkdir(join(backup, '..'), { recursive: true });
await cp(dir, backup, { recursive: true, filter: (path) => !path.split(/[\\/]/).includes('.git') });
return backup;
}
/**
* Local and cloud already carry the same bytes: record the delivery marker
* without a transfer, so the next pass treats the folder as cloud-origin and
* the user is not asked to pick between two identical copies.
*/
async adoptIdenticalDelivery(home, item, files) {
const delivery = {
name: item.name,
...(item.revision === undefined ? {} : { revision: item.revision }),
...(item.manifest_sha256 === undefined ? {} : { manifest_sha256: item.manifest_sha256 }),
files: files.map((file) => ({ path: file.rel, sha256: sha256Hex(file.buffer) })),
synced_at: new Date().toISOString(),
};
await writeFile(join(home, '.manifest.json'), JSON.stringify(delivery, null, 2));
}
/** Fetch, verify and install the cloud copy, backing the local one up first. */
async autoTakeCloud(item, home, installRoot, state, stats, client) {
if (item.script_changed === true) {
this.conflict(stats, item.name, 'script_review_required');
return 'conflict';
}
const bundle = await client.skillBundle(item.name);
if (!bundle.ok) {
this.conflict(stats, item.name, `bundle_failed: ${describeError(bundle.error)}`);
return 'conflict';
}
if (linkedSkillManifest(bundle.data.files) !== bundle.data.manifest_sha256) {
this.conflict(stats, item.name, 'manifest_mismatch');
return 'conflict';
}
if (bundle.data.script_changed === true) {
this.conflict(stats, item.name, 'script_review_required');
return 'conflict';
}
await this.backupLocal(home, item.name);
await this.install(item, bundle.data, installRoot);
this.markDelivered(state, item.name, bundle.data.manifest_sha256);
delete state.removed[item.name];
stats.updated.push(item.name);
return 'resolved';
}
/** Upload the locally-newer copy as the next cloud revision. */
async autoUploadLocal(skill, folder, dir, cloud, state, stats, client) {
const updated = await client.updateSkill(skill.name, {
description: skill.description,
files: this.toUploadFiles(skill.files),
expected_revision: cloud.revision ?? 0,
operation_id: `dsh-skill-${randomUUID()}`,
});
if (!updated.ok) {
const reason = updated.error.code === 'revision_conflict' ? 'cloud_newer' : `upload_failed: ${describeError(updated.error)}`;
this.conflict(stats, skill.name, reason);
return 'conflict';
}
const revision = updated.data.skill?.revision ?? updated.data.revision ?? (cloud.revision ?? 0) + 1;
await rm(join(dir, '.manifest.json'), { force: true });
this.markUploaded(state, skill.name, {
folder,
revision,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
});
delete state.removed[skill.name];
stats.updated.push(skill.name);
return 'resolved';
}
/**
* Same-name skill on both sides without a delivery record. Identical bytes
* are adopted silently; different bytes go to whichever side is newer;
* equal/missing timestamps stay unresolved for a human decision.
*/
async autoResolveCollision(item, home, installRoot, state, stats, client) {
const localFiles = await this.readSkillFiles(home).catch(() => []);
if (!localFiles.some((file) => file.rel === 'SKILL.md'))
return 'unresolved';
if (item.manifest_sha256 !== undefined && this.localManifest(localFiles) === item.manifest_sha256) {
await this.adoptIdenticalDelivery(home, item, localFiles);
this.markDelivered(state, item.name, item.manifest_sha256);
stats.skipped += 1;
return 'resolved';
}
const cloudAt = this.cloudUpdatedAt(item);
const localAt = newestMtime(localFiles);
if (cloudAt === undefined || localAt === 0 || cloudAt === localAt)
return 'unresolved';
if (cloudAt > localAt)
return this.autoTakeCloud(item, home, installRoot, state, stats, client);
const skill = await this.readLocalSkill(home, item.name);
if (skill === undefined)
return 'unresolved';
if (typeof skill === 'string') {
this.conflict(stats, item.name, skill);
return 'conflict';
}
return this.autoUploadLocal(skill, item.name, home, item, state, stats, client);
}
/**
* Cloud-delivered skill edited locally. Identical bytes refresh the marker;
* otherwise the newer side wins (cloud overwrite is backed up first).
*/
async autoResolveLocalDrift(item, home, state, stats, client, installRoot) {
const localFiles = await this.readSkillFiles(home).catch(() => []);
if (item.manifest_sha256 !== undefined && localFiles.length > 0 && this.localManifest(localFiles) === item.manifest_sha256) {
await this.adoptIdenticalDelivery(home, item, localFiles);
this.markDelivered(state, item.name, item.manifest_sha256);
stats.skipped += 1;
return 'resolved';
}
const cloudAt = this.cloudUpdatedAt(item);
const localAt = newestMtime(localFiles);
if (cloudAt === undefined || localAt === 0 || cloudAt === localAt)
return 'unresolved';
if (cloudAt > localAt)
return this.autoTakeCloud(item, home, installRoot, state, stats, client);
const skill = await this.readLocalSkill(home, item.name);
if (skill === undefined)
return 'unresolved';
if (typeof skill === 'string') {
this.conflict(stats, item.name, skill);
return 'conflict';
}
return this.autoUploadLocal(skill, item.name, home, item, state, stats, client);
}
/** One full pass; never throws — outcomes land in the stats. */ /** One full pass; never throws — outcomes land in the stats. */
async syncOnce() { async syncOnce() {
if (this.running) if (this.running)
@ -366,6 +528,11 @@ export class SkillSync {
if (exists && delivery !== undefined) { if (exists && delivery !== undefined) {
// Delivered before: local integrity is judged before any download. // Delivered before: local integrity is judged before any download.
if (!(await this.deliveredIntact(home, delivery))) { if (!(await this.deliveredIntact(home, delivery))) {
const auto = await this.autoResolveLocalDrift(item, home, state, stats, client, parked ? this.holdingRoot() : root);
if (auto !== 'unresolved') {
stateDirty = true;
continue;
}
this.conflict(stats, item.name, 'locally_modified'); this.conflict(stats, item.name, 'locally_modified');
continue; continue;
} }
@ -380,6 +547,14 @@ export class SkillSync {
// Intact but the cloud moved on: fall through and install the update. // Intact but the cloud moved on: fall through and install the update.
} }
if (exists && delivery === undefined) { if (exists && delivery === undefined) {
// Same name on both sides with no delivery proof. Identical bytes are
// adopted; otherwise the newer side wins by timestamp. Only an equal
// or missing timestamp becomes a human conflict.
const auto = await this.autoResolveCollision(item, home, parked ? this.holdingRoot() : root, state, stats, client);
if (auto !== 'unresolved') {
stateDirty = true;
continue;
}
this.conflict(stats, item.name, 'name_collision'); this.conflict(stats, item.name, 'name_collision');
continue; continue;
} }
@ -407,6 +582,10 @@ export class SkillSync {
(exists ? stats.updated : stats.downloaded).push(item.name); (exists ? stats.updated : stats.downloaded).push(item.name);
} }
// ---- UP: local originals -> cloud center --------------------------- // ---- UP: local originals -> cloud center ---------------------------
// The DOWN pass already had the chance to resolve a same-name folder;
// don't repeat the same skill with a second reason (the panel used to show
// one card per reason for the same name).
const knownConflicts = new Set(stats.conflicts.map((entry) => entry.name));
const folders = await readdir(root, { withFileTypes: true }).catch(() => []); const folders = await readdir(root, { withFileTypes: true }).catch(() => []);
const seenFolders = new Set(); const seenFolders = new Set();
for (const entry of folders) { for (const entry of folders) {
@ -420,12 +599,37 @@ export class SkillSync {
if (skill === undefined) if (skill === undefined)
continue; continue;
if (typeof skill === 'string') { if (typeof skill === 'string') {
this.conflict(stats, entry.name, skill); if (!knownConflicts.has(entry.name))
this.conflict(stats, entry.name, skill);
continue; continue;
} }
const record = state.uploaded[skill.name]; const record = state.uploaded[skill.name];
const cloud = cloudByName.get(skill.name); const cloud = cloudByName.get(skill.name);
if (cloud !== undefined && record === undefined) { if (cloud !== undefined && record === undefined) {
if (knownConflicts.has(skill.name))
continue;
if (cloud.manifest_sha256 !== undefined && cloud.manifest_sha256 === skill.manifest) {
// Same bytes already in the center: adopt the cloud identity without
// an upload, so the next pass compares revisions instead of names.
this.markUploaded(state, skill.name, {
folder: entry.name,
revision: cloud.revision ?? 1,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
});
stateDirty = true;
stats.skipped += 1;
continue;
}
const cloudAt = this.cloudUpdatedAt(cloud);
const localAt = newestMtime(skill.files);
if (cloudAt !== undefined && localAt > 0 && localAt > cloudAt) {
const auto = await this.autoUploadLocal(skill, entry.name, dir, cloud, state, stats, client);
if (auto !== 'unresolved') {
stateDirty = true;
continue;
}
}
this.conflict(stats, skill.name, 'name_collision'); this.conflict(stats, skill.name, 'name_collision');
continue; continue;
} }
@ -464,7 +668,33 @@ export class SkillSync {
} }
else { else {
if (cloud.revision !== undefined && cloud.revision !== record.revision) { if (cloud.revision !== undefined && cloud.revision !== record.revision) {
this.conflict(stats, skill.name, 'cloud_newer'); // The center moved on since the last upload. Identical bytes just
// re-pin the revision; otherwise the newer side wins and only an
// equal/missing timestamp stays a conflict.
if (cloud.manifest_sha256 !== undefined && cloud.manifest_sha256 === skill.manifest) {
this.markUploaded(state, skill.name, {
folder: entry.name,
revision: cloud.revision,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
});
stateDirty = true;
stats.skipped += 1;
continue;
}
const cloudAt = this.cloudUpdatedAt(cloud);
const localAt = newestMtime(skill.files);
if (cloudAt !== undefined && localAt > 0 && cloudAt !== localAt) {
const auto = cloudAt > localAt
? await this.autoTakeCloud(cloud, dir, root, state, stats, client)
: await this.autoUploadLocal(skill, entry.name, dir, cloud, state, stats, client);
if (auto !== 'unresolved') {
stateDirty = true;
continue;
}
}
if (!knownConflicts.has(skill.name))
this.conflict(stats, skill.name, 'cloud_newer');
continue; continue;
} }
const updated = await client.updateSkill(skill.name, { const updated = await client.updateSkill(skill.name, {
@ -577,6 +807,31 @@ export class SkillSync {
dropConflict(name) { dropConflict(name) {
this.current = { ...this.current, conflicts: this.current.conflicts.filter((conflict) => conflict.name !== name) }; this.current = { ...this.current, conflicts: this.current.conflicts.filter((conflict) => conflict.name !== name) };
} }
/**
* Resolve every current conflict with one action (`keep_local` or
* `take_cloud`). Partial failures are collected instead of aborting the
* whole batch, so the UI can show "N done, M failed" in one shot.
*/
async resolveConflicts(actionInput) {
const action = actionInput === 'keep_local' || actionInput === 'take_cloud' ? actionInput : '';
if (action === '')
throw new Error('invalid_action');
if (this.running)
throw new Error('sync_running');
const names = [...new Set(this.current.conflicts.map((conflict) => conflict.name))];
const resolved = [];
const failed = [];
for (const name of names) {
try {
await this.resolveConflict(name, action);
resolved.push(name);
}
catch (error) {
failed.push({ name, error: error instanceof Error ? error.message : String(error) });
}
}
return { action, resolved, failed };
}
/** /**
* Both sides of every conflict from the last pass, so a human can decide. * Both sides of every conflict from the last pass, so a human can decide.
* Read-only: it never changes a file or uploads anything. * Read-only: it never changes a file or uploads anything.
@ -641,7 +896,7 @@ export class SkillSync {
}, },
canKeepLocal: location !== 'none', canKeepLocal: location !== 'none',
canTakeCloud: cloudItem !== undefined, canTakeCloud: cloudItem !== undefined,
note: '“保留本地”把本地版本上传成新的云端版本;“采用云端”先备份本地再覆盖;“手动合并”只返回两侧信息,不改文件。', note: '同步会先按内容与更新时间自动采用较新的一边(覆盖前备份本地);只有时间相同/缺失、或目录结构不支持时才需要你逐项选择。',
}); });
} }
return out; return out;

View File

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

View File

@ -118,6 +118,10 @@ export interface SkillSummary {
files?: number files?: number
bytes?: number bytes?: number
script_changed?: boolean script_changed?: boolean
/** Center creation time (ISO string; older servers may send epoch seconds). */
created_at?: string | number
/** Center last-change time — the timestamp the sync engine compares against local mtimes. */
updated_at?: string | number
[key: string]: unknown [key: string]: unknown
} }

View File

@ -30,7 +30,7 @@ export const name = 'dsh-brain'
export const inject = ['webServer'] export const inject = ['webServer']
/** Version reported by the status card. */ /** Version reported by the status card. */
const VERSION = '0.9.7' const VERSION = '0.9.10'
/** How often the skill directory is reconciled with the cloud center. */ /** How often the skill directory is reconciled with the cloud center. */
const SKILL_SYNC_INTERVAL_MS = 15 * 60_000 const SKILL_SYNC_INTERVAL_MS = 15 * 60_000

View File

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

View File

@ -838,6 +838,7 @@ async function serveMarket(deps: RouteDeps, req: IncomingMessage, res: ServerRes
* `GET /dsh-brain/sync/status` latest stats + both sides of each conflict * `GET /dsh-brain/sync/status` latest stats + both sides of each conflict
* `POST /dsh-brain/sync/run` trigger one pass now * `POST /dsh-brain/sync/run` trigger one pass now
* `POST /dsh-brain/sync/resolve` { name, action: keep_local | take_cloud | manual } * `POST /dsh-brain/sync/resolve` { name, action: keep_local | take_cloud | manual }
* `POST /dsh-brain/sync/resolve-all` { action: keep_local | take_cloud } for every conflict
*/ */
async function serveSync(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> { async function serveSync(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
const sync = deps.sync const sync = deps.sync
@ -867,6 +868,14 @@ async function serveSync(deps: RouteDeps, req: IncomingMessage, res: ServerRespo
json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() }) json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() })
return return
} }
if (suffix === '/resolve-all') {
if (req.method !== 'POST') { fail(res, 405, 'method-not-allowed'); return }
const body = await jsonBody(req, res)
if (body === undefined) return
const result = await sync.resolveConflicts(body.action)
json(res, 200, { ok: true, ...result, stats: sync.stats(), conflicts: await sync.conflictDetails() })
return
}
fail(res, 404, 'unknown-sync-route') fail(res, 404, 'unknown-sync-route')
} catch (error) { } catch (error) {
const message = error instanceof Error ? error.message : String(error) const message = error instanceof Error ? error.message : String(error)

View File

@ -15,12 +15,14 @@
* revisions, guarded by the center's `expected_revision` check. * revisions, guarded by the center's `expected_revision` check.
* *
* Safety rules (deliberate, in order): * Safety rules (deliberate, in order):
* 1. A cloud-delivered skill is never re-uploaded. If its local files no * 1. A cloud-delivered skill is never re-uploaded unless its local copy is
* longer match the delivery manifest, the skill is flagged as a * newer than the center's `updated_at`; before any cloud overwrite the
* conflict and left completely alone. * local folder is copied to `$DSH_HOME/.dsh-brain-backups/sync/`.
* 2. A local deletion never deletes the cloud copy. * 2. A local deletion never deletes the cloud copy.
* 3. A name that already exists on the other side is never hijacked; * 3. A same-name skill is never hijacked silently: byte-identical copies are
* it is reported as a conflict for a human to resolve. * adopted in place, otherwise the newer side (local file mtime vs center
* `updated_at`) wins; only equal or missing timestamps are reported as a
* conflict for a human to resolve.
* 4. Bundles whose scripts changed on the cloud side are not installed * 4. Bundles whose scripts changed on the cloud side are not installed
* until the change is acknowledged in the dashboard, mirroring the * until the change is acknowledged in the dashboard, mirroring the
* center's own review flag. * center's own review flag.
@ -65,6 +67,23 @@ export function linkedSkillManifest(files: readonly { path: string; sha256: stri
return sha256Hex(Buffer.from(`cloud-memory-skill-v1\n${lines.join('\n')}\n`, 'utf8')) return sha256Hex(Buffer.from(`cloud-memory-skill-v1\n${lines.join('\n')}\n`, 'utf8'))
} }
/** Epoch milliseconds from a center timestamp (ISO string or epoch seconds/ms). */
function timestampMs(value: unknown): number | undefined {
if (typeof value === 'number' && Number.isFinite(value)) return value < 1e12 ? value * 1000 : value
if (typeof value === 'string' && value !== '') {
const parsed = Date.parse(value)
return Number.isFinite(parsed) ? parsed : undefined
}
return undefined
}
/** Newest local file mtime in one skill folder (0 when the folder has no files). */
function newestMtime(files: readonly { mtimeMs: number }[]): number {
let newest = 0
for (const file of files) if (file.mtimeMs > newest) newest = file.mtimeMs
return newest
}
/** True when the cloud center would accept this relative file path. */ /** True when the cloud center would accept this relative file path. */
export function isCloudSkillPath(rel: string): boolean { export function isCloudSkillPath(rel: string): boolean {
if (rel === '' || rel.length > 200 || rel.startsWith('/') || rel.includes('\\') || rel.includes('//')) return false if (rel === '' || rel.length > 200 || rel.startsWith('/') || rel.includes('\\') || rel.includes('//')) return false
@ -150,6 +169,8 @@ interface SyncState {
interface LocalFile { interface LocalFile {
rel: string rel: string
buffer: Buffer buffer: Buffer
/** Last-modified time; the automatic newer-side winner is chosen from these. */
mtimeMs: number
} }
/** Dependencies of one sync engine instance. */ /** Dependencies of one sync engine instance. */
@ -173,6 +194,14 @@ interface DeliveryManifest {
files?: { path: string; sha256: string }[] files?: { path: string; sha256: string }[]
} }
/**
* Result of an automatic two-sided resolution:
* - resolved: the newer side won and the state was updated;
* - conflict: a specific conflict was recorded (e.g. script review);
* - unresolved: timestamps missing/equal — the caller records a conflict.
*/
type AutoResolution = 'resolved' | 'conflict' | 'unresolved'
export class SkillSync { export class SkillSync {
private running = false private running = false
private current: SkillSyncStats = { private current: SkillSyncStats = {
@ -262,7 +291,10 @@ export class SkillSync {
if (entry.isDirectory()) { if (entry.isDirectory()) {
await walk(rel) await walk(rel)
} else if (entry.isFile()) { } else if (entry.isFile()) {
out.push({ rel, buffer: await readFile(join(dir, rel)) }) const absolute = join(dir, rel)
const buffer = await readFile(absolute)
const info = await stat(absolute)
out.push({ rel, buffer, mtimeMs: info.mtimeMs })
} }
} }
} }
@ -327,6 +359,175 @@ export class SkillSync {
return undefined return undefined
} }
/** Center's last-change time for one listed skill (ISO string or epoch). */
private cloudUpdatedAt(item: SkillSummary): number | undefined {
return timestampMs(item.updated_at) ?? timestampMs(item.created_at)
}
/** Manifest over every local file, including files the center would reject. */
private localManifest(files: readonly LocalFile[]): string {
return linkedSkillManifest(files.map((file) => ({ path: file.rel, sha256: sha256Hex(file.buffer) })))
}
/** Copy a local skill aside before an automatic cloud overwrite. */
private async backupLocal(dir: string, name: string): Promise<string> {
const stamp = new Date().toISOString().replace(/[:.]/g, '-')
const backup = join(dshHome(), '.dsh-brain-backups', 'sync', name, stamp)
await mkdir(join(backup, '..'), { recursive: true })
await cp(dir, backup, { recursive: true, filter: (path) => !path.split(/[\\/]/).includes('.git') })
return backup
}
/**
* Local and cloud already carry the same bytes: record the delivery marker
* without a transfer, so the next pass treats the folder as cloud-origin and
* the user is not asked to pick between two identical copies.
*/
private async adoptIdenticalDelivery(home: string, item: SkillSummary, files: readonly LocalFile[]): Promise<void> {
const delivery: DeliveryManifest & { synced_at: string } = {
name: item.name,
...(item.revision === undefined ? {} : { revision: item.revision }),
...(item.manifest_sha256 === undefined ? {} : { manifest_sha256: item.manifest_sha256 }),
files: files.map((file) => ({ path: file.rel, sha256: sha256Hex(file.buffer) })),
synced_at: new Date().toISOString(),
}
await writeFile(join(home, '.manifest.json'), JSON.stringify(delivery, null, 2))
}
/** Fetch, verify and install the cloud copy, backing the local one up first. */
private async autoTakeCloud(
item: SkillSummary,
home: string,
installRoot: string,
state: SyncState,
stats: SkillSyncStats,
client: CloudClient,
): Promise<AutoResolution> {
if (item.script_changed === true) {
this.conflict(stats, item.name, 'script_review_required')
return 'conflict'
}
const bundle = await client.skillBundle(item.name)
if (!bundle.ok) {
this.conflict(stats, item.name, `bundle_failed: ${describeError(bundle.error)}`)
return 'conflict'
}
if (linkedSkillManifest(bundle.data.files) !== bundle.data.manifest_sha256) {
this.conflict(stats, item.name, 'manifest_mismatch')
return 'conflict'
}
if (bundle.data.script_changed === true) {
this.conflict(stats, item.name, 'script_review_required')
return 'conflict'
}
await this.backupLocal(home, item.name)
await this.install(item, bundle.data, installRoot)
this.markDelivered(state, item.name, bundle.data.manifest_sha256)
delete state.removed[item.name]
stats.updated.push(item.name)
return 'resolved'
}
/** Upload the locally-newer copy as the next cloud revision. */
private async autoUploadLocal(
skill: { name: string; description: string; files: LocalFile[]; manifest: string; hasScripts: boolean },
folder: string,
dir: string,
cloud: SkillSummary,
state: SyncState,
stats: SkillSyncStats,
client: CloudClient,
): Promise<AutoResolution> {
const updated = await client.updateSkill(skill.name, {
description: skill.description,
files: this.toUploadFiles(skill.files),
expected_revision: cloud.revision ?? 0,
operation_id: `dsh-skill-${randomUUID()}`,
})
if (!updated.ok) {
const reason = updated.error.code === 'revision_conflict' ? 'cloud_newer' : `upload_failed: ${describeError(updated.error)}`
this.conflict(stats, skill.name, reason)
return 'conflict'
}
const revision = updated.data.skill?.revision ?? updated.data.revision ?? (cloud.revision ?? 0) + 1
await rm(join(dir, '.manifest.json'), { force: true })
this.markUploaded(state, skill.name, {
folder,
revision,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
})
delete state.removed[skill.name]
stats.updated.push(skill.name)
return 'resolved'
}
/**
* Same-name skill on both sides without a delivery record. Identical bytes
* are adopted silently; different bytes go to whichever side is newer;
* equal/missing timestamps stay unresolved for a human decision.
*/
private async autoResolveCollision(
item: SkillSummary,
home: string,
installRoot: string,
state: SyncState,
stats: SkillSyncStats,
client: CloudClient,
): Promise<AutoResolution> {
const localFiles = await this.readSkillFiles(home).catch(() => [])
if (!localFiles.some((file) => file.rel === 'SKILL.md')) return 'unresolved'
if (item.manifest_sha256 !== undefined && this.localManifest(localFiles) === item.manifest_sha256) {
await this.adoptIdenticalDelivery(home, item, localFiles)
this.markDelivered(state, item.name, item.manifest_sha256)
stats.skipped += 1
return 'resolved'
}
const cloudAt = this.cloudUpdatedAt(item)
const localAt = newestMtime(localFiles)
if (cloudAt === undefined || localAt === 0 || cloudAt === localAt) return 'unresolved'
if (cloudAt > localAt) return this.autoTakeCloud(item, home, installRoot, state, stats, client)
const skill = await this.readLocalSkill(home, item.name)
if (skill === undefined) return 'unresolved'
if (typeof skill === 'string') {
this.conflict(stats, item.name, skill)
return 'conflict'
}
return this.autoUploadLocal(skill, item.name, home, item, state, stats, client)
}
/**
* Cloud-delivered skill edited locally. Identical bytes refresh the marker;
* otherwise the newer side wins (cloud overwrite is backed up first).
*/
private async autoResolveLocalDrift(
item: SkillSummary,
home: string,
state: SyncState,
stats: SkillSyncStats,
client: CloudClient,
installRoot: string,
): Promise<AutoResolution> {
const localFiles = await this.readSkillFiles(home).catch(() => [])
if (item.manifest_sha256 !== undefined && localFiles.length > 0 && this.localManifest(localFiles) === item.manifest_sha256) {
await this.adoptIdenticalDelivery(home, item, localFiles)
this.markDelivered(state, item.name, item.manifest_sha256)
stats.skipped += 1
return 'resolved'
}
const cloudAt = this.cloudUpdatedAt(item)
const localAt = newestMtime(localFiles)
if (cloudAt === undefined || localAt === 0 || cloudAt === localAt) return 'unresolved'
if (cloudAt > localAt) return this.autoTakeCloud(item, home, installRoot, state, stats, client)
const skill = await this.readLocalSkill(home, item.name)
if (skill === undefined) return 'unresolved'
if (typeof skill === 'string') {
this.conflict(stats, item.name, skill)
return 'conflict'
}
return this.autoUploadLocal(skill, item.name, home, item, state, stats, client)
}
/** One full pass; never throws — outcomes land in the stats. */ /** One full pass; never throws — outcomes land in the stats. */
async syncOnce(): Promise<SkillSyncStats> { async syncOnce(): Promise<SkillSyncStats> {
if (this.running) return this.current if (this.running) return this.current
@ -420,6 +621,11 @@ export class SkillSync {
if (exists && delivery !== undefined) { if (exists && delivery !== undefined) {
// Delivered before: local integrity is judged before any download. // Delivered before: local integrity is judged before any download.
if (!(await this.deliveredIntact(home, delivery))) { if (!(await this.deliveredIntact(home, delivery))) {
const auto = await this.autoResolveLocalDrift(item, home, state, stats, client, parked ? this.holdingRoot() : root)
if (auto !== 'unresolved') {
stateDirty = true
continue
}
this.conflict(stats, item.name, 'locally_modified') this.conflict(stats, item.name, 'locally_modified')
continue continue
} }
@ -434,6 +640,14 @@ export class SkillSync {
// Intact but the cloud moved on: fall through and install the update. // Intact but the cloud moved on: fall through and install the update.
} }
if (exists && delivery === undefined) { if (exists && delivery === undefined) {
// Same name on both sides with no delivery proof. Identical bytes are
// adopted; otherwise the newer side wins by timestamp. Only an equal
// or missing timestamp becomes a human conflict.
const auto = await this.autoResolveCollision(item, home, parked ? this.holdingRoot() : root, state, stats, client)
if (auto !== 'unresolved') {
stateDirty = true
continue
}
this.conflict(stats, item.name, 'name_collision') this.conflict(stats, item.name, 'name_collision')
continue continue
} }
@ -462,6 +676,10 @@ export class SkillSync {
} }
// ---- UP: local originals -> cloud center --------------------------- // ---- UP: local originals -> cloud center ---------------------------
// The DOWN pass already had the chance to resolve a same-name folder;
// don't repeat the same skill with a second reason (the panel used to show
// one card per reason for the same name).
const knownConflicts = new Set(stats.conflicts.map((entry) => entry.name))
const folders = await readdir(root, { withFileTypes: true }).catch(() => []) const folders = await readdir(root, { withFileTypes: true }).catch(() => [])
const seenFolders = new Set<string>() const seenFolders = new Set<string>()
for (const entry of folders) { for (const entry of folders) {
@ -472,12 +690,35 @@ export class SkillSync {
const skill = await this.readLocalSkill(dir, entry.name) const skill = await this.readLocalSkill(dir, entry.name)
if (skill === undefined) continue if (skill === undefined) continue
if (typeof skill === 'string') { if (typeof skill === 'string') {
this.conflict(stats, entry.name, skill) if (!knownConflicts.has(entry.name)) this.conflict(stats, entry.name, skill)
continue continue
} }
const record = state.uploaded[skill.name] const record = state.uploaded[skill.name]
const cloud = cloudByName.get(skill.name) const cloud = cloudByName.get(skill.name)
if (cloud !== undefined && record === undefined) { if (cloud !== undefined && record === undefined) {
if (knownConflicts.has(skill.name)) continue
if (cloud.manifest_sha256 !== undefined && cloud.manifest_sha256 === skill.manifest) {
// Same bytes already in the center: adopt the cloud identity without
// an upload, so the next pass compares revisions instead of names.
this.markUploaded(state, skill.name, {
folder: entry.name,
revision: cloud.revision ?? 1,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
})
stateDirty = true
stats.skipped += 1
continue
}
const cloudAt = this.cloudUpdatedAt(cloud)
const localAt = newestMtime(skill.files)
if (cloudAt !== undefined && localAt > 0 && localAt > cloudAt) {
const auto = await this.autoUploadLocal(skill, entry.name, dir, cloud, state, stats, client)
if (auto !== 'unresolved') {
stateDirty = true
continue
}
}
this.conflict(stats, skill.name, 'name_collision') this.conflict(stats, skill.name, 'name_collision')
continue continue
} }
@ -512,7 +753,32 @@ export class SkillSync {
stats.uploaded.push(skill.name) stats.uploaded.push(skill.name)
} else { } else {
if (cloud.revision !== undefined && cloud.revision !== record.revision) { if (cloud.revision !== undefined && cloud.revision !== record.revision) {
this.conflict(stats, skill.name, 'cloud_newer') // The center moved on since the last upload. Identical bytes just
// re-pin the revision; otherwise the newer side wins and only an
// equal/missing timestamp stays a conflict.
if (cloud.manifest_sha256 !== undefined && cloud.manifest_sha256 === skill.manifest) {
this.markUploaded(state, skill.name, {
folder: entry.name,
revision: cloud.revision,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
})
stateDirty = true
stats.skipped += 1
continue
}
const cloudAt = this.cloudUpdatedAt(cloud)
const localAt = newestMtime(skill.files)
if (cloudAt !== undefined && localAt > 0 && cloudAt !== localAt) {
const auto = cloudAt > localAt
? await this.autoTakeCloud(cloud, dir, root, state, stats, client)
: await this.autoUploadLocal(skill, entry.name, dir, cloud, state, stats, client)
if (auto !== 'unresolved') {
stateDirty = true
continue
}
}
if (!knownConflicts.has(skill.name)) this.conflict(stats, skill.name, 'cloud_newer')
continue continue
} }
const updated = await client.updateSkill(skill.name, { const updated = await client.updateSkill(skill.name, {
@ -626,6 +892,29 @@ export class SkillSync {
this.current = { ...this.current, conflicts: this.current.conflicts.filter((conflict) => conflict.name !== name) } this.current = { ...this.current, conflicts: this.current.conflicts.filter((conflict) => conflict.name !== name) }
} }
/**
* Resolve every current conflict with one action (`keep_local` or
* `take_cloud`). Partial failures are collected instead of aborting the
* whole batch, so the UI can show "N done, M failed" in one shot.
*/
async resolveConflicts(actionInput: unknown): Promise<SyncResolveBatchResult> {
const action = actionInput === 'keep_local' || actionInput === 'take_cloud' ? actionInput : ''
if (action === '') throw new Error('invalid_action')
if (this.running) throw new Error('sync_running')
const names = [...new Set(this.current.conflicts.map((conflict) => conflict.name))]
const resolved: string[] = []
const failed: { name: string; error: string }[] = []
for (const name of names) {
try {
await this.resolveConflict(name, action)
resolved.push(name)
} catch (error) {
failed.push({ name, error: error instanceof Error ? error.message : String(error) })
}
}
return { action, resolved, failed }
}
/** /**
* Both sides of every conflict from the last pass, so a human can decide. * Both sides of every conflict from the last pass, so a human can decide.
* Read-only: it never changes a file or uploads anything. * Read-only: it never changes a file or uploads anything.
@ -683,7 +972,7 @@ export class SkillSync {
}, },
canKeepLocal: location !== 'none', canKeepLocal: location !== 'none',
canTakeCloud: cloudItem !== undefined, canTakeCloud: cloudItem !== undefined,
note: '“保留本地”把本地版本上传成新的云端版本;“采用云端”先备份本地再覆盖;“手动合并”只返回两侧信息,不改文件。', note: '同步会先按内容与更新时间自动采用较新的一边(覆盖前备份本地);只有时间相同/缺失、或目录结构不支持时才需要你逐项选择。',
}) })
} }
return out return out
@ -812,3 +1101,10 @@ export interface SyncResolveResult {
backup?: string backup?: string
note: string note: string
} }
/** Outcome of resolving every current conflict with one action. */
export interface SyncResolveBatchResult {
action: 'keep_local' | 'take_cloud'
resolved: string[]
failed: { name: string; error: string }[]
}

View File

@ -510,8 +510,14 @@ check('no render boundary error on the skills tab', !skillsText.includes('渲染
const mcpText = await drive('mcp', true) const mcpText = await drive('mcp', true)
check('the MCP tab renders the host connection', mcpText.includes('我的连接') && mcpText.includes('demo-mcp')) check('the MCP tab renders the host connection', mcpText.includes('我的连接') && mcpText.includes('demo-mcp'))
check('MCP state, transport and auth are shown', mcpText.includes('已连接') && mcpText.includes('http') && mcpText.includes('bearer')) check('collapsed rows keep only name, state and transport',
check('MCP actions are offered', mcpText.includes('健康检查') && mcpText.includes('工具列表') && mcpText.includes('移除连接')) mcpText.includes('已连接') && mcpText.includes('http') && !mcpText.includes('bearer'))
check('the heavier MCP sections start collapsed',
!mcpText.includes('校验并保存连接') && !mcpText.includes('预览作用域') && mcpText.includes('展开'))
const mcpDetail = await drive('mcp', true, '详情 demo-mcp')
check('expanding a connection reveals auth, scope and actions',
mcpDetail.includes('bearer') && mcpDetail.includes('健康检查') && mcpDetail.includes('工具列表') && mcpDetail.includes('移除连接'))
check('the injected tools cache starts empty', mcpText.includes('工具可见不等于业务可调用')) check('the injected tools cache starts empty', mcpText.includes('工具可见不等于业务可调用'))
check('the MCP list has search, filters and select-all', check('the MCP list has search, filters and select-all',
mcpText.includes('全选匹配结果') && mcpText.includes('全选匹配结果') &&

View File

@ -57,7 +57,7 @@ async function post(path, body) {
} }
const caps = await get('/dsh-brain/capabilities') const caps = await get('/dsh-brain/capabilities')
check('capabilities answers with 0.9.7', caps.body?.version === '0.9.7', String(caps.body?.version)) check('capabilities answers with 0.9.8', caps.body?.version === '0.9.8', String(caps.body?.version))
check('P3 market is advertised with one provider', caps.body?.features?.skillsMarketplace === true && caps.body?.features?.marketProviders === 1) check('P3 market is advertised with one provider', caps.body?.features?.skillsMarketplace === true && caps.body?.features?.marketProviders === 1)
check('P3 update and sync-resolve are advertised', caps.body?.features?.skillUpdate === true && caps.body?.features?.syncResolve === true) check('P3 update and sync-resolve are advertised', caps.body?.features?.skillUpdate === true && caps.body?.features?.syncResolve === true)
check('P4/P5/v1.1 flags are advertised', caps.body?.features?.multiClient === true && caps.body?.features?.brainMigration === 'ready') check('P4/P5/v1.1 flags are advertised', caps.body?.features?.multiClient === true && caps.body?.features?.brainMigration === 'ready')

View File

@ -4,7 +4,7 @@
// bundles, linked manifest) — no DSH host, no real service, no real token. // bundles, linked manifest) — no DSH host, no real service, no real token.
import http from 'node:http' import http from 'node:http'
import { createHash } from 'node:crypto' import { createHash } from 'node:crypto'
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os' import { tmpdir } from 'node:os'
import { join } from 'node:path' import { join } from 'node:path'
@ -27,16 +27,24 @@ function storeFiles(files) {
return { path: file.path, sha256: sha(buffer), size: buffer.length, encoding: file.content !== undefined ? 'utf8' : 'base64', data: buffer.toString('base64') } return { path: file.path, sha256: sha(buffer), size: buffer.length, encoding: file.content !== undefined ? 'utf8' : 'base64', data: buffer.toString('base64') }
}) })
} }
const DAY = 24 * 60 * 60 * 1000
const CLOUD_OLD = Date.parse('2026-01-01T00:00:00.000Z')
const CLOUD_EQUAL = Date.parse('2026-06-01T00:00:00.000Z')
const iso = (value) => new Date(value).toISOString()
function summaryOf(skill) { function summaryOf(skill) {
return { return {
name: skill.name, description: skill.description, execution_mode: skill.execution_mode, name: skill.name, description: skill.description, execution_mode: skill.execution_mode,
enabled: true, revision: skill.revision, manifest_sha256: linked(skill.files), files: skill.files.length, enabled: true, revision: skill.revision, manifest_sha256: linked(skill.files), files: skill.files.length,
script_changed: skill.script_changed, script_changed: skill.script_changed,
created_at: iso(skill.created_at ?? CLOUD_OLD), updated_at: iso(skill.updated_at ?? CLOUD_OLD),
} }
} }
function seed(name, files, extra = {}) { function seed(name, files, extra = {}) {
const stored = storeFiles(files) const stored = storeFiles(files)
center.set(name, { name, description: `${name} desc`, execution_mode: 'prompt-only', revision: 1, files: stored, script_changed: false, ...extra }) center.set(name, {
name, description: `${name} desc`, execution_mode: 'prompt-only', revision: 1, files: stored,
script_changed: false, created_at: CLOUD_OLD, updated_at: CLOUD_OLD, ...extra,
})
} }
seed('cloud-one', [ seed('cloud-one', [
{ path: 'SKILL.md', content: '# cloud-one\n\n云端技能一。' }, { path: 'SKILL.md', content: '# cloud-one\n\n云端技能一。' },
@ -73,7 +81,11 @@ const server = http.createServer((req, res) => {
const body = await readBody() const body = await readBody()
if (body.expected_revision !== 0) return send(400, { error: 'invalid_input', message: '必须提供 expected_revision' }) if (body.expected_revision !== 0) return send(400, { error: 'invalid_input', message: '必须提供 expected_revision' })
if (center.has(body.name)) return send(409, { error: 'skill_exists', message: '同名技能已存在' }) if (center.has(body.name)) return send(409, { error: 'skill_exists', message: '同名技能已存在' })
const skill = { name: body.name, description: body.description, execution_mode: body.execution_mode ?? 'prompt-only', revision: 1, files: storeFiles(body.files ?? []), script_changed: false } const skill = {
name: body.name, description: body.description, execution_mode: body.execution_mode ?? 'prompt-only',
revision: 1, files: storeFiles(body.files ?? []), script_changed: false,
created_at: Date.now(), updated_at: Date.now(),
}
center.set(skill.name, skill) center.set(skill.name, skill)
return send(201, { skill: summaryOf(skill), revision: 1, manifest_sha256: linked(skill.files) }) return send(201, { skill: summaryOf(skill), revision: 1, manifest_sha256: linked(skill.files) })
} }
@ -86,6 +98,7 @@ const server = http.createServer((req, res) => {
if (body.files) skill.files = storeFiles(body.files) if (body.files) skill.files = storeFiles(body.files)
if (body.description !== undefined) skill.description = body.description if (body.description !== undefined) skill.description = body.description
skill.revision += 1 skill.revision += 1
skill.updated_at = Date.now()
return send(200, { skill: summaryOf(skill), revision: skill.revision, manifest_sha256: linked(skill.files) }) return send(200, { skill: summaryOf(skill), revision: skill.revision, manifest_sha256: linked(skill.files) })
} }
return send(404, { error: 'unknown_route', path }) return send(404, { error: 'unknown_route', path })
@ -106,11 +119,12 @@ const engine = new SkillSync({
}) })
const root = join(process.env.DSH_HOME, 'skills') const root = join(process.env.DSH_HOME, 'skills')
const skillDir = (name) => join(root, name) const skillDir = (name) => join(root, name)
const writeLocal = (name, files) => { const writeLocal = (name, files, mtime = Date.now()) => {
for (const [rel, content] of Object.entries(files)) { for (const [rel, content] of Object.entries(files)) {
const target = join(skillDir(name), ...rel.split('/')) const target = join(skillDir(name), ...rel.split('/'))
mkdirSync(join(target, '..'), { recursive: true }) mkdirSync(join(target, '..'), { recursive: true })
writeFileSync(target, content) writeFileSync(target, content)
utimesSync(target, new Date(mtime), new Date(mtime))
} }
} }
@ -145,23 +159,71 @@ writeLocal('local-one', { 'SKILL.md': '---\nname: local-one\ndescription: 本地
stats = await engine.syncOnce() stats = await engine.syncOnce()
check('edited local skill updates the center', stats.updated.includes('local-one') && center.get('local-one')?.revision === 2) check('edited local skill updates the center', stats.updated.includes('local-one') && center.get('local-one')?.revision === 2)
// 4. A locally modified cloud skill is flagged, never overwritten or uploaded. // 4. A local edit newer than the cloud is uploaded automatically.
writeLocal('cloud-one', { 'SKILL.md': '# cloud-one\n\n我改了云端技能。' }) writeLocal('cloud-one', { 'SKILL.md': '# cloud-one\n\n我改了云端技能。' }, Date.now())
stats = await engine.syncOnce() stats = await engine.syncOnce()
check('local edit of a cloud skill becomes a conflict', check('local edit newer than cloud auto-uploads',
stats.conflicts.some((c) => c.name === 'cloud-one' && c.reason === 'locally_modified'), JSON.stringify(stats.conflicts)) stats.updated.includes('cloud-one') && center.get('cloud-one')?.revision === 2, JSON.stringify(stats.conflicts))
check('the local edit is left untouched', check('the newer local edit stays on disk',
readFileSync(join(skillDir('cloud-one'), 'SKILL.md'), 'utf8').includes('我改了云端技能')) readFileSync(join(skillDir('cloud-one'), 'SKILL.md'), 'utf8').includes('我改了云端技能'))
check('the center copy is untouched by the conflict', check('newer local edit is not a conflict', !stats.conflicts.some((c) => c.name === 'cloud-one'))
center.get('cloud-one')?.revision === 1)
// 5. A name collision on both sides is flagged, both copies untouched. // 4b. Cloud newer than a stale local copy: auto-download with a local backup.
seed('clash', [{ path: 'SKILL.md', content: '# clash cloud' }]) {
writeLocal('clash', { 'SKILL.md': '# clash local\n' }) const cloud = center.get('cloud-one')
cloud.revision += 1
cloud.files = storeFiles([{ path: 'SKILL.md', content: '# cloud-one v3 (cloud newer)' }])
cloud.updated_at = Date.now() + DAY
writeLocal('cloud-one', { 'SKILL.md': '# cloud-one local stale\n' }, Date.now() - DAY)
stats = await engine.syncOnce()
check('cloud newer auto-downloads over a stale local copy',
readFileSync(join(skillDir('cloud-one'), 'SKILL.md'), 'utf8').includes('cloud newer'))
const backupRoot = join(process.env.DSH_HOME, '.dsh-brain-backups', 'sync', 'cloud-one')
check('auto overwrite backs the local copy up', existsSync(backupRoot))
check('cloud newer overwrite is not a conflict', !stats.conflicts.some((c) => c.name === 'cloud-one'))
}
// 5a. Identical bytes on both sides: adopt silently, no transfer, no conflict.
seed('clash-same', [{ path: 'SKILL.md', content: '# clash same' }], { updated_at: CLOUD_OLD })
writeLocal('clash-same', { 'SKILL.md': '# clash same' }, CLOUD_OLD - DAY)
stats = await engine.syncOnce() stats = await engine.syncOnce()
check('name collision is flagged', stats.conflicts.some((c) => c.name === 'clash' && c.reason === 'name_collision')) check('identical collision auto-adopts without a conflict',
check('collision leaves local files alone', readFileSync(join(skillDir('clash'), 'SKILL.md'), 'utf8').includes('clash local')) !stats.conflicts.some((c) => c.name === 'clash-same') && existsSync(join(skillDir('clash-same'), '.manifest.json')))
check('collision leaves the center alone', center.get('clash')?.revision === 1) check('identical collision uploads nothing', center.get('clash-same')?.revision === 1)
// 5b. Local newer wins the collision.
seed('clash-local', [{ path: 'SKILL.md', content: '# clash cloud' }], { updated_at: CLOUD_OLD })
writeLocal('clash-local', { 'SKILL.md': '# clash local newer' }, CLOUD_OLD + DAY)
stats = await engine.syncOnce()
check('local newer collision auto-uploads',
center.get('clash-local')?.revision === 2 && stats.updated.includes('clash-local'))
check('local newer collision keeps the local file',
readFileSync(join(skillDir('clash-local'), 'SKILL.md'), 'utf8').includes('local newer'))
// 5c. Cloud newer wins the collision.
seed('clash-cloud', [{ path: 'SKILL.md', content: '# clash cloud newer' }], { updated_at: Date.now() + DAY })
writeLocal('clash-cloud', { 'SKILL.md': '# clash local stale' }, Date.now() - DAY)
stats = await engine.syncOnce()
check('cloud newer collision auto-downloads',
readFileSync(join(skillDir('clash-cloud'), 'SKILL.md'), 'utf8').includes('cloud newer'))
check('cloud newer collision is not a conflict', !stats.conflicts.some((c) => c.name === 'clash-cloud'))
// 5d. Same timestamp on both sides: still a human decision.
seed('clash-equal', [{ path: 'SKILL.md', content: '# clash cloud same-time' }], { updated_at: CLOUD_EQUAL })
writeLocal('clash-equal', { 'SKILL.md': '# clash local same-time' }, CLOUD_EQUAL)
stats = await engine.syncOnce()
check('equal timestamps keep the name collision conflict',
stats.conflicts.some((c) => c.name === 'clash-equal' && c.reason === 'name_collision'))
check('equal-timestamp collision leaves both sides untouched',
readFileSync(join(skillDir('clash-equal'), 'SKILL.md'), 'utf8').includes('same-time') && center.get('clash-equal')?.revision === 1)
// 5e. A same-name conflict is reported once, not once per reason.
seed('bad-clash', [{ path: 'SKILL.md', content: '# bad cloud' }], { updated_at: CLOUD_EQUAL })
writeLocal('bad-clash', { 'SKILL.md': '# bad local', 'README.md': 'root file' }, CLOUD_EQUAL)
stats = await engine.syncOnce()
const badClashConflicts = stats.conflicts.filter((c) => c.name === 'bad-clash')
check('one card per same-name conflict',
badClashConflicts.length === 1 && badClashConflicts[0]?.reason === 'name_collision', JSON.stringify(badClashConflicts))
// 6. Script-changed cloud bundles wait for review. // 6. Script-changed cloud bundles wait for review.
check('script-changed bundle is not installed', check('script-changed bundle is not installed',

View File

@ -98,6 +98,59 @@ check('keep_local refuses a stale cloud revision', stale)
const remaining = await sync.conflictDetails() const remaining = await sync.conflictDetails()
check('resolved conflicts drop out of the list', remaining.some((d) => d.name === 'demo') === false && remaining.some((d) => d.name === 'demo2') === false) check('resolved conflicts drop out of the list', remaining.some((d) => d.name === 'demo') === false && remaining.some((d) => d.name === 'demo2') === false)
// Batch: partial failures are reported per item, not fatal.
const batchKeep = await sync.resolveConflicts('keep_local')
check('batch keep_local resolves the good item and reports the stale one',
batchKeep.resolved.includes('demo3') && batchKeep.failed.some((f) => f.name === 'demo4' && f.error === 'stale_revision'),
JSON.stringify(batchKeep))
const afterBatch = await sync.conflictDetails()
check('batch leaves only the failed conflict', afterBatch.length === 1 && afterBatch[0].name === 'demo4')
let badAction = false
try { await sync.resolveConflicts('manual') } catch (error) { badAction = error.message === 'invalid_action' }
check('batch refuses a non-batch action', badAction)
// Second home: a clean batch over every conflict succeeds.
const secondHome = mkdtempSync(join(tmpdir(), 'brain-sync-batch-'))
process.env.DSH_HOME = secondHome
const root2 = join(secondHome, 'skills')
mkdirSync(root2, { recursive: true })
const cloudBody2 = '---\nname: b1\n---\n# b1 CLOUD\n'
const files2 = [{ path: 'SKILL.md', sha256: sha256Hex(cloudBody2), data: Buffer.from(cloudBody2).toString('base64') }]
const manifest2 = linkedSkillManifest(files2)
const items2 = [
{ name: 'b1', enabled: true, revision: 2, manifest_sha256: manifest2, files: 1, bytes: cloudBody2.length },
{ name: 'b2', enabled: true, revision: 2, manifest_sha256: manifest2, files: 1, bytes: cloudBody2.length },
]
function makeDrift(rootDir, folder) {
mkdirSync(join(rootDir, folder), { recursive: true })
writeFileSync(join(rootDir, folder, 'SKILL.md'), `# ${folder} local\n`)
writeFileSync(join(rootDir, folder, '.manifest.json'), JSON.stringify({
name: folder, revision: 1, manifest_sha256: 'old', files: [{ path: 'SKILL.md', sha256: 'deadbeef' }],
}))
}
makeDrift(root2, 'b1')
makeDrift(root2, 'b2')
const client2 = {
listSkills: async () => ({ ok: true, status: 200, data: { items: items2 } }),
skillBundle: async (name) => ({ ok: true, status: 200, data: { name, revision: 2, manifest_sha256: manifest2, files: [{ ...files2[0] }] } }),
createSkill: async () => ({ ok: true, status: 200, data: { skill: { revision: 1 } } }),
updateSkill: async () => ({ ok: true, status: 200, data: { skill: { revision: 3 } } }),
}
const sync2 = new SkillSync({
client: () => client2,
settings: () => ({ enabled: true, skillsSyncEnabled: true, skillsDir: '' }),
log: () => {},
})
const stats2 = await sync2.syncOnce()
check('second pass reports two drift conflicts', stats2.conflicts.length === 2, JSON.stringify(stats2.conflicts))
const batchTake = await sync2.resolveConflicts('take_cloud')
check('batch take_cloud resolves every conflict',
batchTake.resolved.length === 2 && batchTake.failed.length === 0, JSON.stringify(batchTake))
const remaining2 = await sync2.conflictDetails()
check('batch take_cloud empties the conflict list', remaining2.length === 0)
check('batch take_cloud overwrote the local files', readFileSync(join(root2, 'b1', 'SKILL.md'), 'utf8').includes('CLOUD'))
const passed = results.filter((r) => r.ok).length const passed = results.filter((r) => r.ok).length
console.log(`\n${passed}/${results.length} passed`) console.log(`\n${passed}/${results.length} passed`)
process.exit(passed === results.length ? 0 : 1) process.exit(passed === results.length ? 0 : 1)

View File

@ -74,7 +74,7 @@ for (const name of readdirSync(libDir)) {
} }
check('no personal domain remains in shipped lib/', leaked.length === 0, leaked.join(',')) check('no personal domain remains in shipped lib/', leaked.length === 0, leaked.join(','))
const pkg = JSON.parse(readFileSync(join(process.cwd(), 'package.json'), 'utf8')) const pkg = JSON.parse(readFileSync(join(process.cwd(), 'package.json'), 'utf8'))
check('package version is the delivery version', pkg.version === '0.9.7', pkg.version) check('package version is the delivery version', pkg.version === '0.9.8', pkg.version)
const passed = results.filter((r) => r.ok).length const passed = results.filter((r) => r.ok).length
console.log(`\n${passed}/${results.length} passed`) console.log(`\n${passed}/${results.length} passed`)