@claude-flow/cli 3.30.0 → 3.30.1

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.
@@ -1 +1 @@
1
- 3.29.0
1
+ 3.30.0
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "manifest": {
3
- "version": "3.30.0",
3
+ "version": "3.30.1",
4
4
  "files": {
5
5
  "auto-memory-hook.mjs": "e3e1033b24704992ddef6b31c7fa9dd7fcd9e1af7935dd77ef73402b916b31e6",
6
6
  "hook-handler.cjs": "dc926a1a585abac85941347894632a800a9c4394e99166726017643e5b3c5950",
7
7
  "intelligence.cjs": "5a55d979cb7ba5c8c4f27f3b2e6d686fbb1045d180023b803da672a37e05b915",
8
- "statusline.cjs": "8416172e504b03f9ec2266a47bba048578c3b1e30c5c7c97a0a8261460cd601d"
8
+ "statusline.cjs": "7d7bdee732e1c75b863e409afb86ce0d712f4919245e990d806da6752015bffa"
9
9
  }
10
10
  },
11
- "signature": "V62Co3JaEVPFyVi0Miuo0+CdhriygvtceQlJiMKu7sBysvVUOObrueDW9j3hJ7ShWQYwLppMpndTt3EBiI9QDA==",
11
+ "signature": "6Dw13BYh3EAjBOefodVYha+5dpmcAxralqJIfT07xi9WUvhtDqwISpOVRWHMSdHM+XL1YGRh8I071X1XDB3zDw==",
12
12
  "algorithm": "ed25519"
13
13
  }
