@claude-flow/cli 3.23.0 → 3.25.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 (57) hide show
  1. package/.claude/eval/human-relevance-frozen-v1.json +17 -0
  2. package/.claude/evolve-proof/generation-0.json +211 -0
  3. package/.claude/evolve-proof/real-generation-0.json +406 -0
  4. package/.claude/evolve-proof/real-generation-1.json +406 -0
  5. package/.claude/helpers/.helpers-version +1 -1
  6. package/.claude/helpers/intelligence.cjs +10 -0
  7. package/.claude/proven-config.manifest.json +37 -0
  8. package/.claude/proven-config.signed.json +41 -0
  9. package/.claude/proven-config.signed.rvf +0 -0
  10. package/dist/src/config/harness-feedback-applier.d.ts +50 -0
  11. package/dist/src/config/harness-feedback-applier.js +122 -0
  12. package/dist/src/config/proven-config-refresh.d.ts +39 -0
  13. package/dist/src/config/proven-config-refresh.js +154 -0
  14. package/dist/src/config/proven-config-rvfa.d.ts +23 -0
  15. package/dist/src/config/proven-config-rvfa.js +73 -0
  16. package/dist/src/config/proven-config.d.ts +86 -0
  17. package/dist/src/config/proven-config.js +176 -0
  18. package/dist/src/index.js +35 -0
  19. package/dist/src/mcp-tools/neural-tools.d.ts +10 -0
  20. package/dist/src/mcp-tools/neural-tools.js +129 -20
  21. package/dist/src/ruvector/lattice-wasm.d.ts +14 -0
  22. package/dist/src/ruvector/lattice-wasm.js +144 -0
  23. package/dist/src/services/daemon-autostart.d.ts +17 -0
  24. package/dist/src/services/daemon-autostart.js +79 -0
  25. package/dist/src/services/evolve-proof.d.ts +253 -0
  26. package/dist/src/services/evolve-proof.js +343 -0
  27. package/dist/src/services/harness-benchmark.d.ts +68 -0
  28. package/dist/src/services/harness-benchmark.js +94 -0
  29. package/dist/src/services/harness-canary.d.ts +60 -0
  30. package/dist/src/services/harness-canary.js +69 -0
  31. package/dist/src/services/harness-corpus-harvester.d.ts +51 -0
  32. package/dist/src/services/harness-corpus-harvester.js +74 -0
  33. package/dist/src/services/harness-flywheel-generations.d.ts +115 -0
  34. package/dist/src/services/harness-flywheel-generations.js +360 -0
  35. package/dist/src/services/harness-flywheel-runtime.d.ts +25 -0
  36. package/dist/src/services/harness-flywheel-runtime.js +92 -0
  37. package/dist/src/services/harness-flywheel.d.ts +48 -0
  38. package/dist/src/services/harness-flywheel.js +207 -0
  39. package/dist/src/services/harness-frozen-eval.d.ts +22 -0
  40. package/dist/src/services/harness-frozen-eval.js +66 -0
  41. package/dist/src/services/harness-hosts.d.ts +40 -0
  42. package/dist/src/services/harness-hosts.js +88 -0
  43. package/dist/src/services/harness-improvement-ledger.d.ts +63 -0
  44. package/dist/src/services/harness-improvement-ledger.js +101 -0
  45. package/dist/src/services/harness-loop.d.ts +53 -0
  46. package/dist/src/services/harness-loop.js +85 -0
  47. package/dist/src/services/harness-qualification.d.ts +66 -0
  48. package/dist/src/services/harness-qualification.js +143 -0
  49. package/dist/src/services/harness-replay.d.ts +37 -0
  50. package/dist/src/services/harness-replay.js +92 -0
  51. package/dist/src/services/harness-verify.d.ts +33 -0
  52. package/dist/src/services/harness-verify.js +26 -0
  53. package/dist/src/services/harness-worker.d.ts +23 -0
  54. package/dist/src/services/harness-worker.js +66 -0
  55. package/dist/src/services/worker-daemon.d.ts +8 -1
  56. package/dist/src/services/worker-daemon.js +42 -0
  57. package/package.json +1 -1
