@hmharness/evolution 0.14.9 → 0.14.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/index.d.ts +2 -0
  2. package/dist/index.js +2 -0
  3. package/dist/judge.d.ts +65 -0
  4. package/dist/judge.js +194 -0
  5. package/dist/reward-model.d.ts +66 -0
  6. package/dist/reward-model.js +187 -0
  7. package/package.json +2 -2
  8. package/dist/bench.d.ts.v2bak.v2bak +0 -44
  9. package/dist/bench.js.v2bak.v2bak +0 -156
  10. package/dist/candidates.d.ts.v2bak.v2bak +0 -114
  11. package/dist/candidates.js.v2bak.v2bak +0 -232
  12. package/dist/dataset.d.ts.v2bak.v2bak +0 -64
  13. package/dist/dataset.js.v2bak.v2bak +0 -184
  14. package/dist/evolve.d.ts.v2bak.v2bak +0 -98
  15. package/dist/evolve.js.v2bak.v2bak +0 -573
  16. package/dist/impact.d.ts.v2bak.v2bak +0 -77
  17. package/dist/impact.js.v2bak.v2bak +0 -214
  18. package/dist/index.d.ts.v2bak.v2bak +0 -16
  19. package/dist/index.js.v2bak.v2bak +0 -16
  20. package/dist/insights.d.ts.v2bak.v2bak +0 -18
  21. package/dist/insights.js.v2bak.v2bak +0 -80
  22. package/dist/knowledge.d.ts.v2bak.v2bak +0 -15
  23. package/dist/knowledge.js.v2bak.v2bak +0 -145
  24. package/dist/labels.d.ts.v2bak.v2bak +0 -20
  25. package/dist/labels.js.v2bak.v2bak +0 -57
  26. package/dist/memory.d.ts.v2bak.v2bak +0 -32
  27. package/dist/memory.js.v2bak.v2bak +0 -233
  28. package/dist/patches.d.ts.v2bak.v2bak +0 -83
  29. package/dist/patches.js.v2bak.v2bak +0 -253
  30. package/dist/radar.d.ts.v2bak.v2bak +0 -3
  31. package/dist/radar.js.v2bak.v2bak +0 -40
  32. package/dist/ranker.d.ts.v2bak.v2bak +0 -44
  33. package/dist/ranker.js.v2bak.v2bak +0 -55
  34. package/dist/readiness.d.ts.v2bak.v2bak +0 -15
  35. package/dist/readiness.js.v2bak.v2bak +0 -167
  36. package/dist/skillpayload.d.ts.v2bak.v2bak +0 -1
  37. package/dist/skillpayload.js.v2bak +0 -28
  38. package/dist/skillpayload.js.v2bak.v2bak.v2bak +0 -28
  39. package/dist/skills.d.ts.v2bak.v2bak +0 -54
  40. package/dist/skills.js.v2bak.v2bak +0 -321
  41. package/dist/workflows.d.ts.v2bak.v2bak +0 -28
  42. package/dist/workflows.js.v2bak.v2bak +0 -84
