dsh-subagent-profile 0.3.3 → 0.3.4

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.mjs CHANGED
@@ -1,12 +1,6 @@
1
- // index.mjs — dsh-subagent-profile 宿主侧正式插件 bundle(只做装配)。
2
- // 源自原型动态插件 `code.host` 主体;宿主导入面(registerTool/defineTool/
3
- // handle)收敛在 lib/core/shims.mjs,装配块按模块拆分驻留 lib/core/(catalog /
4
- // presets-sync / profiles-store / cost-guard / whitelist / intersection /
5
- // delegation / pure / shims / http-routes / profile-provider / dispatch-tool /
6
- // dispatch-guard)。
7
- // apply 的装配辅助函数(syncBundledPresetsToHome / provideProfileService /
8
- // registerSystemPromptSections / registerSettingsRoutes)保持 section 文本与
9
- // 门控逐字不变;`enabled` 始终经 getter 注入,门控读取当前值。
1
+ // index.mjs — dsh-subagent-profile 宿主侧插件 bundle(只做装配)。宿主导入面收敛在
2
+ // lib/core/shims.mjs,装配块按模块拆分驻留 lib/core/;apply 的装配辅助函数保持
3
+ // section 文本与门控逐字不变,`enabled` 始终经 getter 注入(门控读取当前值)。
10
4
 
11
5
  import { readdirSync, renameSync, rmSync } from 'node:fs';
12
6
  import { createRequire } from 'node:module';
@@ -20,18 +14,22 @@ import { createDispatchGuard } from './lib/core/dispatch-guard.mjs';
20
14
  import { createCatalogCache } from './lib/core/catalog-cache.mjs';
21
15
  import { createFailureLedger } from './lib/core/decision-trace.mjs';
22
16
  import { createEvolutionLedger } from './lib/core/evolution-ledger.mjs';
17
+ import { createAdoptionTracker } from './lib/core/adoption-tracker.mjs';
18
+ import { createReminderStore } from './lib/core/reminder-store.mjs';
19
+ import { mintReminder, mintUnadoptedReminder } from './lib/core/adoption-reminder.mjs';
20
+ import { createBackgroundLedger } from './lib/core/background-ledger.mjs';
21
+ import { createDraftsStore } from './lib/core/drafts-store.mjs';
22
+ import { assessDraftProfile } from './lib/core/draft-gates.mjs';
23
23
  import { createEscapeStore, recordEscapeAllowProvider } from './lib/core/escape.mjs';
24
- import { tierSortKey } from './lib/core/pure.mjs';
25
24
  import { resolveWhitelist, FALLBACK_WHITELIST } from './lib/core/whitelist.mjs';
26
- import { buildAdviceText, refreshSummaries } from './lib/core/evolution-summary.mjs';
25
+ import { profileDirectoryRows, profileStatsFromSummaries, applyProfileStats } from './lib/core/profile-directory.mjs';
26
+ import { buildAdviceText, refreshSummaries, readSummaries } from './lib/core/evolution-advice.mjs';
27
27
 
28
28
  export const name = 'dsh-subagent-profile';
29
29
  export const inject = ['subagents', 'tools', 'agents'];
30
30
 
