@hmharness/evolution 0.14.5 → 0.14.9
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/dist/bench.d.ts.v2bak.v2bak +44 -0
- package/dist/bench.js.v2bak.v2bak +156 -0
- package/dist/candidates.d.ts.v2bak.v2bak +114 -0
- package/dist/candidates.js.v2bak.v2bak +232 -0
- package/dist/dataset.d.ts.v2bak.v2bak +64 -0
- package/dist/dataset.js.v2bak.v2bak +184 -0
- package/dist/evolve.d.ts +14 -0
- package/dist/evolve.d.ts.v2bak.v2bak +98 -0
- package/dist/evolve.js +36 -15
- package/dist/evolve.js.v2bak.v2bak +573 -0
- package/dist/impact.d.ts.v2bak.v2bak +77 -0
- package/dist/impact.js.v2bak.v2bak +214 -0
- package/dist/index.d.ts.v2bak.v2bak +16 -0
- package/dist/index.js.v2bak.v2bak +16 -0
- package/dist/insights.d.ts.v2bak.v2bak +18 -0
- package/dist/insights.js.v2bak.v2bak +80 -0
- package/dist/knowledge.d.ts.v2bak.v2bak +15 -0
- package/dist/knowledge.js.v2bak.v2bak +145 -0
- package/dist/labels.d.ts.v2bak.v2bak +20 -0
- package/dist/labels.js.v2bak.v2bak +57 -0
- package/dist/memory.d.ts.v2bak.v2bak +32 -0
- package/dist/memory.js.v2bak.v2bak +233 -0
- package/dist/patches.d.ts.v2bak.v2bak +83 -0
- package/dist/patches.js +6 -2
- package/dist/patches.js.v2bak.v2bak +253 -0
- package/dist/radar.d.ts.v2bak.v2bak +3 -0
- package/dist/radar.js.v2bak.v2bak +40 -0
- package/dist/ranker.d.ts.v2bak.v2bak +44 -0
- package/dist/ranker.js.v2bak.v2bak +55 -0
- package/dist/readiness.d.ts.v2bak.v2bak +15 -0
- package/dist/readiness.js +14 -2
- package/dist/readiness.js.v2bak.v2bak +167 -0
- package/dist/skillpayload.d.ts.v2bak.v2bak +1 -0
- package/dist/skillpayload.js.v2bak +28 -0
- package/dist/skillpayload.js.v2bak.v2bak.v2bak +28 -0
- package/dist/skills.d.ts.v2bak.v2bak +54 -0
- package/dist/skills.js.v2bak.v2bak +321 -0
- package/dist/workflows.d.ts.v2bak.v2bak +28 -0
- package/dist/workflows.js.v2bak.v2bak +84 -0
- package/package.json +1 -1
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
export interface BenchCase {
|
|
2
|
+
name: string;
|
|
3
|
+
prompt: string;
|
|
4
|
+
/** All substrings (split on &&) must appear in the output, case-insensitive. */
|
|
5
|
+
expect: string[];
|
|
6
|
+
/** Output must equal this string exactly (both trimmed). */
|
|
7
|
+
expectExact?: string;
|
|
8
|
+
/** Output must match this regex (whole output, case-sensitive). */
|
|
9
|
+
expectRegex?: string;
|
|
10
|
+
/** Substrings that must NOT appear (failure-marker exclusion). */
|
|
11
|
+
expectNone?: string[];
|
|
12
|
+
/** At least ONE of these substrings must appear. */
|
|
13
|
+
expectAny?: string[];
|
|
14
|
+
/** When true the case runs through the full agent loop with tools. */
|
|
15
|
+
tools: boolean;
|
|
16
|
+
/** Holdout cases are excluded from the promotion gate and re-verify after promotion (anti-memorization, GDPevo style). */
|
|
17
|
+
holdout: boolean;
|
|
18
|
+
/** Candidate token-cost ceiling as a multiple of the baseline run. */
|
|
19
|
+
costCap?: number;
|
|
20
|
+
}
|
|
21
|
+
export interface BenchResult {
|
|
22
|
+
name: string;
|
|
23
|
+
pass: boolean;
|
|
24
|
+
detail: string;
|
|
25
|
+
}
|
|
26
|
+
export declare function matchExpect(output: string, expect: string[]): boolean;
|
|
27
|
+
/** Fence convention: when the reply is a fenced block, assertions test the
|
|
28
|
+
* fence INNER content (day-55 finding: models preserve literals verbatim
|
|
29
|
+
* inside code fences while normalizing them in prose - the fence is the
|
|
30
|
+
* reply convention that makes exactness attainable for habit-prone models).
|
|
31
|
+
* Tolerates a trailing space after the opening fence markers. */
|
|
32
|
+
export declare function fenceInner(output: string): string;
|
|
33
|
+
/** Full structured assertion: every declared mode must hold. */
|
|
34
|
+
export declare function matchCase(output: string, c: Pick<BenchCase, 'expect' | 'expectExact' | 'expectRegex' | 'expectNone' | 'expectAny'>): {
|
|
35
|
+
pass: boolean;
|
|
36
|
+
detail: string;
|
|
37
|
+
};
|
|
38
|
+
export declare function listCases(home: string): Promise<BenchCase[]>;
|
|
39
|
+
export declare function runBench(home: string, run: (c: BenchCase) => Promise<string>): Promise<{
|
|
40
|
+
results: BenchResult[];
|
|
41
|
+
passRate: number;
|
|
42
|
+
}>;
|
|
43
|
+
/** Starter cases so the evolve gate has a signal from day one. */
|
|
44
|
+
export declare function seedCases(home: string): Promise<string[]>;
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hmharness/evolution - bench
|
|
3
|
+
* The fitness signal for self-evolution. bench/cases/*.task files are:
|
|
4
|
+
* line 1 the prompt
|
|
5
|
+
* expect: a && b substrings that must ALL appear in the final output
|
|
6
|
+
* expect-exact: "..." the output equals this string (trimmed)
|
|
7
|
+
* expect-regex: ... a regex the output must match
|
|
8
|
+
* expect-none: a && b substrings that must NOT appear
|
|
9
|
+
* expect-any: a || b one of these substrings must appear
|
|
10
|
+
* tools: loop (optional) run through the full agent loop with tools
|
|
11
|
+
* cost-cap: 1.3 (optional) candidate cost multiplier ceiling vs baseline
|
|
12
|
+
* Skill or prompt changes must keep the bench green before promotion - the
|
|
13
|
+
* evolve loop enforces this A/B (baseline vs candidate).
|
|
14
|
+
*
|
|
15
|
+
* Assertion upgrade (gate methodology): plain substring matching lets
|
|
16
|
+
* verbose-but-wrong outputs pass; the structured modes pin exact shapes,
|
|
17
|
+
* forbid failure markers, and (with cost-cap) stop a candidate that only
|
|
18
|
+
* passes by burning 3x tokens. Old files keep working - `expect:` keeps
|
|
19
|
+
* its ALL-substrings semantics.
|
|
20
|
+
*/
|
|
21
|
+
import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
|
|
22
|
+
import { join } from 'node:path';
|
|
23
|
+
export function matchExpect(output, expect) {
|
|
24
|
+
const lower = output.toLowerCase();
|
|
25
|
+
return expect.every((e) => lower.includes(e.toLowerCase()));
|
|
26
|
+
}
|
|
27
|
+
/** Fence convention: when the reply is a fenced block, assertions test the
|
|
28
|
+
* fence INNER content (day-55 finding: models preserve literals verbatim
|
|
29
|
+
* inside code fences while normalizing them in prose - the fence is the
|
|
30
|
+
* reply convention that makes exactness attainable for habit-prone models).
|
|
31
|
+
* Tolerates a trailing space after the opening fence markers. */
|
|
32
|
+
export function fenceInner(output) {
|
|
33
|
+
const m = output.match(/```[a-zA-Z]*[ \t]*\r?\n([\s\S]*?)(?:\r?\n)?```/);
|
|
34
|
+
return m ? m[1] : output;
|
|
35
|
+
}
|
|
36
|
+
/** Full structured assertion: every declared mode must hold. */
|
|
37
|
+
export function matchCase(output, c) {
|
|
38
|
+
const body = fenceInner(output);
|
|
39
|
+
if (c.expectExact !== undefined && body.trim() !== c.expectExact.trim()) {
|
|
40
|
+
return { pass: false, detail: `exact mismatch: got "${body.trim().slice(0, 80)}"` };
|
|
41
|
+
}
|
|
42
|
+
if (c.expectRegex !== undefined) {
|
|
43
|
+
try {
|
|
44
|
+
if (!new RegExp(c.expectRegex).test(body))
|
|
45
|
+
return { pass: false, detail: `regex mismatch: /${c.expectRegex.slice(0, 60)}/` };
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return { pass: false, detail: `invalid regex in case: ${c.expectRegex.slice(0, 40)}` };
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (c.expectNone && c.expectNone.some((e) => body.toLowerCase().includes(e.toLowerCase()))) {
|
|
52
|
+
return { pass: false, detail: `forbidden marker present: ${c.expectNone.join(' && ')}` };
|
|
53
|
+
}
|
|
54
|
+
if (c.expectAny && !c.expectAny.some((e) => body.toLowerCase().includes(e.toLowerCase()))) {
|
|
55
|
+
return { pass: false, detail: `none of the allowed markers found: ${c.expectAny.join(' || ')}` };
|
|
56
|
+
}
|
|
57
|
+
if (!matchExpect(body, c.expect)) {
|
|
58
|
+
return { pass: false, detail: `missing "${c.expect.join('" && "')}" in output` };
|
|
59
|
+
}
|
|
60
|
+
return { pass: true, detail: 'ok' };
|
|
61
|
+
}
|
|
62
|
+
export async function listCases(home) {
|
|
63
|
+
const dir = join(home, 'bench', 'cases');
|
|
64
|
+
let files;
|
|
65
|
+
try {
|
|
66
|
+
files = (await readdir(dir)).filter((f) => f.endsWith('.task'));
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return [];
|
|
70
|
+
}
|
|
71
|
+
const cases = [];
|
|
72
|
+
for (const f of files.sort()) {
|
|
73
|
+
const raw = (await readFile(join(dir, f), 'utf8')).trim();
|
|
74
|
+
const lines = raw.split('\n');
|
|
75
|
+
const prompt = lines[0];
|
|
76
|
+
const pick = (key) => {
|
|
77
|
+
const l = lines.find((x) => x.startsWith(key + ':'));
|
|
78
|
+
return l ? l.slice(key.length + 1).trim() : undefined;
|
|
79
|
+
};
|
|
80
|
+
const list = (key) => {
|
|
81
|
+
const v = pick(key);
|
|
82
|
+
return v ? v.split(/&&|\|\|/).map((s) => s.trim()).filter(Boolean) : undefined;
|
|
83
|
+
};
|
|
84
|
+
const costCap = Number(pick('cost-cap'));
|
|
85
|
+
cases.push({
|
|
86
|
+
name: f.replace(/\.task$/, ''),
|
|
87
|
+
prompt,
|
|
88
|
+
expect: list('expect') ?? [],
|
|
89
|
+
expectExact: pick('expect-exact')?.replace(/^"|"$/g, ''),
|
|
90
|
+
expectRegex: pick('expect-regex'),
|
|
91
|
+
expectNone: list('expect-none'),
|
|
92
|
+
expectAny: list('expect-any'),
|
|
93
|
+
tools: pick('tools') === 'loop',
|
|
94
|
+
holdout: pick('holdout') === 'true',
|
|
95
|
+
costCap: Number.isFinite(costCap) && costCap > 0 ? costCap : undefined,
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
return cases;
|
|
99
|
+
}
|
|
100
|
+
export async function runBench(home, run) {
|
|
101
|
+
const cases = await listCases(home);
|
|
102
|
+
const results = [];
|
|
103
|
+
for (const c of cases) {
|
|
104
|
+
try {
|
|
105
|
+
const out = await run(c);
|
|
106
|
+
const r = matchCase(out, c);
|
|
107
|
+
results.push({ name: c.name, pass: r.pass, detail: r.detail });
|
|
108
|
+
}
|
|
109
|
+
catch (err) {
|
|
110
|
+
results.push({ name: c.name, pass: false, detail: String(err).slice(0, 120) });
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
const passed = results.filter((r) => r.pass).length;
|
|
114
|
+
// persist a history record: readiness's "eval-regression-stable" condition
|
|
115
|
+
// reads evolution/benches/*.json - without these records the RL gate's
|
|
116
|
+
// stability condition can never be met (day-20 audit gap)
|
|
117
|
+
try {
|
|
118
|
+
const dir = join(home, 'evolution', 'benches');
|
|
119
|
+
await mkdir(dir, { recursive: true });
|
|
120
|
+
const record = {
|
|
121
|
+
time: new Date().toISOString(),
|
|
122
|
+
total: cases.length,
|
|
123
|
+
passed,
|
|
124
|
+
passRate: cases.length === 0 ? 1 : passed / cases.length,
|
|
125
|
+
results: results.map((r) => ({ name: r.name, pass: r.pass, detail: r.detail.slice(0, 200) })),
|
|
126
|
+
};
|
|
127
|
+
await writeFile(join(dir, `${record.time.replace(/[:.]/g, '-')}.json`), JSON.stringify(record, null, 2) + '\n', 'utf8');
|
|
128
|
+
}
|
|
129
|
+
catch { /* history is best-effort; the run result still returns */ }
|
|
130
|
+
return { results, passRate: cases.length === 0 ? 1 : passed / cases.length };
|
|
131
|
+
}
|
|
132
|
+
/** Starter cases so the evolve gate has a signal from day one. */
|
|
133
|
+
export async function seedCases(home) {
|
|
134
|
+
const dir = join(home, 'bench', 'cases');
|
|
135
|
+
const written = [];
|
|
136
|
+
const seeds = [
|
|
137
|
+
['toolchain-report.task', '运行鸿蒙工具链体检,然后逐项说出一共检查了哪三个工具的名称\nexpect: hdc && hvigorw && ohpm\ntools: loop\n'],
|
|
138
|
+
['reply-determinism.task', '只回复这六个字符,不要任何其他内容:HMH-OK\nexpect: HMH-OK\n'],
|
|
139
|
+
['toolchain-ohpm-status.task', '运行鸿蒙工具链体检,然后只回答 ohpm 的状态是 OK 还是 MISSING\nexpect: OK\ntools: loop\nholdout: true\n'],
|
|
140
|
+
];
|
|
141
|
+
let existing = [];
|
|
142
|
+
try {
|
|
143
|
+
existing = await readdir(dir);
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
/* first seed */
|
|
147
|
+
}
|
|
148
|
+
for (const [name, body] of seeds) {
|
|
149
|
+
if (existing.includes(name))
|
|
150
|
+
continue;
|
|
151
|
+
await mkdir(dir, { recursive: true });
|
|
152
|
+
await writeFile(join(dir, name), body, 'utf8');
|
|
153
|
+
written.push(name);
|
|
154
|
+
}
|
|
155
|
+
return written;
|
|
156
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import type { BenchCase } from './bench.ts';
|
|
2
|
+
export type CandidateTarget = 'prompt' | 'skill' | 'context' | 'tool_policy' | 'model_router' | 'workflow' | 'harness';
|
|
3
|
+
export declare const CANDIDATE_TARGETS: CandidateTarget[];
|
|
4
|
+
export interface EvolutionCandidate {
|
|
5
|
+
id: string;
|
|
6
|
+
target: CandidateTarget;
|
|
7
|
+
/** the version this candidate is measured against (baseline pointer) */
|
|
8
|
+
baseVersion: string;
|
|
9
|
+
candidateVersion: string;
|
|
10
|
+
hypothesis: string;
|
|
11
|
+
/** metric the experiment reports on, e.g. 'bench.passRate' */
|
|
12
|
+
expectedMetric: string;
|
|
13
|
+
/** target-specific payload: skill markdown, prompt delta, router table… */
|
|
14
|
+
payload?: string;
|
|
15
|
+
/** who proposed it - 'agent' proposals on prompt/harness need human sign-off */
|
|
16
|
+
origin?: string;
|
|
17
|
+
createdAt: string;
|
|
18
|
+
}
|
|
19
|
+
export declare function registerCandidate(home: string, cand: Omit<EvolutionCandidate, 'id' | 'createdAt'> & {
|
|
20
|
+
id?: string;
|
|
21
|
+
}): Promise<EvolutionCandidate>;
|
|
22
|
+
export declare function listCandidates(home: string): Promise<EvolutionCandidate[]>;
|
|
23
|
+
export declare function getCandidate(home: string, id: string): Promise<EvolutionCandidate | null>;
|
|
24
|
+
/** Two-proportion two-sided test (treatment vs control pass rates). */
|
|
25
|
+
export declare function twoProportionTest(control: {
|
|
26
|
+
pass: number;
|
|
27
|
+
n: number;
|
|
28
|
+
}, treatment: {
|
|
29
|
+
pass: number;
|
|
30
|
+
n: number;
|
|
31
|
+
}): {
|
|
32
|
+
z: number;
|
|
33
|
+
p: number;
|
|
34
|
+
diff: number;
|
|
35
|
+
};
|
|
36
|
+
export interface ArmResult {
|
|
37
|
+
pass: boolean;
|
|
38
|
+
/** token cost of the arm run (cost-cap honesty, same currency as estTokens) */
|
|
39
|
+
tokens: number;
|
|
40
|
+
}
|
|
41
|
+
/** Injected by the caller: run one bench case under one arm. The runner owns
|
|
42
|
+
* the actual injection point (skills block, memory config, router table…). */
|
|
43
|
+
export type ArmRunner = (c: BenchCase, arm: 'control' | 'treatment') => Promise<ArmResult>;
|
|
44
|
+
export interface ExperimentArm {
|
|
45
|
+
pass: number;
|
|
46
|
+
n: number;
|
|
47
|
+
passRate: number;
|
|
48
|
+
tokens: number;
|
|
49
|
+
/** per-case rows (day-56): which case flipped is the point of a diff */
|
|
50
|
+
results?: Array<{
|
|
51
|
+
name: string;
|
|
52
|
+
pass: boolean;
|
|
53
|
+
tokens: number;
|
|
54
|
+
}>;
|
|
55
|
+
}
|
|
56
|
+
export interface ExperimentReport {
|
|
57
|
+
candidateId: string;
|
|
58
|
+
ranAt: string;
|
|
59
|
+
cases: number;
|
|
60
|
+
control: ExperimentArm;
|
|
61
|
+
treatment: ExperimentArm;
|
|
62
|
+
diff: number;
|
|
63
|
+
z: number;
|
|
64
|
+
p: number;
|
|
65
|
+
verdict: 'promote-eligible' | 'reject' | 'needs-data';
|
|
66
|
+
reason: string;
|
|
67
|
+
}
|
|
68
|
+
/** Per-arm minimum before any verdict counts (aligned with impact.ts canary
|
|
69
|
+
* threshold: >=8 sessions, and blueprint "one success is not significance"). */
|
|
70
|
+
export declare const MIN_ARM_N = 8;
|
|
71
|
+
export declare function verdictFor(control: {
|
|
72
|
+
pass: number;
|
|
73
|
+
n: number;
|
|
74
|
+
}, treatment: {
|
|
75
|
+
pass: number;
|
|
76
|
+
n: number;
|
|
77
|
+
}): {
|
|
78
|
+
verdict: ExperimentReport['verdict'];
|
|
79
|
+
reason: string;
|
|
80
|
+
z: number;
|
|
81
|
+
p: number;
|
|
82
|
+
diff: number;
|
|
83
|
+
};
|
|
84
|
+
export declare function runCandidateExperiment(home: string, candidateId: string, opts: {
|
|
85
|
+
runCase: ArmRunner;
|
|
86
|
+
cases: BenchCase[];
|
|
87
|
+
maxCases?: number;
|
|
88
|
+
}): Promise<ExperimentReport>;
|
|
89
|
+
/** Latest experiment report for a candidate (promotion evidence). */
|
|
90
|
+
export declare function latestExperiment(home: string, candidateId: string): Promise<ExperimentReport | null>;
|
|
91
|
+
export interface ActiveVersion {
|
|
92
|
+
target: CandidateTarget;
|
|
93
|
+
version: string;
|
|
94
|
+
candidateId: string;
|
|
95
|
+
since: string;
|
|
96
|
+
reportAt?: string;
|
|
97
|
+
}
|
|
98
|
+
export declare function activeVersions(home: string): Promise<Record<string, ActiveVersion>>;
|
|
99
|
+
export interface PromoteResult {
|
|
100
|
+
ok: boolean;
|
|
101
|
+
error?: string;
|
|
102
|
+
active?: ActiveVersion;
|
|
103
|
+
}
|
|
104
|
+
/** Blueprint gates, enforced: latest report must be promote-eligible, a
|
|
105
|
+
* previous pointer is written BEFORE activation, agent-origin prompt/harness
|
|
106
|
+
* candidates need approvedByHuman. Skill promotions ride the existing
|
|
107
|
+
* promoteSkill canary channel. */
|
|
108
|
+
export declare function promoteCandidate(home: string, candidateId: string, opts?: {
|
|
109
|
+
approvedByHuman?: boolean;
|
|
110
|
+
}): Promise<PromoteResult>;
|
|
111
|
+
export declare function rollbackCandidate(home: string, target: CandidateTarget): Promise<{
|
|
112
|
+
ok: boolean;
|
|
113
|
+
error?: string;
|
|
114
|
+
}>;
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hmharness/evolution - candidates (V2 M9: Evolution 泛化)
|
|
3
|
+
* Blueprint M9: a typed candidate registry (prompt/skill/context/tool_policy/
|
|
4
|
+
* model_router/workflow/harness), a Control/Treatment experiment runner,
|
|
5
|
+
* statistical comparison, and gated promotion/rollback. See ADR-0003.
|
|
6
|
+
*
|
|
7
|
+
* 红线 (blueprint 14.3, enforced here, not by convention):
|
|
8
|
+
* - 无实验报告(promote-eligible)不晋升 —— no baseline, no improvement claim
|
|
9
|
+
* - 激活前必写 previous 指针 —— no rollback, no promotion
|
|
10
|
+
* - origin=agent 的 prompt/harness 候选需人工标记才可激活 —— agents never
|
|
11
|
+
* self-modify the production prompt
|
|
12
|
+
* - 晋升判据是双比例检验,LLM self-report 无效力 —— M2 证据阶梯双保险
|
|
13
|
+
*/
|
|
14
|
+
import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
|
|
15
|
+
import { join } from 'node:path';
|
|
16
|
+
import { screenForPoison } from "./evolve.js";
|
|
17
|
+
export const CANDIDATE_TARGETS = [
|
|
18
|
+
'prompt', 'skill', 'context', 'tool_policy', 'model_router', 'workflow', 'harness',
|
|
19
|
+
];
|
|
20
|
+
/* ---------------- registry ---------------- */
|
|
21
|
+
function candDir(home) {
|
|
22
|
+
return join(home, 'evolution', 'candidates');
|
|
23
|
+
}
|
|
24
|
+
export async function registerCandidate(home, cand) {
|
|
25
|
+
if (!CANDIDATE_TARGETS.includes(cand.target))
|
|
26
|
+
throw new Error(`unknown candidate target: ${cand.target}`);
|
|
27
|
+
if (!cand.hypothesis.trim() || !cand.candidateVersion.trim())
|
|
28
|
+
throw new Error('candidate needs a hypothesis and a candidateVersion');
|
|
29
|
+
const poison = screenForPoison(cand.hypothesis + '\n' + (cand.payload ?? ''));
|
|
30
|
+
if (poison)
|
|
31
|
+
throw new Error(`candidate rejected by safety screen: ${poison}`);
|
|
32
|
+
const full = {
|
|
33
|
+
...cand,
|
|
34
|
+
id: cand.id ?? `cand_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`,
|
|
35
|
+
createdAt: new Date().toISOString(),
|
|
36
|
+
};
|
|
37
|
+
await mkdir(candDir(home), { recursive: true });
|
|
38
|
+
await writeFile(join(candDir(home), `${full.id}.json`), JSON.stringify(full, null, 2) + '\n', 'utf8');
|
|
39
|
+
return full;
|
|
40
|
+
}
|
|
41
|
+
export async function listCandidates(home) {
|
|
42
|
+
let files = [];
|
|
43
|
+
try {
|
|
44
|
+
files = (await readdir(candDir(home))).filter((f) => f.endsWith('.json'));
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return [];
|
|
48
|
+
}
|
|
49
|
+
const out = [];
|
|
50
|
+
for (const f of files) {
|
|
51
|
+
try {
|
|
52
|
+
out.push(JSON.parse(await readFile(join(candDir(home), f), 'utf8')));
|
|
53
|
+
}
|
|
54
|
+
catch { /* skip torn */ }
|
|
55
|
+
}
|
|
56
|
+
return out.sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1));
|
|
57
|
+
}
|
|
58
|
+
export async function getCandidate(home, id) {
|
|
59
|
+
try {
|
|
60
|
+
return JSON.parse(await readFile(join(candDir(home), `${id}.json`), 'utf8'));
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/* ---------------- statistics ---------------- */
|
|
67
|
+
/** Standard normal CDF, Zelen & Severo approximation of A&S 26.2.17 (|err|<7.5e-8). */
|
|
68
|
+
function normalCdf(z) {
|
|
69
|
+
const t = 1 / (1 + 0.2316419 * Math.abs(z));
|
|
70
|
+
const d = Math.exp(-z * z / 2) / Math.sqrt(2 * Math.PI);
|
|
71
|
+
const poly = t * (0.319381530 + t * (-0.356563782 + t * (1.781477937 + t * (-1.821255978 + t * 1.330274429))));
|
|
72
|
+
const upper = d * poly; // P(Z > |z|) tail
|
|
73
|
+
return z >= 0 ? 1 - upper : upper;
|
|
74
|
+
}
|
|
75
|
+
/** Two-proportion two-sided test (treatment vs control pass rates). */
|
|
76
|
+
export function twoProportionTest(control, treatment) {
|
|
77
|
+
if (control.n <= 0 || treatment.n <= 0)
|
|
78
|
+
return { z: 0, p: 1, diff: 0 };
|
|
79
|
+
const pc = control.pass / control.n;
|
|
80
|
+
const pt = treatment.pass / treatment.n;
|
|
81
|
+
const pool = (control.pass + treatment.pass) / (control.n + treatment.n);
|
|
82
|
+
const se = Math.sqrt(pool * (1 - pool) * (1 / control.n + 1 / treatment.n));
|
|
83
|
+
const z = se > 0 ? (pt - pc) / se : 0;
|
|
84
|
+
return { z, p: 2 * (1 - normalCdf(Math.abs(z))), diff: pt - pc };
|
|
85
|
+
}
|
|
86
|
+
/** Per-arm minimum before any verdict counts (aligned with impact.ts canary
|
|
87
|
+
* threshold: >=8 sessions, and blueprint "one success is not significance"). */
|
|
88
|
+
export const MIN_ARM_N = 8;
|
|
89
|
+
export function verdictFor(control, treatment) {
|
|
90
|
+
const { z, p, diff } = twoProportionTest(control, treatment);
|
|
91
|
+
if (control.n < MIN_ARM_N || treatment.n < MIN_ARM_N) {
|
|
92
|
+
return { verdict: 'needs-data', reason: `samples below ${MIN_ARM_N} per arm (control ${control.n}, treatment ${treatment.n})`, z, p, diff };
|
|
93
|
+
}
|
|
94
|
+
if (p < 0.05 && diff >= 0.10)
|
|
95
|
+
return { verdict: 'promote-eligible', reason: `significant lift (p=${p.toFixed(4)}, diff=${(diff * 100).toFixed(1)}%)`, z, p, diff };
|
|
96
|
+
if ((p < 0.05 && diff <= -0.05) || diff <= -0.10) {
|
|
97
|
+
return { verdict: 'reject', reason: `regression (p=${p.toFixed(4)}, diff=${(diff * 100).toFixed(1)}%)`, z, p, diff };
|
|
98
|
+
}
|
|
99
|
+
return { verdict: 'needs-data', reason: `no significant difference (p=${p.toFixed(4)}, diff=${(diff * 100).toFixed(1)}%)`, z, p, diff };
|
|
100
|
+
}
|
|
101
|
+
export async function runCandidateExperiment(home, candidateId, opts) {
|
|
102
|
+
const cand = await getCandidate(home, candidateId);
|
|
103
|
+
if (!cand)
|
|
104
|
+
throw new Error(`no candidate: ${candidateId}`);
|
|
105
|
+
// holdout cases are excluded from promotion gates (bench.ts anti-memorization)
|
|
106
|
+
const gate = opts.cases.filter((c) => !c.holdout).slice(0, Math.max(1, opts.maxCases ?? 12));
|
|
107
|
+
let cPass = 0, cTok = 0, tPass = 0, tTok = 0;
|
|
108
|
+
// per-case rows (day-56 observability: which case flipped is the whole
|
|
109
|
+
// point of a diff - aggregates alone cannot answer it)
|
|
110
|
+
const ctlRows = [];
|
|
111
|
+
const trtRows = [];
|
|
112
|
+
for (const c of gate) {
|
|
113
|
+
const ctl = await opts.runCase(c, 'control');
|
|
114
|
+
if (ctl.pass)
|
|
115
|
+
cPass++;
|
|
116
|
+
cTok += ctl.tokens;
|
|
117
|
+
ctlRows.push({ name: c.name, pass: ctl.pass, tokens: ctl.tokens });
|
|
118
|
+
const trt = await opts.runCase(c, 'treatment');
|
|
119
|
+
if (trt.pass)
|
|
120
|
+
tPass++;
|
|
121
|
+
tTok += trt.tokens;
|
|
122
|
+
trtRows.push({ name: c.name, pass: trt.pass, tokens: trt.tokens });
|
|
123
|
+
}
|
|
124
|
+
const v = verdictFor({ pass: cPass, n: gate.length }, { pass: tPass, n: gate.length });
|
|
125
|
+
const report = {
|
|
126
|
+
candidateId,
|
|
127
|
+
ranAt: new Date().toISOString(),
|
|
128
|
+
cases: gate.length,
|
|
129
|
+
control: { pass: cPass, n: gate.length, passRate: gate.length ? cPass / gate.length : 0, tokens: cTok, results: ctlRows },
|
|
130
|
+
treatment: { pass: tPass, n: gate.length, passRate: gate.length ? tPass / gate.length : 0, tokens: tTok, results: trtRows },
|
|
131
|
+
...v,
|
|
132
|
+
};
|
|
133
|
+
const dir = join(home, 'evolution', 'experiments', candidateId);
|
|
134
|
+
await mkdir(dir, { recursive: true });
|
|
135
|
+
await writeFile(join(dir, `${report.ranAt.replace(/[:.]/g, '-')}.json`), JSON.stringify(report, null, 2) + '\n', 'utf8');
|
|
136
|
+
return report;
|
|
137
|
+
}
|
|
138
|
+
/** Latest experiment report for a candidate (promotion evidence). */
|
|
139
|
+
export async function latestExperiment(home, candidateId) {
|
|
140
|
+
const dir = join(home, 'evolution', 'experiments', candidateId);
|
|
141
|
+
let files = [];
|
|
142
|
+
try {
|
|
143
|
+
files = (await readdir(dir)).filter((f) => f.endsWith('.json')).sort();
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
if (files.length === 0)
|
|
149
|
+
return null;
|
|
150
|
+
try {
|
|
151
|
+
return JSON.parse(await readFile(join(dir, files[files.length - 1]), 'utf8'));
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const activeDir = (home) => join(home, 'evolution', 'active');
|
|
158
|
+
export async function activeVersions(home) {
|
|
159
|
+
const out = {};
|
|
160
|
+
let files = [];
|
|
161
|
+
try {
|
|
162
|
+
files = await readdir(activeDir(home));
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
return out;
|
|
166
|
+
}
|
|
167
|
+
for (const f of files.filter((f) => f.endsWith('.json') && !f.endsWith('.previous.json'))) {
|
|
168
|
+
try {
|
|
169
|
+
const v = JSON.parse(await readFile(join(activeDir(home), f), 'utf8'));
|
|
170
|
+
out[v.target] = v;
|
|
171
|
+
}
|
|
172
|
+
catch { /* skip torn */ }
|
|
173
|
+
}
|
|
174
|
+
return out;
|
|
175
|
+
}
|
|
176
|
+
/** Blueprint gates, enforced: latest report must be promote-eligible, a
|
|
177
|
+
* previous pointer is written BEFORE activation, agent-origin prompt/harness
|
|
178
|
+
* candidates need approvedByHuman. Skill promotions ride the existing
|
|
179
|
+
* promoteSkill canary channel. */
|
|
180
|
+
export async function promoteCandidate(home, candidateId, opts = {}) {
|
|
181
|
+
const cand = await getCandidate(home, candidateId);
|
|
182
|
+
if (!cand)
|
|
183
|
+
return { ok: false, error: `no candidate: ${candidateId}` };
|
|
184
|
+
const report = await latestExperiment(home, candidateId);
|
|
185
|
+
if (!report)
|
|
186
|
+
return { ok: false, error: 'no experiment report - run the experiment first (no baseline, no promotion)' };
|
|
187
|
+
if (report.verdict !== 'promote-eligible') {
|
|
188
|
+
return { ok: false, error: `latest report verdict is ${report.verdict} (${report.reason}) - not promotable` };
|
|
189
|
+
}
|
|
190
|
+
if ((cand.target === 'prompt' || cand.target === 'harness') && cand.origin === 'agent' && !opts.approvedByHuman) {
|
|
191
|
+
return { ok: false, error: 'agent-origin prompt/harness candidate requires approvedByHuman (production prompt is not agent-writable)' };
|
|
192
|
+
}
|
|
193
|
+
await mkdir(activeDir(home), { recursive: true });
|
|
194
|
+
const cur = await activeVersions(home);
|
|
195
|
+
const previous = cur[cand.target];
|
|
196
|
+
if (previous) {
|
|
197
|
+
await writeFile(join(activeDir(home), `${cand.target}.previous.json`), JSON.stringify(previous, null, 2) + '\n', 'utf8');
|
|
198
|
+
}
|
|
199
|
+
if (cand.target === 'skill') {
|
|
200
|
+
// payload = skill name; the audited canary channel stays the only skill path
|
|
201
|
+
const { promoteSkill } = await import("./skills.js");
|
|
202
|
+
if (!cand.payload)
|
|
203
|
+
return { ok: false, error: 'skill candidate has no payload (skill name)' };
|
|
204
|
+
await promoteSkill(home, cand.payload, { canary: true });
|
|
205
|
+
}
|
|
206
|
+
const active = {
|
|
207
|
+
target: cand.target,
|
|
208
|
+
version: cand.candidateVersion,
|
|
209
|
+
candidateId: cand.id,
|
|
210
|
+
since: new Date().toISOString(),
|
|
211
|
+
reportAt: report.ranAt,
|
|
212
|
+
};
|
|
213
|
+
await writeFile(join(activeDir(home), `${cand.target}.json`), JSON.stringify(active, null, 2) + '\n', 'utf8');
|
|
214
|
+
return { ok: true, active };
|
|
215
|
+
}
|
|
216
|
+
export async function rollbackCandidate(home, target) {
|
|
217
|
+
const dir = activeDir(home);
|
|
218
|
+
const prevPath = join(dir, `${target}.previous.json`);
|
|
219
|
+
let previous = null;
|
|
220
|
+
try {
|
|
221
|
+
previous = JSON.parse(await readFile(prevPath, 'utf8'));
|
|
222
|
+
}
|
|
223
|
+
catch { /* no previous */ }
|
|
224
|
+
if (!previous)
|
|
225
|
+
return { ok: false, error: `no previous pointer for ${target} - nothing to roll back to` };
|
|
226
|
+
if (target === 'skill') {
|
|
227
|
+
const { rollbackSkill } = await import("./skills.js");
|
|
228
|
+
await rollbackSkill(home, previous.version);
|
|
229
|
+
}
|
|
230
|
+
await writeFile(join(dir, `${target}.json`), JSON.stringify(previous, null, 2) + '\n', 'utf8');
|
|
231
|
+
return { ok: true };
|
|
232
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
export interface DatasetSample {
|
|
2
|
+
runId: string;
|
|
3
|
+
task: string;
|
|
4
|
+
outcome: string;
|
|
5
|
+
turns: number;
|
|
6
|
+
toolUses: number;
|
|
7
|
+
toolFailRate: number;
|
|
8
|
+
toolsUsed: string[];
|
|
9
|
+
model: string;
|
|
10
|
+
/** evidence rank from the M2 ladder when the run was evaluated (0 = none) */
|
|
11
|
+
evidenceRank: number;
|
|
12
|
+
/** interpretable reward in [0,1]; llm-judged runs never reach 1.0 (M2 cap) */
|
|
13
|
+
reward: number;
|
|
14
|
+
/** evaluation notes / failure snippets attach here (bounded) */
|
|
15
|
+
evidence?: string;
|
|
16
|
+
split: 'train' | 'eval';
|
|
17
|
+
}
|
|
18
|
+
export interface DatasetManifest {
|
|
19
|
+
version: string;
|
|
20
|
+
createdAt: string;
|
|
21
|
+
/** inclusive run-id scan window (first..last seen, lexicographic) */
|
|
22
|
+
runWindow: {
|
|
23
|
+
first: string | null;
|
|
24
|
+
last: string | null;
|
|
25
|
+
};
|
|
26
|
+
filterFingerprint: string;
|
|
27
|
+
splitSeed: number;
|
|
28
|
+
splitRatio: number;
|
|
29
|
+
counts: {
|
|
30
|
+
scanned: number;
|
|
31
|
+
kept: number;
|
|
32
|
+
dropped: number;
|
|
33
|
+
duplicates: number;
|
|
34
|
+
train: number;
|
|
35
|
+
eval: number;
|
|
36
|
+
};
|
|
37
|
+
rewardHistogram: Record<string, number>;
|
|
38
|
+
}
|
|
39
|
+
export interface DatasetBuildResult {
|
|
40
|
+
manifest: DatasetManifest;
|
|
41
|
+
dir: string;
|
|
42
|
+
}
|
|
43
|
+
/** Interpretable reward mapping (ADR-0004): ok runs start at 1.0 and lose
|
|
44
|
+
* 0.1 per 20% tool-failure rate; non-ok runs cap at 0.3. Evidence rank
|
|
45
|
+
* from the M2 ladder nudges confidence but never creates a free perfect. */
|
|
46
|
+
export declare function rewardFor(outcome: string, toolFailRate: number, evidenceRank?: number): number;
|
|
47
|
+
/** Stable fingerprint of the filter config - manifest must be reproducible. */
|
|
48
|
+
export declare function filterFingerprint(opts: {
|
|
49
|
+
keepOutcome?: string[];
|
|
50
|
+
minTurns?: number;
|
|
51
|
+
}): string;
|
|
52
|
+
/** Deterministic hash-based split (same run always lands in the same half). */
|
|
53
|
+
export declare function splitFor(runId: string, seed: number, evalRatio?: number): 'train' | 'eval';
|
|
54
|
+
export interface BuildDatasetOptions {
|
|
55
|
+
version?: string;
|
|
56
|
+
/** outcomes to keep; default keeps everything labeled */
|
|
57
|
+
keepOutcome?: string[];
|
|
58
|
+
minTurns?: number;
|
|
59
|
+
evalRatio?: number;
|
|
60
|
+
splitSeed?: number;
|
|
61
|
+
}
|
|
62
|
+
export declare function buildDataset(home: string, opts?: BuildDatasetOptions): Promise<DatasetBuildResult>;
|
|
63
|
+
export declare function listDatasets(home: string): Promise<DatasetManifest[]>;
|
|
64
|
+
export declare function loadDataset(home: string, version: string, split?: 'train' | 'eval'): Promise<DatasetSample[]>;
|