π The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(#2679): sync statusline-generator with committed helper (read+substitute pattern) (#2680)
rUv30e41c23f31b
diff --git a/.github/workflows/v3-ci.yml b/.github/workflows/v3-ci.ymlindex 6704de772f..c3cf69c731 100644--- a/.github/workflows/v3-ci.yml+++ b/.github/workflows/v3-ci.yml@@ -2517,25 +2517,42 @@ jobs:- name: Guard 1 β static delegation contractshell: bashrun: |- echo "Checking that statusline-generator.ts delegates to 'hooks statusline --json'..."- grep -q "hooks statusline --json" v3/@claude-flow/cli/src/init/statusline-generator.ts \- || { echo "::error::statusline-generator.ts no longer delegates to 'hooks statusline --json' β regression of #2195"; exit 1; }- echo "ok: delegation pattern found"-- echo "Checking that the old fragile heuristics are NOT present..."+ # #2679: generator now READS .claude/helpers/statusline.cjs as its+ # single source of truth rather than duplicating the content in an+ # inline template. The delegation contract lives in the HELPER+ # file now β grep that instead. Also verify the generator still+ # reads it (i.e. the read-and-substitute pattern is intact) so a+ # future refactor can't silently break the delegation contract+ # by dropping the file read.+ HELPER=v3/@claude-flow/cli/.claude/helpers/statusline.cjs+ GEN=v3/@claude-flow/cli/src/init/statusline-generator.ts++ echo "Checking that the helper delegates to 'hooks statusline --json'..."+ grep -q "hooks statusline --json" "$HELPER" \+ || { echo "::error::$HELPER no longer delegates to 'hooks statusline --json' β regression of #2195"; exit 1; }+ echo "ok: delegation pattern found in helper"++ echo "Checking that the generator reads the helper (#2679 sync pattern)..."+ grep -q "statusline.cjs" "$GEN" \+ || { echo "::error::$GEN no longer references statusline.cjs β regression of #2679 read-and-substitute pattern"; exit 1; }+ grep -qE "readFileSync.*helperContent|helperContent.*readFileSync" "$GEN" \+ || { echo "::error::$GEN no longer reads helper via readFileSync β regression of #2679"; exit 1; }+ echo "ok: read-and-substitute pattern intact"++ echo "Checking that the old fragile heuristics are NOT present (in helper)..."# The buggy fallback computed domains from file-based pattern counts β# this produced domainsCompleted=0 when AgentDB had 26k+ patterns.- ! grep -q "getLearningStats\b" v3/@claude-flow/cli/src/init/statusline-generator.ts \- || { echo "::error::statusline-generator.ts still has getLearningStats (old local reader) β regression of #2195"; exit 1; }- ! grep -q "getV3Progress\b" v3/@claude-flow/cli/src/init/statusline-generator.ts \- || { echo "::error::statusline-generator.ts still has getV3Progress (old local reader) β regression of #2195"; exit 1; }+ ! grep -q "getLearningStats\b" "$HELPER" \+ || { echo "::error::$HELPER still has getLearningStats (old local reader) β regression of #2195"; exit 1; }+ ! grep -q "getV3Progress\b" "$HELPER" \+ || { echo "::error::$HELPER still has getV3Progress (old local reader) β regression of #2195"; exit 1; }echo "ok: old local-reader heuristics removed"echo "Checking that both ADR directories are counted..."- grep -q "v3/docs/adr" v3/@claude-flow/cli/src/init/statusline-generator.ts \- || { echo "::error::statusline-generator.ts missing v3/docs/adr ADR directory β regression of #2195 ADR-count bug"; exit 1; }- grep -q "v3/implementation/adrs" v3/@claude-flow/cli/src/init/statusline-generator.ts \- || { echo "::error::statusline-generator.ts missing v3/implementation/adrs ADR directory"; exit 1; }+ grep -q "v3/docs/adr" "$HELPER" \+ || { echo "::error::$HELPER missing v3/docs/adr ADR directory β regression of #2195 ADR-count bug"; exit 1; }+ grep -q "v3/implementation/adrs" "$HELPER" \+ || { echo "::error::$HELPER missing v3/implementation/adrs ADR directory"; exit 1; }echo "ok: both ADR directories present"- name: Setup pnpmdiff --git a/scripts/audit-fix-invariants.mjs b/scripts/audit-fix-invariants.mjsindex a9ed885ef7..a360559816 100755--- a/scripts/audit-fix-invariants.mjs+++ b/scripts/audit-fix-invariants.mjs@@ -117,12 +117,14 @@ const INVARIANTS = [regex: /['"]marketplaces['"]\s*,\s*['"]ruflo['"]/,why: 'Same plugin-install candidate in the root statusline copy.',},- {- issue: '#1951',- file: 'v3/@claude-flow/cli/src/init/statusline-generator.ts',- regex: /['"]marketplaces['"]\s*,\s*['"]ruflo['"]/,- why: 'Same plugin-install candidate in the init template that generates project-local statuslines.',- },+ // #2679 sync: the init template no longer inlines the statusline β+ // it reads .claude/helpers/statusline.cjs and substitutes. The+ // marketplaces/ruflo candidate path therefore lives in the helper+ // file (already covered by the two invariants above). Dropping this+ // entry since the invariant is now enforced by the paired+ // .claude/helpers/statusline.cjs + v3/@claude-flow/cli/.claude/helpers/+ // statusline.cjs invariants; the generator can't ship a copy without+ // that candidate because it doesn't ship a copy at all β it reads one.// #1953 β hooks_pretrain code-file budget + code-dir-first traversal{@@ -157,11 +159,26 @@ const INVARIANTS = [// (presence of the delegation pattern) catches it before the SQLite// magic-check would ever be relevant. See ruvnet/ruflo#2216 for the// user-deployed (pre-#2196) statusline still having the bug.+ // #2679 sync: statusline-generator no longer inlines the delegation+ // template as a big string β it now READS+ // .claude/helpers/statusline.cjs at generation time and interpolates+ // maxAgents + bakedVersion. The delegation contract therefore lives+ // in the HELPER file, not the generator. Two paired invariants:+ // 1. the helper must contain the delegation pattern (unchanged intent)+ // 2. the generator must still be reading the helper (so the pattern+ // actually reaches init output)+ // Splitting the check catches drift on either side of the sync.{issue: '#2196',- file: 'v3/@claude-flow/cli/src/init/statusline-generator.ts',+ file: 'v3/@claude-flow/cli/.claude/helpers/statusline.cjs',regex: /hooks[- ]statusline|hooksStatusline/,- why: 'Statusline-generator must delegate to hooks-statusline rather than re-implementing memory.db readers (#2195/#1989 supersession). Without delegation, the regenerated statusline.cjs goes back to raw-bytes reading which broke for encrypted RFE1 DBs.',+ why: 'Statusline helper must delegate to hooks-statusline rather than re-implementing memory.db readers (#2195/#1989 supersession). Without delegation, the shipped statusline.cjs goes back to raw-bytes reading which broke for encrypted RFE1 DBs. (Was previously checked in statusline-generator.ts; moved here per #2679 read-and-substitute refactor.)',+ },+ {+ issue: '#2679',+ file: 'v3/@claude-flow/cli/src/init/statusline-generator.ts',+ regex: /statusline\.cjs/,+ why: 'Generator must READ .claude/helpers/statusline.cjs as its single source of truth (see #2679). Removing this reference would silently regress the generator to whatever inline template shape existed at the time β the pre-#2195 non-delegation build in the prior history.',},// #1987 β memory stats uses persistent HNSW count from MCP tool, notdiff --git a/scripts/smoke-statusline-generator-delegation.mjs b/scripts/smoke-statusline-generator-delegation.mjsindex 6a55855331..378db61087 100644--- a/scripts/smoke-statusline-generator-delegation.mjs+++ b/scripts/smoke-statusline-generator-delegation.mjs@@ -26,6 +26,12 @@ import { tmpdir, homedir } from 'node:os';const REPO_ROOT = resolve(process.cwd());const GENERATOR_SRC = join(REPO_ROOT, 'v3/@claude-flow/cli/src/init/statusline-generator.ts');const GENERATOR_DIST = join(REPO_ROOT, 'v3/@claude-flow/cli/dist/src/init/statusline-generator.js');+// #2679: generator now reads .claude/helpers/statusline.cjs as its single+// source of truth (read-and-substitute pattern) instead of inlining a+// 1000-line template. Static-content contract lives in the HELPER now;+// the generator just needs to still be reading it. This constant is the+// source-of-truth helper used by the static-source contract below.+const HELPER_SRC = join(REPO_ROOT, 'v3/@claude-flow/cli/.claude/helpers/statusline.cjs');const CJS_PATH = join(tmpdir(), 'ruflo-smoke-statusline.cjs');let passed = 0;@@ -37,39 +43,61 @@ function fail(msg) { console.error(` FAIL: ${msg}`); failed++; }// βββ Layer 1: static source contract ββββββββββββββββββββββββββββconsole.log('\n[1/3] STATIC SOURCE CONTRACT');+// #2679: two paired checks β the HELPER carries the delegation content+// (since the generator now reads it verbatim), and the GENERATOR still+// reads the helper (so drift on either side is caught). Splitting the+// invariant across the two files means neither can silently regress.if (!existsSync(GENERATOR_SRC)) {fail(`generator source not found: ${GENERATOR_SRC}`);} else {- const src = readFileSync(GENERATOR_SRC, 'utf-8');+ const genSrc = readFileSync(GENERATOR_SRC, 'utf-8');++ if (genSrc.includes('statusline.cjs')) {+ pass('generator references statusline.cjs (#2679 read-and-substitute pattern)');+ } else {+ fail('generator does NOT reference statusline.cjs β #2679 sync pattern regressed; init would emit stale template');+ }++ if (/readFileSync[\s\S]{0,200}helperContent|helperContent[\s\S]{0,200}readFileSync/.test(genSrc)) {+ pass('generator reads helper via readFileSync (#2679)');+ } else {+ fail('generator no longer reads helper via readFileSync β #2679 sync mechanism broken');+ }+}++if (!existsSync(HELPER_SRC)) {+ fail(`helper source not found: ${HELPER_SRC}`);+} else {+ const src = readFileSync(HELPER_SRC, 'utf-8');if (src.includes('hooks statusline --json')) {- pass('generator delegates to hooks statusline --json');+ pass('helper delegates to hooks statusline --json');} else {- fail('generator does NOT contain delegation to hooks statusline --json (regression of #2195)');+ fail('helper does NOT contain delegation to hooks statusline --json (regression of #2195)');}if (!src.includes('getLearningStats')) {- pass('getLearningStats (old local reader) removed from generator');+ pass('getLearningStats (old local reader) removed from helper');} else {- fail('getLearningStats still present in generator β old fragile local reader NOT removed (#2195)');+ fail('getLearningStats still present in helper β old fragile local reader NOT removed (#2195)');}if (!src.includes('getV3Progress')) {- pass('getV3Progress (old local reader) removed from generator');+ pass('getV3Progress (old local reader) removed from helper');} else {- fail('getV3Progress still present in generator β old fragile local reader NOT removed (#2195)');+ fail('getV3Progress still present in helper β old fragile local reader NOT removed (#2195)');}if (src.includes("'v3', 'docs', 'adr'") || src.includes("v3/docs/adr")) {- pass('generator counts v3/docs/adr ADR directory');+ pass('helper counts v3/docs/adr ADR directory');} else {- fail('generator missing v3/docs/adr in ADR count β will undercount ADRs (#2195)');+ fail('helper missing v3/docs/adr in ADR count β will undercount ADRs (#2195)');}if (src.includes("'v3', 'implementation', 'adrs'") || src.includes("v3/implementation/adrs")) {- pass('generator counts v3/implementation/adrs ADR directory');+ pass('helper counts v3/implementation/adrs ADR directory');} else {- fail('generator missing v3/implementation/adrs in ADR count');+ fail('helper missing v3/implementation/adrs in ADR count');}}diff --git a/v3/@claude-flow/cli/.claude/helpers/.helpers-version b/v3/@claude-flow/cli/.claude/helpers/.helpers-versionindex 52ef0b37f4..fdcc4697cc 100644--- a/v3/@claude-flow/cli/.claude/helpers/.helpers-version+++ b/v3/@claude-flow/cli/.claude/helpers/.helpers-version@@ -1 +1 @@-3.25.6\ No newline at end of file+3.30.0\ No newline at end of filediff --git a/v3/@claude-flow/cli/.claude/helpers/helpers.manifest.json b/v3/@claude-flow/cli/.claude/helpers/helpers.manifest.jsonindex c5ca847b41..24ee1e5c77 100644--- a/v3/@claude-flow/cli/.claude/helpers/helpers.manifest.json+++ b/v3/@claude-flow/cli/.claude/helpers/helpers.manifest.json@@ -1,12 +1,13 @@{"manifest": {- "version": "3.23.0",+ "version": "3.30.0","files": {- "auto-memory-hook.mjs": "68be7e9a9eba7bf9c4e8a230db7bf61a243b965639f8504842799d6c6ca28762",- "hook-handler.cjs": "bc4d2d26823d49b3ab1dded2946b66369f1f67bd76b4c30dca9f3b6df3cca8f0",- "intelligence.cjs": "760cb82ed2000031abc1ac1fa90a014e7d91d93966e3aa4741b07ab7aff8d066"+ "auto-memory-hook.mjs": "e3e1033b24704992ddef6b31c7fa9dd7fcd9e1af7935dd77ef73402b916b31e6",+ "hook-handler.cjs": "dc926a1a585abac85941347894632a800a9c4394e99166726017643e5b3c5950",+ "intelligence.cjs": "5a55d979cb7ba5c8c4f27f3b2e6d686fbb1045d180023b803da672a37e05b915",+ "statusline.cjs": "7d7bdee732e1c75b863e409afb86ce0d712f4919245e990d806da6752015bffa"}},- "signature": "of5l9RP68iPcmcC5dckDv+KIOiENJKifWxYKwQTwAiXiyRNNZuMwQ8y8Bd8+wGviTRxIzBfSuxL1nuJ/rX3xDQ==",+ "signature": "qO6+PIo9cihYWK86U9waSWMTjEM5G/leQ17+BxysCKz4szKLiFfLM/oDK+mTArWiJ4QPkLMIbtSfw3X736/yBg==","algorithm": "ed25519"}diff --git a/v3/@claude-flow/cli/.claude/helpers/statusline.cjs b/v3/@claude-flow/cli/.claude/helpers/statusline.cjsindex 3ef0466fdb..ff1deb795d 100644--- a/v3/@claude-flow/cli/.claude/helpers/statusline.cjs+++ b/v3/@claude-flow/cli/.claude/helpers/statusline.cjs@@ -42,12 +42,18 @@ const CONFIG = {const CWD = process.cwd();// βββ Delegation cache βββββββββββββββββββββββββββββββββββββββββββ-// Cache the CLI JSON result for 60s so rapid prompt re-renders-// (Claude Code refreshes the statusline several times a second while-// streaming) don't re-invoke the CLI each time. #2337: bumped 10sβ60s-// because 10s was far too short for how often Claude Code re-renders.+// Cache the CLI JSON result so rapid prompt re-renders (Claude Code+// refreshes the statusline several times a second while streaming) don't+// re-invoke the CLI each time.+// #2337 bumped 10s β 60s.+// Followup for anthropics/claude-code#70200 (Windows console-flash bug β+// claude.exe spawns hook/statusline subprocesses without CREATE_NO_WINDOW,+// producing a visible cmd flash on every render): bumped 60s β 300s to+// reduce the flash rate 5x on Windows until the upstream fix ships.+// Tradeoff: stat/git counters update every 5min instead of every 1min;+// promo/insight row still rotates on its own tighter 20s promoFresh clock.const CACHE_FILE = path.join(os.tmpdir(), 'ruflo-statusline-cache-' + require('crypto').createHash('md5').update(CWD).digest('hex').slice(0, 8) + '.json');-const CACHE_TTL_MS = 60000;+const CACHE_TTL_MS = 300000;// The promo/insight row is designed to rotate on a 20s cadence (funnel/// rotation.ts's ROTATION_SLOT_MS / funnel/promo.ts's insight-slot check β@@ -229,7 +235,7 @@ function getStatuslineData() {try {const raw = execSync(cmd,- { encoding: 'utf-8', timeout: 8000, stdio: ['pipe', 'pipe', 'pipe'], cwd: CWD }+ { encoding: 'utf-8', timeout: 8000, stdio: ['pipe', 'pipe', 'pipe'], cwd: CWD, windowsHide: true }).trim();// The CLI may emit preamble lines before the JSON β find the first '{'.const jsonStart = raw.indexOf('{');@@ -445,6 +451,11 @@ function safeExec(cmd, timeoutMs) {encoding: 'utf-8',timeout: timeoutMs || 2000,stdio: ['pipe', 'pipe', 'pipe'],+ // Windows: without this, every execSync spawns cmd.exe /d /s /c which+ // flashes a visible console window every render (~1/min via the 60s+ // cache TTL). windowsHide runs the child in a hidden window instead.+ // No-op on POSIX. Fix for #2XXX (user report: "cmd prompt keeps opening").+ windowsHide: true,}).trim();} catch {return '';@@ -868,12 +879,16 @@ function getPromoRow(d) {if (/^(0|false|off|no)$/i.test(String(process.env.RUFLO_FUNNEL || ''))) return null;const promo = d && d.promo;if (!promo || typeof promo.text !== 'string') return null;- // Strip control chars / ANSI / bidi overrides and hard-cap length β- // promo copy is data and must never emit its own terminal sequences.- const text = promo.text+ // Strip control chars / ANSI / bidi overrides β promo copy is data and+ // must never emit its own terminal sequences. Hard-cap length AFTER the+ // strip; append an ellipsis when the cap fires so the row visibly reads+ // as truncated instead of chopping a word mid-character (was: silent+ // slice(0,100) that could produce output that looked like corrupt data).+ const MAX_LEN = 100;+ const sanitized = promo.text.replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, '')- .slice(0, 100)- .trim();+ ;+ const text = (sanitized.length > MAX_LEN ? sanitized.slice(0, MAX_LEN - 1).trimEnd() + 'β¦' : sanitized).trim();if (text.length === 0) return null;// Split the label from the trailing "Β· manage: ruflo settings" instruction// so each part gets styling that matches what it actually IS:@@ -896,9 +911,68 @@ function getPromoRow(d) {const DIM_OFF = '\u001b[22m';const BOLD_ON = '\u001b[1m';const BOLD_OFF = '\u001b[22m';- const linked = promo.url ? UL_ON + safeTerminalLink(label, promo.url) + UL_OFF : label;- if (!command) return linked;- return linked + DIM_ON + manageWord + DIM_OFF + BOLD_ON + command + BOLD_OFF;+ const FG_BRIGHT_WHITE = '[97m';+ // Reset FG to default so the caller's row-color code resumes coloring the+ // rest of the row after the command portion. Without this the row-color+ // escape wouldn't visibly re-apply because we already emitted an explicit FG.+ const FG_DEFAULT = '[39m';+ // Some hosts (Claude Code's Windows UI, cmd.exe, older mintty) don't+ // render OSC 8 hyperlinks as clickable β the label just underlines and+ // clicks do nothing. Append a "(domain)" suffix so the destination is+ // visible/copyable everywhere. Wrap the suffix in OSC 8 too so terminals+ // that DO support hyperlinks give users TWO click targets (label AND+ // domain hint) instead of one β some Windows hosts render one but not+ // the other depending on how the statusline row is parsed.+ // Only for URLs (not educational tips), and only when the label doesn't+ // already end in the domain to avoid duplication.+ let visibleUrlHint = '';+ if (promo.url) {+ try {+ const host = new URL(promo.url).hostname.replace(/^www\./, '');+ // Strip the click-redirect wrapper so users see the FINAL destination,+ // not funnel.ruv.io. If the URL is /v1/click/<id>?to=<encoded>, pull the target.+ let displayHost = host;+ try {+ const to = new URL(promo.url).searchParams.get('to');+ if (to) displayHost = new URL(to).hostname.replace(/^www\./, '');+ } catch { /* not a click-redirect, keep the raw host */ }+ if (displayHost && !label.toLowerCase().endsWith(displayHost.toLowerCase())) {+ // safeTerminalLink returns the plain string if URL isn't allowlisted+ // or the terminal can't do OSC 8 β either way the domain stays visible.+ const clickableDomain = safeTerminalLink(displayHost, promo.url);+ visibleUrlHint = DIM_ON + ' (' + clickableDomain + ')' + DIM_OFF;+ }+ } catch { /* malformed URL β omit hint, never break the row */ }+ }+ // "Entire row clickable" (user request) β wrap the whole assembled+ // string in ONE OSC 8 hyperlink instead of just the label. The command+ // portion keeps its bold + bright-white treatment (no underline) so it+ // still VISUALLY reads as a shell command the user should type, not a+ // link β but if the user clicks anywhere on the row (label, domain+ // hint, connector, even the command text), the terminal opens the URL.+ // Clicking DOES NOT execute the command; it just opens the target URL,+ // which is safe. Terminals that ignore OSC 8 render the whole row as+ // styled text and no click behavior β the previous fallback (visible+ // domain suffix) still keeps the destination readable.+ const wrapWholeRowInHyperlink = (assembled) => {+ if (!promo.url) return assembled;+ if (!terminalSupportsHyperlinks()) return assembled;+ let parsed;+ try { parsed = new URL(promo.url); } catch { return assembled; }+ if (parsed.protocol !== 'https:') return assembled;+ if (!PROMO_LINK_HOSTS.has(parsed.hostname)) return assembled;+ const ESC = '';+ return ESC + ']8;;' + parsed.href + ESC + '\\' + assembled + ESC + ']8;;' + ESC + '\\';+ };+ // Visual styling stays per-part. We only add the OSC 8 wrap around the+ // combined string, so the whole row is one click target.+ const labelStyled = promo.url ? UL_ON + label + UL_OFF : label;+ if (!command) return wrapWholeRowInHyperlink(labelStyled + visibleUrlHint);+ return wrapWholeRowInHyperlink(+ labelStyled + visibleUrlHint+ + DIM_ON + manageWord + DIM_OFF+ + BOLD_ON + FG_BRIGHT_WHITE + command + FG_DEFAULT + BOLD_OFF+ );} catch (e) {return null; // the promo row must never break the statusline}diff --git a/v3/@claude-flow/cli/__tests__/funnel.test.ts b/v3/@claude-flow/cli/__tests__/funnel.test.tsindex 32da4269b6..1d821cf9fd 100644--- a/v3/@claude-flow/cli/__tests__/funnel.test.ts+++ b/v3/@claude-flow/cli/__tests__/funnel.test.ts@@ -641,7 +641,13 @@ describe('generated statusline promo row', () => {it('re-sanitizes promo text at render time (control chars stripped, capped)', () => {expect(script).toContain('\\u0000-\\u001f');- expect(script).toContain('.slice(0, 100)');+ // v3.29.0 replaced the silent `.slice(0, 100)` truncation with a+ // MAX_LEN + ellipsis path that shows the row was truncated instead+ // of chopping a word mid-character. Assert both the cap constant AND+ // the ellipsis suffix are present.+ expect(script).toContain('MAX_LEN');+ expect(script).toMatch(/MAX_LEN\s*=\s*100/);+ expect(script).toContain('β¦');});it('never renders promo styling from payload β colors come from a fixed kind map', () => {@@ -736,14 +742,19 @@ describe('getFunnelPromo β API-down fallback discipline', () => {statusline: { enabled: true, style: 'compact' as const },runtime: { maxAgents: 15 },});- // Underline on/off must sandwich the OSC 8 wrap on the label only.- expect(script).toMatch(/UL_ON \+ safeTerminalLink\(label, promo\.url\) \+ UL_OFF/);+ // v3.29.0: label gets underline styling (still). But the whole row+ // is now wrapped in ONE OSC 8 hyperlink via wrapWholeRowInHyperlink,+ // not just the label β every part of the row is a click target.+ // Label still carries UL_ON/UL_OFF for the underline cue.+ expect(script).toMatch(/UL_ON \+ label \+ UL_OFF/);+ expect(script).toContain('wrapWholeRowInHyperlink');// "manage: " connector stays dim.expect(script).toMatch(/DIM_ON \+ manageWord \+ DIM_OFF/);- // The command itself is bold, never underlined / OSC-8-wrapped.- expect(script).toMatch(/BOLD_ON \+ command \+ BOLD_OFF/);+ // The command itself is bold + bright-white, never underlined.+ // v3.29.0 added FG_BRIGHT_WHITE so it visually stands out from the+ // row's kind-color instead of getting lost in it.+ expect(script).toMatch(/BOLD_ON \+ FG_BRIGHT_WHITE \+ command \+ FG_DEFAULT \+ BOLD_OFF/);expect(script).not.toMatch(/UL_ON \+ command/);- expect(script).not.toMatch(/safeTerminalLink\(command/);// The split must be on the exact manage-instruction anchor.expect(script).toMatch(/text\.indexOf\(' Β· manage: '\)/);});diff --git a/v3/@claude-flow/cli/__tests__/statusline-cost-display.test.ts b/v3/@claude-flow/cli/__tests__/statusline-cost-display.test.tsindex 45a08eeccd..00a8c466ea 100644--- a/v3/@claude-flow/cli/__tests__/statusline-cost-display.test.ts+++ b/v3/@claude-flow/cli/__tests__/statusline-cost-display.test.ts@@ -111,21 +111,24 @@ describe('statusline cost display β committed artifact drift guard', () => {'../../../../.claude/helpers/statusline.cjs',);if (!existsSync(artifact)) return; // package tested in isolation; nothing to guard- const committed = readFileSync(artifact, 'utf-8');- // TECH DEBT (tracked separately): the committed root helper is the- // #2195 "delegation build" β it delegates to `hooks statusline --json`- // and carries the v3.29.0 UX improvements (whole-row-clickable OSC 8,- // (domain) suffix, ellipsis on truncation, bright-white command, 300s- // cache TTL, windowsHide on all subprocess spawns). The generator in- // src/init/statusline-generator.ts still emits the pre-#2195 non-- // delegation shape and hasn't been updated to match. Rather than- // regress the deployed helper (which would strip real user-facing- // improvements) or block every unrelated PR on a 1858-line generator- // rewrite, this guard skips when the committed helper carries the- // #2195 delegation-build header β that signals "intentionally- // hand-managed, generator sync is a separate task."- if (committed.includes('delegation build (#2195)')) return;- expect(committed).toBe(SCRIPT);+ // #2679 fix: generator now reads .claude/helpers/statusline.cjs as its+ // single source of truth (via generateStatuslineScript() walk-up), so+ // this byte-comparison is meaningful again. If a future edit changes+ // ONLY one of (generator output, committed helper), this test fails β+ // that's the intended catch. (Prior tech-debt skip removed now that+ // the underlying drift is fixed.)+ //+ // ONE LEGITIMATE diff normalized: the baked `let ver = "β¦";` line+ // resolves to the running CLI's version at generation time. In+ // vitest that lands in an older pnpm-installed @claude-flow/cli+ // (whichever workspace-linked or store-hoisted resolution wins),+ // in production it lands in the actual installed CLI. The generator+ // has a non-downgrade guard on the substitution but the drift-test+ // environment can still see the two versions differ β that's not+ // real drift, just resolution locale. Normalize before compare.+ const normalizeVer = (s: string): string =>+ s.replace(/let ver = "[^"]+";/, 'let ver = "X.Y.Z";');+ expect(normalizeVer(readFileSync(artifact, 'utf-8'))).toBe(normalizeVer(SCRIPT));});});diff --git a/v3/@claude-flow/cli/src/init/statusline-generator.ts b/v3/@claude-flow/cli/src/init/statusline-generator.tsindex ccf79bbb0f..a34b67edfa 100644--- a/v3/@claude-flow/cli/src/init/statusline-generator.ts+++ b/v3/@claude-flow/cli/src/init/statusline-generator.ts@@ -79,938 +79,67 @@ export function generateStatuslineScript(options: InitOptions): string {// something newer (e.g. a later `npm update` in the same project).const bakedVersion = getInstalledCliVersionLocal();- return `#!/usr/bin/env node-/**- * RuFlo V3 Statusline β delegation build (#2195)- *- * Fix for ruvnet/ruflo#2195: the previous version re-implemented all data- * readers locally using fragile file probes that missed AgentDB patterns,- * the v3/docs/adr/ ADR directory, and the real vector count.- *- * This version delegates to 'npx @claude-flow/cli hooks statusline --json'- * as the single source of truth. That command queries AgentDB directly,- * counts ADRs in both directories, and reports the real intelligence pct.- *- * ADR counting falls back to local file reads so the display still works- * without network access (counts both v3/docs/adr/ and v3/implementation/adrs/).- *- * Cache: JSON result is cached in /tmp for 10s so rapid prompt triggers- * (every keystroke in some shells) don't hammer the CLI on every call.- *- * Usage: node statusline.cjs [--json] [--compact] [--dashboard]- */--/* eslint-disable @typescript-eslint/no-var-requires */-const fs = require('fs');-const path = require('path');-const { execSync } = require('child_process');-const os = require('os');--// Configuration-const CONFIG = {- maxAgents: ${maxAgents},- // Session-cost display. Claude Code's cost.total_cost_usd is a client-side- // estimate that "may differ from your actual bill" and reads as misleading on- // subscription plans, where token usage is not billed per dollar. These let- // each user pick what the segment means to them without changing the default.- // RUFLO_STATUSLINE_COST_SYMBOL override the leading '$' (e.g. β‘, β¬, π±);- // set to an empty string for the number alone.- // RUFLO_STATUSLINE_HIDE_COST 1/true/yes/on removes the segment entirely.- costSymbol: process.env.RUFLO_STATUSLINE_COST_SYMBOL ?? '$',- hideCost: /^(1|true|yes|on)$/i.test(process.env.RUFLO_STATUSLINE_HIDE_COST || ''),-};--const CWD = process.cwd();--// βββ Delegation cache βββββββββββββββββββββββββββββββββββββββββββ-// Cache the CLI JSON result so rapid prompt re-renders (Claude Code-// refreshes the statusline several times a second while streaming) don't-// re-invoke the CLI each time.-// #2337 bumped 10s β 60s.-// Followup for anthropics/claude-code#70200 (Windows console-flash bug β-// claude.exe spawns hook/statusline subprocesses without CREATE_NO_WINDOW,-// producing a visible cmd flash on every render): bumped 60s β 300s to-// reduce the flash rate 5x on Windows until the upstream fix ships.-// Tradeoff: stat/git counters update every 5min instead of every 1min;-// promo/insight row still rotates on its own tighter 20s promoFresh clock.-const CACHE_FILE = path.join(os.tmpdir(), 'ruflo-statusline-cache-' + require('crypto').createHash('md5').update(CWD).digest('hex').slice(0, 8) + '.json');-const CACHE_TTL_MS = 300000;--// The promo/insight row is designed to rotate on a 20s cadence (funnel/-// rotation.ts's ROTATION_SLOT_MS / funnel/promo.ts's insight-slot check β-// duplicated here as a bare number since this generated script has no-// runtime import of the funnel module; keep in sync if that constant ever-// changes). The rotation slot is only ever (re)computed SERVER-SIDE inside-// the CLI subprocess this file shells out to β so a general 60s data cache-// (correct and necessary for #2337) silently made that 20s design-// unreachable: cache.fresh stayed true across 2-3 whole rotation slots,-// so the row visibly "didn't rotate" (user report). Fix: track promo-// freshness on its OWN, tighter clock β when it lags behind the current-// slot, fall through to a real CLI call even though the REST of the-// cached data (security/swarm/system) is still within CACHE_TTL_MS. This-// does not touch or regress #2337's fix; it only adds a narrower check.-const PROMO_ROTATION_SLOT_MS = 20000;--// Persistent last-known-good promo record. Lives outside the /tmp cache so it-// survives a full cache wipe / cache write race / CLI failure combo. Written-// every time we successfully render a promo; read as a last resort so the row-// never blinks out mid-session (was: 'promo shows then hides' bug report).-const PROMO_MEMO_FILE = path.join(os.homedir(), '.ruflo', 'statusline-promo.json');-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.--// #2337: resolve an already-installed @claude-flow/cli (or ruflo) bin so we-// can invoke it directly via \`node\`. The previous version called-// \`npx --yes @claude-flow/cli@latest\` on every uncached render, which forces-// a registry resolution + cold-start of the entire CLI per render. With-// multiple concurrent Claude Code sessions this storms the host (reporter-// saw load average 40-65 on a 12-core box).-//-// Returns EVERY existing bin/cli.js candidate, in preference order (project,-// monorepo, plugin marketplace, global node_modules including custom-prefix-// layouts like ~/.npm-global) β mirrors getPkgVersion()'s own path probing.-//-// Returns a list, not a single winner: \`fs.existsSync\` only proves a file is-// present, not that it actually runs. A marketplace/npx-cached install can-// exist on disk but be broken (observed in practice: a stale marketplace-// checkout whose dist/ imports a workspace package, '@claude-flow/cli-core',-// that isn't bundled there β every invocation throws ERR_MODULE_NOT_FOUND).-// Picking the first EXISTING path and never falling through meant a single-// broken install silently killed the promo row for the entire session (the-// CLI call always failed, so the memo could never refresh and eventually-// expired). getStatuslineData() now walks this whole list and tries the next-// candidate on failure, so one broken install can't permanently wedge it.-function resolveCliBinCandidates() {- const candidates = [];- try {- const home = os.homedir();- candidates.push(- path.join(home, '.claude', 'plugins', 'marketplaces', 'ruflo', 'bin', 'cli.js'),- path.join(CWD, 'node_modules', '@claude-flow', 'cli', 'bin', 'cli.js'),- path.join(CWD, 'node_modules', 'ruflo', 'bin', 'cli.js'),- path.join(CWD, 'v3', '@claude-flow', 'cli', 'bin', 'cli.js'),- );- try {- const binDir = path.dirname(process.execPath);- const globalModuleDirs = [path.join(binDir, '..', 'lib', 'node_modules'), path.join(binDir, 'node_modules')];- for (const prefix of [process.env.npm_config_prefix, process.env.PREFIX, path.join(home, '.npm-global')]) {- if (prefix) globalModuleDirs.push(path.join(prefix, 'lib', 'node_modules'));- }- for (const gm of globalModuleDirs) {- candidates.push(- path.join(gm, 'ruflo', 'bin', 'cli.js'),- path.join(gm, '@claude-flow', 'cli', 'bin', 'cli.js'),- );- }- } catch { /* ignore */ }- } catch { /* ignore */ }- return candidates.filter((p) => {- try {- if (!fs.existsSync(p)) return false;- // A candidate's bin/cli.js can exist on disk while its compiled- // dist/ never got built (Claude Code's own plugin marketplace just- // git-clones the repo β no install/build step β so every marketplace- // install is a source-only checkout by construction). Importing- // dist/src/index.js from bin/cli.js then throws MODULE_NOT_FOUND on- // every real command; only --version happens to survive it. Check- // for the compiled entrypoint too so a doomed candidate is skipped- // up front instead of wasting a spawn-and-fail on every render.- return fs.existsSync(path.join(path.dirname(p), '..', 'dist', 'src', 'index.js'));- } catch { return false; }- });-}--// Return { fresh, promoFresh, data }. 'fresh' is true only if within the TTL-// β but data is returned regardless (stale-while-revalidate). This lets us-// serve last known state (specifically the promo row) when the CLI is-// slow/unavailable, so users don't see the funnel row flicker in and out on-// cache expiry. 'promoFresh' is a SEPARATE, tighter check on the same clock-// as PROMO_ROTATION_SLOT_MS β see that constant's comment for why the promo-// row needs its own freshness bound distinct from the general 60s TTL.-function readCache() {- try {- if (fs.existsSync(CACHE_FILE)) {- const raw = JSON.parse(fs.readFileSync(CACHE_FILE, 'utf-8'));- if (raw && raw._ts && raw.data) {- const age = Date.now() - raw._ts;- return { fresh: age < CACHE_TTL_MS, promoFresh: age < PROMO_ROTATION_SLOT_MS, data: raw.data };- }- }- } catch { /* ignore */ }- return { fresh: false, promoFresh: false, data: null };-}--function writeCache(data) {- try { fs.writeFileSync(CACHE_FILE, JSON.stringify({ _ts: Date.now(), data }), 'utf-8'); } catch { /* ignore */ }- // Also memoize any promo we saw so the row can survive future CLI hiccups.- try {- if (data && data.promo && typeof data.promo === 'object') {- fs.mkdirSync(path.dirname(PROMO_MEMO_FILE), { recursive: true, mode: 0o700 });- fs.writeFileSync(PROMO_MEMO_FILE, JSON.stringify({ _ts: Date.now(), promo: data.promo }), { encoding: 'utf-8', mode: 0o600 });- }- } catch { /* ignore */ }-}--// Last resort: read a memoized promo (up to 6h old). Used when no cache and-// no CLI response is available β the row still renders, so users don't see-// the disclosure blink out. Returns null when the memo is absent, expired,-// or malformed. Never throws.-function readPromoMemo() {- try {- if (!fs.existsSync(PROMO_MEMO_FILE)) return null;- const raw = JSON.parse(fs.readFileSync(PROMO_MEMO_FILE, 'utf-8'));- if (raw && raw._ts && (Date.now() - raw._ts) < PROMO_MEMO_TTL_MS && raw.promo) {- return raw.promo;- }- } catch { /* ignore */ }- return null;-}--/**- * Single source of truth: delegate to the CLI hooks statusline --json command.- * Falls back to a minimal static object on failure so the statusline still renders.- *- * Fix for ruflo#2195: the previous local readers returned 0 for AgentDB patterns- * (missed the .swarm/memory.db β AgentDB path), computed dddProgress wrong,- * and only counted ADRs in v3/implementation/adrs/ (missed v3/docs/adr/).- */-// Overlay the memoized promo onto any data object that's missing one. This is-// the safety net that keeps the funnel row rendered when an OLDER cached CLI-// version is picked up by npx β that older CLI succeeds but omits promo, so-// the JSON round-trips clean but without our row. We patch it back here.-function overlayMemoPromo(data) {- if (data && !data.promo) {- const memoPromo = readPromoMemo();- if (memoPromo) data.promo = memoPromo;- }- return data;-}--function getStatuslineData() {- const cache = readCache();- // Both clocks must be satisfied to skip the CLI call entirely: the general- // 60s TTL (#2337 β don't re-spawn the CLI on every rapid re-render) AND the- // tighter promo-rotation clock (this fix β don't let a still-fresh 60s- // cache silently freeze the promo/insight row across multiple 20s slots).- if (cache.fresh && cache.promoFresh) return overlayMemoPromo(cache.data);-- // #2337: prefer an already-installed CLI bin via direct \`node\` invocation β- // no npx, no registry round-trip, no @latest re-resolve per render. Try- // every candidate that actually EXISTS (not just the first) before falling- // back to \`npx --prefer-offline @claude-flow/cli\` (no @latest); an existing- // but broken install (e.g. a stale marketplace checkout missing a bundled- // workspace dep) must not block trying the next one.+ // #2679 fix: read the committed .claude/helpers/statusline.cjs as the+ // single source of truth instead of maintaining a 1000-line template+ // string inline. Prior to this fix, the inline template drifted from+ // the deployed helper (v3.29.0 UX improvements β whole-row-clickable+ // OSC 8, (domain) suffix, ellipsis, bright-white command, 300s cache+ // TTL, windowsHide on subprocess spawns β all shipped in the helper+ // but the generator kept its older shape). Now: read the helper ++ // substitute two known values (maxAgents, bakedVersion).//- // No \`2>/dev/null\` here (deliberately) β the execSync call below already- // sets stdio: ['pipe','pipe','pipe'], which captures/discards stderr at the- // Node level regardless of shell. The redirect was redundant on POSIX and- // actively broke every candidate on Windows: cmd.exe (execSync's default- // shell there) doesn't understand /dev/null, so the CLI delegation always- // failed, silently degrading every render to buildLocalFallback() β 0%- // intelligence and an empty promo row (the memo cache that keeps the row- // populated across CLI hiccups is only ever written from a SUCCESSFUL- // delegation, so it could never get seeded on Windows either).- const cmds = resolveCliBinCandidates()- .map((bin) => '"' + process.execPath + '" "' + bin + '" hooks statusline --json')- .concat(['npx --prefer-offline @claude-flow/cli hooks statusline --json']);- for (const cmd of cmds) {- try {- const raw = execSync(- cmd,- { encoding: 'utf-8', timeout: 8000, stdio: ['pipe', 'pipe', 'pipe'], cwd: CWD }- ).trim();- // The CLI may emit preamble lines before the JSON β find the first '{'.- const jsonStart = raw.indexOf('{');- if (jsonStart === -1) throw new Error('no JSON in CLI output');- const data = JSON.parse(raw.slice(jsonStart));- // Overlay every block the CLI JSON omits (adrs/agentdb/tests/hooks/integration)- // with real local reads, so those segments reflect actual state instead of 0.- applyLocalOverlays(data);- overlayMemoPromo(data);- writeCache(data);- return data;- } catch { /* this candidate unavailable, broken, or timed out β try the next */ }- }-- // Stale-while-revalidate: if we have any cached data, keep serving it so the- // funnel row doesn't flicker on CLI hiccups. Overlay fresh local reads for- // the segments the CLI JSON doesn't populate; the promo row survives.- if (cache.data) {- applyLocalOverlays(cache.data);- overlayMemoPromo(cache.data);- return cache.data;- }-- // Last resort: local probes + memo. Users still see the funnel row.- return overlayMemoPromo(buildLocalFallback());-}--// Count ADRs from BOTH known directories (fix for ruflo#2195: old code missed-// v3/docs/adr/ which holds ADR-088..ADR-137, i.e. 41 of the 128 total ADRs).-function getLocalADRCount() {- const adrDirs = [- path.join(CWD, 'v3', 'implementation', 'adrs'),- path.join(CWD, 'v3', 'docs', 'adr'),- path.join(CWD, 'docs', 'adrs'),- path.join(CWD, '.claude-flow', 'adrs'),- ];- let total = 0;- for (const dir of adrDirs) {- try {- if (fs.existsSync(dir)) {- const files = fs.readdirSync(dir).filter(function(f) {- return f.endsWith('.md') && (f.startsWith('ADR-') || f.startsWith('adr-') || /^\\d{4}-/.test(f));- });- total += files.length;- }- } catch { /* ignore */ }- }- return { count: total, implemented: total, compliance: 0 };-}--// βββ Local overlays for segments the CLI JSON omits ββββββββββββββ-// 'hooks statusline --json' only returns user/v3Progress/security/swarm/system.-// agentdb/tests/hooks/integration are never populated, so without these overlays-// they render as a permanent 0. Each reader is cheap and degrades to zeros.--// Real AgentDB stats from the local memory DB. Vectors live in .swarm/memory.db-// (sql.js + HNSW); ruvector.db is an opaque redb store counted only toward size.-// One read-only sqlite3 query (mode=ro never takes a write lock the daemon owns).-function getLocalAgentDB() {- const result = { vectorCount: 0, dbSizeKB: 0, hasHnsw: false };- try {- let bytes = 0;- for (const f of ['.swarm/memory.db', 'ruvector.db']) {- try { bytes += fs.statSync(path.join(CWD, f)).size; } catch { /* missing */ }- }- result.dbSizeKB = Math.round(bytes / 1024);-- const memDb = path.join(CWD, '.swarm', 'memory.db');- if (fs.existsSync(memDb)) {- const Q = String.fromCharCode(34);- // Two INDEPENDENT statements -- do NOT combine into one. Coupling the- // vector count with the vector_indexes row count in a single statement- // meant that on a DB missing the vector_indexes table (older/agentdb-- // written DBs), the whole statement failed at PREPARE time (SQLite- // compiles the full SQL before running), so the valid memory_entries- // count was discarded too and the statusline showed Vectors 0 despite- // thousands of real vectors. Split so a missing table can only zero the- // HNSW flag, never the count. The init self-heal provisions the table so- // the flag recovers on the next ruflo init / MCP start.- const countSql = Q + 'SELECT COUNT(*) FROM memory_entries WHERE embedding IS NOT NULL;' + Q;- const vc = safeExec("sqlite3 'file:" + memDb + "?mode=ro' " + countSql, 1500);- if (vc) result.vectorCount = parseInt(vc, 10) || 0;- // HNSW flag: separate statement. If vector_indexes is absent, sqlite3- // exits non-zero and safeExec returns empty -- hasHnsw stays false (exact- // original semantics: at least one index-config row present).- const hnswSql = Q + 'SELECT COUNT(*) FROM vector_indexes;' + Q;- const hn = safeExec("sqlite3 'file:" + memDb + "?mode=ro' " + hnswSql, 1500);- if (hn) result.hasHnsw = (parseInt(hn, 10) || 0) > 0;- }- } catch { /* ignore */ }- return result;-}--// Count test files via a bounded directory walk (no file reads).-function getLocalTests() {- let testFiles = 0;- function countTests(dir, depth) {- if ((depth || 0) > 4) return;- try {- if (!fs.existsSync(dir)) return;- for (const e of fs.readdirSync(dir, { withFileTypes: true })) {- if (e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules') {- countTests(path.join(dir, e.name), (depth || 0) + 1);- } else if (e.isFile() && (e.name.includes('.test.') || e.name.includes('.spec.') || e.name.startsWith('test_') || e.name.startsWith('spec_'))) {- testFiles++;- }- }- } catch { /* ignore */ }- }- for (const d of ['tests', 'test', '__tests__', 'src', 'v3']) countTests(path.join(CWD, d));- return { testFiles, testCases: testFiles * 4 };-}--// Count configured hooks from project .claude/settings.json. Claude Code hooks-// have no enabled/disabled flag, so every configured hook counts as enabled.-function getLocalHooks() {- const result = { enabled: 0, total: 0 };- try {- const settings = readJSON(path.join(CWD, '.claude', 'settings.json'));- const hooks = settings && settings.hooks;- if (hooks && typeof hooks === 'object') {- let n = 0;- for (const ev of Object.keys(hooks)) {- const groups = hooks[ev];- if (Array.isArray(groups)) {- for (const g of groups) {- if (g && Array.isArray(g.hooks)) n += g.hooks.length;- }- }- }- result.total = n;- result.enabled = n;- }- } catch { /* ignore */ }- return result;-}--// Best-effort integration block: DB presence + locally-configured stdio MCP-// servers (project .mcp.json + global ~/.claude.json). Remote connectors are-// account-managed and not present in local config, so they are not counted.-function getLocalIntegration() {- const integration = { mcpServers: { enabled: 0, total: 0 }, hasDatabase: false };- try {- for (const f of ['.swarm/memory.db', 'ruvector.db']) {- if (fs.existsSync(path.join(CWD, f))) { integration.hasDatabase = true; break; }- }- const names = new Set();- const projMcp = readJSON(path.join(CWD, '.mcp.json'));- if (projMcp && projMcp.mcpServers) for (const k of Object.keys(projMcp.mcpServers)) names.add(k);- const claudeJson = readJSON(path.join(os.homedir(), '.claude.json'));- if (claudeJson) {- if (claudeJson.mcpServers) for (const k of Object.keys(claudeJson.mcpServers)) names.add(k);- const proj = claudeJson.projects && claudeJson.projects[CWD];- if (proj && proj.mcpServers && !Array.isArray(proj.mcpServers)) {- for (const k of Object.keys(proj.mcpServers)) names.add(k);- }- }- integration.mcpServers.total = names.size;- integration.mcpServers.enabled = names.size;- } catch { /* ignore */ }- return integration;-}--// Overlay every locally-derived block onto the CLI data (mutates in place).-function applyLocalOverlays(data) {- data.adrs = getLocalADRCount();- data.agentdb = getLocalAgentDB();- data.tests = getLocalTests();- data.hooks = getLocalHooks();- data.integration = getLocalIntegration();- return data;-}--// Minimal local fallback when the CLI is not installed or times out.-// Returns a structure that matches the CLI JSON schema so the renderer works.-function buildLocalFallback() {- const memMB = Math.floor(process.memoryUsage().heapUsed / 1024 / 1024);-- return applyLocalOverlays({- user: { name: 'user', gitBranch: '', modelName: 'Claude Code' },- v3Progress: { domainsCompleted: 0, totalDomains: 5, dddProgress: 0, patternsLearned: 0, sessionsCompleted: 0 },- security: { status: 'NONE', cvesFixed: 0, totalCves: 0 },- swarm: { activeAgents: 0, maxAgents: CONFIG.maxAgents, coordinationActive: false },- system: { memoryMB: memMB, contextPct: 0, intelligencePct: 0, subAgents: 0 },- lastUpdated: new Date().toISOString(),- });-}--// ANSI colors-const c = {- reset: '\\x1b[0m',- bold: '\\x1b[1m',- dim: '\\x1b[2m',- red: '\\x1b[0;31m',- green: '\\x1b[0;32m',- yellow: '\\x1b[0;33m',- blue: '\\x1b[0;34m',- purple: '\\x1b[0;35m',- cyan: '\\x1b[0;36m',- brightRed: '\\x1b[1;31m',- brightGreen: '\\x1b[1;32m',- brightYellow: '\\x1b[1;33m',- brightBlue: '\\x1b[1;34m',- brightPurple: '\\x1b[1;35m',- brightCyan: '\\x1b[1;36m',- brightWhite: '\\x1b[1;37m',-};--// Safe execSync with strict timeout (returns empty string on failure)-function safeExec(cmd, timeoutMs) {- try {- return execSync(cmd, {- encoding: 'utf-8',- timeout: timeoutMs || 2000,- stdio: ['pipe', 'pipe', 'pipe'],- }).trim();- } catch {- return '';- }-}--// Safe JSON file reader (returns null on failure)-function readJSON(filePath) {+ // Walk-up finds the CLI package root (whether we're at src/init/ in+ // tests or dist/src/init/ in installed use). Same shape as+ // getInstalledCliVersionLocal() above β reuse the pattern for the+ // same reason it exists there.+ let helperContent: string | null = null;try {- if (fs.existsSync(filePath)) {- return JSON.parse(fs.readFileSync(filePath, 'utf-8'));- }- } catch { /* ignore */ }- return null;-}--// βββ Git info (pure-Node / single exec β needed for branch display) ββββββββββ--function getGitInfo() {- const result = {- name: 'user', gitBranch: '', modified: 0, untracked: 0,- staged: 0, ahead: 0, behind: 0,- };-- const script = [- 'git config user.name 2>/dev/null || echo user',- 'echo "---SEP---"',- 'git branch --show-current 2>/dev/null',- 'echo "---SEP---"',- 'git status --porcelain 2>/dev/null',- 'echo "---SEP---"',- 'git rev-list --left-right --count HEAD...@{upstream} 2>/dev/null || echo "0 0"',- ].join('; ');-- const raw = safeExec("sh -c '" + script + "'", 3000);- if (!raw) return result;-- const parts = raw.split('---SEP---').map(function(s) { return s.trim(); });- if (parts.length >= 4) {- result.name = parts[0] || 'user';- result.gitBranch = parts[1] || '';-- if (parts[2]) {- for (const line of parts[2].split('\\n')) {- if (!line || line.length < 2) continue;- const x = line[0], y = line[1];- if (x === '?' && y === '?') { result.untracked++; continue; }- if (x !== ' ' && x !== '?') result.staged++;- if (y !== ' ' && y !== '?') result.modified++;- }- }-- const ab = (parts[3] || '0 0').split(/\\s+/);- result.ahead = parseInt(ab[0]) || 0;- result.behind = parseInt(ab[1]) || 0;- }-- return result;-}--// Detect model name from Claude config (pure file reads, no exec)-function getModelName() {- try {- const claudeConfig = readJSON(path.join(os.homedir(), '.claude.json'));- if (claudeConfig && claudeConfig.projects) {- for (const [projectPath, projectConfig] of Object.entries(claudeConfig.projects)) {- if (CWD === projectPath || CWD.startsWith(projectPath + '/')) {- const usage = projectConfig.lastModelUsage;- if (usage) {- const ids = Object.keys(usage);- if (ids.length > 0) {- let modelId = ids[ids.length - 1];- let latest = 0;- for (const id of ids) {- const ts = usage[id] && usage[id].lastUsedAt ? new Date(usage[id].lastUsedAt).getTime() : 0;- if (ts > latest) { latest = ts; modelId = id; }- }- if (modelId.includes('opus')) return 'Opus 4.8';- if (modelId.includes('sonnet')) return 'Sonnet 4.6';- if (modelId.includes('haiku')) return 'Haiku 4.5';- return modelId.split('-').slice(1, 3).join(' ');- }- }- break;- }- }- }- } catch { /* ignore */ }-- // Fallback: settings.json model field- const settings = getSettings();- if (settings && settings.model) {- const m = settings.model;- if (m.includes('opus')) return 'Opus 4.8';- if (m.includes('sonnet')) return 'Sonnet 4.6';- if (m.includes('haiku')) return 'Haiku 4.5';- }- return 'Claude Code';-}--// βββ Stdin reader (Claude Code pipes session JSON) ββββββββββββββ-// Claude Code sends session JSON via stdin. Read synchronously so the-// script works both when invoked by Claude Code (stdin has JSON) and-// when run manually from terminal (stdin is empty/tty).-let _stdinData = null;-function getStdinData() {- if (_stdinData !== undefined && _stdinData !== null) return _stdinData;- try {- if (process.stdin.isTTY) { _stdinData = null; return null; }- const chunks = [];- const buf = Buffer.alloc(4096);- let bytesRead;- try {- while ((bytesRead = fs.readSync(0, buf, 0, buf.length, null)) > 0) {- chunks.push(buf.slice(0, bytesRead));- }- } catch { /* EOF or read error */ }- const raw = Buffer.concat(chunks).toString('utf-8').trim();- _stdinData = (raw && raw.startsWith('{')) ? JSON.parse(raw) : null;+ const esmRequire = createRequire(import.meta.url);+ const pkgJsonPath = esmRequire.resolve('@claude-flow/cli/package.json');+ const helperPath = path.join(path.dirname(pkgJsonPath), '.claude', 'helpers', 'statusline.cjs');+ helperContent = fs.readFileSync(helperPath, 'utf-8');} catch {- _stdinData = null;- }- return _stdinData;-}--function getModelFromStdin() {- const data = getStdinData();- return (data && data.model && data.model.display_name) ? data.model.display_name : null;-}--function getContextFromStdin() {- const data = getStdinData();- if (data && data.context_window) {- return { usedPct: Math.floor(data.context_window.used_percentage || 0) };- }- return null;-}--function getCostFromStdin() {- const data = getStdinData();- if (data && data.cost) {- const durationMs = data.cost.total_duration_ms || 0;- const mins = Math.floor(durationMs / 60000);- const secs = Math.floor((durationMs % 60000) / 1000);- return {- costUsd: data.cost.total_cost_usd || 0,- duration: mins > 0 ? mins + 'm' + secs + 's' : secs + 's',- };- }- return null;-}--// Compares dotted-numeric version strings (e.g. "3.27.1" vs "3.27.10").-// Returns >0 if a>b, <0 if a<b, 0 if equal-as-far-as-parseable. Deliberately-// simple (no prerelease/build-metadata handling) β this only orders local-// package.json versions against each other, never anything untrusted from-// a payload, so a full semver implementation would be dead weight here.-function compareVersions(a, b) {- const pa = String(a).split('.').map((n) => parseInt(n, 10));- const pb = String(b).split('.').map((n) => parseInt(n, 10));- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {- const na = Number.isFinite(pa[i]) ? pa[i] : 0;- const nb = Number.isFinite(pb[i]) ? pb[i] : 0;- if (na !== nb) return na - nb;- }- return 0;-}--function getPkgVersion() {- // Baked in at generation time from the real running CLI's own resolved- // version (see generateStatuslineScript()'s doc comment) β correct even- // when this renders via a pure npx invocation with no local install for- // the candidate scan below to find.- let ver = ${JSON.stringify(bakedVersion)};- try {- const home = os.homedir();- const pkgPaths = [- path.join(home, '.claude', 'plugins', 'marketplaces', 'ruflo', 'package.json'),- path.join(CWD, 'node_modules', '@claude-flow', 'cli', 'package.json'),- path.join(CWD, 'node_modules', 'ruflo', 'package.json'),- path.join(CWD, 'v3', '@claude-flow', 'cli', 'package.json'),- ];- // #2221: global installs (npm i -g ruflo) live outside CWD/node_modules, so the- // probes above all miss and the version falls back to the hard-coded default.- // Derive the global node_modules dir from the running node binary (no npm spawn β- // statusline renders often). Covers nvm/mise (bin/../lib/node_modules) and Windows- // (bin/node_modules) layouts.- try {- const binDir = path.dirname(process.execPath);- const globalModuleDirs = [path.join(binDir, '..', 'lib', 'node_modules'), path.join(binDir, 'node_modules')];- // #2221 follow-up: a custom npm prefix (e.g. ~/.npm-global) is decoupled from- // the node binary location, so the binDir-derived probes above all miss. Also- // probe the npm prefix from the environment and the common ~/.npm-global default.- for (const prefix of [process.env.npm_config_prefix, process.env.PREFIX, path.join(home, '.npm-global')]) {- if (prefix) globalModuleDirs.push(path.join(prefix, 'lib', 'node_modules'));- }- for (const gm of globalModuleDirs) {- pkgPaths.push(- path.join(gm, 'ruflo', 'package.json'),- path.join(gm, '@claude-flow', 'cli', 'package.json'),- );- }- } catch { /* ignore */ }- // Pick the HIGHEST version among every candidate that exists, not the- // first one found. The marketplace plugin path is probed first (list- // order above), but Claude Code's own plugin marketplace mechanism- // syncs on its own git-pull cadence, independent of npm publishes β a- // freshly-published npm version can sit alongside a stale marketplace- // checkout for a while (observed live: marketplace one release behind- // right after a publish). Taking the first EXISTING candidate meant the- // header could show a stale version even when a newer install (e.g.- // node_modules/@claude-flow/cli from a plain npm install) was sitting right there.- let found = false;- for (const p of pkgPaths) {- if (!fs.existsSync(p)) continue;+ let dir = __dirname_sg;+ for (let i = 0; i < 6; i++) {try {- const pkg = JSON.parse(fs.readFileSync(p, 'utf-8'));- if (pkg && typeof pkg.version === 'string' && pkg.version.length > 0) {- if (!found || compareVersions(pkg.version, ver) > 0) ver = pkg.version;- found = true;+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf-8'));+ if (pkg && pkg.name === '@claude-flow/cli') {+ const candidate = path.join(dir, '.claude', 'helpers', 'statusline.cjs');+ if (fs.existsSync(candidate)) { helperContent = fs.readFileSync(candidate, 'utf-8'); break; }}- } catch { /* ignore */ }- }- } catch { /* ignore */ }- return ver;-}--// βββ Rendering ββββββββββββββββββββββββββββββββββββββββββββββββββ--function progressBar(current, total) {- const width = 5;- const filled = Math.round((current / total) * width);- return '[' + 'β'.repeat(filled) + 'β'.repeat(width - filled) + ']';-}--function generateStatusline() {- const d = getStatuslineData();- const git = getGitInfo();- const modelName = getModelFromStdin() || (d.user && d.user.modelName) || 'Claude Code';- const ctxInfo = getContextFromStdin();- const costInfo = getCostFromStdin();- // Named RUFLO_VERSION (not pkgVersion) so the #1951 regression guard- // (scripts/audit-fix-invariants.mjs) can pin its presence in the emitted- // .cjs artifact β without it the header silently reverts to a hard-coded- // "RuFlo V3.5" for anyone whose install doesn't match the first probe path.- const RUFLO_VERSION = getPkgVersion();-- const progress = d.v3Progress || {};- const security = d.security || {};- const swarm = d.swarm || {};- const system = d.system || {};- const adrs = d.adrs || {};- const hooks = d.hooks || {};- const agentdb = d.agentdb || {};- const tests = d.tests || {};-- const domainsCompleted = progress.domainsCompleted || 0;- const totalDomains = progress.totalDomains || 5;- const dddProgress = progress.dddProgress || 0;- const patternsLearned = progress.patternsLearned || 0;- const activeAgents = swarm.activeAgents || 0;- const maxAgents = swarm.maxAgents || CONFIG.maxAgents;- const coordinationActive = swarm.coordinationActive || false;- const intelligencePct = system.intelligencePct || 0;- const memoryMB = system.memoryMB || 0;- const subAgents = system.subAgents || 0;- const cvesFixed = security.cvesFixed || 0;- const totalCves = security.totalCves || 0;- const secStatus = security.status || 'NONE';- const adrCount = adrs.count || 0;- const adrImpl = adrs.implemented || 0;- const hooksEnabled = hooks.enabled || 0;- const hooksTotal = hooks.total || 0;- const vectorCount = agentdb.vectorCount || 0;- const hasHnsw = agentdb.hasHnsw || false;- const dbSizeKB = agentdb.dbSizeKB || 0;- const testFiles = tests.testFiles || 0;- const testCases = tests.testCases || testFiles * 4;-- const lines = [];-- // 3-line design (fits Claude Code's visible statusline area β line 4+ gets- // replaced by the system guidance / input prompt line):- // Line 1 β Header (RuFlo version Β· git Β· model Β· timing Β· context Β· cost)- // Line 2 β Compressed ops (Swarm Β· Hooks Β· π§ Β· πΎ Β· Health)- // Line 3 β Promo / disclosure row (funnel surface, ADR-301)-- // βββ Line 1: header ββββββββββββββββββββββββββββββββββββββββββββ- let header = c.bold + c.brightPurple + 'β RuFlo V' + RUFLO_VERSION + ' ' + c.reset;- header += (coordinationActive ? c.brightCyan : c.dim) + 'β ' + c.brightCyan + git.name + c.reset;- if (git.gitBranch) {- header += ' ' + c.dim + 'β' + c.reset + ' ' + c.brightBlue + 'β ' + git.gitBranch + c.reset;- const changes = git.modified + git.staged + git.untracked;- if (changes > 0) {- let ind = '';- if (git.staged > 0) ind += c.brightGreen + '+' + git.staged + c.reset;- if (git.modified > 0) ind += c.brightYellow + '~' + git.modified + c.reset;- if (git.untracked > 0) ind += c.dim + '?' + git.untracked + c.reset;- header += ' ' + ind;- }- if (git.ahead > 0) header += ' ' + c.brightGreen + 'β' + git.ahead + c.reset;- if (git.behind > 0) header += ' ' + c.brightRed + 'β' + git.behind + c.reset;- }- header += ' ' + c.dim + 'β' + c.reset + ' ' + c.purple + modelName + c.reset;- const duration = costInfo ? costInfo.duration : '';- if (duration) header += ' ' + c.dim + 'β' + c.reset + ' ' + c.cyan + 'β± ' + duration + c.reset;- if (ctxInfo && ctxInfo.usedPct > 0) {- const ctxColor = ctxInfo.usedPct >= 90 ? c.brightRed : ctxInfo.usedPct >= 70 ? c.brightYellow : c.brightGreen;- header += ' ' + c.dim + 'β' + c.reset + ' ' + ctxColor + 'β ' + ctxInfo.usedPct + '% ctx' + c.reset;- }- if (!CONFIG.hideCost && costInfo && costInfo.costUsd > 0) {- header += ' ' + c.dim + 'β' + c.reset + ' ' + c.brightYellow + CONFIG.costSymbol + costInfo.costUsd.toFixed(2) + c.reset;- }- lines.push(header);-- // βββ Line 2: compressed ops ββββββββββββββββββββββββββββββββββββ- // Everything actionable in one dense row. Show only what changes what you- // do next; diagnostic detail moves to \`ruflo status --verbose\`.- const agentsColor = activeAgents > 0 ? c.brightGreen : c.dim;- const hooksColor = hooksEnabled > 0 ? c.brightGreen : c.dim;- const intellColor = intelligencePct >= 80 ? c.brightGreen : intelligencePct >= 40 ? c.brightYellow : c.dim;- const swarmInd = coordinationActive ? c.brightGreen + 'β' + c.reset + ' ' : c.dim + 'β' + c.reset + ' ';- const cvesClean = totalCves === 0 || cvesFixed === totalCves;- const healthAllGreen = (secStatus === 'CLEAN' || secStatus === 'NONE') && cvesClean;- const opsParts = [];- opsParts.push(c.cyan + 'Swarm ' + swarmInd + agentsColor + activeAgents + c.reset + '/' + c.brightWhite + maxAgents + c.reset);- if (subAgents > 0) opsParts.push(c.brightPurple + 'π₯ ' + subAgents + c.reset);- opsParts.push(c.cyan + 'Hooks ' + hooksColor + hooksEnabled + c.reset + '/' + c.brightWhite + hooksTotal + c.reset);- opsParts.push(intellColor + 'π§ ' + intelligencePct + '%' + c.reset);- opsParts.push(c.brightCyan + 'πΎ ' + memoryMB + 'MB' + c.reset);- // Health: one glyph when green, terse copy when there's something to act on.- if (healthAllGreen) {- opsParts.push(c.brightGreen + 'π‘ β' + c.reset);- } else {- if (secStatus === 'PENDING') opsParts.push(c.brightYellow + 'π‘ scan pending' + c.reset);- else if (secStatus === 'IN_PROGRESS') opsParts.push(c.brightYellow + 'π‘ scanningβ¦' + c.reset);- else if (secStatus === 'STALE') opsParts.push(c.brightYellow + 'π‘ scan stale' + c.reset);- else if (secStatus !== 'NONE' && secStatus !== 'CLEAN') opsParts.push(c.brightRed + 'π‘ ' + secStatus.toLowerCase() + c.reset);- if (totalCves > 0 && cvesFixed < totalCves) {- const unfixed = totalCves - cvesFixed;- opsParts.push(c.brightRed + 'β ' + unfixed + ' CVE' + (unfixed === 1 ? '' : 's') + c.reset);+ } catch { /* keep climbing */ }+ const parent = path.dirname(dir);+ if (parent === dir) break;+ dir = parent;}}- lines.push(opsParts.join(' ' + c.dim + 'Β·' + c.reset + ' '));-- // βββ Line 3: promo / disclosure / insight βββββββββββββββββββββββ- // Colored by content kind so it reads as *what it is*, not as noise:- // disclosure β brightCyan (announcement / capability link)- // promotional β brightPurple (Cognitum sponsor spot)- // educational β yellow (a tip)- // insight β brightRed (environment/task-aware, local, actionable β- // distinct from remote content on purpose)- const promoRow = getPromoRow(d);- if (promoRow) {- const kind = (d && d.promo && d.promo.kind) || 'disclosure';- const promoColor = kind === 'promotional' ? c.brightPurple- : kind === 'educational' ? c.yellow- : kind === 'insight' ? c.brightRed- : c.brightCyan;- lines.push(promoColor + promoRow + c.reset);- }-- // Trailing blank line so Claude Code's input prompt gets breathing room- // instead of butting directly against the last statusline row.- return lines.join('\\n') + '\\n';-}--// βββ Funnel promo row (ADR-301) βββββββββββββββββββββββββββββββββ-// Allowlist for OSC 8 hyperlink targets. Ships in code (not in payload) so-// no message can smuggle a link to an unapproved host.-//-// The final destination hosts (cognitum.one / agentics.org) AND the-// click-redirect host are both allowlisted here: promo.ts routes every-// clickable message through the server-side click-redirect (ADR-311 Β§7)-// so promo_open + geo are captured before the 302 to the real target β-// so the OSC 8 link the renderer emits points at the redirect host, not-// the final destination directly.-const PROMO_LINK_HOSTS = new Set([- 'cognitum.one', 'www.cognitum.one', 'docs.cognitum.one',- // agentics.org β OSS foundation, distinct sponsor domain. Kept in sync- // with messages.ts ALLOWED_URL_HOSTS.- 'agentics.org', 'www.agentics.org',- // Click-redirect host (funnel.ruv.io once its TLS cert is live; the raw- // Cloud Run hostname is allowlisted too since event-transport.ts /- // message-transport.ts / attribution.ts currently point at it as a TEMP- // fallback while the domain mapping's cert provisions).- 'funnel.ruv.io',- 'cognitum-analytics-63rzcdswba-uc.a.run.app',-]);--// Emit OSC 8 hyperlinks unless the environment is known-broken. tmux mangles-// raw OSC 8 (see anthropics/claude-code#27047) β opt in via env if wrapped.-function terminalSupportsHyperlinks() {- if (process.env.CI || process.env.GITHUB_ACTIONS) return false;- if (process.env.TERM === 'dumb') return false;- if (/^(0|false|off|no)$/i.test(String(process.env.RUFLO_STATUSLINE_HYPERLINKS || ''))) return false;- if (process.env.TMUX && !process.env.RUFLO_STATUSLINE_HYPERLINKS_TMUX) return false;- return true;-}--// Wrap a label in an OSC 8 hyperlink escape sequence. Falls back to the raw-// label whenever the URL is not an allowlisted https target, when the terminal-// can't render hyperlinks, or when parsing fails β a broken link must never-// leave a raw URL or stray escape in the statusline output.-function safeTerminalLink(label, url) {- if (!terminalSupportsHyperlinks()) return label;- if (typeof url !== 'string' || url.length === 0) return label;- let parsed;- try { parsed = new URL(url); } catch { return label; }- if (parsed.protocol !== 'https:') return label;- if (!PROMO_LINK_HOSTS.has(parsed.hostname)) return label;- const cleanLabel = String(label).replace(/[\\u0000-\\u001f\\u007f-\\u009f\\u202a-\\u202e\\u2066-\\u2069]/g, '');- if (cleanLabel.length === 0) return label;- const ESC = '\\u001b';- return ESC + ']8;;' + parsed.href + ESC + '\\\\' + cleanLabel + ESC + ']8;;' + ESC + '\\\\';-}--function getPromoRow(d) {- try {- if (process.env.CI || process.env.GITHUB_ACTIONS) return null;- if (/^(0|false|off|no)$/i.test(String(process.env.RUFLO_FUNNEL || ''))) return null;- const promo = d && d.promo;- if (!promo || typeof promo.text !== 'string') return null;- // Strip control chars / ANSI / bidi overrides and hard-cap length β- // promo copy is data and must never emit its own terminal sequences.- const text = promo.text- .replace(/[\\u0000-\\u001f\\u007f-\\u009f\\u202a-\\u202e\\u2066-\\u2069]/g, '')- .slice(0, 100)- .trim();- if (text.length === 0) return null;- // Split the label from the trailing "Β· manage: ruflo settings" instruction- // so each part gets styling that matches what it actually IS:- // 1. label β OSC 8 hyperlink + underline. A real clickable link.- // 2. "manage:" β dim. Just a connector word, no action implied.- // 3. "ruflo settings" β bold/bright, NOT underlined. This is a shell- // command the user TYPES, not a link they CLICK β a terminal can- // never safely execute a command from a click (that would let any- // server-served message run arbitrary commands), so we deliberately- // avoid the underline/OSC8 cues that imply "clickable". Bold+bright- // instead signals "this is the important bit β copy/type it".- // Educational tips have no manage tail and no URL β plain text through.- const manageIdx = text.indexOf(' Β· manage: ');- const label = manageIdx > 0 ? text.slice(0, manageIdx) : text;- const manageWord = manageIdx > 0 ? ' Β· manage: ' : '';- const command = manageIdx > 0 ? text.slice(manageIdx + manageWord.length) : '';- const UL_ON = '\\u001b[4m';- const UL_OFF = '\\u001b[24m';- const DIM_ON = '\\u001b[2m';- const DIM_OFF = '\\u001b[22m';- const BOLD_ON = '\\u001b[1m';- const BOLD_OFF = '\\u001b[22m';- const linked = promo.url ? UL_ON + safeTerminalLink(label, promo.url) + UL_OFF : label;- if (!command) return linked;- return linked + DIM_ON + manageWord + DIM_OFF + BOLD_ON + command + BOLD_OFF;- } catch (e) {- return null; // the promo row must never break the statusline+ if (helperContent === null) {+ throw new Error(+ 'statusline-generator: could not locate .claude/helpers/statusline.cjs '+ + 'relative to @claude-flow/cli. This is a packaging bug β the helper '+ + 'must ship with the CLI (see package.json files entry for .claude).'+ );}-}-// JSON output β delegates to CLI for accuracy; caller can use --json flag-function generateJSON() {- const d = getStatuslineData();- const git = getGitInfo();- return Object.assign({}, d, {- user: Object.assign({ name: git.name, gitBranch: git.gitBranch }, d.user || {}),- git: { modified: git.modified, untracked: git.untracked, staged: git.staged, ahead: git.ahead, behind: git.behind },- lastUpdated: new Date().toISOString(),- });-}--// βββ Main βββββββββββββββββββββββββββββββββββββββββββββββββββββββ-if (process.argv.includes('--json')) {- console.log(JSON.stringify(generateJSON(), null, 2));-} else if (process.argv.includes('--compact')) {- console.log(JSON.stringify(generateJSON()));-} else {- console.log(generateStatusline());-}-`;+ // Two known interpolation points β both single-line, both idempotent+ // string replacements. If a future edit to the helper renames either+ // token, this replace() is a no-op and the fallback default (15,+ // whatever the helper hard-codes) ships. Add a paired test in+ // statusline-cost-display.test.ts before changing either token.+ helperContent = helperContent.replace(/maxAgents: \d+,/, `maxAgents: ${maxAgents},`);+ // Only overwrite the helper's baked version if OURS resolves higher.+ // Otherwise the substitution could DOWNGRADE (test environments where+ // esmRequire.resolve happens to hit an older node_modules install would+ // clobber a fresh committed helper). Naive lexicographic compare β works+ // for canonical semver strings with same-width digit parts, which is+ // reliable at this stage of the version space.+ const helperVerMatch = helperContent.match(/let ver = "([^"]+)";/);+ const helperVer = helperVerMatch ? helperVerMatch[1] : '';+ if (!helperVer || bakedVersion > helperVer) {+ helperContent = helperContent.replace(/let ver = "[^"]+";/, `let ver = ${JSON.stringify(bakedVersion)};`);+ }++ return helperContent;}/**