dsh-bufeng 0.0.0-stage → 0.64.0

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.
Files changed (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +68 -2
  3. package/bufeng.patch.yml +3 -0
  4. package/client/build-client.mjs +159 -0
  5. package/client/client.js +4038 -0
  6. package/client/src/board.js +133 -0
  7. package/client/src/capabilities.js +787 -0
  8. package/client/src/cards.js +263 -0
  9. package/client/src/data.js +43 -0
  10. package/client/src/graph.js +558 -0
  11. package/client/src/icons.js +88 -0
  12. package/client/src/projects.js +467 -0
  13. package/client/src/prompt.js +55 -0
  14. package/client/src/react.js +7 -0
  15. package/client/src/settings.js +407 -0
  16. package/client/src/styles.js +611 -0
  17. package/client/src/taskboard.js +321 -0
  18. package/client/src/taskgraph.js +145 -0
  19. package/client/src/ui.js +72 -0
  20. package/lib/acceptance-subject.js +71 -0
  21. package/lib/board/server.js +546 -0
  22. package/lib/board/snapshot.js +133 -0
  23. package/lib/board/taskview.js +151 -0
  24. package/lib/bootstrap.js +77 -0
  25. package/lib/catalog.js +385 -0
  26. package/lib/core.js +478 -0
  27. package/lib/data/capability-alias-catalog.json +301 -0
  28. package/lib/data/capability-alias.json +25 -0
  29. package/lib/domain.js +1342 -0
  30. package/lib/host-probe.js +176 -0
  31. package/lib/identity-hook.js +490 -0
  32. package/lib/index.js +119 -0
  33. package/lib/lessons.js +134 -0
  34. package/lib/metering.js +109 -0
  35. package/lib/scope.js +389 -0
  36. package/lib/session/child-watch.js +86 -0
  37. package/lib/session/evidence.js +118 -0
  38. package/lib/session/node-session.js +335 -0
  39. package/lib/session/queue.js +307 -0
  40. package/lib/session/reconcile.js +500 -0
  41. package/lib/tools/capabilities.js +1461 -0
  42. package/lib/tools/governance.js +579 -0
  43. package/lib/tools/index.js +33 -0
  44. package/lib/tools/project.js +500 -0
  45. package/lib/tools/readonly.js +566 -0
  46. package/lib/tools/recover.js +402 -0
  47. package/lib/tools/run.js +1609 -0
  48. package/lib/tools/skills.js +162 -0
  49. package/lib/tools/trees.js +637 -0
  50. package/lib/workspace-rmw.js +365 -0
  51. package/package.json +42 -4
@@ -0,0 +1,1461 @@
1
+ /**
2
+ * lib/tools/capabilities.js — 批1 v0.29.0 查看层:宿主能力面采集 + 节点能力匹配 + bufeng_capabilities 工具。
3
+ * 方案:bufeng-ws/prompt-redesign/skill-mcp装备改造方案-v1.md §3 列表查看 / §4 能力匹配(客户拍板 m00186:
4
+ * 单工具 bufeng_capabilities{list|match};MCP 只做 preset 构成标注+精确名装备建议不产 patch;server 详情
5
+ * 只展示工具面不读 profile;match 无一键应用;看板只读不操作;skill 入口白名单=批2)。
6
+ * * 读写纪律:list/match/coverage 三动作只读(不写账本、不读宿主 profile——MCP 视图只取 ctx.tools 工具面 mcp__ 前缀,
7
+ * preset 构成只取 agentPresets.compositionInventory 的行级标注);v0.46.0 preview/apply 收窄式工作流(设计稿 §5):
8
+ * preview 只读(零账本零文件写入,内存登记 preview 凭据);apply 双凭据(confirm:true+fromPreview=最近 previewHash)
9
+ * 校验通过后唯一写点=domain.updateNodeFields(与 bufeng_update_node 同一条写路径、同权限链、同事件),
10
+ * 本文件 apply 分支不 saveLedger/不 recordEvent(m4 源码级锚钉板)。
11
+ * preset 构成只取 agentPresets.compositionInventory 的行级标注(moduleName 含 MCP 客户端即标,不读 server 配置)。
12
+ * 依赖方向:tools → core/domain(不 import board/*,防 readonly↔server 环;board/server.js 与 snapshot.js 反向 import 本文件合法)。
13
+ */
14
+ import { loadLedger, BUFENG_DIR, ideaTokens, displayKindOf, jsonRender, objSchema, safeRegister, VERSION } from '../core.js'; // v0.46.0:VERSION 参与 previewHash(能力面版本口径)
15
+ import { identityHintFor, findNodeAnywhere, coverageReportOf, coverageTeamOf, readAgentPresetsService, isLivePresetsRegistry, resolveCaller, isRootKind, isGovernanceToolName, unionGovernanceTools, checkEquipToolsDrift, updateNodeFields } from '../domain.js'; // v0.43.0 覆盖矩阵两纯函数(只读对照);v0.46.0 S2:agentPresets 唯一读口(domain 单一 collector);v0.46.0 preview/apply:权限链(resolveCaller/isRootKind 与 trees.js 同源)+ T1 bufeng_* 并入(unionGovernanceTools)+ 写前漂移预检(checkEquipToolsDrift)+ 唯一写点(updateNodeFields)
16
+ import { readFileSync, statSync } from 'node:fs'; // v0.60.0 S2a:statSync=目录缓存候选 memo 键(mtimeMs|size;suggest 只读不写口径 P2-6)
17
+ import { createHash } from 'node:crypto'; // v0.46.0:previewHash=sha256(JSON.stringify(patch)+nodeId+VERSION) 前 16 位
18
+ import { fileURLToPath } from 'node:url';
19
+ import { collectVisibleToolNames } from '../session/node-session.js'; // v0.46.0:T1 bufeng_* 全集并入口径+apply 写前漂移预检(tools→session 显式边,run.js 同款先例)
20
+ import { officialCatalogPath, refreshOfficialCatalog, catalogSnapshotFor, readOfficialCatalog, CATALOG_FULL_PERIOD_MS, createControlledFetch } from '../catalog.js'; // v0.60.0 S2a:官方 MCP 目录叶子(tools→catalog 同向边;catalog.js 只依赖 node 内建零反向);v0.62.3:受控 fetch 缺省(宿主全局 undici 槽被替换,目录拉取走 node:https 直连)
21
+
22
+ /** 匹配计分(v0.30.0 批3 调优;ADR docs/决策/2026-10-19-v0.30.0-批3增强层.md):
23
+ * 分域权重 name×3 / role×2 / systemPrompt×1;闸=命中≥2 且(核心域命中≥1 或 加权分≥3 或 覆盖≥0.10 短语料兜底);
24
+ * coverage 降为诊断字段——长 systemPrompt 会线性稀释旧 coverage≥0.05 闸(真实节点 205-281 token 需 11-15 词命中才过)。 */
25
+ const MATCH_MIN_TOKENS = 2;
26
+ const MATCH_WEIGHTS = { name: 3, role: 2, system: 1 };
27
+ const MATCH_CORE_MIN_HITS = 1;
28
+ const MATCH_SYSTEM_ONLY_MIN_SCORE = 3;
29
+ const MATCH_COVERAGE_FALLBACK = 0.10;
30
+ /** match 输出与快照 slim 行的推荐上限(完整 top-N=10;快照每节点精简 top-3 控帧体积;v0.30.0 复核保持)。 */
31
+ const MATCH_TOP_N = 10;
32
+ /** v0.45.0 批1-A1 P-2 冷启动低水位:正式闸零命中时按加权分取 top-3 低置信兜底(lowConfidence=true 标注,不进正式闸口径)。 */
33
+ const LOW_WATER_TOP_N = 3;
34
+
35
+ /** v0.62 推荐匹配B批(k-mw1y3s8u05d;ADR docs/决策/2026-11-04-推荐匹配B全量批-别名桥扩充与词元卫生与万金油词降权.md):
36
+ * 万金油词 df 处置(catalog 层专用)——df=token 出现于目录候选的占比(catalogCandidatesFor 构建,候选<64 地板=null 零调整):
37
+ * df≥0.30 停用(整段剔除出 matched,不计长度/coreHits/coverage);0.08≤df<0.30 降权(加权分 ×0.25,matched/coreHits/coverage 不变)。
38
+ * 真实缓存 422 条锚:停用层=and/for/ai/mcp;降权层=server(0.1066)/检索(0.1019)/tools(0.0972)/search(0.0877) 等;api(0.064) 不受罚。
39
+ * 本地面(matchNodeCapabilities)不加 df——宿主本地工具面 curated,df 概念不适用。 */
40
+ const CATALOG_DF_STOP_RATIO = 0.30;
41
+ const CATALOG_DF_DOWN_RATIO = 0.08;
42
+ const CATALOG_DF_DOWN_WEIGHT = 0.25;
43
+ const CATALOG_DF_MIN_CANDIDATES = 64;
44
+ /** 词元卫生(同批;病灶②「3」「a」案例):纯数字与单字母 token 不参与匹配——只滤纯数字串与拉丁单字母,
45
+ * 混合串(3.x/x402/16k)与中文 token 不动;只作用于匹配核语料边界,不动 lib/core.js ideaTokens(其他消费方零影响)。 */
46
+ function isNoiseToken(t) { return /^[0-9]+$/.test(t) || /^[a-z]$/.test(t); }
47
+ function hygieneTokens(tokens) { const out = new Set(); for (const t of tokens) if (!isNoiseToken(t)) out.add(t); return out; }
48
+
49
+ /** v0.29.0 批1:技能清单采集——ctx.get('skills').list() 全局视图(不传 cwd:跳过项目本地根,
50
+ * 只扫全局根 ~/.dsh/skills 与内置 office 三件套等;批2 再议项目本地技能面)。
51
+ * 逐条取 {name,description,whenToUse?,modelInvocable,userInvocable,source}(skill-catalog.js 消费先例把
52
+ * invocation.modelInvocable 提为顶层)。降级:服务缺失/抛错 → 空数组+note(绝不炸调用方)。 */
53
+ async function collectSkillsView(ctx) {
54
+ try {
55
+ const reg = typeof ctx?.get === 'function' ? ctx.get('skills') : null;
56
+ if (!reg || typeof reg.list !== 'function') {
57
+ return { skills: [], skillsNote: '宿主技能注册表不可用(ctx skills 服务缺失)——技能清单降级为空;skill 轴语义B 默认集无从实时判定(bufeng_skill 白名单闸调用时同样会明确报错)。' };
58
+ }
59
+ const list = await reg.list();
60
+ if (!Array.isArray(list)) return { skills: [], skillsNote: '宿主技能注册表返回形状异常(非数组)——技能清单降级为空。' };
61
+ const skills = list
62
+ .filter((s) => s && typeof s === 'object' && s.name)
63
+ .map((s) => ({
64
+ name: String(s.name),
65
+ description: s.description ?? '',
66
+ whenToUse: s.whenToUse ?? null,
67
+ modelInvocable: s.invocation?.modelInvocable === true, // 宿主注册表 toSummary 口径:invocation 子对象
68
+ userInvocable: s.invocation?.userInvocable === true,
69
+ source: s.source ?? null,
70
+ defaultSkill: s.source === 'bundled' // v0.29.2 语义B:默认集标注(实时判定,m00244 不落缓存副本)
71
+ }));
72
+ return { skills };
73
+ } catch (e) {
74
+ return { skills: [], skillsNote: `宿主技能注册表读取失败(${String(e?.message ?? e).slice(0, 120)})——技能清单降级为空。` };
75
+ }
76
+ }
77
+
78
+ /** v0.29.0 批1:MCP 工具面采集——ctx.tools.view() 全局视图过滤 mcp__ 前缀,按 serverName 归并。
79
+ * 铁律:只展示工具面(name/description/参数摘要),不读宿主 profile/mcpServers 配置(客户拍板 ⑤)。
80
+ * 工具名形如 mcp__<serverName>__<rawName>(split('__')[1]=serverName)。 */
81
+ function collectMcpView(ctx) {
82
+ try {
83
+ const view = typeof ctx?.tools?.view === 'function' ? ctx.tools.view() : null;
84
+ const visible = view?.visible;
85
+ if (!visible) return { mcpServers: [], mcpNote: '宿主工具面视图不可用(ctx.tools.view 缺失)——MCP 工具面降级为空。' };
86
+ const entries = typeof visible.entries === 'function' ? [...visible.entries()] : Object.entries(visible); // Map 或对象两形态防御
87
+ const byServer = new Map();
88
+ for (const [toolName, def] of entries) {
89
+ if (!String(toolName).startsWith('mcp__')) continue;
90
+ const segs = String(toolName).split('__');
91
+ const serverName = segs.length >= 3 ? segs[1] : 'unknown';
92
+ const params = def?.parameters;
93
+ const props = params && typeof params === 'object' && params.properties && typeof params.properties === 'object' ? Object.keys(params.properties) : [];
94
+ const required = Array.isArray(params?.required) ? params.required : [];
95
+ if (!byServer.has(serverName)) byServer.set(serverName, { serverName, tools: [] });
96
+ byServer.get(serverName).tools.push({
97
+ name: String(toolName),
98
+ description: def?.description ?? '',
99
+ parameters: { props, required } // 参数摘要(属性名清单+必填清单;不透全 schema 控体积)
100
+ });
101
+ }
102
+ if (!byServer.size) return { mcpServers: [], mcpNote: '当前全局工具面无 MCP 工具(mcp__ 前缀零命中)——宿主未配置 MCP server 或其工具未挂载。' };
103
+ for (const srv of byServer.values()) srv.tools.sort((a, b) => a.name.localeCompare(b.name));
104
+ return { mcpServers: [...byServer.values()].sort((a, b) => a.serverName.localeCompare(b.serverName)) };
105
+ } catch (e) {
106
+ return { mcpServers: [], mcpNote: `MCP 工具面读取失败(${String(e?.message ?? e).slice(0, 120)})——降级为空。` };
107
+ }
108
+ }
109
+
110
+ /** v0.29.0 批1:预设清单采集——优先 compositionInventory()(行级构成:rows[].moduleName 含 MCP 客户端行
111
+ * 即标 mcpComposition;preset-registry index.js:792 先例),宿主无此 API 时降级 list()(无构成明细,
112
+ * mcpComposition=null 标注「构成不可用」)。不读 profile:构成只到 moduleName/entryId/enabled 粒度。
113
+ * v0.45.2(ADR docs/决策/2026-10-25-v0.45.2-capabilities预设段静态清单标注与投影降级.md):活注册表判据与
114
+ * equip 校验同源——trees.js bufeng_update_node equip 预检同款表达式「ap && typeof ap.inventory === 'function'」。
115
+ * 两读口一个判据:inventory 在=活注册表(equip.agentPreset 可配可校验);不在=清单即便可读也只是静态默认清单,
116
+ * equip 校验仍 fail-closed 拒(0.45.1 活体病灶:list 出 4 条静态默认预设、update_node 却拒「预设服务未注册」)。
117
+ * 据此:presets 非空且无活注册表 → presetsNote 三要素标注(静态默认清单/当前宿主不可配/agentPreset 装备校验走
118
+ * 活注册表),无事键缺省;有活注册表零新增键(字节级与 0.45.1 一致);presets 为空的三条降级路径
119
+ * (服务未注册/形状异常/读取失败,含脱敏文案)文案零变化。 */
120
+ const PRESET_STATIC_NOTE = 'presets 为静态默认清单——当前宿主不可配(agentPresets 服务缺 inventory 活注册表读口):' +
121
+ 'agentPreset 装备校验走活注册表(bufeng_update_node equip 预检同源判据),此形态下 equip.agentPreset 会被拒;清单仅供查看。';
122
+
123
+ /** v0.45.2 空字段投影降级(collectPresetsView 两产出分支共用):字符串去空白后非空 → 原样;null/缺失/空白/非字符串 → 占位符。
124
+ * name=null/缺失(活体静态清单 name=null 形态)→ '(未命名)'、description 空串 → '(无描述)'——不臆造数据(占位明示未知),
125
+ * 降级后 name/description 恒字符串(lossless JSON 更稳);严禁任何显式 undefined 值键(条件展开·无事键缺省同源纪律)。 */
126
+ const degradePresetText = (value, placeholder) => (typeof value === 'string' && value.trim() ? value : placeholder);
127
+
128
+ async function collectPresetsView(ctx) {
129
+ try {
130
+ // v0.45.0 批1-A1 R5:读口走 ctx.get 惰性通道取 agentPresets 槽位(直读 ctx.agentPresets 属性在宿主未注入该槽位时抛
131
+ // 「cannot get property ... without inject」,活体实证 P-4①:presetsNote 曾漏出 inject 原文)。
132
+ // v0.46.0 S2(读口单源化):读口收敛 domain.readAgentPresetsService(与 trees.js equip 预检同源,仓内唯一读口)——
133
+ // get 可用但返回 null/undefined=服务未注册 → 三态判别文案;get 自身抛错(readError)原样 rethrow 走本函数 catch 脱敏(R5 口径零变化)。
134
+ const { ap, readError } = readAgentPresetsService(ctx);
135
+ if (readError) throw readError;
136
+ const registryLive = isLivePresetsRegistry(ap); // v0.45.2「两读口一个判据」→ S2 单源化后判据唯一活在这里
137
+ if (ap && typeof ap.compositionInventory === 'function') {
138
+ const inv = await ap.compositionInventory();
139
+ if (!Array.isArray(inv)) return { presets: [], presetsNote: '预设构成清单返回形状异常(非数组)——预设清单降级为空。' };
140
+ const presets = inv
141
+ .filter((p) => p && typeof p === 'object' && (p.id || p.name))
142
+ .map((p) => {
143
+ const rows = Array.isArray(p.rows) ? p.rows.filter((r) => r && typeof r === 'object') : [];
144
+ const mcpRows = rows.filter((r) => String(r.moduleName ?? '').includes('mcp-client'));
145
+ return {
146
+ id: p.id ?? p.name,
147
+ name: degradePresetText(p.name, '(未命名)'), // v0.45.2:name=null/缺失/空白 → 占位降级(id 行另有真值可辨识)
148
+ description: degradePresetText(p.description, '(无描述)'), // v0.45.2:description 空串/缺失 → 占位降级
149
+ isDefault: p.isDefault === true,
150
+ ...(p.broken === true ? { broken: true } : {}),
151
+ mcpComposition: mcpRows.length ? mcpRows.map((r) => ({ entryId: r.entryId ?? null, moduleName: r.moduleName ?? null, enabled: r.enabled !== false })) : [],
152
+ mcpCompositionNote: mcpRows.length ? `含 MCP 客户端行 ×${mcpRows.length}(构成只到 moduleName/entryId 粒度,server 明细=宿主配置面)` : '构成中无 MCP 客户端行'
153
+ };
154
+ });
155
+ return { presets, ...(presets.length > 0 && !registryLive ? { presetsNote: PRESET_STATIC_NOTE } : {}) }; // v0.45.2 标注:清单非空且无活注册表才挂(活注册表=零新增键)
156
+ }
157
+ if (ap && typeof ap.list === 'function') {
158
+ const list = await ap.list();
159
+ if (!Array.isArray(list)) return { presets: [], presetsNote: '预设清单返回形状异常(非数组)——降级为空。' };
160
+ const presets = list
161
+ .filter((p) => p && typeof p === 'object' && (p.id || p.name))
162
+ .map((p) => ({
163
+ id: p.id ?? p.name,
164
+ name: degradePresetText(p.name, '(未命名)'), // v0.45.2:list 降级分支同款空字段占位降级
165
+ description: degradePresetText(p.description, '(无描述)'),
166
+ isDefault: p.isDefault === true,
167
+ ...(p.broken === true ? { broken: true } : {}),
168
+ mcpComposition: null, // 宿主无 compositionInventory:构成明细不可用(不读 profile 兜底——只读原则优先于完整性)
169
+ mcpCompositionNote: '宿主预设注册表未暴露构成明细——MCP 构成标注不可用(不读宿主 profile 兜底)'
170
+ }));
171
+ return { presets, ...(presets.length > 0 && !registryLive ? { presetsNote: PRESET_STATIC_NOTE } : {}) }; // v0.45.2 标注:与 compositionInventory 分支同口径
172
+ }
173
+ return { presets: [], presetsNote: '宿主未注册 agentPresets 预设服务——预设清单降级为空。' };
174
+ } catch (e) {
175
+ const raw = String(e?.message ?? e).slice(0, 120);
176
+ const note = /without inject/i.test(raw)
177
+ ? '预设清单读取失败(宿主 agentPresets 服务读取异常,inject 原文已脱敏)——降级为空。' // v0.45.0 R5:不漏宿主 inject 原文
178
+ : `预设清单读取失败(${raw})——降级为空。`;
179
+ return { presets: [], presetsNote: note };
180
+ }
181
+ }
182
+
183
+ /** 能力面采集总装(工具 list 与看板快照共用;看板侧经 server 层 60s TTL 缓存调用)。 */
184
+ async function collectCapabilities(ctx) {
185
+ const [skillsView, presetsView] = await Promise.all([collectSkillsView(ctx), collectPresetsView(ctx)]);
186
+ const mcpView = collectMcpView(ctx);
187
+ return { ...skillsView, ...mcpView, ...presetsView };
188
+ }
189
+
190
+ /** v0.61.0 A8:能力面宣传段 top-3(brief/full 档推荐条目上限,预算口径见设计稿 §6.4;能力面自有口径,与 match 完整 top-N 无关)。 */
191
+ const CAP_PROMPT_TOP_N = 3;
192
+
193
+ /**
194
+ * v0.46.0 capabilityPrompt 宣传段载荷(设计稿 §6.1/§6.3/§6.5):纯函数 node+caps+tier → {lines,meta} 或 null。
195
+ * 渲染条件(§6.3):tier∈{brief,full} 且(节点有装备 或 match 正式闸命中非空)才出段;否则整段缺席(null)。
196
+ * tier 非法(含 off)一律 null——off 态提示词字节与基线全等的唯一保证点;lowConfidence 低置信兜底条目不进提示词(冷启动噪音)。
197
+ * lines 交 domain.renderPromptParts 第 6 参(domain 不接 ctx 零 I/O,§6.5 数据流);meta.tier 供 manifestFromParts
198
+ * 七键登记(capabilityNote 条目独有 tier,其余段恒六键)。无项目级/任务级动态推荐——只节点级静态可用面(§6.3)。
199
+ */
200
+ export function capabilityNotePayload(node, caps, tier) {
201
+ if (tier !== 'brief' && tier !== 'full') return null;
202
+ const equip = node?.equip ?? null;
203
+ const axes = {
204
+ agentPreset: typeof equip?.agentPreset === 'string' && equip.agentPreset ? equip.agentPreset : null,
205
+ allowTools: Array.isArray(equip?.allowTools) ? equip.allowTools.filter((x) => typeof x === 'string' && x) : [],
206
+ denyTools: Array.isArray(equip?.denyTools) ? equip.denyTools.filter((x) => typeof x === 'string' && x) : [],
207
+ allowSkills: Array.isArray(equip?.allowSkills) ? equip.allowSkills.filter((x) => typeof x === 'string' && x) : []
208
+ };
209
+ const hasEquip = !!(axes.agentPreset || axes.allowTools.length || axes.denyTools.length || axes.allowSkills.length);
210
+ let recommendations = [];
211
+ try {
212
+ recommendations = (matchNodeCapabilities(node, caps ?? {}).recommendations ?? []).filter((r) => r && !r.lowConfidence);
213
+ } catch { recommendations = []; } // 匹配内部异常按零命中处理(段缺席与否由 hasEquip 决定,不炸调用方)
214
+ if (!hasEquip && recommendations.length === 0) return null; // §6.3 无装备无命中整段缺席
215
+ const top = recommendations.slice(0, CAP_PROMPT_TOP_N); // brief/full 同 top3(预算口径见设计稿 §6.4)
216
+ const lines = [];
217
+ const equipLine = (label, value) => `·${label}:${value}`;
218
+ if (tier === 'brief') {
219
+ lines.push('【可用能力提示】(节点级静态可用面;按任务需要取用)');
220
+ if (axes.agentPreset) lines.push(equipLine('智能体预设装备', axes.agentPreset));
221
+ if (axes.allowSkills.length) lines.push(equipLine('技能装备', `${axes.allowSkills.join('、')}(运行期入口:bufeng_skill 按名加载正文)`));
222
+ if (axes.allowTools.length) lines.push(equipLine('MCP/工具装备', axes.allowTools.join('、')));
223
+ if (axes.denyTools.length) lines.push(equipLine('工具黑名单', axes.denyTools.join('、')));
224
+ for (const r of top) lines.push(equipLine(r.kind === 'skill' ? '可用技能' : '可用 MCP 工具', r.serverName ? `${r.name}(server ${r.serverName})` : r.name));
225
+ } else {
226
+ lines.push('【可用能力提示】(capabilityPrompt=full;节点级静态可用面+推荐)');
227
+ if (axes.agentPreset) lines.push(equipLine('智能体预设', `${axes.agentPreset}(会话级智能体组合,下次派单新会话生效)`));
228
+ if (axes.allowSkills.length) lines.push(equipLine('技能白名单', `${axes.allowSkills.join('、')}(语义B:默认集∪额外项;运行期入口 bufeng_skill 按名加载正文)`));
229
+ if (axes.allowTools.length) lines.push(equipLine('工具白名单', `${axes.allowTools.join('、')}(只保留这些全局工具;bufeng_* 治理工具豁免恒在位)`));
230
+ if (axes.denyTools.length) lines.push(equipLine('工具黑名单', axes.denyTools.join('、')));
231
+ if (!hasEquip) lines.push('·当前无装备(透传全目录)');
232
+ for (const r of top) {
233
+ const mt = Array.isArray(r.matchedTokens) ? r.matchedTokens.slice(0, 6).join('、') : '';
234
+ lines.push(equipLine(r.kind === 'skill' ? '推荐技能' : '推荐 MCP 工具', `${r.name}${r.serverName ? `(server ${r.serverName})` : ''}${mt ? `(命中词:${mt})` : ''}`));
235
+ }
236
+ }
237
+ lines.push('·以上为建议,按任务需要取用;不需要就忽略本段。');
238
+ return {
239
+ lines,
240
+ meta: {
241
+ tier,
242
+ equipAxes: { agentPreset: axes.agentPreset ? 1 : 0, allowTools: axes.allowTools.length, denyTools: axes.denyTools.length, allowSkills: axes.allowSkills.length },
243
+ recommendations: top.length
244
+ }
245
+ };
246
+ }
247
+
248
+ /**
249
+ * v0.46.0 派单侧能力面采集 60s TTL 缓存(§6.5:dispatchCore 估算与 spawnForTask 投递同源同值——
250
+ * 一次派单两跳只采集一次;能力面为节点级静态面,60s 窗口语义与看板 server 层缓存一致)。
251
+ * 只缓存成功值(采集抛错不缓存,下次重试);board/server.js 既有缓存独立保留(降级值缓存语义不同,不动)。
252
+ * clearCapabilitiesDispatchCache:测试/诊断用清缓存口(冒烟夹具切换 ctx 后防串档)。 */
253
+ const CAP_DISPATCH_TTL_MS = 60_000;
254
+ let capDispatchCache = { at: 0, value: null };
255
+ export function clearCapabilitiesDispatchCache() {
256
+ capDispatchCache = { at: 0, value: null };
257
+ }
258
+ export async function collectCapabilitiesCached(ctx) {
259
+ const now = Date.now();
260
+ if (capDispatchCache.value !== null && now - capDispatchCache.at < CAP_DISPATCH_TTL_MS) return capDispatchCache.value;
261
+ const value = await collectCapabilities(ctx);
262
+ capDispatchCache = { at: now, value };
263
+ return value;
264
+ }
265
+
266
+ /**
267
+ * v0.46.0 派单编排侧宣传段包装(§6.5):读口=GATE capabilityPrompt(调用方判定 tier 后传入);
268
+ * 采集+载荷全 try/catch——采集失败=段缺席+一行 fail-visible note(不阻断派单,§6.3)。
269
+ * collect 参数为可注入采集口(默认 60s TTL 缓存版;单测注 throwing collect 取失败分支)。 */
270
+ export async function capabilityNoteForDispatch(ctx, node, tier, collect = collectCapabilitiesCached) {
271
+ if (tier !== 'brief' && tier !== 'full') return { capNote: null, capFailNote: null };
272
+ try {
273
+ const caps = await collect(ctx);
274
+ const capNote = capabilityNotePayload(node, caps, tier);
275
+ return { capNote, capFailNote: null };
276
+ } catch (e) {
277
+ return {
278
+ capNote: null,
279
+ capFailNote: `能力面采集失败(capabilityNote 段缺席,fail-visible 不阻断派单):${String(e?.message ?? e).slice(0, 80)}——可用 bufeng_capabilities {action:'list'} 排查能力面`
280
+ };
281
+ }
282
+ }
283
+
284
+ /** 节点能力语料分域 token(v0.30.0 批3:name/role/systemPrompt 三域分别保留,供加权计分)。 */
285
+ function nodeDomainTokens(node) {
286
+ return {
287
+ name: hygieneTokens(ideaTokens(node?.name)), // v0.62 B批词元卫生
288
+ role: hygieneTokens(ideaTokens(node?.role)),
289
+ system: hygieneTokens(ideaTokens(node?.systemPrompt))
290
+ };
291
+ }
292
+
293
+ /** 节点全语料 token(三域去重并集;corpusTokens 展示与 coverage 诊断口径与旧版一致)。 */
294
+ function nodeCorpusTokens(node) {
295
+ const d = nodeDomainTokens(node);
296
+ const s = new Set();
297
+ for (const k of ['name', 'role', 'system']) for (const t of d[k]) s.add(t);
298
+ return s;
299
+ }
300
+
301
+ /** 候选名称语料归一(v0.30.0 批3):MCP 工具去掉 mcp__<server>__ 传输包装,下划线/连字符/点一律当分隔符。
302
+ * 旧口径把 mcp__officegw__docx_export / office-docx 各当一整段 token(节点语料永远无法命中);
303
+ * 归一分词后 docx/export 等实义词可参与匹配,包装词 mcp/<server> 不再制造虚假命中。 */
304
+ function normalizeCandidateName(name, kind) {
305
+ let raw = String(name ?? '');
306
+ if (kind === 'mcpTool' && raw.startsWith('mcp__')) {
307
+ const segs = raw.split('__');
308
+ if (segs.length >= 3) raw = segs.slice(2).join('__');
309
+ }
310
+ return raw.replace(/[^a-zA-Z0-9\u4e00-\u9fff]+/g, ' ');
311
+ }
312
+
313
+ /** v0.45.0 批1-A1 中文别名层(P-1 拍板;设计稿 §4.2/§4.3):中→英词条(lib/data/capability-alias.json,纯数据零依赖)。
314
+ * 惰性单例缓存;缺失/损坏按空表处理(输出与无别名行为逐字节等价,不炸调用方)。
315
+ * reverse=英文触发词(小写)→ 中文键 ideaTokens 集;键建议 2 字纯中文(二元组切分下单词命中),
316
+ * 质量纪律:禁泛化词(工程/任务/处理/工作/相关/能力)、禁单字、每键 3-8 触发词、指向交付物或动作。 */
317
+ let aliasIndexCache = null;
318
+ function getAliasIndex() {
319
+ if (aliasIndexCache) return aliasIndexCache;
320
+ let entries = {};
321
+ try {
322
+ const data = JSON.parse(readFileSync(fileURLToPath(new URL('../data/capability-alias.json', import.meta.url)), 'utf8')); // S6 先例:import.meta.url 相对定位(异 cwd 单跑绿)
323
+ if (data && typeof data === 'object' && !Array.isArray(data)) entries = data;
324
+ } catch { /* 数据文件缺失/损坏:按空表(存量零变化),不抛错 */ }
325
+ const reverse = new Map();
326
+ for (const [zh, words] of Object.entries(entries)) {
327
+ if (typeof zh !== 'string' || zh.startsWith('_')) continue; // _meta 等元数据键跳过
328
+ const zhTokens = ideaTokens(zh);
329
+ if (!zhTokens.length) continue;
330
+ for (const w of Array.isArray(words) ? words : []) {
331
+ const key = String(w ?? '').toLowerCase().trim();
332
+ if (!key) continue;
333
+ if (!reverse.has(key)) reverse.set(key, new Set());
334
+ for (const t of zhTokens) reverse.get(key).add(t);
335
+ }
336
+ }
337
+ aliasIndexCache = { reverse };
338
+ return aliasIndexCache;
339
+ }
340
+
341
+ /** 候选能力语料:技能=name+description+whenToUse;MCP 工具=name(归一)+description。
342
+ * v0.45.0 批1-A1:别名展开——候选语料含英文触发词时把对应中文键 token 并入(桥接「中文节点语料×英文候选描述」
343
+ * 的词汇鸿沟);只对基础 token 展开一次(防链式)。aliasIndex 三态:undefined=默认真表(getAliasIndex)、
344
+ * 显式空表(测试逐字节等价锚)、显式传入(单元级)。计分/闸门/排序/MATCH_TOP_N 全部不动(§4.3 单变量纪律)。
345
+ * C 批 §三(ADR 2026-11-05):catalog 索引携 byWord/disambigByWord/disambigTriggers 时走键粒度展开+消歧佐证——
346
+ * 歧义触发词(_消歧 登记如 match→游戏/ideas→策划)须有同键另一触发词在场(如 sports/plans)才注入该中文键
347
+ * (防 69ai「match+ideas 双歧义桥接」跨义过闸);索引无这些键(共享表/EMPTY_ALIAS/旧形状)走原 reverse 展开,逐字节不变。 */
348
+ function candidateCorpusTokens(item, kind, aliasIndex) {
349
+ const name = normalizeCandidateName(item.name, kind);
350
+ const base = kind === 'skill'
351
+ ? ideaTokens([name, item.description, item.whenToUse].filter(Boolean).join(' '))
352
+ : kind === 'catalog'
353
+ ? ideaTokens([name, item.title, item.description].filter(Boolean).join(' ')) // v0.60.0 S2a:目录候选=name 末段+title+description(设计 §三)
354
+ : ideaTokens([name, item.description].filter(Boolean).join(' '));
355
+ const tokens = new Set(base.filter((t) => !isNoiseToken(t))); // v0.62 B批词元卫生:噪音 token 不入场也不作展开键
356
+ const ai = aliasIndex === undefined ? getAliasIndex() : aliasIndex;
357
+ const snapshot = [...tokens]; // 展开基于卫生后快照(防边迭代边添加)
358
+ if (ai.byWord instanceof Map) {
359
+ /* C 批 §三:消歧=豁免集扣除——reverse(共享表∪catalog 表)仍是唯一注入通道,无消歧时与旧行为逐字节等价;
360
+ * 仅当 _消歧 登记的歧义触发词(match→游戏/ideas→策划)无同键佐证词时,把该中文键 token 从本次注入中扣除。 */
361
+ const dis = ai.disambigByWord instanceof Map ? ai.disambigByWord : null;
362
+ const trig = ai.disambigTriggers instanceof Map ? ai.disambigTriggers : null;
363
+ for (const tok of snapshot) {
364
+ let blocked = null;
365
+ if (dis && trig) {
366
+ const perZh = ai.byWord.get(tok);
367
+ if (perZh) {
368
+ for (const [zh, zhTokens] of perZh) {
369
+ if (!(dis.get(tok) ?? new Set()).has(zh)) continue;
370
+ let ok = false; // 佐证判定:同键另一触发词在场(≠本词)才注入
371
+ for (const t of snapshot) if (t !== tok && (trig.get(zh) ?? new Set()).has(t)) { ok = true; break; }
372
+ if (!ok) {
373
+ if (!blocked) blocked = new Set();
374
+ for (const t of zhTokens) blocked.add(t);
375
+ }
376
+ }
377
+ }
378
+ }
379
+ const add = ai.reverse.get(tok);
380
+ if (add) for (const t of add) { if (blocked && blocked.has(t)) continue; tokens.add(t); }
381
+ }
382
+ } else {
383
+ for (const tok of snapshot) {
384
+ const add = ai.reverse.get(tok);
385
+ if (add) for (const t of add) tokens.add(t);
386
+ }
387
+ }
388
+ return tokens;
389
+ }
390
+
391
+ /** v0.30.0 批3 能力匹配调优(方案 §4/§8.1;实现依据=ADR 2026-10-19-v0.30.0-批3增强层.md):
392
+ * 计分:每个命中 token 按所在域取最大权重(name×3/role×2/systemPrompt×1)求和为 weightedScore;
393
+ * 闸:matchedTokens≥2 且(核心域命中≥1 或 加权分≥3 或 coverage≥0.10 短语料高浓度兜底)——
394
+ * 长 systemPrompt 不再线性稀释召回(旧 coverage≥0.05 在 205-281 token 真实语料需 11-15 词命中);
395
+ * 排序:加权分降序 → 命中数降序 → coverage 降序 → 名称字典序(确定性,不依赖候选顺序);
396
+ * coverage=matched/节点全语料 token 数(toFixed(2)),仅诊断展示,不再单独设闸。
397
+ * 返回 {corpusTokens, recommendations[]}——纯函数不落账本、无任何 apply/装备写入参数。 */
398
+ function matchNodeCapabilities(node, caps, opts = {}) {
399
+ const limit = Number.isInteger(opts.limit) && opts.limit > 0 ? opts.limit : MATCH_TOP_N;
400
+ const domains = nodeDomainTokens(node);
401
+ const nT = nodeCorpusTokens(node);
402
+ const cands = [];
403
+ for (const s of caps?.skills ?? []) cands.push({ kind: 'skill', item: s });
404
+ for (const srv of caps?.mcpServers ?? []) for (const t of srv.tools ?? []) cands.push({ kind: 'mcpTool', item: t, serverName: srv.serverName });
405
+ const recs = [];
406
+ const lows = []; // v0.45.0 批1-A1 P-2:未过闸但词面重叠>0 的低水位候选池(正式闸零命中时兜底,不进正式推荐口径)
407
+ for (const c of cands) {
408
+ if (!c.item?.name) continue;
409
+ const cT = candidateCorpusTokens(c.item, c.kind);
410
+ const matched = [];
411
+ for (const tok of nT) if (cT.has(tok)) matched.push(tok);
412
+ // 分域计分:token 可同时出现在多域,取最大权重;domainHits 按域计数(可跨域重复,用于理由展示)
413
+ const domainHits = { name: 0, role: 0, system: 0 };
414
+ let weightedScore = 0;
415
+ let coreHits = 0;
416
+ for (const tok of matched) {
417
+ let w = 0;
418
+ if (domains.system.has(tok)) { w = MATCH_WEIGHTS.system; domainHits.system++; }
419
+ if (domains.role.has(tok)) { w = MATCH_WEIGHTS.role; domainHits.role++; }
420
+ if (domains.name.has(tok)) { w = MATCH_WEIGHTS.name; domainHits.name++; }
421
+ if (domains.role.has(tok) || domains.name.has(tok)) coreHits++;
422
+ weightedScore += w;
423
+ }
424
+ const coverage = nT.size ? +(matched.length / nT.size).toFixed(2) : 0;
425
+ const gatePass = matched.length >= MATCH_MIN_TOKENS &&
426
+ (coreHits >= MATCH_CORE_MIN_HITS || weightedScore >= MATCH_SYSTEM_ONLY_MIN_SCORE || coverage >= MATCH_COVERAGE_FALLBACK);
427
+ const base = {
428
+ kind: c.kind,
429
+ name: c.item.name,
430
+ ...(c.serverName ? { serverName: c.serverName } : {}),
431
+ score: matched.length,
432
+ weightedScore,
433
+ coreHits,
434
+ domainHits,
435
+ matchedTokens: matched,
436
+ coverage
437
+ };
438
+ if (gatePass) {
439
+ recs.push({
440
+ ...base,
441
+ reason: `能力域命中 ${matched.length} 词(${matched.slice(0, 6).join('、')}${matched.length > 6 ? '…' : ''});` +
442
+ `核心域 ${coreHits} 词、加权分 ${weightedScore}(name×3/role×2/提示词×1),覆盖 ${coverage}`
443
+ });
444
+ } else if (matched.length > 0) {
445
+ lows.push(base); // P-2 候选池:不带 reason/lowConfidence,正式闸零命中时再标注
446
+ }
447
+ }
448
+ recs.sort((a, b) => b.weightedScore - a.weightedScore || b.score - a.score || b.coverage - a.coverage ||
449
+ String(a.name).localeCompare(String(b.name)));
450
+ if (recs.length) return { corpusTokens: nT.size, recommendations: recs.slice(0, limit) }; // 正式闸命中:输出与既有行为一致(零 lowConfidence 键)
451
+ // v0.45.0 批1-A1 P-2 冷启动低水位:正式闸零命中时不空手而归——低水位池按同一比较器取 top-3 标 lowConfidence=true;
452
+ // 完全零重叠(lows 也空)→ 保持空(不硬凑)。threshold 口径仍只描述正式闸(低水位不改变闸值本身)。
453
+ lows.sort((a, b) => b.weightedScore - a.weightedScore || b.score - a.score || b.coverage - a.coverage ||
454
+ String(a.name).localeCompare(String(b.name)));
455
+ const lowRecs = lows.slice(0, LOW_WATER_TOP_N).map((x) => ({
456
+ ...x,
457
+ lowConfidence: true,
458
+ reason: `冷启动低水位(未达正式闸):能力域命中 ${x.score} 词(${x.matchedTokens.slice(0, 6).join('、')}${x.score > 6 ? '…' : ''});` +
459
+ `核心域 ${x.coreHits} 词、加权分 ${x.weightedScore}(name×3/role×2/提示词×1),覆盖 ${x.coverage}——` +
460
+ `未过正式闸(命中≥2 且 核心域≥1/加权分≥3/覆盖≥0.10 三选一),按加权分取 top-${LOW_WATER_TOP_N} 低置信兜底,应用前请人工复核`
461
+ }));
462
+ if (!lowRecs.length) return { corpusTokens: nT.size, recommendations: [], emptyReason: 'no-match' }; // v0.60.0 S1 D6:完全零重叠不兜底,显式标注(recommendations 恒 [],近邻/低分不凑数)
463
+ return { corpusTokens: nT.size, recommendations: lowRecs };
464
+ }
465
+
466
+ /** 快照 slim 行(SSE 帧控体积):{kind,name,serverName?,matched,coverage}。 */
467
+ function slimRecommendation(r) {
468
+ return { kind: r.kind, name: r.name, ...(r.serverName ? { serverName: r.serverName } : {}), matched: r.score, coverage: r.coverage };
469
+ }
470
+
471
+
472
+ /* ---------- v0.60.0 S2a(设计 docs/设计/2026-10-29-能力面公网推荐与装备体验重设计-v2.md §三/§四):官方目录候选与按岗建议单 ---------- */
473
+ /** catalog 专属别名层:lib/data/capability-alias-catalog.json(中文能力键→英文触发词,设计 §三枚举)。
474
+ * 仅 catalog 候选语料路径合并共享反查表(getAliasIndex)——不动共享表本身:本地推荐(list/match/快照/派单宣传段)逐字节不变。
475
+ * 惰性单例;文件缺失/损坏按空表处理(catalog 路径退化为共享表,不炸)。 */
476
+ let catalogAliasIndexCache = null;
477
+ function getCatalogAliasIndex() {
478
+ if (catalogAliasIndexCache) return catalogAliasIndexCache;
479
+ const reverse = new Map(getAliasIndex().reverse); // 共享表先并入(复制不回写)
480
+ const byWord = new Map(); // C 批 §三:触发词→中文键→键 token 集(键粒度展开;reverse 仍是既有命中/计分通道,行为等价)
481
+ let disambigByWord = null; // C 批 §三:歧义触发词→中文键集(_消歧 数据键;null=无登记=零消歧)
482
+ let disambigTriggers = null; // C 批 §三:中文键→全触发词集(佐证判定=同键另一触发词在场)
483
+ try {
484
+ const raw = JSON.parse(readFileSync(fileURLToPath(new URL('../data/capability-alias-catalog.json', import.meta.url)), 'utf8'));
485
+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
486
+ for (const [zh, words] of Object.entries(raw)) {
487
+ if (typeof zh !== 'string' || zh.startsWith('_')) continue;
488
+ const zhTokens = ideaTokens(zh);
489
+ if (!zhTokens.length) continue; // v0.62 B批修复:ideaTokens 返回数组,.size 恒 undefined→判空永不成立(死桥;ADR §三)
490
+ for (const w of Array.isArray(words) ? words : []) {
491
+ const key = String(w ?? '').toLowerCase().trim();
492
+ if (!key) continue;
493
+ if (!reverse.has(key)) reverse.set(key, new Set());
494
+ for (const t of zhTokens) reverse.get(key).add(t);
495
+ if (!byWord.has(key)) byWord.set(key, new Map());
496
+ byWord.get(key).set(zh, new Set(zhTokens));
497
+ }
498
+ }
499
+ const dis = raw['_消歧'];
500
+ if (dis && typeof dis === 'object' && !Array.isArray(dis)) { // _ 命名空间标注键(随 _meta 单列口径,不入中文键计数)
501
+ disambigByWord = new Map();
502
+ disambigTriggers = new Map();
503
+ for (const [zh, words] of Object.entries(dis)) {
504
+ if (typeof zh !== 'string' || !Array.isArray(words)) continue;
505
+ const ambSet = new Set(words.map((w) => String(w ?? '').toLowerCase().trim()).filter(Boolean));
506
+ if (!ambSet.size) continue;
507
+ for (const w of ambSet) {
508
+ if (!disambigByWord.has(w)) disambigByWord.set(w, new Set());
509
+ disambigByWord.get(w).add(zh);
510
+ }
511
+ const trigList = Array.isArray(raw[zh]) ? raw[zh] : []; // 佐证词表=同键主表触发词全集(_消歧 只登记歧义词)
512
+ disambigTriggers.set(zh, new Set(trigList.map((w) => String(w ?? '').toLowerCase().trim()).filter(Boolean)));
513
+ }
514
+ }
515
+ }
516
+ } catch { /* 缺失/损坏按空表(catalog 路径=共享表),不抛错 */ }
517
+ catalogAliasIndexCache = { reverse, byWord, disambigByWord, disambigTriggers };
518
+ return catalogAliasIndexCache;
519
+ }
520
+
521
+ /** 空别名表(高危动词判定用:别名展开不参与风险面识别,防中英桥接误伤)。 */
522
+ const EMPTY_ALIAS_INDEX = { reverse: new Map() };
523
+
524
+ /** 目录候选 token 集(设计 §三:serverName 末段+title+description,catalog 别名合并展开)。 */
525
+ function catalogCandidateTokens(row, aliasIndex) {
526
+ const lastSeg = String(row?.serverName ?? '').split('/').filter(Boolean).pop() ?? '';
527
+ return candidateCorpusTokens({ name: lastSeg, title: row?.title, description: row?.description }, 'catalog', aliasIndex);
528
+ }
529
+
530
+ /** 高危动词工具判定(安全 §六-④):工具名/描述 token 含 destructive 动词即视为高危面(是否建议屏蔽还须岗位语料零命中)。 */
531
+ const HIGH_RISK_TOOL_TOKENS = new Set(['exec', 'shell', 'delete', 'remove', 'rm', 'drop', 'push', 'write', 'upload', 'post', 'send', 'eval', 'sql', '删除', '移除', '清除', '执行']);
532
+ function isHighRiskTool(item) {
533
+ for (const t of candidateCorpusTokens(item, 'mcpTool', EMPTY_ALIAS_INDEX)) if (HIGH_RISK_TOOL_TOKENS.has(t)) return true;
534
+ return false;
535
+ }
536
+
537
+ /* 建议单常量(§四:每节点上限 8 条=安装5/收窄2/屏蔽2/技能2 内裁剪;systemPrompt 对 catalog 匹配截断 600 字)。 */
538
+ const SUGGEST_NODE_CAP = 8;
539
+ const SUGGEST_INSTALL_CAP = 5;
540
+ const CATALOG_SYSTEM_MATCH_MAX = 600;
541
+ const CONF_RANK = { high: 0, medium: 1, low: 2 };
542
+ /* 2026-11-04 推荐卡功能描述行批(k-mw25cq0r07w,ADR docs/决策/2026-11-04-推荐卡功能描述行-catalog与本地层描述透传.md):
543
+ * 建议行可选键 description 的单点净化 helper(C3 契约,catalog/local 两层同用)——公网描述=不可信文本,落键前必经
544
+ * 剥 HTML 标签壳→控制字符(U+0000-U+001F/U+007F)替空格→空白折叠单空格→trim→硬截断 ≤200(JS .length,不加省略号);
545
+ * 空/纯标签/净化后空串→返 ''(调用侧不落键=无事键缺省)。仅随 suggestSheet JSON 出行,禁进 capabilityPrompt 派单注入链(C5)。 */
546
+ const SUGGEST_DESC_MAX = 200;
547
+ function sanitizeSuggestDescription(raw) {
548
+ if (typeof raw !== 'string') return '';
549
+ return raw
550
+ .replace(/<[^>]*>/g, ' ')
551
+ .replace(/[\u0000-\u001F\u007F]/g, ' ')
552
+ .replace(/\s+/g, ' ')
553
+ .trim()
554
+ .slice(0, SUGGEST_DESC_MAX);
555
+ }
556
+
557
+ function suggestionIdOf(nodeId, layer, kind, name, picks) {
558
+ return createHash('sha256').update([nodeId, layer, kind, name, (picks ?? []).join(',')].join('|')).digest('hex').slice(0, 12);
559
+ }
560
+
561
+ /** 本地层建议行工厂(15 键契约;source=本地面回指,url 恒 null——本地行无外链)。
562
+ * 2026-11-04 推荐卡功能描述行批:第 13 参 description=可选功能描述(C1/C2 契约)——净化后非空才落键
563
+ * (键序追加在 15 键之后,既有 15 键序零漂移;displayName 维持 name,C4 逻辑零改动)。 */
564
+ function localRow(nodeId, kind, name, reason, axis, picks, previewArgs, confidence, risk, installState, matchedTokens, gapTokens, description) {
565
+ const row = {
566
+ suggestionId: suggestionIdOf(nodeId, 'local', kind, name, picks),
567
+ kind,
568
+ layer: 'local',
569
+ name,
570
+ displayName: name,
571
+ source: { type: 'local', id: name, url: null },
572
+ reason,
573
+ axis,
574
+ picks,
575
+ previewArgs,
576
+ confidence,
577
+ risk,
578
+ installState,
579
+ matchedTokens,
580
+ gapTokens
581
+ };
582
+ const desc = sanitizeSuggestDescription(description);
583
+ if (desc) row.description = desc;
584
+ return row;
585
+ }
586
+
587
+ /* ---------- C 批(k-mw37ndvk0nv / 伞单 k-mw37bwlg0jf,ADR docs/决策/2026-11-05-条目级跨岗万金油处置与69ai消歧与技术债三件.md):条目级跨岗万金油处置 ---------- */
588
+ /** §二 档位常量:suggestSheet 两趟统计「单条目 gate-pass 岗数」后建跨岗表——
589
+ * ≥DROP_ROLES 岗全过闸=跨岗万金油出局;≥DOWN_ROLES=降权(排序有效分×DOWN_WEIGHT,行内字段不动);
590
+ * 树节点数 <MIN_ROLES 地板不建表(护小树夹具,仿 CATALOG_DF_MIN_CANDIDATES 语义)。
591
+ * 处置一律在闸后:gate 判定与 df 层不因处置变化(安全红线:闸参数零改动)。 */
592
+ const CROSS_ROLE_MIN_ROLES = 8;
593
+ const CROSS_ROLE_DROP_ROLES = 4;
594
+ const CROSS_ROLE_DOWN_ROLES = 3;
595
+ const CROSS_ROLE_DOWN_WEIGHT = 0.5;
596
+
597
+ /** catalog 闸计分(纯函数):v0.62 B 批计分循环原样抽出为单源(字节等价语义)——suggestNodeEquipment(行集与排序)
598
+ * 与 suggestSheet 趟1(跨岗 gate-pass 统计)共用;返回按(加权分→命中数→coverage→serverName 字典序)排定的
599
+ * scored 数组(闸前剔除项不含在内;df 停用/降权在闸前,跨岗处置不在本函数——调用侧闸后施加)。 */
600
+ function catalogGateScored(node, catalogCandidates, catalogDf) {
601
+ const catNode = typeof node?.systemPrompt === 'string' && node.systemPrompt.length > CATALOG_SYSTEM_MATCH_MAX
602
+ ? { ...node, systemPrompt: node.systemPrompt.slice(0, CATALOG_SYSTEM_MATCH_MAX) }
603
+ : node;
604
+ const cDomains = nodeDomainTokens(catNode);
605
+ const cT = nodeCorpusTokens(catNode);
606
+ const seen = new Set();
607
+ const scored = [];
608
+ for (const cand of catalogCandidates) {
609
+ const row = cand?.row;
610
+ if (!row?.serverName || seen.has(row.serverName)) continue; // 同 serverName 去重(多 version 组在归一化层已取最新,此处防候选源重复)
611
+ seen.add(row.serverName);
612
+ const matched = [];
613
+ for (const tok of cT) { // v0.62 B批:df≥停用线的万金油词整段剔除(不计 matched 长度/coreHits/coverage)
614
+ if (!cand.tokens.has(tok)) continue;
615
+ if (catalogDf && (catalogDf.get(tok) ?? 0) >= CATALOG_DF_STOP_RATIO) continue;
616
+ matched.push(tok);
617
+ }
618
+ if (matched.length < MATCH_MIN_TOKENS) continue;
619
+ let weightedScore = 0;
620
+ let coreHits = 0;
621
+ for (const tok of matched) {
622
+ let w = 0;
623
+ if (cDomains.system.has(tok)) w = MATCH_WEIGHTS.system;
624
+ if (cDomains.role.has(tok)) w = MATCH_WEIGHTS.role;
625
+ if (cDomains.name.has(tok)) w = MATCH_WEIGHTS.name;
626
+ if (cDomains.role.has(tok) || cDomains.name.has(tok)) coreHits += 1;
627
+ weightedScore += w * (catalogDf && (catalogDf.get(tok) ?? 0) >= CATALOG_DF_DOWN_RATIO ? CATALOG_DF_DOWN_WEIGHT : 1); // v0.62 B批:df 降权层加权 ×0.25
628
+ }
629
+ const coverage = cT.size ? +(matched.length / cT.size).toFixed(2) : 0;
630
+ if (coreHits < MATCH_CORE_MIN_HITS) continue; // catalog 额外强制核心域≥1(纯 systemPrompt 命中不过闸)
631
+ if (!(weightedScore >= MATCH_SYSTEM_ONLY_MIN_SCORE || coverage >= MATCH_COVERAGE_FALLBACK)) continue;
632
+ scored.push({ row, matched, weightedScore, coverage });
633
+ }
634
+ scored.sort((a, b) => b.weightedScore - a.weightedScore || b.matched.length - a.matched.length
635
+ || b.coverage - a.coverage || String(a.row.serverName).localeCompare(String(b.row.serverName)));
636
+ return scored;
637
+ }
638
+
639
+ /**
640
+ * 按岗建议单内核(纯函数;冻结契约导出):输入节点+宿主能力面+目录候选(已 token 化),输出 {domainGaps, suggestions}。
641
+ * 本地层四类(§三):①已装未用=提示型(picks=null 零写入口);②误配收窄=allowTools 精确名;③高危屏蔽=denyTools 精确名(高危动词+岗位零命中);
642
+ * ④技能白名单=allowSkills 追加(仅非默认集、仅闸已挂 allowSkills 为数组时)。本地零达标且低水位池在→低置信 top-3(无写入口)。
643
+ * 公网层(§三 ④-⑦):matched≥2 ∧ 核心域≥1(额外强制)∧(加权分≥3 ∨ 覆盖≥0.10);零命中不兜底;同 serverName 去重。
644
+ * 排序(§四):local 在上 catalog 在下;层内 confidence 秩(high→medium→low);每节点 ≤8 条(安装 5 内裁剪)。
645
+ */
646
+ function suggestNodeEquipment(node, opts = {}) {
647
+ const caps = opts.caps ?? { skills: [], mcpServers: [] };
648
+ const catalogCandidates = Array.isArray(opts.catalogCandidates) ? opts.catalogCandidates : [];
649
+ const catalogDf = opts.catalogDf instanceof Map ? opts.catalogDf : null; // v0.62 B批:目录层 df(缺省 null=旧行为;suggestSheet→catalogCandidatesFor 透传)
650
+ const nodeId = String(node?.id ?? '');
651
+ const equip = node?.equip ?? null;
652
+ const domains = nodeDomainTokens(node);
653
+ const nT = nodeCorpusTokens(node);
654
+ const m = matchNodeCapabilities(node, caps);
655
+ const faceTools = new Map(); // 全名→{item,tokens}(本地面工具索引)
656
+ for (const srv of caps.mcpServers ?? []) {
657
+ for (const t of srv.tools ?? []) {
658
+ if (!t?.name) continue;
659
+ faceTools.set(String(t.name), { item: t, tokens: candidateCorpusTokens(t, 'mcpTool') });
660
+ }
661
+ }
662
+ /* 2026-11-04 推荐卡功能描述行批:local 层建议行描述取值器(C2 契约)——MCP 工具=面 def.description;
663
+ * 技能/低置信行=按 name 回查技能目录;查无=空串(localRow 净化后不落键)。 */
664
+ const localDescOf = (name) => {
665
+ const fd = faceTools.get(String(name));
666
+ if (fd?.item?.description) return fd.item.description;
667
+ const sk = (caps.skills ?? []).find((x) => String(x?.name ?? '') === String(name));
668
+ return sk?.description ?? '';
669
+ };
670
+ const hitsOf = (tokens) => {
671
+ const hit = [];
672
+ for (const tok of nT) if (tokens.has(tok)) hit.push(tok);
673
+ return hit;
674
+ };
675
+
676
+ /* 公网层(先算——domainGaps 的 public-only 判型要用 catalog 命中有无)。 */
677
+ const catRows = [];
678
+ if (catalogCandidates.length) {
679
+ const catNode = typeof node?.systemPrompt === 'string' && node.systemPrompt.length > CATALOG_SYSTEM_MATCH_MAX
680
+ ? { ...node, systemPrompt: node.systemPrompt.slice(0, CATALOG_SYSTEM_MATCH_MAX) }
681
+ : node;
682
+ const cDomains = nodeDomainTokens(catNode);
683
+ const scored = catalogGateScored(node, catalogCandidates, catalogDf); // C 批:闸计分单源抽出(字节等价语义)
684
+ /* C 批 §二:闸后跨岗处置(opts.catalogCrossRole=Map(serverName→'drop'|'down'),缺省不传=旧行为零漂移——
685
+ * m4 B/C 族与 m3/m13 夹具全走不传形态)。drop=从行集剔除(条目本已过闸,闸判定不因处置变化);
686
+ * down=排序有效分×CROSS_ROLE_DOWN_WEIGHT 重排(行内 15 键字段与 reason 原样,降权≠出局)。 */
687
+ const crossRole = opts.catalogCrossRole instanceof Map ? opts.catalogCrossRole : null;
688
+ const eff = crossRole
689
+ ? scored
690
+ .filter((s) => crossRole.get(s.row.serverName) !== 'drop')
691
+ .map((s) => ({ ...s, effScore: crossRole.get(s.row.serverName) === 'down' ? s.weightedScore * CROSS_ROLE_DOWN_WEIGHT : s.weightedScore }))
692
+ .sort((a, b) => b.effScore - a.effScore || b.matched.length - a.matched.length
693
+ || b.coverage - a.coverage || String(a.row.serverName).localeCompare(String(b.row.serverName)))
694
+ : scored;
695
+ for (const s of eff.slice(0, SUGGEST_INSTALL_CAP)) {
696
+ const r = s.row;
697
+ const remoteUrl = Array.isArray(r.remotes) && r.remotes[0] && r.remotes[0].url ? r.remotes[0].url : null;
698
+ const catRow = {
699
+ suggestionId: suggestionIdOf(nodeId, 'catalog', 'install', r.serverName, null),
700
+ kind: 'install',
701
+ layer: 'catalog',
702
+ name: r.serverName,
703
+ displayName: r.title || r.serverName,
704
+ source: { type: 'official-registry', id: r.serverName, url: r.homepage || r.repository || remoteUrl },
705
+ reason: '官方目录命中 ' + s.matched.length + ' 词(' + s.matched.slice(0, 6).join('、') + '),加权分 ' + s.weightedScore + '——目录元数据,需人工安装(本建议不安装、不自动 apply;目录记录=元数据≠安全审计)',
706
+ axis: 'install',
707
+ picks: null,
708
+ previewArgs: null,
709
+ confidence: 'medium',
710
+ risk: ['not-installed', 'third-party-metadata', ...(Array.isArray(r.remotes) && r.remotes.length ? ['remote-endpoint'] : [])],
711
+ installState: 'not-installed',
712
+ matchedTokens: s.matched,
713
+ gapTokens: s.matched.filter((t) => cDomains.name.has(t) || cDomains.role.has(t))
714
+ };
715
+ const catDesc = sanitizeSuggestDescription(r.description); // 2026-11-04 推荐卡功能描述行批:C2 catalog=r.description,C3 单点 helper 两层同用
716
+ if (catDesc) catRow.description = catDesc; // C1:净化后非空才落键(无事键缺省)
717
+ catRows.push(catRow);
718
+ }
719
+ }
720
+
721
+ /* 本地层四类+低水位。 */
722
+ const local = [];
723
+ const allowTools = equip && Array.isArray(equip.allowTools) ? equip.allowTools.map(String) : [];
724
+ const relevant = [];
725
+ const denyPicks = [];
726
+ for (const t of allowTools) {
727
+ const def = faceTools.get(t);
728
+ if (!def) continue; // 面外/死名:不进 picks(不得臆造视图外名);漂移披露归 preview 写前预检
729
+ if (hitsOf(def.tokens).length) relevant.push(t);
730
+ else if (isHighRiskTool(def.item)) denyPicks.push(t); // 高危动词且岗位语料零命中
731
+ }
732
+ if (relevant.length && relevant.length < allowTools.length) {
733
+ const tokens0 = faceTools.get(relevant[0])?.tokens ?? new Set();
734
+ local.push(localRow(nodeId, 'narrow', relevant[0],
735
+ '误配收窄:装备 allowTools 含面外或与岗位语料零命中的工具——建议收窄为精确名清单(' + relevant.join('、') + ';bufeng_* 插件全集在 preview 时自动并入);preview 预览后审计后确认 apply',
736
+ 'allowTools', [...relevant], { action: 'preview', nodeId, allowTools: [...relevant] }, 'medium', [], 'installed', hitsOf(tokens0), [], localDescOf(relevant[0])));
737
+ }
738
+ if (denyPicks.length) {
739
+ local.push(localRow(nodeId, 'deny', denyPicks[0],
740
+ '高危屏蔽:' + denyPicks.join('、') + ' 命中高危动词(exec/shell/delete/rm/drop/push 一类)且岗位语料零对应域——建议 denyTools 精确名屏蔽(审计后确认)',
741
+ 'denyTools', [...denyPicks], { action: 'preview', nodeId, denyTools: [...denyPicks] }, 'medium', ['high-risk-verb'], 'installed', [], [], localDescOf(denyPicks[0])));
742
+ }
743
+ if (equip && Array.isArray(equip.allowSkills)) { // 闸已挂(语义B 数组形态)才谈追加
744
+ const listed = new Set(equip.allowSkills.map(String));
745
+ const skillPicks = [];
746
+ let skillHit = [];
747
+ for (const s of caps.skills ?? []) {
748
+ if (!s?.name || s.defaultSkill) continue; // 只推非默认集(默认集恒在可用集合,推了=全量白名单噪音)
749
+ if (listed.has(String(s.name))) continue;
750
+ const hit = hitsOf(candidateCorpusTokens(s, 'skill'));
751
+ if (hit.length) {
752
+ skillPicks.push(String(s.name));
753
+ if (hit.length > skillHit.length) skillHit = hit;
754
+ }
755
+ }
756
+ if (skillPicks.length) {
757
+ local.push(localRow(nodeId, 'skill', skillPicks[0],
758
+ '技能白名单:岗位语料命中技能(' + skillPicks.join('、') + ',均非默认集)而 allowSkills 未列——建议追加(语义B:默认集恒在可用集合,此处只补额外项;审计后确认)',
759
+ 'allowSkills', [...skillPicks], { action: 'preview', nodeId, allowSkills: [...skillPicks] }, 'medium', [], 'installed', skillHit, [], localDescOf(skillPicks[0])));
760
+ }
761
+ }
762
+ if (relevant.length) {
763
+ const tokens0 = faceTools.get(relevant[0])?.tokens ?? new Set();
764
+ local.push(localRow(nodeId, 'usage', relevant[0],
765
+ '已装未用提示:' + relevant.join('、') + ' 已在装备 allowTools 且命中岗位语料——本行为现状对账提示(无写入口);若近期任务确未使用,审计后确认是否收窄(走 narrow 行 preview→apply)',
766
+ 'none', null, null, 'low', [], 'installed', hitsOf(tokens0), [], localDescOf(relevant[0])));
767
+ }
768
+ if (!local.length && (m.recommendations ?? []).length && (m.recommendations ?? []).every((x) => x.lowConfidence === true)) {
769
+ for (const x of m.recommendations.slice(0, LOW_WATER_TOP_N)) {
770
+ local.push(localRow(nodeId, 'low', x.name,
771
+ '本地低置信候选——' + (x.reason ?? '冷启动低水位') + ';低置信,需人工判断(无写入口,采纳前人工复核)',
772
+ 'none', null, null, 'low', [], 'installed', x.matchedTokens ?? [], [], localDescOf(x.name)));
773
+ }
774
+ }
775
+
776
+ /* 缺口四元组之「缺什么」:equip=null→empty-equip(只提示,不当缺口);否则核心域未覆盖 token top-8(有公网候选=public-only,否则 no-local-coverage)。 */
777
+ const domainGaps = [];
778
+ if (!equip) {
779
+ domainGaps.push({ kind: 'empty-equip', tokens: [], note: '当前全透传(未配置装备),非缺工具——以下建议供编制参考' });
780
+ } else {
781
+ const covered = new Set();
782
+ for (const x of m.recommendations ?? []) for (const t of x.matchedTokens ?? []) covered.add(t);
783
+ const gap = [];
784
+ for (const tok of new Set([...domains.name, ...domains.role])) if (!covered.has(tok)) gap.push(tok);
785
+ if (gap.length) {
786
+ domainGaps.push({
787
+ kind: catRows.length ? 'public-only' : 'no-local-coverage',
788
+ tokens: gap.slice(0, 8),
789
+ note: catRows.length ? '岗位核心域 token 本地面未覆盖(公网层有候选,安装需人工)' : '岗位核心域 token 本地面未覆盖(公网层亦无候选——建议调整编制语料或人工评估)'
790
+ });
791
+ }
792
+ }
793
+
794
+ const localSorted = [...local].sort((a, b) => (CONF_RANK[a.confidence] ?? 9) - (CONF_RANK[b.confidence] ?? 9)); // 稳定排序:medium(narrow/deny/skill) 先、low(usage/低水位) 后
795
+ return { domainGaps, suggestions: [...localSorted, ...catRows].slice(0, SUGGEST_NODE_CAP) };
796
+ }
797
+
798
+ /** 目录缓存候选 memo(键=path|mtimeMs|size):suggest 只读不写(字节+mtime 双等);缓存删除/不可读=stat 失败直读不触 memo(不复活已删缓存)。 */
799
+ let suggestCatalogMemo = { key: null, build: null };
800
+ function catalogCandidatesFor(cachePath, now) {
801
+ let key = null;
802
+ try {
803
+ const st = statSync(cachePath);
804
+ key = cachePath + '|' + st.mtimeMs + '|' + st.size;
805
+ } catch { key = null; }
806
+ if (key && suggestCatalogMemo.key === key && suggestCatalogMemo.build) return suggestCatalogMemo.build(now);
807
+ const snap = catalogSnapshotFor(cachePath, now);
808
+ const aliasIndex = getCatalogAliasIndex();
809
+ const candidates = snap.servers.filter((r) => r && r.serverName).map((row) => ({ row, tokens: catalogCandidateTokens(row, aliasIndex) }));
810
+ /* v0.62 B批:万金油词 df 表——token→出现候选占比;候选 <CATALOG_DF_MIN_CANDIDATES 地板时 df=null(小缓存/测试夹具零漂移)。 */
811
+ let df = null;
812
+ if (candidates.length >= CATALOG_DF_MIN_CANDIDATES) {
813
+ const counts = new Map();
814
+ for (const c of candidates) for (const t of c.tokens) counts.set(t, (counts.get(t) ?? 0) + 1);
815
+ const n = candidates.length;
816
+ df = new Map([...counts.entries()].map(([t, k]) => [t, k / n]));
817
+ }
818
+ const base = snap.view;
819
+ const build = (t) => {
820
+ const view = {
821
+ source: base.source,
822
+ fetchedAt: base.fetchedAt,
823
+ ageMs: base.fetchedAt ? t - Date.parse(base.fetchedAt) : null,
824
+ stale: base.fetchedAt ? (t - Date.parse(base.fetchedAt)) > CATALOG_FULL_PERIOD_MS : false,
825
+ available: base.available
826
+ };
827
+ if (!base.available) view.reason = base.reason;
828
+ return { view, candidates, df };
829
+ };
830
+ if (key) suggestCatalogMemo = { key, build };
831
+ return build(now);
832
+ }
833
+
834
+ /** fetch 注入解析:注册闭包 ctx.get('fetch') → 调用方 exec.get('fetch') → 受控实现(缺省,v0.62.3)。
835
+ * 生产环境宿主不提供 fetch 服务(probe-1:app.asar 无 provide('fetch')),且宿主启动器把 globalThis.fetch 的
836
+ * undici 全局 dispatcher 换成捆绑 userland Agent(跨版本耦合非契约,目录域 15s 挂死根因)——故 globalThis.fetch
837
+ * 移出链条,缺省一律走 createControlledFetch()(node:https 直连);注入通道保留在前(测试 stub 与显式注入契约不变)。 */
838
+ function resolveFetchImpl(ctx, exec) {
839
+ for (const src of [ctx, exec]) {
840
+ try {
841
+ const f = typeof src?.get === 'function' ? src.get('fetch') : null;
842
+ if (typeof f === 'function') return f;
843
+ } catch { /* 通道异常→下一路 */ }
844
+ }
845
+ return createControlledFetch();
846
+ }
847
+
848
+ /** action=catalog 内核(目录缓存唯一写口;绝不抛错——失败=保留旧缓存+lastError 状态回显;可空键缺省防 schema 违约)。 */
849
+ async function catalogRefresh(ctx, { now = Date.now(), exec = null } = {}) {
850
+ const cachePath = officialCatalogPath(BUFENG_DIR);
851
+ let fetchImpl = null;
852
+ try { fetchImpl = resolveFetchImpl(ctx, exec); } catch { /* 构造异常→防御兜底分支 */ }
853
+ if (typeof fetchImpl !== 'function') {
854
+ const snap = catalogSnapshotFor(cachePath, now);
855
+ return {
856
+ action: 'catalog', ok: false, mode: 'unavailable', refreshed: false, stale: false,
857
+ available: snap.view.available, serverCount: snap.servers.length,
858
+ lastError: 'fetch 不可用(受控实现构造失败——node:https 不可用,可回报环境问题)',
859
+ note: '官方目录快照刷新:目录缓存唯一写口=catalog 动作(suggest 只读);节流=lastAttemptAt 60min 窗口内零外呼;全量周期 24h 其余走增量。'
860
+ };
861
+ }
862
+ const r = await refreshOfficialCatalog({ cachePath, fetchImpl, now });
863
+ const out = {
864
+ action: 'catalog', ok: true, mode: r.mode, refreshed: r.refreshed, stale: !!r.stale,
865
+ available: !!r.available, serverCount: r.serverCount,
866
+ note: '官方目录快照刷新:目录缓存唯一写口=catalog 动作(suggest 只读);节流=lastAttemptAt 60min 窗口内零外呼;全量周期 24h 其余走增量;失败保留旧缓存只记 lastError。'
867
+ };
868
+ if (r.fetchedAt) out.fetchedAt = r.fetchedAt;
869
+ if (Number.isFinite(r.ageMs)) out.ageMs = r.ageMs;
870
+ if (r.lastError) out.lastError = r.lastError;
871
+ if (r.reason) out.reason = r.reason;
872
+ return out;
873
+ }
874
+
875
+ /** 目录缓存状态只读视图(不外呼不写盘;冻结契约导出)。 */
876
+ function catalogStatus(_ctx, { now = Date.now() } = {}) {
877
+ const read = readOfficialCatalog(officialCatalogPath(BUFENG_DIR));
878
+ if (!read.cache) {
879
+ return { action: 'catalog', available: false, serverCount: 0, reason: read.reason };
880
+ }
881
+ const c = read.cache;
882
+ const fetchedAt = typeof c.fetchedAt === 'string' ? c.fetchedAt : null;
883
+ const ageMs = fetchedAt ? now - Date.parse(fetchedAt) : null;
884
+ return {
885
+ action: 'catalog', available: true, serverCount: Array.isArray(c.servers) ? c.servers.length : 0,
886
+ fetchedAt,
887
+ ageMs: Number.isFinite(ageMs) ? ageMs : null,
888
+ stale: Number.isFinite(ageMs) ? ageMs > CATALOG_FULL_PERIOD_MS : false,
889
+ lastIncrementalAt: c.lastIncrementalAt ?? null, lastAttemptAt: c.lastAttemptAt ?? null, lastError: c.lastError ?? null
890
+ };
891
+ }
892
+
893
+ /**
894
+ * action=suggest 内核(冻结契约导出):{treeId,now}→建议单对象(顶层恰 9 键;无工具信封、零写盘零写账本)。
895
+ * 目录缓存只读(catalogCandidatesFor);面采集走注册闭包 ctx(与 list 同源);树/参数缺失=可读错误。
896
+ */
897
+ async function suggestSheet(ctx, { treeId, now = Date.now() } = {}) {
898
+ const tid = String(treeId ?? '').trim();
899
+ if (!tid) throw new Error('action=suggest 需要 treeId(bufeng_trees 查树 id)——建议单按树输出全节点分层建议');
900
+ const cur = await loadLedger();
901
+ const tree = (cur.trees ?? []).find((t) => t.id === tid) ?? null;
902
+ if (!tree) throw new Error('树 ' + tid + ' 不存在——先用 bufeng_trees 查树 id');
903
+ const caps = await collectCapabilities(ctx);
904
+ const snap = catalogCandidatesFor(officialCatalogPath(BUFENG_DIR), now);
905
+ /* C 批 §二:条目级跨岗万金油两趟——趟1 无处置跑全树闸计分(catalogGateScored 单源),统计每条目 gate-pass 岗数
906
+ * 建跨岗表(≥CROSS_ROLE_DROP_ROLES 岗出局/≥CROSS_ROLE_DOWN_ROLES 岗降权);树节点数 <CROSS_ROLE_MIN_ROLES
907
+ * 地板不建表(护小树夹具,仿 CATALOG_DF_MIN_CANDIDATES 语义)。趟2 按表走 suggestNodeEquipment 闸后处置
908
+ * (catalogCrossRole 内部透传);顶层 9 键契约与 note 文案冻结零变化。 */
909
+ let catalogCrossRole = null;
910
+ const treeNodes = tree.nodes ?? [];
911
+ if (treeNodes.length >= CROSS_ROLE_MIN_ROLES) {
912
+ const roleHits = new Map();
913
+ for (const node of treeNodes) {
914
+ for (const s of catalogGateScored(node, snap.candidates, snap.df)) {
915
+ roleHits.set(s.row.serverName, (roleHits.get(s.row.serverName) ?? 0) + 1);
916
+ }
917
+ }
918
+ catalogCrossRole = new Map();
919
+ for (const [serverName, hits] of roleHits) {
920
+ if (hits >= CROSS_ROLE_DROP_ROLES) catalogCrossRole.set(serverName, 'drop');
921
+ else if (hits >= CROSS_ROLE_DOWN_ROLES) catalogCrossRole.set(serverName, 'down');
922
+ }
923
+ if (!catalogCrossRole.size) catalogCrossRole = null;
924
+ }
925
+ const nodes = treeNodes.map((node) => {
926
+ const r = suggestNodeEquipment(node, { caps, catalogCandidates: snap.candidates, catalogDf: snap.df, catalogCrossRole, now }); // v0.62 B批:df 透传(内部口径,不进顶层 9 键契约);C 批:跨岗表透传(同口径)
927
+ return {
928
+ nodeId: node.id,
929
+ name: node.name,
930
+ role: node.role ?? '',
931
+ kind: node.kind ?? 'member',
932
+ treeId: tid,
933
+ equip: node.equip ?? null,
934
+ domainGaps: r.domainGaps,
935
+ suggestions: r.suggestions
936
+ };
937
+ });
938
+ let total = 0;
939
+ const byKind = {};
940
+ for (const n of nodes) {
941
+ for (const s of n.suggestions) {
942
+ total += 1;
943
+ byKind[s.kind] = (byKind[s.kind] ?? 0) + 1;
944
+ }
945
+ }
946
+ return {
947
+ schemaVersion: 1,
948
+ action: 'suggest',
949
+ treeId: tid,
950
+ generatedAt: new Date(now).toISOString(),
951
+ catalog: snap.view,
952
+ nodes,
953
+ summary: { nodes: nodes.length, suggestions: total, byKind },
954
+ threshold: {
955
+ matchedTokensMin: MATCH_MIN_TOKENS,
956
+ coreHitsMin: MATCH_CORE_MIN_HITS,
957
+ systemOnlyMinScore: MATCH_SYSTEM_ONLY_MIN_SCORE,
958
+ coverageFallback: MATCH_COVERAGE_FALLBACK,
959
+ weights: MATCH_WEIGHTS,
960
+ catalogGate: 'matched≥2 ∧ 核心域≥1 ∧(加权分≥3 ∨ 覆盖≥0.10)——公网层额外强制核心域≥1',
961
+ perNodeCap: SUGGEST_NODE_CAP,
962
+ installCap: SUGGEST_INSTALL_CAP,
963
+ lowWaterTopN: LOW_WATER_TOP_N
964
+ },
965
+ note: '分层建议单:本地层在上(已装未用/误配收窄/高危屏蔽/技能白名单/低置信低水位),公网层在下(官方目录元数据候选,rawTrust=metadata-only 非安全审计)。picks 一律精确名禁通配;采纳走 preview→审计后确认 apply;目录条目需人工安装(无自动安装通道);suggest 零写盘零写账本(目录缓存唯一写口=action=catalog)。'
966
+ };
967
+ }
968
+
969
+ /* ---------- v0.46.0 内核棒 phase3(k-mvnltcjf05x):preview/apply 收窄式工作流(设计稿 §5) ---------- */
970
+ /** preview 凭据登记(模块级内存表;nodeId 全局唯一):最近一次 preview 的 {previewHash, patch, at}。
971
+ * apply 双凭据=confirm:true + fromPreview===最近 previewHash;apply 成功后保留(同值重放→复算后深等=「没有需要修改的字段」幂等口),
972
+ * 节点装备/能力面漂移由「复算 hash≠fromPreview」拒绝并指路重新 preview。进程重启即清零(凭据不落账本)。 */
973
+ const lastPreviewByNode = new Map();
974
+
975
+ /** 键序无关深等(equip 四轴均为标量数组/字符串;JSON.stringify 直比会因键序不同误判不等)。 */
976
+ function deepEqEquip(a, b) {
977
+ if (a === b) return true;
978
+ if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false;
979
+ const ka = Object.keys(a).sort();
980
+ const kb = Object.keys(b).sort();
981
+ if (ka.length !== kb.length || ka.some((k, i) => k !== kb[i])) return false;
982
+ return ka.every((k) => {
983
+ const va = a[k]; const vb = b[k];
984
+ if (Array.isArray(va) && Array.isArray(vb)) return va.length === vb.length && va.every((x, i) => x === vb[i]);
985
+ return va === vb;
986
+ });
987
+ }
988
+
989
+ /** picks 入参校验(preview/apply 共用):只认 allowTools/denyTools/allowSkills 三轴,至少一项;
990
+ * 每轴必须是非空字符串数组且非空数组(清空/整删装备走 bufeng_update_node equip:null);agentPreset 恒拒(T4)。 */
991
+ function validateEquipPicks(args) {
992
+ const axes = { allowTools: args?.allowTools, denyTools: args?.denyTools, allowSkills: args?.allowSkills };
993
+ const picked = Object.keys(axes).filter((k) => axes[k] !== undefined);
994
+ if (!picked.length) {
995
+ throw new Error('action=preview/apply 需要至少一个装备轴 pick(allowTools/denyTools/allowSkills)——纯查看用 action=list/match;清空装备走 bufeng_update_node equip:null。');
996
+ }
997
+ const out = {};
998
+ for (const k of picked) {
999
+ const v = axes[k];
1000
+ if (!Array.isArray(v) || !v.length) {
1001
+ throw new Error(`${k} 必须是非空字符串数组(收到 ${JSON.stringify(v) ?? 'null'})——空数组/非数组不受理;清空该轴走 bufeng_update_node equip 显式置空。`);
1002
+ }
1003
+ for (const x of v) {
1004
+ if (typeof x !== 'string' || !x.trim()) {
1005
+ throw new Error(`${k} 数组元素必须是非空字符串(收到 ${JSON.stringify(x)})——MCP 工具用精确名(bufeng_capabilities list 查 mcpServers[].tools[].name)。`);
1006
+ }
1007
+ }
1008
+ out[k] = v.map((x) => x.trim());
1009
+ }
1010
+ return out;
1011
+ }
1012
+
1013
+ /** 装备补丁计算(preview/apply 同一纯函数——复算 hash 才能对得上):
1014
+ * T1 allowTools=所选+bufeng_* 插件全集(unionGovernanceTools,面不可用时不并入并在 effects 声明)——真收窄;
1015
+ * T2 denyTools=既有+所选追加(死名仅留档 warn);
1016
+ * T3 allowSkills:全默认集→不写该轴(可用集合不变;节点既有白名单原样保留);含非默认集→写入(真挂闸);
1017
+ * T4 agentPreset 禁改(既有值原样保留进补丁,保 updateNodeFields 整体替换语义不丢轴)。
1018
+ * 未涉及的既有轴(如只动 allowTools 时节点已有 allowSkills)原样带进补丁——补丁=写入后的完整 equip 值。 */
1019
+ function buildEquipPatch(node, picks, face, skills) {
1020
+ const curEquip = node?.equip ?? null;
1021
+ const patchObj = {};
1022
+ const effects = [];
1023
+ const warnings = [];
1024
+ const faceNames = face?.names ? Array.from(face.names) : null;
1025
+ if (picks.allowTools !== undefined) {
1026
+ const merged = unionGovernanceTools(picks.allowTools, faceNames);
1027
+ const govCount = merged.filter((n) => isGovernanceToolName(n)).length;
1028
+ const pickCount = merged.length - govCount;
1029
+ if (faceNames) {
1030
+ effects.push(`T1 工具白名单:allowTools=所选工具 ${pickCount} 个+插件工具 ${govCount} 个(共 ${merged.length} 个)——写入后本节点工具面收窄为这些工具,其余宿主工具将不可用;派单期仍会做漂移核对。`);
1031
+ for (const n of picks.allowTools) {
1032
+ if (!isGovernanceToolName(n) && !faceNames.includes(n)) warnings.push(`allowTools 名「${n}」当前不在宿主工具面(拼写错误或未注册)——apply 的写前漂移预检会拒绝;请修正后重新 preview。`);
1033
+ }
1034
+ } else {
1035
+ effects.push(`T1 工具白名单:allowTools=所选 ${merged.length} 个(宿主工具面视图不可用,bufeng_* 插件全集未并入——apply 会被写前漂移预检 fail-closed 拒绝;恢复工具面后重新 preview)。`);
1036
+ }
1037
+ patchObj.allowTools = merged;
1038
+ }
1039
+ if (picks.denyTools !== undefined) {
1040
+ const existing = Array.isArray(curEquip?.denyTools) ? curEquip.denyTools.filter((x) => typeof x === 'string' && x) : [];
1041
+ const appended = picks.denyTools.filter((n) => !existing.includes(n));
1042
+ patchObj.denyTools = [...existing, ...appended];
1043
+ effects.push(`T2 工具黑名单:denyTools 追加 ${appended.length} 个(现共 ${patchObj.denyTools.length} 个)——黑名单只挡列名工具;已不在工具面的死名仅留档不生效。`);
1044
+ if (faceNames) {
1045
+ for (const n of appended) {
1046
+ if (!isGovernanceToolName(n) && !faceNames.includes(n)) warnings.push(`denyTools 名「${n}」当前不在宿主工具面(死名仅留档不生效,派单不因此拒)。`);
1047
+ }
1048
+ }
1049
+ }
1050
+ if (picks.allowSkills !== undefined) {
1051
+ const defaultSet = new Set((skills ?? []).filter((s) => s?.defaultSkill).map((s) => s.name));
1052
+ const allDefault = picks.allowSkills.every((n) => defaultSet.has(n));
1053
+ const known = new Set((skills ?? []).map((s) => s?.name).filter(Boolean));
1054
+ if (allDefault) {
1055
+ if (Array.isArray(curEquip?.allowSkills) && curEquip.allowSkills.length) {
1056
+ patchObj.allowSkills = curEquip.allowSkills.filter((x) => typeof x === 'string' && x);
1057
+ effects.push(`T3 技能白名单:所选项均为默认集技能(可用集合不变),本次不写 allowSkills;节点既有白名单 ${patchObj.allowSkills.length} 项原样保留。运行期入口=bufeng_skill。`);
1058
+ } else {
1059
+ effects.push('T3 技能白名单:所选项均为默认集技能(可用集合不变),本次不写 allowSkills;运行期入口=bufeng_skill。');
1060
+ }
1061
+ } else {
1062
+ patchObj.allowSkills = [...picks.allowSkills];
1063
+ const nonDefault = picks.allowSkills.filter((n) => !defaultSet.has(n));
1064
+ effects.push(`T3 技能白名单:写入 allowSkills ${patchObj.allowSkills.length} 项(含非默认集技能 ${nonDefault.length} 个:${nonDefault.join('、')})——可用技能集合收窄为默认集∪白名单(语义B)。`);
1065
+ }
1066
+ for (const n of picks.allowSkills) {
1067
+ if (!known.has(n)) warnings.push(`allowSkills 名「${n}」当前不在技能目录(失效名会在能力面 staleSkills 标注;bufeng_skill 调用时会被拒)。`);
1068
+ }
1069
+ }
1070
+ // 未涉及的既有轴原样保留(补丁=写入后的完整 equip;agentPreset 只保留不改——T4)
1071
+ if (curEquip?.agentPreset) patchObj.agentPreset = curEquip.agentPreset;
1072
+ if (picks.allowTools === undefined && Array.isArray(curEquip?.allowTools)) patchObj.allowTools = curEquip.allowTools.filter((x) => typeof x === 'string' && x);
1073
+ if (picks.denyTools === undefined && Array.isArray(curEquip?.denyTools)) patchObj.denyTools = curEquip.denyTools.filter((x) => typeof x === 'string' && x);
1074
+ if (picks.allowSkills === undefined && Array.isArray(curEquip?.allowSkills)) patchObj.allowSkills = curEquip.allowSkills.filter((x) => typeof x === 'string' && x);
1075
+ return { patch: patchObj, effects, warnings };
1076
+ }
1077
+
1078
+ /** previewHash=sha256(JSON.stringify(patch)+nodeId+VERSION) 前 16 位 hex(能力面版本=core VERSION;patch 键序由构造顺序固定,同输入同输出)。 */
1079
+ function previewHashOf(patchObj, nodeId) {
1080
+ return createHash('sha256').update(JSON.stringify(patchObj) + nodeId + VERSION).digest('hex').slice(0, 16);
1081
+ }
1082
+
1083
+ /* ---------- v0.48.0 看板一键装备通道·实现②(k-mvqeqp4407a,ADR docs/决策/2026-10-27-v0.48.0-看板一键装备通道.md §8):装备核心函数 ----------
1084
+ * preview/apply 分支内联体(v0.46.0 工具分支原文)平移至此为两个导出核心函数,供工具 handler 薄壳与看板端点(lib/board/server.js)共用——
1085
+ * 与工具路径是同一段代码,不是复制品(ADR §9:T1-T4 与漂移预检全程在位)。
1086
+ * 凭据表契约(ADR §4):唯一凭据表=上方 lastPreviewByNode(模块级 Map,本身不导出)——工具与看板共享同表:
1087
+ * board 侧 import 本模块(board→tools 合法依赖方向)即 ESM 同进程单例共享本 Map,禁止在 board 侧自建第二张表或复制校验逻辑;
1088
+ * 登记与校验只经下列两个核心函数,任何入口无法伪造/绕过凭据。core 不做 resolveCaller(身份/权限治理留在工具层 execute 内的
1089
+ * 权限矩阵——ADR §3,对齐 updateNodeModelCore/setProjectLeaderCore「core 不判身份」先例;面板路径权限=客户面板二次确认+端点仅本地可达)。 */
1090
+ async function previewEquipChange(input, ctx) {
1091
+ // v0.48.0(ADR §8):只读预览——校验 picks→算补丁→登记内存凭据;零账本零文件写入(行为与 v0.46.0 工具分支逐字一致)。
1092
+ const nodeId = String(input?.nodeId ?? '').trim();
1093
+ if (!nodeId) throw new Error('action=preview 需要 nodeId(bufeng_trees 查节点 id)');
1094
+ if (input?.agentPreset !== undefined) throw new Error('preview/apply 不支持 agentPreset(T4 禁改):预设变更走 bufeng_update_node equip.agentPreset(活注册表校验在同一预检链)。');
1095
+ const picks = validateEquipPicks(input);
1096
+ const cur = await loadLedger();
1097
+ const hit = findNodeAnywhere(cur, nodeId);
1098
+ if (!hit) throw new Error(`节点 ${nodeId} 不存在(active 树优先检索)——先用 bufeng_trees 查节点 id`);
1099
+ const face = collectVisibleToolNames(ctx);
1100
+ const capsPv = await collectCapabilities(ctx);
1101
+ const built = buildEquipPatch(hit.node, picks, face, capsPv?.skills ?? []);
1102
+ const previewHash = previewHashOf(built.patch, nodeId);
1103
+ lastPreviewByNode.set(nodeId, { previewHash, patch: built.patch, at: Date.now() });
1104
+ return {
1105
+ action: 'preview',
1106
+ ok: true,
1107
+ nodeId,
1108
+ patch: built.patch,
1109
+ effects: built.effects,
1110
+ ...(built.warnings.length ? { warnings: built.warnings } : {}),
1111
+ previewHash,
1112
+ before: hit.node.equip ?? {}, // v0.46.1 P0 热修(k-mvnxil3w04g):equip null/undefined 时恒 {}——output schema 声明 before:{type:'object'},null 即宿主合约「value.before must be an object」整包拒
1113
+ after: built.patch,
1114
+ note: 'preview 只读:不写账本不落盘(仅在内存登记本节点 preview 凭据)。确认后 action=apply(confirm:true + fromPreview=本 previewHash)落盘;apply 前节点装备或能力面变化会要求重新 preview。'
1115
+ };
1116
+ }
1117
+
1118
+ async function applyEquipChange(input, ctx) {
1119
+ // v0.48.0(ADR §8):双凭据写——四拒→复算(TOCTOU 防线)→同值幂等→写前漂移预检→唯一写点 domain.updateNodeFields。
1120
+ // actor 由调用方传入(缺省回退工具文案 `bufeng_capabilities apply(previewHash=…)`;面板路径传「面板(客户确认)(previewHash=…)」——core 不判身份)。
1121
+ const nodeId = String(input?.nodeId ?? '').trim();
1122
+ if (!nodeId) throw new Error('action=apply 需要 nodeId(bufeng_trees 查节点 id)');
1123
+ if (input?.agentPreset !== undefined) throw new Error('preview/apply 不支持 agentPreset(T4 禁改):预设变更走 bufeng_update_node equip.agentPreset。');
1124
+ const picks = validateEquipPicks(input);
1125
+ const cur = await loadLedger();
1126
+ const targetP = findNodeAnywhere(cur, nodeId);
1127
+ if (!targetP) throw new Error(`节点 ${nodeId} 不存在(active 树优先检索)——先用 bufeng_trees 查节点 id`);
1128
+ if (input?.confirm !== true) {
1129
+ throw new Error('apply 需要双凭据:confirm:true + fromPreview=最近一次 preview 的 previewHash(当前缺失 confirm)——先 action=preview 生成装备变更预览,确认后携带两凭据重试。');
1130
+ }
1131
+ const fromPreview = typeof input?.fromPreview === 'string' ? input.fromPreview.trim() : '';
1132
+ if (!fromPreview) {
1133
+ throw new Error('apply 需要双凭据:confirm:true + fromPreview=最近一次 preview 的 previewHash(当前缺失 fromPreview)——先 action=preview 取 previewHash,确认后携带两凭据重试。');
1134
+ }
1135
+ const stored = lastPreviewByNode.get(nodeId);
1136
+ if (!stored) {
1137
+ throw new Error(`节点 ${nodeId} 无前置 preview(本进程内未见该节点的 preview 凭据;preview 凭据不落账本,进程重启即清零)——先 action=preview 生成装备变更预览再 apply。`);
1138
+ }
1139
+ if (fromPreview !== stored.previewHash) {
1140
+ throw new Error(`fromPreview 与最近一次 preview 不匹配(传入 ${fromPreview},最新 ${stored.previewHash};同节点以最后一次 preview 为准)——请重新 action=preview 后携带新 previewHash 重试。`);
1141
+ }
1142
+ // 复算(现节点+现能力面;与 preview 同一 buildEquipPatch/previewHashOf 才可比)——apply 重传 picks 的 TOCTOU 复算防线(ADR §4,随函数平移保留)
1143
+ const hitA = findNodeAnywhere(cur, nodeId);
1144
+ const faceA = collectVisibleToolNames(ctx);
1145
+ const capsA = await collectCapabilities(ctx);
1146
+ const builtA = buildEquipPatch(hitA.node, picks, faceA, capsA?.skills ?? []);
1147
+ const recomputed = previewHashOf(builtA.patch, nodeId);
1148
+ if (recomputed !== fromPreview) {
1149
+ throw new Error(`节点装备或能力面自 preview 后已变化(按当前状态复算 previewHash=${recomputed} ≠ 传入 ${fromPreview})——请重新 action=preview 后再 apply。`);
1150
+ }
1151
+ // 同值幂等(updateNodeFields 对 equip 是引用比较,幂等判定收口在本函数)
1152
+ if (deepEqEquip(builtA.patch, hitA.node.equip ?? null)) {
1153
+ return { action: 'apply', ok: true, nodeId, changed: [], previewHash: fromPreview, note: '没有需要修改的字段' };
1154
+ }
1155
+ // 写前漂移预检(与派单链同一纯函数 checkEquipToolsDrift:bufeng_* 豁免不看面;unknownFace fail-closed)
1156
+ const drift = checkEquipToolsDrift(builtA.patch, faceA?.names ?? null);
1157
+ if (drift.unknownFace) {
1158
+ throw new Error(`写前漂移预检未通过:宿主工具面视图不可用(${faceA?.degrade ?? 'ctx.tools.view 缺失或形状异常'})——无法核对 allowTools 名单,为防误配本次 apply 被拒绝(fail-closed)。请恢复工具面视图后重新 preview/apply。`);
1159
+ }
1160
+ if (drift.driftedAllow?.length) {
1161
+ throw new Error(`写前漂移预检未通过:allowTools 含当前工具面不存在的名字(${drift.driftedAllow.join('、')})——这些名字写入后派单期同样会被拒;请修正 picks 后重新 preview。`);
1162
+ }
1163
+ // 唯一写点:domain.updateNodeFields(同 bufeng_update_node 写路径/同事件 bufeng.node.updated,note 经 actor 携 previewHash)
1164
+ const actor = typeof input?.actor === 'string' && input.actor ? input.actor : `bufeng_capabilities apply(previewHash=${fromPreview})`;
1165
+ const res = await updateNodeFields({ nodeId, equip: builtA.patch, actor });
1166
+ return { action: 'apply', ok: true, nodeId, changed: res?.changed ?? [], previewHash: fromPreview, note: `已按 preview 落盘(previewHash=${fromPreview};bufeng.node.updated 事件 note 携该凭据;装备自该节点下次派单的新会话起生效)。` };
1167
+ }
1168
+
1169
+ /** 工具注册:bufeng_capabilities{action:list|match|coverage|preview|apply}——list/match/coverage 只读;preview 只读+内存凭据;apply 双凭据写(v0.46.0)。 */
1170
+ function registerCapabilitiesTools(ctx, ledger) {
1171
+ safeRegister(ctx, ledger, {
1172
+ name: 'bufeng_capabilities',
1173
+ description:
1174
+ '捕风工坊:能力面查看(只读;v0.29.2 批2 装备投影随动)。action=list 列出宿主可用能力——技能(含 modelInvocable 口径与' +
1175
+ '默认集标注 defaultSkill:source=bundled 实时判定)、MCP 工具面(ctx.tools 全局视图按 serverName 归并,只展示工具面不读宿主 profile)、' +
1176
+ '智能体预设清单(标注 MCP 构成;宿主无活注册表时 presets 按静态默认清单标注·当前宿主不可配,agentPreset 装备校验走活注册表)、' +
1177
+ '每节点装备现状投影(agentPreset/allowTools/denyTools/allowSkills——含失效标注 staleSkills:' +
1178
+ 'allowSkills 名单中已不在当前技能目录的名字)。action=match 输入 nodeId:按节点能力域语料' +
1179
+ '(name+role+systemPrompt 分域加权 name×3/role×2/提示词×1)对技能与 MCP 工具做词汇重叠计分' +
1180
+ '(v0.30.0 批3 调优:命中≥2 且「核心域≥1 / 加权分≥3 / 覆盖≥0.10」三选一;coverage 仅诊断;top 10),' +
1181
+ '输出推荐+命中词+分域理由(v0.45.0 批1:候选语料做中文别名展开——英文描述含触发词时并入中文键 token,桥接中英语汇;' +
1182
+ '正式闸零命中时按加权分取 top-3 低置信推荐 lowConfidence=true——冷启动低水位,完全零重叠保持空)。' +
1183
+ 'list/match/coverage 三动作零装备写入;装备变更 v0.46.0 起走收窄式 preview→apply(MCP 工具用 allowTools/denyTools 精确名,' +
1184
+ '技能白名单用 allowSkills——语义B:undefined=透传、[]=仅默认集、[...]=默认集∪额外项;运行期入口=bufeng_skill;' +
1185
+ '预设 agentPreset 不走本工作流,仍走 bufeng_update_node)。' +
1186
+ 'action=preview(v0.46.0,只读):输入 nodeId+至少一个装备轴 pick(allowTools/denyTools/allowSkills),' +
1187
+ '生成装备变更补丁 {patch,effects,warnings,previewHash,before,after}——T1 allowTools 自动并入 bufeng_* 插件全集、' +
1188
+ 'T2 denyTools 追加式、T3 默认集技能不写 allowSkills(可用集合不变)、T4 agentPreset 恒拒;preview 不写账本不落盘。' +
1189
+ 'action=apply(v0.46.0,双凭据写):须 confirm:true 且 fromPreview=最近一次 preview 的 previewHash;' +
1190
+ '哈希缺失/不匹配/无前置 preview/节点装备或能力面自 preview 后已变化,一律拒绝并指路重新 preview;' +
1191
+ '权限同 bufeng_update_node 装备轴分级(总管→自己与都管、都管→名下成员,其余拒);写前做同源漂移预检' +
1192
+ '(allowTools 含工具面不存在的名字或视图不可用=拒);落盘走与 bufeng_update_node 同一条写路径与事件。' +
1193
+ 'action=coverage(v0.43.0 编制覆盖机制,只读):输入 projectId 或 nodeId(都管)二选一,输出项目覆盖矩阵' +
1194
+ '(coveragePlan 环节×名下席位对照)——每环节 status=ok|gap(缺口原因 node-missing/node-retired/no-seat)、' +
1195
+ '团队席位清单 team、未被引用的空闲席位 idleSeats;无矩阵项目按 no-plan 语义列出(reason=no-plan,派单只告警不阻断);' +
1196
+ '补齐走 bufeng_project update coveragePlan。本动作只读零写入(不落账本事件、不改账本字节)。' +
1197
+ 'action=catalog(v0.60.0 S2a):刷新官方 MCP 目录快照到 <BUFENG_DIR>/catalog/official-registry.json——' +
1198
+ '源白名单=registry.modelcontextprotocol.io(HTTPS;15s 超时/单轮 5MB/20 页上限),全量周期 24h 其余走增量(updated_since+version=latest 游标翻页),' +
1199
+ '60min 限流窗口(lastAttemptAt 新鲜即零外呼);status=deleted 剔除、deprecated 保留标注;失败保留旧缓存只记 lastError(绝不炸 suggest);' +
1200
+ '目录缓存唯一写口=本动作(suggest 只读)。' +
1201
+ 'action=suggest(v0.60.0 S2a,只读零写):输入 treeId 出分层建议单(顶层九键/单条十五键)——本地层=装备现状对账(已装未用/误配收窄/高危屏蔽/技能白名单/低置信低水位),' +
1202
+ '公网层=官方目录候选(额外强制核心域≥1;目录元数据,需人工安装;无自动安装、无自动 apply,采纳走 preview 审计后确认)。',
1203
+ parameters: {
1204
+ type: 'object',
1205
+ properties: {
1206
+ action: { type: 'string', enum: ['list', 'match', 'coverage', 'preview', 'apply', 'catalog', 'suggest'], description: 'list=能力清单(skills/MCP 工具面/presets/每节点装备投影);match=节点能力匹配推荐;coverage=覆盖矩阵对照(v0.43.0 只读:projectId 或 nodeId(都管)二选一);preview=装备变更预览(v0.46.0 只读,出 previewHash);apply=按 preview 落盘(v0.46.0,须 confirm:true+fromPreview 双凭据);catalog=官方目录快照刷新(v0.60.0 S2a,唯一缓存写口);suggest=按岗分层建议单(v0.60.0 S2a,只读;treeId 必填)' },
1207
+ nodeId: { type: 'string', description: 'match 必填:目标节点 id(见 bufeng_trees);coverage 时指都管节点 id(kind=leader)' },
1208
+ projectId: { type: 'string', description: 'coverage 可选(优先于 nodeId):项目 id(bufeng_project list 查询),输出该项目环节×席位对照与缺口清单' },
1209
+ treeId: { type: 'string', description: 'suggest 必填:目标树 id(bufeng_trees 查询)——输出该树全节点分层建议单(本地层+公网层,只读零写)' },
1210
+ allowTools: { type: 'array', items: { type: 'string' }, description: 'preview/apply 的 T1 工具白名单 pick:所选 MCP 工具精确名(list 查 mcpServers[].tools[].name);bufeng_* 插件全集自动并入;真收窄(其余宿主工具不可用)' },
1211
+ denyTools: { type: 'array', items: { type: 'string' }, description: 'preview/apply 的 T2 工具黑名单 pick:追加式并入既有黑名单(只挡列名工具;死名仅留档)' },
1212
+ allowSkills: { type: 'array', items: { type: 'string' }, description: 'preview/apply 的 T3 技能白名单 pick:全默认集=不写(可用集合不变);含非默认集技能才写入(真挂闸)' },
1213
+ confirm: { type: 'boolean', description: 'apply 双凭据之一:须显式传 true(确认 preview 的补丁内容)' },
1214
+ fromPreview: { type: 'string', description: 'apply 双凭据之二:最近一次 action=preview 返回的 previewHash(16 位);不匹配即拒并要求重新 preview' }
1215
+ },
1216
+ required: ['action']
1217
+ },
1218
+ output: {
1219
+ schema: objSchema({
1220
+ action: { type: 'string' },
1221
+ skills: { type: 'array', items: { type: 'object' } },
1222
+ mcpServers: { type: 'array', items: { type: 'object' } },
1223
+ presets: { type: 'array', items: { type: 'object' } },
1224
+ nodeEquip: { type: 'array', items: { type: 'object' } },
1225
+ node: { type: 'object' },
1226
+ mode: { type: 'string' },
1227
+ project: { type: 'object' },
1228
+ team: { type: 'array', items: { type: 'object' } },
1229
+ idleSeats: { type: 'array', items: { type: 'object' } },
1230
+ projects: { type: 'array', items: { type: 'object' } },
1231
+ coverage: { type: 'object' },
1232
+ recommendations: { type: 'array', items: { type: 'object' } },
1233
+ threshold: { type: 'object' },
1234
+ ok: { type: 'boolean' },
1235
+ patch: { type: 'object' },
1236
+ effects: { type: 'array', items: { type: 'string' } },
1237
+ warnings: { type: 'array', items: { type: 'string' } },
1238
+ previewHash: { type: 'string' },
1239
+ before: { type: 'object' },
1240
+ after: { type: 'object' },
1241
+ changed: { type: 'array', items: { type: 'string' } },
1242
+ schemaVersion: { type: 'number' },
1243
+ treeId: { type: 'string' },
1244
+ generatedAt: { type: 'string' },
1245
+ catalog: { type: 'object' },
1246
+ nodes: { type: 'array', items: { type: 'object' } },
1247
+ summary: { type: 'object' },
1248
+ refreshed: { type: 'boolean' },
1249
+ available: { type: 'boolean' },
1250
+ serverCount: { type: 'number' },
1251
+ note: { type: 'string' }
1252
+ }),
1253
+ render: jsonRender
1254
+ },
1255
+ execute: async (args, exec) => {
1256
+ const action = args?.action;
1257
+ const cur = await loadLedger();
1258
+ const hint = identityHintFor(cur, exec?.agent?.id ?? null);
1259
+ if (action === 'list') {
1260
+ const caps = await collectCapabilities(ctx);
1261
+ // v0.29.2 批2:allowSkills 失效标注(m00243 fail-visible 在查看面的落点)——
1262
+ // 名单中已不在当前技能目录的名字(改名/下架),实时对账不落缓存;注册表降级(skills 空)时不做失效判定(无真相源不误报)。
1263
+ const liveSkillNames = new Set(caps.skills.map((s) => s.name));
1264
+ const registryLive = caps.skills.length > 0 || !caps.skillsNote;
1265
+ const nodeEquip = cur.trees
1266
+ .filter((t) => t.status === 'active')
1267
+ .flatMap((t) => (t.nodes ?? []).map((n) => {
1268
+ const allowSkills = Array.isArray(n.equip?.allowSkills) ? n.equip.allowSkills : null;
1269
+ const staleSkills = allowSkills && registryLive
1270
+ ? allowSkills.filter((x) => !liveSkillNames.has(x))
1271
+ : null; // null=未配 allowSkills 或注册表降级(无从判定,不误报)
1272
+ return {
1273
+ treeId: t.id,
1274
+ treeName: t.name,
1275
+ nodeId: n.id,
1276
+ name: n.name,
1277
+ kind: n.kind ?? 'member',
1278
+ kindLabel: displayKindOf(n.kind),
1279
+ equip: n.equip ?? null, // {agentPreset?,allowTools?,denyTools?,allowSkills?}(bufeng_update_node 写入;null=未装备)
1280
+ ...(allowSkills ? { skillGate: 'on' } : {}), // 语义B:allowSkills 在场(含空数组)即挂闸
1281
+ ...(staleSkills !== null && staleSkills.length ? { staleSkills } : {})
1282
+ };
1283
+ }));
1284
+ return {
1285
+ action: 'list',
1286
+ ...caps,
1287
+ nodeEquip,
1288
+ note: '装备变更走 bufeng_update_node(agentPreset 自该节点下次派单的新会话起生效;allowTools/denyTools 对已挂会话立即拆旧换新;' +
1289
+ 'allowSkills 语义B 三态:undefined=透传全目录、空数组=仅默认集(defaultSkill 标注,source=bundled 实时判定)、非空=默认集∪额外项,运行期入口=bufeng_skill)。' +
1290
+ '本工具只读:不读宿主 profile、不写任何装备。',
1291
+ ...(hint ? { identityHint: hint } : {})
1292
+ };
1293
+ }
1294
+ if (action === 'match') {
1295
+ const nodeId = String(args?.nodeId ?? '').trim();
1296
+ if (!nodeId) throw new Error('action=match 需要 nodeId(bufeng_trees 查节点 id)');
1297
+ const hit = findNodeAnywhere(cur, nodeId);
1298
+ if (!hit) throw new Error(`节点 ${nodeId} 不存在(active 树优先检索)——先用 bufeng_trees 查节点 id`);
1299
+ const caps = await collectCapabilities(ctx);
1300
+ const m = matchNodeCapabilities(hit.node, caps);
1301
+ return {
1302
+ action: 'match',
1303
+ node: {
1304
+ nodeId: hit.node.id,
1305
+ name: hit.node.name,
1306
+ kindLabel: displayKindOf(hit.node.kind),
1307
+ treeId: hit.tree.id,
1308
+ treeName: hit.tree.name,
1309
+ treeStatus: hit.tree.status,
1310
+ corpusTokens: m.corpusTokens,
1311
+ equip: hit.node.equip ?? null
1312
+ },
1313
+ recommendations: m.recommendations,
1314
+ threshold: {
1315
+ matchedTokens: MATCH_MIN_TOKENS,
1316
+ coreHits: MATCH_CORE_MIN_HITS,
1317
+ systemOnlyMinScore: MATCH_SYSTEM_ONLY_MIN_SCORE,
1318
+ coverageFallback: MATCH_COVERAGE_FALLBACK,
1319
+ weights: MATCH_WEIGHTS,
1320
+ topN: MATCH_TOP_N,
1321
+ coverage: 'diagnostic' // v0.30.0 批3:coverage 只展示不设闸(长提示词稀释治理)
1322
+ },
1323
+ note: '推荐只是只读建议(词汇重叠分域加权计分,无 embedding;coverage 仅诊断)——本工具不做任何 apply;应用推荐走 bufeng_update_node(MCP 工具用 allowTools/denyTools 精确名,预设用 agentPreset,技能白名单用 allowSkills;运行期入口=bufeng_skill)。',
1324
+ ...(hint ? { identityHint: hint } : {})
1325
+ };
1326
+ }
1327
+ if (action === 'coverage') {
1328
+ // v0.43.0 覆盖矩阵对照(只读红线:不 saveLedger、不 recordEvent、账本字节与 mtime 零变化)。
1329
+ // projectId 分支优先:项目环节×席位对照 + 缺口清单 + 空闲席位;nodeId 分支:都管视角(名下成员+绑定项目)。
1330
+ const covProjectId = String(args?.projectId ?? '').trim();
1331
+ const covNodeId = String(args?.nodeId ?? '').trim();
1332
+ if (covProjectId) {
1333
+ const projects = cur.projects ?? [];
1334
+ const p = projects.find((x) => x.id === covProjectId);
1335
+ if (!p) {
1336
+ const names = projects.map((x) => `${x.name}(${x.id})`).join('、') || '(项目库为空)';
1337
+ throw new Error(`项目 ${covProjectId} 不存在(bufeng_project list 查询)。可用项目:${names}`);
1338
+ }
1339
+ const team = coverageTeamOf(p, cur);
1340
+ const coverage = coverageReportOf(p, cur);
1341
+ return {
1342
+ action: 'coverage',
1343
+ mode: 'project',
1344
+ project: { id: p.id, name: p.name, leaderNodeId: p.leaderNodeId ?? null, leader: team.leader },
1345
+ coverage,
1346
+ team: team.members,
1347
+ idleSeats: team.members.filter((m) => !m.covered).map((m) => ({ nodeId: m.nodeId, name: m.name, role: m.role })),
1348
+ note: '覆盖矩阵对照(只读):环节 status=ok|gap(缺口原因 node-missing/node-retired/no-seat;无矩阵 reason=no-plan)。'
1349
+ + (coverage.present
1350
+ ? `矩阵 ${coverage.stages.length} 环节、缺口 ${coverage.gaps.length} 个;空闲席位=未被任何环节以 nodeId 引用的名下成员。`
1351
+ : '该项目未定义覆盖矩阵(coveragePlan=null,派单只告警不阻断);补齐:bufeng_project { action: "update", id, coveragePlan: { stages: [...] } }。')
1352
+ + 'capability 环节按归一化文本包含匹配(NFKC+小写)命中成员 name/role;本项目零账本写入。',
1353
+ ...(hint ? { identityHint: hint } : {})
1354
+ };
1355
+ }
1356
+ if (covNodeId) {
1357
+ const hit = findNodeAnywhere(cur, covNodeId);
1358
+ if (!hit) throw new Error(`节点 ${covNodeId} 不存在(active 树优先检索)——先用 bufeng_trees 查节点 id`);
1359
+ if (hit.node.kind !== 'leader') throw new Error(`节点「${hit.node.name}」(${covNodeId})不是都管(kind=leader)——coverage 的 nodeId 分支只接受都管;节点清单用 bufeng_trees 查询`);
1360
+ // v0.43.1 技术债b:席位收集改走 domain 的 coverageTeamOf(active 树过滤——与 coverageReportOf/coverageTeamOf 口径一致,archived 树内成员不再入列);
1361
+ // bind 未解析(都管已退役/悬挂/只在归档树)时 coverageTeamOf 会回退全席位集,此处收口为空团队(防悬挂误扩)。
1362
+ const covTeam = coverageTeamOf({ leaderNodeId: covNodeId }, cur);
1363
+ const team = covTeam.leader
1364
+ ? covTeam.members.map((m) => ({ nodeId: m.nodeId, name: m.name, role: m.role, kind: m.kind ?? 'member', status: m.status }))
1365
+ : [];
1366
+ const projects = (cur.projects ?? []).filter((p) => p.leaderNodeId === covNodeId)
1367
+ .map((p) => ({ projectId: p.id, name: p.name, coverage: coverageReportOf(p, cur) }));
1368
+ return {
1369
+ action: 'coverage',
1370
+ mode: 'leader',
1371
+ node: { nodeId: hit.node.id, name: hit.node.name, treeId: hit.tree.id, treeName: hit.tree.name, status: hit.node.status },
1372
+ team,
1373
+ projects,
1374
+ note: `都管「${hit.node.name}」覆盖对照(只读):名下成员 ${team.length} 席、绑定项目 ${projects.length} 个(无矩阵项目按 no-plan 列出,reason=no-plan);环节缺口补齐走 bufeng_project update coveragePlan;本动作零账本写入。`,
1375
+ ...(hint ? { identityHint: hint } : {})
1376
+ };
1377
+ }
1378
+ throw new Error('action=coverage 需要 projectId 或 nodeId(都管)');
1379
+ }
1380
+ if (action === 'preview') {
1381
+ // v0.48.0 薄壳化(ADR §8):内联体平移至 previewEquipChange(工具/看板两路径同段代码,不是复制品);
1382
+ // 工具路径 identityHint 由本壳合并(core 返回体不含——core 不判身份,面板路径无需)。
1383
+ const res = await previewEquipChange(args, ctx);
1384
+ return { ...res, ...(hint ? { identityHint: hint } : {}) };
1385
+ }
1386
+ if (action === 'apply') {
1387
+ // v0.46.0 收窄式工作流第二步(双凭据写):权限链与 bufeng_update_node equip 轴同源同文案;
1388
+ // v0.48.0 薄壳化(ADR §8):下方权限矩阵留本分支原位(仅工具路径走——core 不判身份,ADR §3);
1389
+ // 凭据四拒→复算(TOCTOU)→同值幂等→写前漂移预检→唯一写点 await updateNodeFields({nodeId, equip:patch, actor}) 已平移至 applyEquipChange。
1390
+ const nodeId = String(args?.nodeId ?? '').trim();
1391
+ if (!nodeId) throw new Error('action=apply 需要 nodeId(bufeng_trees 查节点 id)');
1392
+ if (args?.agentPreset !== undefined) throw new Error('preview/apply 不支持 agentPreset(T4 禁改):预设变更走 bufeng_update_node equip.agentPreset。');
1393
+ const picks = validateEquipPicks(args);
1394
+ const targetP = findNodeAnywhere(cur, nodeId);
1395
+ if (!targetP) throw new Error(`节点 ${nodeId} 不存在(active 树优先检索)——先用 bufeng_trees 查节点 id`);
1396
+ if (targetP.tree.status === 'active') {
1397
+ const identity = resolveCaller(cur, targetP.tree, exec?.agent?.id ?? null);
1398
+ const callerIsMaster = identity.isRoot || isRootKind(identity.node?.kind);
1399
+ if (isRootKind(targetP.node.kind)) {
1400
+ if (!callerIsMaster) {
1401
+ throw new Error(`「${targetP.node.name}」是工坊总管(根节点):只有总管(树根客户会话)能修改其 name/role;都管/成员要调整时写进 bufeng_report 的 summary 上报总管裁决。`);
1402
+ }
1403
+ } else if (!callerIsMaster) {
1404
+ if (identity.node?.kind === 'leader') {
1405
+ if (targetP.node.treeId !== identity.node.treeId || targetP.node.leaderId !== identity.node.id) {
1406
+ throw new Error('都管只能编辑自己名下成员的定义;改其他节点(含你自己)的设定请写进 bufeng_report 上报总管。');
1407
+ }
1408
+ } else {
1409
+ throw new Error('成员/无身份会话不能修改节点定义;建议写进 bufeng_report 的 summary 上报。');
1410
+ }
1411
+ }
1412
+ // 装备轴分级(与 trees.js bufeng_update_node 同文案,m11 互证钉板):总管给成员配装备越级硬拒
1413
+ if (callerIsMaster && !isRootKind(targetP.node.kind) && (targetP.node.kind ?? 'member') === 'member') {
1414
+ throw new Error(
1415
+ `「${targetP.node.name}」是成员节点。skill/MCP 装备按分级权限:总管只能给自己和都管配置,都管只能给自己名下成员配置;你无权改此节点。` +
1416
+ '需要变更请写进 bufeng_report 的 summary 上报,或请有权限的总管/都管操作。'
1417
+ );
1418
+ }
1419
+ }
1420
+ return applyEquipChange(args, ctx);
1421
+ }
1422
+ if (action === 'catalog') {
1423
+ // v0.60.0 S2a:目录快照刷新(唯一缓存写口;节流/全量/增量/失败降级全在 lib/catalog.js 叶子内——绝不抛错,失败=状态回显)。
1424
+ const res = await catalogRefresh(ctx, { now: Date.now(), exec });
1425
+ return { ...res, ...(hint ? { identityHint: hint } : {}) };
1426
+ }
1427
+ if (action === 'suggest') {
1428
+ // v0.60.0 S2a:分层建议单(顶层九键原样返回——无工具信封、零写盘零写账本;参数/树缺失=可读错误)。
1429
+ return await suggestSheet(ctx, { treeId: args?.treeId, now: Date.now() });
1430
+ }
1431
+ throw new Error(`未知 action「${action}」:合法值 list/match/coverage/preview/apply/catalog/suggest`);
1432
+ }
1433
+ });
1434
+ }
1435
+
1436
+ export {
1437
+ registerCapabilitiesTools,
1438
+ previewEquipChange, // v0.48.0 ADR §8 装备核心函数(preview 只读+内存凭据登记):工具 handler 薄壳与看板端点共用;lastPreviewByNode 本身不导出(ADR §4 唯一凭据表契约)
1439
+ applyEquipChange, // v0.48.0 ADR §8 装备核心函数(apply 双凭据写,唯一写点=domain.updateNodeFields;actor 由调用方传入,core 不判身份)
1440
+ collectCapabilities,
1441
+ // v0.46.0 宣传段四函数(capabilityNotePayload/collectCapabilitiesCached/capabilityNoteForDispatch/clearCapabilitiesDispatchCache)为定义处内联 export,不在此重复列名(重复列名=Duplicate export 编译错)
1442
+ matchNodeCapabilities,
1443
+ slimRecommendation,
1444
+ candidateCorpusTokens, // v0.45.0 批1-A1:别名展开单元级断言入口(空表等价锚)
1445
+ getAliasIndex, // v0.45.0 批1-A1:别名索引单例(测试探针只读)
1446
+ MATCH_MIN_TOKENS,
1447
+ MATCH_WEIGHTS,
1448
+ MATCH_CORE_MIN_HITS,
1449
+ MATCH_SYSTEM_ONLY_MIN_SCORE,
1450
+ MATCH_COVERAGE_FALLBACK,
1451
+ MATCH_TOP_N,
1452
+ LOW_WATER_TOP_N,
1453
+ // v0.60.0 S2a(冻结契约新增导出):建议单/目录动作内核入口(S2b 看板端点与测试探针共用;suggestNodeEquipment=纯函数零副作用)
1454
+ suggestSheet,
1455
+ catalogStatus,
1456
+ catalogRefresh,
1457
+ suggestNodeEquipment,
1458
+ getCatalogAliasIndex,
1459
+ catalogCandidatesFor, // v0.62 B批:目录候选+df 地板单元级断言入口(纯读缓存零副作用)
1460
+ sanitizeSuggestDescription // 2026-11-04 推荐卡功能描述行批:净化单点 helper(C3 契约)——m4 C 族净化矩阵直测入口
1461
+ };