claude-flow 3.22.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 (55) hide show
  1. package/.claude/helpers/.helpers-version +1 -0
  2. package/.claude/helpers/auto-memory-hook.mjs +59 -274
  3. package/.claude/helpers/helpers.manifest.json +12 -0
  4. package/.claude/helpers/hook-handler.cjs +132 -112
  5. package/.claude/helpers/intelligence.cjs +992 -196
  6. package/package.json +1 -1
  7. package/v3/@claude-flow/cli/dist/src/commands/memory-backup.d.ts +11 -0
  8. package/v3/@claude-flow/cli/dist/src/commands/memory-backup.js +46 -0
  9. package/v3/@claude-flow/cli/dist/src/commands/memory.js +2 -1
  10. package/v3/@claude-flow/cli/dist/src/config/harness-feedback-applier.d.ts +50 -0
  11. package/v3/@claude-flow/cli/dist/src/config/harness-feedback-applier.js +122 -0
  12. package/v3/@claude-flow/cli/dist/src/config/proven-config-refresh.d.ts +39 -0
  13. package/v3/@claude-flow/cli/dist/src/config/proven-config-refresh.js +154 -0
  14. package/v3/@claude-flow/cli/dist/src/config/proven-config-rvfa.d.ts +23 -0
  15. package/v3/@claude-flow/cli/dist/src/config/proven-config-rvfa.js +73 -0
  16. package/v3/@claude-flow/cli/dist/src/config/proven-config.d.ts +86 -0
  17. package/v3/@claude-flow/cli/dist/src/config/proven-config.js +176 -0
  18. package/v3/@claude-flow/cli/dist/src/index.js +35 -0
  19. package/v3/@claude-flow/cli/dist/src/mcp-tools/neural-tools.d.ts +10 -0
  20. package/v3/@claude-flow/cli/dist/src/mcp-tools/neural-tools.js +107 -18
  21. package/v3/@claude-flow/cli/dist/src/services/daemon-autostart.d.ts +17 -0
  22. package/v3/@claude-flow/cli/dist/src/services/daemon-autostart.js +79 -0
  23. package/v3/@claude-flow/cli/dist/src/services/evolve-proof.d.ts +247 -0
  24. package/v3/@claude-flow/cli/dist/src/services/evolve-proof.js +341 -0
  25. package/v3/@claude-flow/cli/dist/src/services/harness-benchmark.d.ts +68 -0
  26. package/v3/@claude-flow/cli/dist/src/services/harness-benchmark.js +94 -0
  27. package/v3/@claude-flow/cli/dist/src/services/harness-canary.d.ts +60 -0
  28. package/v3/@claude-flow/cli/dist/src/services/harness-canary.js +69 -0
  29. package/v3/@claude-flow/cli/dist/src/services/harness-corpus-harvester.d.ts +51 -0
  30. package/v3/@claude-flow/cli/dist/src/services/harness-corpus-harvester.js +74 -0
  31. package/v3/@claude-flow/cli/dist/src/services/harness-flywheel-generations.d.ts +111 -0
  32. package/v3/@claude-flow/cli/dist/src/services/harness-flywheel-generations.js +354 -0
  33. package/v3/@claude-flow/cli/dist/src/services/harness-flywheel-runtime.d.ts +25 -0
  34. package/v3/@claude-flow/cli/dist/src/services/harness-flywheel-runtime.js +101 -0
  35. package/v3/@claude-flow/cli/dist/src/services/harness-flywheel.d.ts +48 -0
  36. package/v3/@claude-flow/cli/dist/src/services/harness-flywheel.js +207 -0
  37. package/v3/@claude-flow/cli/dist/src/services/harness-hosts.d.ts +40 -0
  38. package/v3/@claude-flow/cli/dist/src/services/harness-hosts.js +88 -0
  39. package/v3/@claude-flow/cli/dist/src/services/harness-improvement-ledger.d.ts +63 -0
  40. package/v3/@claude-flow/cli/dist/src/services/harness-improvement-ledger.js +101 -0
  41. package/v3/@claude-flow/cli/dist/src/services/harness-loop.d.ts +53 -0
  42. package/v3/@claude-flow/cli/dist/src/services/harness-loop.js +85 -0
  43. package/v3/@claude-flow/cli/dist/src/services/harness-qualification.d.ts +66 -0
  44. package/v3/@claude-flow/cli/dist/src/services/harness-qualification.js +143 -0
  45. package/v3/@claude-flow/cli/dist/src/services/harness-replay.d.ts +37 -0
  46. package/v3/@claude-flow/cli/dist/src/services/harness-replay.js +92 -0
  47. package/v3/@claude-flow/cli/dist/src/services/harness-verify.d.ts +33 -0
  48. package/v3/@claude-flow/cli/dist/src/services/harness-verify.js +26 -0
  49. package/v3/@claude-flow/cli/dist/src/services/harness-worker.d.ts +23 -0
  50. package/v3/@claude-flow/cli/dist/src/services/harness-worker.js +66 -0
  51. package/v3/@claude-flow/cli/dist/src/services/memory-backup.d.ts +24 -0
  52. package/v3/@claude-flow/cli/dist/src/services/memory-backup.js +94 -0
  53. package/v3/@claude-flow/cli/dist/src/services/worker-daemon.d.ts +16 -1
  54. package/v3/@claude-flow/cli/dist/src/services/worker-daemon.js +84 -0
  55. package/v3/@claude-flow/cli/package.json +1 -1
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Proven Configuration Manifest (ADR-176 proof #3 + ADR-177 core).
3
+ *
4
+ * The signed, constraint-carrying artifact that the self-optimizing harness loop
5
+ * (ADR-176) emits and the propagation channel (ADR-177) ships to installs. Two
6
+ * independent gates decide adoption, and BOTH must pass (fail-closed):
7
+ *
8
+ * 1. Authenticity — Ed25519 signature over the canonical manifest bytes,
9
+ * verified against a baked public key. Proves it came from
10
+ * ruflo, unmodified. (native node:crypto, zero deps —
11
+ * same primitive as helper-signing.ts / rvfa-signing.ts.)
12
+ * 2. Suitability — the constraint contract (host/platform/compatibility/
13
+ * layer) checked against THIS install. A perfectly-signed
14
+ * manifest that doesn't fit the local environment is a safe
15
+ * NON-adoption, not an error. "signed != suitable."
16
+ *
17
+ * This is a DISTINCT Ed25519 trust root from helper-signing (ADR-177): the
18
+ * config channel gets its own key so rotating it never touches the hook-code
19
+ * channel that older CLIs verify.
20
+ */
21
+ import { createHash, verify as edVerify, sign as edSign } from 'crypto';
22
+ /** Ruflo config-signing PUBLIC key (safe to commit). Private half in GCP Secret Manager (ruflo-config-signing-key). */
23
+ export const RUFLO_CONFIG_PUBKEY = `-----BEGIN PUBLIC KEY-----
24
+ MCowBQYDK2VwAyEA3zr3BLCFKyrjvjZg9BXxchXIuGYwYwq21FYCjTpQO6A=
25
+ -----END PUBLIC KEY-----`;
26
+ export function sha256Hex(content) {
27
+ return createHash('sha256').update(content).digest('hex');
28
+ }
29
+ /**
30
+ * Deterministic canonical bytes — recursively sorted object keys so signer and
31
+ * verifier agree byte-for-byte regardless of insertion order.
32
+ */
33
+ export function canonicalManifestBytes(m) {
34
+ const canon = (v) => {
35
+ if (Array.isArray(v))
36
+ return v.map(canon);
37
+ if (v && typeof v === 'object') {
38
+ const out = {};
39
+ for (const k of Object.keys(v).sort())
40
+ out[k] = canon(v[k]);
41
+ return out;
42
+ }
43
+ return v;
44
+ };
45
+ return Buffer.from(JSON.stringify(canon(m)), 'utf-8');
46
+ }
47
+ /** Sign a manifest (publish-time; key from GCP via scripts). */
48
+ export function signProvenConfig(manifest, privateKeyPem) {
49
+ const signature = edSign(null, canonicalManifestBytes(manifest), privateKeyPem).toString('base64');
50
+ return { manifest, signature, algorithm: 'ed25519' };
51
+ }
52
+ /**
53
+ * Verify a signed manifest against ruflo's config public key. Returns the
54
+ * manifest on success, or null on ANY failure (bad signature, malformed JSON,
55
+ * wrong algorithm, missing fields). Fail-closed.
56
+ */
57
+ export function verifyProvenConfig(signedJson, pubkeyPem = RUFLO_CONFIG_PUBKEY) {
58
+ try {
59
+ const signed = typeof signedJson === 'string' ? JSON.parse(signedJson) : signedJson;
60
+ if (!signed || signed.algorithm !== 'ed25519' || !signed.signature || !signed.manifest)
61
+ return null;
62
+ if (!signed.manifest.schema || !signed.manifest.policy?.ref)
63
+ return null;
64
+ const ok = edVerify(null, canonicalManifestBytes(signed.manifest), pubkeyPem, Buffer.from(signed.signature, 'base64'));
65
+ return ok ? signed.manifest : null;
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ }
71
+ // ── Suitability gate ────────────────────────────────────────────────────────
72
+ /** Normalize platform aliases so process.platform matches manifest names. */
73
+ function platformMatches(installed, allowed) {
74
+ const norm = (p) => {
75
+ const l = p.toLowerCase();
76
+ if (l === 'darwin' || l === 'macos' || l === 'mac')
77
+ return 'macos';
78
+ if (l === 'win32' || l === 'windows')
79
+ return 'windows';
80
+ return l; // linux, etc.
81
+ };
82
+ const want = norm(installed);
83
+ return allowed.some(a => norm(a) === want);
84
+ }
85
+ function parseVer(v) {
86
+ // Tolerant: accepts X, X.Y, or X.Y.Z (a range like '>=1.9' has no patch).
87
+ const m = /(\d+)(?:\.(\d+))?(?:\.(\d+))?/.exec(v);
88
+ if (!m)
89
+ return [0, 0, 0];
90
+ return [Number(m[1] || 0), Number(m[2] || 0), Number(m[3] || 0)];
91
+ }
92
+ function cmpVer(a, b) {
93
+ const [a1, a2, a3] = parseVer(a);
94
+ const [b1, b2, b3] = parseVer(b);
95
+ return a1 - b1 || a2 - b2 || a3 - b3;
96
+ }
97
+ /**
98
+ * Minimal semver-range satisfier for the compat contract. Supports `>=X`, `>X`,
99
+ * `<=X`, `<X`, `=X`, and a bare version `X` (treated as `>=X`). Deliberately
100
+ * small — the manifest contract only uses min-version bounds.
101
+ */
102
+ export function satisfiesRange(installed, range) {
103
+ const r = range.trim();
104
+ const m = /^(>=|<=|>|<|=)?\s*(.+)$/.exec(r);
105
+ if (!m)
106
+ return false;
107
+ const op = m[1] ?? '>=';
108
+ const target = m[2].trim();
109
+ const c = cmpVer(installed, target);
110
+ switch (op) {
111
+ case '>=': return c >= 0;
112
+ case '>': return c > 0;
113
+ case '<=': return c <= 0;
114
+ case '<': return c < 0;
115
+ case '=': return c === 0;
116
+ default: return false;
117
+ }
118
+ }
119
+ /**
120
+ * Check a manifest's constraint contract against the local environment.
121
+ * Fail-closed: a missing/unsatisfiable constraint => not suitable (safe skip).
122
+ * A constraint the manifest doesn't declare is not required.
123
+ */
124
+ export function isSuitable(manifest, env) {
125
+ // platform
126
+ if (manifest.platform && manifest.platform.length > 0) {
127
+ if (!platformMatches(env.platform, manifest.platform)) {
128
+ return { suitable: false, reason: `platform ${env.platform} not in [${manifest.platform.join(', ')}]` };
129
+ }
130
+ }
131
+ // host presence + version
132
+ if (manifest.host) {
133
+ for (const [name, range] of Object.entries(manifest.host)) {
134
+ const installed = env.hosts?.[name];
135
+ if (!installed)
136
+ return { suitable: false, reason: `required host '${name}' not present` };
137
+ if (!satisfiesRange(installed, range)) {
138
+ return { suitable: false, reason: `host '${name}' ${installed} does not satisfy ${range}` };
139
+ }
140
+ }
141
+ }
142
+ // package compatibility ranges (ruflo, metaharness, …)
143
+ if (manifest.compatibility) {
144
+ for (const [pkg, range] of Object.entries(manifest.compatibility)) {
145
+ const installed = env.versions?.[pkg];
146
+ if (!installed)
147
+ return { suitable: false, reason: `required package '${pkg}' version unknown` };
148
+ if (!satisfiesRange(installed, range)) {
149
+ return { suitable: false, reason: `${pkg} ${installed} does not satisfy ${range}` };
150
+ }
151
+ }
152
+ }
153
+ // hierarchy layer — an install only adopts a manifest for its own (or an ancestor) layer
154
+ if (manifest.layer && env.layer && manifest.layer !== env.layer) {
155
+ // allow ancestor layers: manifest 'framework/node-cli' is adoptable by env layer that startsWith it or vice-versa
156
+ const a = manifest.layer, b = env.layer;
157
+ if (!(b.startsWith(a) || a.startsWith(b))) {
158
+ return { suitable: false, reason: `layer '${a}' not applicable to install layer '${b}'` };
159
+ }
160
+ }
161
+ return { suitable: true };
162
+ }
163
+ /**
164
+ * The combined adoption decision (ADR-177): a manifest is adoptable iff it is
165
+ * both authentic (signature verifies) AND suitable (constraints satisfied).
166
+ */
167
+ export function evaluateForAdoption(signedJson, env, pubkeyPem = RUFLO_CONFIG_PUBKEY) {
168
+ const manifest = verifyProvenConfig(signedJson, pubkeyPem);
169
+ if (!manifest)
170
+ return { adopt: false, reason: 'signature invalid — refusing (authenticity gate)' };
171
+ const suit = isSuitable(manifest, env);
172
+ if (!suit.suitable)
173
+ return { adopt: false, manifest, reason: `not suitable — ${suit.reason} (safe skip)` };
174
+ return { adopt: true, manifest, reason: 'authentic + suitable' };
175
+ }
176
+ //# sourceMappingURL=proven-config.js.map
@@ -133,6 +133,41 @@ export class CLI {
133
133
  }
134
134
  }
135
135
  catch { /* silent */ }
136
+ // ADR-177: adopt a signed proven-configuration champion if the package
137
+ // ships one newer than this project's stamp AND it is authentic +
138
+ // suitable for this environment. Sibling of the helper channel above —
139
+ // its own stamp + trust root; additive no-op when no champion ships.
140
+ try {
141
+ const { autoAdoptProvenConfigIfStale } = await import('./config/proven-config-refresh.js');
142
+ const a = await autoAdoptProvenConfigIfStale(process.cwd());
143
+ if (a.adopted && this.output.isVerbose()) {
144
+ this.output.printDebug(`Adopted proven config (${a.from} → ${a.to})`);
145
+ }
146
+ // Close the loop (ADR-176 phase 9): promote the adopted champion to the
147
+ // ACTIVE policy that consumers (neural_patterns retrieval, …) read. A
148
+ // no-op if nothing is adopted or it is already active; reversible.
149
+ const { applyChampion } = await import('./config/harness-feedback-applier.js');
150
+ const ap = applyChampion(process.cwd());
151
+ if (ap.applied && this.output.isVerbose()) {
152
+ this.output.printDebug(`Applied proven config to active policy (${ap.from ?? '(none)'} → ${ap.to})`);
153
+ }
154
+ }
155
+ catch { /* silent */ }
156
+ // Self-running daemon: ensure the background workers (distillation,
157
+ // backup, …) are actually firing without a manual `daemon start`.
158
+ // Single-instance (only spawns when none is alive; the spawned daemon
159
+ // re-checks its own lock), bounded (TTL/idle self-shutdown), opt-out via
160
+ // RUFLO_DAEMON_AUTOSTART=0. Skipped for `daemon` (no recursion). Detached
161
+ // + fire-and-forget, so it never blocks the command.
162
+ if (commandPath[0] !== 'daemon') {
163
+ try {
164
+ const { ensureDaemonRunning } = await import('./services/daemon-autostart.js');
165
+ const d = ensureDaemonRunning(process.cwd());
166
+ if (d.started && this.output.isVerbose())
167
+ this.output.printDebug('Started background daemon (auto)');
168
+ }
169
+ catch { /* silent */ }
170
+ }
136
171
  }
