claude-flow 3.23.0 → 3.24.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.
Files changed (47) hide show
  1. package/.claude/helpers/.helpers-version +1 -1
  2. package/.claude/helpers/helpers.manifest.json +2 -2
  3. package/package.json +1 -1
  4. package/v3/@claude-flow/cli/dist/src/config/harness-feedback-applier.d.ts +50 -0
  5. package/v3/@claude-flow/cli/dist/src/config/harness-feedback-applier.js +122 -0
  6. package/v3/@claude-flow/cli/dist/src/config/proven-config-refresh.d.ts +39 -0
  7. package/v3/@claude-flow/cli/dist/src/config/proven-config-refresh.js +154 -0
  8. package/v3/@claude-flow/cli/dist/src/config/proven-config-rvfa.d.ts +23 -0
  9. package/v3/@claude-flow/cli/dist/src/config/proven-config-rvfa.js +73 -0
  10. package/v3/@claude-flow/cli/dist/src/config/proven-config.d.ts +86 -0
  11. package/v3/@claude-flow/cli/dist/src/config/proven-config.js +176 -0
  12. package/v3/@claude-flow/cli/dist/src/index.js +35 -0
  13. package/v3/@claude-flow/cli/dist/src/mcp-tools/neural-tools.d.ts +10 -0
  14. package/v3/@claude-flow/cli/dist/src/mcp-tools/neural-tools.js +107 -18
  15. package/v3/@claude-flow/cli/dist/src/services/daemon-autostart.d.ts +17 -0
  16. package/v3/@claude-flow/cli/dist/src/services/daemon-autostart.js +79 -0
  17. package/v3/@claude-flow/cli/dist/src/services/evolve-proof.d.ts +247 -0
  18. package/v3/@claude-flow/cli/dist/src/services/evolve-proof.js +341 -0
  19. package/v3/@claude-flow/cli/dist/src/services/harness-benchmark.d.ts +68 -0
  20. package/v3/@claude-flow/cli/dist/src/services/harness-benchmark.js +94 -0
  21. package/v3/@claude-flow/cli/dist/src/services/harness-canary.d.ts +60 -0
  22. package/v3/@claude-flow/cli/dist/src/services/harness-canary.js +69 -0
  23. package/v3/@claude-flow/cli/dist/src/services/harness-corpus-harvester.d.ts +51 -0
  24. package/v3/@claude-flow/cli/dist/src/services/harness-corpus-harvester.js +74 -0
  25. package/v3/@claude-flow/cli/dist/src/services/harness-flywheel-generations.d.ts +111 -0
  26. package/v3/@claude-flow/cli/dist/src/services/harness-flywheel-generations.js +354 -0
  27. package/v3/@claude-flow/cli/dist/src/services/harness-flywheel-runtime.d.ts +25 -0
  28. package/v3/@claude-flow/cli/dist/src/services/harness-flywheel-runtime.js +101 -0
  29. package/v3/@claude-flow/cli/dist/src/services/harness-flywheel.d.ts +48 -0
  30. package/v3/@claude-flow/cli/dist/src/services/harness-flywheel.js +207 -0
  31. package/v3/@claude-flow/cli/dist/src/services/harness-hosts.d.ts +40 -0
  32. package/v3/@claude-flow/cli/dist/src/services/harness-hosts.js +88 -0
  33. package/v3/@claude-flow/cli/dist/src/services/harness-improvement-ledger.d.ts +63 -0
  34. package/v3/@claude-flow/cli/dist/src/services/harness-improvement-ledger.js +101 -0
  35. package/v3/@claude-flow/cli/dist/src/services/harness-loop.d.ts +53 -0
  36. package/v3/@claude-flow/cli/dist/src/services/harness-loop.js +85 -0
  37. package/v3/@claude-flow/cli/dist/src/services/harness-qualification.d.ts +66 -0
  38. package/v3/@claude-flow/cli/dist/src/services/harness-qualification.js +143 -0
  39. package/v3/@claude-flow/cli/dist/src/services/harness-replay.d.ts +37 -0
  40. package/v3/@claude-flow/cli/dist/src/services/harness-replay.js +92 -0
  41. package/v3/@claude-flow/cli/dist/src/services/harness-verify.d.ts +33 -0
  42. package/v3/@claude-flow/cli/dist/src/services/harness-verify.js +26 -0
  43. package/v3/@claude-flow/cli/dist/src/services/harness-worker.d.ts +23 -0
  44. package/v3/@claude-flow/cli/dist/src/services/harness-worker.js +66 -0
  45. package/v3/@claude-flow/cli/dist/src/services/worker-daemon.d.ts +8 -1
  46. package/v3/@claude-flow/cli/dist/src/services/worker-daemon.js +42 -0
  47. package/v3/@claude-flow/cli/package.json +1 -1
