@matrixfu/skill-set-manager 0.0.0-stage → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js ADDED
@@ -0,0 +1,1091 @@
1
+ /**
2
+ * skill-set-manager host 半:Config 校验、roots 装配、storageDomain(失败回退 JSON)、
3
+ * 启动无条件还原 pending(§6.6)、Remote 操作面(操作唯一实现,§14)、webServer 兜底通道。
4
+ */
5
+ import z from '@deepseek-ai/schemastery';
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol';
9
+ import { parseSkillSetLine, parseToolArgs, TOOL_ACTIONS } from './lib/core/commandLine.js';
10
+ import { buildRoots, projectSkillsDir } from './lib/core/paths.js';
11
+ import { registerLibrary, readManifest, localModified, backfillManifestStats, claimSource } from './lib/core/manifest.js';
12
+ import * as sets from './lib/core/sets.js';
13
+ import { findProjectRoot } from './lib/core/projectRoot.js';
14
+ import { readBinding } from './lib/core/binding.js';
15
+ import { readManaged } from './lib/core/managed.js';
16
+ import { converge, selfCheck, claimForeign } from './lib/core/effective.js';
17
+ import { providerSkills } from './lib/core/providerSkills.js';
18
+ import { entryKind, removeEntry } from './lib/core/linkx.js';
19
+ import { bindProject } from './lib/core/provision.js';
20
+ import { createOpGate } from './lib/core/opgate.js';
21
+ import { openDomain, projectKey } from './lib/core/storage.js';
22
+ import { startOverride, endOverride, endOverrideIfActive, restoreAllPending, pushUndo, applyUndo } from './lib/core/pending.js';
23
+ import { syncResident, pruneLegacyResidentLinks, dropResidentName } from './lib/core/resident.js';
24
+ import os from 'node:os';
25
+ import { parseRepoSpec, fetchRepo, installSkills, cacheDirFor } from './lib/core/github.js';
26
+ import { probeProxy } from './lib/core/gitnet.js';
27
+ import { resolveRepoSource } from './lib/core/source.js';
28
+ import * as updates from './lib/core/updates.js';
29
+ import * as bk from './lib/core/backup.js';
30
+ import * as lifecycle from './lib/core/lifecycle.js';
31
+ import { diagnose } from './lib/core/diagnose.js';
32
+ import * as migrate from './lib/core/migrate.js';
33
+ import { decorate } from './lib/core/translations.js';
34
+ import * as dataPlane from './lib/core/dataPlane.js';
35
+ import { buildLlmPrompt, refId, normalizeSel } from './lib/core/translateExec.js';
36
+
37
+ /** 行级配置(cordis.patch.yml 的 config 块;用户 patch 层升级存活)。 */
38
+ export const Config = z.object({
39
+ gitignoreLine: z.boolean().default(true),
40
+ residentLinkToCrossHarness: z.boolean().default(false), // P3 后语义 = 额外保留旧 ~/.dsh/skills 链(默认常驻已搬 ~/.agents/skills)
41
+ autoTranslate: z.boolean().default(false), // P3:库列表后自动翻 pending(默认关 = 零出网;手动批量不受限)
42
+ autoBindNewProject: z.boolean().default(false),
43
+ autoBindSlug: z.string().default(''),
44
+ customSkillDirs: z.array(z.string()).default([]),
45
+ });
46
+
47
+ export const inject = ['sessionQuery', 'workingDirectory', 'agents', 'sessions'];
48
+
49
+ const EFFECTIVE_PRESETS = new Set(['standard', 'ptc', 'cordis']);
50
+
51
+ export function apply(ctx, config) {
52
+ const roots = buildRoots({
53
+ customSkillDirs: config.customSkillDirs,
54
+ crossHarnessResident: config.residentLinkToCrossHarness,
55
+ });
56
+ let storePromise;
57
+ const storeOf = () => (storePromise ??= openDomain(ctx, { fallbackDir: roots.dshHome }));
58
+
59
+ // `/` 菜单「技能」组是 client 按会话缓存的 skills/list 快照(dsh-client-ui-skill/lib/client.js 的 fetches Map),
60
+ // 上游没有订阅 skills/change 失效(skills/change 也不在 dsh-api-remotes 的转发生效事件白名单里),
61
+ // 所以插件切集后菜单不刷新——这是上游缺口,不是本插件写盘没生效(全名调用走 host 现扫,一直是对的)。
62
+ // 插件侧唯一可靠触发「清全部缓存」的事件 = 'plugin-manager/changed':它就在转发白名单
63
+ // (dsh-api-remotes/lib/index.js 的 API_REMOTE_FORWARDED_EVENTS),且 asar 全库检索只有
64
+ // ui-skill 的 clearAll 订阅它(无其他消费方,副作用为零)。生效清单每次成功落盘后补发一次,
65
+ // `/` 菜单即在当前会话重新拉取;上游日后补 skills/change 订阅时本发法仍幂等无害。
66
+ let slashClearQueued = false;
67
+ const emitSlashCacheClear = () => {
68
+ if (slashClearQueued) return; // 同一宏任务内多次写盘合并为一次事件(如 uninstallSkill 内顺带 syncResident)
69
+ slashClearQueued = true;
70
+ queueMicrotask(() => {
71
+ slashClearQueued = false;
72
+ try { ctx.emit('plugin-manager/changed', { reason: 'skill-set-manager' }); }
73
+ catch (e) { ctx.logger.warn(`skill-set-manager:/ 菜单缓存失效事件发送失败: ${e?.message ?? e}`); }
74
+ });
75
+ };
76
+ // 长任务闸门(GLOSSARY「长任务」):单飞、最近结果、写盘后的失效事件都在这里——不再靠每个调用点自己记得。
77
+ const gate = createOpGate({ onMutated: emitSlashCacheClear });
78
+ const trInflight = new Set(); // M1 互斥(终审 2026-10-26):autoTranslate 后台批与手动 translateRun 不叠加同条目重复出网
79
+
80
+ // Remote 命名空间 = 操作唯一实现(§14);fetch 兜底通道共用同一清单。
81
+ const REMOTE_METHODS = [
82
+ 'state', 'panelSnapshot', 'listSets', 'saveSet', 'deleteSet', 'renameSet', 'copySet', 'setResident', 'saveAsFromEffective', 'exportSet', 'importSets', 'importPreview', 'importApply', 'bind', 'switchSet', 'undoSwitch', 'startOverride', 'endOverride', 'libraryList',
83
+ // P1a:技能生命周期 + 诊断 + 解绑
84
+ 'installApply', 'updateCheck', 'updateApply', 'updateCheckAll', 'cacheClear', 'uninstallSkill', 'backupsList', 'backupRestore',
85
+ 'diagnoseRun', 'reclaimDeadLinks', 'rebuildManaged', 'claimForeign', 'migratePreview', 'migrateApply', 'migrateUndo', 'migrateAgentsPreview', 'migrateAgentsApply', 'migrateAgentsUndo', 'unbind', 'claimSource', 'longStatus',
86
+ // P3:翻译数据面
87
+ 'translatePending', 'translateRun', 'translateModels',
88
+ ];
89
+
90
+ class SkillSetManagerRemote extends TypertRemoteService {
91
+ constructor(ctx) {
92
+ super(ctx, 'skillSetManager', { namespace: 'skill-set-manager' });
93
+ }
94
+
95
+ /** 会话 → 项目根 + preset 判定(投影优先,header 可能过期——探针取证)。 */
96
+ async locate(req) {
97
+ const sessionId = req?.sessionId;
98
+ let cwd = req?.cwd;
99
+ let preset;
100
+ let presetSource = 'request';
101
+ if (sessionId) {
102
+ try {
103
+ const session = ctx.sessions.get(sessionId);
104
+ if (session && !cwd) cwd = ctx.workingDirectory.get(session);
105
+ } catch {}
106
+ try {
107
+ const obs = await ctx.sessionQuery.observeSession(sessionId);
108
+ preset = obs?.projections?.values?.agentPreset;
109
+ presetSource = 'projection';
110
+ } catch {
111
+ const header = ctx.sessionQuery.stat?.(sessionId) ?? ctx.sessions.info?.(sessionId);
112
+ if (header) { preset = header.agentPreset; presetSource = 'header(stale-possible)'; }
113
+ }
114
+ }
115
+ if (!cwd) cwd = process.cwd();
116
+ const projectRoot = findProjectRoot(cwd);
117
+ const presetWarn = preset && !EFFECTIVE_PRESETS.has(preset)
118
+ ? `当前 preset「${preset}」未挂载技能注入,切换技能集不会改变可见技能(§10.2 #1)`
119
+ : null;
120
+ return { cwd, projectRoot, preset, presetSource, presetWarn, rootDrift: projectRoot !== cwd };
121
+ }
122
+
123
+ /** 插件/Preset 提供技能(灰色只读分区):运行时注入、不在生效区盘上,插件唯一可见
124
+ * 口径是平台 skills 服务清单(探针事实 probe/skill-set-probe)。服务缺席 → null(不可知)。 */
125
+ async _providerEntries(projectRoot, { effectiveNames = [], managedEntries = {}, residentNames = null } = {}) {
126
+ if (!projectRoot) return null;
127
+ try {
128
+ const skills = this.ctx.get('skills');
129
+ const resident = residentNames ?? sets.loadResident(roots).skills ?? [];
130
+ return await providerSkills(
131
+ { skillsService: skills, projectRoot, managedEntries },
132
+ { effectiveNames, residentNames: resident },
133
+ );
134
+ } catch (e) {
135
+ this.ctx.logger.warn(`skill-set-manager:插件/Preset 技能枚举不可用: ${e?.message ?? e}`);
136
+ return null;
137
+ }
138
+ }
139
+
140
+ /**
141
+ * 面板/设置/右栏共用的只读快照(架构评审候选 4):
142
+ * - **零写**:索引自愈(review m3)照旧排队执行,但不再 await 一次 store 写;
143
+ * - **不重复读**:常驻名单在本次快照里只读一次,provider 组合与灰行判定复用同一份;
144
+ * - 面板走 panelSnapshot、设置/右栏走 state——两个名字是同一组合的显式契约,将来要分叉再各自加字段。
145
+ */
146
+ async _snapshot(req) {
147
+ const loc = await this.locate(req);
148
+ const binding = readBinding(loc.projectRoot);
149
+ const set = binding?.setSlug ? sets.loadSet(roots, binding.setSlug) : null;
150
+ const eff = binding?.setSlug ? sets.effectiveNames(roots, binding.setSlug) : { names: [], missing: [] };
151
+ const sc = selfCheck(roots, loc.projectRoot);
152
+ const managed = readManaged(loc.projectRoot);
153
+ const residentNames = sets.loadResident(roots).skills;
154
+ const store = await storeOf();
155
+ // 插件/Preset 分区:排除口径 = 生效清单(常驻 ∪ 集)+ 托管台账 + 常驻名单(库名不排除,见 providerSkills 注释)。
156
+ const providerEntries = await this._providerEntries(loc.projectRoot, {
157
+ effectiveNames: eff.names, managedEntries: managed?.entries ?? {}, residentNames,
158
+ });
159
+ // 索引自愈(review m3):面板每打开一次该项目即入索引——仅带会话的定位才入索引,host cwd 兜底行是垃圾(review n5)。
160
+ // 只排队不等待:写得慢/失败不再拖慢首屏,也不改变 m3 语义。
161
+ if (req?.sessionId && loc.projectRoot) {
162
+ Promise.resolve(store.put('bindings', projectKey(loc.projectRoot), { projectRoot: loc.projectRoot })).catch(() => {});
163
+ }
164
+ return {
165
+ ...loc,
166
+ sessionId: req?.sessionId ?? null,
167
+ binding,
168
+ set,
169
+ sets: sets.listSets(roots),
170
+ library: (await this.libraryList()).library,
171
+ effective: eff,
172
+ resident: residentNames,
173
+ residentForeign: dataPlane.residentForeign(roots, { residentNames }), // 灰行判定源:常驻区名单外条目(设计 §6.4)
174
+ unmanaged: providerEntries, // 灰段数据源:插件/Preset 提供(不受技能集管控);null = 不可知
175
+ residentTarget: roots.globalResidentDirs[0], // 弹窗「去设置管理」文案指向
176
+ selfCheck: { ok: sc.ok, frozen: sc.frozen, unbound: sc.unbound, missing: sc.missing, extra: sc.extra, foreign: sc.foreign, brokenLinks: sc.brokenLinks, detail: sc.detail },
177
+ managed: managed?.entries ?? {},
178
+ sessionOverride: managed?.sessionOverride ?? null, // 覆盖明细透出(用户 2026-10-26:被剔项从三区消失无处发现/还原)
179
+ sessionOverrideActive: (managed?.sessionOverride?.added?.length ?? 0) + (managed?.sessionOverride?.removed?.length ?? 0) > 0,
180
+ undoAvailable: !!(await store.get('undo', projectKey(loc.projectRoot))),
181
+ };
182
+ }
183
+
184
+ /** 面板首屏的读契约(零写快照)。 */
185
+ async panelSnapshot(req) { return this._snapshot(req); }
186
+
187
+ /** 设置页/右栏的宽口径(同一零写快照;诊断另有 diagnoseRun)。 */
188
+ async state(req) { return this._snapshot(req); }
189
+
190
+ async listSets() {
191
+ return { sets: sets.listSets(roots), resident: sets.loadResident(roots) };
192
+ }
193
+
194
+ async saveSet(req) {
195
+ return sets.saveSet(roots, req.set);
196
+ }
197
+
198
+ async deleteSet(req) {
199
+ const store = await storeOf();
200
+ const affected = [];
201
+ const push = (pr) => { if (pr && readBinding(pr)?.setSlug === req.slug && !affected.includes(pr)) affected.push(pr); };
202
+ // P1a:bindings 索引全量推导(§7.8 冻结红标仍由 selfCheck 兜底)
203
+ for (const pr of lifecycle.findBoundProjects(await this._candidateProjects(), req.slug)) push(pr);
204
+ for (const table of ['pending', 'undo']) {
205
+ for (const key of await store.keys(table)) {
206
+ const rec = await store.get(table, key);
207
+ push(rec?.projectRoot);
208
+ }
209
+ }
210
+ const deleted = sets.deleteSet(roots, req.slug);
211
+ return { deleted, affectedProjects: affected };
212
+ }
213
+
214
+ async renameSet(req) {
215
+ return sets.renameSet(roots, req.slug, req.name);
216
+ }
217
+
218
+ async copySet(req) {
219
+ return sets.copySet(roots, req.slug, req.name);
220
+ }
221
+
222
+ async setResident(req) {
223
+ return await gate.mutate(async () => {
224
+ sets.saveResident(roots, req.names ?? []);
225
+ return await syncResident(roots); // 常驻链接增删在 `~/.agents/skills/`,也在生效区,菜单必须跟(失效事件由闸门补发)
226
+ });
227
+ }
228
+
229
+ async saveAsFromEffective(req) {
230
+ const loc = await this.locate(req);
231
+ const binding = readBinding(loc.projectRoot);
232
+ // 显式 names = 弹窗勾选草稿(候选区已排除常驻,原样保存);
233
+ // 隐式 = 生效清单兜底,须剔常驻(用户 2026-10-26:全局技能不该被另存进项目集合)
234
+ const explicit = Array.isArray(req.names);
235
+ const names = explicit ? req.names : sets.effectiveNames(roots, binding?.setSlug).names;
236
+ return sets.saveAsSet(roots, { name: req.name, names, excludeResident: !explicit });
237
+ }
238
+
239
+ async exportSet(req) {
240
+ return sets.exportSet(roots, req.slug);
241
+ }
242
+
243
+ async importSets(req) {
244
+ return sets.importSets(roots, req.payload);
245
+ }
246
+
247
+ /** 导入预览(只读):缺哪些技能、有没有 pin 可装、显示名会不会撞车(§5.6 两步导入第一步)。 */
248
+ async importPreview(req) {
249
+ return sets.importPreview(roots, req.payload);
250
+ }
251
+
252
+ /**
253
+ * 导入落盘(§5.6):三选一由 client 传 choices;「按 pin 安装」在这里走与
254
+ * installApply **完全同一条**稀疏拉取 + installSkills 路径(§14 单一实现),
255
+ * 插件自己不擅自联网——只有 choices 选了 install 才拉。
256
+ */
257
+ async importApply(req) {
258
+ return await gate.run('importApply', { target: req.payload?.name ?? null }, () => this._importApply(req));
259
+ }
260
+
261
+ async _importApply(req) {
262
+ const tmps = [];
263
+ const notes = [];
264
+ try {
265
+ const res = await sets.importApply(roots, req.payload, {
266
+ choices: req.choices ?? {},
267
+ install: async (name, pin) => {
268
+ await this._netGate(); // 只有 choices 选了 install 才联网(§14 口径),联网先过代理预检
269
+ const { canonical, spec } = resolveRepoSource(pin.source); // 解析一次:canonical 入 manifest,spec 供 fetch(owner 不带 github: 前缀,评审 C1)
270
+ if (spec.owner.includes(':')) throw new Error(`来源解析异常:owner="${spec.owner}" 仍带前缀(按 pin 安装会拼出错误 remote URL)`);
271
+ // 2026-11-17 加固:同 installApply 走持久缓存底 + 硬超时 + 失败留痕;url 覆盖夹具仍 tmp 隔离
272
+ const dir = req.url ? fs.mkdtempSync(path.join(os.tmpdir(), 'ssm-pin-')) : cacheDirFor(roots, spec);
273
+ if (req.url) tmps.push(dir);
274
+ const got = await fetchRepo(spec, { dir, timeoutMs: 180000, failLog: roots.failLog, ...(req.url ? { url: req.url } : {}) });
275
+ const rows = await installSkills(roots, {
276
+ source: canonical,
277
+ commit: got.commit,
278
+ skillsDir: got.skillsDir,
279
+ names: [name],
280
+ overwrite: false,
281
+ backup: async (n) => bk.snapshot(roots, n),
282
+ });
283
+ const row = rows.find((r) => r.name === name);
284
+ if (!row?.ok) throw new Error(`按 pin 安装失败:${row?.reason ?? '上游未返回该技能'}`);
285
+ if (pin.commit && pin.commit !== got.commit)
286
+ notes.push(`${name}: pin 记的是 ${String(pin.commit).slice(0, 7)},上游 HEAD 是 ${got.commit.slice(0, 7)}——已按 HEAD 装入(稀疏拉取不保证能取任意 SHA)`);
287
+ registerLibrary(roots);
288
+ return { commit: got.commit };
289
+ },
290
+ });
291
+ if (notes.length) res.warnings.push(...notes);
292
+ return res;
293
+ } finally {
294
+ for (const t of tmps) { try { fs.rmSync(t, { recursive: true, force: true }); } catch {} }
295
+ }
296
+ }
297
+
298
+ /** 绑定 + 直接写 + 幂等补 .gitignore 署名行(§7.6)。顺序不变式见 provision.js(唯一绑定写点)。 */
299
+ async bind(req) {
300
+ const loc = await this.locate(req);
301
+ if (!sets.loadSet(roots, req.slug) && req.slug !== sets.RESIDENT_SLUG) throw new Error(`技能集不存在: ${req.slug}`);
302
+ return await bindProject(roots, loc.projectRoot, req.slug, {
303
+ gitignore: config.gitignoreLine,
304
+ // P1a 索引:deleteSet/uninstall 全量推导。手动绑定失败即如实失败,不静默吞
305
+ index: async (projectRoot) => { await (await storeOf()).put('bindings', projectKey(projectRoot), { projectRoot }); },
306
+ // 切集落盘即让 `/` 菜单重新拉取(switchSet/undo 之外的入口也覆盖:bind 是唯一绑定写点)
307
+ onCommitted: () => emitSlashCacheClear(),
308
+ });
309
+ }
310
+
311
+ /** 切换:先压一次性 undo 快照,再 bind(§5.2 撤销入口)。 */
312
+ async switchSet(req) {
313
+ const store = await storeOf();
314
+ const loc = await this.locate(req);
315
+ await pushUndo(store, roots, loc.projectRoot);
316
+ const bound = await this.bind(req);
317
+ return { ...bound, undoAvailable: true };
318
+ }
319
+
320
+ async undoSwitch(req) {
321
+ const store = await storeOf();
322
+ const loc = await this.locate(req);
323
+ const restored = await gate.mutate(() => applyUndo(store, roots, loc.projectRoot));
324
+ return { restored };
325
+ }
326
+
327
+ async startOverride(req) {
328
+ const store = await storeOf();
329
+ const loc = await this.locate(req);
330
+ // 未绑定态「勾选即起盘」也写 `.agents/skills/`(2026-10-28),菜单同样要跟
331
+ const snap = await gate.mutate(() => startOverride(store, roots, loc.projectRoot, { add: req.add ?? [], remove: req.remove ?? [], sessionId: req.sessionId ?? null }));
332
+ return { snapshot: snap };
333
+ }
334
+
335
+ async endOverride(req) {
336
+ const store = await storeOf();
337
+ const loc = await this.locate(req);
338
+ const ended = await endOverride(store, roots, loc.projectRoot);
339
+ if (ended) gate.touch();
340
+ return { ended };
341
+ }
342
+
343
+ /** 库登记 + 候选清单(建集勾选数据源)+ P1a manifest 摘要字段。 */
344
+ async libraryList() {
345
+ registerLibrary(roots);
346
+ const library = [];
347
+ let names;
348
+ try { names = fs.readdirSync(roots.libraryRoot); } catch { names = []; }
349
+ for (const n of names) {
350
+ if (n.startsWith('.')) continue;
351
+ const dir = path.join(roots.libraryRoot, n);
352
+ const mf = readManifest(dir);
353
+ // 「本地改动」走 core 的 stats 廉价口径:stat 未变即不读盘。旧口径每次打开面板/设置页都
354
+ // 把整库 sha256 一遍(本机实测 96 技能 11386 文件 451.8MB ≈ 1.5s,且是同步 fs,
355
+ // 期间 host 事件循环整个卡住),这就是「点技能集要等 2~3 秒」的根因。
356
+ const modified = localModified(dir, mf);
357
+ if (mf && !mf.stats) backfillManifestStats(dir, mf); // 升级前的旧 manifest 无 stats:补一次,之后一律走快路径
358
+ const hasSkillMd = fs.existsSync(path.join(dir, 'SKILL.md'));
359
+ library.push({
360
+ name: n,
361
+ source: mf?.source ?? 'unknown',
362
+ commit: mf?.commit ?? null,
363
+ hasSkillMd,
364
+ skillMd: hasSkillMd ? path.join(dir, 'SKILL.md') : null, // 右栏点击打开的绝对路径(P1b-T0)
365
+ managed: !!mf,
366
+ localModified: modified,
367
+ backupCount: bk.listBackups(roots, n).length,
368
+ });
369
+ }
370
+ // P3:读时对账翻译缓存(缓存非真相源,§6.1)+ 三字段 decorate;autoTranslate 默认关 = 钩子不触发
371
+ let cache = {};
372
+ try {
373
+ const store = await storeOf();
374
+ const r = await dataPlane.libraryView(roots, store, {
375
+ autoTranslate: config.autoTranslate,
376
+ onPending: (names) => { void this._translate(names).catch(() => {}); },
377
+ });
378
+ cache = r.cache;
379
+ } catch (e) { ctx.logger.warn(`skill-set-manager 翻译对账失败(列表照常无中文列): ${e?.message ?? e}`); }
380
+ return { library: decorate(library, cache) };
381
+ }
382
+
383
+ /** 认领来源(§8.1):本地技能补 manifest(认领时的盘上内容即基线);source='unknown' 撤认领回落本地态。 */
384
+ async claimSource(req) {
385
+ const mf = claimSource(roots, { name: req.name, source: req.source, commit: req.commit ?? null });
386
+ return { name: mf.name, source: mf.source, commit: mf.commit, files: Object.keys(mf.files).length, dirDigest: mf.dirDigest };
387
+ }
388
+
389
+ // ---- P1a:GitHub 安装 / 升级 / 卸载 / 回收站(全部薄包装 core,同一实现) ----
390
+
391
+ /**
392
+ * manifest.source = github:owner/repo[/subpath] → 稀疏拉取(2026-11-17 加固):
393
+ * 无 urlOverride 走持久上游缓存底(cacheDirFor,增量 fetch,无需 tmp 回收——
394
+ * GLOSSARY「上游缓存」:每次仍真 fetch 最新);urlOverride(file:// 夹具)仍走
395
+ * 独立 tmp 目录批量回收,夹具互不污染、也不污染生产缓存。
396
+ * 检查路径超时 120s(活体实测 2026-11-17:vibe-knowledge 的 checkout blob 层经 PAC 代理
397
+ * 实测 >60s,60s 必红;吊死才翻倍,常态增量不受影响)。
398
+ */
399
+ _fetchFor(tmpDirs, urlOverride = null, timeoutMs = 120000) {
400
+ return async (source) => {
401
+ // 单一口径走 core source.js:手拆 '/' 曾把 clone 地址尾部的 `.git` 当仓库名,
402
+ // 拼出 owner/repo.git.git → 远端「Repository not found」(用户报告 2026-10-26,检查更新炸)
403
+ const { spec } = resolveRepoSource(source);
404
+ if (urlOverride) {
405
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ssm-up-'));
406
+ tmpDirs.push(tmpDir);
407
+ return fetchRepo(spec, { dir: tmpDir, url: urlOverride, timeoutMs, failLog: roots.failLog });
408
+ }
409
+ return fetchRepo(spec, { dir: cacheDirFor(roots, spec), timeoutMs, failLog: roots.failLog });
410
+ };
411
+ }
412
+
413
+ /**
414
+ * 代理预检(2026-11-17 加固):git 实际会走的代理(env → git 全局配置)没人监听,
415
+ * 当场报人话错——Watt Toolkit 没启动时 git 指死 26561 直接 refused,不再吊死或
416
+ * 抛 git 乱码(gitnet.probeProxy 口径;未配代理 = 直连环境,直接放行)。
417
+ */
418
+ async _netGate() {
419
+ const { dead } = await probeProxy();
420
+ if (dead) throw new Error(`本机代理 ${dead} 无响应——Watt Toolkit 代理未监听,启动它后重试`);
421
+ }
422
+
423
+ async installApply(req) {
424
+ return await gate.run('installApply', { target: req.spec }, async () => {
425
+ await this._netGate();
426
+ const spec = parseRepoSpec(req.spec);
427
+ const dir = req.url ? fs.mkdtempSync(path.join(os.tmpdir(), 'ssm-install-')) : cacheDirFor(roots, spec);
428
+ try {
429
+ // req.url:file:// 或私仓镜像覆盖(活体验证夹具也走这里)
430
+ const got = await fetchRepo(spec, { dir, timeoutMs: 180000, failLog: roots.failLog, ...(req.url ? { url: req.url } : {}) });
431
+ const results = await installSkills(roots, {
432
+ source: `github:${spec.owner}/${spec.repo}${spec.subpath ? `/${spec.subpath}` : ''}`,
433
+ commit: got.commit,
434
+ skillsDir: got.skillsDir,
435
+ names: req.names ?? null,
436
+ overwrite: !!req.overwrite,
437
+ backup: async (name) => bk.snapshot(roots, name),
438
+ });
439
+ registerLibrary(roots);
440
+ return { commit: got.commit, results };
441
+ } finally {
442
+ if (req.url) { try { fs.rmSync(dir, { recursive: true, force: true }); } catch {} }
443
+ }
444
+ });
445
+ }
446
+
447
+ async updateCheck(req) {
448
+ return await gate.run('updateCheck', { target: req.name, mutates: false }, async () => {
449
+ await this._netGate();
450
+ const tmps = [];
451
+ try { return await updates.checkUpdate(roots, req.name, { fetch: this._fetchFor(tmps, req.url ?? null, 120000) }); }
452
+ finally { for (const t of tmps) { try { fs.rmSync(t, { recursive: true, force: true }); } catch {} } }
453
+ });
454
+ }
455
+
456
+ /** 批量检查更新(GLOSSARY「批量检查更新」):按来源仓库分组每仓一拉;sources 子集 = 重试失败仓库。 */
457
+ async updateCheckAll(req) {
458
+ return await gate.run('updateCheckAll', { mutates: false }, async () => {
459
+ await this._netGate();
460
+ const tmps = [];
461
+ try {
462
+ return await updates.checkUpdateAll(roots, {
463
+ fetch: this._fetchFor(tmps, req.url ?? null, 120000),
464
+ sources: req.sources ?? null,
465
+ });
466
+ } finally { for (const t of tmps) { try { fs.rmSync(t, { recursive: true, force: true }); } catch {} } }
467
+ });
468
+ }
469
+
470
+ /** 清空上游缓存(逃生口:缓存坏了/换网络通道):删底即下次自然重建,幂等。 */
471
+ async cacheClear() {
472
+ try { fs.rmSync(roots.cacheDir, { recursive: true, force: true }); } catch {}
473
+ return { cleared: true };
474
+ }
475
+
476
+ async updateApply(req) {
477
+ return await gate.run('updateApply', { target: req.name }, async () => {
478
+ await this._netGate();
479
+ const tmps = [];
480
+ try { return await updates.applyUpdate(roots, req.name, { fetch: this._fetchFor(tmps, req.url ?? null, 180000), backup: async (n) => bk.snapshot(roots, n) }); }
481
+ finally { for (const t of tmps) { try { fs.rmSync(t, { recursive: true, force: true }); } catch {} } }
482
+ });
483
+ }
484
+
485
+ /** 候选项目集 = bindings 索引 ∪ pending/undo 记录(旧版遗留兜底)。 */
486
+ async _candidateProjects() {
487
+ const store = await storeOf();
488
+ const out = new Set();
489
+ for (const key of await store.keys('bindings')) {
490
+ const rec = await store.get('bindings', key);
491
+ if (rec?.projectRoot) out.add(rec.projectRoot);
492
+ }
493
+ for (const table of ['pending', 'undo']) {
494
+ for (const key of await store.keys(table)) {
495
+ const rec = await store.get(table, key);
496
+ if (rec?.projectRoot) out.add(rec.projectRoot);
497
+ }
498
+ }
499
+ return [...out];
500
+ }
501
+
502
+ async uninstallSkill(req) {
503
+ return await gate.run('uninstallSkill', { target: req.name }, async () => {
504
+ const res = await lifecycle.uninstallSkill(roots, { name: req.name, bindings: await this._candidateProjects() });
505
+ // M4(终审 2026-10-26):卸载常驻技能 → 常驻名单同步剔除 + 回收链接(否则幽灵名灰行失真、启动 syncResident 反复告警)。
506
+ try {
507
+ if (dropResidentName(roots, req.name)) await syncResident(roots);
508
+ } catch (e) { ctx.logger.warn(`skill-set-manager 常驻名单剔除失败: ${e?.message ?? e}`); }
509
+ // 失效事件由闸门在成功后统一补发(queueMicrotask 合并,与 syncResident 重入也不会双发)
510
+ return res;
511
+ });
512
+ }
513
+
514
+ async backupsList(req) {
515
+ return { backups: bk.listBackups(roots, req.name) };
516
+ }
517
+
518
+ async backupRestore(req) {
519
+ return bk.restore(roots, req.name, req.dir);
520
+ }
521
+
522
+ // ---- P1a:诊断(§9 只读 + 两类可修复) ----
523
+
524
+ _workspaceScopeInstalled() {
525
+ // profile 目录逐个 package.json 查依赖(profile 名对插件不可见——不猜 desktop)。
526
+ try {
527
+ for (const p of fs.readdirSync(path.join(roots.dshHome, 'profiles'))) {
528
+ try {
529
+ const pkg = JSON.parse(fs.readFileSync(path.join(roots.dshHome, 'profiles', p, 'package.json'), 'utf8'));
530
+ if (Object.keys(pkg.dependencies ?? {}).some((d) => d.includes('dsh-workspace-scope'))) return true;
531
+ } catch {}
532
+ }
533
+ } catch {}
534
+ return false;
535
+ }
536
+
537
+ async diagnoseRun(req) {
538
+ // 无活动会话时项目面如实置空,不得拿 host 进程 cwd 冒充(review M2)
539
+ const loc = req?.sessionId ? await this.locate(req) : { cwd: null, projectRoot: null };
540
+ const providerEntries = loc.projectRoot
541
+ ? await this._providerEntries(loc.projectRoot, {
542
+ effectiveNames: readBinding(loc.projectRoot)?.setSlug
543
+ ? sets.effectiveNames(roots, readBinding(loc.projectRoot).setSlug).names : [],
544
+ managedEntries: readManaged(loc.projectRoot)?.entries ?? {},
545
+ })
546
+ : null;
547
+ return diagnose(roots, {
548
+ projectRoot: loc.projectRoot,
549
+ cwd: loc.cwd ?? process.cwd(),
550
+ workspaceScopeInstalled: this._workspaceScopeInstalled(),
551
+ providerEntries,
552
+ });
553
+ }
554
+
555
+ /** 自动修复①(§9):按托管清单回收失效链接后按当前集重建。
556
+ * 死 stub 判定用 entryKind(stat 失败即 missing,含死链);摘除走 linkx.removeEntry
557
+ * (Windows 死 junction 的 ENOTDIR/EPERM 兜底,review m9);flat 条目按 `<name>.md` 口径(m7)。 */
558
+ async reclaimDeadLinks(req) {
559
+ if (!req?.sessionId) throw new Error('无活动会话:无法定位项目,请先在对话页打开会话(review M2)');
560
+ const loc = await this.locate(req);
561
+ const managed = readManaged(loc.projectRoot) ?? { entries: {} };
562
+ const reclaimed = [];
563
+ const warnings = [];
564
+ const skillsDir = projectSkillsDir(loc.projectRoot);
565
+ for (const name of Object.keys(managed.entries)) {
566
+ const p = path.join(skillsDir, managed.entries[name]?.flat ? `${name}.md` : name);
567
+ if (entryKind(p) !== 'missing') continue;
568
+ try { removeEntry(p); } catch (e) { warnings.push(`${name}: 死链摘除失败 ${e?.message ?? e}`); continue; } // 摘除失败不动台账
569
+ delete managed.entries[name];
570
+ reclaimed.push(name);
571
+ }
572
+ if (reclaimed.length) writeManaged(loc.projectRoot, managed);
573
+ let rebuilt = null;
574
+ const slug = readBinding(loc.projectRoot)?.setSlug;
575
+ if (slug) rebuilt = await converge(roots, loc.projectRoot, slug);
576
+ if (reclaimed.length || rebuilt) gate.touch(); // 摘死链 + 重建都可能改生效清单
577
+ return { reclaimed, rebuilt, warnings };
578
+ }
579
+
580
+ /** 自动修复②(§9 / review minor#2 转正,M1 后 planEffective 会把外删条目带回 add):按当前集重建。 */
581
+ async rebuildManaged(req) {
582
+ if (!req?.sessionId) throw new Error('无活动会话:无法定位项目,请先在对话页打开会话(review M2)');
583
+ const loc = await this.locate(req);
584
+ const slug = readBinding(loc.projectRoot)?.setSlug;
585
+ if (!slug) throw new Error('未绑定技能集,无从重建');
586
+ return await gate.mutate(async () => {
587
+ // 台账失配态下 add/remove/keep 三项皆空,理由只存在于 plan.warnForeign/warnMissing:
588
+ // claimHint 让文案带「接管」指引(活体复盘 2026-10-27:前端此前直接丢弃返回值)。
589
+ const { plan, applied, warnings } = await converge(roots, loc.projectRoot, slug, { claimHint: true });
590
+ return { applied, warnings, plan }; // 重建改了生效清单,失效事件由闸门补发(空转时也无害:幂等)
591
+ });
592
+ }
593
+
594
+ /**
595
+ * 接管(认领)台账失配的自家链接:只把盘上已在、名字在本集里的链接补回台账,绝不动条目本身。
596
+ * 台账被上一代快照整体覆盖后(applyUndo 语义)planEffective 会把它全体判为外来并跳过,
597
+ * 「重新生成」从此空转——本方法就是那条丢失的恢复通道(活体实锤 2026-10-27:16 链接 / 台账 0 条)。
598
+ */
599
+ async claimForeign(req) {
600
+ if (!req?.sessionId) throw new Error('无活动会话:无法定位项目,请先在对话页打开会话(review M2)');
601
+ const loc = await this.locate(req);
602
+ return await claimForeign(roots, loc.projectRoot);
603
+ }
604
+
605
+ // ---- P1a:迁移向导(§8.2,ledger 落 storageDomain) ----
606
+
607
+ _migrateLedger() {
608
+ return {
609
+ load: async () => (await storeOf()).get('migration', 'ledger'),
610
+ save: async (data) => { await (await storeOf()).put('migration', 'ledger', data); },
611
+ };
612
+ }
613
+
614
+ async migratePreview() {
615
+ return migrate.preview(roots);
616
+ }
617
+
618
+ async migrateApply() {
619
+ return await gate.run('migrateApply', {}, async () => {
620
+ const pv = migrate.preview(roots);
621
+ return await migrate.apply(roots, { moves: pv.moves, ledger: this._migrateLedger() });
622
+ });
623
+ }
624
+
625
+ async migrateUndo() {
626
+ return await gate.run('migrateUndo', {}, () => migrate.undo(roots, { ledger: this._migrateLedger() }));
627
+ }
628
+
629
+ // ---- P3:~/.agents/skills 存量迁移(设计 §5.7/§6.6;ledger 独立域,不与旧向导互踩) ----
630
+
631
+ _migrateAgentsLedger() {
632
+ return {
633
+ load: async () => (await storeOf()).get('migrate_agents', 'ledger'), // 表名禁连字符(fallback/domain 两侧同款约束,活体实锤)
634
+ save: async (data) => { await (await storeOf()).put('migrate_agents', 'ledger', data); },
635
+ };
636
+ }
637
+
638
+ async migrateAgentsPreview() {
639
+ return migrate.previewAgents(roots);
640
+ }
641
+
642
+ async migrateAgentsApply() {
643
+ return await gate.run('migrateAgentsApply', {}, () => migrate.applyAgents(roots, { ledger: this._migrateAgentsLedger() }));
644
+ }
645
+
646
+ async migrateAgentsUndo() {
647
+ return await gate.run('migrateAgentsUndo', {}, () => migrate.undoAgents(roots, { ledger: this._migrateAgentsLedger() }));
648
+ }
649
+
650
+ // ---- P3:翻译数据面(设计 §6.1/§5.8——llm 主路由,translator 在场才兜底) ----
651
+
652
+ /** 待翻清单(M2 终审 2026-10-26):pending + failed 都返回——failed 同哈希不自愈但 UI 须有重试入口(AC#2)。 */
653
+ async translatePending() {
654
+ const store = await storeOf();
655
+ const r = await dataPlane.reconcileLibrary(roots, store);
656
+ const failed = Object.keys(r.cache).filter((name) => r.cache[name]?.status === 'failed' && r.cache[name]?.en).sort();
657
+ return {
658
+ pending: r.pending.map((name) => ({ name, en: r.cache[name]?.en ?? null })),
659
+ failed: failed.map((name) => ({ name, en: r.cache[name]?.en ?? null })),
660
+ autoTranslate: config.autoTranslate,
661
+ };
662
+ }
663
+
664
+ /**
665
+ * 模型面(rc.3 探针实锤 2026-10-26:listModels 改位置字符串参数,对象参数被整体 stringify 成
666
+ * "[object Object]" 炸 NO_ADAPTER;rc.2 则是 {providerId} 对象参数——双签名兼容)。
667
+ * 全部调用 await Promise.resolve 收 rejection、逐 provider 隔离、refId 归一,绝不逃到 Remote 面。
668
+ */
669
+ async translateModels() {
670
+ let current = null;
671
+ const options = [];
672
+ const llm = ctx.get('llm');
673
+ const listModels = async (pid) => {
674
+ try { return await Promise.resolve(llm.listModels(pid)); } // rc.3:位置字符串参数
675
+ catch (e1) {
676
+ try { return await Promise.resolve(llm.listModels({ providerId: pid })); } // rc.2:对象参数
677
+ catch { throw e1; }
678
+ }
679
+ };
680
+ try { current = normalizeSel(await Promise.resolve(ctx.get('agentDefaultModel')?.currentSelection?.() ?? null)); } catch (e) { ctx.logger.warn(`skill-set-manager 当前模型读取失败: ${e?.message ?? e}`); }
681
+ try {
682
+ const provs = await Promise.resolve(llm?.listProviders?.() ?? []);
683
+ for (const p of Array.isArray(provs) ? provs : []) {
684
+ const pid = refId(p);
685
+ if (!pid) continue;
686
+ const pname = typeof p?.name === 'string' && p.name.trim() ? p.name.trim() : pid;
687
+ let models = [];
688
+ try { models = await listModels(pid); } catch (e) { ctx.logger.warn(`skill-set-manager provider ${pid} 模型列表跳过: ${e?.message ?? e}`); continue; } // 单 provider 失败只损失该 provider
689
+ for (const m of Array.isArray(models) ? models : []) {
690
+ const mid = refId(m);
691
+ if (!mid) continue;
692
+ const mname = typeof m?.name === 'string' && m.name.trim() ? m.name.trim() : mid;
693
+ options.push({ provider: pid, model: mid, label: `${pname} · ${mname}` });
694
+ }
695
+ }
696
+ } catch (e) { ctx.logger.warn(`skill-set-manager 模型列表失败: ${e?.message ?? e}`); }
697
+ return { current, options };
698
+ }
699
+
700
+ /** llm 单条调用:归一后 provider/model 必须是字符串(rc.3 教训:对象进 stream 即崩);只拼非 reasoning delta。 */
701
+ _callLlmTranslate(sel) {
702
+ const llm = ctx.get('llm');
703
+ const s = normalizeSel(sel);
704
+ if (!llm || !s) return null;
705
+ return async (enOrArr) => { // chunk 拼接批收 en 数组、逐条收字符串(runBatch 两种形态都投喂)
706
+ let cur = null;
707
+ let text = '';
708
+ for await (const ev of llm.stream({ provider: s.provider, model: s.model, messages: [{ role: 'user', content: [{ type: 'text', text: buildLlmPrompt(Array.isArray(enOrArr) ? enOrArr : [enOrArr]) }] }] })) {
709
+ if (ev.type === 'block-start') cur = ev.blockType ?? null;
710
+ else if (typeof ev.type === 'string' && ev.type.endsWith('-delta') && cur !== 'reasoning' && typeof ev.text === 'string') text += ev.text;
711
+ else if (ev.type === 'finish' && ev.reason && ev.reason !== 'stop' && !text) throw new Error(`llm finish: ${ev.reason}`);
712
+ }
713
+ return text;
714
+ };
715
+ }
716
+
717
+ _callMtTranslate() {
718
+ const mt = ctx.get('translator'); // 本机 live profile 未挂载(探针证实)→ null = 无兜底,LLM 失败逐条 failed
719
+ if (!mt) return null;
720
+ return async (en) => {
721
+ const r = await mt.translate?.(en, { to: 'zh' }); // 形状未经实证(服务缺席),抛错即该条 failed
722
+ return typeof r === 'string' ? r : r?.text ?? null;
723
+ };
724
+ }
725
+
726
+ async _translate(names, { provider = null, model = null } = {}) {
727
+ const all = Array.isArray(names) ? names : [];
728
+ const fresh = all.filter((n) => !trInflight.has(n)); // M1 互斥:已在翻的条目跳过(手动批与 autoTranslate 后台批可叠加时不重复出网)
729
+ const skipped = all.length - fresh.length;
730
+ if (!fresh.length) return { done: [], failed: [], skipped };
731
+ fresh.forEach((n) => trInflight.add(n));
732
+ try {
733
+ const store = await storeOf();
734
+ let sel = null;
735
+ try { sel = normalizeSel(provider && model ? { provider, model } : (await Promise.resolve(ctx.get('agentDefaultModel')?.currentSelection?.() ?? null))); } catch (e) { ctx.logger.warn(`skill-set-manager 翻译模型选择失败: ${e?.message ?? e}`); }
736
+ const r = await dataPlane.translateRunCore({ roots, store, names: fresh, callLlm: this._callLlmTranslate(sel), callMt: this._callMtTranslate() });
737
+ return { done: r.done, failed: r.failed, skipped: r.skipped + skipped };
738
+ } finally {
739
+ fresh.forEach((n) => trInflight.delete(n));
740
+ }
741
+ }
742
+
743
+ async translateRun(req) {
744
+ // 兜底:RPC 内任何未预期抛出不得逃到 Remote 面(2026-10-26 实锤:NO_ADAPTER 同步抛经
745
+ // webServer 兜底通道成为 unhandled rejection,直接崩 host 进程)。
746
+ try {
747
+ return await this._translate(Array.isArray(req?.names) ? req.names : [], { provider: req?.provider ?? null, model: req?.model ?? null });
748
+ } catch (e) {
749
+ ctx.logger.warn(`skill-set-manager 批量翻译失败: ${e?.message ?? e}`);
750
+ return { done: [], failed: (Array.isArray(req?.names) ? req.names : []).map((name) => ({ name, error: String(e?.message ?? e) })), skipped: 0 };
751
+ }
752
+ }
753
+
754
+ /** 长任务态的 host 真相源(GLOSSARY「长任务」:进行中与结果不随界面关闭而消失)。 */
755
+ async longStatus() {
756
+ return gate.status();
757
+ }
758
+
759
+ /** 解绑(面板缺口):回收托管条目 + 删 binding/managed;gitignore 行保留。 */
760
+ async unbind(req) {
761
+ const loc = await this.locate(req);
762
+ return await gate.mutate(async () => {
763
+ const res = lifecycle.unbindProject(loc.projectRoot);
764
+ const store = await storeOf();
765
+ await store.delete('bindings', projectKey(loc.projectRoot));
766
+ await store.delete('pending', projectKey(loc.projectRoot)); // 解绑即撤掉临时覆盖标记:条目已回收,别留待还原的悬账
767
+ return { ...res, projectRoot: loc.projectRoot }; // 解绑回收了托管条目,菜单要跟着缩(闸门补发)
768
+ });
769
+ }
770
+ }
771
+
772
+ // @Remote 的显式等价:网关 source-mode 读取的 prototype marker(形状照抄 dsh-typert-protocol 源码
773
+ // addMarker/remoteMethods;加载器解析器不保证支持装饰符语法——ledger 裁定)。
774
+ // 方法清单 = 文件头 REMOTE_METHODS 单一来源(fetch 兜底通道共用)。
775
+ Object.defineProperty(SkillSetManagerRemote.prototype, '@deepseek-ai/dsh-typert-protocol/remote-methods', {
776
+ configurable: true,
777
+ value: Object.freeze({ version: 1, methods: Object.freeze(REMOTE_METHODS.map((name) => Object.freeze({ kind: 'direct', exportName: name }))) }),
778
+ });
779
+
780
+ const remote = new SkillSetManagerRemote(ctx);
781
+
782
+ // ---- P2:人机入口(§12 P2):slash 命令与模型工具只是同一批 remote.* 方法的
783
+ // 薄包装(§14「一个操作、两个调用方」)——这里只允许出现解析与文本渲染。 ----
784
+ const NO_SESSION = '无法定位项目:请在对话页打开会话后再调用(插件不拿 host 进程 cwd 冒充项目根)';
785
+ const HELP = '用法:/skill-set list | show | use <集名或显示名> [--yes] | undo';
786
+ const detailText = (d) => (Array.isArray(d) ? d.join(';') : String(d ?? ''));
787
+ const fmtList = (r, currentSlug) => {
788
+ const lines = [`技能集(${r.sets.length})|全局常驻 ${r.resident.skills.length} 项`];
789
+ for (const s of r.sets) lines.push(` ${s.slug === currentSlug ? '→' : ' '} ${s.slug} ${s.name}(${(s.skills || []).length})`);
790
+ if (!r.sets.length) lines.push(' (还没有技能集:面板「从当前生效清单另存为」是第一个集的主路径)');
791
+ lines.push(currentSlug ? `当前项目绑定:${currentSlug}` : '当前项目:未绑定技能集');
792
+ return lines.join('\n');
793
+ };
794
+ const fmtShow = (st) => {
795
+ const sc = st.selfCheck;
796
+ const lines = [
797
+ `项目根:${st.projectRoot}${st.rootDrift ? `(≠ 会话目录 ${st.cwd}:改动影响该仓库全部会话)` : ''}`,
798
+ `当前技能集:${st.set ? `${st.set.name}(${st.set.slug})` : '未绑定'}`,
799
+ `生效清单(${st.effective.names.length}):${st.effective.names.join('、') || '(空)'}`,
800
+ `全局常驻(${st.resident.length}):${st.resident.join('、') || '(无)'}`,
801
+ ...(st.unmanaged == null ? [] : [
802
+ `插件/Preset 提供(${st.unmanaged.length},不受技能集管控,切换技能集不移除):${st.unmanaged.map((e) => `${e.name}(${e.provider})`).join('、') || '(无)'}`,
803
+ ]),
804
+ sc.ok ? '自检:✓ 与盘上一致' : `自检:⚠ ${detailText(sc.detail) || '自算清单与盘上不一致'}`,
805
+ ];
806
+ if (st.sessionOverrideActive) lines.push('临时覆盖:本次会话进行中(会话结束即还原)');
807
+ if (sc.frozen) lines.push('冻结绑定:技能集已被删除,清单原样保留、插件不再驱动——改绑或重建。');
808
+ if (st.presetWarn) lines.push(`注意:${st.presetWarn}`);
809
+ lines.push('提示:`/` 命令列表在新会话前不会同步,以本命令与面板为准。');
810
+ return lines.join('\n');
811
+ };
812
+ const fmtSwitch = (set, res) => {
813
+ const a = res.applied ?? { added: 0, removed: 0, kept: 0 };
814
+ const w = res.warnings?.length ? `\n警告:${res.warnings.join(';')}` : '';
815
+ return `已切换:${set.name}(${set.slug})\n新增 ${a.added} / 移除 ${a.removed}(保留 ${a.kept}),下一轮请求即生效。${w}\n/skill-set undo 可撤销本次切换。`;
816
+ };
817
+ const DOCTOR_GROUPS = [['partition', '分区构成'], ['copies', '副本漂移'], ['dangling', '悬空引用'], ['deadLinks', '失效链接'], ['structure', '结构与 frontmatter'], ['env', '环境']];
818
+ const fmtDoctor = (d) => {
819
+ const lines = [];
820
+ for (const [key, label] of DOCTOR_GROUPS) {
821
+ const rows = d.groups?.[key] ?? [];
822
+ lines.push(`【${label}】${rows.length} 条`);
823
+ for (const r of rows.slice(0, 5)) lines.push(` ${r.level === 'info' ? '·' : '⚠'} ${r.what}${r.fix ? `|修复:${r.fix}` : ''}`);
824
+ if (rows.length > 5) lines.push(` …另 ${rows.length - 5} 条见设置页「诊断」页签`);
825
+ }
826
+ lines.push(`可自动修复:回收失效链接(${d.fixable?.reclaimDeadLinks?.count ?? 0} 条)与「按当前技能集重建」——两者都在面板或设置页诊断页签执行。`);
827
+ return lines.join('\n');
828
+ };
829
+
830
+ /** 命令面契约:处理器必须返回 {kind:'success'|'error'},不得让异常冒到宿主(评审 I3:技能集 JSON 可手改坏)。 */
831
+ const guard = (fn) => async (inv) => {
832
+ try { return await fn(inv); }
833
+ catch (e) { return { kind: 'error', text: `操作失败:${e?.message ?? e}` }; }
834
+ };
835
+
836
+ /** slug 或显示名——命令与工具同一匹配口径(评审 M7)。 */
837
+ const matchSets = (all, ref) => all.filter((s) => s.slug === ref || s.name === ref);
838
+
839
+ /** `/skill-set` 处理器:解析 → remote → 文本(无业务逻辑)。 */
840
+ async function runSkillSet(inv) {
841
+ const { action, arg, yes } = parseSkillSetLine(inv?.rawInput);
842
+ const sessionId = inv?.agent?.id ?? null;
843
+ if (action === 'list') {
844
+ const r = await remote.listSets();
845
+ const current = sessionId ? (await remote.state({ sessionId })).binding?.setSlug ?? null : null;
846
+ return { kind: 'success', text: fmtList(r, current) };
847
+ }
848
+ if (action === 'show') {
849
+ if (!sessionId) return { kind: 'error', text: NO_SESSION };
850
+ return { kind: 'success', text: fmtShow(await remote.state({ sessionId })) };
851
+ }
852
+ if (action === 'use') {
853
+ if (!sessionId) return { kind: 'error', text: NO_SESSION };
854
+ if (!arg) return { kind: 'error', text: `缺少技能集。\n${HELP}` };
855
+ const hit = matchSets((await remote.listSets()).sets, arg);
856
+ if (!hit.length) return { kind: 'error', text: `找不到技能集「${arg}」。/skill-set list 查看全部。` };
857
+ if (hit.length > 1) return { kind: 'error', text: `「${arg}」匹配多个集:${hit.map((s) => `${s.slug}(${s.name})`).join('、')}——请用 slug。` };
858
+ const st = await remote.state({ sessionId });
859
+ if (st.rootDrift && !yes)
860
+ return { kind: 'error', text: `项目根 ≠ 会话目录:本次会改 ${st.projectRoot},影响该仓库全部会话。\n确认无误后加 --yes 重试:/skill-set use ${hit[0].slug} --yes` };
861
+ const res = await remote.switchSet({ sessionId, slug: hit[0].slug });
862
+ return { kind: 'success', text: fmtSwitch(hit[0], res) };
863
+ }
864
+ if (action === 'undo') {
865
+ if (!sessionId) return { kind: 'error', text: NO_SESSION };
866
+ const r = await remote.undoSwitch({ sessionId });
867
+ return { kind: 'success', text: r.restored ? '已撤销上一次切换,生效清单回到切换前。' : '没有可撤销的切换记录(撤销入口用过一次即消失)。' };
868
+ }
869
+ return { kind: 'error', text: `未知子命令「${action}」。\n${HELP}` };
870
+ }
871
+
872
+ /** `/skill-doctor` 处理器:全局只读诊断(无会话时项目面如实置空,review M2 口径)。 */
873
+ async function runDoctor(inv) {
874
+ return { kind: 'success', text: fmtDoctor(await remote.diagnoseRun({ sessionId: inv?.agent?.id ?? null })) };
875
+ }
876
+
877
+ // 注册即挂 disposer(P1 血泪规则);服务缺位 → 一次性警告 + 该入口退化。
878
+ const commands = ctx.get('commands');
879
+ if (!commands) ctx.logger.warn('skill-set-manager:无 commands 服务,/skill-set 与 /skill-doctor 不可用(面板与设置页不受影响)');
880
+ else
881
+ ctx.effect(() => {
882
+ const defs = [
883
+ { name: 'skill-set', description: '查看与切换本项目的技能集(list / show / use <集> / undo)', input: { hint: '<list | show | use <集> [--yes] | undo>' }, handler: guard(runSkillSet) },
884
+ { name: 'skill-doctor', description: '技能诊断:六类状态分组 + 修复指引', handler: guard(runDoctor) },
885
+ ];
886
+ const offs = [];
887
+ for (const def of defs) {
888
+ try { offs.push(commands.register(def)); }
889
+ catch (e) { ctx.logger.warn(`skill-set-manager:命令 /${def.name} 注册失败(同名被占用或上一代际残留): ${e?.message ?? e}`); }
890
+ }
891
+ return () => { for (const off of offs) { try { off(); } catch {} } };
892
+ }, 'skill-set-manager.commands');
893
+
894
+ // ---- P2:模型侧入口(§12 P2 行 211):slash 命令是人机专属,不提供 tool 模型就管不了技能集。
895
+ // 工具与命令、UI 复用同一批 remote 方法(§14),差别只在文本渲染与 rootDrift 的处理。 ----
896
+ const renderToolValue = (value) => {
897
+ if (value && typeof value.text === 'string') return value.text;
898
+ return JSON.stringify(value ?? null, null, 2);
899
+ };
900
+ const tools = ctx.get('tools');
901
+ if (!tools) ctx.logger.warn('skill-set-manager:无 tools 服务,skill_set 工具不可用(模型侧无法管理技能集,其余不受影响)');
902
+ else
903
+ ctx.effect(() => {
904
+ let off;
905
+ try {
906
+ off = tools.register({
907
+ name: 'skill_set',
908
+ description: '查看或切换当前项目的技能集。list=列出全部技能集与当前绑定;show=当前项目根、生效清单与自检;use=切换到指定技能集(下一轮请求即生效,无需重启会话;技能体在下一轮开始前就位)。',
909
+ parameters: {
910
+ type: 'object',
911
+ properties: {
912
+ action: { type: 'string', enum: [...TOOL_ACTIONS], description: 'list / show / use 三选一' },
913
+ slug: { type: 'string', description: 'action=use 时必填:技能集 slug 或显示名(可先 action=list 查询)' },
914
+ },
915
+ required: ['action'],
916
+ additionalProperties: false,
917
+ },
918
+ output: {
919
+ schema: { type: 'object', properties: { ok: { type: 'boolean' }, text: { type: 'string' } } },
920
+ render: (_args, value) => [{ type: 'text', text: renderToolValue(value) }],
921
+ },
922
+ isConcurrencySafe: (args) => { try { return parseToolArgs(args).action !== 'use'; } catch { return false; } }, // 写操作排他
923
+ execute: async (args, exec) => {
924
+ const { action, slug } = parseToolArgs(args);
925
+ const sessionId = exec?.agent?.id ?? null;
926
+ if (!sessionId) throw new Error('无会话上下文:skill_set 只能在会话内调用(需要会话定位项目根)');
927
+ if (action === 'list') {
928
+ const r = await remote.listSets();
929
+ const current = (await remote.state({ sessionId })).binding?.setSlug ?? null;
930
+ return { ok: true, current, resident: r.resident.skills, sets: r.sets.map((s) => ({ slug: s.slug, name: s.name, count: (s.skills || []).length })), text: fmtList(r, current) };
931
+ }
932
+ if (action === 'show') {
933
+ const st = await remote.state({ sessionId });
934
+ return {
935
+ ok: true, selfCheckOk: st.selfCheck.ok, projectRoot: st.projectRoot, rootDrift: st.rootDrift,
936
+ set: st.set?.slug ?? null, effective: st.effective.names, missing: st.effective.missing,
937
+ text: fmtShow(st),
938
+ };
939
+ }
940
+ const hit = matchSets((await remote.listSets()).sets, slug);
941
+ if (!hit.length) throw new Error(`找不到技能集「${slug}」:先 action=list 查看全部`);
942
+ if (hit.length > 1) throw new Error(`「${slug}」匹配多个集:${hit.map((s) => `${s.slug}(${s.name})`).join('、')}——改用 slug`);
943
+ const st = await remote.state({ sessionId });
944
+ // 模型侧没有 --yes 通道:项目根漂移时改的是整仓库全部会话,明确拒绝比静默误伤好(P2 裁定)。
945
+ if (st.rootDrift)
946
+ throw new Error(`项目根 ${st.projectRoot} ≠ 会话目录 ${st.cwd}:会影响该仓库全部会话,需人工确认——请在面板切换,或人侧执行 /skill-set use ${hit[0].slug} --yes`);
947
+ const res = await remote.switchSet({ sessionId, slug: hit[0].slug });
948
+ return { ok: true, set: hit[0].slug, applied: res.applied, warnings: res.warnings ?? [], text: fmtSwitch(hit[0], res) };
949
+ },
950
+ });
951
+ } catch (e) {
952
+ ctx.logger.warn(`skill-set-manager:skill_set 工具注册失败(同名被占用或上一代际残留): ${e?.message ?? e}`);
953
+ }
954
+ return () => { try { off?.(); } catch {} };
955
+ }, 'skill-set-manager.tool');
956
+
957
+ // 启动无条件还原(崩溃残留即设计前提);失败不阻塞激活,只警告。
958
+ storeOf().then(async (store) => {
959
+ try {
960
+ const r = await restoreAllPending(store, roots);
961
+ if (r.warnings.length) ctx.logger.warn(`skill-set-manager 启动还原警告: ${r.warnings.join('; ')}`);
962
+ if (r.restored.length) ctx.logger.info(`skill-set-manager 启动还原 ${r.restored.length} 个项目的临时覆盖`);
963
+ } catch (e) {
964
+ ctx.logger.warn(`skill-set-manager 启动还原失败: ${e?.message ?? e}`);
965
+ }
966
+ }).catch((e) => ctx.logger.warn(`skill-set-manager 存储打开失败: ${e?.message ?? e}`));
967
+
968
+ // 常驻链接幂等修复(§5.3:常驻 = 库 → 全局生效区的链接,重启/外部改动后自愈)。
969
+ syncResident(roots).then((r) => {
970
+ if (r.warnings.length) ctx.logger.warn(`skill-set-manager 常驻同步警告: ${r.warnings.join('; ')}`);
971
+ }).catch((e) => ctx.logger.warn(`skill-set-manager 常驻同步失败: ${e?.message ?? e}`));
972
+
973
+ // P3 常驻区搬迁:按台账回收旧 ~/.dsh/skills 的自建遗留链(他人条目零触碰,幂等)。
974
+ pruneLegacyResidentLinks(roots).then((r) => {
975
+ if (r.pruned.length) ctx.logger.info(`skill-set-manager 回收 ${r.pruned.length} 条旧常驻链(常驻区已迁 ~/.agents/skills)`);
976
+ if (r.warnings.length) ctx.logger.warn(`skill-set-manager 旧链回收警告: ${r.warnings.join('; ')}`);
977
+ }).catch((e) => ctx.logger.warn(`skill-set-manager 旧链回收失败: ${e?.message ?? e}`));
978
+
979
+ // 新会话自动绑定(默认关;开启后仅对无绑定的项目落默认集)。
980
+ if (config.autoBindNewProject && config.autoBindSlug) {
981
+ ctx.on('session/created', async (session) => {
982
+ try {
983
+ const cwd = ctx.workingDirectory.get(session);
984
+ const projectRoot = findProjectRoot(cwd);
985
+ if (readBinding(projectRoot)) return;
986
+ if (!sets.loadSet(roots, config.autoBindSlug)) return;
987
+ // 自动绑定与手动绑定同一条链(provision.js):丢覆盖的顺序不变式、gitignore、索引、失效事件一次做完
988
+ await bindProject(roots, projectRoot, config.autoBindSlug, {
989
+ gitignore: config.gitignoreLine,
990
+ // 自动绑定不得因索引失败打断会话创建;手动 bind 则如实失败(口径差异仅此一处)
991
+ index: async (pr) => { try { await (await storeOf()).put('bindings', projectKey(pr), { projectRoot: pr }); } catch {} },
992
+ onCommitted: () => emitSlashCacheClear(), // 补正:这条路径历史上漏发 / 菜单失效
993
+ });
994
+ } catch (e) {
995
+ ctx.logger.warn(`skill-set-manager 自动绑定失败: ${e?.message ?? e}`);
996
+ }
997
+ });
998
+ }
999
+
1000
+ // 事件级还原(§6.6 P2):会话结束(session/disposed)或归档(workspace/session-stop,
1001
+ // 探针取证:parallel 派发、payload 只有 sessionId)即尽力还原该项目临时覆盖,不再等重启。
1002
+ // 定位不到会话 cwd 就绝不动盘——不拿 host 进程 cwd 冒充项目根(review M2 同族)。
1003
+ const cwdOfSession = (sessionId, sessionHint = null) => {
1004
+ if (!sessionId) return null;
1005
+ // 事件自带的 session 对象优先(处置时机注册表可能已摘除该会话,评审 M8),再回落注册表/落盘索引
1006
+ for (const s of [sessionHint, (() => { try { return ctx.sessions.get(sessionId); } catch { return null; } })()]) {
1007
+ if (!s) continue;
1008
+ try { const c = ctx.workingDirectory.get(s); if (c) return c; } catch {}
1009
+ }
1010
+ try { const h = ctx.sessionQuery.stat?.(sessionId) ?? ctx.sessions.info?.(sessionId); if (h?.cwd) return h.cwd; } catch {}
1011
+ return null;
1012
+ };
1013
+ const restoreOnSessionEnd = async (sessionId, label, sessionHint = null) => {
1014
+ try {
1015
+ const cwd = cwdOfSession(sessionId, sessionHint);
1016
+ if (!cwd) return; // 无 cwd = 无法定位项目:启动无条件还原仍是兜底(§6.6 设计前提不变)
1017
+ const projectRoot = findProjectRoot(cwd);
1018
+ // 带 ending sessionId:同仓库另一会话开着覆盖时不误伤(§6.6「只对本次会话生效」,评审 I1)
1019
+ const r = await endOverrideIfActive(await storeOf(), roots, projectRoot, sessionId);
1020
+ if (r.ended) ctx.logger.info(`skill-set-manager:会话${label}已还原 ${projectRoot} 的临时覆盖`);
1021
+ } catch (e) {
1022
+ ctx.logger.warn(`skill-set-manager 会话${label}还原失败: ${e?.message ?? e}`);
1023
+ }
1024
+ };
1025
+ ctx.on('session/disposed', (session) => { void restoreOnSessionEnd(session?.id, '结束', session); });
1026
+ ctx.on('workspace/session-stop', (request) => { void restoreOnSessionEnd(request?.sessionId, '归档'); });
1027
+
1028
+ // 技能目录变化 = 缓存失效点(本实现无缓存:roots 为纯路径装配,扫描即时——裁定记录在 ledger)。
1029
+ ctx.on('skills/change', () => {});
1030
+
1031
+ // 兜底通道:Remote 面不可达时 client 走同源 fetch(同一实现,非第二套逻辑)。
1032
+ // webServer 是可选服务,必须经 ctx.inject 等它就绪再取用,不能在 apply 里一次性 ctx.get:
1033
+ // 冷启动时本 fiber 可以排在 webserver fiber 之前,一次性取用拿到 undefined,于是只警告
1034
+ // 一声就跳过注册 → 路由永久不被认领 → webServer 的 fallback 对未认领路径回 404
1035
+ // (Service 口径原文:answers anything not yet claimed during startup with 404 until its
1036
+ // owner registers)。client 的兜底 fetch 于是拿到「HTTP 404」,面板整片报「加载失败」。
1037
+ // 实锤 2026-10-26:重启 dsh desktop 后面板 404,同一份代码热启用一次就好——差别只在启动
1038
+ // 顺序;无凭据 curl 可判口径:未认领 = 落进 /api 鉴权门回 401,已认领 = 直达 handler 回 400/200
1039
+ // (见 scripts/probe-fetch-route.mjs)。可选服务走 ctx.inject 也是 practices.md 的明文口径。
1040
+ // headless profile 无 webServer 时回调根本不跑,entry 不崩(原 ctx.get 分支的意图不变)。
1041
+ // 关键:路由 disposer 必须挂进注入回调给的 sctx.effect——否则 bundle 禁用后路由泄漏在
1042
+ // app 级路由表里引用已 dispose 的旧 ctx(“inactive context”),再启用时
1043
+ // duplicate 注册被拒,路由永久停在已死的旧 handler 上。
1044
+ try {
1045
+ ctx.inject(['webServer'], (sctx) => {
1046
+ const webServer = sctx.get('webServer');
1047
+ if (!webServer) {
1048
+ ctx.logger.warn('skill-set-manager:webServer 不可用,fetch 兜底通道暂不注册(Remote 面不受影响)');
1049
+ return;
1050
+ }
1051
+ const route = {
1052
+ kind: 'exact',
1053
+ path: '/api/skill-set-manager',
1054
+ handler: async (req, res) => {
1055
+ if (req.method !== 'POST') { res.writeHead(405); res.end(); return; }
1056
+ let body = '';
1057
+ for await (const chunk of req) body += chunk;
1058
+ try {
1059
+ const { method, args } = JSON.parse(body || '{}');
1060
+ const fn = remote[method];
1061
+ if (typeof fn !== 'function' || !REMOTE_METHODS.includes(method)) {
1062
+ res.writeHead(400, { 'content-type': 'application/json' });
1063
+ res.end(JSON.stringify({ error: `unknown method: ${method}` }));
1064
+ return;
1065
+ }
1066
+ const value = await fn.call(remote, args);
1067
+ res.writeHead(200, { 'content-type': 'application/json' });
1068
+ res.end(JSON.stringify({ value }));
1069
+ } catch (e) {
1070
+ res.writeHead(500, { 'content-type': 'application/json' });
1071
+ res.end(JSON.stringify({ error: String(e?.message ?? e) }));
1072
+ }
1073
+ },
1074
+ };
1075
+ sctx.effect(() => {
1076
+ let off;
1077
+ try {
1078
+ off = webServer.register(route);
1079
+ } catch (e) {
1080
+ // 抢占上一代际泄漏的死路由占位(仅 duplicate 才抢;该路径名空间归本插件)。
1081
+ if (!/duplicate/.test(String(e?.message ?? e))) throw e;
1082
+ webServer.exact?.delete(route.path);
1083
+ off = webServer.register(route);
1084
+ }
1085
+ return () => off();
1086
+ }, 'skill-set-manager.fetchRoute');
1087
+ });
1088
+ } catch (e) {
1089
+ ctx.logger.warn(`skill-set-manager webServer 兜底通道注册失败(不影响 Remote 面): ${e?.message ?? e}`);
1090
+ }
1091
+ }