137
172
  // Handle lazy-loaded commands that weren't recognized by the parser
138
173
  // If commandPath is empty but positional has a command name, check if it's lazy-loadable
@@ -12,6 +12,16 @@
12
12
  * Note: For production neural features, use @claude-flow/neural module
13
13
  */
14
14
  import { type MCPTool } from './types.js';
15
+ /**
16
+ * ADR-176 flywheel: expose the stored patterns (id/name/content) so the
17
+ * self-optimizing loop can harvest a benchmark corpus from real usage. Additive,
18
+ * read-only, never throws.
19
+ */
20
+ export declare function getStorePatterns(): Array<{
21
+ id: string;
22
+ name: string;
23
+ content?: string;
24
+ }>;
15
25
  /**
16
26
  * Public helper: read-only stats about the neural store, for the unified
17
27
  * learning-stats aggregator. Returns total pattern count + per-type breakdown
@@ -15,6 +15,55 @@ import { getProjectCwd } from './types.js';
15
15
  import { validateIdentifier, validateText } from './validate-input.js';
16
16
  import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
17
17
  import { join } from 'node:path';
18
+ let _corpusStatsCache = null;
19
+ // (query, store) → embedding + cosine cache. Small LRU (not size-1): the flywheel
20
+ // scores many configs across several queries in interleaved order, so a size-1
21
+ // cache would thrash. Cap keeps memory bounded; eviction is oldest-first.
22
+ const _cosineCache = new Map();
23
+ const _COSINE_CACHE_MAX = 128;
24
+ function _cosineCacheGet(key) {
25
+ const v = _cosineCache.get(key);
26
+ if (v) {
27
+ _cosineCache.delete(key);
28
+ _cosineCache.set(key, v);
29
+ } // LRU touch
30
+ return v;
31
+ }
32
+ function _cosineCacheSet(key, v) {
33
+ _cosineCache.set(key, v);
34
+ if (_cosineCache.size > _COSINE_CACHE_MAX)
35
+ _cosineCache.delete(_cosineCache.keys().next().value);
36
+ }
37
+ function corpusFingerprint(patterns) {
38
+ let h = 2166136261 >>> 0;
39
+ for (const p of patterns) {
40
+ const s = `${p.id}|${p.name?.length ?? 0}|${p.content?.length ?? 0}`;
41
+ for (let i = 0; i < s.length; i++) {
42
+ h ^= s.charCodeAt(i);
43
+ h = Math.imul(h, 16777619) >>> 0;
44
+ }
45
+ }
46
+ return `${patterns.length}:${h.toString(16)}`;
47
+ }
48
+ let _champCache = null;
49
+ function activeChampionParams() {
50
+ try {
51
+ if (_champCache && Date.now() - _champCache.at < 30_000)
52
+ return _champCache.params;
53
+ const p = join(getProjectCwd(), '.claude-flow', 'harness-active-policy.json');
54
+ let params = {};
55
+ if (existsSync(p)) {
56
+ const active = JSON.parse(readFileSync(p, 'utf-8'));
57
+ if (active && !active.rolledBack && active.params && typeof active.params === 'object')
58
+ params = active.params;
59
+ }
60
+ _champCache = { at: Date.now(), params };
61
+ return params;
62
+ }
63
+ catch {
64
+ return {};
65
+ }
66
+ }
18
67
  // Real embeddings — resolved LAZILY on first use.
19
68
  // Perf (measured 2026-07): the previous top-level-await version of this block
20
69
  // ran `await import('ruvector')` + `initOnnxEmbedder()` + a probe embed at
@@ -159,6 +208,19 @@ function loadNeuralStore() {
159
208
  }
160
209
  return { models: {}, patterns: {}, version: '3.0.0' };
161
210
  }
211
+ /**
212
+ * ADR-176 flywheel: expose the stored patterns (id/name/content) so the
213
+ * self-optimizing loop can harvest a benchmark corpus from real usage. Additive,
214
+ * read-only, never throws.
215
+ */
216
+ export function getStorePatterns() {
217
+ try {
218
+ return Object.values(loadNeuralStore().patterns ?? {}).map((p) => ({ id: p.id, name: p.name, content: p.content }));
219
+ }
220
+ catch {
221
+ return [];
222
+ }
223
+ }
162
224
  function saveNeuralStore(store) {
163
225
  ensureNeuralDir();
164
226
  writeFileSync(getNeuralPath(), JSON.stringify(store, null, 2), 'utf-8');
@@ -604,13 +666,28 @@ export const neuralTools = [
604
666
  // sub-params than non-rerank (the cross-encoder adds semantic depth,
605
667
  // so the hybrid stage can be more keyword-focused). nDCG@3 0.900 →
606
668
  // 0.963 on rerank just by switching sw 2.0 → 3.0 in the hybrid stage.
607
- const alpha = Number(input.alpha ?? 0.5);
608
- const mmrLambda = Number(input.mmrLambda ?? 0.7);
669
+ // Champion-provided defaults (ADR-176/177): explicit input wins, then the
670
+ // adopted proven-config champion, then the hardcoded ADR-082 defaults.
671
+ const champ = activeChampionParams();
672
+ const alpha = Number(input.alpha ?? champ.alpha ?? 0.5);
673
+ const mmrLambda = Number(input.mmrLambda ?? champ.mmrLambda ?? 0.7);
609
674
  const { tokenize, buildCorpusStats, hybridScores, mmrRerank, multiFieldBM25, typePenalty } = await import('../memory/hybrid-retrieval.js');
610
- const queryEmbedding = await generateEmbedding(query, 384);
611
675
  const patterns = Object.values(store.patterns);
612
- // Compute cosine for every pattern (this is what the old path did).
613
- const cosineArr = patterns.map((p) => cosineSimilarity(queryEmbedding, p.embedding));
676
+ // Query embedding + cosine array depend only on (query, store) NOT the
677
+ // retrieval config. Cache them so scoring many configs for one query
678
+ // (the flywheel's access pattern) embeds + cosines once, not per config.
679
+ const _cosKey = `${corpusFingerprint(patterns)}::${query}`;
680
+ let queryEmbedding, cosineArr;
681
+ const _hit = _cosineCacheGet(_cosKey);
682
+ if (_hit) {
683
+ queryEmbedding = _hit.queryEmbedding;
684
+ cosineArr = _hit.cosineArr;
685
+ }
686
+ else {
687
+ queryEmbedding = await generateEmbedding(query, 384);
688
+ cosineArr = patterns.map((p) => cosineSimilarity(queryEmbedding, p.embedding));
689
+ _cosineCacheSet(_cosKey, { queryEmbedding, cosineArr });
690
+ }
614
691
  if (mode === 'cosine') {
615
692
  const ranked = patterns
616
693
  .map((p, i) => ({ ...p, similarity: cosineArr[i] }))
@@ -630,23 +707,35 @@ export const neuralTools = [
630
707
  // Hybrid path — multi-field BM25 (subject 3×, body 1×) + type penalty
631
708
  // for meta-commits (release bumps / merges) per ADR-079. Falls back
632
709
  // to single-field BM25 when no content is stored.
633
- const subjectDocs = patterns.map((p) => tokenize(p.name ?? ''));
634
- const bodyDocs = patterns.map((p) => {
635
- // Body is content minus the subject — if content starts with name,
636
- // strip it; otherwise use full content (with name removed if duplicated).
637
- const c = p.content ?? '';
638
- const n = p.name ?? '';
639
- return tokenize(c.startsWith(n) ? c.slice(n.length) : c);
640
- });
641
- const subjectStats = buildCorpusStats(subjectDocs);
642
- const bodyStats = buildCorpusStats(bodyDocs);
710
+ // Cache the (config-independent) tokenized docs + BM25 stats by store fingerprint.
711
+ const _fp = corpusFingerprint(patterns);
712
+ let subjectDocs, bodyDocs, subjectStats, bodyStats;
713
+ if (_corpusStatsCache && _corpusStatsCache.fp === _fp) {
714
+ subjectDocs = _corpusStatsCache.subjectDocs;
715
+ bodyDocs = _corpusStatsCache.bodyDocs;
716
+ subjectStats = _corpusStatsCache.subjectStats;
717
+ bodyStats = _corpusStatsCache.bodyStats;
718
+ }
719
+ else {
720
+ subjectDocs = patterns.map((p) => tokenize(p.name ?? ''));
721
+ bodyDocs = patterns.map((p) => {
722
+ // Body is content minus the subject — if content starts with name,
723
+ // strip it; otherwise use full content (with name removed if duplicated).
724
+ const c = p.content ?? '';
725
+ const n = p.name ?? '';
726
+ return tokenize(c.startsWith(n) ? c.slice(n.length) : c);
727
+ });
728
+ subjectStats = buildCorpusStats(subjectDocs);
729
+ bodyStats = buildCorpusStats(bodyDocs);
730
+ _corpusStatsCache = { fp: _fp, subjectDocs, bodyDocs, subjectStats, bodyStats };
731
+ }
643
732
  const queryTokens = tokenize(query);
644
733
  // ADR-082: subjectWeight 3.0 → 2.0 from grid (sw=2 dominates at hybrid-only).
645
734
  // ADR-083 joint grid: when rerank is on, the cross-encoder handles
646
735
  // semantic understanding, so the hybrid stage can be MORE
647
736
  // subject-focused (sw=3) — recovers nDCG@3 0.963.
648
- const subjectWeight = Number(input.subjectWeight ?? (useRerank ? 3.0 : 2.0));
649
- const bodyWeight = Number(input.bodyWeight ?? 1.0);
737
+ const subjectWeight = Number(input.subjectWeight ?? champ.subjectWeight ?? (useRerank ? 3.0 : 2.0));
738
+ const bodyWeight = Number(input.bodyWeight ?? champ.bodyWeight ?? 1.0);
650
739
  const bm25Arr = patterns.map((_, i) => multiFieldBM25(queryTokens, subjectDocs[i], bodyDocs[i], subjectStats, bodyStats, subjectWeight, bodyWeight));
651
740
  const baseHybrid = hybridScores(cosineArr, bm25Arr, alpha);
652
741
  // Type penalty — opt-in (default 1.0 = disabled). Ablation in ADR-079
@@ -654,7 +743,7 @@ export const neuralTools = [
654
743
  // penalty enabled) because some relevant work commits also match the
655
744
  // Merge/release regex. Callers wanting aggressive meta-commit
656
745
  // suppression can set {typePenaltyFactor: 0.5}.
657
- const typeFactor = Number(input.typePenaltyFactor ?? 1.0);
746
+ const typeFactor = Number(input.typePenaltyFactor ?? champ.typePenaltyFactor ?? 1.0);
658
747
  const hybridArr = typeFactor === 1.0
659
748
  ? baseHybrid
660
749
  : baseHybrid.map((s, i) => s * typePenalty(patterns[i].name, typeFactor));
@@ -0,0 +1,17 @@
1
+ /** True if a live daemon already holds the project's pidfile. */
2
+ export declare function isDaemonAlive(projectRoot: string): boolean;
3
+ export interface EnsureResult {
4
+ started: boolean;
5
+ reason?: string;
6
+ }
7
+ /** Spawn `daemon start` detached, reusing all its lock/TTL machinery. Injectable for tests. */
8
+ export type SpawnDaemonFn = (projectRoot: string) => void;
9
+ /**
10
+ * Ensure a daemon is running for `projectRoot`. No-op when disabled or when one
11
+ * is already alive. Best-effort; never throws.
12
+ */
13
+ export declare function ensureDaemonRunning(projectRoot: string, opts?: {
14
+ spawnFn?: SpawnDaemonFn;
15
+ isAlive?: (root: string) => boolean;
16
+ }): EnsureResult;
17
+ //# sourceMappingURL=daemon-autostart.d.ts.map
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Self-running daemon (auto-start).
3
+ *
4
+ * The self-optimizing loop's workers (distillation, backup, and the future
5
+ * evolve worker) are inert unless the daemon runs — but it required a manual
6
+ * `ruflo daemon start`. This ensures a daemon is running on CLI use, SAFELY:
7
+ *
8
+ * - single-instance: only starts when no live daemon holds the pidfile, and
9
+ * the spawned `daemon start` independently enforces single-instance via its
10
+ * own lock + checkExistingDaemon() — so a race spawns at most one survivor,
11
+ * - bounded lifetime: the daemon self-terminates on TTL/idle (12h default,
12
+ * RUFLO_DAEMON_TTL_SECS) — auto-start never means "runs forever",
13
+ * - opt-out: RUFLO_DAEMON_AUTOSTART=0|false|no disables it entirely,
14
+ * - cheap: a pidfile read + a signal-0 liveness check on the fast path,
15
+ * - best-effort + silent: never blocks or fails a command.
16
+ *
17
+ * Reuses `daemon start` verbatim (all its lock/TTL/worker machinery) — this
18
+ * module only decides WHETHER to spawn, never reimplements the daemon.
19
+ */
20
+ import * as fs from 'fs';
21
+ import * as path from 'path';
22
+ import { spawn } from 'child_process';
23
+ /** True if a live daemon already holds the project's pidfile. */
24
+ export function isDaemonAlive(projectRoot) {
25
+ const pidFile = path.join(projectRoot, '.claude-flow', 'daemon.pid');
26
+ try {
27
+ if (!fs.existsSync(pidFile))
28
+ return false;
29
+ const pid = parseInt(fs.readFileSync(pidFile, 'utf-8').trim(), 10);
30
+ if (Number.isNaN(pid) || pid === process.pid)
31
+ return false;
32
+ process.kill(pid, 0); // signal 0 = existence check
33
+ return true;
34
+ }
35
+ catch {
36
+ // Dead process → stale pidfile. Clean it so `daemon start` proceeds cleanly.
37
+ try {
38
+ fs.unlinkSync(pidFile);
39
+ }
40
+ catch { /* ignore */ }
41
+ return false;
42
+ }
43
+ }
44
+ function autostartDisabled() {
45
+ return /^(0|false|no|off)$/i.test(process.env.RUFLO_DAEMON_AUTOSTART ?? '');
46
+ }
47
+ const defaultSpawn = (projectRoot) => {
48
+ const cliBin = process.argv[1]; // the running bin/cli.js
49
+ const child = spawn(process.execPath, [cliBin, 'daemon', 'start', '--quiet'], {
50
+ cwd: projectRoot,
51
+ detached: true,
52
+ stdio: 'ignore',
53
+ env: { ...process.env },
54
+ });
55
+ child.unref();
56
+ };
57
+ /**
58
+ * Ensure a daemon is running for `projectRoot`. No-op when disabled or when one
59
+ * is already alive. Best-effort; never throws.
60
+ */
61
+ export function ensureDaemonRunning(projectRoot, opts = {}) {
62
+ try {
63
+ if (autostartDisabled())
64
+ return { started: false, reason: 'disabled (RUFLO_DAEMON_AUTOSTART=0)' };
65
+ // Only in an initialized project (avoid scaffolding a daemon in a random dir).
66
+ if (!fs.existsSync(path.join(projectRoot, '.claude-flow')) && !fs.existsSync(path.join(projectRoot, '.claude'))) {
67
+ return { started: false, reason: 'not a ruflo project' };
68
+ }
69
+ const alive = (opts.isAlive ?? isDaemonAlive)(projectRoot);
70
+ if (alive)
71
+ return { started: false, reason: 'already running' };
72
+ (opts.spawnFn ?? defaultSpawn)(projectRoot);
73
+ return { started: true };
74
+ }
75
+ catch (e) {
76
+ return { started: false, reason: `error: ${e?.message ?? e}` };
77
+ }
78
+ }
79
+ //# sourceMappingURL=daemon-autostart.js.map