@suifei/dsh-ai-team 0.3.84 → 0.3.89
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 +18 -0
- package/index.js +110 -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/rubric.js +167 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/__init__.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/__main__.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/backend.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/budget.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/config.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/consolidate.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/cycle.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/dream.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/evidence.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/gate.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/handoff_backend.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_codex.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_copilot.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_copilot_cli.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_cursor.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_opencode.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_pi.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_sources.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/judges.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/memory.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/mine.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/multi_skill.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/replay.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/skill_resolver.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/staging.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/state.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/tasks_file.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/types.cpython-311.pyc +0 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.89 - 2026-11-12
|
|
4
|
+
|
|
5
|
+
**完全对齐 darwin-skill v2.1(9 维 rubric + 独立 judge)**
|
|
6
|
+
|
|
7
|
+
- **9 维 rubric(`skillopt_rubric`)**:结构 59(Frontmatter 7 / 工作流 12 / 失败模式 12 / 检查点 6 / 具体性 18 / 资源 4)+ 效果 35(架构 12 / 实测 23)+ Meta 6(反例黑名单)——静态启发式评分带逐维证据;**绝对总分明确标注 TRIAGE-ONLY**(绝不作 keep/revert 依据),dim8 未实测时标注 dry-run。
|
|
8
|
+
- **独立 judge(`skillopt_judge`)**:paired 同-judge 比较 + A/B 随机化盲评 + 奇数 N(默认 3,可配 `skilloptJudgeVotes`)多数决(better≥worse→keep,含 tie;无有效票→inconclusive 不得 adopt);judge 是**一次性独立子代理**(`subagents.startActivation`),上下文干净,杜绝自评自改。
|
|
9
|
+
- **adopt 验证门**:`skillopt_adopt` 经 `wrapToolsWithAdoptGate` 包装——先读 staged 候选与 live 基线,跑独立 judge;revert/inconclusive/无法验证时**拒绝 adopt** 并给出理由(unverified adopt is refused),keep 才放行引擎。
|
|
10
|
+
- **根因修复**:插件 `inject` 增加 `tools`/`shell`——此前 shell 服务未就绪时 SkillOpt 整段静默跳过(diag 实测 `hasShell:false`);judge 的 `ensureParent` 改惰性引用(修复 TDZ `Cannot access before initialization`)。
|
|
11
|
+
- **工具输出协议修复**:`skillopt_rubric`/`skillopt_judge` 的 render 返回 content 数组(此前 `content.some is not a function`)。
|
|
12
|
+
- 测试:`test/darwin-alignment.test.js` 10 项(rubric 强弱对照/权重和 100、A/B 盲评与解析、多数决与平局、judge-runner 子代理注入、adopt 门 keep/revert/inconclusive/无法验证、只拦 adopt 不动其他工具)。
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
## 0.3.86 - 2026-11-12
|
|
16
|
+
|
|
17
|
+
- **技能进化链路可观测性**:health 新增 `runtime.services`(tools.register / shell / 已注册的 skillopt_* 工具清单);SkillOpt 注册条件不满足时记 `skillopt.skip.fail` 诊断——消除「静默未启用」的排查盲区(此前只能靠 diag 猜)。
|
|
18
|
+
- 实证:本机 7 个 skillopt 工具全部注册、Python 3.11 引擎可运行(`status` 实跑 `nights so far: 0`);技能进化链路**已就绪但从未运行**(默认 mock backend 为安全默认)。
|
|
19
|
+
|
|
20
|
+
|
|
3
21
|
## 0.3.84 - 2026-11-12
|
|
4
22
|
|
|
5
23
|
- **旧会话自动迁移(review 修复)**:唤醒失败且错误表明 subagent 不可用时(旧形态成员会话由 agents.create 创建、不在 subagent catalog),自动以 subagent 形态重建一次(重置会话)并记录 member.autoreseat 诊断——避免成员在重构后静默不再被唤醒,用户无需手动迁移。
|
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,9 @@ 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';
|
|
28
31
|
import { createMemberPermissionGuard } from './lib/host/permission-guard.js';
|
|
29
32
|
import { installFaultAdapter } from './lib/host/fault-adapter.js';
|
|
30
33
|
import { buildModelCatalog } from './lib/host/model-catalog.js';
|
|
@@ -39,9 +42,9 @@ import { createDiagLogger, defaultDiagDir } from './lib/diaglog.js';
|
|
|
39
42
|
export const name = 'ai-team';
|
|
40
43
|
|
|
41
44
|
/** The workbench only makes sense where the Web carrier exists. */
|
|
42
|
-
export const inject = ['webServer', 'permissionPresets', 'sandboxPolicy'];
|
|
45
|
+
export const inject = ['webServer', 'permissionPresets', 'sandboxPolicy', 'tools', 'shell'];
|
|
43
46
|
|
|
44
|
-
const VERSION = '0.3.
|
|
47
|
+
const VERSION = '0.3.89';
|
|
45
48
|
const HUMAN_ID = 'mem_human';
|
|
46
49
|
|
|
47
50
|
const SKILLOPT_BACKENDS = ['mock', 'claude', 'codex', 'copilot', 'cursor', 'pi', 'opencode', 'handoff', 'azure_openai'];
|
|
@@ -64,6 +67,8 @@ export const Config = z.object({
|
|
|
64
67
|
skilloptBackend: z.union(SKILLOPT_BACKENDS).default('mock'),
|
|
65
68
|
// per-call timeout for skillopt_* engine runs
|
|
66
69
|
skilloptTimeoutMs: z.number().step(1).min(10_000).max(600_000).default(120_000),
|
|
70
|
+
// Darwin paired judge:独立子代理票数,奇数 ≥3(接近平局可升 5)。
|
|
71
|
+
skilloptJudgeVotes: z.number().step(1).min(3).max(9).default(3),
|
|
67
72
|
});
|
|
68
73
|
|
|
69
74
|
function send(res, body, status = 200) {
|
|
@@ -747,11 +752,43 @@ export function apply(ctx, config = {}) {
|
|
|
747
752
|
let disposeSkillOpt = () => {};
|
|
748
753
|
try {
|
|
749
754
|
const shell = ctx.get('shell');
|
|
755
|
+
// 探针:SkillOpt 注册依赖 tools.register + shell 两个服务。历史上这条
|
|
756
|
+
// if 为假时无任何诊断,导致「技能进化静默未启用」(用户实证盘查)。
|
|
757
|
+
if (!tools?.register || !shell) {
|
|
758
|
+
diag.append({
|
|
759
|
+
ev: 'skillopt.skip.fail',
|
|
760
|
+
hasToolsRegister: typeof tools?.register === 'function',
|
|
761
|
+
hasShell: Boolean(shell),
|
|
762
|
+
});
|
|
763
|
+
console.warn('[ai-team] SkillOpt tools not registered:', { hasToolsRegister: typeof tools?.register === 'function', hasShell: Boolean(shell) });
|
|
764
|
+
}
|
|
750
765
|
if (tools?.register && shell) {
|
|
766
|
+
// Darwin validation gate(对齐 darwin-skill v2.1):adopt 之前必须
|
|
767
|
+
// 通过 paired 独立 judge 的多数决;绝对 rubric 分只做 triage。
|
|
768
|
+
const engineScript = fileURLToPath(new URL('./lib/vendor/skillopt/scripts/sleep.py', import.meta.url));
|
|
769
|
+
const readPair = makeReadPair({ shell, engineScript, diag });
|
|
770
|
+
const judge = makeJudge({
|
|
771
|
+
subagents: ctx.get('subagents'),
|
|
772
|
+
// 惰性解析:ensureParent 在 apply 之后才定义(const TDZ),
|
|
773
|
+
// judge 只在 adopt 时调用,此处不能立即取值。
|
|
774
|
+
ensureParent: () => ensureParent(),
|
|
775
|
+
providerName: () => providers[0],
|
|
776
|
+
votes: config.skilloptJudgeVotes ?? 3,
|
|
777
|
+
diag,
|
|
778
|
+
});
|
|
779
|
+
const adoptGate = createAdoptGate({
|
|
780
|
+
readPair,
|
|
781
|
+
judge,
|
|
782
|
+
diag: (line, extra) => diag.append({
|
|
783
|
+
ev: extra?.ev ?? 'skillopt.adoptgate',
|
|
784
|
+
message: line,
|
|
785
|
+
...(extra?.project === undefined ? {} : { project: extra.project }),
|
|
786
|
+
}),
|
|
787
|
+
});
|
|
751
788
|
// Backend/timeout come from the plugin Config (patch layer), so an
|
|
752
789
|
// operator can move the skillopt_* tools off the safe mock default.
|
|
753
790
|
disposeSkillOpt = applySkillOpt({
|
|
754
|
-
tools,
|
|
791
|
+
tools: wrapToolsWithAdoptGate(tools, adoptGate),
|
|
755
792
|
shell,
|
|
756
793
|
logger: console,
|
|
757
794
|
}, {
|
|
@@ -759,7 +796,68 @@ export function apply(ctx, config = {}) {
|
|
|
759
796
|
project: process.cwd(),
|
|
760
797
|
timeoutMs: config.skilloptTimeoutMs ?? 120_000,
|
|
761
798
|
}) ?? (() => {});
|
|
762
|
-
|
|
799
|
+
// 9 维 rubric(triage)与独立 judge(keep/revert)作为新工具暴露。
|
|
800
|
+
const rubricTool = tools.register({
|
|
801
|
+
name: 'skillopt_rubric',
|
|
802
|
+
description: 'Score a SKILL.md against the 9-dimension Darwin rubric (triage only — absolute scores must not be used for keep/revert).',
|
|
803
|
+
parameters: {
|
|
804
|
+
project: { type: 'string', description: 'Project directory (defaults to cwd)' },
|
|
805
|
+
skillPath: { type: 'string', description: 'Path to SKILL.md to score' },
|
|
806
|
+
dim8: { type: 'number', description: 'Measured effect score 1-10 (omit for dry-run)' },
|
|
807
|
+
measured: { type: 'boolean', description: 'Set when dim8 came from a real prompt run' },
|
|
808
|
+
},
|
|
809
|
+
// DSH 工具输出协议:render 必须返回 content 数组(与 vendored 一致)。
|
|
810
|
+
output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
|
|
811
|
+
async execute(args) {
|
|
812
|
+
const project = typeof args?.project === 'string' && args.project !== '' ? args.project : process.cwd();
|
|
813
|
+
const skillPath = typeof args?.skillPath === 'string' && args.skillPath !== ''
|
|
814
|
+
? args.skillPath
|
|
815
|
+
: join(project, 'SKILL.md');
|
|
816
|
+
if (!existsSync(skillPath)) return `[skillopt rubric] SKILL.md not found: ${skillPath}`;
|
|
817
|
+
const result = scoreSkillRubric(readFileSync(skillPath, 'utf8'), {
|
|
818
|
+
dim8: typeof args?.dim8 === 'number' ? args.dim8 : undefined,
|
|
819
|
+
measured: args?.measured === true,
|
|
820
|
+
});
|
|
821
|
+
diag.append({ ev: 'skillopt.rubric', project, skillPath, total: result.total, measured: result.evaluated });
|
|
822
|
+
return formatRubric(result);
|
|
823
|
+
},
|
|
824
|
+
});
|
|
825
|
+
const judgeTool = tools.register({
|
|
826
|
+
name: 'skillopt_judge',
|
|
827
|
+
description: 'Paired independent-judge verdict (N odd votes, majority) for before/after SKILL.md — the authoritative keep/revert signal.',
|
|
828
|
+
parameters: {
|
|
829
|
+
project: { type: 'string', description: 'Project directory' },
|
|
830
|
+
beforePath: { type: 'string', description: 'Baseline file path (default: current live SKILL.md)' },
|
|
831
|
+
afterPath: { type: 'string', description: 'Candidate file path (default: latest staged proposal)' },
|
|
832
|
+
},
|
|
833
|
+
// DSH 工具输出协议:render 必须返回 content 数组(与 vendored 一致)。
|
|
834
|
+
output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
|
|
835
|
+
async execute(args) {
|
|
836
|
+
const project = typeof args?.project === 'string' && args.project !== '' ? args.project : process.cwd();
|
|
837
|
+
let pair;
|
|
838
|
+
try {
|
|
839
|
+
pair = await readPair(project);
|
|
840
|
+
} catch (error) {
|
|
841
|
+
return `[skillopt judge] cannot read pair: ${error?.message ?? error}`;
|
|
842
|
+
}
|
|
843
|
+
const before = typeof args?.beforePath === 'string' && existsSync(args.beforePath) ? readFileSync(args.beforePath, 'utf8') : pair.before;
|
|
844
|
+
const after = typeof args?.afterPath === 'string' && existsSync(args.afterPath) ? readFileSync(args.afterPath, 'utf8') : pair.after;
|
|
845
|
+
const result = await judge({ before, after, projectDir: project });
|
|
846
|
+
const lines = result.votes.map((vote) => ` judge${vote.index}: ${vote.vote ?? 'invalid'} (margin ${vote.margin ?? '-'}) ${vote.reason}`);
|
|
847
|
+
return [
|
|
848
|
+
`[skillopt judge] verdict=${result.verdict} better=${result.better} worse=${result.worse} tie=${result.ties} valid=${result.valid}`,
|
|
849
|
+
...lines,
|
|
850
|
+
result.errors.length > 0 ? ` errors: ${result.errors.join('; ')}` : '',
|
|
851
|
+
].filter(Boolean).join('\n');
|
|
852
|
+
},
|
|
853
|
+
});
|
|
854
|
+
const disposeExtra = () => {
|
|
855
|
+
try { disposeSkillOpt?.(); } catch { /* already disposed */ }
|
|
856
|
+
try { rubricTool?.(); } catch { /* noop */ }
|
|
857
|
+
try { judgeTool?.(); } catch { /* noop */ }
|
|
858
|
+
};
|
|
859
|
+
disposeSkillOpt = disposeExtra;
|
|
860
|
+
diag.append({ ev: 'skillopt.registered', backend: config.skilloptBackend ?? 'mock', timeoutMs: config.skilloptTimeoutMs ?? 120_000, adoptGate: true, judgeVotes: config.skilloptJudgeVotes ?? 3 });
|
|
763
861
|
}
|
|
764
862
|
} catch (error) {
|
|
765
863
|
diag.append({ ev: 'skillopt.fail', message: error?.message ?? String(error) });
|
|
@@ -1200,6 +1298,13 @@ export function apply(ctx, config = {}) {
|
|
|
1200
1298
|
})),
|
|
1201
1299
|
runtime: {
|
|
1202
1300
|
roots: ctx.get('agents')?.roots?.().length ?? null,
|
|
1301
|
+
// 服务探测(技能进化链路依赖 tools.register + shell):
|
|
1302
|
+
// 同步可观测,避免历史「静默未启用」盲区。
|
|
1303
|
+
services: {
|
|
1304
|
+
tools: typeof ctx.get('tools')?.register === 'function',
|
|
1305
|
+
shell: Boolean(ctx.get('shell')),
|
|
1306
|
+
skilloptTools: (ctx.get('tools')?.definitions?.() ?? []).map((definition) => definition.name).filter((toolName) => String(toolName).startsWith('skillopt_')),
|
|
1307
|
+
},
|
|
1203
1308
|
defaultModel: ctx.get('agentDefaultModel')?.currentSelection?.() ?? null,
|
|
1204
1309
|
llmProviders: ctx.get('llm')?.listProviders?.() ?? [],
|
|
1205
1310
|
providers: ctx.get('subagents')?.list?.() ?? [],
|
|
@@ -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,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
|
+
}
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
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.89",
|
|
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",
|