@@ -1,184 +0,0 @@
1
- /**
2
- * @hmharness/evolution - dataset (V2 M10: Trajectory → Dataset Version)
3
- * Pure data engineering, zero model calls. Pipeline per blueprint:
4
- * Trajectory → Filter → Deduplicate → Label → Evidence Attach → Reward
5
- * → Dataset Version → Train/Eval Split
6
- * Source of truth: HMH_HOME/runs/<run-id>/ (M1 trajectory recorder's
7
- * summary.json + trajectory.jsonl). Output: versioned, redacted, split
8
- * under evolution/datasets/<version>/. See ADR-0004.
9
- */
10
- import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
11
- import { createHash } from 'node:crypto';
12
- import { join } from 'node:path';
13
- import { redactSecrets } from "./insights.js";
14
- const RUNS_DIR = 'runs';
15
- /** Interpretable reward mapping (ADR-0004): ok runs start at 1.0 and lose
16
- * 0.1 per 20% tool-failure rate; non-ok runs cap at 0.3. Evidence rank
17
- * from the M2 ladder nudges confidence but never creates a free perfect. */
18
- export function rewardFor(outcome, toolFailRate, evidenceRank = 0) {
19
- let r;
20
- if (outcome === 'ok') {
21
- r = 1.0 - Math.min(0.6, Math.round(toolFailRate * 10) / 10);
22
- }
23
- else {
24
- r = Math.max(0, 0.3 - Math.round(toolFailRate * 10) / 10);
25
- }
26
- // llm-judge ladder ranks (5+) can never mint a perfect sample
27
- if (evidenceRank >= 5)
28
- r = Math.min(r, 0.7);
29
- return Math.max(0, Math.min(1, r));
30
- }
31
- /** Stable fingerprint of the filter config - manifest must be reproducible. */
32
- export function filterFingerprint(opts) {
33
- return createHash('sha256').update(JSON.stringify({
34
- keepOutcome: opts.keepOutcome ?? ['ok', 'turn-budget', 'error'],
35
- minTurns: opts.minTurns ?? 1,
36
- redact: true,
37
- })).digest('hex').slice(0, 12);
38
- }
39
- /** Normalize both the recorder schema (outcome object + metrics block) and
40
- * the flat test/hand-written shape into one view. */
41
- function normalizeSummary(s) {
42
- const outcome = typeof s.outcome === 'string'
43
- ? s.outcome
44
- : (s.outcome?.success ? 'ok' : String(s.outcome?.reason ?? ''));
45
- return {
46
- task: String(s.task ?? ''),
47
- outcome,
48
- turns: Number(s.turns ?? s.metrics?.turns ?? 0),
49
- toolUses: Number(s.toolUses ?? s.metrics?.toolUses ?? 0),
50
- toolFailures: Number(s.toolFailures ?? s.metrics?.toolFailures ?? 0),
51
- toolsUsed: s.toolsUsed ?? [],
52
- model: String(s.model ?? ''),
53
- rank: Number(s.evidence?.rank ?? 0),
54
- detail: String(s.evidence?.detail ?? ''),
55
- };
56
- }
57
- async function readRunSummaries(home) {
58
- const root = join(home, RUNS_DIR);
59
- let ids = [];
60
- try {
61
- ids = (await readdir(root)).filter((d) => !d.startsWith('.'));
62
- }
63
- catch {
64
- return [];
65
- }
66
- ids.sort();
67
- const out = [];
68
- for (const id of ids) {
69
- try {
70
- const s = JSON.parse(await readFile(join(root, id, 'summary.json'), 'utf8'));
71
- out.push({ runId: id, summary: s });
72
- }
73
- catch { /* torn or absent summary - not a dataset candidate */ }
74
- }
75
- return out;
76
- }
77
- /** Deterministic hash-based split (same run always lands in the same half). */
78
- export function splitFor(runId, seed, evalRatio = 0.2) {
79
- const h = createHash('sha256').update(`${seed}:${runId}`).digest();
80
- const v = h.readUInt32BE(0) / 0xffffffff;
81
- return v < evalRatio ? 'eval' : 'train';
82
- }
83
- export async function buildDataset(home, opts = {}) {
84
- const keep = opts.keepOutcome ?? ['ok', 'turn-budget', 'error'];
85
- const minTurns = opts.minTurns ?? 1;
86
- const evalRatio = opts.evalRatio ?? 0.2;
87
- const seed = opts.splitSeed ?? 20260913;
88
- const runs = await readRunSummaries(home);
89
- const fp = filterFingerprint({ keepOutcome: keep, minTurns });
90
- const byFingerprint = new Map();
91
- let dropped = 0;
92
- let duplicates = 0;
93
- for (const { runId, summary } of runs) {
94
- const n = normalizeSummary(summary);
95
- if (!n.outcome || !keep.includes(n.outcome) || n.turns < minTurns) {
96
- dropped++;
97
- continue;
98
- }
99
- const fpRun = createHash('sha256').update(`${n.task}|${n.outcome}|${n.turns}|${n.toolsUsed.join(',')}`, 'utf8').digest('hex').slice(0, 16);
100
- if (byFingerprint.has(fpRun)) {
101
- duplicates++;
102
- continue;
103
- } // keep first (oldest) - newest is a rerun of the same shape
104
- byFingerprint.set(fpRun, { runId, summary });
105
- }
106
- const samples = [];
107
- const histogram = {};
108
- for (const { runId, summary } of byFingerprint.values()) {
109
- const n = normalizeSummary(summary);
110
- const failRate = n.toolUses > 0 ? n.toolFailures / n.toolUses : 0;
111
- const reward = rewardFor(n.outcome, failRate, n.rank);
112
- const bucket = reward.toFixed(1);
113
- histogram[bucket] = (histogram[bucket] ?? 0) + 1;
114
- samples.push({
115
- runId,
116
- task: redactSecrets(n.task),
117
- outcome: n.outcome,
118
- turns: n.turns,
119
- toolUses: n.toolUses,
120
- toolFailRate: Math.round(failRate * 100) / 100,
121
- toolsUsed: n.toolsUsed,
122
- model: n.model,
123
- evidenceRank: n.rank,
124
- reward,
125
- ...(n.detail ? { evidence: redactSecrets(n.detail).slice(0, 400) } : {}),
126
- split: splitFor(runId, seed, evalRatio),
127
- });
128
- }
129
- samples.sort((a, b) => (a.runId < b.runId ? -1 : 1));
130
- const version = opts.version ?? `v-${new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)}`;
131
- const dir = join(home, 'evolution', 'datasets', version);
132
- await mkdir(dir, { recursive: true });
133
- await writeFile(join(dir, 'samples.jsonl'), samples.map((s) => JSON.stringify(s)).join('\n') + (samples.length ? '\n' : ''), 'utf8');
134
- const manifest = {
135
- version,
136
- createdAt: new Date().toISOString(),
137
- runWindow: { first: runs[0]?.runId ?? null, last: runs[runs.length - 1]?.runId ?? null },
138
- filterFingerprint: fp,
139
- splitSeed: seed,
140
- splitRatio: evalRatio,
141
- counts: {
142
- scanned: runs.length,
143
- kept: samples.length,
144
- dropped,
145
- duplicates,
146
- train: samples.filter((s) => s.split === 'train').length,
147
- eval: samples.filter((s) => s.split === 'eval').length,
148
- },
149
- rewardHistogram: histogram,
150
- };
151
- await writeFile(join(dir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n', 'utf8');
152
- return { manifest, dir };
153
- }
154
- export async function listDatasets(home) {
155
- const root = join(home, 'evolution', 'datasets');
156
- let vers = [];
157
- try {
158
- vers = (await readdir(root)).filter((d) => d.startsWith('v-'));
159
- }
160
- catch {
161
- return [];
162
- }
163
- vers.sort();
164
- const out = [];
165
- for (const v of vers) {
166
- try {
167
- out.push(JSON.parse(await readFile(join(root, v, 'manifest.json'), 'utf8')));
168
- }
169
- catch { /* skip torn */ }
170
- }
171
- return out;
172
- }
173
- export async function loadDataset(home, version, split) {
174
- const file = join(home, 'evolution', 'datasets', version, 'samples.jsonl');
175
- let text;
176
- try {
177
- text = await readFile(file, 'utf8');
178
- }
179
- catch {
180
- return [];
181
- }
182
- return text.split('\n').filter(Boolean).map((l) => JSON.parse(l))
183
- .filter((s) => !split || s.split === split);
184
- }
@@ -1,98 +0,0 @@
1
- import { type ProviderConfig } from '@hmharness/kernel';
2
- import { type BenchCase } from './bench.ts';
3
- export interface SkillProposal {
4
- name: string;
5
- description: string;
6
- skill_md: string;
7
- }
8
- export interface ProposalOutcome {
9
- name: string;
10
- action: 'promoted' | 'rejected' | 'error';
11
- reason: string;
12
- baseline?: {
13
- passRate: number;
14
- cases: string;
15
- };
16
- candidate?: {
17
- passRate: number;
18
- cases: string;
19
- };
20
- holdout?: {
21
- baselineRate: number;
22
- candidateRate: number;
23
- };
24
- /** P0 lineage ledger: what fed this decision (provenance for impact
25
- * attribution - which insights produced which skill, with which scores).
26
- * Evolution-artifact genealogy is the GEPA/DGM archive lesson: decisions
27
- * without ancestry cannot be audited for objective hacking. */
28
- lineage?: {
29
- parentInsights: string[];
30
- scores: {
31
- train: number;
32
- holdout?: number;
33
- };
34
- metaModel: string;
35
- decidedAt: string;
36
- };
37
- }
38
- export interface EvolveReport {
39
- time: string;
40
- model: string;
41
- seededCases: string[];
42
- insightCount: number;
43
- noteCount: number;
44
- proposals: SkillProposal[];
45
- outcomes: ProposalOutcome[];
46
- memoryDistilled: string | null;
47
- /** code-level evolution: proposed patches (DGM bridge) */
48
- codePatches?: Array<{
49
- name: string;
50
- file: string;
51
- reason: string;
52
- }>;
53
- /** code-level outcomes: merged/reverted/error per patch */
54
- patchOutcomes?: Array<{
55
- name: string;
56
- action: string;
57
- reason: string;
58
- branch?: string;
59
- }>;
60
- /** P0 impact attribution: canary A/B comparison applied this cycle */
61
- impact?: {
62
- rows: Array<{
63
- skill: string;
64
- exposed: string;
65
- control: string;
66
- verdict: string;
67
- }>;
68
- applied: string[];
69
- };
70
- /** P1 lifecycle: skills moved to dormant this cycle */
71
- decayed?: string[];
72
- /** budget state at cycle start (observability) */
73
- budget?: {
74
- cyclesToday: number;
75
- maxCyclesPerDay?: number;
76
- };
77
- /** chars/4 estimate of this cycle's meta-call traffic; feeds the daily
78
- * token budget gate (readBudget sums today's entries) */
79
- estTokens?: number;
80
- }
81
- /** Runs one bench case with the given skills block injected. */
82
- export type CaseRunner = (c: BenchCase, skillsPrompt: string) => Promise<string>;
83
- /** Rough token estimate, language-aware: ASCII runs ~4 chars/token, CJK
84
- * ~1 char/token. A flat chars/4 undercounted Chinese 2-4x, letting verbose
85
- * zh candidates dodge the cost cap. Used on BOTH sides of every comparison
86
- * (baseline and candidate), never as the only rejection reason (the
87
- * pass-rate gate decides; cost-cap only vetoes pass-by-rambling). */
88
- export declare function estTokens(text: string): number;
89
- export declare function runEvolution(opts: {
90
- home: string;
91
- provider: ProviderConfig;
92
- runCase: CaseRunner;
93
- maxProposals?: number;
94
- /** Skip the meta-model call and evaluate these proposals directly (tests / future UIs). */
95
- presetProposals?: SkillProposal[];
96
- log?: (line: string) => void;
97
- }): Promise<EvolveReport>;
98
- export declare function screenForPoison(text: string): string | null;