feat(skills): 同步冲突支持批量处理(0.9.10) #3

Merged
newbie merged 1 commits from feat/sync-batch-resolve into main 2026-11-14 16:05:21 +08:00
11 changed files with 174 additions and 9 deletions

View File

@ -130,7 +130,8 @@ v1 范围:支持 发现 / 状态 / 搜索 / 浏览 / 写入 / 按 id 读取;
先备份本地再覆盖,本地文件 mtime 更新就发布新修订;只有时间相同或缺
失时才报冲突(`locally_modified` / `name_collision` / `cloud_newer`),
等面板里逐项确认。本地删除不删云端,且同版本不会被重新拉回(云端出
了新版才会再下来)。云端只接受固定布局(根目录只有 `SKILL.md`,
了新版才会再下来)。面板里可逐项处理,也可用「全部保留本地 / 全部采用
云端」批量处理(有二次确认,失败项会逐条汇总)。云端只接受固定布局(根目录只有 `SKILL.md`,
其余文件进 `references/`、`scripts/`、`assets/`,扩展名有白名单,
单文件 ≤512 KiB、整包 ≤2 MiB、≤100 个文件),不符合的本地技能报
`unsupported_layout`,不会为了迁就而裁剪文件。
@ -221,7 +222,7 @@ pnpm publish --access public --no-git-checks
- 卸载同样是两步:`uninstall/plan` 给出真实目录、文件数与不可恢复提示并签发一次性 token,`remove` 必须带 `confirmed: true` 与匹配 token。
- **技能市场(P3)**:接入经验证来源 `anthropics/skills` 的 `.claude-plugin/marketplace.json`;搜索→详情→`market/plan`(固定提交)→勾选安装。客户端只传 provider/id,从不传 URL。
- **更新/回退(P3)**:安装写 `.skill-source.json`;`skills/update/check|apply` 与 `skills/rollback` 更新前整目录备份,过期提交拒绝。
- **同步冲突(P3)**:`sync/status|run|resolve` 提供两侧信息,逐项「保留本地 / 采用云端 / 手动合并」。
- **同步冲突(P3)**:`sync/status|run|resolve|resolve-all` 提供两侧信息;面板支持逐项「保留本地 / 采用云端 / 手动合并」,也支持「全部保留本地 / 全部采用云端」批量处理(二次确认,逐项失败会汇总提示)。
- **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`)。

View File

@ -915,7 +915,7 @@ window.__ModuleLoader__.load({
// ---- P3: interactive sync conflict resolution -------------------------
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 setState = tuple[1]
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, '同步失败') } })
}, 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 stats = data === null || data === undefined ? null : data.stats
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' } },
state.error === null ? null : h(Banner, { tone: 'bad' }, state.error),
state.notice === null ? null : h(Banner, { tone: state.notice.tone }, state.notice.text),
statPills,
batchRow,
confirmAllRow,
conflicts.length === 0 ? h('p', { style: styles.hint }, '当前没有待处理冲突。') : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } }, conflictRows),
),
)

View File

@ -172,6 +172,7 @@ POST /mcp-connector/api { "method": "status" | "healthCheck" | "toolsList" | "
| GET | `/cloud-memory/sync/status` | 最近统计 + 每个冲突的本地/云端两侧 |
| POST | `/cloud-memory/sync/run` | 立即执行一次同步 |
| 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`。
- `take_cloud`:先把本地目录备份到 `$DSH_HOME/.dsh-brain-backups/sync/<name>/<时间>`,再写入云端 bundle。
@ -181,7 +182,7 @@ POST /mcp-connector/api { "method": "status" | "healthCheck" | "toolsList" | "
- `verify-market.mjs`:19 项通过(清单解析、search/detail、未知来源 400、plan 固定提交、只装勾选项、来源记录)。
- `verify-skill-update.mjs`:15 项通过(真实 git 仓库的 check/apply/rollback、无来源拒绝、过期提交拒绝、备份存在)。
- `verify-sync-resolve.mjs`:12 项通过(一次真实 pass 产生 4 个冲突、take_cloud 备份并覆盖、keep_local 上传、manual 只读、stale 拒绝)。
- `verify-sync-resolve.mjs`:23 项通过(一次真实 pass 产生 4 个冲突、take_cloud 备份并覆盖、keep_local 上传、manual 只读、stale 拒绝、批量成功与部分失败)。
## 7. P4:MCP 管理与市场(0.6.0)
@ -236,7 +237,7 @@ refreshCatalog, toolsList, toolSearch, toolExplorer, toolDetail`
| `skills/install/plan` `install/commit` | `sync_running` |
| `skills/toggle` `skills/remove` | `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 + 同步结束后放行)。

View File

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

View File

@ -749,6 +749,7 @@ async function serveMarket(deps, req, res) {
* `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/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) {
const sync = deps.sync;
@ -788,6 +789,18 @@ async function serveSync(deps, req, res) {
json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() });
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');
}
catch (error) {

View File

@ -807,6 +807,31 @@ export class SkillSync {
dropConflict(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.
* Read-only: it never changes a file or uploads anything.

View File

@ -1,6 +1,6 @@
{
"name": "dsh-brain",
"version": "0.9.9",
"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.",
"type": "module",
"license": "MIT",

View File

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

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
* `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-all` { action: keep_local | take_cloud } for every conflict
*/
async function serveSync(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
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() })
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')
} catch (error) {
const message = error instanceof Error ? error.message : String(error)

View File

@ -892,6 +892,29 @@ export class SkillSync {
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.
* Read-only: it never changes a file or uploads anything.
@ -1078,3 +1101,10 @@ export interface SyncResolveResult {
backup?: 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

@ -98,6 +98,59 @@ check('keep_local refuses a stale cloud revision', stale)
const remaining = await sync.conflictDetails()
check('resolved conflicts drop out of the list', remaining.some((d) => d.name === 'demo') === false && remaining.some((d) => d.name === 'demo2') === false)
// 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
console.log(`\n${passed}/${results.length} passed`)
process.exit(passed === results.length ? 0 : 1)