@@ -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
@@ -40,14 +89,34 @@ function ensureEmbeddings() {
40
89
  return embeddingsPromise;
41
90
  embeddingsPromise = (async () => {
42
91
  try {
92
+ // Tier -1 (PRIMARY): Lattice WASM — real multi-model semantic embeddings
93
+ // (miniLM / bge / paraphrase-miniLM / GPU qwen3-0.6b) ahead of everything.
94
+ // Optional + FAIL-CLOSED: absent/init-fail ⇒ fall straight through to the
95
+ // existing ruvector-ONNX → hash tiers with zero regression.
96
+ try {
97
+ const lat = await import('../ruvector/lattice-wasm.js').catch(() => null);
98
+ if (lat && await lat.latticeAvailable()) {
99
+ const model = lat.DEFAULT_LATTICE_MODEL;
100
+ realEmbeddings = {
101
+ embed: async (text) => {
102
+ const v = await lat.latticeEmbed(text, model);
103
+ if (!v || !v.length)
104
+ throw new Error('lattice embed failed'); // → generateEmbedding falls to next tier
105
+ return v;
106
+ },
107
+ };
108
+ embeddingServiceName = `lattice-wasm/${model} (${lat.latticeModels().length} model${lat.latticeModels().length === 1 ? '' : 's'})`;
109
+ }
110
+ }
111
+ catch { /* lattice absent — fall through */ }
43
112
  // Tier 0: ruvector@0.2.27 — bundled all-MiniLM-L6-v2 + parallel worker pool.
44
113
  // Probe with isOnnxAvailable() and verify an actual embed succeeds (avoids
45
114
  // the type-load-success-but-runtime-fails trap from ADR-086). The probe now
46
115
  // runs on first embed request instead of at import time.
47
116
  // NOTE: ruvector's embed() returns `{embedding, dimension, timeMs}` — we
48
117
  // unwrap to plain number[] for the shared interface.
49
- const rv = await import('ruvector').catch(() => null);
50
- if (rv?.embed && typeof rv.embed === 'function' && rv.isOnnxAvailable?.()) {
118
+ const rv = !realEmbeddings ? await import('ruvector').catch(() => null) : null;
119
+ if (!realEmbeddings && rv?.embed && typeof rv.embed === 'function' && rv.isOnnxAvailable?.()) {
51
120
  try {
52
121
  if (typeof rv.initOnnxEmbedder === 'function')
53
122
  await rv.initOnnxEmbedder();
@@ -159,6 +228,19 @@ function loadNeuralStore() {
159
228
  }
160
229
  return { models: {}, patterns: {}, version: '3.0.0' };
161
230
  }
231
+ /**
232
+ * ADR-176 flywheel: expose the stored patterns (id/name/content) so the
233
+ * self-optimizing loop can harvest a benchmark corpus from real usage. Additive,
234
+ * read-only, never throws.
235
+ */
236
+ export function getStorePatterns() {
237
+ try {
238
+ return Object.values(loadNeuralStore().patterns ?? {}).map((p) => ({ id: p.id, name: p.name, content: p.content }));
239
+ }
240
+ catch {
241
+ return [];
242
+ }
243
+ }
162
244
  function saveNeuralStore(store) {
163
245
  ensureNeuralDir();
164
246
  writeFileSync(getNeuralPath(), JSON.stringify(store, null, 2), 'utf-8');
@@ -604,13 +686,28 @@ export const neuralTools = [
604
686
  // sub-params than non-rerank (the cross-encoder adds semantic depth,
605
687
  // so the hybrid stage can be more keyword-focused). nDCG@3 0.900 →
606
688
  // 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);
689
+ // Champion-provided defaults (ADR-176/177): explicit input wins, then the
690
+ // adopted proven-config champion, then the hardcoded ADR-082 defaults.
691
+ const champ = activeChampionParams();
692
+ const alpha = Number(input.alpha ?? champ.alpha ?? 0.5);
693
+ const mmrLambda = Number(input.mmrLambda ?? champ.mmrLambda ?? 0.7);
609
694
  const { tokenize, buildCorpusStats, hybridScores, mmrRerank, multiFieldBM25, typePenalty } = await import('../memory/hybrid-retrieval.js');
610
- const queryEmbedding = await generateEmbedding(query, 384);
611
695
  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));
696
+ // Query embedding + cosine array depend only on (query, store) NOT the
697
+ // retrieval config. Cache them so scoring many configs for one query
698
+ // (the flywheel's access pattern) embeds + cosines once, not per config.
699
+ const _cosKey = `${corpusFingerprint(patterns)}::${query}`;
700
+ let queryEmbedding, cosineArr;
701
+ const _hit = _cosineCacheGet(_cosKey);
702
+ if (_hit) {
703
+ queryEmbedding = _hit.queryEmbedding;
704
+ cosineArr = _hit.cosineArr;
705
+ }
706
+ else {
707
+ queryEmbedding = await generateEmbedding(query, 384);
708
+ cosineArr = patterns.map((p) => cosineSimilarity(queryEmbedding, p.embedding));
709
+ _cosineCacheSet(_cosKey, { queryEmbedding, cosineArr });
710
+ }
614
711
  if (mode === 'cosine') {
615
712
  const ranked = patterns
616
713
  .map((p, i) => ({ ...p, similarity: cosineArr[i] }))
@@ -630,23 +727,35 @@ export const neuralTools = [
630
727
  // Hybrid path — multi-field BM25 (subject 3×, body 1×) + type penalty
631
728
  // for meta-commits (release bumps / merges) per ADR-079. Falls back
632
729
  // 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);
730
+ // Cache the (config-independent) tokenized docs + BM25 stats by store fingerprint.
731
+ const _fp = corpusFingerprint(patterns);
732
+ let subjectDocs, bodyDocs, subjectStats, bodyStats;
733
+ if (_corpusStatsCache && _corpusStatsCache.fp === _fp) {
734
+ subjectDocs = _corpusStatsCache.subjectDocs;
735
+ bodyDocs = _corpusStatsCache.bodyDocs;
736
+ subjectStats = _corpusStatsCache.subjectStats;
737
+ bodyStats = _corpusStatsCache.bodyStats;
738
+ }
739
+ else {
740
+ subjectDocs = patterns.map((p) => tokenize(p.name ?? ''));
741
+ bodyDocs = patterns.map((p) => {
742
+ // Body is content minus the subject — if content starts with name,
743
+ // strip it; otherwise use full content (with name removed if duplicated).
744
+ const c = p.content ?? '';
745
+ const n = p.name ?? '';
746
+ return tokenize(c.startsWith(n) ? c.slice(n.length) : c);
747
+ });
748
+ subjectStats = buildCorpusStats(subjectDocs);
749
+ bodyStats = buildCorpusStats(bodyDocs);
750
+ _corpusStatsCache = { fp: _fp, subjectDocs, bodyDocs, subjectStats, bodyStats };
751
+ }
643
752
  const queryTokens = tokenize(query);
644
753
  // ADR-082: subjectWeight 3.0 → 2.0 from grid (sw=2 dominates at hybrid-only).
645
754
  // ADR-083 joint grid: when rerank is on, the cross-encoder handles
646
755
  // semantic understanding, so the hybrid stage can be MORE
647
756
  // 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);
757
+ const subjectWeight = Number(input.subjectWeight ?? champ.subjectWeight ?? (useRerank ? 3.0 : 2.0));
758
+ const bodyWeight = Number(input.bodyWeight ?? champ.bodyWeight ?? 1.0);
650
759
  const bm25Arr = patterns.map((_, i) => multiFieldBM25(queryTokens, subjectDocs[i], bodyDocs[i], subjectStats, bodyStats, subjectWeight, bodyWeight));
651
760
  const baseHybrid = hybridScores(cosineArr, bm25Arr, alpha);
652
761
  // Type penalty — opt-in (default 1.0 = disabled). Ablation in ADR-079
@@ -654,7 +763,7 @@ export const neuralTools = [
654
763
  // penalty enabled) because some relevant work commits also match the
655
764
  // Merge/release regex. Callers wanting aggressive meta-commit
656
765
  // suppression can set {typePenaltyFactor: 0.5}.
657
- const typeFactor = Number(input.typePenaltyFactor ?? 1.0);
766
+ const typeFactor = Number(input.typePenaltyFactor ?? champ.typePenaltyFactor ?? 1.0);
658
767
  const hybridArr = typeFactor === 1.0
659
768
  ? baseHybrid
660
769
  : baseHybrid.map((s, i) => s * typePenalty(patterns[i].name, typeFactor));
@@ -0,0 +1,14 @@
1
+ /** Default package name (ruvnet WASM convention); override with RUFLO_LATTICE_WASM_PKG. */
2
+ export declare const LATTICE_WASM_PKG: string;
3
+ export type LatticeModel = 'minilm' | 'bge' | 'paraphrase-minilm' | 'qwen3-0.6b' | string;
4
+ export declare const DEFAULT_LATTICE_MODEL: LatticeModel;
5
+ /** Is the Lattice WASM embedder installed + initializable? Cached; never throws. */
6
+ export declare function latticeAvailable(): Promise<boolean>;
7
+ /** The models Lattice reports (empty until availability is probed). */
8
+ export declare function latticeModels(): LatticeModel[];
9
+ /**
10
+ * Embed `text` with `model` via Lattice WASM. Returns null on any failure so the
11
+ * caller can fall through to the next tier. Never throws.
12
+ */
13
+ export declare function latticeEmbed(text: string, model?: LatticeModel): Promise<number[] | null>;
14
+ //# sourceMappingURL=lattice-wasm.d.ts.map
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Lattice WASM embedder adapter — the primary embedding tier (ADR: embedding
3
+ * substrate upgrade). Replaces hash placeholders with real semantic embeddings
4
+ * and adds multiple models (miniLM, bge, multi-paraphrase-miniLM, GPU qwen3-0.6B).
5
+ *
6
+ * Built on the proven `@ruvector/ruvllm-wasm` optional-dependency convention:
7
+ * - dynamically imported (never a hard dependency),
8
+ * - WASM initialized from bundled bytes,
9
+ * - fully FAIL-CLOSED: if the package is absent, the WASM fails to init, or the
10
+ * embed API differs, `latticeAvailable()` returns false and callers fall
11
+ * through to the existing ruvector-ONNX → hash tiers with ZERO regression.
12
+ *
13
+ * The package specifier is configurable (`RUFLO_LATTICE_WASM_PKG`) so the exact
14
+ * published name can be set without a code change; the API is probed tolerantly.
15
+ * Opt-in for the GPU model: qwen3 is only selected when explicitly requested.
16
+ */
17
+ import { createRequire } from 'module';
18
+ import { readFileSync } from 'fs';
19
+ const require_ = createRequire(import.meta.url);
20
+ /** Default package name (ruvnet WASM convention); override with RUFLO_LATTICE_WASM_PKG. */
21
+ export const LATTICE_WASM_PKG = process.env.RUFLO_LATTICE_WASM_PKG || '@ruvector/lattice-wasm';
22
+ export const DEFAULT_LATTICE_MODEL = process.env.RUFLO_EMBED_MODEL || 'minilm';
23
+ /* eslint-disable @typescript-eslint/no-explicit-any */
24
+ let _mod = null;
25
+ let _ready = false;
26
+ let _probed = false;
27
+ let _available = false;
28
+ let _models = [];
29
+ async function loadModule() {
30
+ if (_mod)
31
+ return _mod;
32
+ const spec = LATTICE_WASM_PKG;
33
+ _mod = await import(spec).catch(() => null); // optional — absent ⇒ null ⇒ unavailable
34
+ return _mod;
35
+ }
36
+ async function ensureInit() {
37
+ if (_ready)
38
+ return true;
39
+ const mod = await loadModule();
40
+ if (!mod)
41
+ return false;
42
+ try {
43
+ // ruvnet WASM convention: initSync({ module: <wasm bytes> }); tolerate variants.
44
+ if (!_ready && typeof mod.initSync === 'function') {
45
+ let wasmBytes;
46
+ for (const cand of ['lattice_wasm_bg.wasm', 'lattice_bg.wasm', 'index_bg.wasm']) {
47
+ try {
48
+ wasmBytes = readFileSync(require_.resolve(`${LATTICE_WASM_PKG}/${cand}`));
49
+ break;
50
+ }
51
+ catch { /* try next */ }
52
+ }
53
+ mod.initSync(wasmBytes ? { module: wasmBytes } : undefined);
54
+ }
55
+ else if (typeof mod.default === 'function') {
56
+ await mod.default(); // some wasm-bindgen builds export an async default init
57
+ }
58
+ _ready = true;
59
+ return true;
60
+ }
61
+ catch {
62
+ return false; // init failed ⇒ fail closed
63
+ }
64
+ }
65
+ /** Extract a plain number[] from whatever shape the module's embed returns. */
66
+ function toVec(r) {
67
+ const v = (r && typeof r === 'object' && 'embedding' in r) ? r.embedding : r;
68
+ if (!v)
69
+ return null;
70
+ if (Array.isArray(v))
71
+ return v;
72
+ if (v.length !== undefined)
73
+ return Array.from(v);
74
+ return null;
75
+ }
76
+ /** Is the Lattice WASM embedder installed + initializable? Cached; never throws. */
77
+ export async function latticeAvailable() {
78
+ if (_probed)
79
+ return _available;
80
+ _probed = true;
81
+ try {
82
+ if (!(await ensureInit())) {
83
+ _available = false;
84
+ return false;
85
+ }
86
+ const mod = _mod;
87
+ // discover models (tolerant): listModels() / models / MODELS
88
+ try {
89
+ const list = typeof mod.listModels === 'function' ? mod.listModels() : (mod.models ?? mod.MODELS);
90
+ if (Array.isArray(list) && list.length)
91
+ _models = list;
92
+ }
93
+ catch { /* leave default */ }
94
+ if (!_models.length)
95
+ _models = [DEFAULT_LATTICE_MODEL];
96
+ // verify an actual embed succeeds (the ADR-086 "loads but runtime-fails" trap).
97
+ const probe = await latticeEmbedRaw('probe', DEFAULT_LATTICE_MODEL);
98
+ _available = !!probe && probe.length > 0;
99
+ return _available;
100
+ }
101
+ catch {
102
+ _available = false;
103
+ return false;
104
+ }
105
+ }
106
+ /** The models Lattice reports (empty until availability is probed). */
107
+ export function latticeModels() { return [..._models]; }
108
+ async function latticeEmbedRaw(text, model) {
109
+ const mod = _mod;
110
+ if (!mod)
111
+ return null;
112
+ // tolerant API probing across plausible wasm-bindgen surfaces.
113
+ const attempts = [
114
+ () => typeof mod.embed === 'function' ? mod.embed(text, model) : undefined,
115
+ () => typeof mod.embed === 'function' ? mod.embed(text) : undefined,
116
+ () => typeof mod.embedText === 'function' ? mod.embedText(text, model) : undefined,
117
+ () => typeof mod.Embedder === 'function' ? new mod.Embedder(model).embed(text) : undefined,
118
+ ];
119
+ for (const a of attempts) {
120
+ try {
121
+ const r = await a();
122
+ const v = toVec(r);
123
+ if (v)
124
+ return v;
125
+ }
126
+ catch { /* try next surface */ }
127
+ }
128
+ return null;
129
+ }
130
+ /**
131
+ * Embed `text` with `model` via Lattice WASM. Returns null on any failure so the
132
+ * caller can fall through to the next tier. Never throws.
133
+ */
134
+ export async function latticeEmbed(text, model = DEFAULT_LATTICE_MODEL) {
135
+ try {
136
+ if (!(await latticeAvailable()))
137
+ return null;
138
+ return await latticeEmbedRaw(text, model);
139
+ }
140
+ catch {
141
+ return null;
142
+ }
143
+ }
144
+ //# sourceMappingURL=lattice-wasm.js.map
@@ -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