@@ -0,0 +1,207 @@
1
+ /**
2
+ * Self-optimizing flywheel (ADR-176) — closes the loop so an install gets
3
+ * smarter AS IT RUNS, with proof.
4
+ *
5
+ * Each tick:
6
+ * 1. HARVEST a benchmark corpus from the install's REAL store (self-supervised
7
+ * self-retrieval), blended with the human-labeled ADR-081 anchor.
8
+ * 2. BASELINE = the currently-active champion (or shipped defaults).
9
+ * 3. PROPOSE neighbor configs; pick the best on the TRAIN split (local
10
+ * hill-climb — deterministic, selection uses train only).
11
+ * 4. GATE the winner through the shipped runHarnessLoop on the HELD-OUT split:
12
+ * held_out_improves AND redblue(anchor-no-regress) AND drift<=thr AND
13
+ * replay-deterministic AND receipt_coverage AND canary-no-worse.
14
+ * 5. On accept → APPLY locally (the install self-optimizes on its own data; no
15
+ * signing needed because nothing is propagated), CHAIN to the previous
16
+ * champion, and record the attempt in the improvement ledger. Also STAGE
17
+ * the unsigned champion for optional promotion to the signed global channel.
18
+ *
19
+ * Trust split: LOCAL self-optimization is unsigned (an install trusting its own
20
+ * measured gate); CROSS-install propagation still requires the config-signed
21
+ * champion (ADR-177). Deterministic, $0, never throws. Injectable deps → testable
22
+ * without ONNX/network.
23
+ */
24
+ import { createHash } from 'node:crypto';
25
+ import { runHarnessLoop } from './harness-loop.js';
26
+ import { hashCorpus } from './harness-benchmark.js';
27
+ import { harvestSelfSupervisedTasks, blendCorpus } from './harness-corpus-harvester.js';
28
+ import { applyChampionParams } from '../config/harness-feedback-applier.js';
29
+ import { appendLedger, bootstrapDeltaCILow } from './harness-improvement-ledger.js';
30
+ export const DEFAULT_CONFIG = { alpha: 0.5, subjectWeight: 2.0, mmrLambda: 0.7, bodyWeight: 1.0, typePenaltyFactor: 1.0 };
31
+ const EPS = 1e-3;
32
+ const cfgCanon = (c) => JSON.stringify(Object.fromEntries(Object.keys(c).sort().map((k) => [k, c[k]])));
33
+ const refOf = (c) => 'sha256:' + createHash('sha256').update(cfgCanon(c)).digest('hex');
34
+ const cfgKey = (c) => cfgCanon(c);
35
+ function ndcg3(names, labels) {
36
+ const rel = names.slice(0, 3).map((n) => !!n && labels.some((s) => n.toLowerCase().includes(s.toLowerCase())));
37
+ const dcg = rel.reduce((a, r, i) => a + (r ? 1 / Math.log2(i + 2) : 0), 0);
38
+ const num = rel.filter(Boolean).length;
39
+ if (num === 0)
40
+ return 0;
41
+ let idcg = 0;
42
+ for (let i = 0; i < num; i++)
43
+ idcg += 1 / Math.log2(i + 2);
44
+ return idcg > 0 ? dcg / idcg : 0;
45
+ }
46
+ /** grade dispatch: anchor tasks (labels[]) → nDCG@3; harvested tasks (doc id) → reciprocal rank. */
47
+ function grade(ranked, expected) {
48
+ if (Array.isArray(expected))
49
+ return ndcg3(ranked.map((r) => r.name), expected);
50
+ const idx = ranked.findIndex((r) => r.id === expected);
51
+ return idx >= 0 ? 1 / (idx + 1) : 0;
52
+ }
53
+ function neighbors(base) {
54
+ const steps = { alpha: 0.1, subjectWeight: 0.5, mmrLambda: 0.1, bodyWeight: 0.5, typePenaltyFactor: 0.25 };
55
+ const out = [];
56
+ const seen = new Set();
57
+ // Per-axis moves at 1 AND 2 steps in each direction — enough to escape a flat
58
+ // single step and reach a multi-step optimum over successive ticks (the
59
+ // single-step search got stuck one hop short of the known champion).
60
+ for (const ax of Object.keys(steps)) {
61
+ for (const mult of [1, 2]) {
62
+ for (const dir of [-1, 1]) {
63
+ const v = +(base[ax] + dir * mult * steps[ax]).toFixed(3);
64
+ if (ax === 'alpha' && (v <= 0 || v >= 1))
65
+ continue;
66
+ if (ax === 'mmrLambda' && (v < 0 || v > 1))
67
+ continue;
68
+ if (v <= 0)
69
+ continue;
70
+ const cand = { ...base, [ax]: v };
71
+ const k = cfgKey(cand);
72
+ if (seen.has(k))
73
+ continue;
74
+ seen.add(k);
75
+ out.push(cand);
76
+ }
77
+ }
78
+ }
79
+ return out;
80
+ }
81
+ /** Deterministic id-sort split (matches computeHeldOutSplit @ frac). */
82
+ function split(tasks, frac) {
83
+ const ordered = [...tasks].sort((a, b) => a.id.localeCompare(b.id));
84
+ const cut = Math.max(0, ordered.length - Math.max(1, Math.round(ordered.length * frac)));
85
+ return { train: ordered.slice(0, cut), held: ordered.slice(cut) };
86
+ }
87
+ /**
88
+ * Run one flywheel tick against `projectRoot`. Best-effort; never throws.
89
+ * Returns a rich result AND (as a side effect) appends to the improvement ledger
90
+ * and — on accept — applies the champion locally + chains it.
91
+ */
92
+ export async function runFlywheelTick(projectRoot, deps) {
93
+ try {
94
+ const patterns = await deps.getPatterns();
95
+ if (!patterns || patterns.length < 8)
96
+ return { ran: false, reason: 'store too small to harvest a corpus' };
97
+ const harvested = harvestSelfSupervisedTasks(patterns, { sample: deps.sample ?? 40 });
98
+ if (harvested.length < 4)
99
+ return { ran: false, reason: 'not enough harvestable tasks' };
100
+ const blended = blendCorpus(deps.anchorTasks, harvested);
101
+ const anchorIdSet = new Set(blended.anchorIds);
102
+ const baseline = { ...DEFAULT_CONFIG, ...(deps.activeParams?.() ?? {}) };
103
+ const candidates = neighbors(baseline);
104
+ // OBJECTIVE = the human-labeled anchor (the relevance we actually care about,
105
+ // where headroom is known to exist). GUARD = the large, growing harvested set
106
+ // (don't wreck broad retrieval while tuning the objective). Optimize the
107
+ // trusted signal; guard breadth with the cheap one.
108
+ const objective = blended.tasks.filter((t) => anchorIdSet.has(t.id));
109
+ const guard = blended.tasks.filter((t) => !anchorIdSet.has(t.id));
110
+ if (objective.length < 4)
111
+ return { ran: false, reason: 'objective (anchor) too small to gate' };
112
+ // Precompute retrieval for baseline + all candidates over every task (async
113
+ // I/O up front → the harness scoring stays pure/sync).
114
+ const cache = new Map();
115
+ const configs = [baseline, ...candidates];
116
+ for (const cfg of configs) {
117
+ for (const t of blended.tasks) {
118
+ const q = t.input.q;
119
+ cache.set(`${t.id}::${cfgKey(cfg)}`, (await deps.search(q, cfg)) || []);
120
+ }
121
+ }
122
+ const evalFn = (input, cfg) => cache.get(`${input.id}::${cfgKey(cfg)}`) ?? [];
123
+ const gradeFn = (output, expected) => grade(output, expected);
124
+ const heldScoreFor = (cfg, t) => gradeFn(evalFn(t.input, cfg), t.expected);
125
+ // Local hill-climb on the OBJECTIVE train split (selection uses train only).
126
+ const { train, held } = split(objective, 0.5);
127
+ const trainScore = (cfg) => train.reduce((s, t) => s + heldScoreFor(cfg, t), 0) / train.length;
128
+ const baseTrain = trainScore(baseline);
129
+ let candidate = baseline, candTrain = baseTrain;
130
+ for (const c of candidates) {
131
+ const s = trainScore(c);
132
+ if (s > candTrain + 1e-9) {
133
+ candTrain = s;
134
+ candidate = c;
135
+ }
136
+ }
137
+ // Generalization guard: the candidate must not regress the broad harvested
138
+ // set (bound to the adversarial redblue verdict). This replaces the earlier
139
+ // (inverted) design where the cheap metric was the objective.
140
+ const guardScore = (cfg) => guard.length ? guard.reduce((s, t) => s + heldScoreFor(cfg, t), 0) / guard.length : 1;
141
+ const guardRegressed = guardScore(candidate) < guardScore(baseline) - EPS;
142
+ // Qualified trajectories — one per objective train task. Deterministic,
143
+ // executable checks with unambiguous ground truth → oracle:test-exec.
144
+ const trajectories = train.map((t) => ({
145
+ id: `fw-${t.id}`, steps: [{ action: 'retrieve', tier: 'oracle:test-exec' }],
146
+ outcome: 'success', benchmarkTaskId: `${blended.version}/${t.id}`,
147
+ inputs: { q: t.input.q }, recordedOutputs: { ranked: cache.get(`${t.id}::${cfgKey(candidate)}`) },
148
+ }));
149
+ const replay = (tr) => tr.recordedOutputs;
150
+ const anchorRegressed = guardRegressed; // ledger field: did the broad guard set regress?
151
+ const corpus = { version: blended.version, tasks: objective, corpusHash: hashCorpus(objective) };
152
+ const result = await runHarnessLoop({
153
+ trajectories, corpus, baseline, candidate, evalFn, gradeFn, replay,
154
+ verify: {
155
+ redblue: async () => (guardRegressed ? 'FAIL' : 'PASS'),
156
+ drift: async () => guard.length ? guard.filter((t) => heldScoreFor(candidate, t) < heldScoreFor(baseline, t) - EPS).length / guard.length : 0,
157
+ },
158
+ canaryRunner: (input, cfg) => {
159
+ const t = objective.find((x) => x.id === input.id);
160
+ const worse = heldScoreFor(cfg, t) < heldScoreFor(baseline, t) - EPS;
161
+ return { ok: !worse, rolledBack: worse, latencyMs: 0, costUsd: 0, accepted: !worse };
162
+ },
163
+ holdoutFrac: 0.5, driftThreshold: 0.2, layer: 'repo/local', policyRefOf: refOf, now: deps.now,
164
+ });
165
+ const baselineScore = result.baselineScore ?? 0;
166
+ const candidateScore = result.candidateScore ?? 0;
167
+ // Significance gate (SOTA noise guard): the per-held-out-task deltas must have
168
+ // a positive one-sided 95% bootstrap lower bound — the gain has to survive
169
+ // resampling, not ride on one lucky task. FINAL accept = loop-accept AND
170
+ // significant, so the ledger's accepted subsequence stays monotonic + real.
171
+ const heldDeltas = held.map((t) => heldScoreFor(candidate, t) - heldScoreFor(baseline, t));
172
+ const deltaCILow = bootstrapDeltaCILow(heldDeltas);
173
+ const significant = deltaCILow > 0;
174
+ const finalAccept = result.accepted && significant;
175
+ const entry = {
176
+ ts: deps.now ?? Date.now(),
177
+ corpusVersion: blended.version, corpusHash: blended.corpusHash,
178
+ corpusSize: blended.tasks.length, anchorSize: blended.anchorIds.length,
179
+ baselineRef: refOf(baseline), candidateRef: refOf(candidate),
180
+ baselineScore, candidateScore, delta: candidateScore - baselineScore,
181
+ deltaCILow, significant, loopAccepted: result.accepted,
182
+ anchorRegressed, accepted: finalAccept,
183
+ gates: Object.fromEntries(Object.entries(result.verdict?.terms ?? {}).map(([k, v]) => [k, v.pass])),
184
+ reason: finalAccept ? result.reason : (result.accepted ? `held back — improvement not significant (CI low ${deltaCILow.toFixed(4)})` : result.reason),
185
+ };
186
+ let applied = false;
187
+ if (finalAccept && result.manifest) {
188
+ entry.championRef = refOf(candidate);
189
+ // Apply locally (self-optimization) + chain to the previous champion.
190
+ const ap = applyChampionParams(projectRoot, {
191
+ championId: refOf(candidate), params: candidate,
192
+ layer: 'repo/local', previous: refOf(baseline), now: deps.now,
193
+ });
194
+ applied = ap.applied;
195
+ }
196
+ appendLedger(`${projectRoot}/.claude-flow/metrics`, entry);
197
+ return {
198
+ ran: true, reason: entry.reason, accepted: finalAccept, applied,
199
+ baselineScore, candidateScore, delta: candidateScore - baselineScore,
200
+ anchorRegressed, championRef: entry.championRef, corpusVersion: blended.version,
201
+ };
202
+ }
203
+ catch (e) {
204
+ return { ran: false, reason: `error: ${e?.message ?? e}` };
205
+ }
206
+ }
207
+ //# sourceMappingURL=harness-flywheel.js.map
@@ -0,0 +1,40 @@
1
+ export interface HostAdapter {
2
+ id: string;
3
+ label: string;
4
+ /** True when this host is usable in the current environment. */
5
+ detect: () => boolean;
6
+ }
7
+ export declare class HostRegistry {
8
+ private hosts;
9
+ register(a: HostAdapter): this;
10
+ get(id: string): HostAdapter | undefined;
11
+ all(): HostAdapter[];
12
+ /** Hosts present in this environment (detect() true, swallowing errors). */
13
+ available(): HostAdapter[];
14
+ }
15
+ /** True if `bin --version` runs. Used by the built-in adapters' detect(). */
16
+ export declare function commandExists(bin: string): boolean;
17
+ /** The built-in hosts. Detection is injectable per-adapter for tests. */
18
+ export declare function defaultHostRegistry(): HostRegistry;
19
+ /** Run `fn` for each host (sequentially, isolated), collecting per-host results. */
20
+ export declare function fanOutHosts<T>(hosts: HostAdapter[], fn: (h: HostAdapter) => Promise<T> | T): Promise<Array<{
21
+ host: string;
22
+ result: T | null;
23
+ error?: string;
24
+ }>>;
25
+ export declare const LAYER_LEVELS: readonly ["global", "language", "framework", "repo"];
26
+ /** All ancestor prefixes of a layer path, shallowest first. */
27
+ export declare function ancestorsOf(layer: string): string[];
28
+ /** True if `a` is an ancestor of (or equal to) `b` at a path boundary. */
29
+ export declare function isAncestorOrEqual(a: string, b: string): boolean;
30
+ export declare function layerDepth(layer: string): number;
31
+ /**
32
+ * Pick the most-specific champion applicable to an install's layer: the deepest
33
+ * manifest whose layer is an ancestor-or-equal of `installLayer`. Layers the
34
+ * install can't clear fall back to the parent (return the next-deepest). Null if
35
+ * none applies.
36
+ */
37
+ export declare function selectChampionForLayer<M extends {
38
+ layer?: string;
39
+ }>(manifests: M[], installLayer: string): M | null;
40
+ //# sourceMappingURL=harness-hosts.d.ts.map
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Host registry + hierarchical layers (ADR-176 phase 7).
3
+ *
4
+ * "All available hosts": a small registry (claude-code, codex, extensible) that
5
+ * the optimize+verify+canary pass fans out across, so a champion is proven
6
+ * per-host rather than via an unvalidated `--host` passthrough.
7
+ *
8
+ * Hierarchical evolution: repository-specific optima emerge, so evolution is
9
+ * layered — global → language → framework → repo — each layer inheriting upward
10
+ * but independently benchmarked. An install adopts the most-specific champion
11
+ * whose layer is an ancestor-or-equal of its own. Zero deps, $0.
12
+ */
13
+ import { execFileSync } from 'child_process';
14
+ export class HostRegistry {
15
+ hosts = new Map();
16
+ register(a) { this.hosts.set(a.id, a); return this; }
17
+ get(id) { return this.hosts.get(id); }
18
+ all() { return [...this.hosts.values()]; }
19
+ /** Hosts present in this environment (detect() true, swallowing errors). */
20
+ available() {
21
+ return this.all().filter(h => { try {
22
+ return h.detect();
23
+ }
24
+ catch {
25
+ return false;
26
+ } });
27
+ }
28
+ }
29
+ /** True if `bin --version` runs. Used by the built-in adapters' detect(). */
30
+ export function commandExists(bin) {
31
+ try {
32
+ execFileSync(bin, ['--version'], { stdio: 'ignore', timeout: 3000 });
33
+ return true;
34
+ }
35
+ catch {
36
+ return false;
37
+ }
38
+ }
39
+ /** The built-in hosts. Detection is injectable per-adapter for tests. */
40
+ export function defaultHostRegistry() {
41
+ return new HostRegistry()
42
+ .register({ id: 'claude-code', label: 'Claude Code', detect: () => commandExists('claude') })
43
+ .register({ id: 'codex', label: 'OpenAI Codex', detect: () => commandExists('codex') });
44
+ }
45
+ /** Run `fn` for each host (sequentially, isolated), collecting per-host results. */
46
+ export async function fanOutHosts(hosts, fn) {
47
+ const out = [];
48
+ for (const h of hosts) {
49
+ try {
50
+ out.push({ host: h.id, result: await fn(h) });
51
+ }
52
+ catch (e) {
53
+ out.push({ host: h.id, result: null, error: e?.message ?? String(e) });
54
+ }
55
+ }
56
+ return out;
57
+ }
58
+ // ── Hierarchical layers ─────────────────────────────────────────────────────
59
+ export const LAYER_LEVELS = ['global', 'language', 'framework', 'repo'];
60
+ /** All ancestor prefixes of a layer path, shallowest first. */
61
+ export function ancestorsOf(layer) {
62
+ const parts = layer.split('/').filter(Boolean);
63
+ const out = [];
64
+ for (let i = 1; i <= parts.length; i++)
65
+ out.push(parts.slice(0, i).join('/'));
66
+ return out;
67
+ }
68
+ /** True if `a` is an ancestor of (or equal to) `b` at a path boundary. */
69
+ export function isAncestorOrEqual(a, b) {
70
+ return a === b || b.startsWith(a + '/');
71
+ }
72
+ export function layerDepth(layer) {
73
+ return layer.split('/').filter(Boolean).length;
74
+ }
75
+ /**
76
+ * Pick the most-specific champion applicable to an install's layer: the deepest
77
+ * manifest whose layer is an ancestor-or-equal of `installLayer`. Layers the
78
+ * install can't clear fall back to the parent (return the next-deepest). Null if
79
+ * none applies.
80
+ */
81
+ export function selectChampionForLayer(manifests, installLayer) {
82
+ const applicable = manifests.filter(m => !!m.layer && isAncestorOrEqual(m.layer, installLayer));
83
+ if (applicable.length === 0)
84
+ return null;
85
+ applicable.sort((x, y) => layerDepth(y.layer) - layerDepth(x.layer));
86
+ return applicable[0];
87
+ }
88
+ //# sourceMappingURL=harness-hosts.js.map
@@ -0,0 +1,63 @@
1
+ export declare const LEDGER_FILE = "harness-improvement.jsonl";
2
+ export interface LedgerEntry {
3
+ ts: number;
4
+ corpusVersion: string;
5
+ corpusHash: string;
6
+ corpusSize: number;
7
+ anchorSize: number;
8
+ baselineRef: string;
9
+ candidateRef: string;
10
+ baselineScore: number;
11
+ candidateScore: number;
12
+ delta: number;
13
+ deltaCILow?: number;
14
+ significant?: boolean;
15
+ loopAccepted?: boolean;
16
+ anchorRegressed: boolean;
17
+ accepted: boolean;
18
+ gates: Record<string, boolean>;
19
+ championRef?: string;
20
+ reason: string;
21
+ }
22
+ /**
23
+ * One-sided 95% bootstrap lower bound on the mean of paired per-task deltas.
24
+ * Deterministic (seeded LCG) so the confidence bound is reproducible — the same
25
+ * evidence yields the same verdict. A positive lower bound means the improvement
26
+ * survives resampling: it is not an artifact of a lucky held-out task (small-N
27
+ * noise guard, "measured not marketing").
28
+ */
29
+ export declare function bootstrapDeltaCILow(deltas: number[], opts?: {
30
+ iters?: number;
31
+ alpha?: number;
32
+ seed?: number;
33
+ }): number;
34
+ export interface ImprovementSummary {
35
+ attempts: number;
36
+ accepted: number;
37
+ rejected: number;
38
+ cumulativeDelta: number;
39
+ currentScore: number | null;
40
+ firstScore: number | null;
41
+ monotonic: boolean;
42
+ chainIntact: boolean;
43
+ trajectory: Array<{
44
+ ts: number;
45
+ corpusVersion: string;
46
+ baseline: number;
47
+ candidate: number;
48
+ delta: number;
49
+ accepted: boolean;
50
+ }>;
51
+ }
52
+ /** Append one attempt. Best-effort, never throws; rotates when over the cap. */
53
+ export declare function appendLedger(dir: string, entry: LedgerEntry): void;
54
+ /** Read all ledger entries (oldest → newest). Never throws. */
55
+ export declare function readLedger(dir: string): LedgerEntry[];
56
+ /**
57
+ * Fold the ledger into an auditable improvement claim. Monotonicity + chain
58
+ * integrity are the PROOF: they hold iff every shipped champion strictly beat
59
+ * its predecessor and referenced it. A single violation flips the flag — the
60
+ * summary cannot silently launder a regression.
61
+ */
62
+ export declare function summarizeImprovement(dir: string): ImprovementSummary;
63
+ //# sourceMappingURL=harness-improvement-ledger.d.ts.map
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Improvement ledger — the proof-of-improvement surface for the self-optimizing
3
+ * flywheel (ADR-176). Every mint ATTEMPT (accepted or rejected) is appended to a
4
+ * bounded, append-only JSONL. Because runHarnessLoop only ACCEPTS a strict
5
+ * improvement (held_out_improves AND canary-no-worse AND anchor-no-regress), the
6
+ * subsequence of accepted champions is monotonically non-decreasing in held-out
7
+ * score BY CONSTRUCTION — and each accepted entry chains to its predecessor via
8
+ * baselineRef == previous championRef. summarizeImprovement() turns that into an
9
+ * auditable claim: "N champions shipped, each strictly beat the last, cumulative
10
+ * +X; M attempts refused (the gate is not a rubber stamp)."
11
+ *
12
+ * Pure Node, $0. Rotation-capped so an always-on daemon can't grow it unbounded.
13
+ */
14
+ import * as fs from 'fs';
15
+ import * as path from 'path';
16
+ export const LEDGER_FILE = 'harness-improvement.jsonl';
17
+ const MAX_ENTRIES = 5000; // rotation cap (keeps the most-recent tail)
18
+ /**
19
+ * One-sided 95% bootstrap lower bound on the mean of paired per-task deltas.
20
+ * Deterministic (seeded LCG) so the confidence bound is reproducible — the same
21
+ * evidence yields the same verdict. A positive lower bound means the improvement
22
+ * survives resampling: it is not an artifact of a lucky held-out task (small-N
23
+ * noise guard, "measured not marketing").
24
+ */
25
+ export function bootstrapDeltaCILow(deltas, opts = {}) {
26
+ const n = deltas.length;
27
+ if (n === 0)
28
+ return 0;
29
+ const iters = opts.iters ?? 2000;
30
+ const alpha = opts.alpha ?? 0.05;
31
+ let seed = (opts.seed ?? 0x9e3779b1) >>> 0;
32
+ const rnd = () => { seed = (1664525 * seed + 1013904223) >>> 0; return seed / 4294967296; };
33
+ const means = new Array(iters);
34
+ for (let b = 0; b < iters; b++) {
35
+ let s = 0;
36
+ for (let i = 0; i < n; i++)
37
+ s += deltas[Math.floor(rnd() * n)];
38
+ means[b] = s / n;
39
+ }
40
+ means.sort((a, b) => a - b);
41
+ return means[Math.floor(alpha * iters)];
42
+ }
43
+ function ledgerPath(dir) {
44
+ return path.join(dir, LEDGER_FILE);
45
+ }
46
+ /** Append one attempt. Best-effort, never throws; rotates when over the cap. */
47
+ export function appendLedger(dir, entry) {
48
+ try {
49
+ fs.mkdirSync(dir, { recursive: true });
50
+ const p = ledgerPath(dir);
51
+ fs.appendFileSync(p, JSON.stringify(entry) + '\n', 'utf-8');
52
+ // Rotate: if too many lines, keep the most-recent MAX_ENTRIES.
53
+ const lines = fs.readFileSync(p, 'utf-8').split('\n').filter(Boolean);
54
+ if (lines.length > MAX_ENTRIES) {
55
+ fs.writeFileSync(p, lines.slice(lines.length - MAX_ENTRIES).join('\n') + '\n', 'utf-8');
56
+ }
57
+ }
58
+ catch { /* non-fatal */ }
59
+ }
60
+ /** Read all ledger entries (oldest → newest). Never throws. */
61
+ export function readLedger(dir) {
62
+ try {
63
+ const raw = fs.readFileSync(ledgerPath(dir), 'utf-8');
64
+ return raw.split('\n').filter(Boolean).map((l) => JSON.parse(l));
65
+ }
66
+ catch {
67
+ return [];
68
+ }
69
+ }
70
+ /**
71
+ * Fold the ledger into an auditable improvement claim. Monotonicity + chain
72
+ * integrity are the PROOF: they hold iff every shipped champion strictly beat
73
+ * its predecessor and referenced it. A single violation flips the flag — the
74
+ * summary cannot silently launder a regression.
75
+ */
76
+ export function summarizeImprovement(dir) {
77
+ const all = readLedger(dir);
78
+ const accepted = all.filter((e) => e.accepted);
79
+ let monotonic = true;
80
+ let chainIntact = true;
81
+ for (let i = 0; i < accepted.length; i++) {
82
+ if (!(accepted[i].candidateScore > accepted[i].baselineScore))
83
+ monotonic = false;
84
+ if (accepted[i].anchorRegressed)
85
+ monotonic = false;
86
+ if (i > 0 && accepted[i].baselineRef !== accepted[i - 1].championRef)
87
+ chainIntact = false;
88
+ }
89
+ return {
90
+ attempts: all.length,
91
+ accepted: accepted.length,
92
+ rejected: all.length - accepted.length,
93
+ cumulativeDelta: accepted.reduce((s, e) => s + e.delta, 0),
94
+ currentScore: accepted.length ? accepted[accepted.length - 1].candidateScore : null,
95
+ firstScore: accepted.length ? accepted[0].baselineScore : null,
96
+ monotonic,
97
+ chainIntact,
98
+ trajectory: all.map((e) => ({ ts: e.ts, corpusVersion: e.corpusVersion, baseline: e.baselineScore, candidate: e.candidateScore, delta: e.delta, accepted: e.accepted })),
99
+ };
100
+ }
101
+ //# sourceMappingURL=harness-improvement-ledger.js.map
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Loop orchestrator (ADR-176 phase 8).
3
+ *
4
+ * Composes every gate into one pass:
5
+ * OBSERVE → QUALIFY → BENCHMARK(held-out) → VERIFY(adversarial+drift)
6
+ * → CANARY → ACCEPT(conjunction) → emit champion manifest.
7
+ *
8
+ * $0 + fail-closed by default: with no optimizer/verifier/canary wired, nothing
9
+ * is promoted and the current signed champion stands. A champion manifest is
10
+ * emitted ONLY when every accept() term holds — and it is emitted UNSIGNED here;
11
+ * signing is a separate publish step (scripts/sign-proven-config.mjs, GCP key)
12
+ * so key material never touches the loop. The daemon worker runs this bounded.
13
+ */
14
+ import { AntiPatternArchive, type Trajectory, type ReplayFn } from './harness-qualification.js';
15
+ import { type HarnessBenchmarkCorpus, type EvalFn, type GradeFn, type AcceptResult } from './harness-benchmark.js';
16
+ import { type VerifyOptions, type VerifyResult } from './harness-verify.js';
17
+ import { type CanaryRunner, type CanaryTelemetry } from './harness-canary.js';
18
+ import type { ProvenConfigManifest } from '../config/proven-config.js';
19
+ export interface HarnessLoopOptions<C> {
20
+ trajectories: Trajectory[];
21
+ corpus: HarnessBenchmarkCorpus;
22
+ baseline: C;
23
+ candidate?: C;
24
+ evalFn: EvalFn<C>;
25
+ gradeFn: GradeFn;
26
+ replay?: ReplayFn;
27
+ verify?: VerifyOptions;
28
+ canaryRunner?: CanaryRunner<C>;
29
+ archive?: AntiPatternArchive;
30
+ holdoutFrac?: number;
31
+ driftThreshold?: number;
32
+ layer?: string;
33
+ policyRefOf?: (candidate: C) => string;
34
+ now?: number;
35
+ }
36
+ export interface HarnessLoopResult {
37
+ admitted: number;
38
+ rejected: number;
39
+ baselineScore?: number;
40
+ candidateScore?: number;
41
+ verify?: VerifyResult;
42
+ canary?: {
43
+ candidate: CanaryTelemetry;
44
+ baseline: CanaryTelemetry;
45
+ pass: boolean;
46
+ };
47
+ verdict?: AcceptResult;
48
+ accepted: boolean;
49
+ manifest?: ProvenConfigManifest;
50
+ reason: string;
51
+ }
52
+ export declare function runHarnessLoop<C>(opts: HarnessLoopOptions<C>): Promise<HarnessLoopResult>;
53
+ //# sourceMappingURL=harness-loop.d.ts.map
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Loop orchestrator (ADR-176 phase 8).
3
+ *
4
+ * Composes every gate into one pass:
5
+ * OBSERVE → QUALIFY → BENCHMARK(held-out) → VERIFY(adversarial+drift)
6
+ * → CANARY → ACCEPT(conjunction) → emit champion manifest.
7
+ *
8
+ * $0 + fail-closed by default: with no optimizer/verifier/canary wired, nothing
9
+ * is promoted and the current signed champion stands. A champion manifest is
10
+ * emitted ONLY when every accept() term holds — and it is emitted UNSIGNED here;
11
+ * signing is a separate publish step (scripts/sign-proven-config.mjs, GCP key)
12
+ * so key material never touches the loop. The daemon worker runs this bounded.
13
+ */
14
+ import { admitTrajectories } from './harness-qualification.js';
15
+ import { computeHeldOutSplit, scoreOnTasks, accept, } from './harness-benchmark.js';
16
+ import { runVerify } from './harness-verify.js';
17
+ import { runCanary, compareCanary } from './harness-canary.js';
18
+ export async function runHarnessLoop(opts) {
19
+ const driftThreshold = opts.driftThreshold ?? 0.05;
20
+ // 1. QUALIFY — only receipt-backed, deterministic, benchmark-attributed
21
+ // trajectories become training data; rejects → anti-pattern archive.
22
+ const admission = admitTrajectories(opts.trajectories, { replay: opts.replay, archive: opts.archive, ts: opts.now });
23
+ const base = { admitted: admission.admittedCount, rejected: admission.rejectedCount, accepted: false, reason: '' };
24
+ if (admission.admittedCount === 0)
25
+ return { ...base, reason: 'no qualified trajectories (receipt_coverage=0)' };
26
+ if (opts.candidate === undefined)
27
+ return { ...base, reason: 'no candidate to evaluate' };
28
+ // 2. BENCHMARK — held-out scoring (isolated, reproducible split).
29
+ const { heldOut } = computeHeldOutSplit(opts.corpus.tasks, opts.holdoutFrac ?? 0.2);
30
+ const baselineScore = scoreOnTasks(heldOut, opts.baseline, opts.evalFn, opts.gradeFn).fitness;
31
+ const candidateScore = scoreOnTasks(heldOut, opts.candidate, opts.evalFn, opts.gradeFn).fitness;
32
+ // 3. VERIFY — adversarial + drift (fail-closed: SKIPPED cannot pass).
33
+ const verify = await runVerify({ ...opts.verify, driftThreshold });
34
+ // 4. CANARY — required (separate promotion from deployment); absent => no promote.
35
+ if (!opts.canaryRunner) {
36
+ return { ...base, baselineScore, candidateScore, verify, accepted: false, reason: 'canary required (no runner) — cannot promote' };
37
+ }
38
+ const slice = opts.corpus.tasks.map(t => ({ id: t.id, input: t.input }));
39
+ const canaryCand = runCanary(opts.candidate, slice, opts.canaryRunner);
40
+ const canaryBase = runCanary(opts.baseline, slice, opts.canaryRunner);
41
+ const canaryCmp = compareCanary(canaryCand, canaryBase);
42
+ // 5. ACCEPT — the full conjunction. receipt_coverage=1 by construction (only
43
+ // qualified trajectories are used; rejects were excluded).
44
+ const verdict = {
45
+ heldOutScore: candidateScore,
46
+ baselineHeldOutScore: baselineScore,
47
+ redblue: verify.redblue,
48
+ drift: verify.drift < 0 ? Number.POSITIVE_INFINITY : verify.drift,
49
+ driftThreshold,
50
+ replayDeterministic: !!opts.replay, // qualification already enforced replay determinism on admitted set
51
+ receiptCoverage: 1,
52
+ canaryRollbackRate: canaryCand.rollbackRate,
53
+ baselineRollbackRate: canaryBase.rollbackRate,
54
+ };
55
+ const decision = accept(verdict);
56
+ const result = {
57
+ ...base, baselineScore, candidateScore, verify,
58
+ canary: { candidate: canaryCand, baseline: canaryBase, pass: canaryCmp.pass },
59
+ verdict: decision, accepted: decision.accept,
60
+ reason: decision.accept ? 'accepted — all gates hold' : `rejected — ${decision.failed.join(', ')}`,
61
+ };
62
+ // 6. EMIT the champion manifest (UNSIGNED) on acceptance.
63
+ if (decision.accept && canaryCmp.pass) {
64
+ result.manifest = {
65
+ schema: 'ruflo.proven-config/v1',
66
+ policy: { ref: opts.policyRefOf ? opts.policyRefOf(opts.candidate) : 'sha256:unknown' },
67
+ layer: opts.layer,
68
+ compatibility: { ruflo: '>=3.24.0' },
69
+ benchmark: { corpus: opts.corpus.version, corpusHash: opts.corpus.corpusHash },
70
+ receipt: {
71
+ heldOutDelta: candidateScore - baselineScore,
72
+ redblue: verify.redblue,
73
+ drift: verify.drift,
74
+ canary: { rollbackRate: canaryCand.rollbackRate, latencyP95: canaryCand.latencyP95, costPerTask: canaryCand.costPerTask },
75
+ receiptCoverage: 1,
76
+ },
77
+ };
78
+ }
79
+ else if (decision.accept && !canaryCmp.pass) {
80
+ result.accepted = false;
81
+ result.reason = `rejected — canary regressed (${canaryCmp.failed.join(', ')})`;
82
+ }
83
+ return result;
84
+ }
85
+ //# sourceMappingURL=harness-loop.js.map