@hmharness/cognitive 0.19.0
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/benchmark.d.ts +80 -0
- package/dist/benchmark.js +85 -0
- package/dist/continual.d.ts +90 -0
- package/dist/continual.js +142 -0
- package/dist/evolution2.d.ts +93 -0
- package/dist/evolution2.js +181 -0
- package/dist/exploration.d.ts +106 -0
- package/dist/exploration.js +182 -0
- package/dist/goal.d.ts +97 -0
- package/dist/goal.js +133 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.js +24 -0
- package/dist/memory.d.ts +64 -0
- package/dist/memory.js +200 -0
- package/dist/multi-agent.d.ts +118 -0
- package/dist/multi-agent.js +119 -0
- package/dist/protocol.d.ts +155 -0
- package/dist/protocol.js +103 -0
- package/dist/registry.d.ts +75 -0
- package/dist/registry.js +195 -0
- package/dist/rlm.d.ts +88 -0
- package/dist/rlm.js +139 -0
- package/dist/skill-compiler.d.ts +81 -0
- package/dist/skill-compiler.js +124 -0
- package/dist/status.d.ts +20 -0
- package/dist/status.js +76 -0
- package/dist/trajectory.d.ts +54 -0
- package/dist/trajectory.js +112 -0
- package/dist/world-model.d.ts +146 -0
- package/dist/world-model.js +219 -0
- package/package.json +31 -0
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hmharness/cognitive - GeneralBench schema + Transfer lab (blueprint §12/§13/§17)
|
|
3
|
+
*
|
|
4
|
+
* GeneralBench (BENCH-001..012): a track registry where every track is a
|
|
5
|
+
* runnable suite with UNIFORM metrics — success, action efficiency,
|
|
6
|
+
* recovery, calibration, transfer delta, cost, latency (blueprint §12 指标
|
|
7
|
+
* must-include list). Tracks are host-supplied; the runner computes the
|
|
8
|
+
* uniform metric layer so cross-track comparison is honest.
|
|
9
|
+
*
|
|
10
|
+
* Transfer lab (TR-001..007): Transfer Score = performance gain in a TARGET
|
|
11
|
+
* environment given skills/policy learned in a SOURCE environment, vs a
|
|
12
|
+
* from-scratch baseline. Negative transfer (learned policy hurts) is a
|
|
13
|
+
* first-class outcome, not an error.
|
|
14
|
+
*/
|
|
15
|
+
import type { CognitiveTrajectory } from './protocol.js';
|
|
16
|
+
export type BenchTrackId = 'software' | 'computer-use' | 'research' | 'planning' | 'exploration' | 'memory' | 'world-model' | 'long-horizon' | 'transfer' | 'open-ended';
|
|
17
|
+
export interface BenchCase {
|
|
18
|
+
id: string;
|
|
19
|
+
track: BenchTrackId;
|
|
20
|
+
/** the task as given to the agent */
|
|
21
|
+
prompt: string;
|
|
22
|
+
environmentId: string;
|
|
23
|
+
/** host-resolved checker: the ground truth, never the agent's own word */
|
|
24
|
+
verify: (traj: CognitiveTrajectory) => Promise<{
|
|
25
|
+
pass: boolean;
|
|
26
|
+
note?: string;
|
|
27
|
+
}>;
|
|
28
|
+
/** action-count budget before efficiency starts decaying */
|
|
29
|
+
actionBudget: number;
|
|
30
|
+
}
|
|
31
|
+
export interface UniformMetrics {
|
|
32
|
+
success: number;
|
|
33
|
+
actionEfficiency: number;
|
|
34
|
+
recoveryRate: number;
|
|
35
|
+
calibration: number;
|
|
36
|
+
predicted: boolean;
|
|
37
|
+
costUnits: number;
|
|
38
|
+
latencyMs: number;
|
|
39
|
+
}
|
|
40
|
+
export interface CaseRun {
|
|
41
|
+
caseId: string;
|
|
42
|
+
metrics: UniformMetrics;
|
|
43
|
+
note?: string;
|
|
44
|
+
}
|
|
45
|
+
export interface TrackReport {
|
|
46
|
+
track: BenchTrackId;
|
|
47
|
+
runs: CaseRun[];
|
|
48
|
+
aggregate: Record<string, number>;
|
|
49
|
+
}
|
|
50
|
+
/** BENCH-001. The registry: tracks register cases; the runner normalizes. */
|
|
51
|
+
export declare class GeneralBench {
|
|
52
|
+
private cases;
|
|
53
|
+
register(case_: BenchCase): void;
|
|
54
|
+
list(): BenchCase[];
|
|
55
|
+
listByTrack(track: BenchTrackId): BenchCase[];
|
|
56
|
+
runCase(caseId: string, traj: CognitiveTrajectory): Promise<CaseRun>;
|
|
57
|
+
runTrack(track: BenchTrackId, trajectories: Map<string, CognitiveTrajectory>): Promise<TrackReport>;
|
|
58
|
+
}
|
|
59
|
+
export declare function uniformMetrics(traj: CognitiveTrajectory, actionBudget: number): UniformMetrics;
|
|
60
|
+
export interface TransferCell {
|
|
61
|
+
sourceEnv: string;
|
|
62
|
+
targetEnv: string;
|
|
63
|
+
/** success rate in target WITH the source-learned policy/skill/memory */
|
|
64
|
+
withTransfer: number;
|
|
65
|
+
/** success rate in target from scratch (no carry-over) */
|
|
66
|
+
fromScratch: number;
|
|
67
|
+
samplesWith: number;
|
|
68
|
+
samplesWithout: number;
|
|
69
|
+
}
|
|
70
|
+
export interface TransferMatrix {
|
|
71
|
+
cells: TransferCell[];
|
|
72
|
+
}
|
|
73
|
+
/** TR-006. Transfer Score = relative gain; negative means the carried-over
|
|
74
|
+
* policy HURT (TR-007 negative transfer is a first-class result). */
|
|
75
|
+
export declare function transferScore(cell: TransferCell): number;
|
|
76
|
+
export declare function transferVerdict(cell: TransferCell): 'positive' | 'neutral' | 'negative';
|
|
77
|
+
/** TR-001. Build the matrix from per-cell measurements. */
|
|
78
|
+
export declare function buildTransferMatrix(cells: TransferCell[]): TransferMatrix & {
|
|
79
|
+
summary: Record<string, number>;
|
|
80
|
+
};
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/** BENCH-001. The registry: tracks register cases; the runner normalizes. */
|
|
2
|
+
export class GeneralBench {
|
|
3
|
+
cases = new Map();
|
|
4
|
+
register(case_) {
|
|
5
|
+
if (this.cases.has(case_.id))
|
|
6
|
+
throw new Error(`bench case ${case_.id} already registered`);
|
|
7
|
+
this.cases.set(case_.id, case_);
|
|
8
|
+
}
|
|
9
|
+
list() {
|
|
10
|
+
return [...this.cases.values()];
|
|
11
|
+
}
|
|
12
|
+
listByTrack(track) {
|
|
13
|
+
return this.list().filter((c) => c.track === track);
|
|
14
|
+
}
|
|
15
|
+
async runCase(caseId, traj) {
|
|
16
|
+
const c = this.cases.get(caseId);
|
|
17
|
+
if (!c)
|
|
18
|
+
throw new Error(`unknown bench case ${caseId}`);
|
|
19
|
+
const verdict = await c.verify(traj);
|
|
20
|
+
const metrics = uniformMetrics(traj, c.actionBudget);
|
|
21
|
+
return { caseId, metrics, note: verdict.note };
|
|
22
|
+
}
|
|
23
|
+
async runTrack(track, trajectories) {
|
|
24
|
+
const runs = [];
|
|
25
|
+
for (const c of this.listByTrack(track)) {
|
|
26
|
+
const traj = trajectories.get(c.id);
|
|
27
|
+
if (!traj)
|
|
28
|
+
continue;
|
|
29
|
+
runs.push(await this.runCase(c.id, traj));
|
|
30
|
+
}
|
|
31
|
+
return { track, runs, aggregate: aggregate(runs) };
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
export function uniformMetrics(traj, actionBudget) {
|
|
35
|
+
const actions = Math.max(1, traj.metrics.actions);
|
|
36
|
+
const failures = traj.steps.filter((s) => s.outcome === 'failure').length;
|
|
37
|
+
return {
|
|
38
|
+
success: traj.metrics.success ? 1 : 0,
|
|
39
|
+
actionEfficiency: Number(Math.min(1, actionBudget / actions).toFixed(3)),
|
|
40
|
+
recoveryRate: failures ? Number(Math.min(1, traj.metrics.recoveryCount / failures).toFixed(3)) : 0,
|
|
41
|
+
calibration: traj.metrics.brierScore !== undefined ? Number((1 - traj.metrics.brierScore).toFixed(3)) : 0,
|
|
42
|
+
predicted: traj.metrics.brierScore !== undefined,
|
|
43
|
+
costUnits: traj.steps.reduce((s, x) => s + (x.durationMs ?? 0) / 1_000, 0),
|
|
44
|
+
latencyMs: traj.metrics.elapsedMs,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
function aggregate(runs) {
|
|
48
|
+
if (runs.length === 0)
|
|
49
|
+
return {};
|
|
50
|
+
const keys = ['success', 'actionEfficiency', 'recoveryRate', 'calibration', 'costUnits', 'latencyMs'];
|
|
51
|
+
const out = { cases: runs.length };
|
|
52
|
+
for (const k of keys) {
|
|
53
|
+
out[k] = Number((runs.reduce((s, r) => s + Number(r.metrics[k]), 0) / runs.length).toFixed(3));
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
/** TR-006. Transfer Score = relative gain; negative means the carried-over
|
|
58
|
+
* policy HURT (TR-007 negative transfer is a first-class result). */
|
|
59
|
+
export function transferScore(cell) {
|
|
60
|
+
if (cell.fromScratch === 0)
|
|
61
|
+
return cell.withTransfer > 0 ? 1 : 0;
|
|
62
|
+
return Number(((cell.withTransfer - cell.fromScratch) / cell.fromScratch).toFixed(3));
|
|
63
|
+
}
|
|
64
|
+
export function transferVerdict(cell) {
|
|
65
|
+
const s = transferScore(cell);
|
|
66
|
+
if (s > 0.1)
|
|
67
|
+
return 'positive';
|
|
68
|
+
if (s < -0.1)
|
|
69
|
+
return 'negative';
|
|
70
|
+
return 'neutral';
|
|
71
|
+
}
|
|
72
|
+
/** TR-001. Build the matrix from per-cell measurements. */
|
|
73
|
+
export function buildTransferMatrix(cells) {
|
|
74
|
+
const scores = cells.map(transferScore);
|
|
75
|
+
return {
|
|
76
|
+
cells,
|
|
77
|
+
summary: {
|
|
78
|
+
cells: cells.length,
|
|
79
|
+
meanTransfer: scores.length ? Number((scores.reduce((s, x) => s + x, 0) / scores.length).toFixed(3)) : 0,
|
|
80
|
+
positive: cells.filter((c) => transferVerdict(c) === 'positive').length,
|
|
81
|
+
negative: cells.filter((c) => transferVerdict(c) === 'negative').length,
|
|
82
|
+
neutral: cells.filter((c) => transferVerdict(c) === 'neutral').length,
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hmharness/cognitive - continual learning control plane (blueprint §9 / CL-001..010)
|
|
3
|
+
*
|
|
4
|
+
* Decides WHAT to learn from a trajectory dataset — and at which layer.
|
|
5
|
+
* The learning-target taxonomy is the control plane's core:
|
|
6
|
+
* memory | skill | workflow | tool | router | world_model | prompt | adapter | model
|
|
7
|
+
* Discipline from the blueprint:
|
|
8
|
+
* - default harness-level first (memory/skill/workflow/router): cheap,
|
|
9
|
+
* reversible, fast to validate
|
|
10
|
+
* - adapter/model updates face a STRICTLY higher evidence bar
|
|
11
|
+
* (evidenceThreshold('model') > everything else) — weight changes are
|
|
12
|
+
* last, not first
|
|
13
|
+
* - diagnosis is deterministic-statistical here (failure clustering,
|
|
14
|
+
* calibration gaps, repeated patterns); LLM diagnosis plugs in as an
|
|
15
|
+
* injected diagnoser without changing the contract
|
|
16
|
+
*/
|
|
17
|
+
import type { CognitiveTrajectory } from './protocol.js';
|
|
18
|
+
export type LearningTarget = 'memory' | 'skill' | 'workflow' | 'tool' | 'router' | 'world_model' | 'prompt' | 'adapter' | 'model';
|
|
19
|
+
export interface LearningDataset {
|
|
20
|
+
trajectories: CognitiveTrajectory[];
|
|
21
|
+
}
|
|
22
|
+
export interface LearningOpportunity {
|
|
23
|
+
id: string;
|
|
24
|
+
signal: string;
|
|
25
|
+
evidence: {
|
|
26
|
+
trajectories: string[];
|
|
27
|
+
metric: string;
|
|
28
|
+
value: number;
|
|
29
|
+
};
|
|
30
|
+
suggestedTargets: LearningTarget[];
|
|
31
|
+
}
|
|
32
|
+
export interface LearningPlan {
|
|
33
|
+
opportunityId: string;
|
|
34
|
+
target: LearningTarget;
|
|
35
|
+
/** host-interpretable payload: what to write/patch/train */
|
|
36
|
+
payload: Record<string, unknown>;
|
|
37
|
+
expectedEffect: string;
|
|
38
|
+
rollbackStrategy: string;
|
|
39
|
+
}
|
|
40
|
+
export interface Candidate {
|
|
41
|
+
id: string;
|
|
42
|
+
plan: LearningPlan;
|
|
43
|
+
createdAt: string;
|
|
44
|
+
status: 'draft' | 'trained' | 'evaluated' | 'promoted' | 'rejected';
|
|
45
|
+
evalResult?: EvalResult;
|
|
46
|
+
}
|
|
47
|
+
export interface EvalResult {
|
|
48
|
+
candidateId: string;
|
|
49
|
+
pass: boolean;
|
|
50
|
+
metrics: Record<string, number>;
|
|
51
|
+
holdoutSize: number;
|
|
52
|
+
}
|
|
53
|
+
export interface HostTrainer {
|
|
54
|
+
/** applies a harness-level plan (write memory, patch workflow, reroute…) */
|
|
55
|
+
trainHarness(plan: LearningPlan): Promise<{
|
|
56
|
+
payload: Record<string, unknown>;
|
|
57
|
+
}>;
|
|
58
|
+
/** trains an adapter/model — only invoked when evidence threshold met */
|
|
59
|
+
trainModel?(plan: LearningPlan): Promise<{
|
|
60
|
+
payload: Record<string, unknown>;
|
|
61
|
+
}>;
|
|
62
|
+
}
|
|
63
|
+
export interface HostEvaluator {
|
|
64
|
+
evaluate(candidate: Candidate, holdout: LearningDataset): Promise<EvalResult>;
|
|
65
|
+
}
|
|
66
|
+
/** Evidence bar per target — the blueprint's "model update gate". */
|
|
67
|
+
export declare function evidenceThreshold(target: LearningTarget): number;
|
|
68
|
+
export declare class LearningController {
|
|
69
|
+
private trainer?;
|
|
70
|
+
private evaluator?;
|
|
71
|
+
private store;
|
|
72
|
+
private candidates;
|
|
73
|
+
constructor(trainer?: HostTrainer | undefined, evaluator?: HostEvaluator | undefined);
|
|
74
|
+
/** CL-001/CL-002. Trajectories land here and only here. */
|
|
75
|
+
collect(trajectory: CognitiveTrajectory): Promise<void>;
|
|
76
|
+
dataset(): LearningDataset;
|
|
77
|
+
/** CL-003. Deterministic diagnosis: what kind of learning would pay off? */
|
|
78
|
+
diagnose(dataset: LearningDataset): Promise<LearningOpportunity[]>;
|
|
79
|
+
/** CL-004. Choose the learning target: cheapest reversible layer that
|
|
80
|
+
* addresses the opportunity, gated by evidence strength. */
|
|
81
|
+
chooseTarget(opportunity: LearningOpportunity): LearningTarget;
|
|
82
|
+
/** CL-005/006. Train = produce a candidate (host-executed for harness
|
|
83
|
+
* targets; model targets require the trainer to implement trainModel). */
|
|
84
|
+
train(plan: LearningPlan): Promise<Candidate>;
|
|
85
|
+
/** CL-007. Holdout evaluation through the INDEPENDENT host evaluator. */
|
|
86
|
+
evaluate(candidate: Candidate, holdout: LearningDataset): Promise<EvalResult>;
|
|
87
|
+
/** CL promotion gate: evaluator pass + (for model targets) threshold met. */
|
|
88
|
+
promote(candidateId: string): Promise<void>;
|
|
89
|
+
candidate(id: string): Candidate | undefined;
|
|
90
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/** Evidence bar per target — the blueprint's "model update gate". */
|
|
2
|
+
export function evidenceThreshold(target) {
|
|
3
|
+
switch (target) {
|
|
4
|
+
case 'model': return 0.95;
|
|
5
|
+
case 'adapter': return 0.9;
|
|
6
|
+
case 'prompt': return 0.8;
|
|
7
|
+
default: return 0.6; // memory/skill/workflow/tool/router/world_model
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export class LearningController {
|
|
11
|
+
trainer;
|
|
12
|
+
evaluator;
|
|
13
|
+
store = [];
|
|
14
|
+
candidates = new Map();
|
|
15
|
+
constructor(trainer, evaluator) {
|
|
16
|
+
this.trainer = trainer;
|
|
17
|
+
this.evaluator = evaluator;
|
|
18
|
+
}
|
|
19
|
+
/** CL-001/CL-002. Trajectories land here and only here. */
|
|
20
|
+
async collect(trajectory) {
|
|
21
|
+
this.store.push(trajectory);
|
|
22
|
+
if (this.store.length > 5_000)
|
|
23
|
+
this.store.splice(0, this.store.length - 5_000);
|
|
24
|
+
}
|
|
25
|
+
dataset() {
|
|
26
|
+
return { trajectories: [...this.store] };
|
|
27
|
+
}
|
|
28
|
+
/** CL-003. Deterministic diagnosis: what kind of learning would pay off? */
|
|
29
|
+
async diagnose(dataset) {
|
|
30
|
+
const out = [];
|
|
31
|
+
const failed = dataset.trajectories.filter((t) => !t.metrics.success);
|
|
32
|
+
if (failed.length >= 2) {
|
|
33
|
+
// repeated failure signatures → remember the pitfall (memory) and try
|
|
34
|
+
// to compile what DID work elsewhere (skill)
|
|
35
|
+
const byEnv = new Map();
|
|
36
|
+
for (const f of failed)
|
|
37
|
+
byEnv.set(f.environment.id, [...(byEnv.get(f.environment.id) ?? []), f]);
|
|
38
|
+
for (const [env, list] of byEnv) {
|
|
39
|
+
if (list.length < 2)
|
|
40
|
+
continue;
|
|
41
|
+
out.push({
|
|
42
|
+
id: `opp-fail-${env}`,
|
|
43
|
+
signal: `${list.length} failed trajectories in ${env}`,
|
|
44
|
+
evidence: { trajectories: list.map((t) => t.id), metric: 'failCount', value: list.length },
|
|
45
|
+
suggestedTargets: ['memory', 'skill'],
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
const withPredictions = dataset.trajectories.filter((t) => t.metrics.brierScore !== undefined);
|
|
50
|
+
if (withPredictions.length >= 3) {
|
|
51
|
+
const meanBrier = withPredictions.reduce((s, t) => s + (t.metrics.brierScore ?? 0), 0) / withPredictions.length;
|
|
52
|
+
if (meanBrier > 0.25) {
|
|
53
|
+
out.push({
|
|
54
|
+
id: 'opp-calibration',
|
|
55
|
+
signal: `prediction calibration is poor (mean Brier ${meanBrier.toFixed(3)} > 0.25)`,
|
|
56
|
+
evidence: { trajectories: withPredictions.map((t) => t.id), metric: 'meanBrier', value: Number(meanBrier.toFixed(3)) },
|
|
57
|
+
suggestedTargets: ['world_model'],
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const recoveries = dataset.trajectories.filter((t) => t.metrics.recoveryCount >= 2);
|
|
62
|
+
if (recoveries.length >= 2) {
|
|
63
|
+
out.push({
|
|
64
|
+
id: 'opp-recovery',
|
|
65
|
+
signal: `${recoveries.length} trajectories needed multiple recoveries — workflow doesn't encode the fix`,
|
|
66
|
+
evidence: { trajectories: recoveries.map((t) => t.id), metric: 'recoveryCount', value: recoveries.length },
|
|
67
|
+
suggestedTargets: ['workflow', 'skill'],
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
const longOnes = dataset.trajectories.filter((t) => t.metrics.actions > 30 && t.metrics.success);
|
|
71
|
+
if (longOnes.length >= 2) {
|
|
72
|
+
out.push({
|
|
73
|
+
id: 'opp-efficiency',
|
|
74
|
+
signal: `${longOnes.length} successful but long trajectories (${Math.round(longOnes.reduce((s, t) => s + t.metrics.actions, 0) / longOnes.length)} actions avg)`,
|
|
75
|
+
evidence: { trajectories: longOnes.map((t) => t.id), metric: 'avgActions', value: Math.round(longOnes.reduce((s, t) => s + t.metrics.actions, 0) / longOnes.length) },
|
|
76
|
+
suggestedTargets: ['router', 'workflow'],
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
/** CL-004. Choose the learning target: cheapest reversible layer that
|
|
82
|
+
* addresses the opportunity, gated by evidence strength. */
|
|
83
|
+
chooseTarget(opportunity) {
|
|
84
|
+
const order = ['memory', 'skill', 'workflow', 'router', 'tool', 'world_model', 'prompt', 'adapter', 'model'];
|
|
85
|
+
const strength = Math.min(1, opportunity.evidence.value / 5);
|
|
86
|
+
for (const t of order) {
|
|
87
|
+
if (!opportunity.suggestedTargets.includes(t))
|
|
88
|
+
continue;
|
|
89
|
+
if (strength >= evidenceThreshold(t))
|
|
90
|
+
return t;
|
|
91
|
+
}
|
|
92
|
+
// evidence too weak for any suggested target: the cheapest safe default
|
|
93
|
+
return opportunity.suggestedTargets[0] ?? 'memory';
|
|
94
|
+
}
|
|
95
|
+
/** CL-005/006. Train = produce a candidate (host-executed for harness
|
|
96
|
+
* targets; model targets require the trainer to implement trainModel). */
|
|
97
|
+
async train(plan) {
|
|
98
|
+
if (!this.trainer)
|
|
99
|
+
throw new Error('no HostTrainer configured');
|
|
100
|
+
if ((plan.target === 'model' || plan.target === 'adapter') && !this.trainer.trainModel) {
|
|
101
|
+
throw new Error(`target ${plan.target} requires a trainer with trainModel() — refusing to fake it`);
|
|
102
|
+
}
|
|
103
|
+
const produced = plan.target === 'model' || plan.target === 'adapter'
|
|
104
|
+
? await this.trainer.trainModel(plan)
|
|
105
|
+
: await this.trainer.trainHarness(plan);
|
|
106
|
+
const candidate = {
|
|
107
|
+
id: `cand-${plan.opportunityId}-${plan.target}-${Date.now().toString(36)}`,
|
|
108
|
+
plan: { ...plan, payload: { ...plan.payload, ...produced.payload } },
|
|
109
|
+
createdAt: new Date().toISOString(),
|
|
110
|
+
status: 'trained',
|
|
111
|
+
};
|
|
112
|
+
this.candidates.set(candidate.id, candidate);
|
|
113
|
+
return candidate;
|
|
114
|
+
}
|
|
115
|
+
/** CL-007. Holdout evaluation through the INDEPENDENT host evaluator. */
|
|
116
|
+
async evaluate(candidate, holdout) {
|
|
117
|
+
if (!this.evaluator)
|
|
118
|
+
throw new Error('no HostEvaluator configured');
|
|
119
|
+
const result = await this.evaluator.evaluate(candidate, holdout);
|
|
120
|
+
candidate.evalResult = result;
|
|
121
|
+
candidate.status = 'evaluated';
|
|
122
|
+
return result;
|
|
123
|
+
}
|
|
124
|
+
/** CL promotion gate: evaluator pass + (for model targets) threshold met. */
|
|
125
|
+
async promote(candidateId) {
|
|
126
|
+
const c = this.candidates.get(candidateId);
|
|
127
|
+
if (!c)
|
|
128
|
+
throw new Error(`unknown candidate ${candidateId}`);
|
|
129
|
+
if (!c.evalResult?.pass)
|
|
130
|
+
throw new Error(`candidate ${candidateId} did not pass holdout evaluation`);
|
|
131
|
+
if ((c.plan.target === 'model' || c.plan.target === 'adapter')) {
|
|
132
|
+
const strength = Math.min(1, (c.evalResult.metrics.holdoutSize ?? 0) / 50);
|
|
133
|
+
if (strength < evidenceThreshold(c.plan.target) - 0.1) {
|
|
134
|
+
throw new Error(`candidate ${candidateId} targets ${c.plan.target} but holdout evidence is below the model-update gate`);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
c.status = 'promoted';
|
|
138
|
+
}
|
|
139
|
+
candidate(id) {
|
|
140
|
+
return this.candidates.get(id);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
export type EvolutionTarget = 'memory' | 'skill' | 'workflow' | 'tool' | 'router' | 'world_model' | 'prompt' | 'adapter' | 'model';
|
|
2
|
+
export interface EvolutionCandidate {
|
|
3
|
+
id: string;
|
|
4
|
+
target: EvolutionTarget;
|
|
5
|
+
/** WHAT changes and WHY it should work — the falsifiable hypothesis */
|
|
6
|
+
hypothesis: string;
|
|
7
|
+
expectedEffect: {
|
|
8
|
+
metric: string;
|
|
9
|
+
op: '>=' | '<=';
|
|
10
|
+
value: number;
|
|
11
|
+
where: string;
|
|
12
|
+
};
|
|
13
|
+
/** what this change could plausibly hurt (must be non-empty) */
|
|
14
|
+
possibleRegression: string[];
|
|
15
|
+
evaluationDataset: string;
|
|
16
|
+
holdoutDataset: string;
|
|
17
|
+
transferTest: {
|
|
18
|
+
sourceEnv: string;
|
|
19
|
+
targetEnv: string;
|
|
20
|
+
};
|
|
21
|
+
rollbackStrategy: string;
|
|
22
|
+
resourceBudget: {
|
|
23
|
+
maxWallMs: number;
|
|
24
|
+
maxCostUnits: number;
|
|
25
|
+
};
|
|
26
|
+
safetyConstraints: string[];
|
|
27
|
+
status: 'proposed' | 'sandboxed' | 'gated' | 'canary' | 'promoted' | 'rolled-back' | 'rejected';
|
|
28
|
+
createdAt: string;
|
|
29
|
+
measurements?: Array<{
|
|
30
|
+
phase: string;
|
|
31
|
+
at: string;
|
|
32
|
+
metrics: Record<string, number>;
|
|
33
|
+
}>;
|
|
34
|
+
flagged?: {
|
|
35
|
+
reason: string;
|
|
36
|
+
at: string;
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
export interface GateSample {
|
|
40
|
+
/** 1 = candidate beat baseline on this sample, 0 = not */
|
|
41
|
+
won: 0 | 1;
|
|
42
|
+
source: 'train' | 'holdout' | 'transfer';
|
|
43
|
+
}
|
|
44
|
+
export interface SequentialGateResult {
|
|
45
|
+
decision: 'promote' | 'reject' | 'continue';
|
|
46
|
+
samples: number;
|
|
47
|
+
wins: number;
|
|
48
|
+
pValue: number;
|
|
49
|
+
}
|
|
50
|
+
export interface CanaryResult {
|
|
51
|
+
pass: boolean;
|
|
52
|
+
windowsObserved: number;
|
|
53
|
+
realTaskDelta: number;
|
|
54
|
+
metricDelta: number;
|
|
55
|
+
}
|
|
56
|
+
/** EV-012. Reward hacking: metrics improved, real tasks did not. */
|
|
57
|
+
export interface RewardHackingDetectorInput {
|
|
58
|
+
metricBefore: number;
|
|
59
|
+
metricAfter: number;
|
|
60
|
+
realTaskSuccessBefore: number;
|
|
61
|
+
realTaskSuccessAfter: number;
|
|
62
|
+
}
|
|
63
|
+
export declare class EvolutionController {
|
|
64
|
+
private home;
|
|
65
|
+
private candidates;
|
|
66
|
+
constructor(home: string);
|
|
67
|
+
/** EV-001/002. Intake: the FULL contract or nothing. */
|
|
68
|
+
propose(input: Omit<EvolutionCandidate, 'id' | 'status' | 'createdAt'>): EvolutionCandidate;
|
|
69
|
+
get(id: string): EvolutionCandidate | undefined;
|
|
70
|
+
list(): EvolutionCandidate[];
|
|
71
|
+
/** EV-007. Mark sandboxed (execution happens in the host's isolated
|
|
72
|
+
* evolution sandbox — separate from task sandboxes per blueprint §12). */
|
|
73
|
+
markSandboxes(id: string): void;
|
|
74
|
+
/** CL-008 / EV sequential gate: Wald-style SPRT lite on win/loss samples.
|
|
75
|
+
* Holdout and transfer samples BOTH count; train samples never decide. */
|
|
76
|
+
sequentialGate(samples: GateSample[], opts?: {
|
|
77
|
+
alpha?: number;
|
|
78
|
+
beta?: number;
|
|
79
|
+
}): SequentialGateResult;
|
|
80
|
+
markGated(id: string, gate: SequentialGateResult): void;
|
|
81
|
+
/** Canary phase: EV impact measurement on a slice of real traffic. */
|
|
82
|
+
canary(id: string, input: RewardHackingDetectorInput, windows?: number): Promise<CanaryResult>;
|
|
83
|
+
promote(id: string): Promise<void>;
|
|
84
|
+
rollback(id: string, reason: string): Promise<void>;
|
|
85
|
+
/** EV-011. Immutable, append-only audit trail. */
|
|
86
|
+
private audit;
|
|
87
|
+
auditLog(limit?: number): Promise<Array<Record<string, unknown>>>;
|
|
88
|
+
}
|
|
89
|
+
/** EV-012. Metrics moved but real tasks didn't — the classic Goodhart tell. */
|
|
90
|
+
export declare function detectRewardHacking(input: RewardHackingDetectorInput): {
|
|
91
|
+
hacked: boolean;
|
|
92
|
+
reason?: string;
|
|
93
|
+
};
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hmharness/cognitive - self-evolution 2.0 governance (blueprint §10 / EV-001..015)
|
|
3
|
+
*
|
|
4
|
+
* The upgrade over "evolve when metrics move": every evolution candidate is
|
|
5
|
+
* a CONTRACT that must declare — before training — hypothesis, expected
|
|
6
|
+
* effect, possible regression, evaluation dataset, rollback, budget and
|
|
7
|
+
* safety constraints. The controller then walks the pipeline:
|
|
8
|
+
*
|
|
9
|
+
* sandbox -> train/test split -> holdout + transfer test -> sequential
|
|
10
|
+
* statistical gate -> canary -> impact measurement -> promote/rollback
|
|
11
|
+
* -> immutable audit
|
|
12
|
+
*
|
|
13
|
+
* Hard prohibitions enforced structurally (blueprint §9 禁止 list):
|
|
14
|
+
* - the candidate may not touch evaluator definitions (self-grading)
|
|
15
|
+
* - approval/security/config core is out of scope by kind: such candidates
|
|
16
|
+
* are rejected at intake, not caught later
|
|
17
|
+
* - promotion requires BOTH the sequential gate and a transfer test — a
|
|
18
|
+
* single-benchmark gain never promotes globally
|
|
19
|
+
* - reward hacking detection: metric gains without real-task gains flag
|
|
20
|
+
* the candidate and freeze the pipeline
|
|
21
|
+
*/
|
|
22
|
+
import { appendFile, mkdir, readFile } from 'node:fs/promises';
|
|
23
|
+
import { join } from 'node:path';
|
|
24
|
+
import { stableHash } from "./protocol.js";
|
|
25
|
+
const FORBIDDEN_TARGET_HINTS = ['approval', 'security', 'config', 'sandbox-policy', 'evaluator', 'audit'];
|
|
26
|
+
export class EvolutionController {
|
|
27
|
+
home;
|
|
28
|
+
candidates = new Map();
|
|
29
|
+
constructor(home) {
|
|
30
|
+
this.home = home;
|
|
31
|
+
}
|
|
32
|
+
/** EV-001/002. Intake: the FULL contract or nothing. */
|
|
33
|
+
propose(input) {
|
|
34
|
+
const errors = [];
|
|
35
|
+
if (!input.hypothesis?.trim())
|
|
36
|
+
errors.push('hypothesis required (what changes and why it works)');
|
|
37
|
+
if (!input.expectedEffect)
|
|
38
|
+
errors.push('expectedEffect required');
|
|
39
|
+
if (!input.possibleRegression?.length)
|
|
40
|
+
errors.push('possibleRegression required — declare what this could hurt');
|
|
41
|
+
if (!input.holdoutDataset)
|
|
42
|
+
errors.push('holdoutDataset required — no promotion without holdout');
|
|
43
|
+
if (!input.transferTest)
|
|
44
|
+
errors.push('transferTest required — single-benchmark gains never promote globally');
|
|
45
|
+
if (!input.rollbackStrategy?.trim())
|
|
46
|
+
errors.push('rollbackStrategy required — no irreversible evolution');
|
|
47
|
+
const hint = FORBIDDEN_TARGET_HINTS.find((h) => JSON.stringify(input).toLowerCase().includes(h) && (input.target === 'tool' || input.target === 'workflow') && JSON.stringify(input).toLowerCase().match(new RegExp(`(modify|patch|change)[^"]{0,40}${h}`)));
|
|
48
|
+
if (hint)
|
|
49
|
+
errors.push(`candidate appears to modify ${hint} core — out of evolution scope by policy`);
|
|
50
|
+
if (errors.length)
|
|
51
|
+
throw new Error(`evolution candidate rejected at intake: ${errors.join('; ')}`);
|
|
52
|
+
const c = {
|
|
53
|
+
...input,
|
|
54
|
+
id: `evo-${stableHash(input.hypothesis + input.target).slice(0, 10)}-${Date.now().toString(36)}`,
|
|
55
|
+
status: 'proposed',
|
|
56
|
+
createdAt: new Date().toISOString(),
|
|
57
|
+
};
|
|
58
|
+
this.candidates.set(c.id, c);
|
|
59
|
+
return c;
|
|
60
|
+
}
|
|
61
|
+
get(id) {
|
|
62
|
+
return this.candidates.get(id);
|
|
63
|
+
}
|
|
64
|
+
list() {
|
|
65
|
+
return [...this.candidates.values()];
|
|
66
|
+
}
|
|
67
|
+
/** EV-007. Mark sandboxed (execution happens in the host's isolated
|
|
68
|
+
* evolution sandbox — separate from task sandboxes per blueprint §12). */
|
|
69
|
+
markSandboxes(id) {
|
|
70
|
+
const c = this.candidates.get(id);
|
|
71
|
+
if (c && c.status === 'proposed')
|
|
72
|
+
c.status = 'sandboxed';
|
|
73
|
+
}
|
|
74
|
+
/** CL-008 / EV sequential gate: Wald-style SPRT lite on win/loss samples.
|
|
75
|
+
* Holdout and transfer samples BOTH count; train samples never decide. */
|
|
76
|
+
sequentialGate(samples, opts) {
|
|
77
|
+
const deciding = samples.filter((s) => s.source !== 'train');
|
|
78
|
+
const n = deciding.length;
|
|
79
|
+
const wins = deciding.reduce((s, x) => s + x.won, 0);
|
|
80
|
+
if (n < 5)
|
|
81
|
+
return { decision: 'continue', samples: n, wins, pValue: 1 };
|
|
82
|
+
// one-sided binomial p-value under H0 (win rate 0.5), normal approx
|
|
83
|
+
const z = (wins - n / 2) / Math.sqrt(n / 4);
|
|
84
|
+
const pValue = Number(normalSurvival(z).toFixed(4));
|
|
85
|
+
const alpha = opts?.alpha ?? 0.05;
|
|
86
|
+
const beta = 1 - (opts?.beta ?? 0.2);
|
|
87
|
+
if (pValue < alpha)
|
|
88
|
+
return { decision: 'promote', samples: n, wins, pValue };
|
|
89
|
+
if (pValue > beta)
|
|
90
|
+
return { decision: 'reject', samples: n, wins, pValue };
|
|
91
|
+
return { decision: 'continue', samples: n, wins, pValue };
|
|
92
|
+
}
|
|
93
|
+
markGated(id, gate) {
|
|
94
|
+
const c = this.candidates.get(id);
|
|
95
|
+
if (!c)
|
|
96
|
+
return;
|
|
97
|
+
if (gate.decision === 'promote')
|
|
98
|
+
c.status = 'gated';
|
|
99
|
+
else if (gate.decision === 'reject') {
|
|
100
|
+
c.status = 'rejected';
|
|
101
|
+
void this.audit(c, 'rejected-by-sequential-gate', { samples: gate.samples, wins: gate.wins, pValue: gate.pValue });
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/** Canary phase: EV impact measurement on a slice of real traffic. */
|
|
105
|
+
async canary(id, input, windows = 3) {
|
|
106
|
+
const c = this.candidates.get(id);
|
|
107
|
+
if (!c || c.status !== 'gated')
|
|
108
|
+
throw new Error(`candidate ${id} is not gated — cannot canary`);
|
|
109
|
+
c.status = 'canary';
|
|
110
|
+
const hacked = detectRewardHacking(input);
|
|
111
|
+
const result = {
|
|
112
|
+
pass: !hacked.hacked,
|
|
113
|
+
windowsObserved: windows,
|
|
114
|
+
realTaskDelta: Number((input.realTaskSuccessAfter - input.realTaskSuccessBefore).toFixed(4)),
|
|
115
|
+
metricDelta: Number((input.metricAfter - input.metricBefore).toFixed(4)),
|
|
116
|
+
};
|
|
117
|
+
c.measurements = [...(c.measurements ?? []), { phase: 'canary', at: new Date().toISOString(), metrics: { realTaskDelta: result.realTaskDelta, metricDelta: result.metricDelta } }];
|
|
118
|
+
if (hacked.hacked) {
|
|
119
|
+
c.flagged = { reason: hacked.reason ?? 'reward hacking detected', at: new Date().toISOString() };
|
|
120
|
+
c.status = 'rejected';
|
|
121
|
+
await this.audit(c, 'flagged-reward-hacking', { reason: hacked.reason ?? '' });
|
|
122
|
+
}
|
|
123
|
+
return result;
|
|
124
|
+
}
|
|
125
|
+
async promote(id) {
|
|
126
|
+
const c = this.candidates.get(id);
|
|
127
|
+
if (!c)
|
|
128
|
+
throw new Error(`unknown candidate ${id}`);
|
|
129
|
+
if (c.flagged)
|
|
130
|
+
throw new Error(`candidate ${id} is flagged: ${c.flagged.reason}`);
|
|
131
|
+
if (c.status !== 'canary')
|
|
132
|
+
throw new Error(`candidate ${id} must pass canary before promotion (status=${c.status})`);
|
|
133
|
+
c.status = 'promoted';
|
|
134
|
+
await this.audit(c, 'promoted', { rollback: c.rollbackStrategy });
|
|
135
|
+
}
|
|
136
|
+
async rollback(id, reason) {
|
|
137
|
+
const c = this.candidates.get(id);
|
|
138
|
+
if (!c)
|
|
139
|
+
throw new Error(`unknown candidate ${id}`);
|
|
140
|
+
c.status = 'rolled-back';
|
|
141
|
+
await this.audit(c, 'rolled-back', { reason });
|
|
142
|
+
}
|
|
143
|
+
/** EV-011. Immutable, append-only audit trail. */
|
|
144
|
+
async audit(c, event, detail) {
|
|
145
|
+
const dir = join(this.home, 'cognitive', 'evolution');
|
|
146
|
+
await mkdir(dir, { recursive: true });
|
|
147
|
+
await appendFile(join(dir, 'audit.jsonl'), JSON.stringify({ at: new Date().toISOString(), event, candidateId: c.id, target: c.target, hypothesis: c.hypothesis ?? '', detail }) + '\n', 'utf8');
|
|
148
|
+
}
|
|
149
|
+
async auditLog(limit = 50) {
|
|
150
|
+
try {
|
|
151
|
+
const text = await readFile(join(this.home, 'cognitive', 'evolution', 'audit.jsonl'), 'utf8');
|
|
152
|
+
return text.split('\n').filter((l) => l.trim()).slice(-limit).map((l) => JSON.parse(l));
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
return [];
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/** EV-012. Metrics moved but real tasks didn't — the classic Goodhart tell. */
|
|
160
|
+
export function detectRewardHacking(input) {
|
|
161
|
+
const metricGain = input.metricAfter - input.metricBefore;
|
|
162
|
+
const realGain = input.realTaskSuccessAfter - input.realTaskSuccessBefore;
|
|
163
|
+
if (metricGain > 0.05 && realGain <= 0.005) {
|
|
164
|
+
return {
|
|
165
|
+
hacked: true,
|
|
166
|
+
reason: `metric +${(metricGain * 100).toFixed(1)}% but real-task success ${realGain >= 0 ? '+' : ''}${(realGain * 100).toFixed(1)}% — optimizing the evaluator, not the work`,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
return { hacked: false };
|
|
170
|
+
}
|
|
171
|
+
/** Upper tail of the standard normal CDF via the Abramowitz–Stegun 7.1.26
|
|
172
|
+
* erf approximation (JS has no erfc builtin). */
|
|
173
|
+
function normalSurvival(z) {
|
|
174
|
+
const neg = z < 0;
|
|
175
|
+
const x = Math.abs(z) / Math.SQRT2;
|
|
176
|
+
const t = 1 / (1 + 0.3275911 * x);
|
|
177
|
+
const erf = 1 -
|
|
178
|
+
((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * Math.exp(-x * x);
|
|
179
|
+
const upperTail = (1 - erf) / 2;
|
|
180
|
+
return neg ? 1 - upperTail : upperTail;
|
|
181
|
+
}
|