@suifei/dsh-ai-team 0.4.145 → 0.4.147

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 (50) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/LICENSE +21 -21
  3. package/README.md +31 -2
  4. package/client.js +551 -49
  5. package/cordis.patch.yml +31 -31
  6. package/icon.svg +12 -12
  7. package/index.js +105 -25
  8. package/lib/domain/ids.js +26 -26
  9. package/lib/domain/inbox.js +93 -93
  10. package/lib/domain/member-config.js +168 -168
  11. package/lib/domain/policy.js +8 -1
  12. package/lib/domain/task.js +2 -0
  13. package/lib/domain/team-blueprint.js +240 -0
  14. package/lib/host/decision-report.js +72 -72
  15. package/lib/host/default-roster.js +18 -0
  16. package/lib/host/default-workspace.js +69 -69
  17. package/lib/host/fault-adapter.js +50 -50
  18. package/lib/host/member-tools.js +6 -1
  19. package/lib/host/people-view.js +9 -2
  20. package/lib/host/permission-guard.js +61 -61
  21. package/lib/host/project-registry.js +104 -104
  22. package/lib/host/project-runtime.js +2 -2
  23. package/lib/host/risk-view.js +99 -99
  24. package/lib/host/service.js +195 -16
  25. package/lib/host/views.js +42 -1
  26. package/lib/host/waker.js +38 -8
  27. package/lib/host/weekly-view.js +86 -86
  28. package/lib/host/workspace-path.js +94 -94
  29. package/lib/ledger/checkpoint.js +415 -415
  30. package/lib/ledger/events.js +398 -398
  31. package/lib/ledger/fold.js +23 -0
  32. package/lib/ledger/namespace.js +124 -124
  33. package/lib/ledger/tools.js +118 -118
  34. package/lib/ledger/writer.js +1266 -1266
  35. package/lib/runtime/error-chain.js +31 -31
  36. package/lib/runtime/shell-guard.js +102 -102
  37. package/lib/runtime/skill-catalog.js +41 -41
  38. package/lib/runtime/skill-policy.js +12 -12
  39. package/lib/runtime/stop-guard.js +17 -2
  40. package/lib/skillopt/adopt-gate.js +108 -108
  41. package/lib/skillopt/gate-wiring.js +146 -146
  42. package/lib/skillopt/jobs.js +135 -135
  43. package/lib/skillopt/proposal-store.js +33 -33
  44. package/lib/skillopt/review-runner.js +107 -107
  45. package/lib/skillopt/rubric.js +189 -189
  46. package/lib/skillopt/subagent-text.js +101 -101
  47. package/lib/skillopt/tool-access.js +56 -56
  48. package/locale/en.json +6 -6
  49. package/locale/zh.json +6 -6
  50. package/package.json +1 -1
