@suifei/dsh-ai-team 0.3.89 → 0.3.98
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/CHANGELOG.md +11 -0
- package/index.js +79 -16
- package/lib/skillopt/judge-runner.js +3 -18
- package/lib/skillopt/optimize-wiring.js +110 -0
- package/lib/skillopt/optimizer.js +182 -0
- package/lib/skillopt/subagent-text.js +101 -0
- package/package.json +1 -1
- package/skills/ai-team-core/SKILL.md +15 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.90 - 2026-11-12
|
|
4
|
+
|
|
5
|
+
**Darwin Phase 2 自动 hill-climbing 循环(`skillopt_optimize`)**
|
|
6
|
+
|
|
7
|
+
- 每轮:rubric 诊断最大加权短板 → 独立生成器产出候选(子代理,仅改该维度)→ 写入 → paired 独立 judge 多数决 → keep 保留 / revert 回滚 → results.tsv 追加。
|
|
8
|
+
- 约束:单维改动、150% 体积上限、连续 2 轮 margin 全 slight/tie 触顶 break(HL-4 见好就收)、judge 不可用即回滚(未验证改动绝不保留)。
|
|
9
|
+
- 版本化双模式:项目是**干净 git 仓库**时 commit/revert(新提交回滚,不用 reset --hard);否则 `.skillopt-sleep/backups/*.bak` 文件备份恢复。
|
|
10
|
+
- 结果记录 `<project>/.skillopt-sleep/results.tsv`(9 列,与 darwin 格式一致);keep/revert 记 `eval_mode=paired`。
|
|
11
|
+
- 测试:`test/skillopt-optimize.test.js` 9 项(短板诊断与平局、plateau 判据、候选校验、keep/revert/跳过/回滚/触顶、TSV 9 列)。
|
|
12
|
+
|
|
13
|
+
|
|
3
14
|
## 0.3.89 - 2026-11-12
|
|
4
15
|
|
|
5
16
|
**完全对齐 darwin-skill v2.1(9 维 rubric + 独立 judge)**
|
package/index.js
CHANGED
|
@@ -28,6 +28,8 @@ import { apply as applySkillOpt } from './lib/vendor/skillopt/src/index.js';
|
|
|
28
28
|
import { createAdoptGate, wrapToolsWithAdoptGate } from './lib/skillopt/adopt-gate.js';
|
|
29
29
|
import { formatRubric, scoreSkillRubric } from './lib/skillopt/rubric.js';
|
|
30
30
|
import { makeJudge, makeReadPair } from './lib/skillopt/gate-wiring.js';
|
|
31
|
+
import { runOptimizeLoop } from './lib/skillopt/optimizer.js';
|
|
32
|
+
import { makeGenerator, makeResultAppender, makeVcs } from './lib/skillopt/optimize-wiring.js';
|
|
31
33
|
import { createMemberPermissionGuard } from './lib/host/permission-guard.js';
|
|
32
34
|
import { installFaultAdapter } from './lib/host/fault-adapter.js';
|
|
33
35
|
import { buildModelCatalog } from './lib/host/model-catalog.js';
|
|
@@ -44,7 +46,7 @@ export const name = 'ai-team';
|
|
|
44
46
|
/** The workbench only makes sense where the Web carrier exists. */
|
|
45
47
|
export const inject = ['webServer', 'permissionPresets', 'sandboxPolicy', 'tools', 'shell'];
|
|
46
48
|
|
|
47
|
-
const VERSION = '0.3.
|
|
49
|
+
const VERSION = '0.3.98';
|
|
48
50
|
const HUMAN_ID = 'mem_human';
|
|
49
51
|
|
|
50
52
|
const SKILLOPT_BACKENDS = ['mock', 'claude', 'codex', 'copilot', 'cursor', 'pi', 'opencode', 'handoff', 'azure_openai'];
|
|
@@ -751,28 +753,35 @@ export function apply(ctx, config = {}) {
|
|
|
751
753
|
const tools = ctx.get('tools');
|
|
752
754
|
let disposeSkillOpt = () => {};
|
|
753
755
|
try {
|
|
754
|
-
|
|
755
|
-
//
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
756
|
+
// shell 惰性代理:注入时机早于 shell 服务就绪时,注册仍必须完成——
|
|
757
|
+
// 每次调用现取,避免「boot 时 shell 未就绪 → 整条技能链静默跳过」。
|
|
758
|
+
const shellProxy = {
|
|
759
|
+
resolve: (spec) => {
|
|
760
|
+
const service = ctx.get('shell');
|
|
761
|
+
if (service === undefined || service === null) throw new Error('shell service is not available');
|
|
762
|
+
return typeof service.resolve === 'function' ? service.resolve(spec) : spec;
|
|
763
|
+
},
|
|
764
|
+
execute: async (spec) => {
|
|
765
|
+
const service = ctx.get('shell');
|
|
766
|
+
if (service === undefined || service === null) throw new Error('shell service is not available');
|
|
767
|
+
return typeof service.execute === 'function' ? service.execute(spec) : service.run(spec);
|
|
768
|
+
},
|
|
769
|
+
};
|
|
770
|
+
if (!tools?.register) {
|
|
771
|
+
diag.append({ ev: 'skillopt.skip.fail', hasToolsRegister: false, hasShell: Boolean(ctx.get('shell')) });
|
|
772
|
+
console.warn('[ai-team] SkillOpt tools not registered: no tool registry');
|
|
764
773
|
}
|
|
765
|
-
if (tools?.register
|
|
774
|
+
if (tools?.register) {
|
|
766
775
|
// Darwin validation gate(对齐 darwin-skill v2.1):adopt 之前必须
|
|
767
776
|
// 通过 paired 独立 judge 的多数决;绝对 rubric 分只做 triage。
|
|
768
777
|
const engineScript = fileURLToPath(new URL('./lib/vendor/skillopt/scripts/sleep.py', import.meta.url));
|
|
769
|
-
const readPair = makeReadPair({ shell, engineScript, diag });
|
|
778
|
+
const readPair = makeReadPair({ shell: shellProxy, engineScript, diag });
|
|
770
779
|
const judge = makeJudge({
|
|
771
780
|
subagents: ctx.get('subagents'),
|
|
772
781
|
// 惰性解析:ensureParent 在 apply 之后才定义(const TDZ),
|
|
773
782
|
// judge 只在 adopt 时调用,此处不能立即取值。
|
|
774
783
|
ensureParent: () => ensureParent(),
|
|
775
|
-
providerName: () =>
|
|
784
|
+
providerName: () => (ctx.get('subagents')?.list?.() ?? [])[0],
|
|
776
785
|
votes: config.skilloptJudgeVotes ?? 3,
|
|
777
786
|
diag,
|
|
778
787
|
});
|
|
@@ -789,7 +798,7 @@ export function apply(ctx, config = {}) {
|
|
|
789
798
|
// operator can move the skillopt_* tools off the safe mock default.
|
|
790
799
|
disposeSkillOpt = applySkillOpt({
|
|
791
800
|
tools: wrapToolsWithAdoptGate(tools, adoptGate),
|
|
792
|
-
shell,
|
|
801
|
+
shell: shellProxy,
|
|
793
802
|
logger: console,
|
|
794
803
|
}, {
|
|
795
804
|
backend: config.skilloptBackend ?? 'mock',
|
|
@@ -851,13 +860,67 @@ export function apply(ctx, config = {}) {
|
|
|
851
860
|
].filter(Boolean).join('\n');
|
|
852
861
|
},
|
|
853
862
|
});
|
|
863
|
+
// Darwin Phase 2:自动 hill-climbing(诊断→生成→写入→judge→keep/revert)。
|
|
864
|
+
// 同一轮只改一个维度,版本化走干净 git 仓库,否则 .bak 备份。
|
|
865
|
+
const optimizeTool = tools.register({
|
|
866
|
+
name: 'skillopt_optimize',
|
|
867
|
+
description: 'Run the Darwin hill-climbing loop on one SKILL.md: weakest-dimension diagnosis, generated candidate, paired independent judge, keep/revert, results.tsv.',
|
|
868
|
+
parameters: {
|
|
869
|
+
project: { type: 'string', description: 'Project directory' },
|
|
870
|
+
skillPath: { type: 'string', description: 'Path to SKILL.md to optimize' },
|
|
871
|
+
rounds: { type: 'number', description: 'Max rounds (default 3)' },
|
|
872
|
+
},
|
|
873
|
+
output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
|
|
874
|
+
async execute(args) {
|
|
875
|
+
const project = typeof args?.project === 'string' && args.project !== '' ? args.project : process.cwd();
|
|
876
|
+
const skillPath = typeof args?.skillPath === 'string' && args.skillPath !== '' ? args.skillPath : join(project, 'SKILL.md');
|
|
877
|
+
if (!existsSync(skillPath)) return `[skillopt optimize] SKILL.md not found: ${skillPath}`;
|
|
878
|
+
const rounds = Number.isSafeInteger(args?.rounds) ? Math.max(1, Math.min(5, args.rounds)) : 3;
|
|
879
|
+
const vcs = await makeVcs({ shell: shellProxy, projectDir: project });
|
|
880
|
+
const result = await runOptimizeLoop({
|
|
881
|
+
skillPath,
|
|
882
|
+
rounds,
|
|
883
|
+
readText: async (path) => readFileSync(path, 'utf8'),
|
|
884
|
+
writeText: async (path, text) => writeFileSync(path, text, 'utf8'),
|
|
885
|
+
score: (text) => scoreSkillRubric(text, { measured: false }),
|
|
886
|
+
generate: makeGenerator({
|
|
887
|
+
subagents: ctx.get('subagents'),
|
|
888
|
+
ensureParent: () => ensureParent(),
|
|
889
|
+
providerName: () => (ctx.get('subagents')?.list?.() ?? [])[0],
|
|
890
|
+
cwd: project,
|
|
891
|
+
diag,
|
|
892
|
+
}),
|
|
893
|
+
judge: async ({ before, after }) => {
|
|
894
|
+
const judge = makeJudge({
|
|
895
|
+
subagents: ctx.get('subagents'),
|
|
896
|
+
ensureParent: () => ensureParent(),
|
|
897
|
+
providerName: () => (ctx.get('subagents')?.list?.() ?? [])[0],
|
|
898
|
+
votes: config.skilloptJudgeVotes ?? 3,
|
|
899
|
+
diag,
|
|
900
|
+
});
|
|
901
|
+
return judge({ before, after, projectDir: project });
|
|
902
|
+
},
|
|
903
|
+
vcs,
|
|
904
|
+
appendResult: makeResultAppender({ projectDir: project }),
|
|
905
|
+
});
|
|
906
|
+
diag.append({ ev: 'skillopt.optimize', project, skillPath, status: result.status, rounds: result.rounds.length, finalScore: result.finalScore, vcs: vcs.kind });
|
|
907
|
+
const lines = [
|
|
908
|
+
`[skillopt optimize] status=${result.status} rounds=${result.rounds.length} finalScore=${result.finalScore ?? '-'} vcs=${vcs.kind}`,
|
|
909
|
+
...(result.rounds ?? []).map((round) => ` r${round.round} ${round.dimension}: ${round.verdict} (${round.better}-${round.worse}) ${round.oldScore}→${round.newScore ?? '-'}${round.kept ? ' kept' : ' reverted'}`),
|
|
910
|
+
result.error ? ` error: ${result.error}` : '',
|
|
911
|
+
].filter(Boolean);
|
|
912
|
+
return lines.join('\n');
|
|
913
|
+
},
|
|
914
|
+
});
|
|
915
|
+
// 汇总释放:引擎工具 + 三个附加工具(顺序无关,各自 try)。
|
|
854
916
|
const disposeExtra = () => {
|
|
855
917
|
try { disposeSkillOpt?.(); } catch { /* already disposed */ }
|
|
856
918
|
try { rubricTool?.(); } catch { /* noop */ }
|
|
857
919
|
try { judgeTool?.(); } catch { /* noop */ }
|
|
920
|
+
try { optimizeTool?.(); } catch { /* noop */ }
|
|
858
921
|
};
|
|
859
922
|
disposeSkillOpt = disposeExtra;
|
|
860
|
-
diag.append({ ev: 'skillopt.registered', backend: config.skilloptBackend ?? 'mock', timeoutMs: config.skilloptTimeoutMs ?? 120_000, adoptGate: true, judgeVotes: config.skilloptJudgeVotes ?? 3 });
|
|
923
|
+
diag.append({ ev: 'skillopt.registered', backend: config.skilloptBackend ?? 'mock', timeoutMs: config.skilloptTimeoutMs ?? 120_000, adoptGate: true, judgeVotes: config.skilloptJudgeVotes ?? 3, optimize: true });
|
|
861
924
|
}
|
|
862
925
|
} catch (error) {
|
|
863
926
|
diag.append({ ev: 'skillopt.fail', message: error?.message ?? String(error) });
|
|
@@ -7,22 +7,10 @@
|
|
|
7
7
|
* 汇总成 paired 多数决 verdict。
|
|
8
8
|
*/
|
|
9
9
|
import { buildPairPrompt, decideByMajority, normalizeVoteCount, parseJudgeOutput, voteFromParsed } from './judge.js';
|
|
10
|
+
import { awaitActivationText } from './subagent-text.js';
|
|
10
11
|
|
|
11
12
|
const JUDGE_TIMEOUT_MS = 120_000;
|
|
12
13
|
|
|
13
|
-
/** 从子代理的 result.output 里取纯文本。 */
|
|
14
|
-
function outputText(output) {
|
|
15
|
-
if (typeof output === 'string') return output;
|
|
16
|
-
if (Array.isArray(output)) {
|
|
17
|
-
return output.map((part) => (typeof part === 'string' ? part : part?.text ?? part?.content ?? '')).join('\n');
|
|
18
|
-
}
|
|
19
|
-
if (output && typeof output === 'object') {
|
|
20
|
-
if (typeof output.text === 'string') return output.text;
|
|
21
|
-
if (typeof output.content === 'string') return output.content;
|
|
22
|
-
}
|
|
23
|
-
return '';
|
|
24
|
-
}
|
|
25
|
-
|
|
26
14
|
/**
|
|
27
15
|
* 起 N 个独立 judge 子代理做 paired 比较。
|
|
28
16
|
*
|
|
@@ -61,12 +49,9 @@ export async function judgePair(input) {
|
|
|
61
49
|
label: `skillopt-judge-${index + 1}`,
|
|
62
50
|
request: { cwd, prompt: [{ type: 'text', text: prompt }], parent },
|
|
63
51
|
delivery: 'parent',
|
|
52
|
+
signal: new AbortController().signal,
|
|
64
53
|
});
|
|
65
|
-
const
|
|
66
|
-
Promise.resolve(activation?.result),
|
|
67
|
-
new Promise((resolve) => setTimeout(() => resolve(null), JUDGE_TIMEOUT_MS)),
|
|
68
|
-
]);
|
|
69
|
-
const text = outputText(result?.output ?? result ?? '');
|
|
54
|
+
const text = await awaitActivationText(activation, { timeoutMs: JUDGE_TIMEOUT_MS });
|
|
70
55
|
const parsed = parseJudgeOutput(text);
|
|
71
56
|
const vote = voteFromParsed(parsed === null ? null : { ...parsed, aIsAfter: mapping.aIsAfter });
|
|
72
57
|
if (vote === null) errors.push(`judge ${index + 1}: unparseable output`);
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 自动优化循环的宿主适配:VCS(git / 文件备份)、候选生成器(独立子代理)、
|
|
3
|
+
* results.tsv 追加。与 optimizer.js 的纯编排分离,便于测试替换。
|
|
4
|
+
*/
|
|
5
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync, copyFileSync } from 'node:fs';
|
|
6
|
+
import { dirname, join } from 'node:path';
|
|
7
|
+
import { runEngineCli, quoteArgv } from './gate-wiring.js';
|
|
8
|
+
import { awaitActivationText } from './subagent-text.js';
|
|
9
|
+
|
|
10
|
+
/** 项目是否为干净 git 仓库(决定 git 棘轮还是文件备份)。 */
|
|
11
|
+
async function isCleanGitRepo(shell, cwd) {
|
|
12
|
+
const inside = await runEngineCli(shell, ['git', '-C', cwd, 'rev-parse', '--is-inside-work-tree']).catch(() => null);
|
|
13
|
+
if (inside?.exitCode !== 0 || !/true/.test(inside?.stdout ?? '')) return false;
|
|
14
|
+
const status = await runEngineCli(shell, ['git', '-C', cwd, 'status', '--porcelain']).catch(() => null);
|
|
15
|
+
return status?.exitCode === 0 && (status.stdout ?? '').trim() === '';
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @param {{shell:object, projectDir:string, now?:()=>number}} deps
|
|
20
|
+
* @returns {Promise<object>} vcs 适配器
|
|
21
|
+
*/
|
|
22
|
+
export async function makeVcs({ shell, projectDir, now = () => Date.now() }) {
|
|
23
|
+
const git = await isCleanGitRepo(shell, projectDir);
|
|
24
|
+
if (git) {
|
|
25
|
+
const commit = async (message) => {
|
|
26
|
+
const add = await runEngineCli(shell, ['git', '-C', projectDir, 'add', '-A']);
|
|
27
|
+
if (add.exitCode !== 0) throw new Error(`git add failed: ${add.stderr}`);
|
|
28
|
+
const done = await runEngineCli(shell, ['git', '-C', projectDir, 'commit', '-m', message, '--no-verify']);
|
|
29
|
+
if (done.exitCode !== 0) throw new Error(`git commit failed: ${done.stderr}`);
|
|
30
|
+
const head = await runEngineCli(shell, ['git', '-C', projectDir, 'rev-parse', '--short', 'HEAD']);
|
|
31
|
+
return (head.stdout ?? '').trim() || null;
|
|
32
|
+
};
|
|
33
|
+
return {
|
|
34
|
+
kind: 'git',
|
|
35
|
+
commit,
|
|
36
|
+
// keep 时无需额外动作:commit 已留下保留版本。
|
|
37
|
+
commitKept: async () => {},
|
|
38
|
+
revert: async () => {
|
|
39
|
+
const done = await runEngineCli(shell, ['git', '-C', projectDir, 'revert', 'HEAD', '--no-edit']);
|
|
40
|
+
if (done.exitCode !== 0) throw new Error(`git revert failed: ${done.stderr}`);
|
|
41
|
+
},
|
|
42
|
+
writeBaseline: async (path, text) => { writeFileSync(path, text, 'utf8'); },
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
const backupDir = join(projectDir, '.skillopt-sleep', 'backups');
|
|
46
|
+
mkdirSync(backupDir, { recursive: true });
|
|
47
|
+
return {
|
|
48
|
+
kind: 'file',
|
|
49
|
+
backup: async (path, text) => {
|
|
50
|
+
const stamp = new Date(now()).toISOString().replace(/[:.]/g, '-');
|
|
51
|
+
const target = join(backupDir, `${path.split(/[\\/]/).pop()}.${stamp}.bak`);
|
|
52
|
+
writeFileSync(target, text, 'utf8');
|
|
53
|
+
return target;
|
|
54
|
+
},
|
|
55
|
+
restore: async (path, backupPath) => {
|
|
56
|
+
if (!existsSync(backupPath)) throw new Error(`backup missing: ${backupPath}`);
|
|
57
|
+
copyFileSync(backupPath, path);
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** 独立生成器:一次性子代理按 rubric 短板改进,只输出完整新文件。 */
|
|
63
|
+
export function makeGenerator({ subagents, ensureParent, providerName, cwd, diag }) {
|
|
64
|
+
return async ({ skillPath, before, dimension, round }) => {
|
|
65
|
+
const parentInfo = await ensureParent();
|
|
66
|
+
const provider = providerName();
|
|
67
|
+
const prompt = [
|
|
68
|
+
'你是技能改进器。只输出改进后的完整 SKILL.md 内容(不要解释、不要代码围栏)。',
|
|
69
|
+
`目标维度:dim${dimension.id} ${dimension.name}(当前 ${dimension.score}/10,权重 ${dimension.weight})。`,
|
|
70
|
+
'硬约束:不得改变技能的核心用途;只解决该维度;不得删掉已有的失败分支/检查点/反例清单;',
|
|
71
|
+
'不得加长到原文 150% 以上;不得引入软化措辞(建议/可以考虑/根据情况/灵活把握/视情况而定)。',
|
|
72
|
+
`这是第 ${round} 轮。`,
|
|
73
|
+
'',
|
|
74
|
+
'## 原文',
|
|
75
|
+
before,
|
|
76
|
+
].join('\n');
|
|
77
|
+
const activation = await subagents.startActivation({
|
|
78
|
+
provider,
|
|
79
|
+
label: `skillopt-optimize-${round}`,
|
|
80
|
+
request: { cwd, prompt: [{ type: 'text', text: prompt }], parent: parentInfo?.agent },
|
|
81
|
+
delivery: 'parent',
|
|
82
|
+
signal: new AbortController().signal,
|
|
83
|
+
});
|
|
84
|
+
// 探针(ev 以 .fail 结尾以便在 errors 级 diag 中可见)。
|
|
85
|
+
diag?.append?.({ ev: 'skillopt.generate.probe.fail', kind: activation?.kind ?? null, hasHandle: Boolean(activation?.handle), hasAgent: Boolean(activation?.handle?.agent), hasSnapshot: typeof activation?.handle?.agent?.session?.snapshotEvents === 'function', outputStart: typeof activation?.outputStart, keys: Object.keys(activation ?? {}).join(',') });
|
|
86
|
+
try {
|
|
87
|
+
const raw = await awaitActivationText(activation);
|
|
88
|
+
diag?.append?.({ ev: 'skillopt.generate.text.fail', chars: raw.length, preview: raw.slice(0, 160) });
|
|
89
|
+
// 去掉可能包裹的 ```markdown 围栏。
|
|
90
|
+
const fenced = raw.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```/);
|
|
91
|
+
return fenced !== null ? fenced[1] : raw.trim();
|
|
92
|
+
} finally {
|
|
93
|
+
try { await activation?.dispose?.(); } catch { /* already gone */ }
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** results.tsv 追加(表头自动补)。 */
|
|
99
|
+
export function makeResultAppender({ projectDir }) {
|
|
100
|
+
const dir = join(projectDir, '.skillopt-sleep');
|
|
101
|
+
const path = join(dir, 'results.tsv');
|
|
102
|
+
return async (line) => {
|
|
103
|
+
mkdirSync(dir, { recursive: true });
|
|
104
|
+
const header = ['timestamp', 'commit', 'skill', 'old_score', 'new_score', 'status', 'dimension', 'note', 'eval_mode'].join('\t');
|
|
105
|
+
const prefix = existsSync(path) && readFileSync(path, 'utf8').includes('eval_mode') ? '' : header + '\n';
|
|
106
|
+
writeFileSync(path, prefix + line + '\n', { encoding: 'utf8', flag: 'a' });
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export { quoteArgv };
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Darwin Phase 2 自动优化循环(hill-climbing)——插件侧编排。
|
|
3
|
+
*
|
|
4
|
+
* 一轮 = 诊断(rubric 最大加权短板)→ 生成改进(独立生成器,非 judge)→
|
|
5
|
+
* 写入 → paired 独立 judge 多数决 → keep(保留)或 revert(回滚)→ 记录。
|
|
6
|
+
*
|
|
7
|
+
* 安全约束(对齐 darwin 与项目纪律):
|
|
8
|
+
* - 每轮只针对一个维度(避免多变量无法归因);
|
|
9
|
+
* - 体积上限 150%(超限直接拒绝,不进入 judge);
|
|
10
|
+
* - 棘轮用 paired 多数决(绝对分只做 triage);
|
|
11
|
+
* - 版本化:项目是干净 git 仓库时用 commit/revert,否则用 .bak 文件恢复;
|
|
12
|
+
* - 连续 2 轮 judge margin 全为 slight/tie → 触顶 break(见好就收,HL-4)。
|
|
13
|
+
*
|
|
14
|
+
* 纯逻辑与 I/O 分离:所有外部动作(读/写/git/生成/judge/评分/时钟)都注入,
|
|
15
|
+
* 因此循环可在测试里用一个内存文件系统完整验证。
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
export const DEFAULT_ROUNDS = 3;
|
|
19
|
+
const MAX_GROWTH = 1.5;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* 最大加权短板(weight × (10 - score) / 10;同分时取原始分更低者)。
|
|
23
|
+
*
|
|
24
|
+
* dim8「实测表现」被排除:它由测试 prompt 的真实运行决定,静态改写无法改进,
|
|
25
|
+
* 选它会让生成器空转(实测暴露的问题)。dim8 的改进走 full_test 流程。
|
|
26
|
+
*/
|
|
27
|
+
export function weakestDimension(rubric) {
|
|
28
|
+
const scored = (rubric?.dimensions ?? []).filter((dimension) => Number.isFinite(dimension?.score) && dimension?.id !== 8);
|
|
29
|
+
if (scored.length === 0) return null;
|
|
30
|
+
return scored.reduce((worst, dimension) => {
|
|
31
|
+
const gap = dimension.weight * (10 - dimension.score) / 10;
|
|
32
|
+
const worstGap = worst.weight * (10 - worst.score) / 10;
|
|
33
|
+
if (gap > worstGap) return dimension;
|
|
34
|
+
if (gap === worstGap && dimension.score < worst.score) return dimension;
|
|
35
|
+
return worst;
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 触顶判据:连续 2 轮 judge 的 margin 全为 slight/tie。 */
|
|
40
|
+
export function isPlateau(recentMargins) {
|
|
41
|
+
const lastTwo = recentMargins.slice(-2);
|
|
42
|
+
return lastTwo.length === 2 && lastTwo.every((row) => row.every((margin) => margin === 'slight' || margin === 'tie'));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** 一轮候选的静态校验:不得超体积上限、必须真的变了。 */
|
|
46
|
+
export function validateCandidate({ before, after }) {
|
|
47
|
+
if (typeof after !== 'string' || after.trim() === '') return { ok: false, reason: 'generator returned an empty candidate' };
|
|
48
|
+
if (after === before) return { ok: false, reason: 'generator returned an unchanged candidate' };
|
|
49
|
+
if (after.length > before.length * MAX_GROWTH) {
|
|
50
|
+
return { ok: false, reason: `candidate exceeds 150% of the original size (${before.length} -> ${after.length}); trim before judging` };
|
|
51
|
+
}
|
|
52
|
+
return { ok: true, reason: '' };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** results.tsv 行(9 列,与 darwin 格式一致)。 */
|
|
56
|
+
export function resultRow({ timestamp, commit, skill, oldScore, newScore, status, dimension, note, evalMode }) {
|
|
57
|
+
return [timestamp, commit, skill, oldScore, newScore, status, dimension, note, evalMode].join('\t');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export const RESULTS_HEADER = ['timestamp', 'commit', 'skill', 'old_score', 'new_score', 'status', 'dimension', 'note', 'eval_mode'].join('\t');
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 跑一个 skill 的优化循环。
|
|
64
|
+
*
|
|
65
|
+
* @param {object} input
|
|
66
|
+
* @param {string} input.skillPath 目标 SKILL.md 绝对路径
|
|
67
|
+
* @param {string} [input.skillName] 记录用名字(默认取文件名所在目录名)
|
|
68
|
+
* @param {number} [input.rounds] MAX_ROUNDS(默认 3)
|
|
69
|
+
* @param {(path:string)=>Promise<string>} input.readText
|
|
70
|
+
* @param {(path:string, text:string)=>Promise<void>} input.writeText
|
|
71
|
+
* @param {(text:string, options:{measured:boolean})=>object} input.score 同步 rubric 评分
|
|
72
|
+
* @param {(input:{skillPath:string, before:string, dimension:object, round:number})=>Promise<string>} input.generate 生成候选全文
|
|
73
|
+
* @param {(input:{before:string, after:string, skillPath:string})=>Promise<{verdict:string, better:number, worse:number, ties:number, valid:number, votes:Array, errors:string[]}>} input.judge
|
|
74
|
+
* @param {object} input.vcs `{kind:'git', commit:(message)=>Promise<string>, revert:()=>Promise<void>}` 或 `{kind:'file', backup:(path:string,text:string)=>Promise<string>, restore:(path:string,backup:string)=>Promise<void>}`
|
|
75
|
+
* @param {(line:string)=>Promise<void>} [input.appendResult] 追加 results.tsv(含表头由实现方保证)
|
|
76
|
+
* @param {() => number} [input.now]
|
|
77
|
+
* @returns {Promise<{status:'completed'|'plateau'|'reverted'|'error', rounds:Array, finalScore:number|null, error?:string}>}
|
|
78
|
+
*/
|
|
79
|
+
export async function runOptimizeLoop(input) {
|
|
80
|
+
const {
|
|
81
|
+
skillPath, skillName, rounds = DEFAULT_ROUNDS, readText, writeText, score, generate, judge, vcs,
|
|
82
|
+
appendResult, now = () => Date.now(),
|
|
83
|
+
} = input;
|
|
84
|
+
const name = skillName ?? skillPath.split(/[\\/]/).slice(-2, -1)[0] ?? skillPath;
|
|
85
|
+
const history = [];
|
|
86
|
+
const staleness = [];
|
|
87
|
+
const stamp = () => new Date(now()).toISOString().slice(0, 19);
|
|
88
|
+
try {
|
|
89
|
+
for (let round = 1; round <= rounds; round++) {
|
|
90
|
+
const before = await readText(skillPath);
|
|
91
|
+
const baseline = score(before, { measured: false });
|
|
92
|
+
const dimension = weakestDimension(baseline);
|
|
93
|
+
if (dimension === null) {
|
|
94
|
+
await appendResult?.(resultRow({ timestamp: stamp(), commit: '-', skill: name, oldScore: String(baseline?.total ?? '-'), newScore: '-', status: 'error', dimension: '-', note: 'rubric produced no scorable dimensions', evalMode: 'structural' }));
|
|
95
|
+
return { status: 'error', rounds: history, finalScore: baseline?.total ?? null, error: 'no scorable dimensions' };
|
|
96
|
+
}
|
|
97
|
+
let candidate;
|
|
98
|
+
try {
|
|
99
|
+
candidate = await generate({ skillPath, before, dimension, round });
|
|
100
|
+
} catch (error) {
|
|
101
|
+
return { status: 'error', rounds: history, finalScore: baseline?.total ?? null, error: `generator failed: ${error?.message ?? error}` };
|
|
102
|
+
}
|
|
103
|
+
const validation = validateCandidate({ before, after: candidate });
|
|
104
|
+
if (!validation.ok) {
|
|
105
|
+
await appendResult?.(resultRow({ timestamp: stamp(), commit: '-', skill: name, oldScore: String(baseline.total), newScore: '-', status: 'skipped', dimension: dimension.name, note: validation.reason, evalMode: 'structural' }));
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
// 版本化:先记录基线,再写入候选。
|
|
109
|
+
let version = null;
|
|
110
|
+
if (vcs?.kind === 'git') {
|
|
111
|
+
try { version = await vcs.commit(`optimize ${name}: address dim${dimension.id} ${dimension.name}`); }
|
|
112
|
+
catch { version = null; }
|
|
113
|
+
} else if (vcs?.kind === 'file') {
|
|
114
|
+
version = await vcs.backup(skillPath, before);
|
|
115
|
+
}
|
|
116
|
+
await writeText(skillPath, candidate);
|
|
117
|
+
let verdict;
|
|
118
|
+
try {
|
|
119
|
+
verdict = await judge({ before, after: candidate, skillPath });
|
|
120
|
+
} catch (error) {
|
|
121
|
+
// judge 不可用:回滚,绝不保留未验证改动。
|
|
122
|
+
await restore(vcs, skillPath, before, version);
|
|
123
|
+
return { status: 'error', rounds: history, finalScore: baseline.total, error: `judge unavailable: ${error?.message ?? error}` };
|
|
124
|
+
}
|
|
125
|
+
const margins = (verdict.votes ?? []).map((vote) => vote.margin ?? 'slight');
|
|
126
|
+
staleness.push(margins);
|
|
127
|
+
const kept = verdict.verdict === 'keep';
|
|
128
|
+
if (!kept) {
|
|
129
|
+
await restore(vcs, skillPath, before, version);
|
|
130
|
+
} else if (vcs?.kind === 'git' && version !== null && typeof vcs.commitKept === 'function') {
|
|
131
|
+
await vcs.commitKept(version);
|
|
132
|
+
}
|
|
133
|
+
const afterScore = kept ? score(candidate, { measured: false }) : baseline;
|
|
134
|
+
history.push({
|
|
135
|
+
round,
|
|
136
|
+
dimension: `dim${dimension.id} ${dimension.name}`,
|
|
137
|
+
verdict: verdict.verdict,
|
|
138
|
+
better: verdict.better,
|
|
139
|
+
worse: verdict.worse,
|
|
140
|
+
ties: verdict.ties,
|
|
141
|
+
margins,
|
|
142
|
+
oldScore: baseline.total,
|
|
143
|
+
newScore: afterScore?.total ?? null,
|
|
144
|
+
kept,
|
|
145
|
+
});
|
|
146
|
+
await appendResult?.(resultRow({
|
|
147
|
+
timestamp: stamp(),
|
|
148
|
+
commit: version ?? '-',
|
|
149
|
+
skill: name,
|
|
150
|
+
oldScore: String(baseline.total),
|
|
151
|
+
newScore: String(afterScore?.total ?? '-'),
|
|
152
|
+
status: kept ? 'keep' : 'revert',
|
|
153
|
+
dimension: `dim${dimension.id}`,
|
|
154
|
+
note: `${verdict.better}-${verdict.worse} ${verdict.verdict}${verdict.errors?.length ? ` (${verdict.errors.join('; ')})` : ''}`,
|
|
155
|
+
evalMode: 'paired',
|
|
156
|
+
}));
|
|
157
|
+
if (!kept) {
|
|
158
|
+
return { status: 'reverted', rounds: history, finalScore: baseline.total };
|
|
159
|
+
}
|
|
160
|
+
if (isPlateau(staleness)) {
|
|
161
|
+
return { status: 'plateau', rounds: history, finalScore: (await readText(skillPath)).length > 0 ? (score(await readText(skillPath), { measured: false })?.total ?? null) : null };
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
const finalText = await readText(skillPath);
|
|
165
|
+
return { status: 'completed', rounds: history, finalScore: score(finalText, { measured: false })?.total ?? null };
|
|
166
|
+
} catch (error) {
|
|
167
|
+
return { status: 'error', rounds: history, finalScore: null, error: error?.message ?? String(error) };
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async function restore(vcs, skillPath, before, version) {
|
|
172
|
+
if (vcs?.kind === 'git') {
|
|
173
|
+
try { await vcs.revert(); } catch { /* fall through to file restore */ }
|
|
174
|
+
// 兜底:git revert 失败时用内存里的基线覆盖,保证不留下未验证改动。
|
|
175
|
+
}
|
|
176
|
+
if (vcs?.kind === 'file' && version !== null && typeof vcs.restore === 'function') {
|
|
177
|
+
try { await vcs.restore(skillPath, version); return; } catch { /* fall through */ }
|
|
178
|
+
}
|
|
179
|
+
if (vcs?.kind === 'git') {
|
|
180
|
+
try { await vcs.writeBaseline?.(skillPath, before); } catch { /* last resort */ }
|
|
181
|
+
}
|
|
182
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 一次性子代理的「等完成 + 取最终文本」——单一份实现,judge 与生成器共用。
|
|
3
|
+
*
|
|
4
|
+
* 取证依据(@deepseek-ai/dsh-subagent/lib/types/assistant-output.js):
|
|
5
|
+
* 子代理的最终输出**不是** `activation.result`,而是
|
|
6
|
+
* `activation.handle.agent.session.snapshotEvents(activation.outputStart)` 中
|
|
7
|
+
* **最后一个非空 `assistant/message`** 的 `data.message.content`;
|
|
8
|
+
* 若无消息,回退到 `assistant/attempt|message` 的 `data.stream` 累积文本。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const END_EVENTS = new Set(['subagent/end', 'session/end']);
|
|
12
|
+
|
|
13
|
+
/** 从会话事件里提取最终 assistant 文本。 */
|
|
14
|
+
export function extractAssistantText(events) {
|
|
15
|
+
let message = null;
|
|
16
|
+
const streamPieces = [];
|
|
17
|
+
for (const event of Array.isArray(events) ? events : []) {
|
|
18
|
+
if (event?.type === 'assistant/message') {
|
|
19
|
+
const content = event?.data?.message?.content;
|
|
20
|
+
if (Array.isArray(content) && content.length > 0) message = content;
|
|
21
|
+
}
|
|
22
|
+
if (event?.type === 'assistant/message' || event?.type === 'assistant/attempt') {
|
|
23
|
+
const pieces = event?.data?.stream;
|
|
24
|
+
if (Array.isArray(pieces)) {
|
|
25
|
+
for (const piece of pieces) {
|
|
26
|
+
const text = typeof piece === 'string' ? piece : piece?.text;
|
|
27
|
+
if (typeof text === 'string' && text !== '') streamPieces.push(text);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
if (message === null) return streamPieces.join('');
|
|
33
|
+
return message
|
|
34
|
+
.map((block) => (typeof block === 'string' ? block : block?.text ?? ''))
|
|
35
|
+
.filter((text) => text !== '')
|
|
36
|
+
.join('\n');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* 等子代理结束并返回最终文本。
|
|
41
|
+
*
|
|
42
|
+
* 两条真实路径(按可用性选择):
|
|
43
|
+
* 1. `activation.result` 是执行结果 Promise(实测返回对象含 childId/result/
|
|
44
|
+
* dispose/messageId)——解析其 output/content/lastAssistantMessage;
|
|
45
|
+
* 2. 若只有 `activation.handle.agent.session`,则轮询 snapshotEvents
|
|
46
|
+
* (见 extractAssistantText 的事件规则)。
|
|
47
|
+
*
|
|
48
|
+
* @param {object} activation startActivation 返回
|
|
49
|
+
* @param {{timeoutMs?: number, pollMs?: number}} [options]
|
|
50
|
+
* @returns {Promise<string>}
|
|
51
|
+
*/
|
|
52
|
+
export async function awaitActivationText(activation, options = {}) {
|
|
53
|
+
const timeoutMs = options.timeoutMs ?? 120_000;
|
|
54
|
+
const pollMs = options.pollMs ?? 400;
|
|
55
|
+
const timeout = new Promise((resolve) => setTimeout(() => resolve(null), timeoutMs));
|
|
56
|
+
|
|
57
|
+
// 路径 1:result Promise(实测的主路径)。
|
|
58
|
+
const pending = activation?.result;
|
|
59
|
+
if (pending !== undefined && pending !== null && typeof pending.then === 'function') {
|
|
60
|
+
const settled = await Promise.race([Promise.resolve(pending).catch(() => null), timeout]);
|
|
61
|
+
const text = textOfResult(settled);
|
|
62
|
+
if (text !== '') return text;
|
|
63
|
+
// 空结果时继续走事件路径(某些 backend 只在会话事件里留输出)。
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// 路径 2:会话事件轮询。
|
|
67
|
+
const agent = activation?.handle?.agent;
|
|
68
|
+
const readEvents = () => {
|
|
69
|
+
try {
|
|
70
|
+
return agent?.session?.snapshotEvents?.(activation?.outputStart) ?? [];
|
|
71
|
+
} catch {
|
|
72
|
+
return [];
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
const deadline = Date.now() + timeoutMs;
|
|
76
|
+
const finished = (events) => events.some((event) => END_EVENTS.has(event?.type));
|
|
77
|
+
while (Date.now() < deadline) {
|
|
78
|
+
const events = readEvents();
|
|
79
|
+
if (finished(events) || (agent?.status === 'idle' && events.length > 0)) return extractAssistantText(events);
|
|
80
|
+
await new Promise((resolve) => setTimeout(resolve, pollMs));
|
|
81
|
+
}
|
|
82
|
+
return extractAssistantText(readEvents());
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** 把 activation.result 的值归一成文本(兼容 string / output 数组 / content)。 */
|
|
86
|
+
export function textOfResult(settled) {
|
|
87
|
+
if (settled === null || settled === undefined) return '';
|
|
88
|
+
if (typeof settled === 'string') return settled;
|
|
89
|
+
const candidates = [settled.output, settled.content, settled.lastAssistantMessage, settled.text];
|
|
90
|
+
for (const candidate of candidates) {
|
|
91
|
+
if (typeof candidate === 'string' && candidate !== '') return candidate;
|
|
92
|
+
if (Array.isArray(candidate)) {
|
|
93
|
+
const text = candidate
|
|
94
|
+
.map((part) => (typeof part === 'string' ? part : part?.text ?? part?.content ?? ''))
|
|
95
|
+
.filter((piece) => piece !== '')
|
|
96
|
+
.join('\n');
|
|
97
|
+
if (text !== '') return text;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return '';
|
|
101
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@suifei/dsh-ai-team",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.98",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "文渊阁 (Wenyuan Pavilion) — AI Team mode for DeepSeek Harness: concurrent projects, owned tasks, threads, inbox and an append-only team ledger",
|
|
6
6
|
"license": "MIT",
|
|
@@ -30,3 +30,18 @@ whenToUse: 所有 Agent(PMO/主理人/执行/验收)在规划、实现、验
|
|
|
30
30
|
- PMO/主理人:用复盘、头脑风暴、深度研究形成验收标准与 Task 草案,不把决策推给 Human;需要 Human 时交给 PMO 自动决策。
|
|
31
31
|
- 执行:先读核心纪律与结果定义;交付证据必须实测,不手填数字。
|
|
32
32
|
- 验收:独立复跑;只按 resultDefinition / QA checklist 判定;不共享执行者的 claim。
|
|
33
|
+
|
|
34
|
+
## 会议要求
|
|
35
|
+
|
|
36
|
+
请启动“正反极限论证器”。不要急着回答,也不要默认 Human 或 PMO 的问题已经定义正确。
|
|
37
|
+
第一步,用最完整、最准确的方式重新表述我真正想解决的问题,并指出其中可能存在的隐含假设。
|
|
38
|
+
第二步,分别建立两个最强版本的论证:【最强支持方】尽可能使用事实、逻辑、案例和因果关系证明我的当前想法成立;【最强反对方】同样以最有力的方式证明我的想法可能错误。禁止故意给任何一边安排弱论据。
|
|
39
|
+
第三步,比较双方真正的分歧点,找出最可能改变最终结论的3个关键变量。
|
|
40
|
+
第四步,只向我提出一个最值得回答的问题。等我回答后,再综合双方证据,明确给出当前判断、理由、最大风险、结论置信度以及下一步最值得采取的行动。
|
|
41
|
+
我的问题是:[用户填写,或者由 PMO 代填]。
|
|
42
|
+
|
|
43
|
+
## 结果定义
|
|
44
|
+
|
|
45
|
+
- **明确可量化**:结果必须能够被客观测量和验证。
|
|
46
|
+
- **与业务目标对齐**:结果应直接反映业务价值和用户满意度。
|
|
47
|
+
- **可追溯性**:所有结果都应有清晰的来源和记录,便于后续分析和优化。
|