@suifei/dsh-ai-team 0.3.86 → 0.3.90
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 +23 -0
- package/index.js +141 -5
- package/lib/skillopt/adopt-gate.js +90 -0
- package/lib/skillopt/gate-wiring.js +126 -0
- package/lib/skillopt/judge-runner.js +83 -0
- package/lib/skillopt/judge.js +106 -0
- package/lib/skillopt/optimize-wiring.js +108 -0
- package/lib/skillopt/optimizer.js +177 -0
- package/lib/skillopt/rubric.js +167 -0
- package/package.json +1 -1
- package/skills/ai-team-core/SKILL.md +15 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
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
|
+
|
|
14
|
+
## 0.3.89 - 2026-11-12
|
|
15
|
+
|
|
16
|
+
**完全对齐 darwin-skill v2.1(9 维 rubric + 独立 judge)**
|
|
17
|
+
|
|
18
|
+
- **9 维 rubric(`skillopt_rubric`)**:结构 59(Frontmatter 7 / 工作流 12 / 失败模式 12 / 检查点 6 / 具体性 18 / 资源 4)+ 效果 35(架构 12 / 实测 23)+ Meta 6(反例黑名单)——静态启发式评分带逐维证据;**绝对总分明确标注 TRIAGE-ONLY**(绝不作 keep/revert 依据),dim8 未实测时标注 dry-run。
|
|
19
|
+
- **独立 judge(`skillopt_judge`)**:paired 同-judge 比较 + A/B 随机化盲评 + 奇数 N(默认 3,可配 `skilloptJudgeVotes`)多数决(better≥worse→keep,含 tie;无有效票→inconclusive 不得 adopt);judge 是**一次性独立子代理**(`subagents.startActivation`),上下文干净,杜绝自评自改。
|
|
20
|
+
- **adopt 验证门**:`skillopt_adopt` 经 `wrapToolsWithAdoptGate` 包装——先读 staged 候选与 live 基线,跑独立 judge;revert/inconclusive/无法验证时**拒绝 adopt** 并给出理由(unverified adopt is refused),keep 才放行引擎。
|
|
21
|
+
- **根因修复**:插件 `inject` 增加 `tools`/`shell`——此前 shell 服务未就绪时 SkillOpt 整段静默跳过(diag 实测 `hasShell:false`);judge 的 `ensureParent` 改惰性引用(修复 TDZ `Cannot access before initialization`)。
|
|
22
|
+
- **工具输出协议修复**:`skillopt_rubric`/`skillopt_judge` 的 render 返回 content 数组(此前 `content.some is not a function`)。
|
|
23
|
+
- 测试:`test/darwin-alignment.test.js` 10 项(rubric 强弱对照/权重和 100、A/B 盲评与解析、多数决与平局、judge-runner 子代理注入、adopt 门 keep/revert/inconclusive/无法验证、只拦 adopt 不动其他工具)。
|
|
24
|
+
|
|
25
|
+
|
|
3
26
|
## 0.3.86 - 2026-11-12
|
|
4
27
|
|
|
5
28
|
- **技能进化链路可观测性**:health 新增 `runtime.services`(tools.register / shell / 已注册的 skillopt_* 工具清单);SkillOpt 注册条件不满足时记 `skillopt.skip.fail` 诊断——消除「静默未启用」的排查盲区(此前只能靠 diag 猜)。
|
package/index.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
import { homedir } from 'node:os';
|
|
12
12
|
import { join } from 'node:path';
|
|
13
13
|
import { fileURLToPath } from 'node:url';
|
|
14
|
-
import { readFileSync, writeFileSync } from 'node:fs';
|
|
14
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
15
15
|
import z from '@deepseek-ai/schemastery';
|
|
16
16
|
import { ProjectRuntime } from './lib/host/project-runtime.js';
|
|
17
17
|
import { ProjectRegistry } from './lib/host/project-registry.js';
|
|
@@ -25,6 +25,11 @@ import { formatSkillCatalog } from './lib/runtime/skill-catalog.js';
|
|
|
25
25
|
import { isSkillExcluded } from './lib/runtime/skill-policy.js';
|
|
26
26
|
import { installFileSkillProvider } from './lib/runtime/skill-provider.js';
|
|
27
27
|
import { apply as applySkillOpt } from './lib/vendor/skillopt/src/index.js';
|
|
28
|
+
import { createAdoptGate, wrapToolsWithAdoptGate } from './lib/skillopt/adopt-gate.js';
|
|
29
|
+
import { formatRubric, scoreSkillRubric } from './lib/skillopt/rubric.js';
|
|
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';
|
|
28
33
|
import { createMemberPermissionGuard } from './lib/host/permission-guard.js';
|
|
29
34
|
import { installFaultAdapter } from './lib/host/fault-adapter.js';
|
|
30
35
|
import { buildModelCatalog } from './lib/host/model-catalog.js';
|
|
@@ -39,9 +44,9 @@ import { createDiagLogger, defaultDiagDir } from './lib/diaglog.js';
|
|
|
39
44
|
export const name = 'ai-team';
|
|
40
45
|
|
|
41
46
|
/** The workbench only makes sense where the Web carrier exists. */
|
|
42
|
-
export const inject = ['webServer', 'permissionPresets', 'sandboxPolicy'];
|
|
47
|
+
export const inject = ['webServer', 'permissionPresets', 'sandboxPolicy', 'tools', 'shell'];
|
|
43
48
|
|
|
44
|
-
const VERSION = '0.3.
|
|
49
|
+
const VERSION = '0.3.90';
|
|
45
50
|
const HUMAN_ID = 'mem_human';
|
|
46
51
|
|
|
47
52
|
const SKILLOPT_BACKENDS = ['mock', 'claude', 'codex', 'copilot', 'cursor', 'pi', 'opencode', 'handoff', 'azure_openai'];
|
|
@@ -64,6 +69,8 @@ export const Config = z.object({
|
|
|
64
69
|
skilloptBackend: z.union(SKILLOPT_BACKENDS).default('mock'),
|
|
65
70
|
// per-call timeout for skillopt_* engine runs
|
|
66
71
|
skilloptTimeoutMs: z.number().step(1).min(10_000).max(600_000).default(120_000),
|
|
72
|
+
// Darwin paired judge:独立子代理票数,奇数 ≥3(接近平局可升 5)。
|
|
73
|
+
skilloptJudgeVotes: z.number().step(1).min(3).max(9).default(3),
|
|
67
74
|
});
|
|
68
75
|
|
|
69
76
|
function send(res, body, status = 200) {
|
|
@@ -758,10 +765,32 @@ export function apply(ctx, config = {}) {
|
|
|
758
765
|
console.warn('[ai-team] SkillOpt tools not registered:', { hasToolsRegister: typeof tools?.register === 'function', hasShell: Boolean(shell) });
|
|
759
766
|
}
|
|
760
767
|
if (tools?.register && shell) {
|
|
768
|
+
// Darwin validation gate(对齐 darwin-skill v2.1):adopt 之前必须
|
|
769
|
+
// 通过 paired 独立 judge 的多数决;绝对 rubric 分只做 triage。
|
|
770
|
+
const engineScript = fileURLToPath(new URL('./lib/vendor/skillopt/scripts/sleep.py', import.meta.url));
|
|
771
|
+
const readPair = makeReadPair({ shell, engineScript, diag });
|
|
772
|
+
const judge = makeJudge({
|
|
773
|
+
subagents: ctx.get('subagents'),
|
|
774
|
+
// 惰性解析:ensureParent 在 apply 之后才定义(const TDZ),
|
|
775
|
+
// judge 只在 adopt 时调用,此处不能立即取值。
|
|
776
|
+
ensureParent: () => ensureParent(),
|
|
777
|
+
providerName: () => providers[0],
|
|
778
|
+
votes: config.skilloptJudgeVotes ?? 3,
|
|
779
|
+
diag,
|
|
780
|
+
});
|
|
781
|
+
const adoptGate = createAdoptGate({
|
|
782
|
+
readPair,
|
|
783
|
+
judge,
|
|
784
|
+
diag: (line, extra) => diag.append({
|
|
785
|
+
ev: extra?.ev ?? 'skillopt.adoptgate',
|
|
786
|
+
message: line,
|
|
787
|
+
...(extra?.project === undefined ? {} : { project: extra.project }),
|
|
788
|
+
}),
|
|
789
|
+
});
|
|
761
790
|
// Backend/timeout come from the plugin Config (patch layer), so an
|
|
762
791
|
// operator can move the skillopt_* tools off the safe mock default.
|
|
763
792
|
disposeSkillOpt = applySkillOpt({
|
|
764
|
-
tools,
|
|
793
|
+
tools: wrapToolsWithAdoptGate(tools, adoptGate),
|
|
765
794
|
shell,
|
|
766
795
|
logger: console,
|
|
767
796
|
}, {
|
|
@@ -769,7 +798,114 @@ export function apply(ctx, config = {}) {
|
|
|
769
798
|
project: process.cwd(),
|
|
770
799
|
timeoutMs: config.skilloptTimeoutMs ?? 120_000,
|
|
771
800
|
}) ?? (() => {});
|
|
772
|
-
|
|
801
|
+
// 9 维 rubric(triage)与独立 judge(keep/revert)作为新工具暴露。
|
|
802
|
+
const rubricTool = tools.register({
|
|
803
|
+
name: 'skillopt_rubric',
|
|
804
|
+
description: 'Score a SKILL.md against the 9-dimension Darwin rubric (triage only — absolute scores must not be used for keep/revert).',
|
|
805
|
+
parameters: {
|
|
806
|
+
project: { type: 'string', description: 'Project directory (defaults to cwd)' },
|
|
807
|
+
skillPath: { type: 'string', description: 'Path to SKILL.md to score' },
|
|
808
|
+
dim8: { type: 'number', description: 'Measured effect score 1-10 (omit for dry-run)' },
|
|
809
|
+
measured: { type: 'boolean', description: 'Set when dim8 came from a real prompt run' },
|
|
810
|
+
},
|
|
811
|
+
// DSH 工具输出协议:render 必须返回 content 数组(与 vendored 一致)。
|
|
812
|
+
output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
|
|
813
|
+
async execute(args) {
|
|
814
|
+
const project = typeof args?.project === 'string' && args.project !== '' ? args.project : process.cwd();
|
|
815
|
+
const skillPath = typeof args?.skillPath === 'string' && args.skillPath !== ''
|
|
816
|
+
? args.skillPath
|
|
817
|
+
: join(project, 'SKILL.md');
|
|
818
|
+
if (!existsSync(skillPath)) return `[skillopt rubric] SKILL.md not found: ${skillPath}`;
|
|
819
|
+
const result = scoreSkillRubric(readFileSync(skillPath, 'utf8'), {
|
|
820
|
+
dim8: typeof args?.dim8 === 'number' ? args.dim8 : undefined,
|
|
821
|
+
measured: args?.measured === true,
|
|
822
|
+
});
|
|
823
|
+
diag.append({ ev: 'skillopt.rubric', project, skillPath, total: result.total, measured: result.evaluated });
|
|
824
|
+
return formatRubric(result);
|
|
825
|
+
},
|
|
826
|
+
});
|
|
827
|
+
const judgeTool = tools.register({
|
|
828
|
+
name: 'skillopt_judge',
|
|
829
|
+
description: 'Paired independent-judge verdict (N odd votes, majority) for before/after SKILL.md — the authoritative keep/revert signal.',
|
|
830
|
+
parameters: {
|
|
831
|
+
project: { type: 'string', description: 'Project directory' },
|
|
832
|
+
beforePath: { type: 'string', description: 'Baseline file path (default: current live SKILL.md)' },
|
|
833
|
+
afterPath: { type: 'string', description: 'Candidate file path (default: latest staged proposal)' },
|
|
834
|
+
},
|
|
835
|
+
// DSH 工具输出协议:render 必须返回 content 数组(与 vendored 一致)。
|
|
836
|
+
output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
|
|
837
|
+
async execute(args) {
|
|
838
|
+
const project = typeof args?.project === 'string' && args.project !== '' ? args.project : process.cwd();
|
|
839
|
+
let pair;
|
|
840
|
+
try {
|
|
841
|
+
pair = await readPair(project);
|
|
842
|
+
} catch (error) {
|
|
843
|
+
return `[skillopt judge] cannot read pair: ${error?.message ?? error}`;
|
|
844
|
+
}
|
|
845
|
+
const before = typeof args?.beforePath === 'string' && existsSync(args.beforePath) ? readFileSync(args.beforePath, 'utf8') : pair.before;
|
|
846
|
+
const after = typeof args?.afterPath === 'string' && existsSync(args.afterPath) ? readFileSync(args.afterPath, 'utf8') : pair.after;
|
|
847
|
+
const result = await judge({ before, after, projectDir: project });
|
|
848
|
+
const lines = result.votes.map((vote) => ` judge${vote.index}: ${vote.vote ?? 'invalid'} (margin ${vote.margin ?? '-'}) ${vote.reason}`);
|
|
849
|
+
return [
|
|
850
|
+
`[skillopt judge] verdict=${result.verdict} better=${result.better} worse=${result.worse} tie=${result.ties} valid=${result.valid}`,
|
|
851
|
+
...lines,
|
|
852
|
+
result.errors.length > 0 ? ` errors: ${result.errors.join('; ')}` : '',
|
|
853
|
+
].filter(Boolean).join('\n');
|
|
854
|
+
},
|
|
855
|
+
});
|
|
856
|
+
// Darwin Phase 2:自动 hill-climbing(诊断→生成→写入→judge→keep/revert)。
|
|
857
|
+
// 同一轮只改一个维度,版本化走干净 git 仓库,否则 .bak 备份。
|
|
858
|
+
const optimizeTool = tools.register({
|
|
859
|
+
name: 'skillopt_optimize',
|
|
860
|
+
description: 'Run the Darwin hill-climbing loop on one SKILL.md: weakest-dimension diagnosis, generated candidate, paired independent judge, keep/revert, results.tsv.',
|
|
861
|
+
parameters: {
|
|
862
|
+
project: { type: 'string', description: 'Project directory' },
|
|
863
|
+
skillPath: { type: 'string', description: 'Path to SKILL.md to optimize' },
|
|
864
|
+
rounds: { type: 'number', description: 'Max rounds (default 3)' },
|
|
865
|
+
},
|
|
866
|
+
output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
|
|
867
|
+
async execute(args) {
|
|
868
|
+
const project = typeof args?.project === 'string' && args.project !== '' ? args.project : process.cwd();
|
|
869
|
+
const skillPath = typeof args?.skillPath === 'string' && args.skillPath !== '' ? args.skillPath : join(project, 'SKILL.md');
|
|
870
|
+
if (!existsSync(skillPath)) return `[skillopt optimize] SKILL.md not found: ${skillPath}`;
|
|
871
|
+
const rounds = Number.isSafeInteger(args?.rounds) ? Math.max(1, Math.min(5, args.rounds)) : 3;
|
|
872
|
+
const vcs = await makeVcs({ shell, projectDir: project });
|
|
873
|
+
const result = await runOptimizeLoop({
|
|
874
|
+
skillPath,
|
|
875
|
+
rounds,
|
|
876
|
+
readText: async (path) => readFileSync(path, 'utf8'),
|
|
877
|
+
writeText: async (path, text) => writeFileSync(path, text, 'utf8'),
|
|
878
|
+
score: (text) => scoreSkillRubric(text, { measured: false }),
|
|
879
|
+
generate: makeGenerator({
|
|
880
|
+
subagents: ctx.get('subagents'),
|
|
881
|
+
ensureParent: () => ensureParent(),
|
|
882
|
+
providerName: () => providers[0],
|
|
883
|
+
cwd: project,
|
|
884
|
+
}),
|
|
885
|
+
judge: async ({ before, after }) => {
|
|
886
|
+
const judge = makeJudge({
|
|
887
|
+
subagents: ctx.get('subagents'),
|
|
888
|
+
ensureParent: () => ensureParent(),
|
|
889
|
+
providerName: () => providers[0],
|
|
890
|
+
votes: config.skilloptJudgeVotes ?? 3,
|
|
891
|
+
diag,
|
|
892
|
+
});
|
|
893
|
+
return judge({ before, after, projectDir: project });
|
|
894
|
+
},
|
|
895
|
+
vcs,
|
|
896
|
+
appendResult: makeResultAppender({ projectDir: project }),
|
|
897
|
+
});
|
|
898
|
+
diag.append({ ev: 'skillopt.optimize', project, skillPath, status: result.status, rounds: result.rounds.length, finalScore: result.finalScore, vcs: vcs.kind });
|
|
899
|
+
const lines = [
|
|
900
|
+
`[skillopt optimize] status=${result.status} rounds=${result.rounds.length} finalScore=${result.finalScore ?? '-'} vcs=${vcs.kind}`,
|
|
901
|
+
...(result.rounds ?? []).map((round) => ` r${round.round} ${round.dimension}: ${round.verdict} (${round.better}-${round.worse}) ${round.oldScore}→${round.newScore ?? '-'}${round.kept ? ' kept' : ' reverted'}`),
|
|
902
|
+
result.error ? ` error: ${result.error}` : '',
|
|
903
|
+
].filter(Boolean);
|
|
904
|
+
return lines.join('\n');
|
|
905
|
+
},
|
|
906
|
+
});
|
|
907
|
+
disposeSkillOpt = disposeExtra;
|
|
908
|
+
diag.append({ ev: 'skillopt.registered', backend: config.skilloptBackend ?? 'mock', timeoutMs: config.skilloptTimeoutMs ?? 120_000, adoptGate: true, judgeVotes: config.skilloptJudgeVotes ?? 3, optimize: true });
|
|
773
909
|
}
|
|
774
910
|
} catch (error) {
|
|
775
911
|
diag.append({ ev: 'skillopt.fail', message: error?.message ?? String(error) });
|
|
@@ -0,0 +1,90 @@
|
|
|
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
|
+
* @param {(line: string, extra?: object) => void} [deps.diag]
|
|
17
|
+
* @returns {(args: object, exec?: object) => Promise<string|null>} 返回拒绝原因;null = 放行
|
|
18
|
+
*/
|
|
19
|
+
export function createAdoptGate(deps) {
|
|
20
|
+
const { readPair, judge, diag } = deps;
|
|
21
|
+
return async (args) => {
|
|
22
|
+
const projectDir = typeof args?.project === 'string' && args.project.trim() !== '' ? args.project : null;
|
|
23
|
+
if (projectDir === null) return 'adopt gate: project directory is required';
|
|
24
|
+
let pair;
|
|
25
|
+
try {
|
|
26
|
+
pair = await readPair(projectDir);
|
|
27
|
+
} catch (error) {
|
|
28
|
+
const message = `adopt gate: cannot read proposal/baseline (${error?.message ?? error})`;
|
|
29
|
+
diag?.(message, { ev: 'skillopt.adoptgate.fail' });
|
|
30
|
+
return message;
|
|
31
|
+
}
|
|
32
|
+
if (pair?.after === null || pair?.after === undefined || pair?.before === null || pair?.before === undefined) {
|
|
33
|
+
const message = 'adopt gate: cannot verify — staged proposal or baseline SKILL.md is missing (unverified adopt is refused)';
|
|
34
|
+
diag?.(message, { ev: 'skillopt.adoptgate.fail', project: projectDir });
|
|
35
|
+
return message;
|
|
36
|
+
}
|
|
37
|
+
let result;
|
|
38
|
+
try {
|
|
39
|
+
result = await judge({ before: pair.before, after: pair.after, projectDir, skillPath: pair.skillPath ?? null });
|
|
40
|
+
} catch (error) {
|
|
41
|
+
const message = `adopt gate: judge unavailable (${error?.message ?? error}) — unverified adopt is refused`;
|
|
42
|
+
diag?.(message, { ev: 'skillopt.adoptgate.fail', project: projectDir });
|
|
43
|
+
return message;
|
|
44
|
+
}
|
|
45
|
+
diag?.('skillopt.adoptgate.decision', {
|
|
46
|
+
ev: 'skillopt.adoptgate',
|
|
47
|
+
project: projectDir,
|
|
48
|
+
verdict: result.verdict,
|
|
49
|
+
better: result.better,
|
|
50
|
+
worse: result.worse,
|
|
51
|
+
ties: result.ties,
|
|
52
|
+
valid: result.valid,
|
|
53
|
+
});
|
|
54
|
+
if (result.verdict === 'keep') return null;
|
|
55
|
+
const reasons = result.votes
|
|
56
|
+
.filter((vote) => vote.vote === 'worse')
|
|
57
|
+
.map((vote) => `judge ${vote.index}: ${vote.reason || 'worse'}`)
|
|
58
|
+
.join(' | ');
|
|
59
|
+
if (result.verdict === 'inconclusive') {
|
|
60
|
+
return `adopt gate: inconclusive judge votes (${result.errors.join('; ') || 'no valid votes'}) — refusing unverified adopt`;
|
|
61
|
+
}
|
|
62
|
+
return `adopt gate: paired judge rejected the change (${result.better} better / ${result.worse} worse / ${result.ties} tie; ${result.valid} valid votes)${reasons ? ` — ${reasons}` : ''}`;
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 包装 tools 服务,让 `skillopt_adopt` 的 execute 先过 adopt gate。
|
|
68
|
+
* @param {object} tools ctx.get('tools')
|
|
69
|
+
* @param {(args: object, exec?: object) => Promise<string|null>} gate
|
|
70
|
+
* @returns {object} 供 applySkillOpt 使用的 tools 代理
|
|
71
|
+
*/
|
|
72
|
+
export function wrapToolsWithAdoptGate(tools, gate) {
|
|
73
|
+
if (tools === null || tools === undefined || typeof tools.register !== 'function') return tools;
|
|
74
|
+
return {
|
|
75
|
+
...tools,
|
|
76
|
+
register(definition, options) {
|
|
77
|
+
if (definition?.name !== 'skillopt_adopt') return tools.register(definition, options);
|
|
78
|
+
const originalExecute = definition.execute;
|
|
79
|
+
const guarded = {
|
|
80
|
+
...definition,
|
|
81
|
+
async execute(args, exec) {
|
|
82
|
+
const refused = await gate(args, exec);
|
|
83
|
+
if (typeof refused === 'string' && refused !== '') return `[skillopt skillopt_adopt] ${refused}`;
|
|
84
|
+
return originalExecute.call(definition, args, exec);
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
return tools.register(guarded, options);
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SkillOpt adopt gate 的宿主接线:把「读候选/基线」和「独立 judge」落到
|
|
3
|
+
* DSH 服务上。与 adopt-gate.js(纯协议)分离,便于单测协议、集成测接线。
|
|
4
|
+
*
|
|
5
|
+
* baseline 取 live SKILL.md 当前内容:adopt 之前 live 文件就是改前版本
|
|
6
|
+
* (staging 只写候选项),因此不需要 git 历史即可对比。
|
|
7
|
+
*/
|
|
8
|
+
import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { judgePair } from './judge-runner.js';
|
|
11
|
+
|
|
12
|
+
/** 引号一个 argv 元素(Windows cmd 与 POSIX sh 通用单引号形式)。 */
|
|
13
|
+
export function quoteArgv(argv) {
|
|
14
|
+
const quote = (value) => {
|
|
15
|
+
const text = String(value);
|
|
16
|
+
if (text === '' || /[\s"'`$\\!&|<>()*?^%;]/.test(text)) return '"' + text.replace(/"/g, '\\"') + '"';
|
|
17
|
+
return text;
|
|
18
|
+
};
|
|
19
|
+
return argv.map(quote).join(' ');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** 跑引擎 CLI(status 等只读命令);返回 {exitCode, stdout, stderr}。 */
|
|
23
|
+
export async function runEngineCli(shell, args, options = {}) {
|
|
24
|
+
const request = {
|
|
25
|
+
command: quoteArgv(args),
|
|
26
|
+
timeoutMs: options.timeoutMs ?? 60_000,
|
|
27
|
+
signal: options.signal,
|
|
28
|
+
};
|
|
29
|
+
const spec = typeof shell?.resolve === 'function' ? shell.resolve(request) : request;
|
|
30
|
+
const exec = typeof shell?.execute === 'function'
|
|
31
|
+
? await shell.execute(spec)
|
|
32
|
+
: await shell.run(spec);
|
|
33
|
+
const result = typeof exec?.result === 'function' ? await exec.result() : exec;
|
|
34
|
+
const text = (value) => (typeof value === 'string' ? value : value?.text ?? '');
|
|
35
|
+
return {
|
|
36
|
+
exitCode: result?.exitCode ?? null,
|
|
37
|
+
stdout: text(result?.stdout),
|
|
38
|
+
stderr: text(result?.stderr),
|
|
39
|
+
timedOut: result?.timedOut === true,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* 构造 readPair:从引擎 status 找 latest staging,从 staging 目录读候选与基线。
|
|
45
|
+
* @param {{shell:object, engineScript:string, python?:string, diag?:object}} deps
|
|
46
|
+
* @returns {(projectDir: string) => Promise<{before:string, after:string, skillPath:string|null}>}
|
|
47
|
+
*/
|
|
48
|
+
export function makeReadPair(deps) {
|
|
49
|
+
const { shell, engineScript, python = 'python', diag } = deps;
|
|
50
|
+
return async (projectDir) => {
|
|
51
|
+
const status = await runEngineCli(shell, [python, engineScript, 'status', '--json', '--project', projectDir]);
|
|
52
|
+
if (status.timedOut) throw new Error('engine status timed out');
|
|
53
|
+
const raw = status.stdout.slice(status.stdout.indexOf('{'));
|
|
54
|
+
let payload;
|
|
55
|
+
try {
|
|
56
|
+
payload = JSON.parse(raw);
|
|
57
|
+
} catch {
|
|
58
|
+
throw new Error(`cannot parse engine status: ${(status.stderr || status.stdout).slice(0, 200)}`);
|
|
59
|
+
}
|
|
60
|
+
const stagingDir = payload?.latest_staging;
|
|
61
|
+
if (typeof stagingDir !== 'string' || stagingDir === '' || !existsSync(stagingDir)) {
|
|
62
|
+
throw new Error('no staged proposal (run skillopt_run first; latest_staging is empty)');
|
|
63
|
+
}
|
|
64
|
+
const names = readdirSync(stagingDir);
|
|
65
|
+
const markdown = names.filter((name) => name.toLowerCase().endsWith('.md'));
|
|
66
|
+
const manifests = names.filter((name) => name.toLowerCase().endsWith('.json'));
|
|
67
|
+
if (markdown.length === 0 || manifests.length === 0) {
|
|
68
|
+
throw new Error(`staging ${stagingDir} has no proposal/manifest pair (found: ${names.join(', ') || 'nothing'})`);
|
|
69
|
+
}
|
|
70
|
+
// manifest: 取含 live_skill_path 的第一行(字段名以引擎为准)。
|
|
71
|
+
let livePath = null;
|
|
72
|
+
for (const manifestName of manifests) {
|
|
73
|
+
try {
|
|
74
|
+
const manifest = JSON.parse(readFileSync(join(stagingDir, manifestName), 'utf8'));
|
|
75
|
+
const rows = Array.isArray(manifest) ? manifest : manifest?.skills ?? manifest?.proposals ?? [manifest];
|
|
76
|
+
const row = (Array.isArray(rows) ? rows : []).find((entry) => typeof entry?.live_skill_path === 'string');
|
|
77
|
+
if (row !== undefined) { livePath = row.live_skill_path; break; }
|
|
78
|
+
} catch { /* try next */ }
|
|
79
|
+
}
|
|
80
|
+
const after = readFileSync(join(stagingDir, markdown[0]), 'utf8');
|
|
81
|
+
if (livePath === null || !existsSync(livePath)) {
|
|
82
|
+
// 无基线时退回「候选内部基线」不可行——拒绝由 gate 处理。
|
|
83
|
+
throw new Error('staging manifest has no reachable live_skill_path; baseline unavailable');
|
|
84
|
+
}
|
|
85
|
+
const before = readFileSync(livePath, 'utf8');
|
|
86
|
+
diag?.append?.({ ev: 'skillopt.readpair', project: projectDir, stagingDir, livePath, bytesBefore: before.length, bytesAfter: after.length });
|
|
87
|
+
return { before, after, skillPath: livePath };
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 构造 judge 函数(供 adopt gate 用):惰性取 parent/provider,起独立子代理盲评。
|
|
93
|
+
* @param {object} deps
|
|
94
|
+
* @param {object} deps.subagents ctx.get('subagents')
|
|
95
|
+
* @param {() => Promise<{agent: object}>} deps.ensureParent
|
|
96
|
+
* @param {() => string} deps.providerName
|
|
97
|
+
* @param {number} [deps.votes]
|
|
98
|
+
* @param {object} [deps.diag]
|
|
99
|
+
*/
|
|
100
|
+
export function makeJudge(deps) {
|
|
101
|
+
const { subagents, ensureParent, providerName, votes, diag } = deps;
|
|
102
|
+
return async ({ before, after, projectDir }) => {
|
|
103
|
+
const parentInfo = await ensureParent();
|
|
104
|
+
const provider = providerName();
|
|
105
|
+
const result = await judgePair({
|
|
106
|
+
before,
|
|
107
|
+
after,
|
|
108
|
+
subagents,
|
|
109
|
+
parent: parentInfo?.agent,
|
|
110
|
+
provider,
|
|
111
|
+
cwd: projectDir,
|
|
112
|
+
votes,
|
|
113
|
+
});
|
|
114
|
+
diag?.append?.({
|
|
115
|
+
ev: 'skillopt.judge',
|
|
116
|
+
project: projectDir,
|
|
117
|
+
verdict: result.verdict,
|
|
118
|
+
better: result.better,
|
|
119
|
+
worse: result.worse,
|
|
120
|
+
ties: result.ties,
|
|
121
|
+
valid: result.valid,
|
|
122
|
+
errors: result.errors,
|
|
123
|
+
});
|
|
124
|
+
return result;
|
|
125
|
+
};
|
|
126
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 独立 judge 执行器:用 DSH 的 subagent 起**一次性评审子代理**(与 darwin
|
|
3
|
+
* 的「spawn 独立子 agent」同义),子代理上下文干净、不参与优化,天然杜绝
|
|
4
|
+
* 「自己改自己评」的乐观偏差。
|
|
5
|
+
*
|
|
6
|
+
* 每个 judge 只做一次 A/B 盲评(顺序随机化),输出一行 JSON;本模块负责
|
|
7
|
+
* 汇总成 paired 多数决 verdict。
|
|
8
|
+
*/
|
|
9
|
+
import { buildPairPrompt, decideByMajority, normalizeVoteCount, parseJudgeOutput, voteFromParsed } from './judge.js';
|
|
10
|
+
|
|
11
|
+
const JUDGE_TIMEOUT_MS = 120_000;
|
|
12
|
+
|
|
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
|
+
/**
|
|
27
|
+
* 起 N 个独立 judge 子代理做 paired 比较。
|
|
28
|
+
*
|
|
29
|
+
* @param {object} input
|
|
30
|
+
* @param {string} input.before 改前全文
|
|
31
|
+
* @param {string} input.after 改后全文
|
|
32
|
+
* @param {object} input.subagents ctx.get('subagents')
|
|
33
|
+
* @param {object} input.parent 父 Agent(插件 parentInfo.agent)
|
|
34
|
+
* @param {string} input.provider subagent provider 名
|
|
35
|
+
* @param {string} input.cwd judge 子代理工作目录
|
|
36
|
+
* @param {number} [input.votes] 奇数票数(默认 3,平局可升 5)
|
|
37
|
+
* @param {() => number} [input.random] 注入随机源(测试用;默认 Math.random)
|
|
38
|
+
* @returns {Promise<{verdict:'keep'|'revert'|'inconclusive', better:number, worse:number, ties:number, valid:number, votes:Array, errors:string[]}>}
|
|
39
|
+
*/
|
|
40
|
+
export async function judgePair(input) {
|
|
41
|
+
const {
|
|
42
|
+
before, after, subagents, parent, provider, cwd,
|
|
43
|
+
votes: requestedVotes, random = Math.random,
|
|
44
|
+
} = input;
|
|
45
|
+
if (typeof before !== 'string' || typeof after !== 'string') {
|
|
46
|
+
throw new TypeError('judgePair needs before/after text');
|
|
47
|
+
}
|
|
48
|
+
if (typeof subagents?.startActivation !== 'function' || parent === undefined) {
|
|
49
|
+
throw new Error('judge unavailable: subagent service or parent agent missing');
|
|
50
|
+
}
|
|
51
|
+
const votes = normalizeVoteCount(requestedVotes);
|
|
52
|
+
const rows = [];
|
|
53
|
+
const errors = [];
|
|
54
|
+
for (let index = 0; index < votes; index++) {
|
|
55
|
+
const order = random() < 0.5 ? 'ab' : 'ba';
|
|
56
|
+
const { prompt, mapping } = buildPairPrompt({ before, after, order });
|
|
57
|
+
let activation = null;
|
|
58
|
+
try {
|
|
59
|
+
activation = await subagents.startActivation({
|
|
60
|
+
provider,
|
|
61
|
+
label: `skillopt-judge-${index + 1}`,
|
|
62
|
+
request: { cwd, prompt: [{ type: 'text', text: prompt }], parent },
|
|
63
|
+
delivery: 'parent',
|
|
64
|
+
});
|
|
65
|
+
const result = await Promise.race([
|
|
66
|
+
Promise.resolve(activation?.result),
|
|
67
|
+
new Promise((resolve) => setTimeout(() => resolve(null), JUDGE_TIMEOUT_MS)),
|
|
68
|
+
]);
|
|
69
|
+
const text = outputText(result?.output ?? result ?? '');
|
|
70
|
+
const parsed = parseJudgeOutput(text);
|
|
71
|
+
const vote = voteFromParsed(parsed === null ? null : { ...parsed, aIsAfter: mapping.aIsAfter });
|
|
72
|
+
if (vote === null) errors.push(`judge ${index + 1}: unparseable output`);
|
|
73
|
+
rows.push({ index: index + 1, order, vote, reason: parsed?.reason ?? '', margin: parsed?.margin ?? null });
|
|
74
|
+
} catch (error) {
|
|
75
|
+
errors.push(`judge ${index + 1}: ${error?.message ?? String(error)}`);
|
|
76
|
+
rows.push({ index: index + 1, order, vote: null, reason: '', margin: null });
|
|
77
|
+
} finally {
|
|
78
|
+
try { await activation?.dispose?.(); } catch { /* already gone */ }
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const decision = decideByMajority(rows.map((row) => row.vote));
|
|
82
|
+
return { ...decision, votes: rows, errors };
|
|
83
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Darwin Skill 2.1 的 keep/revert 判据:**paired 同-judge 比较 + 奇数 N 多数决**。
|
|
3
|
+
*
|
|
4
|
+
* 为什么不比绝对分数:LLM judge 的绝对分住在「文字 × 该 judge 当下的标准尺」
|
|
5
|
+
* 里,不是文字属性——同一份未改文字换 judge 可摆 ±8,保守编辑的真实增益
|
|
6
|
+
* (+3~8) 会被换尺噪音淹没(darwin 实测 false-revert 来源)。paired 让同一个
|
|
7
|
+
* judge 在一次调用内读两版,用同一把不准的尺量两版,比较时误差相减抵销
|
|
8
|
+
* (within-judge cancellation)。
|
|
9
|
+
*
|
|
10
|
+
* 本模块只含协议与纯函数:A/B 随机化、prompt 构造、多数决、tie/margin 聚合。
|
|
11
|
+
* 真正的 judge 是**独立子代理**(不在优化器上下文里自评自改)——由调用方注入。
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** 三次调用(奇数 N)的开销上限:N 必须是奇数,3 为默认,接近平局升 5。 */
|
|
15
|
+
export const DEFAULT_JUDGE_VOTES = 3;
|
|
16
|
+
|
|
17
|
+
const VERDICTS = new Set(['better', 'worse', 'tie']);
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* 盲评 prompt:不告诉 judge 哪版是"新版本",只看两版与 rubric 准则。
|
|
21
|
+
* @param {{before: string, after: string, order: 'ab'|'ba'}} input
|
|
22
|
+
* @returns {{prompt: string, mapping: {aIsAfter: boolean}}}
|
|
23
|
+
*/
|
|
24
|
+
export function buildPairPrompt({ before, after, order }) {
|
|
25
|
+
const aIsAfter = order === 'ba';
|
|
26
|
+
const versionA = aIsAfter ? after : before;
|
|
27
|
+
const versionB = aIsAfter ? before : after;
|
|
28
|
+
const prompt = [
|
|
29
|
+
'你是独立的技能质量评审(judge)。只做比较,不要改写任何文件。',
|
|
30
|
+
'',
|
|
31
|
+
'## 评估准则(Darwin 9 维 rubric)',
|
|
32
|
+
'结构:1 Frontmatter质量 7 · 2 工作流清晰度 12 · 3 失败模式编码 12 · 4 检查点设计 6 · 5 可执行具体性 18 · 6 资源整合度 4',
|
|
33
|
+
'效果:7 整体架构 12 · 8 实测表现 23',
|
|
34
|
+
'Meta:9 反例与黑名单 6',
|
|
35
|
+
'注意:明确写出失败分支(如果 X 失败 → Y)、显性检查点(🔴/STOP/CHECKPOINT)、具体参数与示例、反例清单者更优;',
|
|
36
|
+
'软化措辞(建议/可以考虑/根据情况/灵活把握/视情况而定)与空话(说白了/换句话说/首先其次/综上所述)是减分项。',
|
|
37
|
+
'',
|
|
38
|
+
'## 版本 A',
|
|
39
|
+
versionA,
|
|
40
|
+
'',
|
|
41
|
+
'## 版本 B',
|
|
42
|
+
versionB,
|
|
43
|
+
'',
|
|
44
|
+
'只输出一行 JSON:{"better":"A"|"B"|"tie","margin":"clear"|"slight","reason":"一句话理由"}',
|
|
45
|
+
].join('\n');
|
|
46
|
+
return { prompt, mapping: { aIsAfter } };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 解析 judge 输出:容忍代码围栏与前后噪声,只认 better/margin/reason。
|
|
51
|
+
* @param {string} output
|
|
52
|
+
* @returns {{better: 'A'|'B'|'tie', margin: 'clear'|'slight', reason: string} | null}
|
|
53
|
+
*/
|
|
54
|
+
export function parseJudgeOutput(output) {
|
|
55
|
+
const text = typeof output === 'string' ? output : '';
|
|
56
|
+
const match = text.match(/\{[\s\S]*?"better"[\s\S]*?\}/);
|
|
57
|
+
if (match === null) return null;
|
|
58
|
+
try {
|
|
59
|
+
const row = JSON.parse(match[0]);
|
|
60
|
+
if (row?.better !== 'A' && row?.better !== 'B' && row?.better !== 'tie') return null;
|
|
61
|
+
return {
|
|
62
|
+
better: row.better,
|
|
63
|
+
margin: row.margin === 'clear' ? 'clear' : 'slight',
|
|
64
|
+
reason: typeof row.reason === 'string' ? row.reason.slice(0, 300) : '',
|
|
65
|
+
};
|
|
66
|
+
} catch {
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* 把一次 judge 的输出转成「改后是否不差」的投票(keep 的依据)。
|
|
73
|
+
* @param {{better:string, margin:string, aIsAfter:boolean}|null} parsed
|
|
74
|
+
* @returns {'better'|'worse'|'tie'|null}
|
|
75
|
+
*/
|
|
76
|
+
export function voteFromParsed(parsed) {
|
|
77
|
+
if (parsed === null || parsed === undefined) return null;
|
|
78
|
+
if (parsed.better === 'tie') return 'tie';
|
|
79
|
+
const afterIsA = parsed.aIsAfter === true;
|
|
80
|
+
const afterWon = (parsed.better === 'A' && afterIsA) || (parsed.better === 'B' && !afterIsA);
|
|
81
|
+
return afterWon ? 'better' : 'worse';
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 多数决:keep 当且仅当 better ≥ worse(含 tie)——与 darwin Phase 2 Step 5 一致。
|
|
86
|
+
* 无效投票(null)不计数;全部无效时判 'inconclusive'(不得据此 adopt)。
|
|
87
|
+
* @param {Array<'better'|'worse'|'tie'|null>} votes
|
|
88
|
+
* @returns {{verdict: 'keep'|'revert'|'inconclusive', better:number, worse:number, ties:number, valid:number}}
|
|
89
|
+
*/
|
|
90
|
+
export function decideByMajority(votes) {
|
|
91
|
+
const valid = votes.filter((vote) => vote === 'better' || vote === 'worse' || vote === 'tie');
|
|
92
|
+
const better = valid.filter((vote) => vote === 'better').length;
|
|
93
|
+
const worse = valid.filter((vote) => vote === 'worse').length;
|
|
94
|
+
const ties = valid.filter((vote) => vote === 'tie').length;
|
|
95
|
+
if (valid.length === 0) return { verdict: 'inconclusive', better, worse, ties, valid: 0 };
|
|
96
|
+
return { verdict: better >= worse ? 'keep' : 'revert', better, worse, ties, valid: valid.length };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** 校验投票数:奇数且 ≥3(close call 可升 5)。 */
|
|
100
|
+
export function normalizeVoteCount(count) {
|
|
101
|
+
const value = Number.isSafeInteger(count) ? count : DEFAULT_JUDGE_VOTES;
|
|
102
|
+
if (value < 3) return 3;
|
|
103
|
+
return value % 2 === 1 ? value : value + 1;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export { VERDICTS };
|
|
@@ -0,0 +1,108 @@
|
|
|
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
|
+
|
|
9
|
+
/** 项目是否为干净 git 仓库(决定 git 棘轮还是文件备份)。 */
|
|
10
|
+
async function isCleanGitRepo(shell, cwd) {
|
|
11
|
+
const inside = await runEngineCli(shell, ['git', '-C', cwd, 'rev-parse', '--is-inside-work-tree']).catch(() => null);
|
|
12
|
+
if (inside?.exitCode !== 0 || !/true/.test(inside?.stdout ?? '')) return false;
|
|
13
|
+
const status = await runEngineCli(shell, ['git', '-C', cwd, 'status', '--porcelain']).catch(() => null);
|
|
14
|
+
return status?.exitCode === 0 && (status.stdout ?? '').trim() === '';
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @param {{shell:object, projectDir:string, now?:()=>number}} deps
|
|
19
|
+
* @returns {Promise<object>} vcs 适配器
|
|
20
|
+
*/
|
|
21
|
+
export async function makeVcs({ shell, projectDir, now = () => Date.now() }) {
|
|
22
|
+
const git = await isCleanGitRepo(shell, projectDir);
|
|
23
|
+
if (git) {
|
|
24
|
+
const commit = async (message) => {
|
|
25
|
+
const add = await runEngineCli(shell, ['git', '-C', projectDir, 'add', '-A']);
|
|
26
|
+
if (add.exitCode !== 0) throw new Error(`git add failed: ${add.stderr}`);
|
|
27
|
+
const done = await runEngineCli(shell, ['git', '-C', projectDir, 'commit', '-m', message, '--no-verify']);
|
|
28
|
+
if (done.exitCode !== 0) throw new Error(`git commit failed: ${done.stderr}`);
|
|
29
|
+
const head = await runEngineCli(shell, ['git', '-C', projectDir, 'rev-parse', '--short', 'HEAD']);
|
|
30
|
+
return (head.stdout ?? '').trim() || null;
|
|
31
|
+
};
|
|
32
|
+
return {
|
|
33
|
+
kind: 'git',
|
|
34
|
+
commit,
|
|
35
|
+
// keep 时无需额外动作:commit 已留下保留版本。
|
|
36
|
+
commitKept: async () => {},
|
|
37
|
+
revert: async () => {
|
|
38
|
+
const done = await runEngineCli(shell, ['git', '-C', projectDir, 'revert', 'HEAD', '--no-edit']);
|
|
39
|
+
if (done.exitCode !== 0) throw new Error(`git revert failed: ${done.stderr}`);
|
|
40
|
+
},
|
|
41
|
+
writeBaseline: async (path, text) => { writeFileSync(path, text, 'utf8'); },
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
const backupDir = join(projectDir, '.skillopt-sleep', 'backups');
|
|
45
|
+
mkdirSync(backupDir, { recursive: true });
|
|
46
|
+
return {
|
|
47
|
+
kind: 'file',
|
|
48
|
+
backup: async (path, text) => {
|
|
49
|
+
const stamp = new Date(now()).toISOString().replace(/[:.]/g, '-');
|
|
50
|
+
const target = join(backupDir, `${path.split(/[\\/]/).pop()}.${stamp}.bak`);
|
|
51
|
+
writeFileSync(target, text, 'utf8');
|
|
52
|
+
return target;
|
|
53
|
+
},
|
|
54
|
+
restore: async (path, backupPath) => {
|
|
55
|
+
if (!existsSync(backupPath)) throw new Error(`backup missing: ${backupPath}`);
|
|
56
|
+
copyFileSync(backupPath, path);
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 独立生成器:一次性子代理按 rubric 短板改进,只输出完整新文件。 */
|
|
62
|
+
export function makeGenerator({ subagents, ensureParent, providerName, cwd }) {
|
|
63
|
+
return async ({ skillPath, before, dimension, round }) => {
|
|
64
|
+
const parentInfo = await ensureParent();
|
|
65
|
+
const provider = providerName();
|
|
66
|
+
const prompt = [
|
|
67
|
+
'你是技能改进器。只输出改进后的完整 SKILL.md 内容(不要解释、不要代码围栏)。',
|
|
68
|
+
`目标维度:dim${dimension.id} ${dimension.name}(当前 ${dimension.score}/10,权重 ${dimension.weight})。`,
|
|
69
|
+
'硬约束:不得改变技能的核心用途;只解决该维度;不得删掉已有的失败分支/检查点/反例清单;',
|
|
70
|
+
'不得加长到原文 150% 以上;不得引入软化措辞(建议/可以考虑/根据情况/灵活把握/视情况而定)。',
|
|
71
|
+
`这是第 ${round} 轮。`,
|
|
72
|
+
'',
|
|
73
|
+
'## 原文',
|
|
74
|
+
before,
|
|
75
|
+
].join('\n');
|
|
76
|
+
const activation = await subagents.startActivation({
|
|
77
|
+
provider,
|
|
78
|
+
label: `skillopt-optimize-${round}`,
|
|
79
|
+
request: { cwd, prompt: [{ type: 'text', text: prompt }], parent: parentInfo?.agent },
|
|
80
|
+
delivery: 'parent',
|
|
81
|
+
});
|
|
82
|
+
try {
|
|
83
|
+
const result = await activation?.result;
|
|
84
|
+
const raw = Array.isArray(result?.output)
|
|
85
|
+
? result.output.map((part) => (typeof part === 'string' ? part : part?.text ?? '')).join('\n')
|
|
86
|
+
: String(result?.output ?? '');
|
|
87
|
+
// 去掉可能包裹的 ```markdown 围栏。
|
|
88
|
+
const fenced = raw.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```/);
|
|
89
|
+
return fenced !== null ? fenced[1] : raw.trim();
|
|
90
|
+
} finally {
|
|
91
|
+
try { await activation?.dispose?.(); } catch { /* already gone */ }
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** results.tsv 追加(表头自动补)。 */
|
|
97
|
+
export function makeResultAppender({ projectDir }) {
|
|
98
|
+
const dir = join(projectDir, '.skillopt-sleep');
|
|
99
|
+
const path = join(dir, 'results.tsv');
|
|
100
|
+
return async (line) => {
|
|
101
|
+
mkdirSync(dir, { recursive: true });
|
|
102
|
+
const header = ['timestamp', 'commit', 'skill', 'old_score', 'new_score', 'status', 'dimension', 'note', 'eval_mode'].join('\t');
|
|
103
|
+
const prefix = existsSync(path) && readFileSync(path, 'utf8').includes('eval_mode') ? '' : header + '\n';
|
|
104
|
+
writeFileSync(path, prefix + line + '\n', { encoding: 'utf8', flag: 'a' });
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export { quoteArgv };
|
|
@@ -0,0 +1,177 @@
|
|
|
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
|
+
/** 最大加权短板(weight × (10 - score) / 10;同分时取原始分更低者)。 */
|
|
22
|
+
export function weakestDimension(rubric) {
|
|
23
|
+
const scored = (rubric?.dimensions ?? []).filter((dimension) => Number.isFinite(dimension?.score));
|
|
24
|
+
if (scored.length === 0) return null;
|
|
25
|
+
return scored.reduce((worst, dimension) => {
|
|
26
|
+
const gap = dimension.weight * (10 - dimension.score) / 10;
|
|
27
|
+
const worstGap = worst.weight * (10 - worst.score) / 10;
|
|
28
|
+
if (gap > worstGap) return dimension;
|
|
29
|
+
if (gap === worstGap && dimension.score < worst.score) return dimension;
|
|
30
|
+
return worst;
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 触顶判据:连续 2 轮 judge 的 margin 全为 slight/tie。 */
|
|
35
|
+
export function isPlateau(recentMargins) {
|
|
36
|
+
const lastTwo = recentMargins.slice(-2);
|
|
37
|
+
return lastTwo.length === 2 && lastTwo.every((row) => row.every((margin) => margin === 'slight' || margin === 'tie'));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 一轮候选的静态校验:不得超体积上限、必须真的变了。 */
|
|
41
|
+
export function validateCandidate({ before, after }) {
|
|
42
|
+
if (typeof after !== 'string' || after.trim() === '') return { ok: false, reason: 'generator returned an empty candidate' };
|
|
43
|
+
if (after === before) return { ok: false, reason: 'generator returned an unchanged candidate' };
|
|
44
|
+
if (after.length > before.length * MAX_GROWTH) {
|
|
45
|
+
return { ok: false, reason: `candidate exceeds 150% of the original size (${before.length} -> ${after.length}); trim before judging` };
|
|
46
|
+
}
|
|
47
|
+
return { ok: true, reason: '' };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** results.tsv 行(9 列,与 darwin 格式一致)。 */
|
|
51
|
+
export function resultRow({ timestamp, commit, skill, oldScore, newScore, status, dimension, note, evalMode }) {
|
|
52
|
+
return [timestamp, commit, skill, oldScore, newScore, status, dimension, note, evalMode].join('\t');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export const RESULTS_HEADER = ['timestamp', 'commit', 'skill', 'old_score', 'new_score', 'status', 'dimension', 'note', 'eval_mode'].join('\t');
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 跑一个 skill 的优化循环。
|
|
59
|
+
*
|
|
60
|
+
* @param {object} input
|
|
61
|
+
* @param {string} input.skillPath 目标 SKILL.md 绝对路径
|
|
62
|
+
* @param {string} [input.skillName] 记录用名字(默认取文件名所在目录名)
|
|
63
|
+
* @param {number} [input.rounds] MAX_ROUNDS(默认 3)
|
|
64
|
+
* @param {(path:string)=>Promise<string>} input.readText
|
|
65
|
+
* @param {(path:string, text:string)=>Promise<void>} input.writeText
|
|
66
|
+
* @param {(text:string, options:{measured:boolean})=>object} input.score 同步 rubric 评分
|
|
67
|
+
* @param {(input:{skillPath:string, before:string, dimension:object, round:number})=>Promise<string>} input.generate 生成候选全文
|
|
68
|
+
* @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
|
|
69
|
+
* @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>}`
|
|
70
|
+
* @param {(line:string)=>Promise<void>} [input.appendResult] 追加 results.tsv(含表头由实现方保证)
|
|
71
|
+
* @param {() => number} [input.now]
|
|
72
|
+
* @returns {Promise<{status:'completed'|'plateau'|'reverted'|'error', rounds:Array, finalScore:number|null, error?:string}>}
|
|
73
|
+
*/
|
|
74
|
+
export async function runOptimizeLoop(input) {
|
|
75
|
+
const {
|
|
76
|
+
skillPath, skillName, rounds = DEFAULT_ROUNDS, readText, writeText, score, generate, judge, vcs,
|
|
77
|
+
appendResult, now = () => Date.now(),
|
|
78
|
+
} = input;
|
|
79
|
+
const name = skillName ?? skillPath.split(/[\\/]/).slice(-2, -1)[0] ?? skillPath;
|
|
80
|
+
const history = [];
|
|
81
|
+
const staleness = [];
|
|
82
|
+
const stamp = () => new Date(now()).toISOString().slice(0, 19);
|
|
83
|
+
try {
|
|
84
|
+
for (let round = 1; round <= rounds; round++) {
|
|
85
|
+
const before = await readText(skillPath);
|
|
86
|
+
const baseline = score(before, { measured: false });
|
|
87
|
+
const dimension = weakestDimension(baseline);
|
|
88
|
+
if (dimension === null) {
|
|
89
|
+
await appendResult?.(resultRow({ timestamp: stamp(), commit: '-', skill: name, oldScore: String(baseline?.total ?? '-'), newScore: '-', status: 'error', dimension: '-', note: 'rubric produced no scorable dimensions', evalMode: 'structural' }));
|
|
90
|
+
return { status: 'error', rounds: history, finalScore: baseline?.total ?? null, error: 'no scorable dimensions' };
|
|
91
|
+
}
|
|
92
|
+
let candidate;
|
|
93
|
+
try {
|
|
94
|
+
candidate = await generate({ skillPath, before, dimension, round });
|
|
95
|
+
} catch (error) {
|
|
96
|
+
return { status: 'error', rounds: history, finalScore: baseline?.total ?? null, error: `generator failed: ${error?.message ?? error}` };
|
|
97
|
+
}
|
|
98
|
+
const validation = validateCandidate({ before, after: candidate });
|
|
99
|
+
if (!validation.ok) {
|
|
100
|
+
await appendResult?.(resultRow({ timestamp: stamp(), commit: '-', skill: name, oldScore: String(baseline.total), newScore: '-', status: 'skipped', dimension: dimension.name, note: validation.reason, evalMode: 'structural' }));
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
// 版本化:先记录基线,再写入候选。
|
|
104
|
+
let version = null;
|
|
105
|
+
if (vcs?.kind === 'git') {
|
|
106
|
+
try { version = await vcs.commit(`optimize ${name}: address dim${dimension.id} ${dimension.name}`); }
|
|
107
|
+
catch { version = null; }
|
|
108
|
+
} else if (vcs?.kind === 'file') {
|
|
109
|
+
version = await vcs.backup(skillPath, before);
|
|
110
|
+
}
|
|
111
|
+
await writeText(skillPath, candidate);
|
|
112
|
+
let verdict;
|
|
113
|
+
try {
|
|
114
|
+
verdict = await judge({ before, after: candidate, skillPath });
|
|
115
|
+
} catch (error) {
|
|
116
|
+
// judge 不可用:回滚,绝不保留未验证改动。
|
|
117
|
+
await restore(vcs, skillPath, before, version);
|
|
118
|
+
return { status: 'error', rounds: history, finalScore: baseline.total, error: `judge unavailable: ${error?.message ?? error}` };
|
|
119
|
+
}
|
|
120
|
+
const margins = (verdict.votes ?? []).map((vote) => vote.margin ?? 'slight');
|
|
121
|
+
staleness.push(margins);
|
|
122
|
+
const kept = verdict.verdict === 'keep';
|
|
123
|
+
if (!kept) {
|
|
124
|
+
await restore(vcs, skillPath, before, version);
|
|
125
|
+
} else if (vcs?.kind === 'git' && version !== null && typeof vcs.commitKept === 'function') {
|
|
126
|
+
await vcs.commitKept(version);
|
|
127
|
+
}
|
|
128
|
+
const afterScore = kept ? score(candidate, { measured: false }) : baseline;
|
|
129
|
+
history.push({
|
|
130
|
+
round,
|
|
131
|
+
dimension: `dim${dimension.id} ${dimension.name}`,
|
|
132
|
+
verdict: verdict.verdict,
|
|
133
|
+
better: verdict.better,
|
|
134
|
+
worse: verdict.worse,
|
|
135
|
+
ties: verdict.ties,
|
|
136
|
+
margins,
|
|
137
|
+
oldScore: baseline.total,
|
|
138
|
+
newScore: afterScore?.total ?? null,
|
|
139
|
+
kept,
|
|
140
|
+
});
|
|
141
|
+
await appendResult?.(resultRow({
|
|
142
|
+
timestamp: stamp(),
|
|
143
|
+
commit: version ?? '-',
|
|
144
|
+
skill: name,
|
|
145
|
+
oldScore: String(baseline.total),
|
|
146
|
+
newScore: String(afterScore?.total ?? '-'),
|
|
147
|
+
status: kept ? 'keep' : 'revert',
|
|
148
|
+
dimension: `dim${dimension.id}`,
|
|
149
|
+
note: `${verdict.better}-${verdict.worse} ${verdict.verdict}${verdict.errors?.length ? ` (${verdict.errors.join('; ')})` : ''}`,
|
|
150
|
+
evalMode: 'paired',
|
|
151
|
+
}));
|
|
152
|
+
if (!kept) {
|
|
153
|
+
return { status: 'reverted', rounds: history, finalScore: baseline.total };
|
|
154
|
+
}
|
|
155
|
+
if (isPlateau(staleness)) {
|
|
156
|
+
return { status: 'plateau', rounds: history, finalScore: (await readText(skillPath)).length > 0 ? (score(await readText(skillPath), { measured: false })?.total ?? null) : null };
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
const finalText = await readText(skillPath);
|
|
160
|
+
return { status: 'completed', rounds: history, finalScore: score(finalText, { measured: false })?.total ?? null };
|
|
161
|
+
} catch (error) {
|
|
162
|
+
return { status: 'error', rounds: history, finalScore: null, error: error?.message ?? String(error) };
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function restore(vcs, skillPath, before, version) {
|
|
167
|
+
if (vcs?.kind === 'git') {
|
|
168
|
+
try { await vcs.revert(); } catch { /* fall through to file restore */ }
|
|
169
|
+
// 兜底:git revert 失败时用内存里的基线覆盖,保证不留下未验证改动。
|
|
170
|
+
}
|
|
171
|
+
if (vcs?.kind === 'file' && version !== null && typeof vcs.restore === 'function') {
|
|
172
|
+
try { await vcs.restore(skillPath, version); return; } catch { /* fall through */ }
|
|
173
|
+
}
|
|
174
|
+
if (vcs?.kind === 'git') {
|
|
175
|
+
try { await vcs.writeBaseline?.(skillPath, before); } catch { /* last resort */ }
|
|
176
|
+
}
|
|
177
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Darwin Skill 9 维 rubric(对齐 alchaincyf/darwin-skill v2.1 的权威定义):
|
|
3
|
+
*
|
|
4
|
+
* 结构维度(59):1 Frontmatter 7 / 2 工作流清晰度 12 / 3 失败模式编码 12 /
|
|
5
|
+
* 4 检查点设计 6 / 5 可执行具体性 18 / 6 资源整合度 4
|
|
6
|
+
* 效果维度(35):7 整体架构 12 / 8 实测表现 23
|
|
7
|
+
* Meta-skill(6):9 反例与黑名单 6
|
|
8
|
+
*
|
|
9
|
+
* 评分规则:维度 1-7、9 打 1-10 分 × 权重;维度 8(实测表现)由调用方注入
|
|
10
|
+
* (跑测试 prompt)或按干跑打分。总分 = Σ(维度分 × 权重) / 10,满分 100。
|
|
11
|
+
*
|
|
12
|
+
* ⚠️ 绝对总分只用于 triage(先改哪支最弱),**绝不用于 keep/revert**——
|
|
13
|
+
* LLM judge 换尺 ±8 噪音会淹没保守编辑的真实增益。keep/revert 一律走
|
|
14
|
+
* judge.js 的 paired 同-judge 多数决。
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
export const NINE_DIMENSIONS = Object.freeze([
|
|
18
|
+
{ id: 1, name: 'Frontmatter质量', weight: 7, group: 'structure' },
|
|
19
|
+
{ id: 2, name: '工作流清晰度', weight: 12, group: 'structure' },
|
|
20
|
+
{ id: 3, name: '失败模式编码', weight: 12, group: 'structure' },
|
|
21
|
+
{ id: 4, name: '检查点设计', weight: 6, group: 'structure' },
|
|
22
|
+
{ id: 5, name: '可执行具体性', weight: 18, group: 'structure' },
|
|
23
|
+
{ id: 6, name: '资源整合度', weight: 4, group: 'structure' },
|
|
24
|
+
{ id: 7, name: '整体架构', weight: 12, group: 'effect' },
|
|
25
|
+
{ id: 8, name: '实测表现', weight: 23, group: 'effect' },
|
|
26
|
+
{ id: 9, name: '反例与黑名单', weight: 6, group: 'meta' },
|
|
27
|
+
]);
|
|
28
|
+
|
|
29
|
+
/** 软化措辞(dim5 扣分项):出现 ≥3 处扣 ≥3 分。 */
|
|
30
|
+
const SOFT_WORDS = ['建议', '可以考虑', '根据情况', '灵活把握', '视情况而定', '酌情', '尽量'];
|
|
31
|
+
/** AI 腔/废话词(dim7 扣分项):出现一处扣 1 分。 */
|
|
32
|
+
const FILLER_WORDS = ['说白了', '换句话说', '首先其次', '综上所述', '总而言之'];
|
|
33
|
+
/** 失败模式句式(dim3):显式「如果 X → Y」分支,含缺失/为空/超时等触发条件。 */
|
|
34
|
+
const FAILURE_PATTERNS = [
|
|
35
|
+
/如果[^\n]{0,60}(失败|缺失|为空|不存在|不一致|超时|报错)/,
|
|
36
|
+
/兜底/,
|
|
37
|
+
/fallback/i,
|
|
38
|
+
/异常处理/,
|
|
39
|
+
/恢复/,
|
|
40
|
+
];
|
|
41
|
+
/** 检查点显性标记(dim4):仅靠『如果…建议…』措辞不算。 */
|
|
42
|
+
const CHECKPOINT_PATTERNS = [/🔴/, /🛑/, /CHECKPOINT/, /STOP/];
|
|
43
|
+
/** 反例/黑名单章节(dim9)。 */
|
|
44
|
+
const COUNTEREXAMPLE_PATTERNS = [/反例/, /黑名单/, /不要做/, /禁止/, /反模式/];
|
|
45
|
+
|
|
46
|
+
const clampScore = (value) => Math.max(1, Math.min(10, value));
|
|
47
|
+
const countMatches = (text, patterns) => patterns.reduce((total, pattern) => total + (String(text).match(pattern)?.length ?? 0), 0);
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 静态评分(dims 1-7、9)。dim8 由调用方注入(measured dim8 干跑/实测分)。
|
|
51
|
+
*
|
|
52
|
+
* @param {string} text SKILL.md 全文
|
|
53
|
+
* @param {{dim8?: number, measured?: boolean, resourcePaths?: string[]}} [options]
|
|
54
|
+
* @returns {{dimensions: Array<{id:number,name:string,weight:number,score:number,evidence:string}>, total:number, evaluated:boolean, triageOnly:boolean}}
|
|
55
|
+
*/
|
|
56
|
+
export function scoreSkillRubric(text, options = {}) {
|
|
57
|
+
const source = typeof text === 'string' ? text : '';
|
|
58
|
+
const dim8 = typeof options.dim8 === 'number' ? clampScore(options.dim8) : 5;
|
|
59
|
+
const evidence = [];
|
|
60
|
+
const scores = new Map();
|
|
61
|
+
|
|
62
|
+
// dim1 Frontmatter:name/description/触发词/长度/空话尾巴
|
|
63
|
+
{
|
|
64
|
+
const hasName = /^---\s*[\s\S]*?name:/m.test(source);
|
|
65
|
+
const hasDescription = /^---\s*[\s\S]*?description:/m.test(source);
|
|
66
|
+
const description = source.match(/description:\s*([^\n]+)/)?.[1] ?? '';
|
|
67
|
+
const hasTriggers = /触发|trigger|当用户|使用场景/i.test(description);
|
|
68
|
+
const vagueTail = /(灵活应用|根据情况判断|视情况)/.test(description.slice(-80));
|
|
69
|
+
let score = 4;
|
|
70
|
+
if (hasName) score += 2;
|
|
71
|
+
if (hasDescription) score += 1;
|
|
72
|
+
if (hasTriggers) score += 2;
|
|
73
|
+
if (description.length > 0 && description.length <= 1024) score += 1;
|
|
74
|
+
if (vagueTail) score -= 2;
|
|
75
|
+
scores.set(1, clampScore(score));
|
|
76
|
+
evidence.push(`dim1 frontmatter: name=${hasName} desc=${hasDescription} triggers=${hasTriggers} vagueTail=${vagueTail}`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// dim2 工作流:编号/标题步骤数
|
|
80
|
+
{
|
|
81
|
+
const steps = (source.match(/^\s{0,4}(\d+[.)、]|#{2,4}\s*(Step|步骤|Phase|阶段)\s*\d)/gim) ?? []).length;
|
|
82
|
+
const score = steps === 0 ? 3 : steps <= 2 ? 5 : steps <= 5 ? 7 : 9;
|
|
83
|
+
scores.set(2, clampScore(score));
|
|
84
|
+
evidence.push(`dim2 workflow steps=${steps}`);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// dim3 失败模式编码:显式失败分支;只写正向流程扣分
|
|
88
|
+
{
|
|
89
|
+
const hits = countMatches(source, FAILURE_PATTERNS);
|
|
90
|
+
const score = hits === 0 ? 2 : hits <= 2 ? 6 : hits <= 5 ? 8 : 9;
|
|
91
|
+
scores.set(3, clampScore(score));
|
|
92
|
+
evidence.push(`dim3 failure patterns=${hits}`);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// dim4 检查点:显性标记(🔴/STOP/CHECKPOINT)
|
|
96
|
+
{
|
|
97
|
+
const hits = countMatches(source, CHECKPOINT_PATTERNS);
|
|
98
|
+
const score = hits === 0 ? 2 : hits >= 3 ? 9 : 7;
|
|
99
|
+
scores.set(4, clampScore(score));
|
|
100
|
+
evidence.push(`dim4 explicit checkpoints=${hits}`);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// dim5 可执行具体性:软化措辞扣分 + 具体参数/示例加分
|
|
104
|
+
{
|
|
105
|
+
const soft = SOFT_WORDS.reduce((total, word) => total + (source.split(word).length - 1), 0);
|
|
106
|
+
const concrete = (source.match(/```|`[^`\n]+`|--[a-z-]+|\d+(\.\d+)?(ms|s|px|%|KB|MB)/g) ?? []).length;
|
|
107
|
+
let score = 6 + Math.min(3, Math.floor(concrete / 8));
|
|
108
|
+
if (soft >= 3) score -= Math.min(5, soft);
|
|
109
|
+
scores.set(5, clampScore(score));
|
|
110
|
+
evidence.push(`dim5 softWords=${soft} concreteHints=${concrete}`);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// dim6 资源整合度:references/scripts/assets 引用可达
|
|
114
|
+
{
|
|
115
|
+
const refs = (source.match(/(references|scripts|assets)\/[^\s)`"']+/g) ?? []).length;
|
|
116
|
+
const known = Array.isArray(options.resourcePaths) ? options.resourcePaths.length : refs;
|
|
117
|
+
const score = refs === 0 ? (known === 0 ? 5 : 6) : known >= refs ? 9 : 6;
|
|
118
|
+
scores.set(6, clampScore(score));
|
|
119
|
+
evidence.push(`dim6 resource refs=${refs} reachable=${known}`);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// dim7 整体架构:层级 + 冗余扣分
|
|
123
|
+
{
|
|
124
|
+
const headings = (source.match(/^#{1,4}\s+/gm) ?? []).length;
|
|
125
|
+
const filler = FILLER_WORDS.reduce((total, word) => total + (source.split(word).length - 1), 0);
|
|
126
|
+
let score = headings >= 5 ? 8 : headings >= 2 ? 6 : 4;
|
|
127
|
+
score -= Math.min(4, filler);
|
|
128
|
+
scores.set(7, clampScore(score));
|
|
129
|
+
evidence.push(`dim7 headings=${headings} filler=${filler}`);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// dim8 实测表现:调用方注入(measured=true 时才是实测)
|
|
133
|
+
scores.set(8, dim8);
|
|
134
|
+
|
|
135
|
+
// dim9 反例与黑名单
|
|
136
|
+
{
|
|
137
|
+
const hits = countMatches(source, COUNTEREXAMPLE_PATTERNS);
|
|
138
|
+
const score = hits === 0 ? 2 : hits >= 2 ? 9 : 7;
|
|
139
|
+
scores.set(9, clampScore(score));
|
|
140
|
+
evidence.push(`dim9 counterexamples=${hits}`);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const dimensions = NINE_DIMENSIONS.map((dimension) => ({
|
|
144
|
+
...dimension,
|
|
145
|
+
score: scores.get(dimension.id),
|
|
146
|
+
evidence: evidence.find((line) => line.startsWith(`dim${dimension.id} `)) ?? '',
|
|
147
|
+
}));
|
|
148
|
+
const total = Math.round(dimensions.reduce((sum, dimension) => sum + dimension.score * dimension.weight, 0) / 10 * 10) / 10;
|
|
149
|
+
return {
|
|
150
|
+
dimensions,
|
|
151
|
+
total,
|
|
152
|
+
// dim8 未经实测(干跑)时标注,避免把 triage 分当真实效果。
|
|
153
|
+
evaluated: options.measured === true,
|
|
154
|
+
triageOnly: true,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** 输出可读的 triage 摘要(工具返回值用纯文本时)。 */
|
|
159
|
+
export function formatRubric(result) {
|
|
160
|
+
const rows = result.dimensions.map((dimension) => ` dim${dimension.id} ${dimension.name.padEnd(12)} ${String(dimension.score).padStart(2)}/10 ×${String(dimension.weight).padStart(2)} ${dimension.evidence}`);
|
|
161
|
+
return [
|
|
162
|
+
`[skillopt rubric] total=${result.total}/100${result.evaluated ? '' : ' (dim8 dry-run: NOT a measured effect score)'}`,
|
|
163
|
+
' ⚠️ absolute totals are TRIAGE-ONLY; keep/revert must use paired judge majority',
|
|
164
|
+
...rows,
|
|
165
|
+
` weakest dim: ${result.dimensions.reduce((worst, dimension) => (dimension.weight * (10 - dimension.score) > worst.weight * (10 - worst.score) ? dimension : worst), result.dimensions[0]).name}`,
|
|
166
|
+
].join('\n');
|
|
167
|
+
}
|
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.90",
|
|
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
|
+
- **可追溯性**:所有结果都应有清晰的来源和记录,便于后续分析和优化。
|