@@ -1,31 +1,31 @@
1
- /**
2
- * 把 Error 的 cause 链摊平成一行可检索文本。
3
- *
4
- * 实机背景:`subagents.sendMessage` 失败时外层只给
5
- * `subagent "X" is unavailable`,真实原因(persistence 读不出会话、descriptor
6
- * 不可续、血缘校验失败)挂在 `cause` 上被丢掉,诊断日志因此无法定位。
7
- */
8
-
9
- const MAX_DEPTH = 4;
10
- const MAX_PART = 240;
11
-
12
- /**
13
- * @param {unknown} error
14
- * @returns {string|null} `code: message ← code: message`;没有 cause 时返回 null
15
- */
16
- export function describeCauseChain(error) {
17
- if (error === undefined || error === null) return null;
18
- const parts = [];
19
- const seen = new Set();
20
- let current = error.cause;
21
- let depth = 0;
22
- while (current !== undefined && current !== null && depth < MAX_DEPTH && !seen.has(current)) {
23
- seen.add(current);
24
- const code = typeof current.code === 'string' && current.code !== '' ? `${current.code}: ` : '';
25
- const message = typeof current.message === 'string' ? current.message : String(current);
26
- parts.push(`${code}${message}`.slice(0, MAX_PART));
27
- current = current.cause;
28
- depth += 1;
29
- }
30
- return parts.length === 0 ? null : parts.join(' ← ');
31
- }
1
+ /**
2
+ * 把 Error 的 cause 链摊平成一行可检索文本。
3
+ *
4
+ * 实机背景:`subagents.sendMessage` 失败时外层只给
5
+ * `subagent "X" is unavailable`,真实原因(persistence 读不出会话、descriptor
6
+ * 不可续、血缘校验失败)挂在 `cause` 上被丢掉,诊断日志因此无法定位。
7
+ */
8
+
9
+ const MAX_DEPTH = 4;
10
+ const MAX_PART = 240;
11
+
12
+ /**
13
+ * @param {unknown} error
14
+ * @returns {string|null} `code: message ← code: message`;没有 cause 时返回 null
15
+ */
16
+ export function describeCauseChain(error) {
17
+ if (error === undefined || error === null) return null;
18
+ const parts = [];
19
+ const seen = new Set();
20
+ let current = error.cause;
21
+ let depth = 0;
22
+ while (current !== undefined && current !== null && depth < MAX_DEPTH && !seen.has(current)) {
23
+ seen.add(current);
24
+ const code = typeof current.code === 'string' && current.code !== '' ? `${current.code}: ` : '';
25
+ const message = typeof current.message === 'string' ? current.message : String(current);
26
+ parts.push(`${code}${message}`.slice(0, MAX_PART));
27
+ current = current.cause;
28
+ depth += 1;
29
+ }
30
+ return parts.length === 0 ? null : parts.join(' ← ');
31
+ }
@@ -1,102 +1,102 @@
1
- /**
2
- * 成员 shell 风险守卫。
3
- *
4
- * 实机事故:成员把项目名 `localservice` 误读成「Windows 常驻服务」,在工作目录里写了
5
- * `tools/serve.ps1`,再用 `Start-Process -WindowStyle Hidden -ExecutionPolicy Bypass`
6
- * 拉起一个隐藏窗口的常驻进程——这正是杀软启发式最敏感的组合(隐藏 PowerShell + 自启
7
- * 脚本 + 本地监听),用户那台机器因此报毒。
8
- *
9
- * 插件本身给成员的是 full-access(产品前提),但「悄悄起隐藏常驻进程」不该是默认行为。
10
- * 这里在 `tools.guard` 上挂一道守卫:
11
- * - `warn`(默认):记录一条可见的 `.fail` 诊断行,放行;
12
- * - `block`:直接拒绝该次工具调用,理由回给成员;
13
- * - `off`:完全不介入。
14
- *
15
- * 只对**团队成员会话**生效:Human 自己的会话、host 会话不受影响。
16
- */
17
-
18
- /** 高风险命令特征:隐藏窗口常驻进程、绕过执行策略、计划任务/服务注册、管道执行下载内容。 */
19
- const PATTERNS = [
20
- { id: 'hidden-window', re: /-windowstyle\s+hidden|-w\s+hidden/i, reason: '以隐藏窗口启动进程(杀软高危特征)' },
21
- { id: 'bypass-policy', re: /-executionpolicy\s+bypass/i, reason: '绕过 PowerShell 执行策略' },
22
- { id: 'encoded-command', re: /-(encodedcommand|enc)\s+[A-Za-z0-9+/=]{40,}/i, reason: '以 Base64 编码执行命令' },
23
- { id: 'persist-service', re: /\b(sc\s+create|new-service|schtasks\s+\/create|reg\s+add\s+[^\n]*\\run)\b/i, reason: '注册系统服务/计划任务/开机自启' },
24
- { id: 'pipe-to-shell', re: /\b(curl|wget|invoke-webrequest|iwr)\b[^\n|]*\|\s*(sh|bash|powershell|pwsh)\b/i, reason: '把下载内容直接管道给 shell 执行' },
25
- { id: 'script-host', re: /\b(wscript|cscript|mshta)\b/i, reason: '用脚本宿主执行(wscript/cscript/mshta)' },
26
- ];
27
-
28
- /**
29
- * 检查一段 shell 命令是否命中高风险特征。
30
- * @returns {{ id: string, reason: string, excerpt: string } | null}
31
- */
32
- export function inspectShellCommand(command) {
33
- if (typeof command !== 'string' || command.trim() === '') return null;
34
- const text = command.replace(/\s+/g, ' ');
35
- for (const pattern of PATTERNS) {
36
- if (!pattern.re.test(text)) continue;
37
- const at = text.search(pattern.re);
38
- const excerpt = text.slice(Math.max(0, at - 40), Math.min(text.length, at + 120));
39
- return { id: pattern.id, reason: pattern.reason, excerpt };
40
- }
41
- return null;
42
- }
43
-
44
- /** 从工具入参里取出可能承载命令的字符串。 */
45
- export function commandOfToolCall(name, args) {
46
- if (typeof name !== 'string') return '';
47
- const fields = Array.isArray(args) ? [] : Object.entries(args ?? {});
48
- const keys = ['command', 'cmd', 'script', 'code', 'input', 'args'];
49
- for (const [key, value] of fields) {
50
- if (typeof value !== 'string' || value === '') continue;
51
- if (keys.includes(key)) return value;
52
- }
53
- // 有些 shell 工具把命令放在数组参数里。
54
- for (const [, value] of fields) {
55
- if (Array.isArray(value) && value.every((item) => typeof item === 'string')) return value.join(' ');
56
- }
57
- return '';
58
- }
59
-
60
- const SHELL_TOOLS = new Set(['pwsh', 'shell', 'bash', 'terminal', 'run_code', 'powershell']);
61
-
62
- /**
63
- * 注册守卫。只对成员会话生效,返回 disposer。
64
- *
65
- * @param {object} options
66
- * @param {object} options.tools `ctx.tools`
67
- * @param {() => Set<string>} options.memberSessions 当前团队成员会话 id 集合
68
- * @param {(row: object) => void} options.diag
69
- * @param {'off'|'warn'|'block'} options.mode
70
- */
71
- export function registerShellGuard({ tools, memberSessions, diag, mode = 'warn' }) {
72
- if (mode === 'off') return () => {};
73
- if (tools === undefined || typeof tools.guard !== 'function') return () => {};
74
- return tools.guard((execution) => {
75
- try {
76
- const name = execution?.name;
77
- if (!SHELL_TOOLS.has(String(name))) return undefined;
78
- const sessionId = execution?.agent?.id;
79
- const members = memberSessions();
80
- if (typeof sessionId !== 'string' || !members.has(sessionId)) return undefined;
81
- const command = commandOfToolCall(name, execution?.arguments);
82
- const hit = inspectShellCommand(command);
83
- if (hit === null) return undefined;
84
- diag?.append?.({
85
- ev: 'member.shell-risk.fail',
86
- memberId: null,
87
- sessionId,
88
- tool: String(name),
89
- pattern: hit.id,
90
- action: mode,
91
- excerpt: hit.excerpt,
92
- });
93
- if (mode === 'block') {
94
- return `已阻止:${hit.reason}。若要启动常驻进程,请让 Human 明确授权后手动执行,或改用可见窗口。`;
95
- }
96
- return undefined;
97
- } catch {
98
- // 守卫自身出错绝不能阻断工具调用。
99
- return undefined;
100
- }
101
- });
102
- }
1
+ /**
2
+ * 成员 shell 风险守卫。
3
+ *
4
+ * 实机事故:成员把项目名 `localservice` 误读成「Windows 常驻服务」,在工作目录里写了
5
+ * `tools/serve.ps1`,再用 `Start-Process -WindowStyle Hidden -ExecutionPolicy Bypass`
6
+ * 拉起一个隐藏窗口的常驻进程——这正是杀软启发式最敏感的组合(隐藏 PowerShell + 自启
7
+ * 脚本 + 本地监听),用户那台机器因此报毒。
8
+ *
9
+ * 插件本身给成员的是 full-access(产品前提),但「悄悄起隐藏常驻进程」不该是默认行为。
10
+ * 这里在 `tools.guard` 上挂一道守卫:
11
+ * - `warn`(默认):记录一条可见的 `.fail` 诊断行,放行;
12
+ * - `block`:直接拒绝该次工具调用,理由回给成员;
13
+ * - `off`:完全不介入。
14
+ *
15
+ * 只对**团队成员会话**生效:Human 自己的会话、host 会话不受影响。
16
+ */
17
+
18
+ /** 高风险命令特征:隐藏窗口常驻进程、绕过执行策略、计划任务/服务注册、管道执行下载内容。 */
19
+ const PATTERNS = [
20
+ { id: 'hidden-window', re: /-windowstyle\s+hidden|-w\s+hidden/i, reason: '以隐藏窗口启动进程(杀软高危特征)' },
21
+ { id: 'bypass-policy', re: /-executionpolicy\s+bypass/i, reason: '绕过 PowerShell 执行策略' },
22
+ { id: 'encoded-command', re: /-(encodedcommand|enc)\s+[A-Za-z0-9+/=]{40,}/i, reason: '以 Base64 编码执行命令' },
23
+ { id: 'persist-service', re: /\b(sc\s+create|new-service|schtasks\s+\/create|reg\s+add\s+[^\n]*\\run)\b/i, reason: '注册系统服务/计划任务/开机自启' },
24
+ { id: 'pipe-to-shell', re: /\b(curl|wget|invoke-webrequest|iwr)\b[^\n|]*\|\s*(sh|bash|powershell|pwsh)\b/i, reason: '把下载内容直接管道给 shell 执行' },
25
+ { id: 'script-host', re: /\b(wscript|cscript|mshta)\b/i, reason: '用脚本宿主执行(wscript/cscript/mshta)' },
26
+ ];
27
+
28
+ /**
29
+ * 检查一段 shell 命令是否命中高风险特征。
30
+ * @returns {{ id: string, reason: string, excerpt: string } | null}
31
+ */
32
+ export function inspectShellCommand(command) {
33
+ if (typeof command !== 'string' || command.trim() === '') return null;
34
+ const text = command.replace(/\s+/g, ' ');
35
+ for (const pattern of PATTERNS) {
36
+ if (!pattern.re.test(text)) continue;
37
+ const at = text.search(pattern.re);
38
+ const excerpt = text.slice(Math.max(0, at - 40), Math.min(text.length, at + 120));
39
+ return { id: pattern.id, reason: pattern.reason, excerpt };
40
+ }
41
+ return null;
42
+ }
43
+
44
+ /** 从工具入参里取出可能承载命令的字符串。 */
45
+ export function commandOfToolCall(name, args) {
46
+ if (typeof name !== 'string') return '';
47
+ const fields = Array.isArray(args) ? [] : Object.entries(args ?? {});
48
+ const keys = ['command', 'cmd', 'script', 'code', 'input', 'args'];
49
+ for (const [key, value] of fields) {
50
+ if (typeof value !== 'string' || value === '') continue;
51
+ if (keys.includes(key)) return value;
52
+ }
53
+ // 有些 shell 工具把命令放在数组参数里。
54
+ for (const [, value] of fields) {
55
+ if (Array.isArray(value) && value.every((item) => typeof item === 'string')) return value.join(' ');
56
+ }
57
+ return '';
58
+ }
59
+
60
+ const SHELL_TOOLS = new Set(['pwsh', 'shell', 'bash', 'terminal', 'run_code', 'powershell']);
61
+
62
+ /**
63
+ * 注册守卫。只对成员会话生效,返回 disposer。
64
+ *
65
+ * @param {object} options
66
+ * @param {object} options.tools `ctx.tools`
67
+ * @param {() => Set<string>} options.memberSessions 当前团队成员会话 id 集合
68
+ * @param {(row: object) => void} options.diag
69
+ * @param {'off'|'warn'|'block'} options.mode
70
+ */
71
+ export function registerShellGuard({ tools, memberSessions, diag, mode = 'warn' }) {
72
+ if (mode === 'off') return () => {};
73
+ if (tools === undefined || typeof tools.guard !== 'function') return () => {};
74
+ return tools.guard((execution) => {
75
+ try {
76
+ const name = execution?.name;
77
+ if (!SHELL_TOOLS.has(String(name))) return undefined;
78
+ const sessionId = execution?.agent?.id;
79
+ const members = memberSessions();
80
+ if (typeof sessionId !== 'string' || !members.has(sessionId)) return undefined;
81
+ const command = commandOfToolCall(name, execution?.arguments);
82
+ const hit = inspectShellCommand(command);
83
+ if (hit === null) return undefined;
84
+ diag?.append?.({
85
+ ev: 'member.shell-risk.fail',
86
+ memberId: null,
87
+ sessionId,
88
+ tool: String(name),
89
+ pattern: hit.id,
90
+ action: mode,
91
+ excerpt: hit.excerpt,
92
+ });
93
+ if (mode === 'block') {
94
+ return `已阻止:${hit.reason}。若要启动常驻进程,请让 Human 明确授权后手动执行,或改用可见窗口。`;
95
+ }
96
+ return undefined;
97
+ } catch {
98
+ // 守卫自身出错绝不能阻断工具调用。
99
+ return undefined;
100
+ }
101
+ });
102
+ }
@@ -1,41 +1,41 @@
1
- /**
2
- * Bounded, invocation-neutral view of the DSH skill catalog for a member
3
- * prompt. Full bodies stay with the `skill` tool; this only makes names,
4
- * descriptions and "when to use" discoverable so a member can load one on
5
- * demand instead of guessing.
6
- */
7
-
8
- import { isSkillExcluded } from './skill-policy.js';
9
-
10
- function clean(value, limit) {
11
- const text = typeof value === 'string' ? value.replace(/\s+/g, ' ').trim() : '';
12
- return text.length > limit ? `${text.slice(0, limit - 1)}…` : text;
13
- }
14
-
15
- export async function formatSkillCatalog(skills, options = {}) {
16
- if (!skills || typeof skills.list !== 'function') return '';
17
- const summaries = await skills.list({
18
- ...(options.cwd ? { cwd: options.cwd } : {}),
19
- }).catch(() => []);
20
- if (!Array.isArray(summaries) || summaries.length === 0) return '';
21
- // 只注入「模型可以自己调用」的技能:`disable-model-invocation: true` 的技能
22
- // 是给 Human 显式用的,列进成员 prompt 会把成员引向一个它无权调用的入口。
23
- // SkillSummary 把这两个开关放在 `invocation` 下;直接读顶层字段会让过滤永远
24
- // 通过(字段恒为 undefined),被禁的技能照样写进 prompt。
25
- const available = summaries.filter((skill) => {
26
- if (isSkillExcluded(skill?.name)) return false;
27
- const modelInvocable = skill?.invocation?.modelInvocable ?? skill?.modelInvocable;
28
- const disabled = skill?.invocation?.disableModelInvocation ?? skill?.disableModelInvocation;
29
- if (modelInvocable === false || disabled === true) return false;
30
- return true;
31
- });
32
- if (available.length === 0) return '';
33
- const limit = Number.isSafeInteger(options.limit) && options.limit > 0 ? options.limit : 12;
34
- const rows = available.slice(0, limit).map((skill) => {
35
- const name = clean(skill?.name, 80);
36
- const description = clean(skill?.description, 240);
37
- const when = clean(skill?.whenToUse, 180);
38
- return `- ${name}:${description}${when ? `(何时用:${when})` : ''}`;
39
- });
40
- return `\n\n## 可用 DSH 技能\n${rows.join('\n')}\n需要时用 skill 工具按名字加载完整技能说明;不要凭描述臆造步骤。`;
41
- }
1
+ /**
2
+ * Bounded, invocation-neutral view of the DSH skill catalog for a member
3
+ * prompt. Full bodies stay with the `skill` tool; this only makes names,
4
+ * descriptions and "when to use" discoverable so a member can load one on
5
+ * demand instead of guessing.
6
+ */
7
+
8
+ import { isSkillExcluded } from './skill-policy.js';
9
+
10
+ function clean(value, limit) {
11
+ const text = typeof value === 'string' ? value.replace(/\s+/g, ' ').trim() : '';
12
+ return text.length > limit ? `${text.slice(0, limit - 1)}…` : text;
13
+ }
14
+
15
+ export async function formatSkillCatalog(skills, options = {}) {
16
+ if (!skills || typeof skills.list !== 'function') return '';
17
+ const summaries = await skills.list({
18
+ ...(options.cwd ? { cwd: options.cwd } : {}),
19
+ }).catch(() => []);
20
+ if (!Array.isArray(summaries) || summaries.length === 0) return '';
21
+ // 只注入「模型可以自己调用」的技能:`disable-model-invocation: true` 的技能
22
+ // 是给 Human 显式用的,列进成员 prompt 会把成员引向一个它无权调用的入口。
23
+ // SkillSummary 把这两个开关放在 `invocation` 下;直接读顶层字段会让过滤永远
24
+ // 通过(字段恒为 undefined),被禁的技能照样写进 prompt。
25
+ const available = summaries.filter((skill) => {
26
+ if (isSkillExcluded(skill?.name)) return false;
27
+ const modelInvocable = skill?.invocation?.modelInvocable ?? skill?.modelInvocable;
28
+ const disabled = skill?.invocation?.disableModelInvocation ?? skill?.disableModelInvocation;
29
+ if (modelInvocable === false || disabled === true) return false;
30
+ return true;
31
+ });
32
+ if (available.length === 0) return '';
33
+ const limit = Number.isSafeInteger(options.limit) && options.limit > 0 ? options.limit : 12;
34
+ const rows = available.slice(0, limit).map((skill) => {
35
+ const name = clean(skill?.name, 80);
36
+ const description = clean(skill?.description, 240);
37
+ const when = clean(skill?.whenToUse, 180);
38
+ return `- ${name}:${description}${when ? `(何时用:${when})` : ''}`;
39
+ });
40
+ return `\n\n## 可用 DSH 技能\n${rows.join('\n')}\n需要时用 skill 工具按名字加载完整技能说明;不要凭描述臆造步骤。`;
41
+ }
@@ -1,12 +1,12 @@
1
- /**
2
- * Skills that must not be exposed by the AI Team plugin.
3
- *
4
- * These may still exist in the user's global DSH skill directory; the Team
5
- * provider and prompt catalog filter them so they never enter a member's Team
6
- * context or the workbench skill list.
7
- */
8
- export const EXCLUDED_SKILL_NAMES = Object.freeze(new Set(['huashu-nuwa']));
9
-
10
- export function isSkillExcluded(name) {
11
- return typeof name === 'string' && EXCLUDED_SKILL_NAMES.has(name);
12
- }
1
+ /**
2
+ * Skills that must not be exposed by the AI Team plugin.
3
+ *
4
+ * These may still exist in the user's global DSH skill directory; the Team
5
+ * provider and prompt catalog filter them so they never enter a member's Team
6
+ * context or the workbench skill list.
7
+ */
8
+ export const EXCLUDED_SKILL_NAMES = Object.freeze(new Set(['huashu-nuwa']));
9
+
10
+ export function isSkillExcluded(name) {
11
+ return typeof name === 'string' && EXCLUDED_SKILL_NAMES.has(name);
12
+ }
@@ -31,6 +31,20 @@ export function stoppedTeamDenial(execution, projectOf) {
31
31
  };