@@ -42,12 +42,18 @@ const CONFIG = {
42
42
  const CWD = process.cwd();
43
43
 
44
44
  // ─── Delegation cache ───────────────────────────────────────────
45
- // Cache the CLI JSON result for 60s so rapid prompt re-renders
46
- // (Claude Code refreshes the statusline several times a second while
47
- // streaming) don't re-invoke the CLI each time. #2337: bumped 10s→60s
48
- // because 10s was far too short for how often Claude Code re-renders.
45
+ // Cache the CLI JSON result so rapid prompt re-renders (Claude Code
46
+ // refreshes the statusline several times a second while streaming) don't
47
+ // re-invoke the CLI each time.
48
+ // #2337 bumped 10s 60s.
49
+ // Followup for anthropics/claude-code#70200 (Windows console-flash bug —
50
+ // claude.exe spawns hook/statusline subprocesses without CREATE_NO_WINDOW,
51
+ // producing a visible cmd flash on every render): bumped 60s → 300s to
52
+ // reduce the flash rate 5x on Windows until the upstream fix ships.
53
+ // Tradeoff: stat/git counters update every 5min instead of every 1min;
54
+ // promo/insight row still rotates on its own tighter 20s promoFresh clock.
49
55
  const CACHE_FILE = path.join(os.tmpdir(), 'ruflo-statusline-cache-' + require('crypto').createHash('md5').update(CWD).digest('hex').slice(0, 8) + '.json');
50
- const CACHE_TTL_MS = 60000;
56
+ const CACHE_TTL_MS = 300000;
51
57
 
52
58
  // The promo/insight row is designed to rotate on a 20s cadence (funnel/
53
59
  // rotation.ts's ROTATION_SLOT_MS / funnel/promo.ts's insight-slot check —
@@ -229,7 +235,7 @@ function getStatuslineData() {
229
235
  try {
230
236
  const raw = execSync(
231
237
  cmd,
232
- { encoding: 'utf-8', timeout: 8000, stdio: ['pipe', 'pipe', 'pipe'], cwd: CWD }
238
+ { encoding: 'utf-8', timeout: 8000, stdio: ['pipe', 'pipe', 'pipe'], cwd: CWD, windowsHide: true }
233
239
  ).trim();
234
240
  // The CLI may emit preamble lines before the JSON — find the first '{'.
235
241
  const jsonStart = raw.indexOf('{');
@@ -445,6 +451,11 @@ function safeExec(cmd, timeoutMs) {
445
451
  encoding: 'utf-8',
446
452
  timeout: timeoutMs || 2000,
447
453
  stdio: ['pipe', 'pipe', 'pipe'],
454
+ // Windows: without this, every execSync spawns cmd.exe /d /s /c which
455
+ // flashes a visible console window every render (~1/min via the 60s
456
+ // cache TTL). windowsHide runs the child in a hidden window instead.
457
+ // No-op on POSIX. Fix for #2XXX (user report: "cmd prompt keeps opening").
458
+ windowsHide: true,
448
459
  }).trim();
449
460
  } catch {
450
461
  return '';
@@ -868,12 +879,16 @@ function getPromoRow(d) {
868
879
  if (/^(0|false|off|no)$/i.test(String(process.env.RUFLO_FUNNEL || ''))) return null;
869
880
  const promo = d && d.promo;
870
881
  if (!promo || typeof promo.text !== 'string') return null;
871
- // Strip control chars / ANSI / bidi overrides and hard-cap length
872
- // promo copy is data and must never emit its own terminal sequences.
873
- const text = promo.text
882
+ // Strip control chars / ANSI / bidi overrides promo copy is data and
883
+ // must never emit its own terminal sequences. Hard-cap length AFTER the
884
+ // strip; append an ellipsis when the cap fires so the row visibly reads
885
+ // as truncated instead of chopping a word mid-character (was: silent
886
+ // slice(0,100) that could produce output that looked like corrupt data).
887
+ const MAX_LEN = 100;
888
+ const sanitized = promo.text
874
889
  .replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, '')
875
- .slice(0, 100)
876
- .trim();
890
+ ;
891
+ const text = (sanitized.length > MAX_LEN ? sanitized.slice(0, MAX_LEN - 1).trimEnd() + '…' : sanitized).trim();
877
892
  if (text.length === 0) return null;
878
893
  // Split the label from the trailing "· manage: ruflo settings" instruction
879
894
  // so each part gets styling that matches what it actually IS:
@@ -896,9 +911,68 @@ function getPromoRow(d) {
896
911
  const DIM_OFF = '\u001b[22m';
897
912
  const BOLD_ON = '\u001b[1m';
898
913
  const BOLD_OFF = '\u001b[22m';
899
- const linked = promo.url ? UL_ON + safeTerminalLink(label, promo.url) + UL_OFF : label;
900
- if (!command) return linked;
901
- return linked + DIM_ON + manageWord + DIM_OFF + BOLD_ON + command + BOLD_OFF;
914
+ const FG_BRIGHT_WHITE = '';
915
+ // Reset FG to default so the caller's row-color code resumes coloring the
916
+ // rest of the row after the command portion. Without this the row-color
917
+ // escape wouldn't visibly re-apply because we already emitted an explicit FG.
918
+ const FG_DEFAULT = '';
919
+ // Some hosts (Claude Code's Windows UI, cmd.exe, older mintty) don't
920
+ // render OSC 8 hyperlinks as clickable — the label just underlines and
921
+ // clicks do nothing. Append a "(domain)" suffix so the destination is
922
+ // visible/copyable everywhere. Wrap the suffix in OSC 8 too so terminals
923
+ // that DO support hyperlinks give users TWO click targets (label AND
924
+ // domain hint) instead of one — some Windows hosts render one but not
925
+ // the other depending on how the statusline row is parsed.
926
+ // Only for URLs (not educational tips), and only when the label doesn't
927
+ // already end in the domain to avoid duplication.
928
+ let visibleUrlHint = '';
929
+ if (promo.url) {
930
+ try {
931
+ const host = new URL(promo.url).hostname.replace(/^www\./, '');
932
+ // Strip the click-redirect wrapper so users see the FINAL destination,
933
+ // not funnel.ruv.io. If the URL is /v1/click/<id>?to=<encoded>, pull the target.
934
+ let displayHost = host;
935
+ try {
936
+ const to = new URL(promo.url).searchParams.get('to');
937
+ if (to) displayHost = new URL(to).hostname.replace(/^www\./, '');
938
+ } catch { /* not a click-redirect, keep the raw host */ }
939
+ if (displayHost && !label.toLowerCase().endsWith(displayHost.toLowerCase())) {
940
+ // safeTerminalLink returns the plain string if URL isn't allowlisted
941
+ // or the terminal can't do OSC 8 — either way the domain stays visible.
942
+ const clickableDomain = safeTerminalLink(displayHost, promo.url);
943
+ visibleUrlHint = DIM_ON + ' (' + clickableDomain + ')' + DIM_OFF;
944
+ }
945
+ } catch { /* malformed URL — omit hint, never break the row */ }
946
+ }
947
+ // "Entire row clickable" (user request) — wrap the whole assembled
948
+ // string in ONE OSC 8 hyperlink instead of just the label. The command
949
+ // portion keeps its bold + bright-white treatment (no underline) so it
950
+ // still VISUALLY reads as a shell command the user should type, not a
951
+ // link — but if the user clicks anywhere on the row (label, domain
952
+ // hint, connector, even the command text), the terminal opens the URL.
953
+ // Clicking DOES NOT execute the command; it just opens the target URL,
954
+ // which is safe. Terminals that ignore OSC 8 render the whole row as
955
+ // styled text and no click behavior — the previous fallback (visible
956
+ // domain suffix) still keeps the destination readable.
957
+ const wrapWholeRowInHyperlink = (assembled) => {
958
+ if (!promo.url) return assembled;
959
+ if (!terminalSupportsHyperlinks()) return assembled;
960
+ let parsed;
961
+ try { parsed = new URL(promo.url); } catch { return assembled; }
962
+ if (parsed.protocol !== 'https:') return assembled;
963
+ if (!PROMO_LINK_HOSTS.has(parsed.hostname)) return assembled;
964
+ const ESC = '';
965
+ return ESC + ']8;;' + parsed.href + ESC + '\\' + assembled + ESC + ']8;;' + ESC + '\\';
966
+ };
967
+ // Visual styling stays per-part. We only add the OSC 8 wrap around the
968
+ // combined string, so the whole row is one click target.
969
+ const labelStyled = promo.url ? UL_ON + label + UL_OFF : label;
970
+ if (!command) return wrapWholeRowInHyperlink(labelStyled + visibleUrlHint);
971
+ return wrapWholeRowInHyperlink(
972
+ labelStyled + visibleUrlHint
973
+ + DIM_ON + manageWord + DIM_OFF
974
+ + BOLD_ON + FG_BRIGHT_WHITE + command + FG_DEFAULT + BOLD_OFF
975
+ );
902
976
  } catch (e) {
903
977
  return null; // the promo row must never break the statusline
904
978
  }
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "generation": 1,
4
- "generatedAt": "2026-07-14T19:16:42.603Z",
5
- "gitSha": "fea1d9e9",
4
+ "generatedAt": "2026-07-14T20:11:46.876Z",
5
+ "gitSha": "5fa2a3ce",
6
6
  "catalog": {
7
7
  "agents": 164,
8
8
  "tools": 387,
@@ -77,938 +77,69 @@ export function generateStatuslineScript(options) {
77
77
  // candidate scan still wins over this baked-in value when it finds
78
78
  // something newer (e.g. a later `npm update` in the same project).
79
79
  const bakedVersion = getInstalledCliVersionLocal();
80
- return `#!/usr/bin/env node
81
- /**
82
- * RuFlo V3 Statusline delegation build (#2195)
83
- *
84
- * Fix for ruvnet/ruflo#2195: the previous version re-implemented all data
85
- * readers locally using fragile file probes that missed AgentDB patterns,
86
- * the v3/docs/adr/ ADR directory, and the real vector count.
87
- *
88
- * This version delegates to 'npx @claude-flow/cli hooks statusline --json'
89
- * as the single source of truth. That command queries AgentDB directly,
90
- * counts ADRs in both directories, and reports the real intelligence pct.
91
- *
92
- * ADR counting falls back to local file reads so the display still works
93
- * without network access (counts both v3/docs/adr/ and v3/implementation/adrs/).
94
- *
95
- * Cache: JSON result is cached in /tmp for 10s so rapid prompt triggers
96
- * (every keystroke in some shells) don't hammer the CLI on every call.
97
- *
98
- * Usage: node statusline.cjs [--json] [--compact] [--dashboard]
99
- */
100
-
101
- /* eslint-disable @typescript-eslint/no-var-requires */
102
- const fs = require('fs');
103
- const path = require('path');
104
- const { execSync } = require('child_process');
105
- const os = require('os');
106
-
107
- // Configuration
108
- const CONFIG = {
109
- maxAgents: ${maxAgents},
110
- // Session-cost display. Claude Code's cost.total_cost_usd is a client-side
111
- // estimate that "may differ from your actual bill" and reads as misleading on
112
- // subscription plans, where token usage is not billed per dollar. These let
113
- // each user pick what the segment means to them without changing the default.
114
- // RUFLO_STATUSLINE_COST_SYMBOL override the leading '$' (e.g. ⚡, €, 🌱);
115
- // set to an empty string for the number alone.
116
- // RUFLO_STATUSLINE_HIDE_COST 1/true/yes/on removes the segment entirely.
117
- costSymbol: process.env.RUFLO_STATUSLINE_COST_SYMBOL ?? '$',
118
- hideCost: /^(1|true|yes|on)$/i.test(process.env.RUFLO_STATUSLINE_HIDE_COST || ''),
119
- };
120
-
121
- const CWD = process.cwd();
122
-
123
- // ─── Delegation cache ───────────────────────────────────────────
124
- // Cache the CLI JSON result so rapid prompt re-renders (Claude Code
125
- // refreshes the statusline several times a second while streaming) don't
126
- // re-invoke the CLI each time.
127
- // #2337 bumped 10s 60s.
128
- // Followup for anthropics/claude-code#70200 (Windows console-flash bug
129
- // claude.exe spawns hook/statusline subprocesses without CREATE_NO_WINDOW,
130
- // producing a visible cmd flash on every render): bumped 60s → 300s to
131
- // reduce the flash rate 5x on Windows until the upstream fix ships.
132
- // Tradeoff: stat/git counters update every 5min instead of every 1min;
133
- // promo/insight row still rotates on its own tighter 20s promoFresh clock.
134
- const CACHE_FILE = path.join(os.tmpdir(), 'ruflo-statusline-cache-' + require('crypto').createHash('md5').update(CWD).digest('hex').slice(0, 8) + '.json');
135
- const CACHE_TTL_MS = 300000;
136
-
137
- // The promo/insight row is designed to rotate on a 20s cadence (funnel/
138
- // rotation.ts's ROTATION_SLOT_MS / funnel/promo.ts's insight-slot check
139
- // duplicated here as a bare number since this generated script has no
140
- // runtime import of the funnel module; keep in sync if that constant ever
141
- // changes). The rotation slot is only ever (re)computed SERVER-SIDE inside
142
- // the CLI subprocess this file shells out to — so a general 60s data cache
143
- // (correct and necessary for #2337) silently made that 20s design
144
- // unreachable: cache.fresh stayed true across 2-3 whole rotation slots,
145
- // so the row visibly "didn't rotate" (user report). Fix: track promo
146
- // freshness on its OWN, tighter clock — when it lags behind the current
147
- // slot, fall through to a real CLI call even though the REST of the
148
- // cached data (security/swarm/system) is still within CACHE_TTL_MS. This
149
- // does not touch or regress #2337's fix; it only adds a narrower check.
150
- const PROMO_ROTATION_SLOT_MS = 20000;
151
-
152
- // Persistent last-known-good promo record. Lives outside the /tmp cache so it
153
- // survives a full cache wipe / cache write race / CLI failure combo. Written
154
- // every time we successfully render a promo; read as a last resort so the row
155
- // never blinks out mid-session (was: 'promo shows then hides' bug report).
156
- const PROMO_MEMO_FILE = path.join(os.homedir(), '.ruflo', 'statusline-promo.json');
157
- const PROMO_MEMO_TTL_MS = 6 * 60 * 60 * 1000; // 6h — long enough to bridge any hiccup, short enough that a real disable takes effect fast.
158
-
159
- // #2337: resolve an already-installed @claude-flow/cli (or ruflo) bin so we
160
- // can invoke it directly via \`node\`. The previous version called
161
- // \`npx --yes @claude-flow/cli@latest\` on every uncached render, which forces
162
- // a registry resolution + cold-start of the entire CLI per render. With
163
- // multiple concurrent Claude Code sessions this storms the host (reporter
164
- // saw load average 40-65 on a 12-core box).
165
- //
166
- // Returns EVERY existing bin/cli.js candidate, in preference order (project,
167
- // monorepo, plugin marketplace, global node_modules including custom-prefix
168
- // layouts like ~/.npm-global) — mirrors getPkgVersion()'s own path probing.
169
- //
170
- // Returns a list, not a single winner: \`fs.existsSync\` only proves a file is
171
- // present, not that it actually runs. A marketplace/npx-cached install can
172
- // exist on disk but be broken (observed in practice: a stale marketplace
173
- // checkout whose dist/ imports a workspace package, '@claude-flow/cli-core',
174
- // that isn't bundled there — every invocation throws ERR_MODULE_NOT_FOUND).
175
- // Picking the first EXISTING path and never falling through meant a single
176
- // broken install silently killed the promo row for the entire session (the
177
- // CLI call always failed, so the memo could never refresh and eventually
178
- // expired). getStatuslineData() now walks this whole list and tries the next
179
- // candidate on failure, so one broken install can't permanently wedge it.
180
- function resolveCliBinCandidates() {
181
- const candidates = [];
182
- try {
183
- const home = os.homedir();
184
- candidates.push(
185
- path.join(home, '.claude', 'plugins', 'marketplaces', 'ruflo', 'bin', 'cli.js'),
186
- path.join(CWD, 'node_modules', '@claude-flow', 'cli', 'bin', 'cli.js'),
187
- path.join(CWD, 'node_modules', 'ruflo', 'bin', 'cli.js'),
188
- path.join(CWD, 'v3', '@claude-flow', 'cli', 'bin', 'cli.js'),
189
- );
190
- try {
191
- const binDir = path.dirname(process.execPath);
192
- const globalModuleDirs = [path.join(binDir, '..', 'lib', 'node_modules'), path.join(binDir, 'node_modules')];
193
- for (const prefix of [process.env.npm_config_prefix, process.env.PREFIX, path.join(home, '.npm-global')]) {
194
- if (prefix) globalModuleDirs.push(path.join(prefix, 'lib', 'node_modules'));
195
- }
196
- for (const gm of globalModuleDirs) {
197
- candidates.push(
198
- path.join(gm, 'ruflo', 'bin', 'cli.js'),
199
- path.join(gm, '@claude-flow', 'cli', 'bin', 'cli.js'),
200
- );
201
- }
202
- } catch { /* ignore */ }
203
- } catch { /* ignore */ }
204
- return candidates.filter((p) => {
205
- try {
206
- if (!fs.existsSync(p)) return false;
207
- // A candidate's bin/cli.js can exist on disk while its compiled
208
- // dist/ never got built (Claude Code's own plugin marketplace just
209
- // git-clones the repo — no install/build step — so every marketplace
210
- // install is a source-only checkout by construction). Importing
211
- // dist/src/index.js from bin/cli.js then throws MODULE_NOT_FOUND on
212
- // every real command; only --version happens to survive it. Check
213
- // for the compiled entrypoint too so a doomed candidate is skipped
214
- // up front instead of wasting a spawn-and-fail on every render.
215
- return fs.existsSync(path.join(path.dirname(p), '..', 'dist', 'src', 'index.js'));
216
- } catch { return false; }
217
- });
218
- }
219
-
220
- // Return { fresh, promoFresh, data }. 'fresh' is true only if within the TTL
221
- // — but data is returned regardless (stale-while-revalidate). This lets us
222
- // serve last known state (specifically the promo row) when the CLI is
223
- // slow/unavailable, so users don't see the funnel row flicker in and out on
224
- // cache expiry. 'promoFresh' is a SEPARATE, tighter check on the same clock
225
- // as PROMO_ROTATION_SLOT_MS — see that constant's comment for why the promo
226
- // row needs its own freshness bound distinct from the general 60s TTL.
227
- function readCache() {
228
- try {
229
- if (fs.existsSync(CACHE_FILE)) {
230
- const raw = JSON.parse(fs.readFileSync(CACHE_FILE, 'utf-8'));
231
- if (raw && raw._ts && raw.data) {
232
- const age = Date.now() - raw._ts;
233
- return { fresh: age < CACHE_TTL_MS, promoFresh: age < PROMO_ROTATION_SLOT_MS, data: raw.data };
234
- }
235
- }
236
- } catch { /* ignore */ }
237
- return { fresh: false, promoFresh: false, data: null };
238
- }
239
-
240
- function writeCache(data) {
241
- try { fs.writeFileSync(CACHE_FILE, JSON.stringify({ _ts: Date.now(), data }), 'utf-8'); } catch { /* ignore */ }
242
- // Also memoize any promo we saw so the row can survive future CLI hiccups.
243
- try {
244
- if (data && data.promo && typeof data.promo === 'object') {
245
- fs.mkdirSync(path.dirname(PROMO_MEMO_FILE), { recursive: true, mode: 0o700 });
246
- fs.writeFileSync(PROMO_MEMO_FILE, JSON.stringify({ _ts: Date.now(), promo: data.promo }), { encoding: 'utf-8', mode: 0o600 });
247
- }
248
- } catch { /* ignore */ }
249
- }
250
-
251
- // Last resort: read a memoized promo (up to 6h old). Used when no cache and
252
- // no CLI response is available — the row still renders, so users don't see
253
- // the disclosure blink out. Returns null when the memo is absent, expired,
254
- // or malformed. Never throws.
255
- function readPromoMemo() {
256
- try {
257
- if (!fs.existsSync(PROMO_MEMO_FILE)) return null;
258
- const raw = JSON.parse(fs.readFileSync(PROMO_MEMO_FILE, 'utf-8'));
259
- if (raw && raw._ts && (Date.now() - raw._ts) < PROMO_MEMO_TTL_MS && raw.promo) {
260
- return raw.promo;
261
- }
262
- } catch { /* ignore */ }
263
- return null;
264
- }
265
-
266
- /**
267
- * Single source of truth: delegate to the CLI hooks statusline --json command.
268
- * Falls back to a minimal static object on failure so the statusline still renders.
269
- *
270
- * Fix for ruflo#2195: the previous local readers returned 0 for AgentDB patterns
271
- * (missed the .swarm/memory.db → AgentDB path), computed dddProgress wrong,
272
- * and only counted ADRs in v3/implementation/adrs/ (missed v3/docs/adr/).
273
- */
274
- // Overlay the memoized promo onto any data object that's missing one. This is
275
- // the safety net that keeps the funnel row rendered when an OLDER cached CLI
276
- // version is picked up by npx — that older CLI succeeds but omits promo, so
277
- // the JSON round-trips clean but without our row. We patch it back here.
278
- function overlayMemoPromo(data) {
279
- if (data && !data.promo) {
280
- const memoPromo = readPromoMemo();
281
- if (memoPromo) data.promo = memoPromo;
282
- }
283
- return data;
284
- }
285
-
286
- function getStatuslineData() {
287
- const cache = readCache();
288
- // Both clocks must be satisfied to skip the CLI call entirely: the general
289
- // 60s TTL (#2337 — don't re-spawn the CLI on every rapid re-render) AND the
290
- // tighter promo-rotation clock (this fix — don't let a still-fresh 60s
291
- // cache silently freeze the promo/insight row across multiple 20s slots).
292
- if (cache.fresh && cache.promoFresh) return overlayMemoPromo(cache.data);
293
-
294
- // #2337: prefer an already-installed CLI bin via direct \`node\` invocation —
295
- // no npx, no registry round-trip, no @latest re-resolve per render. Try
296
- // every candidate that actually EXISTS (not just the first) before falling
297
- // back to \`npx --prefer-offline @claude-flow/cli\` (no @latest); an existing
298
- // but broken install (e.g. a stale marketplace checkout missing a bundled
299
- // workspace dep) must not block trying the next one.
300
- //
301
- // No \`2>/dev/null\` here (deliberately) — the execSync call below already
302
- // sets stdio: ['pipe','pipe','pipe'], which captures/discards stderr at the
303
- // Node level regardless of shell. The redirect was redundant on POSIX and
304
- // actively broke every candidate on Windows: cmd.exe (execSync's default
305
- // shell there) doesn't understand /dev/null, so the CLI delegation always
306
- // failed, silently degrading every render to buildLocalFallback() — 0%
307
- // intelligence and an empty promo row (the memo cache that keeps the row
308
- // populated across CLI hiccups is only ever written from a SUCCESSFUL
309
- // delegation, so it could never get seeded on Windows either).
310
- const cmds = resolveCliBinCandidates()
311
- .map((bin) => '"' + process.execPath + '" "' + bin + '" hooks statusline --json')
312
- .concat(['npx --prefer-offline @claude-flow/cli hooks statusline --json']);
313
- for (const cmd of cmds) {
314
- try {
315
- const raw = execSync(
316
- cmd,
317
- { encoding: 'utf-8', timeout: 8000, stdio: ['pipe', 'pipe', 'pipe'], cwd: CWD }
318
- ).trim();
319
- // The CLI may emit preamble lines before the JSON — find the first '{'.
320
- const jsonStart = raw.indexOf('{');
321
- if (jsonStart === -1) throw new Error('no JSON in CLI output');
322
- const data = JSON.parse(raw.slice(jsonStart));
323
- // Overlay every block the CLI JSON omits (adrs/agentdb/tests/hooks/integration)
324
- // with real local reads, so those segments reflect actual state instead of 0.
325
- applyLocalOverlays(data);
326
- overlayMemoPromo(data);
327
- writeCache(data);
328
- return data;
329
- } catch { /* this candidate unavailable, broken, or timed out — try the next */ }
330
- }
331
-
332
- // Stale-while-revalidate: if we have any cached data, keep serving it so the
333
- // funnel row doesn't flicker on CLI hiccups. Overlay fresh local reads for
334
- // the segments the CLI JSON doesn't populate; the promo row survives.
335
- if (cache.data) {
336
- applyLocalOverlays(cache.data);
337
- overlayMemoPromo(cache.data);
338
- return cache.data;
339
- }
340
-
341
- // Last resort: local probes + memo. Users still see the funnel row.
342
- return overlayMemoPromo(buildLocalFallback());
343
- }
344
-
345
- // Count ADRs from BOTH known directories (fix for ruflo#2195: old code missed
346
- // v3/docs/adr/ which holds ADR-088..ADR-137, i.e. 41 of the 128 total ADRs).
347
- function getLocalADRCount() {
348
- const adrDirs = [
349
- path.join(CWD, 'v3', 'implementation', 'adrs'),
350
- path.join(CWD, 'v3', 'docs', 'adr'),
351
- path.join(CWD, 'docs', 'adrs'),
352
- path.join(CWD, '.claude-flow', 'adrs'),
353
- ];
354
- let total = 0;
355
- for (const dir of adrDirs) {
356
- try {
357
- if (fs.existsSync(dir)) {
358
- const files = fs.readdirSync(dir).filter(function(f) {
359
- return f.endsWith('.md') && (f.startsWith('ADR-') || f.startsWith('adr-') || /^\\d{4}-/.test(f));
360
- });
361
- total += files.length;
362
- }
363
- } catch { /* ignore */ }
364
- }
365
- return { count: total, implemented: total, compliance: 0 };
366
- }
367
-
368
- // ─── Local overlays for segments the CLI JSON omits ──────────────
369
- // 'hooks statusline --json' only returns user/v3Progress/security/swarm/system.
370
- // agentdb/tests/hooks/integration are never populated, so without these overlays
371
- // they render as a permanent 0. Each reader is cheap and degrades to zeros.
372
-
373
- // Real AgentDB stats from the local memory DB. Vectors live in .swarm/memory.db
374
- // (sql.js + HNSW); ruvector.db is an opaque redb store counted only toward size.
375
- // One read-only sqlite3 query (mode=ro never takes a write lock the daemon owns).
376
- function getLocalAgentDB() {
377
- const result = { vectorCount: 0, dbSizeKB: 0, hasHnsw: false };
378
- try {
379
- let bytes = 0;
380
- for (const f of ['.swarm/memory.db', 'ruvector.db']) {
381
- try { bytes += fs.statSync(path.join(CWD, f)).size; } catch { /* missing */ }
382
- }
383
- result.dbSizeKB = Math.round(bytes / 1024);
384
-
385
- const memDb = path.join(CWD, '.swarm', 'memory.db');
386
- if (fs.existsSync(memDb)) {
387
- const Q = String.fromCharCode(34);
388
- // Two INDEPENDENT statements -- do NOT combine into one. Coupling the
389
- // vector count with the vector_indexes row count in a single statement
390
- // meant that on a DB missing the vector_indexes table (older/agentdb-
391
- // written DBs), the whole statement failed at PREPARE time (SQLite
392
- // compiles the full SQL before running), so the valid memory_entries
393
- // count was discarded too and the statusline showed Vectors 0 despite
394
- // thousands of real vectors. Split so a missing table can only zero the
395
- // HNSW flag, never the count. The init self-heal provisions the table so
396
- // the flag recovers on the next ruflo init / MCP start.
397
- const countSql = Q + 'SELECT COUNT(*) FROM memory_entries WHERE embedding IS NOT NULL;' + Q;
398
- const vc = safeExec("sqlite3 'file:" + memDb + "?mode=ro' " + countSql, 1500);
399
- if (vc) result.vectorCount = parseInt(vc, 10) || 0;
400
- // HNSW flag: separate statement. If vector_indexes is absent, sqlite3
401
- // exits non-zero and safeExec returns empty -- hasHnsw stays false (exact
402
- // original semantics: at least one index-config row present).
403
- const hnswSql = Q + 'SELECT COUNT(*) FROM vector_indexes;' + Q;
404
- const hn = safeExec("sqlite3 'file:" + memDb + "?mode=ro' " + hnswSql, 1500);
405
- if (hn) result.hasHnsw = (parseInt(hn, 10) || 0) > 0;
406
- }
407
- } catch { /* ignore */ }
408
- return result;
409
- }
410
-
411
- // Count test files via a bounded directory walk (no file reads).
412
- function getLocalTests() {
413
- let testFiles = 0;
414
- function countTests(dir, depth) {
415
- if ((depth || 0) > 4) return;
416
- try {
417
- if (!fs.existsSync(dir)) return;
418
- for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
419
- if (e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules') {
420
- countTests(path.join(dir, e.name), (depth || 0) + 1);
421
- } else if (e.isFile() && (e.name.includes('.test.') || e.name.includes('.spec.') || e.name.startsWith('test_') || e.name.startsWith('spec_'))) {
422
- testFiles++;
423
- }
424
- }
425
- } catch { /* ignore */ }
426
- }
427
- for (const d of ['tests', 'test', '__tests__', 'src', 'v3']) countTests(path.join(CWD, d));
428
- return { testFiles, testCases: testFiles * 4 };
429
- }
430
-
431
- // Count configured hooks from project .claude/settings.json. Claude Code hooks
432
- // have no enabled/disabled flag, so every configured hook counts as enabled.
433
- function getLocalHooks() {
434
- const result = { enabled: 0, total: 0 };
435
- try {
436
- const settings = readJSON(path.join(CWD, '.claude', 'settings.json'));
437
- const hooks = settings && settings.hooks;
438
- if (hooks && typeof hooks === 'object') {
439
- let n = 0;
440
- for (const ev of Object.keys(hooks)) {
441
- const groups = hooks[ev];
442
- if (Array.isArray(groups)) {
443
- for (const g of groups) {
444
- if (g && Array.isArray(g.hooks)) n += g.hooks.length;
445
- }
446
- }
447
- }
448
- result.total = n;
449
- result.enabled = n;
450
- }
451
- } catch { /* ignore */ }
452
- return result;
453
- }
454
-
455
- // Best-effort integration block: DB presence + locally-configured stdio MCP
456
- // servers (project .mcp.json + global ~/.claude.json). Remote connectors are
457
- // account-managed and not present in local config, so they are not counted.
458
- function getLocalIntegration() {
459
- const integration = { mcpServers: { enabled: 0, total: 0 }, hasDatabase: false };
460
- try {
461
- for (const f of ['.swarm/memory.db', 'ruvector.db']) {
462
- if (fs.existsSync(path.join(CWD, f))) { integration.hasDatabase = true; break; }
463
- }
464
- const names = new Set();
465
- const projMcp = readJSON(path.join(CWD, '.mcp.json'));
466
- if (projMcp && projMcp.mcpServers) for (const k of Object.keys(projMcp.mcpServers)) names.add(k);
467
- const claudeJson = readJSON(path.join(os.homedir(), '.claude.json'));
468
- if (claudeJson) {
469
- if (claudeJson.mcpServers) for (const k of Object.keys(claudeJson.mcpServers)) names.add(k);
470
- const proj = claudeJson.projects && claudeJson.projects[CWD];
471
- if (proj && proj.mcpServers && !Array.isArray(proj.mcpServers)) {
472
- for (const k of Object.keys(proj.mcpServers)) names.add(k);
473
- }
474
- }
475
- integration.mcpServers.total = names.size;
476
- integration.mcpServers.enabled = names.size;
477
- } catch { /* ignore */ }
478
- return integration;
479
- }
480
-
481
- // Overlay every locally-derived block onto the CLI data (mutates in place).
482
- function applyLocalOverlays(data) {
483
- data.adrs = getLocalADRCount();
484
- data.agentdb = getLocalAgentDB();
485
- data.tests = getLocalTests();
486
- data.hooks = getLocalHooks();
487
- data.integration = getLocalIntegration();
488
- return data;
489
- }
490
-
491
- // Minimal local fallback when the CLI is not installed or times out.
492
- // Returns a structure that matches the CLI JSON schema so the renderer works.
493
- function buildLocalFallback() {
494
- const memMB = Math.floor(process.memoryUsage().heapUsed / 1024 / 1024);
495
-
496
- return applyLocalOverlays({
497
- user: { name: 'user', gitBranch: '', modelName: 'Claude Code' },
498
- v3Progress: { domainsCompleted: 0, totalDomains: 5, dddProgress: 0, patternsLearned: 0, sessionsCompleted: 0 },
499
- security: { status: 'NONE', cvesFixed: 0, totalCves: 0 },
500
- swarm: { activeAgents: 0, maxAgents: CONFIG.maxAgents, coordinationActive: false },
501
- system: { memoryMB: memMB, contextPct: 0, intelligencePct: 0, subAgents: 0 },
502
- lastUpdated: new Date().toISOString(),
503
- });
504
- }
505
-
506
- // ANSI colors
507
- const c = {
508
- reset: '\\x1b[0m',
509
- bold: '\\x1b[1m',
510
- dim: '\\x1b[2m',
511
- red: '\\x1b[0;31m',
512
- green: '\\x1b[0;32m',
513
- yellow: '\\x1b[0;33m',
514
- blue: '\\x1b[0;34m',
515
- purple: '\\x1b[0;35m',
516
- cyan: '\\x1b[0;36m',
517
- brightRed: '\\x1b[1;31m',
518
- brightGreen: '\\x1b[1;32m',
519
- brightYellow: '\\x1b[1;33m',
520
- brightBlue: '\\x1b[1;34m',
521
- brightPurple: '\\x1b[1;35m',
522
- brightCyan: '\\x1b[1;36m',
523
- brightWhite: '\\x1b[1;37m',
524
- };
525
-
526
- // Safe execSync with strict timeout (returns empty string on failure)
527
- function safeExec(cmd, timeoutMs) {
528
- try {
529
- return execSync(cmd, {
530
- encoding: 'utf-8',
531
- timeout: timeoutMs || 2000,
532
- stdio: ['pipe', 'pipe', 'pipe'],
533
- }).trim();
534
- } catch {
535
- return '';
536
- }
537
- }
538
-
539
- // Safe JSON file reader (returns null on failure)
540
- function readJSON(filePath) {
541
- try {
542
- if (fs.existsSync(filePath)) {
543
- return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
544
- }
545
- } catch { /* ignore */ }
546
- return null;
547
- }
548
-
549
- // ─── Git info (pure-Node / single exec — needed for branch display) ──────────
550
-
551
- function getGitInfo() {
552
- const result = {
553
- name: 'user', gitBranch: '', modified: 0, untracked: 0,
554
- staged: 0, ahead: 0, behind: 0,
555
- };
556
-
557
- const script = [
558
- 'git config user.name 2>/dev/null || echo user',
559
- 'echo "---SEP---"',
560
- 'git branch --show-current 2>/dev/null',
561
- 'echo "---SEP---"',
562
- 'git status --porcelain 2>/dev/null',
563
- 'echo "---SEP---"',
564
- 'git rev-list --left-right --count HEAD...@{upstream} 2>/dev/null || echo "0 0"',
565
- ].join('; ');
566
-
567
- const raw = safeExec("sh -c '" + script + "'", 3000);
568
- if (!raw) return result;
569
-
570
- const parts = raw.split('---SEP---').map(function(s) { return s.trim(); });
571
- if (parts.length >= 4) {
572
- result.name = parts[0] || 'user';
573
- result.gitBranch = parts[1] || '';
574
-
575
- if (parts[2]) {
576
- for (const line of parts[2].split('\\n')) {
577
- if (!line || line.length < 2) continue;
578
- const x = line[0], y = line[1];
579
- if (x === '?' && y === '?') { result.untracked++; continue; }
580
- if (x !== ' ' && x !== '?') result.staged++;
581
- if (y !== ' ' && y !== '?') result.modified++;
582
- }
583
- }
584
-
585
- const ab = (parts[3] || '0 0').split(/\\s+/);
586
- result.ahead = parseInt(ab[0]) || 0;
587
- result.behind = parseInt(ab[1]) || 0;
588
- }
589
-
590
- return result;
591
- }
592
-
593
- // Detect model name from Claude config (pure file reads, no exec)
594
- function getModelName() {
595
- try {
596
- const claudeConfig = readJSON(path.join(os.homedir(), '.claude.json'));
597
- if (claudeConfig && claudeConfig.projects) {
598
- for (const [projectPath, projectConfig] of Object.entries(claudeConfig.projects)) {
599
- if (CWD === projectPath || CWD.startsWith(projectPath + '/')) {
600
- const usage = projectConfig.lastModelUsage;
601
- if (usage) {
602
- const ids = Object.keys(usage);
603
- if (ids.length > 0) {
604
- let modelId = ids[ids.length - 1];
605
- let latest = 0;
606
- for (const id of ids) {
607
- const ts = usage[id] && usage[id].lastUsedAt ? new Date(usage[id].lastUsedAt).getTime() : 0;
608
- if (ts > latest) { latest = ts; modelId = id; }
609
- }
610
- if (modelId.includes('opus')) return 'Opus 4.8';
611
- if (modelId.includes('sonnet')) return 'Sonnet 4.6';
612
- if (modelId.includes('haiku')) return 'Haiku 4.5';
613
- return modelId.split('-').slice(1, 3).join(' ');
614
- }
615
- }
616
- break;
617
- }
618
- }
619
- }
620
- } catch { /* ignore */ }
621
-
622
- // Fallback: settings.json model field
623
- const settings = getSettings();
624
- if (settings && settings.model) {
625
- const m = settings.model;
626
- if (m.includes('opus')) return 'Opus 4.8';
627
- if (m.includes('sonnet')) return 'Sonnet 4.6';
628
- if (m.includes('haiku')) return 'Haiku 4.5';
629
- }
630
- return 'Claude Code';
631
- }
632
-
633
- // ─── Stdin reader (Claude Code pipes session JSON) ──────────────
634
- // Claude Code sends session JSON via stdin. Read synchronously so the
635
- // script works both when invoked by Claude Code (stdin has JSON) and
636
- // when run manually from terminal (stdin is empty/tty).
637
- let _stdinData = null;
638
- function getStdinData() {
639
- if (_stdinData !== undefined && _stdinData !== null) return _stdinData;
640
- try {
641
- if (process.stdin.isTTY) { _stdinData = null; return null; }
642
- const chunks = [];
643
- const buf = Buffer.alloc(4096);
644
- let bytesRead;
645
- try {
646
- while ((bytesRead = fs.readSync(0, buf, 0, buf.length, null)) > 0) {
647
- chunks.push(buf.slice(0, bytesRead));
648
- }
649
- } catch { /* EOF or read error */ }
650
- const raw = Buffer.concat(chunks).toString('utf-8').trim();
651
- _stdinData = (raw && raw.startsWith('{')) ? JSON.parse(raw) : null;
652
- } catch {
653
- _stdinData = null;
654
- }
655
- return _stdinData;
656
- }
657
-
658
- function getModelFromStdin() {
659
- const data = getStdinData();
660
- return (data && data.model && data.model.display_name) ? data.model.display_name : null;
661
- }
662
-
663
- function getContextFromStdin() {
664
- const data = getStdinData();
665
- if (data && data.context_window) {
666
- return { usedPct: Math.floor(data.context_window.used_percentage || 0) };
667
- }
668
- return null;
669
- }
670
-
671
- function getCostFromStdin() {
672
- const data = getStdinData();
673
- if (data && data.cost) {
674
- const durationMs = data.cost.total_duration_ms || 0;
675
- const mins = Math.floor(durationMs / 60000);
676
- const secs = Math.floor((durationMs % 60000) / 1000);
677
- return {
678
- costUsd: data.cost.total_cost_usd || 0,
679
- duration: mins > 0 ? mins + 'm' + secs + 's' : secs + 's',
680
- };
681
- }
682
- return null;
683
- }
684
-
685
- // Compares dotted-numeric version strings (e.g. "3.27.1" vs "3.27.10").
686
- // Returns >0 if a>b, <0 if a<b, 0 if equal-as-far-as-parseable. Deliberately
687
- // simple (no prerelease/build-metadata handling) — this only orders local
688
- // package.json versions against each other, never anything untrusted from
689
- // a payload, so a full semver implementation would be dead weight here.
690
- function compareVersions(a, b) {
691
- const pa = String(a).split('.').map((n) => parseInt(n, 10));
692
- const pb = String(b).split('.').map((n) => parseInt(n, 10));
693
- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
694
- const na = Number.isFinite(pa[i]) ? pa[i] : 0;
695
- const nb = Number.isFinite(pb[i]) ? pb[i] : 0;
696
- if (na !== nb) return na - nb;
697
- }
698
- return 0;
699
- }
700
-
701
- function getPkgVersion() {
702
- // Baked in at generation time from the real running CLI's own resolved
703
- // version (see generateStatuslineScript()'s doc comment) — correct even
704
- // when this renders via a pure npx invocation with no local install for
705
- // the candidate scan below to find.
706
- let ver = ${JSON.stringify(bakedVersion)};
707
- try {
708
- const home = os.homedir();
709
- const pkgPaths = [
710
- path.join(home, '.claude', 'plugins', 'marketplaces', 'ruflo', 'package.json'),
711
- path.join(CWD, 'node_modules', '@claude-flow', 'cli', 'package.json'),
712
- path.join(CWD, 'node_modules', 'ruflo', 'package.json'),
713
- path.join(CWD, 'v3', '@claude-flow', 'cli', 'package.json'),
714
- ];
715
- // #2221: global installs (npm i -g ruflo) live outside CWD/node_modules, so the
716
- // probes above all miss and the version falls back to the hard-coded default.
717
- // Derive the global node_modules dir from the running node binary (no npm spawn —
718
- // statusline renders often). Covers nvm/mise (bin/../lib/node_modules) and Windows
719
- // (bin/node_modules) layouts.
720
- try {
721
- const binDir = path.dirname(process.execPath);
722
- const globalModuleDirs = [path.join(binDir, '..', 'lib', 'node_modules'), path.join(binDir, 'node_modules')];
723
- // #2221 follow-up: a custom npm prefix (e.g. ~/.npm-global) is decoupled from
724
- // the node binary location, so the binDir-derived probes above all miss. Also
725
- // probe the npm prefix from the environment and the common ~/.npm-global default.
726
- for (const prefix of [process.env.npm_config_prefix, process.env.PREFIX, path.join(home, '.npm-global')]) {
727
- if (prefix) globalModuleDirs.push(path.join(prefix, 'lib', 'node_modules'));
728
- }
729
- for (const gm of globalModuleDirs) {
730
- pkgPaths.push(
731
- path.join(gm, 'ruflo', 'package.json'),
732
- path.join(gm, '@claude-flow', 'cli', 'package.json'),
733
- );
734
- }
735
- } catch { /* ignore */ }
736
- // Pick the HIGHEST version among every candidate that exists, not the
737
- // first one found. The marketplace plugin path is probed first (list
738
- // order above), but Claude Code's own plugin marketplace mechanism
739
- // syncs on its own git-pull cadence, independent of npm publishes — a
740
- // freshly-published npm version can sit alongside a stale marketplace
741
- // checkout for a while (observed live: marketplace one release behind
742
- // right after a publish). Taking the first EXISTING candidate meant the
743
- // header could show a stale version even when a newer install (e.g.
744
- // node_modules/@claude-flow/cli from a plain npm install) was sitting right there.
745
- let found = false;
746
- for (const p of pkgPaths) {
747
- if (!fs.existsSync(p)) continue;
748
- try {
749
- const pkg = JSON.parse(fs.readFileSync(p, 'utf-8'));
750
- if (pkg && typeof pkg.version === 'string' && pkg.version.length > 0) {
751
- if (!found || compareVersions(pkg.version, ver) > 0) ver = pkg.version;
752
- found = true;
753
- }
754
- } catch { /* ignore */ }
755
- }
756
- } catch { /* ignore */ }
757
- return ver;
758
- }
759
-
760
- // ─── Rendering ──────────────────────────────────────────────────
761
-
762
- function progressBar(current, total) {
763
- const width = 5;
764
- const filled = Math.round((current / total) * width);
765
- return '[' + '●'.repeat(filled) + '○'.repeat(width - filled) + ']';
766
- }
767
-
768
- function generateStatusline() {
769
- const d = getStatuslineData();
770
- const git = getGitInfo();
771
- const modelName = getModelFromStdin() || (d.user && d.user.modelName) || 'Claude Code';
772
- const ctxInfo = getContextFromStdin();
773
- const costInfo = getCostFromStdin();
774
- // Named RUFLO_VERSION (not pkgVersion) so the #1951 regression guard
775
- // (scripts/audit-fix-invariants.mjs) can pin its presence in the emitted
776
- // .cjs artifact — without it the header silently reverts to a hard-coded
777
- // "RuFlo V3.5" for anyone whose install doesn't match the first probe path.
778
- const RUFLO_VERSION = getPkgVersion();
779
-
780
- const progress = d.v3Progress || {};
781
- const security = d.security || {};
782
- const swarm = d.swarm || {};
783
- const system = d.system || {};
784
- const adrs = d.adrs || {};
785
- const hooks = d.hooks || {};
786
- const agentdb = d.agentdb || {};
787
- const tests = d.tests || {};
788
-
789
- const domainsCompleted = progress.domainsCompleted || 0;
790
- const totalDomains = progress.totalDomains || 5;
791
- const dddProgress = progress.dddProgress || 0;
792
- const patternsLearned = progress.patternsLearned || 0;
793
- const activeAgents = swarm.activeAgents || 0;
794
- const maxAgents = swarm.maxAgents || CONFIG.maxAgents;
795
- const coordinationActive = swarm.coordinationActive || false;
796
- const intelligencePct = system.intelligencePct || 0;
797
- const memoryMB = system.memoryMB || 0;
798
- const subAgents = system.subAgents || 0;
799
- const cvesFixed = security.cvesFixed || 0;
800
- const totalCves = security.totalCves || 0;
801
- const secStatus = security.status || 'NONE';
802
- const adrCount = adrs.count || 0;
803
- const adrImpl = adrs.implemented || 0;
804
- const hooksEnabled = hooks.enabled || 0;
805
- const hooksTotal = hooks.total || 0;
806
- const vectorCount = agentdb.vectorCount || 0;
807
- const hasHnsw = agentdb.hasHnsw || false;
808
- const dbSizeKB = agentdb.dbSizeKB || 0;
809
- const testFiles = tests.testFiles || 0;
810
- const testCases = tests.testCases || testFiles * 4;
811
-
812
- const lines = [];
813
-
814
- // 3-line design (fits Claude Code's visible statusline area — line 4+ gets
815
- // replaced by the system guidance / input prompt line):
816
- // Line 1 — Header (RuFlo version · git · model · timing · context · cost)
817
- // Line 2 — Compressed ops (Swarm · Hooks · 🧠 · 💾 · Health)
818
- // Line 3 — Promo / disclosure row (funnel surface, ADR-301)
819
-
820
- // ─── Line 1: header ────────────────────────────────────────────
821
- let header = c.bold + c.brightPurple + '▊ RuFlo V' + RUFLO_VERSION + ' ' + c.reset;
822
- header += (coordinationActive ? c.brightCyan : c.dim) + '● ' + c.brightCyan + git.name + c.reset;
823
- if (git.gitBranch) {
824
- header += ' ' + c.dim + '│' + c.reset + ' ' + c.brightBlue + '⏇ ' + git.gitBranch + c.reset;
825
- const changes = git.modified + git.staged + git.untracked;
826
- if (changes > 0) {
827
- let ind = '';
828
- if (git.staged > 0) ind += c.brightGreen + '+' + git.staged + c.reset;
829
- if (git.modified > 0) ind += c.brightYellow + '~' + git.modified + c.reset;
830
- if (git.untracked > 0) ind += c.dim + '?' + git.untracked + c.reset;
831
- header += ' ' + ind;
832
- }
833
- if (git.ahead > 0) header += ' ' + c.brightGreen + '↑' + git.ahead + c.reset;
834
- if (git.behind > 0) header += ' ' + c.brightRed + '↓' + git.behind + c.reset;
835
- }
836
- header += ' ' + c.dim + '│' + c.reset + ' ' + c.purple + modelName + c.reset;
837
- const duration = costInfo ? costInfo.duration : '';
838
- if (duration) header += ' ' + c.dim + '│' + c.reset + ' ' + c.cyan + '⏱ ' + duration + c.reset;
839
- if (ctxInfo && ctxInfo.usedPct > 0) {
840
- const ctxColor = ctxInfo.usedPct >= 90 ? c.brightRed : ctxInfo.usedPct >= 70 ? c.brightYellow : c.brightGreen;
841
- header += ' ' + c.dim + '│' + c.reset + ' ' + ctxColor + '● ' + ctxInfo.usedPct + '% ctx' + c.reset;
842
- }
843
- if (!CONFIG.hideCost && costInfo && costInfo.costUsd > 0) {
844
- header += ' ' + c.dim + '│' + c.reset + ' ' + c.brightYellow + CONFIG.costSymbol + costInfo.costUsd.toFixed(2) + c.reset;
845
- }
846
- lines.push(header);
847
-
848
- // ─── Line 2: compressed ops ────────────────────────────────────
849
- // Everything actionable in one dense row. Show only what changes what you
850
- // do next; diagnostic detail moves to \`ruflo status --verbose\`.
851
- const agentsColor = activeAgents > 0 ? c.brightGreen : c.dim;
852
- const hooksColor = hooksEnabled > 0 ? c.brightGreen : c.dim;
853
- const intellColor = intelligencePct >= 80 ? c.brightGreen : intelligencePct >= 40 ? c.brightYellow : c.dim;
854
- const swarmInd = coordinationActive ? c.brightGreen + '◉' + c.reset + ' ' : c.dim + '○' + c.reset + ' ';
855
- const cvesClean = totalCves === 0 || cvesFixed === totalCves;
856
- const healthAllGreen = (secStatus === 'CLEAN' || secStatus === 'NONE') && cvesClean;
857
- const opsParts = [];
858
- opsParts.push(c.cyan + 'Swarm ' + swarmInd + agentsColor + activeAgents + c.reset + '/' + c.brightWhite + maxAgents + c.reset);
859
- if (subAgents > 0) opsParts.push(c.brightPurple + '👥 ' + subAgents + c.reset);
860
- opsParts.push(c.cyan + 'Hooks ' + hooksColor + hooksEnabled + c.reset + '/' + c.brightWhite + hooksTotal + c.reset);
861
- opsParts.push(intellColor + '🧠 ' + intelligencePct + '%' + c.reset);
862
- opsParts.push(c.brightCyan + '💾 ' + memoryMB + 'MB' + c.reset);
863
- // Health: one glyph when green, terse copy when there's something to act on.
864
- if (healthAllGreen) {
865
- opsParts.push(c.brightGreen + '🛡 ✓' + c.reset);
866
- } else {
867
- if (secStatus === 'PENDING') opsParts.push(c.brightYellow + '🛡 scan pending' + c.reset);
868
- else if (secStatus === 'IN_PROGRESS') opsParts.push(c.brightYellow + '🛡 scanning…' + c.reset);
869
- else if (secStatus === 'STALE') opsParts.push(c.brightYellow + '🛡 scan stale' + c.reset);
870
- else if (secStatus !== 'NONE' && secStatus !== 'CLEAN') opsParts.push(c.brightRed + '🛡 ' + secStatus.toLowerCase() + c.reset);
871
- if (totalCves > 0 && cvesFixed < totalCves) {
872
- const unfixed = totalCves - cvesFixed;
873
- opsParts.push(c.brightRed + '⚠ ' + unfixed + ' CVE' + (unfixed === 1 ? '' : 's') + c.reset);
874
- }
875
- }
876
- lines.push(opsParts.join(' ' + c.dim + '·' + c.reset + ' '));
877
-
878
- // ─── Line 3: promo / disclosure / insight ───────────────────────
879
- // Colored by content kind so it reads as *what it is*, not as noise:
880
- // disclosure → brightCyan (announcement / capability link)
881
- // promotional → brightPurple (Cognitum sponsor spot)
882
- // educational → yellow (a tip)
883
- // insight → brightRed (environment/task-aware, local, actionable —
884
- // distinct from remote content on purpose)
885
- const promoRow = getPromoRow(d);
886
- if (promoRow) {
887
- const kind = (d && d.promo && d.promo.kind) || 'disclosure';
888
- const promoColor = kind === 'promotional' ? c.brightPurple
889
- : kind === 'educational' ? c.yellow
890
- : kind === 'insight' ? c.brightRed
891
- : c.brightCyan;
892
- lines.push(promoColor + promoRow + c.reset);
893
- }
894
-
895
- // Trailing blank line so Claude Code's input prompt gets breathing room
896
- // instead of butting directly against the last statusline row.
897
- return lines.join('\\n') + '\\n';
898
- }
899
-
900
- // ─── Funnel promo row (ADR-301) ─────────────────────────────────
901
- // Allowlist for OSC 8 hyperlink targets. Ships in code (not in payload) so
902
- // no message can smuggle a link to an unapproved host.
903
- //
904
- // The final destination hosts (cognitum.one / agentics.org) AND the
905
- // click-redirect host are both allowlisted here: promo.ts routes every
906
- // clickable message through the server-side click-redirect (ADR-311 §7)
907
- // so promo_open + geo are captured before the 302 to the real target —
908
- // so the OSC 8 link the renderer emits points at the redirect host, not
909
- // the final destination directly.
910
- const PROMO_LINK_HOSTS = new Set([
911
- 'cognitum.one', 'www.cognitum.one', 'docs.cognitum.one',
912
- // agentics.org — OSS foundation, distinct sponsor domain. Kept in sync
913
- // with messages.ts ALLOWED_URL_HOSTS.
914
- 'agentics.org', 'www.agentics.org',
915
- // Click-redirect host (funnel.ruv.io once its TLS cert is live; the raw
916
- // Cloud Run hostname is allowlisted too since event-transport.ts /
917
- // message-transport.ts / attribution.ts currently point at it as a TEMP
918
- // fallback while the domain mapping's cert provisions).
919
- 'funnel.ruv.io',
920
- 'cognitum-analytics-63rzcdswba-uc.a.run.app',
921
- ]);
922
-
923
- // Emit OSC 8 hyperlinks unless the environment is known-broken. tmux mangles
924
- // raw OSC 8 (see anthropics/claude-code#27047) — opt in via env if wrapped.
925
- function terminalSupportsHyperlinks() {
926
- if (process.env.CI || process.env.GITHUB_ACTIONS) return false;
927
- if (process.env.TERM === 'dumb') return false;
928
- if (/^(0|false|off|no)$/i.test(String(process.env.RUFLO_STATUSLINE_HYPERLINKS || ''))) return false;
929
- if (process.env.TMUX && !process.env.RUFLO_STATUSLINE_HYPERLINKS_TMUX) return false;
930
- return true;
931
- }
932
-
933
- // Wrap a label in an OSC 8 hyperlink escape sequence. Falls back to the raw
934
- // label whenever the URL is not an allowlisted https target, when the terminal
935
- // can't render hyperlinks, or when parsing fails — a broken link must never
936
- // leave a raw URL or stray escape in the statusline output.
937
- function safeTerminalLink(label, url) {
938
- if (!terminalSupportsHyperlinks()) return label;
939
- if (typeof url !== 'string' || url.length === 0) return label;
940
- let parsed;
941
- try { parsed = new URL(url); } catch { return label; }
942
- if (parsed.protocol !== 'https:') return label;
943
- if (!PROMO_LINK_HOSTS.has(parsed.hostname)) return label;
944
- const cleanLabel = String(label).replace(/[\\u0000-\\u001f\\u007f-\\u009f\\u202a-\\u202e\\u2066-\\u2069]/g, '');
945
- if (cleanLabel.length === 0) return label;
946
- const ESC = '\\u001b';
947
- return ESC + ']8;;' + parsed.href + ESC + '\\\\' + cleanLabel + ESC + ']8;;' + ESC + '\\\\';
948
- }
949
-
950
- function getPromoRow(d) {
951
- try {
952
- if (process.env.CI || process.env.GITHUB_ACTIONS) return null;
953
- if (/^(0|false|off|no)$/i.test(String(process.env.RUFLO_FUNNEL || ''))) return null;
954
- const promo = d && d.promo;
955
- if (!promo || typeof promo.text !== 'string') return null;
956
- // Strip control chars / ANSI / bidi overrides and hard-cap length —
957
- // promo copy is data and must never emit its own terminal sequences.
958
- const text = promo.text
959
- .replace(/[\\u0000-\\u001f\\u007f-\\u009f\\u202a-\\u202e\\u2066-\\u2069]/g, '')
960
- .slice(0, 100)
961
- .trim();
962
- if (text.length === 0) return null;
963
- // Split the label from the trailing "· manage: ruflo settings" instruction
964
- // so each part gets styling that matches what it actually IS:
965
- // 1. label — OSC 8 hyperlink + underline. A real clickable link.
966
- // 2. "manage:" — dim. Just a connector word, no action implied.
967
- // 3. "ruflo settings" — bold/bright, NOT underlined. This is a shell
968
- // command the user TYPES, not a link they CLICK — a terminal can
969
- // never safely execute a command from a click (that would let any
970
- // server-served message run arbitrary commands), so we deliberately
971
- // avoid the underline/OSC8 cues that imply "clickable". Bold+bright
972
- // instead signals "this is the important bit — copy/type it".
973
- // Educational tips have no manage tail and no URL — plain text through.
974
- const manageIdx = text.indexOf(' · manage: ');
975
- const label = manageIdx > 0 ? text.slice(0, manageIdx) : text;
976
- const manageWord = manageIdx > 0 ? ' · manage: ' : '';
977
- const command = manageIdx > 0 ? text.slice(manageIdx + manageWord.length) : '';
978
- const UL_ON = '\\u001b[4m';
979
- const UL_OFF = '\\u001b[24m';
980
- const DIM_ON = '\\u001b[2m';
981
- const DIM_OFF = '\\u001b[22m';
982
- const BOLD_ON = '\\u001b[1m';
983
- const BOLD_OFF = '\\u001b[22m';
984
- const linked = promo.url ? UL_ON + safeTerminalLink(label, promo.url) + UL_OFF : label;
985
- if (!command) return linked;
986
- return linked + DIM_ON + manageWord + DIM_OFF + BOLD_ON + command + BOLD_OFF;
987
- } catch (e) {
988
- return null; // the promo row must never break the statusline
989
- }
990
- }
991
-
992
- // JSON output — delegates to CLI for accuracy; caller can use --json flag
993
- function generateJSON() {
994
- const d = getStatuslineData();
995
- const git = getGitInfo();
996
- return Object.assign({}, d, {
997
- user: Object.assign({ name: git.name, gitBranch: git.gitBranch }, d.user || {}),
998
- git: { modified: git.modified, untracked: git.untracked, staged: git.staged, ahead: git.ahead, behind: git.behind },
999
- lastUpdated: new Date().toISOString(),
1000
- });
1001
- }
1002
-
1003
- // ─── Main ───────────────────────────────────────────────────────
1004
- if (process.argv.includes('--json')) {
1005
- console.log(JSON.stringify(generateJSON(), null, 2));
1006
- } else if (process.argv.includes('--compact')) {
1007
- console.log(JSON.stringify(generateJSON()));
1008
- } else {
1009
- console.log(generateStatusline());
1010
- }
1011
- `;
80
+ // #2679 fix: read the committed .claude/helpers/statusline.cjs as the
81
+ // single source of truth instead of maintaining a 1000-line template
82
+ // string inline. Prior to this fix, the inline template drifted from
83
+ // the deployed helper (v3.29.0 UX improvements — whole-row-clickable
84
+ // OSC 8, (domain) suffix, ellipsis, bright-white command, 300s cache
85
+ // TTL, windowsHide on subprocess spawns all shipped in the helper
86
+ // but the generator kept its older shape). Now: read the helper +
87
+ // substitute two known values (maxAgents, bakedVersion).
88
+ //
89
+ // Walk-up finds the CLI package root (whether we're at src/init/ in
90
+ // tests or dist/src/init/ in installed use). Same shape as
91
+ // getInstalledCliVersionLocal() above — reuse the pattern for the
92
+ // same reason it exists there.
93
+ let helperContent = null;
94
+ try {
95
+ const esmRequire = createRequire(import.meta.url);
96
+ const pkgJsonPath = esmRequire.resolve('@claude-flow/cli/package.json');
97
+ const helperPath = path.join(path.dirname(pkgJsonPath), '.claude', 'helpers', 'statusline.cjs');
98
+ helperContent = fs.readFileSync(helperPath, 'utf-8');
99
+ }
100
+ catch {
101
+ let dir = __dirname_sg;
102
+ for (let i = 0; i < 6; i++) {
103
+ try {
104
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf-8'));
105
+ if (pkg && pkg.name === '@claude-flow/cli') {
106
+ const candidate = path.join(dir, '.claude', 'helpers', 'statusline.cjs');
107
+ if (fs.existsSync(candidate)) {
108
+ helperContent = fs.readFileSync(candidate, 'utf-8');
109
+ break;
110
+ }
111
+ }
112
+ }
113
+ catch { /* keep climbing */ }
114
+ const parent = path.dirname(dir);
115
+ if (parent === dir)
116
+ break;
117
+ dir = parent;
118
+ }
119
+ }
120
+ if (helperContent === null) {
121
+ throw new Error('statusline-generator: could not locate .claude/helpers/statusline.cjs '
122
+ + 'relative to @claude-flow/cli. This is a packaging bug — the helper '
123
+ + 'must ship with the CLI (see package.json files entry for .claude).');
124
+ }
125
+ // Two known interpolation points both single-line, both idempotent
126
+ // string replacements. If a future edit to the helper renames either
127
+ // token, this replace() is a no-op and the fallback default (15,
128
+ // whatever the helper hard-codes) ships. Add a paired test in
129
+ // statusline-cost-display.test.ts before changing either token.
130
+ helperContent = helperContent.replace(/maxAgents: \d+,/, `maxAgents: ${maxAgents},`);
131
+ // Only overwrite the helper's baked version if OURS resolves higher.
132
+ // Otherwise the substitution could DOWNGRADE (test environments where
133
+ // esmRequire.resolve happens to hit an older node_modules install would
134
+ // clobber a fresh committed helper). Naive lexicographic compare — works
135
+ // for canonical semver strings with same-width digit parts, which is
136
+ // reliable at this stage of the version space.
137
+ const helperVerMatch = helperContent.match(/let ver = "([^"]+)";/);
138
+ const helperVer = helperVerMatch ? helperVerMatch[1] : '';
139
+ if (!helperVer || bakedVersion > helperVer) {
140
+ helperContent = helperContent.replace(/let ver = "[^"]+";/, `let ver = ${JSON.stringify(bakedVersion)};`);
141
+ }
142
+ return helperContent;
1012
143
  }
1013
144
  /**
1014
145
  * Generate statusline hook for shell integration
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@claude-flow/cli",
3
- "version": "3.30.0",
3
+ "version": "3.30.1",
4
4
  "type": "module",
5
5
  "description": "Ruflo CLI - Enterprise AI agent orchestration with 60+ specialized agents, swarm coordination, MCP server, self-learning hooks, and vector memory for Claude Code",
6
6
  "main": "dist/src/index.js",