claude-flow 3.21.1 → 3.22.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/package.json +1 -1
- package/v3/@claude-flow/cli/dist/src/commands/daemon.js +23 -2
- package/v3/@claude-flow/cli/dist/src/commands/memory-distill.d.ts +27 -0
- package/v3/@claude-flow/cli/dist/src/commands/memory-distill.js +374 -0
- package/v3/@claude-flow/cli/dist/src/commands/memory.js +4 -2
- package/v3/@claude-flow/cli/dist/src/index.d.ts +1 -1
- package/v3/@claude-flow/cli/dist/src/index.js +22 -1
- package/v3/@claude-flow/cli/dist/src/init/executor.js +20 -0
- package/v3/@claude-flow/cli/dist/src/init/helper-refresh.d.ts +19 -0
- package/v3/@claude-flow/cli/dist/src/init/helper-refresh.js +175 -0
- package/v3/@claude-flow/cli/dist/src/init/helper-signing.d.ts +30 -0
- package/v3/@claude-flow/cli/dist/src/init/helper-signing.js +60 -0
- package/v3/@claude-flow/cli/dist/src/init/helpers-generator.d.ts +16 -0
- package/v3/@claude-flow/cli/dist/src/init/helpers-generator.js +63 -6
- package/v3/@claude-flow/cli/dist/src/init/statusline-generator.js +18 -7
- package/v3/@claude-flow/cli/dist/src/mcp-client.js +13 -0
- package/v3/@claude-flow/cli/dist/src/mcp-tools/agenticow-speculate-tools.js +9 -2
- package/v3/@claude-flow/cli/dist/src/mcp-tools/browser-intent-tools.d.ts +162 -0
- package/v3/@claude-flow/cli/dist/src/mcp-tools/browser-intent-tools.js +548 -0
- package/v3/@claude-flow/cli/dist/src/mcp-tools/browser-tools.d.ts +9 -1
- package/v3/@claude-flow/cli/dist/src/mcp-tools/browser-tools.js +4 -1
- package/v3/@claude-flow/cli/dist/src/memory/memory-bridge.js +67 -47
- package/v3/@claude-flow/cli/dist/src/memory/memory-initializer.d.ts +71 -0
- package/v3/@claude-flow/cli/dist/src/memory/memory-initializer.js +330 -2
- package/v3/@claude-flow/cli/dist/src/services/distill-tuning.d.ts +111 -0
- package/v3/@claude-flow/cli/dist/src/services/distill-tuning.js +510 -0
- package/v3/@claude-flow/cli/dist/src/services/memory-distillation.d.ts +41 -0
- package/v3/@claude-flow/cli/dist/src/services/memory-distillation.js +277 -0
- package/v3/@claude-flow/cli/dist/src/services/worker-daemon.d.ts +22 -1
- package/v3/@claude-flow/cli/dist/src/services/worker-daemon.js +117 -6
- package/v3/@claude-flow/cli/package.json +5 -2
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
export type PromoteThreshold = 'execution-only' | 'execution+corroborated';
|
|
2
|
+
export interface TuningConfig {
|
|
3
|
+
batchSize: number;
|
|
4
|
+
dedupDistance: number;
|
|
5
|
+
promoteThreshold: PromoteThreshold;
|
|
6
|
+
}
|
|
7
|
+
export interface ParamGrid {
|
|
8
|
+
batchSize?: number[];
|
|
9
|
+
dedupDistance?: number[];
|
|
10
|
+
promoteThreshold?: PromoteThreshold[];
|
|
11
|
+
}
|
|
12
|
+
export interface TuningCandidate {
|
|
13
|
+
config: TuningConfig;
|
|
14
|
+
/** MRR@10 on the inner train-query split (never the true held-out set). */
|
|
15
|
+
trainScore: number;
|
|
16
|
+
trainRecallAt10: number;
|
|
17
|
+
trainQueryCount: number;
|
|
18
|
+
patternCount: number;
|
|
19
|
+
promotedCount: number;
|
|
20
|
+
distillMs: number;
|
|
21
|
+
/** Present iff M1 itself skipped this run (corrupt DB, missing tables, ...). */
|
|
22
|
+
skipped?: string;
|
|
23
|
+
}
|
|
24
|
+
export interface HeldOutScore {
|
|
25
|
+
mrrAt10: number;
|
|
26
|
+
recallAt10: number;
|
|
27
|
+
queryCount: number;
|
|
28
|
+
/** Same held-out query set scored against raw (undistilled) train entries. */
|
|
29
|
+
baselineMrrAt10: number;
|
|
30
|
+
baselineRecallAt10: number;
|
|
31
|
+
}
|
|
32
|
+
export interface TuningProvenance {
|
|
33
|
+
gridSize: number;
|
|
34
|
+
corpusSize: number;
|
|
35
|
+
trainSize: number;
|
|
36
|
+
heldOutSize: number;
|
|
37
|
+
metric: 'mrr@10';
|
|
38
|
+
/** Stamped from `options.now` (or the orchestrator's own Date.now() at the
|
|
39
|
+
* I/O boundary) — never read from inside pure scoring logic. */
|
|
40
|
+
tunedAt: number;
|
|
41
|
+
sourceDbPath: string;
|
|
42
|
+
sourceChecksumSha256: string;
|
|
43
|
+
}
|
|
44
|
+
export interface TuningReport {
|
|
45
|
+
candidates: TuningCandidate[];
|
|
46
|
+
winner: TuningCandidate;
|
|
47
|
+
heldOut: HeldOutScore;
|
|
48
|
+
/** True when held-out MRR@10 is >20% worse (relative) than the winner's train score. */
|
|
49
|
+
overfit: boolean;
|
|
50
|
+
provenance: TuningProvenance;
|
|
51
|
+
}
|
|
52
|
+
export interface TuneDistillationOptions {
|
|
53
|
+
/** Source DB — read (copied + hashed) only; NEVER opened with a DB connection. */
|
|
54
|
+
dbPath: string;
|
|
55
|
+
grid?: ParamGrid;
|
|
56
|
+
/** Namespaces to distill / include in the raw baseline pool (default: all). */
|
|
57
|
+
namespaces?: string[];
|
|
58
|
+
/** Outer train/held-out split fraction (default 0.8). */
|
|
59
|
+
trainFraction?: number;
|
|
60
|
+
/** Namespaces the query set is drawn from (default: feedback + commands). */
|
|
61
|
+
queryNamespaces?: string[];
|
|
62
|
+
topK?: number;
|
|
63
|
+
/** Timestamp stamped into `provenance.tunedAt`. Caller-supplied so the core
|
|
64
|
+
* logic stays a pure function of its inputs; defaults to `Date.now()` at
|
|
65
|
+
* this I/O boundary if omitted. */
|
|
66
|
+
now?: number;
|
|
67
|
+
tmpDir?: string;
|
|
68
|
+
verbose?: boolean;
|
|
69
|
+
}
|
|
70
|
+
export interface TimeSplit {
|
|
71
|
+
totalRows: number;
|
|
72
|
+
trainBoundaryRowid: number;
|
|
73
|
+
trainRowids: number[];
|
|
74
|
+
heldOutRowids: number[];
|
|
75
|
+
}
|
|
76
|
+
export interface TunedConfigFile {
|
|
77
|
+
batchSize: number;
|
|
78
|
+
dedupDistance: number;
|
|
79
|
+
promoteThreshold: PromoteThreshold;
|
|
80
|
+
provenance: TuningProvenance & {
|
|
81
|
+
winnerTrainScore: number;
|
|
82
|
+
heldOutScore: number;
|
|
83
|
+
baselineHeldOutScore: number;
|
|
84
|
+
overfit: boolean;
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
export declare const DEFAULT_GRID_BATCH_SIZE: number[];
|
|
88
|
+
export declare const DEFAULT_GRID_DEDUP_DISTANCE: number[];
|
|
89
|
+
export declare const DEFAULT_GRID_PROMOTE_THRESHOLD: PromoteThreshold[];
|
|
90
|
+
/**
|
|
91
|
+
* Grid-search the distillation config against isolated copies of `dbPath`,
|
|
92
|
+
* scored on a held-out split. See module header for the full methodology.
|
|
93
|
+
*/
|
|
94
|
+
export declare function tuneDistillation(options: TuneDistillationOptions): Promise<TuningReport>;
|
|
95
|
+
/** Shape the winning config + provenance for persistence. Pure — no I/O. */
|
|
96
|
+
export declare function buildTunedConfigFile(report: TuningReport): TunedConfigFile;
|
|
97
|
+
/** Write the winning config to disk. Caller decides whether/where to call this. */
|
|
98
|
+
export declare function writeTunedConfigFile(report: TuningReport, filePath: string): void;
|
|
99
|
+
/** Where the tuned config lives by default, for daemon/CLI callers. */
|
|
100
|
+
export declare function defaultTunedConfigPath(cwd?: string): string;
|
|
101
|
+
/**
|
|
102
|
+
* Split a table's rows by rowid (a monotonic proxy for insertion time) into
|
|
103
|
+
* an earliest `trainFraction` chunk and a most-recent remainder. Pure given a
|
|
104
|
+
* fixed db snapshot. `table`/`extraWhere` are only ever called with internal
|
|
105
|
+
* literal strings (never external input) — not a SQL-injection surface.
|
|
106
|
+
*/
|
|
107
|
+
export declare function computeTimeSplit(db: unknown, trainFraction: number, opts?: {
|
|
108
|
+
table?: string;
|
|
109
|
+
extraWhere?: string;
|
|
110
|
+
}): TimeSplit;
|
|
111
|
+
//# sourceMappingURL=distill-tuning.d.ts.map
|
|
@@ -0,0 +1,510 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* distill-tuning.ts — Milestone 4 self-optimization harness (ADR-174
|
|
3
|
+
* "Self-optimization (ruflo tuning ruflo)").
|
|
4
|
+
*
|
|
5
|
+
* Finds the memory-distillation config (batchSize, dedupDistance,
|
|
6
|
+
* promoteThreshold) that maximises MEASURED retrieval quality — not a
|
|
7
|
+
* marketing claim — via grid search over ISOLATED copies of a source DB,
|
|
8
|
+
* scored on a held-out split. $0, offline, no LLM.
|
|
9
|
+
*
|
|
10
|
+
* ── M1 is frozen ────────────────────────────────────────────────────────────
|
|
11
|
+
* `runDistillation` (memory-distillation.ts) is Milestone 1 and DONE. This
|
|
12
|
+
* module only imports and calls it; it never changes its behaviour.
|
|
13
|
+
* `promoteThreshold` is NOT an M1 parameter, so the two grid values are
|
|
14
|
+
* implemented here as a post-processing pass over the copy's
|
|
15
|
+
* `reasoning_patterns.metadata` after M1 has run (see
|
|
16
|
+
* `applyCorroboratedPromotion`) — 'execution-only' leaves M1's own promote
|
|
17
|
+
* gate untouched (only `oracle:test-exec` promotes, per ADR-171);
|
|
18
|
+
* 'execution+corroborated' additionally promotes `proxy:structural` patterns
|
|
19
|
+
* that multiple near-duplicate entries corroborated (`uses >=
|
|
20
|
+
* CORROBORATION_MIN_USES`), widening the promoted-recall pool.
|
|
21
|
+
*
|
|
22
|
+
* ── Isolation (load-bearing) ─────────────────────────────────────────────
|
|
23
|
+
* The source DB at `options.dbPath` is NEVER opened with a database
|
|
24
|
+
* connection anywhere in this module — only `fs.copyFileSync` (byte copy)
|
|
25
|
+
* and a whole-file sha256 checksum (`fs.readFileSync`) ever touch it. Every
|
|
26
|
+
* grid candidate, and the read-only split/query-set pass, runs against its
|
|
27
|
+
* OWN temp copy. The checksum is asserted equal before and after the whole
|
|
28
|
+
* run.
|
|
29
|
+
*
|
|
30
|
+
* ── Held-out discipline (ADR-174 §Self-optimization) ─────────────────────
|
|
31
|
+
* Earliest ~80% of `memory_entries` (by rowid — a monotonic proxy for
|
|
32
|
+
* insertion time) = TRAIN, most-recent ~20% = HELD-OUT. HELD-OUT is scored
|
|
33
|
+
* exactly ONCE, for the winning config only, AFTER the winner has already
|
|
34
|
+
* been chosen using an INNER 80/20 split of TRAIN itself (so grid search
|
|
35
|
+
* never peeks at the true held-out set — tuning isn't circular).
|
|
36
|
+
*
|
|
37
|
+
* @module services/distill-tuning
|
|
38
|
+
*/
|
|
39
|
+
import * as fs from 'fs';
|
|
40
|
+
import * as path from 'path';
|
|
41
|
+
import * as os from 'os';
|
|
42
|
+
import * as crypto from 'crypto';
|
|
43
|
+
import { runDistillation } from './memory-distillation.js';
|
|
44
|
+
import { distillTrajectoryContent } from '../memory/structured-distill.js';
|
|
45
|
+
import { cosineSim } from '../memory/hybrid-retrieval.js';
|
|
46
|
+
// ── Grid defaults (requirement 1) ───────────────────────────────────────
|
|
47
|
+
export const DEFAULT_GRID_BATCH_SIZE = [100, 200, 500];
|
|
48
|
+
export const DEFAULT_GRID_DEDUP_DISTANCE = [0.05, 0.1, 0.15, 0.2, 0.3];
|
|
49
|
+
export const DEFAULT_GRID_PROMOTE_THRESHOLD = [
|
|
50
|
+
'execution-only',
|
|
51
|
+
'execution+corroborated',
|
|
52
|
+
];
|
|
53
|
+
const DEFAULT_TOP_K = 10;
|
|
54
|
+
const DEFAULT_TRAIN_FRACTION = 0.8;
|
|
55
|
+
const DEFAULT_QUERY_NAMESPACES = ['feedback', 'commands'];
|
|
56
|
+
/** Minimum corroborating uses for a proxy:structural pattern to promote under
|
|
57
|
+
* 'execution+corroborated' — multiple near-duplicate entries clustering into
|
|
58
|
+
* one pattern is treated as weak corroboration (still not oracle ground
|
|
59
|
+
* truth; ADR-171 discipline is preserved by keeping this a distinct,
|
|
60
|
+
* visibly-named policy rather than silently loosening the default gate). */
|
|
61
|
+
const CORROBORATION_MIN_USES = 2;
|
|
62
|
+
/** Caps the raw-baseline candidate pool so scoring stays fast on large corpora. */
|
|
63
|
+
const MAX_BASELINE_INDEX_SIZE = 3000;
|
|
64
|
+
// ── Public entry point ───────────────────────────────────────────────────
|
|
65
|
+
/**
|
|
66
|
+
* Grid-search the distillation config against isolated copies of `dbPath`,
|
|
67
|
+
* scored on a held-out split. See module header for the full methodology.
|
|
68
|
+
*/
|
|
69
|
+
export async function tuneDistillation(options) {
|
|
70
|
+
const { dbPath, grid = {}, namespaces, trainFraction = DEFAULT_TRAIN_FRACTION, queryNamespaces = DEFAULT_QUERY_NAMESPACES, topK = DEFAULT_TOP_K, now, tmpDir = os.tmpdir(), verbose = false, } = options;
|
|
71
|
+
if (!dbPath || !fs.existsSync(dbPath)) {
|
|
72
|
+
throw new Error(`tuneDistillation: source db not found at ${dbPath}`);
|
|
73
|
+
}
|
|
74
|
+
const Database = await loadBetterSqlite3();
|
|
75
|
+
if (!Database) {
|
|
76
|
+
throw new Error('tuneDistillation: better-sqlite3 unavailable — cannot run the tuning harness');
|
|
77
|
+
}
|
|
78
|
+
const sourceChecksumBefore = sha256File(dbPath);
|
|
79
|
+
const batchSizes = grid.batchSize ?? DEFAULT_GRID_BATCH_SIZE;
|
|
80
|
+
const dedupDistances = grid.dedupDistance ?? DEFAULT_GRID_DEDUP_DISTANCE;
|
|
81
|
+
const promoteThresholds = grid.promoteThreshold ?? DEFAULT_GRID_PROMOTE_THRESHOLD;
|
|
82
|
+
const configs = [];
|
|
83
|
+
for (const batchSize of batchSizes) {
|
|
84
|
+
for (const dedupDistance of dedupDistances) {
|
|
85
|
+
for (const promoteThreshold of promoteThresholds) {
|
|
86
|
+
configs.push({ batchSize, dedupDistance, promoteThreshold });
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (configs.length === 0) {
|
|
91
|
+
throw new Error('tuneDistillation: empty grid — supply at least one value per grid axis');
|
|
92
|
+
}
|
|
93
|
+
// ── Splits + query sets: a dedicated read-only copy, never the source itself ──
|
|
94
|
+
const readCopy = copyToTemp(dbPath, tmpDir, 'split-read');
|
|
95
|
+
let outerSplit;
|
|
96
|
+
let innerSplit;
|
|
97
|
+
let trainQuerySet;
|
|
98
|
+
let heldOutQuerySet;
|
|
99
|
+
let heldOutBaselineIndex;
|
|
100
|
+
try {
|
|
101
|
+
const readDb = new Database(readCopy, { readonly: true });
|
|
102
|
+
try {
|
|
103
|
+
outerSplit = computeTimeSplit(readDb, trainFraction);
|
|
104
|
+
assertDisjoint(outerSplit.trainRowids, outerSplit.heldOutRowids);
|
|
105
|
+
innerSplit = computeTimeSplit(readDb, trainFraction, {
|
|
106
|
+
extraWhere: `rowid <= ${outerSplit.trainBoundaryRowid}`,
|
|
107
|
+
});
|
|
108
|
+
assertDisjoint(innerSplit.trainRowids, innerSplit.heldOutRowids);
|
|
109
|
+
trainQuerySet = buildQuerySet(readDb, {
|
|
110
|
+
loRowid: innerSplit.trainBoundaryRowid,
|
|
111
|
+
hiRowid: outerSplit.trainBoundaryRowid,
|
|
112
|
+
namespaces: queryNamespaces,
|
|
113
|
+
});
|
|
114
|
+
heldOutQuerySet = buildQuerySet(readDb, {
|
|
115
|
+
loRowid: outerSplit.trainBoundaryRowid,
|
|
116
|
+
hiRowid: Infinity,
|
|
117
|
+
namespaces: queryNamespaces,
|
|
118
|
+
});
|
|
119
|
+
heldOutBaselineIndex = buildRawIndex(readDb, {
|
|
120
|
+
loRowid: 0,
|
|
121
|
+
hiRowid: outerSplit.trainBoundaryRowid,
|
|
122
|
+
namespaces,
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
finally {
|
|
126
|
+
readDb.close();
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
safeUnlink(readCopy);
|
|
131
|
+
}
|
|
132
|
+
// ── Grid search: TRAIN-internal scoring only — never touches heldOutQuerySet ──
|
|
133
|
+
const candidates = [];
|
|
134
|
+
for (const config of configs) {
|
|
135
|
+
if (verbose)
|
|
136
|
+
console.log(`tuneDistillation: evaluating ${JSON.stringify(config)}`);
|
|
137
|
+
const result = await evaluateCandidate({
|
|
138
|
+
Database,
|
|
139
|
+
sourceDbPath: dbPath,
|
|
140
|
+
tmpDir,
|
|
141
|
+
config,
|
|
142
|
+
fitBoundaryRowid: innerSplit.trainBoundaryRowid,
|
|
143
|
+
namespaces,
|
|
144
|
+
querySet: trainQuerySet,
|
|
145
|
+
topK,
|
|
146
|
+
});
|
|
147
|
+
candidates.push({
|
|
148
|
+
config,
|
|
149
|
+
trainScore: result.mrrAtK,
|
|
150
|
+
trainRecallAt10: result.recallAtK,
|
|
151
|
+
trainQueryCount: result.queryCount,
|
|
152
|
+
patternCount: result.patternCount,
|
|
153
|
+
promotedCount: result.promotedCount,
|
|
154
|
+
distillMs: result.distillMs,
|
|
155
|
+
...(result.skipped ? { skipped: result.skipped } : {}),
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
const scored = candidates.filter((c) => !c.skipped);
|
|
159
|
+
if (scored.length === 0) {
|
|
160
|
+
throw new Error('tuneDistillation: every grid candidate was skipped — see candidates[].skipped');
|
|
161
|
+
}
|
|
162
|
+
const winner = scored.reduce((best, c) => (c.trainScore > best.trainScore ? c : best), scored[0]);
|
|
163
|
+
// ── Held-out: score the winner ONCE, refit on the FULL outer train partition ──
|
|
164
|
+
const winnerFull = await evaluateCandidate({
|
|
165
|
+
Database,
|
|
166
|
+
sourceDbPath: dbPath,
|
|
167
|
+
tmpDir,
|
|
168
|
+
config: winner.config,
|
|
169
|
+
fitBoundaryRowid: outerSplit.trainBoundaryRowid,
|
|
170
|
+
namespaces,
|
|
171
|
+
querySet: heldOutQuerySet,
|
|
172
|
+
topK,
|
|
173
|
+
});
|
|
174
|
+
const baseline = scoreQuerySet(heldOutBaselineIndex, heldOutQuerySet, topK);
|
|
175
|
+
const heldOut = {
|
|
176
|
+
mrrAt10: winnerFull.mrrAtK,
|
|
177
|
+
recallAt10: winnerFull.recallAtK,
|
|
178
|
+
queryCount: winnerFull.queryCount,
|
|
179
|
+
baselineMrrAt10: baseline.mrrAtK,
|
|
180
|
+
baselineRecallAt10: baseline.recallAtK,
|
|
181
|
+
};
|
|
182
|
+
// Overfit: held-out MRR is more than 20% (relative) worse than the winner's
|
|
183
|
+
// own train score. Guard divide-by-zero — a zero train score can't overfit.
|
|
184
|
+
const overfit = winner.trainScore > 0 && heldOut.mrrAt10 < winner.trainScore * 0.8;
|
|
185
|
+
const sourceChecksumAfter = sha256File(dbPath);
|
|
186
|
+
if (sourceChecksumAfter !== sourceChecksumBefore) {
|
|
187
|
+
// This must be structurally impossible (dbPath is never opened with a DB
|
|
188
|
+
// connection anywhere above) — a mismatch means an invariant was broken.
|
|
189
|
+
throw new Error('tuneDistillation: source DB checksum changed during tuning — refusing to report a result');
|
|
190
|
+
}
|
|
191
|
+
return {
|
|
192
|
+
candidates,
|
|
193
|
+
winner,
|
|
194
|
+
heldOut,
|
|
195
|
+
overfit,
|
|
196
|
+
provenance: {
|
|
197
|
+
gridSize: configs.length,
|
|
198
|
+
corpusSize: outerSplit.totalRows,
|
|
199
|
+
trainSize: outerSplit.trainRowids.length,
|
|
200
|
+
heldOutSize: outerSplit.heldOutRowids.length,
|
|
201
|
+
metric: 'mrr@10',
|
|
202
|
+
tunedAt: now ?? Date.now(),
|
|
203
|
+
sourceDbPath: dbPath,
|
|
204
|
+
sourceChecksumSha256: sourceChecksumAfter,
|
|
205
|
+
},
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
// ── Persisted config artifact (requirement 6) ────────────────────────────
|
|
209
|
+
/** Shape the winning config + provenance for persistence. Pure — no I/O. */
|
|
210
|
+
export function buildTunedConfigFile(report) {
|
|
211
|
+
return {
|
|
212
|
+
batchSize: report.winner.config.batchSize,
|
|
213
|
+
dedupDistance: report.winner.config.dedupDistance,
|
|
214
|
+
promoteThreshold: report.winner.config.promoteThreshold,
|
|
215
|
+
provenance: {
|
|
216
|
+
...report.provenance,
|
|
217
|
+
winnerTrainScore: report.winner.trainScore,
|
|
218
|
+
heldOutScore: report.heldOut.mrrAt10,
|
|
219
|
+
baselineHeldOutScore: report.heldOut.baselineMrrAt10,
|
|
220
|
+
overfit: report.overfit,
|
|
221
|
+
},
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
/** Write the winning config to disk. Caller decides whether/where to call this. */
|
|
225
|
+
export function writeTunedConfigFile(report, filePath) {
|
|
226
|
+
const dir = path.dirname(filePath);
|
|
227
|
+
if (!fs.existsSync(dir))
|
|
228
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
229
|
+
fs.writeFileSync(filePath, JSON.stringify(buildTunedConfigFile(report), null, 2));
|
|
230
|
+
}
|
|
231
|
+
/** Where the tuned config lives by default, for daemon/CLI callers. */
|
|
232
|
+
export function defaultTunedConfigPath(cwd = process.cwd()) {
|
|
233
|
+
return path.join(cwd, '.claude-flow', 'distill-tuned.json');
|
|
234
|
+
}
|
|
235
|
+
// ── Time-based split ─────────────────────────────────────────────────────
|
|
236
|
+
/**
|
|
237
|
+
* Split a table's rows by rowid (a monotonic proxy for insertion time) into
|
|
238
|
+
* an earliest `trainFraction` chunk and a most-recent remainder. Pure given a
|
|
239
|
+
* fixed db snapshot. `table`/`extraWhere` are only ever called with internal
|
|
240
|
+
* literal strings (never external input) — not a SQL-injection surface.
|
|
241
|
+
*/
|
|
242
|
+
export function computeTimeSplit(db, trainFraction, opts = {}) {
|
|
243
|
+
const table = opts.table ?? 'memory_entries';
|
|
244
|
+
const whereParts = ['embedding IS NOT NULL'];
|
|
245
|
+
if (opts.extraWhere)
|
|
246
|
+
whereParts.push(`(${opts.extraWhere})`);
|
|
247
|
+
const where = `WHERE ${whereParts.join(' AND ')}`;
|
|
248
|
+
const rows = db
|
|
249
|
+
.prepare(`SELECT rowid AS rowid FROM ${table} ${where} ORDER BY rowid`)
|
|
250
|
+
.all();
|
|
251
|
+
const total = rows.length;
|
|
252
|
+
if (total === 0)
|
|
253
|
+
return { totalRows: 0, trainBoundaryRowid: 0, trainRowids: [], heldOutRowids: [] };
|
|
254
|
+
const trainCount = Math.min(total, Math.max(1, Math.floor(total * trainFraction)));
|
|
255
|
+
const trainBoundaryRowid = rows[trainCount - 1].rowid;
|
|
256
|
+
const trainRowids = [];
|
|
257
|
+
const heldOutRowids = [];
|
|
258
|
+
for (const r of rows) {
|
|
259
|
+
if (r.rowid <= trainBoundaryRowid)
|
|
260
|
+
trainRowids.push(r.rowid);
|
|
261
|
+
else
|
|
262
|
+
heldOutRowids.push(r.rowid);
|
|
263
|
+
}
|
|
264
|
+
return { totalRows: total, trainBoundaryRowid, trainRowids, heldOutRowids };
|
|
265
|
+
}
|
|
266
|
+
function assertDisjoint(a, b) {
|
|
267
|
+
const setA = new Set(a);
|
|
268
|
+
for (const x of b) {
|
|
269
|
+
if (setA.has(x)) {
|
|
270
|
+
throw new Error(`tuneDistillation: train/held-out partitions are not disjoint (rowid ${x} in both)`);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
// ── Query set + baseline index construction ─────────────────────────────
|
|
275
|
+
function buildQuerySet(db, opts) {
|
|
276
|
+
const { loRowid, hiRowid, namespaces } = opts;
|
|
277
|
+
if (namespaces.length === 0)
|
|
278
|
+
return [];
|
|
279
|
+
const placeholders = namespaces.map(() => '?').join(',');
|
|
280
|
+
const hiFinite = Number.isFinite(hiRowid);
|
|
281
|
+
const sql = `SELECT rowid, id, namespace, content, embedding FROM memory_entries
|
|
282
|
+
WHERE rowid > ? ${hiFinite ? 'AND rowid <= ?' : ''} AND embedding IS NOT NULL
|
|
283
|
+
AND COALESCE(namespace,'default') IN (${placeholders})
|
|
284
|
+
ORDER BY rowid`;
|
|
285
|
+
const args = hiFinite ? [loRowid, hiRowid, ...namespaces] : [loRowid, ...namespaces];
|
|
286
|
+
const rows = db.prepare(sql).all(...args);
|
|
287
|
+
const out = [];
|
|
288
|
+
for (const r of rows) {
|
|
289
|
+
const embedding = parseEmbeddingJson(r.embedding);
|
|
290
|
+
if (!embedding)
|
|
291
|
+
continue;
|
|
292
|
+
const distilled = distillTrajectoryContent(String(r.content ?? ''));
|
|
293
|
+
out.push({ id: r.id, namespace: r.namespace, embedding, labels: distilled.labels, paths: distilled.paths });
|
|
294
|
+
}
|
|
295
|
+
return out;
|
|
296
|
+
}
|
|
297
|
+
function buildRawIndex(db, opts) {
|
|
298
|
+
const { loRowid, hiRowid, namespaces } = opts;
|
|
299
|
+
let sql = 'SELECT rowid, content, embedding FROM memory_entries WHERE rowid > ? AND rowid <= ? AND embedding IS NOT NULL';
|
|
300
|
+
const args = [loRowid, hiRowid];
|
|
301
|
+
if (namespaces && namespaces.length) {
|
|
302
|
+
sql += ` AND COALESCE(namespace,'default') IN (${namespaces.map(() => '?').join(',')})`;
|
|
303
|
+
args.push(...namespaces);
|
|
304
|
+
}
|
|
305
|
+
sql += ' ORDER BY rowid';
|
|
306
|
+
const rows = db.prepare(sql).all(...args);
|
|
307
|
+
const sampled = sampleCap(rows, MAX_BASELINE_INDEX_SIZE);
|
|
308
|
+
const out = [];
|
|
309
|
+
for (const r of sampled) {
|
|
310
|
+
const embedding = parseEmbeddingJson(r.embedding);
|
|
311
|
+
if (!embedding)
|
|
312
|
+
continue;
|
|
313
|
+
const distilled = distillTrajectoryContent(String(r.content ?? ''));
|
|
314
|
+
out.push({ id: -1, embedding, labels: distilled.labels, paths: distilled.paths });
|
|
315
|
+
}
|
|
316
|
+
return out;
|
|
317
|
+
}
|
|
318
|
+
/** Evenly-spaced sample so large corpora stay fast without biasing toward one end. */
|
|
319
|
+
function sampleCap(rows, cap) {
|
|
320
|
+
if (rows.length <= cap)
|
|
321
|
+
return rows;
|
|
322
|
+
const stride = rows.length / cap;
|
|
323
|
+
const out = [];
|
|
324
|
+
for (let i = 0; i < cap; i++)
|
|
325
|
+
out.push(rows[Math.floor(i * stride)]);
|
|
326
|
+
return out;
|
|
327
|
+
}
|
|
328
|
+
function parseEmbeddingJson(raw) {
|
|
329
|
+
if (typeof raw !== 'string' || !raw)
|
|
330
|
+
return null;
|
|
331
|
+
try {
|
|
332
|
+
const v = JSON.parse(raw);
|
|
333
|
+
return Array.isArray(v) ? v : null;
|
|
334
|
+
}
|
|
335
|
+
catch {
|
|
336
|
+
return null;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
// ── Candidate evaluation (one isolated temp copy per call) ──────────────
|
|
340
|
+
async function evaluateCandidate(params) {
|
|
341
|
+
const { Database, sourceDbPath, tmpDir, config, fitBoundaryRowid, namespaces, querySet, topK } = params;
|
|
342
|
+
const label = `cand-${config.batchSize}-${config.dedupDistance}-${config.promoteThreshold.replace(/\W+/g, '_')}`;
|
|
343
|
+
const tmpCopy = copyToTemp(sourceDbPath, tmpDir, label);
|
|
344
|
+
try {
|
|
345
|
+
// Reset any pre-existing distilled state on the COPY (the real
|
|
346
|
+
// .swarm/memory.db already carries real reasoning_patterns/episodes/
|
|
347
|
+
// distill_state from M1's own runs — without this reset every candidate's
|
|
348
|
+
// cursor would already be at the tail and "process" zero rows, silently
|
|
349
|
+
// scoring the CURRENT production config instead of the candidate's own).
|
|
350
|
+
// Then trim to the fit partition. Both on the isolated copy only.
|
|
351
|
+
const prep = new Database(tmpCopy);
|
|
352
|
+
try {
|
|
353
|
+
resetDistillationState(prep);
|
|
354
|
+
prep.prepare('DELETE FROM memory_entries WHERE rowid > ?').run(fitBoundaryRowid);
|
|
355
|
+
}
|
|
356
|
+
finally {
|
|
357
|
+
prep.close();
|
|
358
|
+
}
|
|
359
|
+
const t0 = Date.now();
|
|
360
|
+
const distillOpts = {
|
|
361
|
+
dbPath: tmpCopy,
|
|
362
|
+
namespaces,
|
|
363
|
+
batchSize: config.batchSize,
|
|
364
|
+
dedupDistance: config.dedupDistance,
|
|
365
|
+
dryRun: false,
|
|
366
|
+
judge: 'structural',
|
|
367
|
+
};
|
|
368
|
+
const report = await runDistillation(distillOpts);
|
|
369
|
+
const distillMs = Date.now() - t0;
|
|
370
|
+
if (report.skipped) {
|
|
371
|
+
return { mrrAtK: 0, recallAtK: 0, queryCount: querySet.length, patternCount: 0, promotedCount: 0, distillMs, skipped: report.skipped };
|
|
372
|
+
}
|
|
373
|
+
const scoreDb = new Database(tmpCopy);
|
|
374
|
+
let index;
|
|
375
|
+
let patternCount;
|
|
376
|
+
try {
|
|
377
|
+
if (config.promoteThreshold === 'execution+corroborated') {
|
|
378
|
+
applyCorroboratedPromotion(scoreDb);
|
|
379
|
+
}
|
|
380
|
+
index = loadPromotedPatternIndex(scoreDb);
|
|
381
|
+
patternCount = scoreDb.prepare('SELECT COUNT(*) AS c FROM reasoning_patterns').get().c;
|
|
382
|
+
}
|
|
383
|
+
finally {
|
|
384
|
+
scoreDb.close();
|
|
385
|
+
}
|
|
386
|
+
const { mrrAtK, recallAtK } = scoreQuerySet(index, querySet, topK);
|
|
387
|
+
return { mrrAtK, recallAtK, queryCount: querySet.length, patternCount, promotedCount: index.length, distillMs };
|
|
388
|
+
}
|
|
389
|
+
finally {
|
|
390
|
+
safeUnlink(tmpCopy);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
function resetDistillationState(db) {
|
|
394
|
+
const tableExists = (name) => (db.prepare("SELECT COUNT(*) AS c FROM sqlite_master WHERE type='table' AND name=?").get(name)?.c ?? 0) > 0;
|
|
395
|
+
for (const t of ['distill_state', 'causal_edges', 'pattern_embeddings', 'reasoning_patterns', 'episodes']) {
|
|
396
|
+
if (tableExists(t))
|
|
397
|
+
db.exec(`DELETE FROM ${t}`);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
function applyCorroboratedPromotion(db) {
|
|
401
|
+
db.prepare(`UPDATE reasoning_patterns SET metadata = json_set(metadata, '$.promoted', 1)
|
|
402
|
+
WHERE json_extract(metadata, '$.provenance') = 'proxy:structural' AND uses >= ?`).run(CORROBORATION_MIN_USES);
|
|
403
|
+
}
|
|
404
|
+
// ── Scoring (MRR@K / recall@K, shared by candidate + baseline paths) ────
|
|
405
|
+
function scoreQuerySet(index, queries, topK) {
|
|
406
|
+
if (queries.length === 0 || index.length === 0)
|
|
407
|
+
return { mrrAtK: 0, recallAtK: 0 };
|
|
408
|
+
let mrrSum = 0;
|
|
409
|
+
let recallHits = 0;
|
|
410
|
+
for (const q of queries) {
|
|
411
|
+
const ranked = index
|
|
412
|
+
.map((p) => ({ p, sim: cosineSim(q.embedding, p.embedding) }))
|
|
413
|
+
.sort((a, b) => b.sim - a.sim)
|
|
414
|
+
.slice(0, topK);
|
|
415
|
+
let firstCorrectRank = -1;
|
|
416
|
+
for (let i = 0; i < ranked.length; i++) {
|
|
417
|
+
if (isTopicallyCorrect(q, ranked[i].p)) {
|
|
418
|
+
firstCorrectRank = i + 1;
|
|
419
|
+
break;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
if (firstCorrectRank > 0) {
|
|
423
|
+
mrrSum += 1 / firstCorrectRank;
|
|
424
|
+
recallHits += 1;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
return { mrrAtK: mrrSum / queries.length, recallAtK: recallHits / queries.length };
|
|
428
|
+
}
|
|
429
|
+
/** Proxy for "topically correct": shares at least one label or path with the query. */
|
|
430
|
+
function isTopicallyCorrect(q, p) {
|
|
431
|
+
if (p.labels.some((l) => q.labels.includes(l)))
|
|
432
|
+
return true;
|
|
433
|
+
if (p.paths.some((pp) => q.paths.includes(pp)))
|
|
434
|
+
return true;
|
|
435
|
+
return false;
|
|
436
|
+
}
|
|
437
|
+
// ── pattern_embeddings BLOB → number[] ───────────────────────────────────
|
|
438
|
+
function loadPromotedPatternIndex(db) {
|
|
439
|
+
const rows = db
|
|
440
|
+
.prepare(`SELECT rp.id AS id, rp.tags AS tags, rp.metadata AS metadata, pe.embedding AS embedding
|
|
441
|
+
FROM reasoning_patterns rp
|
|
442
|
+
JOIN pattern_embeddings pe ON pe.pattern_id = rp.id
|
|
443
|
+
WHERE json_extract(rp.metadata, '$.promoted') = 1`)
|
|
444
|
+
.all();
|
|
445
|
+
return rows.map((r) => {
|
|
446
|
+
let labels = [];
|
|
447
|
+
try {
|
|
448
|
+
const t = JSON.parse(r.tags ?? '[]');
|
|
449
|
+
if (Array.isArray(t))
|
|
450
|
+
labels = t;
|
|
451
|
+
}
|
|
452
|
+
catch {
|
|
453
|
+
/* not JSON — no labels */
|
|
454
|
+
}
|
|
455
|
+
let paths = [];
|
|
456
|
+
try {
|
|
457
|
+
const m = JSON.parse(r.metadata ?? '{}');
|
|
458
|
+
if (Array.isArray(m.paths))
|
|
459
|
+
paths = m.paths;
|
|
460
|
+
}
|
|
461
|
+
catch {
|
|
462
|
+
/* not JSON — no paths */
|
|
463
|
+
}
|
|
464
|
+
return { id: r.id, embedding: bufferToFloat32Array(r.embedding), labels, paths };
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
/**
|
|
468
|
+
* Copy a BLOB Buffer's bytes into a fresh, 4-byte-aligned ArrayBuffer before
|
|
469
|
+
* viewing it as Float32Array — better-sqlite3 BLOB buffers aren't guaranteed
|
|
470
|
+
* to start at a 4-byte-aligned offset within their backing ArrayBuffer, and
|
|
471
|
+
* the Float32Array constructor throws on misaligned views.
|
|
472
|
+
*/
|
|
473
|
+
function bufferToFloat32Array(buf) {
|
|
474
|
+
const floatCount = Math.floor(buf.byteLength / 4);
|
|
475
|
+
const aligned = new ArrayBuffer(floatCount * 4);
|
|
476
|
+
new Uint8Array(aligned).set(buf.subarray(0, floatCount * 4));
|
|
477
|
+
return Array.from(new Float32Array(aligned));
|
|
478
|
+
}
|
|
479
|
+
// ── fs / hashing / better-sqlite3 loading helpers ────────────────────────
|
|
480
|
+
function sha256File(p) {
|
|
481
|
+
return crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex');
|
|
482
|
+
}
|
|
483
|
+
function copyToTemp(sourcePath, tmpDir, label) {
|
|
484
|
+
if (!fs.existsSync(tmpDir))
|
|
485
|
+
fs.mkdirSync(tmpDir, { recursive: true });
|
|
486
|
+
const unique = crypto.randomBytes(6).toString('hex');
|
|
487
|
+
const dest = path.join(tmpDir, `distill-tune-${label}-${unique}.db`);
|
|
488
|
+
fs.copyFileSync(sourcePath, dest);
|
|
489
|
+
return dest;
|
|
490
|
+
}
|
|
491
|
+
function safeUnlink(p) {
|
|
492
|
+
for (const suffix of ['', '-wal', '-shm', '-journal']) {
|
|
493
|
+
try {
|
|
494
|
+
fs.unlinkSync(p + suffix);
|
|
495
|
+
}
|
|
496
|
+
catch {
|
|
497
|
+
/* already gone / never created */
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
async function loadBetterSqlite3() {
|
|
502
|
+
try {
|
|
503
|
+
const mod = 'better-sqlite3';
|
|
504
|
+
return (await import(mod)).default;
|
|
505
|
+
}
|
|
506
|
+
catch {
|
|
507
|
+
return null;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
//# sourceMappingURL=distill-tuning.js.map
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export type DistillProvenance = 'oracle:test-exec' | 'judge:fable' | 'proxy:structural';
|
|
2
|
+
export interface DistillOptions {
|
|
3
|
+
dbPath: string;
|
|
4
|
+
/** Restrict to these namespaces (default: all namespaces with embeddings). */
|
|
5
|
+
namespaces?: string[];
|
|
6
|
+
/** Rows per transaction (default 200). */
|
|
7
|
+
batchSize?: number;
|
|
8
|
+
/** Hard cap on rows processed this invocation (default: unbounded within a run). */
|
|
9
|
+
maxEntries?: number;
|
|
10
|
+
/** Cosine distance below which two entries collapse into one pattern (default 0.2, the ADR-174 M4-tuned platform default: ~37% fewer patterns, retrieval-neutral). */
|
|
11
|
+
dedupDistance?: number;
|
|
12
|
+
/** Report counts, write nothing (default false). */
|
|
13
|
+
dryRun?: boolean;
|
|
14
|
+
/** Judge tier. Only 'structural' ($0) is implemented here; 'fable' is reserved (ADR-172). */
|
|
15
|
+
judge?: 'structural' | 'fable';
|
|
16
|
+
/** Ignore the cursor and re-scan from this rowid (default: cursor-driven). */
|
|
17
|
+
sinceRowid?: number;
|
|
18
|
+
verbose?: boolean;
|
|
19
|
+
}
|
|
20
|
+
export interface DistillReport {
|
|
21
|
+
processed: number;
|
|
22
|
+
episodes: number;
|
|
23
|
+
patterns: number;
|
|
24
|
+
patternEmbeddings: number;
|
|
25
|
+
causalEdges: number;
|
|
26
|
+
promoted: number;
|
|
27
|
+
byProvenance: Record<string, number>;
|
|
28
|
+
namespaces: string[];
|
|
29
|
+
dryRun: boolean;
|
|
30
|
+
spendUsd: number;
|
|
31
|
+
corrupt?: boolean;
|
|
32
|
+
skipped?: string;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Distill accumulated memory into the structured intelligence tables.
|
|
36
|
+
* Incremental, $0, transactional, provenance-tagged.
|
|
37
|
+
*/
|
|
38
|
+
export declare function runDistillation(options: DistillOptions): Promise<DistillReport>;
|
|
39
|
+
/** Where the memory DB lives, for daemon/CLI callers. */
|
|
40
|
+
export declare function defaultMemoryDbPath(cwd?: string): string;
|
|
41
|
+
//# sourceMappingURL=memory-distillation.d.ts.map
|