32
32
  }
33
33
 
34
+ /** 首发只在账本交付草稿。父会话识别覆盖成员绑定 sessionId 以前的首次调用。 */
35
+ export function blueprintToolDenial(execution, projectOf) {
36
+ if (execution?.name === 'team') return null;
37
+ const sessionId = execution?.agent?.id;
38
+ if (typeof sessionId !== 'string' || sessionId === '') return null;
39
+ const parent = execution.agent?.session?.header?.parentSession;
40
+ const project = projectOf(sessionId) ?? (typeof parent === 'string' && parent !== '' ? projectOf(parent) : null);
41
+ if (project?.blueprint !== true) return null;
42
+ return {
43
+ projectId: project.projectId,
44
+ reason: '首发试跑只用 team 工具交付草稿。发布、发送、删除、付费或永久变更由负责人提请用户明确决定并由用户操作。',
45
+ };
46
+ }
47
+
34
48
  /**
35
49
  * SkillOpt 一次性子代理(handoff 作答、判官、生成)只凭题面文字作答,不得调用任何工具。
36
50
  *
@@ -81,9 +95,10 @@ export function registerStopGuard({ tools, projectOf, diag }) {
81
95
  if (tools === undefined || tools === null || typeof tools.guard !== 'function') return () => {};
82
96
  return tools.guard((execution) => {
83
97
  try {
84
- const denial = stoppedTeamDenial(execution, projectOf);
98
+ const blueprint = blueprintToolDenial(execution, projectOf);
99
+ const denial = blueprint ?? stoppedTeamDenial(execution, projectOf);
85
100
  if (denial === null) return undefined;
86
- diag?.append?.({ ev: 'team.stopped.blocked', projectId: denial.projectId, sessionId: execution?.agent?.id ?? null, tool: String(execution?.name ?? '') });
101
+ diag?.append?.({ ev: blueprint ? 'blueprint.tool.blocked' : 'team.stopped.blocked', projectId: denial.projectId, sessionId: execution?.agent?.id ?? null, tool: String(execution?.name ?? '') });
87
102
  return denial.reason;
88
103
  } catch {
89
104
  // 守卫自身出错绝不能阻断工具调用。
@@ -1,108 +1,108 @@
1
- /**
2
- * adopt 前门(Darwin 的 validation gate):把 `skillopt_adopt` 包一层——
3
- * 先跑 paired 独立 judge,多数决为 revert/inconclusive 时拒绝 adopt,
4
- * keep 时才放行原引擎调用。**不改 vendored 引擎**,只包 tools.register。
5
- *
6
- * gate 需要读取「改前 vs 改后」两版文本:改进后的候选来自 staged proposal
7
- * (由调用方注入 readProposal),改前版本来自 git(HEAD 的 SKILL.md)或调用方
8
- * 注入的 baseline 读取。任一缺失时门以「无法验证」拒绝——与 darwin 的
9
- * 「没有验证证据不得 adopt」一致。
10
- */
11
-
12
- /**
13
- * @param {object} deps
14
- * @param {(projectDir: string) => Promise<{before: string|null, after: string|null, skillPath: string|null}>} deps.readPair
15
- * @param {(input: object) => Promise<{verdict:string, better:number, worse:number, ties:number, valid:number, votes:Array, errors:string[]}>} [deps.judge]
16
- * 同步不可行时(工具 execute 内无法等待子代理)改用 deps.hasKeepRecord。
17
- * @param {(input:{projectDir:string, skillPath:string|null}) => Promise<boolean>|boolean} [deps.hasKeepRecord]
18
- * 两阶段异步模式的同步判据:results.tsv 中存在该 skill 的 paired keep 记录。
19
- * @param {(line: string, extra?: object) => void} [deps.diag]
20
- * @returns {(args: object, exec?: object) => Promise<string|null>} 返回拒绝原因;null = 放行
21
- */
22
- export function createAdoptGate(deps) {
23
- const { readPair, judge, hasKeepRecord, diag } = deps;
24
- return async (args) => {
25
- const projectDir = typeof args?.project === 'string' && args.project.trim() !== '' ? args.project : null;
26
- if (projectDir === null) return 'adopt gate: project directory is required';
27
- let pair;
28
- try {
29
- pair = await readPair(projectDir);
30
- } catch (error) {
31
- const message = `adopt gate: cannot read proposal/baseline (${error?.message ?? error})`;
32
- diag?.(message, { ev: 'skillopt.adoptgate.fail' });
33
- return message;
34
- }
35
- if (pair?.after === null || pair?.after === undefined || pair?.before === null || pair?.before === undefined) {
36
- const message = 'adopt gate: cannot verify — staged proposal or baseline SKILL.md is missing (unverified adopt is refused)';
37
- diag?.(message, { ev: 'skillopt.adoptgate.fail', project: projectDir });
38
- return message;
39
- }
40
- // 两阶段异步模式:判据来自已落盘的 paired keep 记录(同步可查)。
41
- if (typeof hasKeepRecord === 'function') {
42
- let verified = false;
43
- try {
44
- verified = await hasKeepRecord({ projectDir, skillPath: pair.skillPath ?? null, candidate: pair.after });
45
- } catch (error) {
46
- const message = `adopt gate: cannot read judge records (${error?.message ?? error})`;
47
- diag?.(message, { ev: 'skillopt.adoptgate.fail', project: projectDir });
48
- return message;
49
- }
50
- diag?.('skillopt.adoptgate.decision', { ev: 'skillopt.adoptgate', project: projectDir, source: 'paired-keep-record', verified });
51
- if (verified) return null;
52
- return 'adopt gate: no paired keep record for this skill — run the optimize loop to a keep first (unverified adopt is refused)';
53
- }
54
- if (typeof judge !== 'function') return 'adopt gate: no verification source configured (unverified adopt is refused)';
55
- let result;
56
- try {
57
- result = await judge({ before: pair.before, after: pair.after, projectDir, skillPath: pair.skillPath ?? null });
58
- } catch (error) {
59
- const message = `adopt gate: judge unavailable (${error?.message ?? error}) — unverified adopt is refused`;
60
- diag?.(message, { ev: 'skillopt.adoptgate.fail', project: projectDir });
61
- return message;
62
- }
63
- diag?.('skillopt.adoptgate.decision', {
64
- ev: 'skillopt.adoptgate',
65
- project: projectDir,
66
- verdict: result.verdict,
67
- better: result.better,
68
- worse: result.worse,
69
- ties: result.ties,
70
- valid: result.valid,
71
- });
72
- if (result.verdict === 'keep') return null;
73
- const reasons = result.votes
74
- .filter((vote) => vote.vote === 'worse')
75
- .map((vote) => `judge ${vote.index}: ${vote.reason || 'worse'}`)
76
- .join(' | ');
77
- if (result.verdict === 'inconclusive') {
78
- return `adopt gate: inconclusive judge votes (${result.errors.join('; ') || 'no valid votes'}) — refusing unverified adopt`;
79
- }
80
- return `adopt gate: paired judge rejected the change (${result.better} better / ${result.worse} worse / ${result.ties} tie; ${result.valid} valid votes)${reasons ? ` — ${reasons}` : ''}`;
81
- };
82
- }
83
-
84
- /**
85
- * 包装 tools 服务,让 `skillopt_adopt` 的 execute 先过 adopt gate。
86
- * @param {object} tools ctx.get('tools')
87
- * @param {(args: object, exec?: object) => Promise<string|null>} gate
88
- * @returns {object} 供 applySkillOpt 使用的 tools 代理
89
- */
90
- export function wrapToolsWithAdoptGate(tools, gate) {
91
- if (tools === null || tools === undefined || typeof tools.register !== 'function') return tools;
92
- return {
93
- ...tools,
94
- register(definition, options) {
95
- if (definition?.name !== 'skillopt_adopt') return tools.register(definition, options);
96
- const originalExecute = definition.execute;
97
- const guarded = {
98
- ...definition,
99
- async execute(args, exec) {
100
- const refused = await gate(args, exec);
101
- if (typeof refused === 'string' && refused !== '') return `[skillopt skillopt_adopt] ${refused}`;
102
- return originalExecute.call(definition, args, exec);
103
- },
104
- };
105
- return tools.register(guarded, options);
106
- },
107
- };
108
- }
1
+ /**
2
+ * adopt 前门(Darwin 的 validation gate):把 `skillopt_adopt` 包一层——
3
+ * 先跑 paired 独立 judge,多数决为 revert/inconclusive 时拒绝 adopt,
4
+ * keep 时才放行原引擎调用。**不改 vendored 引擎**,只包 tools.register。
5
+ *
6
+ * gate 需要读取「改前 vs 改后」两版文本:改进后的候选来自 staged proposal
7
+ * (由调用方注入 readProposal),改前版本来自 git(HEAD 的 SKILL.md)或调用方
8
+ * 注入的 baseline 读取。任一缺失时门以「无法验证」拒绝——与 darwin 的
9
+ * 「没有验证证据不得 adopt」一致。
10
+ */
11
+
12
+ /**
13
+ * @param {object} deps
14
+ * @param {(projectDir: string) => Promise<{before: string|null, after: string|null, skillPath: string|null}>} deps.readPair
15
+ * @param {(input: object) => Promise<{verdict:string, better:number, worse:number, ties:number, valid:number, votes:Array, errors:string[]}>} [deps.judge]
16
+ * 同步不可行时(工具 execute 内无法等待子代理)改用 deps.hasKeepRecord。
17
+ * @param {(input:{projectDir:string, skillPath:string|null}) => Promise<boolean>|boolean} [deps.hasKeepRecord]
18
+ * 两阶段异步模式的同步判据:results.tsv 中存在该 skill 的 paired keep 记录。
19
+ * @param {(line: string, extra?: object) => void} [deps.diag]
20
+ * @returns {(args: object, exec?: object) => Promise<string|null>} 返回拒绝原因;null = 放行
21
+ */
22
+ export function createAdoptGate(deps) {
23
+ const { readPair, judge, hasKeepRecord, diag } = deps;
24
+ return async (args) => {
25
+ const projectDir = typeof args?.project === 'string' && args.project.trim() !== '' ? args.project : null;
26
+ if (projectDir === null) return 'adopt gate: project directory is required';
27
+ let pair;
28
+ try {
29
+ pair = await readPair(projectDir);
30
+ } catch (error) {
31
+ const message = `adopt gate: cannot read proposal/baseline (${error?.message ?? error})`;
32
+ diag?.(message, { ev: 'skillopt.adoptgate.fail' });
33
+ return message;
34
+ }
35
+ if (pair?.after === null || pair?.after === undefined || pair?.before === null || pair?.before === undefined) {
36
+ const message = 'adopt gate: cannot verify — staged proposal or baseline SKILL.md is missing (unverified adopt is refused)';
37
+ diag?.(message, { ev: 'skillopt.adoptgate.fail', project: projectDir });
38
+ return message;
39
+ }
40
+ // 两阶段异步模式:判据来自已落盘的 paired keep 记录(同步可查)。
41
+ if (typeof hasKeepRecord === 'function') {
42
+ let verified = false;
43
+ try {
44
+ verified = await hasKeepRecord({ projectDir, skillPath: pair.skillPath ?? null, candidate: pair.after });
45
+ } catch (error) {
46
+ const message = `adopt gate: cannot read judge records (${error?.message ?? error})`;
47
+ diag?.(message, { ev: 'skillopt.adoptgate.fail', project: projectDir });
48
+ return message;
49
+ }
50
+ diag?.('skillopt.adoptgate.decision', { ev: 'skillopt.adoptgate', project: projectDir, source: 'paired-keep-record', verified });
51
+ if (verified) return null;
52
+ return 'adopt gate: no paired keep record for this skill — run the optimize loop to a keep first (unverified adopt is refused)';
53
+ }
54
+ if (typeof judge !== 'function') return 'adopt gate: no verification source configured (unverified adopt is refused)';
55
+ let result;
56
+ try {
57
+ result = await judge({ before: pair.before, after: pair.after, projectDir, skillPath: pair.skillPath ?? null });
58
+ } catch (error) {
59
+ const message = `adopt gate: judge unavailable (${error?.message ?? error}) — unverified adopt is refused`;
60
+ diag?.(message, { ev: 'skillopt.adoptgate.fail', project: projectDir });
61
+ return message;
62
+ }
63
+ diag?.('skillopt.adoptgate.decision', {
64
+ ev: 'skillopt.adoptgate',
65
+ project: projectDir,
66
+ verdict: result.verdict,
67
+ better: result.better,
68
+ worse: result.worse,
69
+ ties: result.ties,
70
+ valid: result.valid,
71
+ });
72
+ if (result.verdict === 'keep') return null;
73
+ const reasons = result.votes
74
+ .filter((vote) => vote.vote === 'worse')
75
+ .map((vote) => `judge ${vote.index}: ${vote.reason || 'worse'}`)
76
+ .join(' | ');
77
+ if (result.verdict === 'inconclusive') {
78
+ return `adopt gate: inconclusive judge votes (${result.errors.join('; ') || 'no valid votes'}) — refusing unverified adopt`;
79
+ }
80
+ return `adopt gate: paired judge rejected the change (${result.better} better / ${result.worse} worse / ${result.ties} tie; ${result.valid} valid votes)${reasons ? ` — ${reasons}` : ''}`;
81
+ };
82
+ }
83
+
84
+ /**
85
+ * 包装 tools 服务,让 `skillopt_adopt` 的 execute 先过 adopt gate。
86
+ * @param {object} tools ctx.get('tools')
87
+ * @param {(args: object, exec?: object) => Promise<string|null>} gate
88
+ * @returns {object} 供 applySkillOpt 使用的 tools 代理
89
+ */
90
+ export function wrapToolsWithAdoptGate(tools, gate) {
91
+ if (tools === null || tools === undefined || typeof tools.register !== 'function') return tools;
92
+ return {
93
+ ...tools,
94
+ register(definition, options) {
95
+ if (definition?.name !== 'skillopt_adopt') return tools.register(definition, options);
96
+ const originalExecute = definition.execute;
97
+ const guarded = {
98
+ ...definition,
99
+ async execute(args, exec) {
100
+ const refused = await gate(args, exec);
101
+ if (typeof refused === 'string' && refused !== '') return `[skillopt skillopt_adopt] ${refused}`;
102
+ return originalExecute.call(definition, args, exec);
103
+ },
104
+ };
105
+ return tools.register(guarded, options);
106
+ },
107
+ };
108
+ }