31
- // 自装 bundled 的 "orchestrator" agent 预设到 DSH agent-presets 根,让该模式
32
- // 无需手动复制就出现在新建会话选择器里(与官方 dsh-liangshen 自安装相同)。
33
- // 幂等:字节一致的树跳过;bundle 变更重写预设——即预期的升级路径。fail-soft:
34
- // 写入被拒时 dispatch 工具与设置页照常工作。
31
+ // 自装 bundled 的 "orchestrator" 预设到 agent-presets 根(与官方自安装相同)。
32
+ // 幂等:字节一致跳过、bundle 变更重写;fail-soft:写入被拒时工具与设置页照常工作。
35
33
  function syncBundledPresetsToHome(ctx) {
36
34
  try {
37
35
  const presetRoot = join(dshHome(), '.agent-presets');
@@ -44,12 +42,9 @@ function syncBundledPresetsToHome(ctx) {
44
42
  }
45
43
  }
46
44
 
47
- // 卸载清理:把本插件持久化的 3 个数据文件 + 自装的 orchestrator 预设目录改名备份
48
- // (只动本插件拥有的 orchestrator 目录,不碰 .agent-presets 下其它插件/用户的目录)。
49
- // 改为「改名到 <name>.removed-<ts>」而非 rmSync 删除:ctx.effect 的清理器在禁用/热
50
- // 重载/进程退出时都可能触发,硬删除会静默丢失用户 profiles/state/失败台账(S1)。
51
- // 备份保留可恢复副本;规范路径被清空,重装/重启后经 syncBundledPresetsToHome 重新
52
- // 同步预设、数据文件按需重新生成。fail-soft:改名失败不抛(卸载不应因清理失败而阻断)。
45
+ // 卸载清理:本插件 3 个数据文件 + orchestrator 预设目录改名备份(effect 清理器
46
+ // 在禁用/热重载/退出时都可能触发,硬删除会静默丢用户数据)。备份保留可恢复副本;
47
+ // 规范路径清空后重启按需重建。fail-soft:改名失败不抛。
53
48
  function removeOwnedData(home) {
54
49
  const stamp = Date.now();
55
50
  for (const file of ['subagent-profiles.json', 'subagent-profiles.state.json', 'subagent-profiles.failed-traces.json']) {
@@ -58,10 +53,8 @@ function removeOwnedData(home) {
58
53
  try { renameSync(join(home, '.agent-presets', 'orchestrator'), join(home, '.agent-presets', `orchestrator.removed-${stamp}`)); } catch { /* best effort */ }
59
54
  }
60
55
 
61
- // 启动清理 S1 改名备份残留:.removed-<ts> 备份在下次正常启动后已无保留价值(数据
62
- // 文件按需重新生成),启动时清掉防积累(热重载/禁用反复触发 effect 会持续产生新
63
- // 备份)。只清本插件前缀(subagent-profiles.* 与 orchestrator.removed-*),不碰其它
64
- // 文件;卸载后用户手动改回原名的场景不受影响(改回后无 .removed 残留)。fail-soft。
56
+ // 启动清理 .removed-* 备份残留(只清本插件前缀,防热重载反复产生新备份积累);
57
+ // 卸载后用户手动改回原名的场景不受影响。fail-soft。
65
58
  function cleanRemovedBackups(home) {
66
59
  for (const dir of [home, join(home, '.agent-presets')]) {
67
60
  let names;
@@ -78,13 +71,28 @@ function cleanRemovedBackups(home) {
78
71
  }
79
72
  }
80
73
 
81
- // 卸载接线:注销 dispatch 工具(若仍注册)+ 清空失败台账 + 级联取消在途派发 +
82
- // 清空守卫记账 + 删本插件数据文件与自装预设目录。另挂钩宿主 agent/disposed
83
- // (Agent 注册 fiber 卸载时发射):父会话逻辑结束时按父释放并发/token 记账,
84
- // 防配额随会话累积驻留。
85
- function registerTeardown(ctx, dispatch, ledger, guard, home) {
74
+ // parent_adopted 装配:tracker 工厂 + ctx 订阅 session/event(按 session.id 过滤),
75
+ // 卸载退订并清理定时器。onDecision getRefreshAdvice 延迟读取(先判定后聚合时为空
76
+ // 操作);onDecided 把「明确未采纳」转成提醒中心条目(同源审计 + 注意级提醒)。
77
+ function setupAdoptionTracker(ctx, home, getRefreshAdvice, onUnadopted) {
78
+ const adoptionTracker = createAdoptionTracker({
79
+ stateFile: join(home, 'subagent-evolution', 'adopted-state.json'),
80
+ warn: (message) => ctx.logger.warn(`[dsh-subagent-profile] ${message}`),
81
+ onDecision: () => { try { getRefreshAdvice()(); } catch { /* 聚合重算失败不影响判定(fail-soft) */ } },
82
+ onDecided: onUnadopted,
83
+ });
84
+ const onSessionEvent = (session, event) => adoptionTracker.handleEvent(session, event);
85
+ ctx.on('session/event', onSessionEvent);
86
+ ctx.effect(() => () => { ctx.off('session/event', onSessionEvent); adoptionTracker.dispose(); });
87
+ return adoptionTracker;
88
+ }
89
+
90
+ // 卸载接线:注销工具 + 清空台账 + 级联取消 + 删数据文件与预设目录。agent/disposed
91
+ // 挂钩按父释放并发/token 记账,并把该父会话未决采纳判定判「明确未采纳」。
92
+ function registerTeardown(ctx, dispatch, ledger, guard, home, backgroundLedger, adoptionTracker) {
86
93
  ctx.effect(() => dispatch.dispose);
87
94
  ctx.effect(() => ledger.clear);
95
+ ctx.effect(() => backgroundLedger.clear);
88
96
  ctx.effect(() => () => {
89
97
  guard.cancelAll();
90
98
  guard.reset();
@@ -94,6 +102,7 @@ function registerTeardown(ctx, dispatch, ledger, guard, home) {
94
102
  const parentSessionId = agent?.session?.header?.id;
95
103
  if (parentSessionId !== undefined && parentSessionId !== null && parentSessionId !== '') {
96
104
  guard.resetParent(parentSessionId);
105
+ adoptionTracker.parentDisposed(parentSessionId);
97
106
  }
98
107
  };
99
108
  ctx.on('agent/disposed', onAgentDisposed);
@@ -159,26 +168,28 @@ function sectionGatePasses(ctx, getEnabled, context) {
159
168
  // dispatch:profiles section 文本。引号引用:description 套引号;为空时显示
160
169
  // 占位符(不套引号)。压平在存储层完成(sanitizeProfile),此处仅负责显示层包裹。
161
170
  // 门控 profiles section 内附一行行为规则提示(非开放的 persona 注入)。
162
- function profileSectionText(store, gate, context) {
171
+ function profileSectionText(store, gate, context, summaries) {
163
172
  if (!gate(context)) return '';
164
- const rows = [...store.profiles.values()]
165
- .filter((p) => p.enabled !== false)
166
- .sort((a, b) => tierSortKey(a.tokenTier) - tierSortKey(b.tokenTier))
167
- .map((p) => {
168
- const desc = typeof p.description === 'string' && p.description.length > 0 ? `"${p.description}"` : '(无描述)';
169
- return `- ${p.id}: ${desc}${p.preset !== undefined ? ` (preset: ${p.preset})` : ''}`;
170
- });
173
+ const rows = applyProfileStats(profileDirectoryRows(store), profileStatsFromSummaries(store, summaries));
171
174
  if (rows.length === 0) return '';
172
- const note = '- 选择方案时先匹配任务复杂度与方案描述的能力边界,成本只在能力都胜任的方案之间比较——复杂任务不得为省 token 改用能力不足的便宜方案。\n- 别把 1-2 步即可自查/可搜完的小事委派出去 —— 几分钟内能自查完的直接做。';
173
- return `Available dispatch profiles (dispatch.profile):\n${rows.join('\n')}\n${note}`;
175
+ const lines = rows.map((p) => {
176
+ const desc = p.description.length > 0 ? `"${p.description}"` : '(无描述)';
177
+ const meta = [];
178
+ if (p.preset !== undefined) meta.push(`preset: ${p.preset}`);
179
+ else if (p.model !== undefined) meta.push(`model: ${p.model}`);
180
+ if (p.tokenTier !== undefined) meta.push(`tier: ${p.tokenTier}`);
181
+ if (p.avgCost !== undefined) meta.push(`平均 ${p.avgCost} 元/次`);
182
+ if (p.successRate !== undefined) meta.push(`成功率 ${p.successRate}${p.n !== undefined ? ` (N=${p.n})` : ''}`);
183
+ return `- ${p.id}: ${desc}${meta.length > 0 ? ` (${meta.join(' · ')})` : ''}`;
184
+ });
185
+ const note = '- 选择方案时先匹配任务复杂度与方案描述的能力边界,成本只在能力都胜任的方案之间比较——复杂任务不得为省 token 改用能力不足的便宜方案。\n- 别把 1-2 步即可自查/可搜完的小事委派出去 —— 几分钟内能自查完的直接做。\n- 优先使用已保存的 profile;只有少数字段需要临时覆盖时才传 per-call 参数。查资料/汇总/读文件等轻任务优先 cheap 或 flash。';
186
+ return `Available dispatch profiles (dispatch.profile):\n${lines.join('\n')}\n${note}`;
174
187
  }
175
188
 
176
189
  // orchestrator:mode section 文本(逐字保留;与 profiles 同门控)。
177
190
  const ORCHESTRATOR_MODE_TEXT = '本机已安装 dsh-subagent-profile 插件的「编排者模式」agent preset:新建会话的预设选择器中可选「编排者模式」。该模式把 Agent 定位为主协调者——拆解任务后按场景用 dispatch(内置 swap-standard=标准编码、researcher=调研检索,可在「子 Agent 方案」设置页自定义)与 subagent/subagent_fork/workflow 委派给子 Agent,再整合结果。preset 文件由插件维护于 ~/.dsh/.agent-presets,安装/升级时自动同步;用户提到「编排者模式 / orchestrator / 主协调模式」时即指本预设,请据此协作。';
178
191
 
179
- // 建议注入候选池:system-trust 白名单(agentPresets 可选;解析失败回退内置
180
- // 回退名单——fail-loud 检查在建议生成路径进行,不在此处)。刻意不叠加逃生舱放行
181
- // 集:只读建议不享受逃生舱(逃生舱仅放行「其余三道闸全过」的显式派发,不扩建议池)。
192
+ // 建议注入候选池:受信任预设白名单(解析失败回退内置名单)。不叠加逃生舱放行集。
182
193
  async function resolveAdviceWhitelist(ctx) {
183
194
  try {
184
195
  return new Set(await resolveWhitelist(ctx.get('agentPresets')));
@@ -187,17 +198,19 @@ async function resolveAdviceWhitelist(ctx) {
187
198
  }
188
199
  }
189
200
 
190
- // 目录 section:渲染可用方案(systemPrompt section text 接受函数,官方
191
- // tool-subagent 即此用法)。门控注意:`enabled` 必须经 getter 实时读取,
192
- // 使 /set-enabled 切换立即生效、无需重启。
193
- function registerSystemPromptSections(ctx, store, getEnabled, getEvolutionAdvice, adviceEnv) {
201
+ // 系统提示各 section:门控经 sectionGatePasses;`enabled` getter 实时读取。
202
+ function registerSystemPromptSections(ctx, store, getEnabled, getEvolutionAdvice, adviceEnv, guard) {
194
203
  const pluginSystemPrompt = ctx.get('systemPrompt');
195
204
  if (pluginSystemPrompt === undefined) return;
196
205
  const gate = (context) => sectionGatePasses(ctx, getEnabled, context);
197
206
  pluginSystemPrompt.section({
198
207
  name: 'dispatch:profiles',
199
208
  order: 116.5,
200
- text: (context) => profileSectionText(store, gate, context),
209
+ text: (context) => {
210
+ let summaries = null;
211
+ try { summaries = readSummaries(adviceEnv.summariesFile, adviceEnv.logger); } catch { /* 统计只增强,不影响目录注入 */ }
212
+ return profileSectionText(store, gate, context, summaries);
213
+ },
201
214
  });
202
215
  // 宣告自装的 orchestrator 预设,让当前 agent 知道该模式存在、可引导用户使用。
203
216
  // 门控与 profiles 段相同——只有可派发的 agent 才看得到。
@@ -206,10 +219,7 @@ function registerSystemPromptSections(ctx, store, getEnabled, getEvolutionAdvice
206
219
  order: 117,
207
220
  text: (context) => (gate(context) ? ORCHESTRATOR_MODE_TEXT : ''),
208
221
  });
209
- // 只读建议段:门控 = orchestrator(sectionGatePasses)+ evolutionAdvice 开关。
210
- // 只进父 Agent(复用同一门控)、默认关、只含确定性聚合数字与建议文案,不含派生原文。
211
- // 生成异常 try/catch 兜底:fail-loud 检查(非 system 候选)落 warn 日志但绝不
212
- // 阻断每次提示装配——损坏/手改的 summaries 不得让 orchestrator 会话无法启动。
222
+ // 派发优化建议段:门控 = orchestrator + evolutionAdvice 开关;异常兜底不阻断装配。
213
223
  pluginSystemPrompt.section({
214
224
  name: 'evolution:advice',
215
225
  order: 116.8,
@@ -218,11 +228,26 @@ function registerSystemPromptSections(ctx, store, getEnabled, getEvolutionAdvice
218
228
  try {
219
229
  return buildAdviceText(adviceEnv);
220
230
  } catch (error) {
221
- adviceEnv.logger.warn(`[dsh-subagent-profile] evolution:advice 生成失败,本次不注入:${error instanceof Error ? error.message : String(error)}`);
222
- return '';
231
+ // 候选校验失败(如逃生舱放行的非 system 预设)不再静默空转——logger.warn
232
+ // 留痕 + 注入段标注「建议暂不可用及原因」,父 Agent 可见、派发行为不受影响。
233
+ const reason = error instanceof Error ? error.message : String(error);
234
+ adviceEnv.logger.warn(`[dsh-subagent-profile] evolution:advice 生成失败:${reason}`);
235
+ return `(派发优化建议暂不可用:${reason}。派发行为不受影响。)`;
223
236
  }
224
237
  },
225
238
  });
239
+ // 派发预算余量段:与 profiles 同门控;无父 sessionId 不注入(无法关联具体会话)。
240
+ pluginSystemPrompt.section({
241
+ name: 'dispatch:budget',
242
+ order: 116.7,
243
+ text: (context) => {
244
+ if (!gate(context)) return '';
245
+ const parentSessionId = context?.agent?.session?.header?.id;
246
+ if (typeof parentSessionId !== 'string' || parentSessionId === '') return '';
247
+ const b = guard.snapshot(parentSessionId);
248
+ return `派发预算余量:本会话在途 ${b.concurrency}/${b.maxConcurrent},累计 token ${b.tokens}/${b.maxParentTokens},剩余 ${Math.max(0, b.maxParentTokens - b.tokens)} token。`;
249
+ },
250
+ });
226
251
  }
227
252
 
228
253
  // Client 设置 UI 的 HTTP loopback 路由(webServer.register ↔ client fetch,纯 JSON)。
@@ -230,7 +255,7 @@ function registerSystemPromptSections(ctx, store, getEnabled, getEvolutionAdvice
230
255
  // webServer 可选——无头部署保留 dispatch 工具、只丢设置页。webServer 的激活
231
256
  // (listen)是异步的,可能晚于本插件 inject 依赖解析完成,故在等它的 inject
232
257
  // 子 scope 内注册(apply 时 ctx.get 会读到 undefined)。
233
- function registerSettingsRoutes(ctx, store, getEnabled, setEnabled, syncTool, catalog, ledger, getAudit, getEvolutionAdvice, setEvolutionAdvice, getEscapeEnabled, setEscapeEnabled, escape, refreshAdvice) {
258
+ function registerSettingsRoutes(ctx, store, getEnabled, setEnabled, syncTool, catalog, ledger, backgroundLedger, draftsStore, applyDraft, getAudit, getEvolutionAdvice, setEvolutionAdvice, getEscapeEnabled, setEscapeEnabled, escape, refreshAdvice, summariesFile, dispatchFile, adviceWhitelist, previewDraft, reminderStore) {
234
259
  ctx.inject(['webServer'], (scope) => {
235
260
  scope.effect(createHttpRoutes({
236
261
  webServer: scope.webServer,
@@ -240,6 +265,9 @@ function registerSettingsRoutes(ctx, store, getEnabled, setEnabled, syncTool, ca
240
265
  syncTool,
241
266
  catalog,
242
267
  ledger,
268
+ backgroundLedger,
269
+ draftsStore,
270
+ applyDraft,
243
271
  getAudit,
244
272
  getEvolutionAdvice,
245
273
  setEvolutionAdvice,
@@ -247,6 +275,11 @@ function registerSettingsRoutes(ctx, store, getEnabled, setEnabled, syncTool, ca
247
275
  setEscapeEnabled,
248
276
  escape,
249
277
  refreshAdvice,
278
+ summariesFile,
279
+ dispatchFile,
280
+ adviceWhitelist,
281
+ previewDraft,
282
+ reminderStore,
250
283
  logger: ctx.logger,
251
284
  }), 'dsh-subagent-profile: settings routes');
252
285
  });
@@ -277,7 +310,8 @@ function readPluginVersion() {
277
310
 
278
311
  // 逃生舱装配:放行集 store + 开关态(state.json 持久化)+ 访问器。开关态经对象字段
279
312
  // 可变(/set-escape 改写),getEscapeSet 开关关时恒空数组(零叠加、零放行审计)。
280
- function setupEscape(ctx, store, evoLedger, home) {
313
+ // 放行时 mint P0(紧急)提醒(高可见治理事件,与放行审计同源留痕)。
314
+ function setupEscape(ctx, store, evoLedger, home, getReminderStore) {
281
315
  const escape = createEscapeStore({ dshHome: home, logger: ctx.logger, onGovernanceFailure: () => evoLedger.markGovernanceFailure() });
282
316
  const state = { escapeEnabled: store.loadEscapeEnabled() };
283
317
  return {
@@ -285,13 +319,16 @@ function setupEscape(ctx, store, evoLedger, home) {
285
319
  getEscapeSet: () => (state.escapeEnabled ? escape.list() : []),
286
320
  getEscapeEnabled: () => state.escapeEnabled,
287
321
  setEscapeEnabled: (next) => { state.escapeEnabled = next; },
288
- recordEscapeAllowProvider: (parent, preset) => recordEscapeAllowProvider(evoLedger, parent, preset),
322
+ recordEscapeAllowProvider: (parent, preset) => {
323
+ recordEscapeAllowProvider(evoLedger, parent, preset);
324
+ mintReminder(getReminderStore(), { severity: 'P0', kind: 'escape-allow', title: '逃生舱放行非官方预设', detail: '预设 "' + preset + '" 经逃生舱放行,其余安全检查仍全量生效', sessionId: parent?.session?.header?.id });
325
+ },
289
326
  };
290
327
  }
291
328
 
292
329
  // `dispatch` 工具装配(defineTool + execute + syncTool)。须在 HTTP inject 之前
293
330
  // 构造,使 createHttpRoutes 能拿 dispatch.syncTool 供 /set-enabled 注册/注销。
294
- function createDispatch(ctx, store, catalog, ledger, guard, evoLedger, getEscapeSet, getEnabled) {
331
+ function createDispatch(ctx, store, catalog, ledger, guard, evoLedger, backgroundLedger, adoptionTracker, getEscapeSet, getEnabled, getEvolutionAdvice) {
295
332
  return createDispatchTool({
296
333
  register: (tool) => ctx.tools.register(tool),
297
334
  store,
@@ -303,18 +340,35 @@ function createDispatch(ctx, store, catalog, ledger, guard, evoLedger, getEscape
303
340
  ledger,
304
341
  guard,
305
342
  evoLedger,
343
+ backgroundLedger,
344
+ adoptionTracker,
306
345
  getEscapeSet,
346
+ getEvolutionAdvice,
307
347
  });
308
348
  }
309
349
 
350
+ // auto-profile 落库:三道安全检查评估(draft-gates)→ 任一 fail 即 throw → 落库 + 审计。
351
+ async function applyDraftProfile({ ctx, store, catalog, getEscapeSet, evoLedger, draft }) {
352
+ const { ok, checks, clean } = await assessDraftProfile({ ctx, store, catalog, getEscapeSet, draft });
353
+ if (!ok) {
354
+ const failed = checks.find((c) => c.verdict === 'fail');
355
+ throw new Error(failed !== undefined && typeof failed.reason === 'string' ? failed.reason : 'draft 未通过安全检查');
356
+ }
357
+ store.profiles.set(clean.id, { ...clean, persisted: true });
358
+ const persisted = store.persistProfiles();
359
+ evoLedger.recordGovernanceAudit({ kind: 'draft-apply', profileId: clean.id, source: typeof draft.source === 'string' ? draft.source : 'human' });
360
+ return { id: clean.id, persisted: persisted.persisted };
361
+ }
362
+
310
363
  export async function apply(ctx) {
311
364
  const home = dshHome();
312
- // 启动清理:上个生命周期留下的 .removed-* 备份残留(S1 改名的副产物)。
313
- cleanRemovedBackups(home);
365
+ cleanRemovedBackups(home); // 上个生命周期留下的 .removed-* 备份残留。
366
+ // reminderStore 变量提前声明:evoLedger.onAlert 与 escape mint 钩子延迟读取。
367
+ let reminderStore;
314
368
  // 派发台账 + 审计分级须在 store 之前构造:store 的治理审计钩子指向其 markGovernanceFailure。
315
- const evoLedger = createEvolutionLedger({ dshHome: home, pluginVersion: readPluginVersion(), warn: (message) => ctx.logger.warn(`[dsh-subagent-profile] ${message}`) });
369
+ const evoLedger = createEvolutionLedger({ dshHome: home, pluginVersion: readPluginVersion(), warn: (message) => ctx.logger.warn(`[dsh-subagent-profile] ${message}`), onAlert: (lost) => mintReminder(reminderStore, { severity: 'P0', kind: 'audit-degraded', title: '审计降级', detail: '治理审计丢失 ' + lost + ' 条,健康状态已降级——请检查磁盘', sessionId: null }) });
316
370
  const store = createProfileStore({ dshHome: home, logger: ctx.logger, onGovernanceFailure: () => evoLedger.markGovernanceFailure() });
317
- const escapeCtl = setupEscape(ctx, store, evoLedger, home);
371
+ const escapeCtl = setupEscape(ctx, store, evoLedger, home, () => reminderStore);
318
372
  let enabled = store.loadEnabled();
319
373
  let evolutionAdvice = store.loadEvolutionAdvice();
320
374
  store.loadProfiles();
@@ -323,21 +377,36 @@ export async function apply(ctx) {
323
377
  const catalog = createSharedCatalog(ctx);
324
378
  const ledger = createFailureLedger({ warn: (message) => ctx.logger.warn(`[dsh-subagent-profile] ${message}`), stateFile: join(home, 'subagent-profiles.failed-traces.json') });
325
379
  const guard = createDispatchGuard({ warn: (message) => ctx.logger.warn(`[dsh-subagent-profile] ${message}`) });
326
- const dispatch = createDispatch(ctx, store, catalog, ledger, guard, evoLedger, escapeCtl.getEscapeSet, () => enabled);
380
+ const backgroundLedger = createBackgroundLedger({ warn: (message) => ctx.logger.warn(`[dsh-subagent-profile] ${message}`) });
381
+ const draftsStore = createDraftsStore({ dshHome: home, onGovernanceFailure: () => evoLedger.markGovernanceFailure() });
382
+ reminderStore = createReminderStore({ dshHome: home, audit: (entry) => evoLedger.recordGovernanceAudit(entry), warn: (message) => ctx.logger.warn(`[dsh-subagent-profile] ${message}`) });
383
+ let refreshAdvice = () => {};
384
+ const adoptionTracker = setupAdoptionTracker(ctx, home, () => refreshAdvice, (rec) => mintUnadoptedReminder(reminderStore, evoLedger, rec));
385
+ const dispatch = createDispatch(ctx, store, catalog, ledger, guard, evoLedger, backgroundLedger, adoptionTracker, escapeCtl.getEscapeSet, () => enabled, () => evolutionAdvice);
327
386
  provideProfileService(ctx, store);
328
387
  const adviceWhitelist = await resolveAdviceWhitelist(ctx);
329
388
  const adviceEnv = { summariesFile: join(home, 'subagent-evolution', 'summaries.json'), dispatchFile: join(home, 'subagent-evolution', 'dispatch.jsonl'), whitelist: adviceWhitelist, logger: ctx.logger };
330
- // 生产聚合触发点(T1 修复):/options/refresh 手动刷新时重算 summaries.json,让
331
- // evolution:advice 有初始生成路径(原先 computeSummaries/writeSummaries 只被测试调用)。
332
- const refreshAdvice = () => refreshSummaries({
333
- dispatchFile: join(home, 'subagent-evolution', 'dispatch.jsonl'),
334
- summariesFile: join(home, 'subagent-evolution', 'summaries.json'),
335
- logger: ctx.logger,
336
- });
337
- registerSystemPromptSections(ctx, store, () => enabled, () => evolutionAdvice, adviceEnv);
389
+ // 生产聚合触发点(T1 修复):/options/refresh /list 触发的惰性重算;parent_adopted
390
+ // 的「已确认未采纳」计数经 opts 惰性 join 进 weighted_success(-0.3 惩罚)。
391
+ refreshAdvice = () => refreshSummaries({ dispatchFile: adviceEnv.dispatchFile, summariesFile: adviceEnv.summariesFile, logger: ctx.logger, opts: { parentAdoptedConfirmedFalse: adoptionTracker.confirmedFalseCounts() } });
392
+ registerSystemPromptSections(ctx, store, () => enabled, () => evolutionAdvice, adviceEnv, guard);
338
393
  const disposeProvider = createProfileProvider({ subagents: ctx.subagents, store, getEnabled: () => enabled, logger: ctx.logger, catalog, getEscapeSet: escapeCtl.getEscapeSet, recordEscapeAllowProvider: escapeCtl.recordEscapeAllowProvider });
339
394
  if (typeof disposeProvider === 'function') ctx.effect(() => disposeProvider);
395
+ const applyDraft = (draft) => applyDraftProfile({ ctx, store, catalog, getEscapeSet: escapeCtl.getEscapeSet, evoLedger, draft });
396
+ // /draft/preview:只读安全检查预览(不落库)。body 为 {config, name, description, source}。
397
+ const previewDraft = (body) => assessDraftProfile({
398
+ ctx,
399
+ store,
400
+ catalog,
401
+ getEscapeSet: escapeCtl.getEscapeSet,
402
+ draft: {
403
+ config: body !== null && typeof body === 'object' && typeof body.config === 'object' && body.config !== null ? body.config : {},
404
+ name: body !== null && typeof body === 'object' && typeof body.name === 'string' ? body.name : '',
405
+ description: body !== null && typeof body === 'object' && typeof body.description === 'string' ? body.description : '',
406
+ source: body !== null && typeof body === 'object' && typeof body.source === 'string' ? body.source : 'human',
407
+ },
408
+ });
340
409
  // Client 设置 UI 的 HTTP loopback 路由 —— lib/core/http-routes.mjs。
341
- registerSettingsRoutes(ctx, store, () => enabled, (next) => { enabled = next; }, dispatch.syncTool, catalog, ledger, () => evoLedger.auditState(), () => evolutionAdvice, (next) => { evolutionAdvice = next; }, escapeCtl.getEscapeEnabled, escapeCtl.setEscapeEnabled, escapeCtl.escape, refreshAdvice);
342
- registerTeardown(ctx, dispatch, ledger, guard, home);
410
+ registerSettingsRoutes(ctx, store, () => enabled, (next) => { enabled = next; }, dispatch.syncTool, catalog, ledger, backgroundLedger, draftsStore, applyDraft, () => evoLedger.auditState(), () => evolutionAdvice, (next) => { evolutionAdvice = next; }, escapeCtl.getEscapeEnabled, escapeCtl.setEscapeEnabled, escapeCtl.escape, refreshAdvice, join(home, 'subagent-evolution', 'summaries.json'), adviceEnv.dispatchFile, adviceEnv.whitelist, previewDraft, reminderStore);
411
+ registerTeardown(ctx, dispatch, ledger, guard, home, backgroundLedger, adoptionTracker);
343
412
  }