Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 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

feat: Cognitum customer lifecycle funnel — ADR-301..310 + implementation (#2622)

rUvd0ac73d79848
diff --git a/.claude/helpers/hook-handler.cjs b/.claude/helpers/hook-handler.cjs
index b2b91a8c75..c187d8e60c 100755
--- a/.claude/helpers/hook-handler.cjs
+++ b/.claude/helpers/hook-handler.cjs
@@ -15,9 +15,79 @@
const path = require('path');
const fs = require('fs');
+const os = require('os');
const helpersDir = __dirname;
+// Resolve an installed @claude-flow/cli (or ruflo) bin — mirrors
+// statusline-generator.ts's resolveCliBin() candidate list. Used only to
+// spawn the detached funnel-refresh helper below; failures are silent (no
+// candidate found just means the refresh never fires this session).
+function resolveCliBinForHook() {
+ try {
+ const home = os.homedir();
+ const cwd = process.cwd();
+ const candidates = [
+ 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'),
+ // helpersDir is .claude/helpers/ inside the package itself when this
+ // file is running from a real @claude-flow/cli install (not a project
+ // that merely copied the helper) — its bin/ is two levels up.
+ path.join(helpersDir, '..', '..', 'bin', 'cli.js'),
+ ];
+ for (const p of candidates) {
+ if (fs.existsSync(p)) return p;
+ }
+ } catch (e) { /* ignore */ }
+ return null;
+}
+
+// Fire-and-forget doesn't work when the CALLER is itself a short-lived
+// subprocess (confirmed live: two consecutive statusline renders 5s apart
+// both saw an empty funnel-messages-cache, because the async HTTPS fetch
+// inside a `void refreshRemoteMessages()` call gets killed when the spawning
+// process exits before the request completes). Spawning fully DETACHED +
+// unref'd decouples the refresh's lifetime from this hook's — it keeps
+// running (up to message-transport.ts's own 4s fetch timeout) even after
+// session-restore's own process has already exited, so it actually gets a
+// chance to write the cache. Never awaited here — must not add to
+// SessionStart's own timeout budget.
+function spawnDetachedFunnelRefresh() {
+ try {
+ const cliBin = resolveCliBinForHook();
+ if (!cliBin) return;
+ const { spawn } = require('child_process');
+ const child = spawn(process.execPath, [cliBin, 'hooks', 'refresh-funnel', '--quiet'], {
+ detached: true,
+ stdio: 'ignore',
+ env: process.env,
+ });
+ child.unref();
+ } catch (e) { /* best-effort only */ }
+}
+
+// Same detached/unref'd pattern as spawnDetachedFunnelRefresh() above, for
+// ADR-316's co-pilot advisor tip. Safe to call on EVERY session-restore:
+// refresh-advisor's own action checks consent + a 24h TTL BEFORE spending
+// anything, so an unconsented or already-fresh install is a fast no-op file
+// read, never a network call. Never awaited here — must not add to
+// SessionStart's own timeout budget.
+function spawnDetachedAdvisorRefresh() {
+ try {
+ const cliBin = resolveCliBinForHook();
+ if (!cliBin) return;
+ const { spawn } = require('child_process');
+ const child = spawn(process.execPath, [cliBin, 'hooks', 'refresh-advisor', '--quiet'], {
+ detached: true,
+ stdio: 'ignore',
+ env: process.env,
+ });
+ child.unref();
+ } catch (e) { /* best-effort only */ }
+}
+
// Safe require with stdout suppression - the helper modules have CLI
// sections that run unconditionally on require(), so we mute console
// during the require to prevent noisy output.
@@ -168,6 +238,57 @@ const handlers = {
} else {
console.log('[INFO] Router not available, using default routing');
}
+
+ // Rate-limit -> sponsored-capacity nudge (ADR-312/313). Fires here,
+ // client-side, BEFORE the API call this prompt would make — so it still
+ // reaches the transcript even if that call then fails from the rate
+ // limit. Cheap local file reads only; never a network call or a child
+ // process, so it cannot add latency to prompt submission.
+ try {
+ const rlFunnelEnv = process.env.RUFLO_FUNNEL;
+ const rlDisabledByEnv = rlFunnelEnv !== undefined && /^(0|false|off|no)$/i.test(String(rlFunnelEnv).trim());
+ const rlCiVars = ['CI', 'GITHUB_ACTIONS', 'GITLAB_CI', 'CIRCLECI', 'TRAVIS', 'BUILDKITE', 'JENKINS_URL', 'TEAMCITY_VERSION', 'TF_BUILD'];
+ const rlIsCi = rlCiVars.some((v) => {
+ const val = process.env[v];
+ return val !== undefined && val !== '' && val !== '0' && String(val).toLowerCase() !== 'false';
+ });
+ const rlHome = path.join(os.homedir(), '.ruflo');
+ let rlUserDisabled = false;
+ try {
+ const rlUserCfg = JSON.parse(fs.readFileSync(path.join(rlHome, 'funnel.json'), 'utf8'));
+ rlUserDisabled = !!(rlUserCfg && rlUserCfg.enabled === false);
+ } catch (e) { /* absent/malformed = not disabled */ }
+ let rlProjectDisabled = false;
+ try {
+ const rlProjCfg = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'claude-flow.config.json'), 'utf8'));
+ rlProjectDisabled = !!(rlProjCfg && rlProjCfg.funnel && rlProjCfg.funnel.enabled === false);
+ } catch (e) { /* absent/malformed = not disabled */ }
+
+ if (!rlDisabledByEnv && !rlIsCi && !rlUserDisabled && !rlProjectDisabled) {
+ let rlStatus = null;
+ try { rlStatus = JSON.parse(fs.readFileSync(path.join(rlHome, 'rate-limit-status.json'), 'utf8')); } catch (e) { /* not flagged */ }
+ let rlIsLimited = false;
+ if (rlStatus && rlStatus.limited) {
+ if (rlStatus.since) {
+ const rlSinceMs = Date.parse(rlStatus.since);
+ rlIsLimited = isNaN(rlSinceMs) ? true : (Date.now() - rlSinceMs) < 6 * 60 * 60 * 1000;
+ } else {
+ rlIsLimited = true;
+ }
+ }
+ if (rlIsLimited) {
+ let rlConsented = false;
+ try {
+ const rlConsentFile = JSON.parse(fs.readFileSync(path.join(rlHome, 'consent.json'), 'utf8'));
+ const rlReceipt = rlConsentFile && rlConsentFile['sponsored-downtime'];
+ rlConsented = !!(rlReceipt && rlReceipt.granted === true && rlReceipt.at !== null && rlReceipt.policyVersion === 1);
+ } catch (e) { /* not consented */ }
+ if (!rlConsented) {
+ console.log('[COGNITUM] Hit your Claude usage limit? Free sponsored capacity is available at cognitum.one/meta-llm — run: ruflo proxy sponsor-enable --yes');
+ }
+ }
+ }
+ } catch (e) { /* nudge must never break the hook */ }
},
'pre-bash': () => {
@@ -234,6 +355,14 @@ const handlers = {
console.log(`[INTELLIGENCE] Loaded ${initResult.nodes} patterns, ${initResult.edges} edges`);
}
}
+ // Warm the funnel message cache once per session (see
+ // spawnDetachedFunnelRefresh's doc comment for why this must happen
+ // here, detached, rather than as the statusline's own fire-and-forget).
+ spawnDetachedFunnelRefresh();
+ // ADR-316 co-pilot advisor tip — same detached pattern; cheap no-op
+ // when not consented or still within the 24h TTL (see refresh-advisor's
+ // own doc comment).
+ spawnDetachedAdvisorRefresh();
},
'session-end': async () => {
diff --git a/.claude/helpers/intelligence.cjs b/.claude/helpers/intelligence.cjs
index 9fc094dd90..5f3d6d3905 100755
--- a/.claude/helpers/intelligence.cjs
+++ b/.claude/helpers/intelligence.cjs
@@ -587,6 +587,16 @@ function recordEdit(file, success) {
sessionId: sessionGet('sessionId') || null,
});
fs.appendFileSync(PENDING_PATH, entry + '\n', 'utf-8');
+ // Runaway-storage guard: pending-insights is append-only and only drained by
+ // consolidation. If it grows past ~512KB (thousands of un-consolidated edits
+ // — e.g. the daemon never ran), keep only the most recent 2000 lines so it
+ // can never grow unbounded. Cheap (a statSync per edit; rewrite only when over).
+ try {
+ if (fs.statSync(PENDING_PATH).size > 512 * 1024) {
+ const lines = fs.readFileSync(PENDING_PATH, 'utf-8').split('\n').filter(Boolean);
+ if (lines.length > 2000) fs.writeFileSync(PENDING_PATH, lines.slice(-2000).join('\n') + '\n', 'utf-8');
+ }
+ } catch (e) { /* non-fatal */ }
}
/**
diff --git a/.claude/helpers/statusline.cjs b/.claude/helpers/statusline.cjs
index f5ad7079c8..5751c656f4 100644
--- a/.claude/helpers/statusline.cjs
+++ b/.claude/helpers/statusline.cjs
@@ -49,6 +49,28 @@ const CWD = process.cwd();
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;
+// 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
@@ -56,18 +78,30 @@ const CACHE_TTL_MS = 60000;
// multiple concurrent Claude Code sessions this storms the host (reporter
// saw load average 40-65 on a 12-core box).
//
-// Returns the absolute path to bin/cli.js or null. Mirrors getPkgVersion()'s
-// path probing (project, monorepo, plugin marketplace, global node_modules
-// including custom-prefix layouts like ~/.npm-global).
-function resolveCliBin() {
+// 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();
- const candidates = [
+ 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')];
@@ -81,27 +115,54 @@ function resolveCliBin() {
);
}
} catch { /* ignore */ }
- for (const p of candidates) {
- if (fs.existsSync(p)) return p;
- }
} catch { /* ignore */ }
- return null;
+ return candidates.filter((p) => { try { return fs.existsSync(p); } 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 && (Date.now() - raw._ts) < CACHE_TTL_MS) {
- return raw.data;
+ 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 null;
+ 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;
}
/**
@@ -112,37 +173,65 @@ function writeCache(data) {
* (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 cached = readCache();
- if (cached) return cached;
+ 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.
+ const cmds = resolveCliBinCandidates()
+ .map((bin) => '"' + process.execPath + '" "' + bin + '" hooks statusline --json 2>/dev/null')
+ .concat(['npx --prefer-offline @claude-flow/cli hooks statusline --json 2>/dev/null']);
+ 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 */ }
+ }
- try {
- // #2337: prefer an already-installed CLI bin via direct `node` invocation
- // — no npx, no registry round-trip, no @latest re-resolve per render.
- // Fall back to `npx --prefer-offline @claude-flow/cli` (no @latest) only
- // when nothing is installed locally, so a cold environment still works.
- const cliBin = resolveCliBin();
- const cmd = cliBin
- ? '"' + process.execPath + '" "' + cliBin + '" hooks statusline --json 2>/dev/null'
- : 'npx --prefer-offline @claude-flow/cli hooks statusline --json 2>/dev/null';
- 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);
- writeCache(data);
- return data;
- } catch { /* CLI unavailable or timed out */ }
-
- // Fallback: use local file probes only (will be less accurate, but non-zero
- // when CLI is available and accurate when it's not).
- return buildLocalFallback();
+ // 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
@@ -188,13 +277,24 @@ function getLocalAgentDB() {
const memDb = path.join(CWD, '.swarm', 'memory.db');
if (fs.existsSync(memDb)) {
const Q = String.fromCharCode(34);
- const sql = Q + 'SELECT (SELECT COUNT(*) FROM memory_entries WHERE embedding IS NOT NULL)||' + "'|'" + '||(SELECT COUNT(*) FROM vector_indexes);' + Q;
- const out = safeExec("sqlite3 'file:" + memDb + "?mode=ro' " + sql, 1500);
- if (out && out.indexOf('|') !== -1) {
- const parts = out.split('|');
- result.vectorCount = parseInt(parts[0], 10) || 0;
- result.hasHnsw = (parseInt(parts[1], 10) || 0) > 0;
- }
+ // 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;
@@ -531,7 +631,11 @@ function generateStatusline() {
const modelName = getModelFromStdin() || (d.user && d.user.modelName) || 'Claude Code';
const ctxInfo = getContextFromStdin();
const costInfo = getCostFromStdin();
- const pkgVersion = getPkgVersion();
+ // 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 || {};
@@ -567,8 +671,14 @@ function generateStatusline() {
const lines = [];
- // Header
- let header = c.bold + c.brightPurple + '▊ RuFlo V' + pkgVersion + ' ' + c.reset;
+ // 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;
@@ -595,81 +705,148 @@ function generateStatusline() {
}
lines.push(header);
- // Separator
- lines.push(c.dim + '─'.repeat(53) + c.reset);
-
- // Line 1: DDD Domains
- const domainsColor = domainsCompleted >= 3 ? c.brightGreen : domainsCompleted > 0 ? c.yellow : c.red;
- let perfIndicator;
- if (hasHnsw && vectorCount > 0) {
- const speedup = vectorCount > 10000 ? '12500x' : vectorCount > 1000 ? '150x' : '10x';
- perfIndicator = c.brightGreen + '⚡ HNSW ' + speedup + c.reset;
- } else if (patternsLearned > 0) {
- const pk = patternsLearned >= 1000 ? (patternsLearned / 1000).toFixed(1) + 'k' : String(patternsLearned);
- perfIndicator = c.brightYellow + '📚 ' + pk + ' patterns' + c.reset;
- } else {
- perfIndicator = c.dim + '⚡ target: 150x-12500x' + c.reset;
- }
- lines.push(
- c.brightCyan + '🏗️ DDD Domains' + c.reset + ' ' + progressBar(domainsCompleted, totalDomains) + ' ' +
- domainsColor + domainsCompleted + c.reset + '/' + c.brightWhite + totalDomains + c.reset + ' ' + perfIndicator
- );
-
- // Line 2: Swarm + Hooks + CVE + Memory + Intelligence
- const swarmInd = coordinationActive ? c.brightGreen + '◉' + c.reset : c.dim + '○' + c.reset;
- const agentsColor = activeAgents > 0 ? c.brightGreen : c.red;
- const secIcon = secStatus === 'CLEAN' ? '🟢' : (secStatus === 'IN_PROGRESS' || secStatus === 'STALE') ? '🟡' : (secStatus === 'NONE' ? '⚪' : '🔴');
- const secColor = secStatus === 'CLEAN' ? c.brightGreen : (secStatus === 'IN_PROGRESS' || secStatus === 'STALE') ? c.brightYellow : (secStatus === 'NONE' ? c.dim : c.brightRed);
+ // ─── 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);
+ }
+ }
+ 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;
+}
- lines.push(
- c.brightYellow + '🤖 Swarm' + c.reset + ' ' + swarmInd + ' [' + agentsColor + String(activeAgents).padStart(2) + c.reset + '/' + c.brightWhite + maxAgents + c.reset + '] ' +
- c.brightPurple + '👥 ' + subAgents + c.reset + ' ' +
- c.brightBlue + '🪝 ' + hooksColor + hooksEnabled + c.reset + '/' + c.brightWhite + hooksTotal + c.reset + ' ' +
- secIcon + ' ' + secColor + 'CVE ' + cvesFixed + c.reset + '/' + c.brightWhite + totalCves + c.reset + ' ' +
- c.brightCyan + '💾 ' + memoryMB + 'MB' + c.reset + ' ' +
- intellColor + '🧠 ' + String(intelligencePct).padStart(3) + '%' + c.reset
- );
-
- // Line 3: Architecture
- const dddColor = dddProgress >= 50 ? c.brightGreen : dddProgress > 0 ? c.yellow : c.red;
- const adrColor = adrCount > 0 ? (adrImpl === adrCount ? c.brightGreen : c.yellow) : c.dim;
- const adrDisplay = adrColor + '●' + adrImpl + '/' + adrCount + c.reset;
-
- lines.push(
- c.brightPurple + '🔧 Architecture' + c.reset + ' ' +
- c.cyan + 'ADRs' + c.reset + ' ' + adrDisplay + ' ' + c.dim + '│' + c.reset + ' ' +
- c.cyan + 'DDD' + c.reset + ' ' + dddColor + '●' + String(dddProgress).padStart(3) + '%' + c.reset + ' ' + c.dim + '│' + c.reset + ' ' +
- c.cyan + 'Security' + c.reset + ' ' + secColor + '●' + secStatus + c.reset
- );
-
- // Line 4: AgentDB, Tests, Integration
- const hnswInd = hasHnsw ? c.brightGreen + '⚡' + c.reset : '';
- const sizeDisp = dbSizeKB >= 1024 ? (dbSizeKB / 1024).toFixed(1) + 'MB' : dbSizeKB + 'KB';
- const vectorColor = vectorCount > 0 ? c.brightGreen : c.dim;
- const testColor = testFiles > 0 ? c.brightGreen : c.dim;
-
- // MCP / DB integration from data
- const integration = d.integration || {};
- const mcpServers = (integration.mcpServers) || {};
- let integStr = '';
- if (mcpServers.total > 0) {
- const mcpCol = mcpServers.enabled === mcpServers.total ? c.brightGreen : mcpServers.enabled > 0 ? c.brightYellow : c.red;
- integStr += c.cyan + 'MCP' + c.reset + ' ' + mcpCol + '●' + mcpServers.enabled + '/' + mcpServers.total + c.reset;
+// 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 (integration.hasDatabase) integStr += (integStr ? ' ' : '') + c.brightGreen + '◆' + c.reset + 'DB';
- if (!integStr) integStr = c.dim + '● none' + c.reset;
-
- lines.push(
- c.brightCyan + '📊 AgentDB' + c.reset + ' ' +
- c.cyan + 'Vectors' + c.reset + ' ' + vectorColor + '●' + vectorCount + hnswInd + c.reset + ' ' + c.dim + '│' + c.reset + ' ' +
- c.cyan + 'Size' + c.reset + ' ' + c.brightWhite + sizeDisp + c.reset + ' ' + c.dim + '│' + c.reset + ' ' +
- c.cyan + 'Tests' + c.reset + ' ' + testColor + '●' + testFiles + c.reset + ' ' + c.dim + '(~' + testCases + ' cases)' + c.reset + ' ' + c.dim + '│' + c.reset + ' ' +
- integStr
- );
-
- return lines.join('\n');
}
// JSON output — delegates to CLI for accuracy; caller can use --json flag
diff --git a/.github/workflows/funnel-gates.yml b/.github/workflows/funnel-gates.yml
new file mode 100644
index 0000000000..8b42a0e1b8
--- /dev/null
+++ b/.github/workflows/funnel-gates.yml
@@ -0,0 +1,135 @@
+# Funnel release gates — ADR-310.
+#
+# Enforces the hard gates on every change touching a funnel surface:
+# - promo output in CI or non-TTY: 0
+# - promotional display before disclosure: 0
+# - control-sequence injection through message copy: 0
+# - lower-precedence source re-enabling a higher disable: 0
+# - credit recovery on anything but COGNITUM_CREDIT_EXHAUSTED: 0
+# - funnel events without telemetry consent: 0
+# - RUFLO_FUNNEL=0 suppresses every funnel surface
+#
+# Two jobs:
+# 1. invariants — the vitest suite mapping 1:1 to the gates above
+# 2. runtime-suppression — builds the CLI and proves, in a real CI
+# environment, that `hooks statusline --json` emits promo: null and
+# that RUFLO_FUNNEL=0 / user opt-out hold end-to-end
+
+name: funnel-gates
+
+on:
+ push:
+ branches: [main]
+ paths:
+ - 'v3/@claude-flow/cli/src/funnel/**'
+ - 'v3/@claude-flow/cli/src/commands/funnel.ts'
+ - 'v3/@claude-flow/cli/src/commands/init.ts'
+ - 'v3/@claude-flow/cli/src/commands/hooks.ts'
+ - 'v3/@claude-flow/cli/src/init/statusline-generator.ts'
+ - 'v3/@claude-flow/cli/__tests__/funnel.test.ts'
+ - 'v3/docs/api/cognitum-v1.openapi.yaml'
+ - '.github/workflows/funnel-gates.yml'
+ pull_request:
+ paths:
+ - 'v3/@claude-flow/cli/src/funnel/**'
+ - 'v3/@claude-flow/cli/src/commands/funnel.ts'
+ - 'v3/@claude-flow/cli/src/commands/init.ts'
+ - 'v3/@claude-flow/cli/src/commands/hooks.ts'
+ - 'v3/@claude-flow/cli/src/init/statusline-generator.ts'
+ - 'v3/@claude-flow/cli/__tests__/funnel.test.ts'
+ - 'v3/docs/api/cognitum-v1.openapi.yaml'
+ - '.github/workflows/funnel-gates.yml'
+ workflow_dispatch:
+
+# Setup mirrors the green "Build V3" job in v3-ci.yml exactly (pnpm 8 via
+# action-setup@v6, frozen-lockfile full install, workspace-wide build) — a
+# filtered install under a newer pnpm resolves the bare-semver workspace
+# deps from the registry instead of linking them, and the cli build then
+# can't find @claude-flow/cli-core's dist.
+env:
+ NODE_VERSION: '20'
+ PNPM_VERSION: '8'
+
+jobs:
+ invariants:
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ steps:
+ - uses: actions/checkout@v4
+ - uses: pnpm/action-setup@v6
+ with:
+ version: ${{ env.PNPM_VERSION }}
+ - uses: actions/setup-node@v4
+ with:
+ node-version: ${{ env.NODE_VERSION }}
+ cache: 'pnpm'
+ cache-dependency-path: v3/pnpm-lock.yaml
+ - name: Install dependencies
+ working-directory: v3
+ run: pnpm install --frozen-lockfile
+ - name: Funnel invariant suite (ADR-310 gate map)
+ working-directory: v3/@claude-flow/cli
+ run: npx vitest run __tests__/funnel.test.ts __tests__/statusline-cost-display.test.ts
+
+ - name: OpenAPI contract parses (ADR-308)
+ run: |
+ python3 -m pip install --quiet pyyaml
+ python3 -c "import yaml,sys; yaml.safe_load(open('v3/docs/api/cognitum-v1.openapi.yaml')); print('openapi yaml ok')"
+
+ runtime-suppression:
+ runs-on: ubuntu-latest
+ timeout-minutes: 25
+ steps:
+ - uses: actions/checkout@v4
+ - uses: pnpm/action-setup@v6
+ with:
+ version: ${{ env.PNPM_VERSION }}
+ - uses: actions/setup-node@v4
+ with:
+ node-version: ${{ env.NODE_VERSION }}
+ cache: 'pnpm'
+ cache-dependency-path: v3/pnpm-lock.yaml
+ - name: Install dependencies
+ working-directory: v3
+ run: pnpm install --frozen-lockfile
+ - name: Build workspace
+ working-directory: v3
+ run: pnpm build
+
+ # Gate: promo output in CI = 0. GitHub Actions sets CI=true — the real
+ # environment IS the test fixture.
+ - name: Promo suppressed under CI (promo must be null)
+ working-directory: v3/@claude-flow/cli
+ run: |
+ export RUFLO_STATE_DIR="$(mktemp -d)"
+ PROMO=$(node bin/cli.js hooks statusline --json 2>/dev/null | node -e "let d='';process.stdin.on('data',c=>d+=c).on('end',()=>{const j=JSON.parse(d);process.stdout.write(String(j.promo))})")
+ echo "promo=$PROMO"
+ test "$PROMO" = "null"
+
+ # Gate: RUFLO_FUNNEL=0 suppresses every surface even outside CI env vars.
+ - name: RUFLO_FUNNEL=0 suppresses promo (CI vars cleared)
+ working-directory: v3/@claude-flow/cli
+ run: |
+ export RUFLO_STATE_DIR="$(mktemp -d)"
+ PROMO=$(env -u CI -u GITHUB_ACTIONS RUFLO_FUNNEL=0 RUFLO_STATE_DIR="$RUFLO_STATE_DIR" node bin/cli.js hooks statusline --json 2>/dev/null | node -e "let d='';process.stdin.on('data',c=>d+=c).on('end',()=>{const j=JSON.parse(d);process.stdout.write(String(j.promo))})")
+ echo "promo=$PROMO"
+ test "$PROMO" = "null"
+
+ # Gate: user opt-out (`ruflo funnel disable`) holds and reports its source.
+ - name: funnel disable persists and wins over re-enable attempts below it
+ working-directory: v3/@claude-flow/cli
+ run: |
+ export RUFLO_STATE_DIR="$(mktemp -d)"
+ node bin/cli.js funnel disable
+ STATUS=$(env -u CI -u GITHUB_ACTIONS RUFLO_STATE_DIR="$RUFLO_STATE_DIR" node bin/cli.js funnel status --json 2>/dev/null | node -e "let d='';process.stdin.on('data',c=>d+=c).on('end',()=>{const j=JSON.parse(d);process.stdout.write(j.enabled+':'+j.decidedBy)})")
+ echo "status=$STATUS"
+ test "$STATUS" = "false:user-config"
+
+ # Gate: init in CI never prompts (enrollment suppressed, exit 0).
+ - name: init --minimal in CI runs non-interactively with no enrollment prompt
+ run: |
+ export RUFLO_STATE_DIR="$(mktemp -d)"
+ WORKDIR="$(mktemp -d)"
+ cd "$WORKDIR"
+ node "$GITHUB_WORKSPACE/v3/@claude-flow/cli/bin/cli.js" init --minimal --force < /dev/null | tee init.log
+ ! grep -q "Unlock additional capabilities" init.log
diff --git a/.github/workflows/v3-ci.yml b/.github/workflows/v3-ci.yml
index 9b2a78622d..6704de772f 100644
--- a/.github/workflows/v3-ci.yml
+++ b/.github/workflows/v3-ci.yml
@@ -269,9 +269,17 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: '22' }
- # js-yaml + tsx are needed by the smokes — install only those.
+ # js-yaml + tsx are needed by the smokes — install only those. Installed
+ # into an isolated prefix (not the repo root) and copied into node_modules
+ # rather than `npm install`-ed directly here: the root package.json now
+ # carries an `overrides.js-yaml` entry (CVE-1 fix), and npm refuses ANY
+ # direct/top-level install of a package that also has a top-level
+ # `overrides` entry for it (EOVERRIDE), regardless of version specifier.
- name: Install smoke deps
- run: npm install --no-save --no-package-lock js-yaml tsx
+ run: |
+ npm install --prefix /tmp/smoke-deps --no-package-lock js-yaml tsx
+ mkdir -p node_modules
+ cp -r /tmp/smoke-deps/node_modules/. node_modules/
- name: "#2267 — every .github/workflows/*.yml must parse"
run: node scripts/smoke-workflows-yaml.mjs
- name: "#2257 — router patterns must be word-boundary-anchored"
diff --git a/package-lock.json b/package-lock.json
index 2cc827aa11..3bc1853a9c 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "claude-flow",
- "version": "3.25.1",
+ "version": "3.26.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "claude-flow",
- "version": "3.25.1",
+ "version": "3.26.0",
"license": "MIT",
"dependencies": {
"@claude-flow/cli-core": "3.7.0-alpha.5",
@@ -7316,16 +7316,26 @@
"license": "MIT"
},
"node_modules/js-yaml": {
- "version": "4.1.1",
- "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
- "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.2.1.tgz",
+ "integrity": "sha512-zfLtNfQqxVqq3uaTqSkh4x4hZw3KHobGUA0fJUj4wawW8bsQLTVqpHdXSIzidh7o+4lEW36tANuAGdaFx6Zgnw==",
"dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/puzrin"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/nodeca"
+ }
+ ],
"license": "MIT",
"dependencies": {
"argparse": "^2.0.1"
},
"bin": {
- "js-yaml": "bin/js-yaml.js"
+ "js-yaml": "bin/js-yaml.mjs"
}
},
"node_modules/json-bigint": {
diff --git a/package.json b/package.json
index b7f148851c..7237e82a94 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "claude-flow",
- "version": "3.25.6",
+ "version": "3.26.0",
"description": "Ruflo - Enterprise AI agent orchestration for Claude Code. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration",
"main": "dist/index.js",
"type": "module",
@@ -23,6 +23,7 @@
"v3/@claude-flow/cli/dist/**/*.d.ts",
"!v3/@claude-flow/cli/dist/**/*.map",
"v3/@claude-flow/cli/package.json",
+ "v3/@claude-flow/cli/catalog-manifest.json",
"v3/@claude-flow/shared/dist/**/*.js",
"v3/@claude-flow/shared/dist/**/*.d.ts",
"!v3/@claude-flow/shared/dist/**/*.map",
@@ -81,6 +82,7 @@
"overrides": {
"ruvector": "^0.2.27",
"better-sqlite3": ">=12.8.0",
+ "js-yaml": ">=4.3.0",
"hono": ">=4.12.25",
"@ruvector/rvf-wasm": "0.1.5",
"@hono/node-server": ">=1.19.14",
diff --git a/ruflo/package.json b/ruflo/package.json
index 35f8e9b623..7236697d9e 100644
--- a/ruflo/package.json
+++ b/ruflo/package.json
@@ -1,6 +1,6 @@
{
"name": "ruflo",
- "version": "3.25.6",
+ "version": "3.26.0",
"description": "Ruflo - Enterprise AI agent orchestration platform. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration",
"main": "bin/ruflo.js",
"type": "module",
diff --git a/scripts/audit-env-var-precedence.mjs b/scripts/audit-env-var-precedence.mjs
index 563534d330..724662c0e9 100644
--- a/scripts/audit-env-var-precedence.mjs
+++ b/scripts/audit-env-var-precedence.mjs
@@ -56,6 +56,14 @@ const KNOWN_ESCAPE_HATCHES = new Set([
'RUFLO_HOOK_SKIP_NPX', // CI: suppress cold-install latency in smoke tests
'RUFLO_SUBLINEAR_NATIVE', // Manual override for native vs WASM sublinear — CI/perf knob
'RUFLO_METAHARNESS_CACHE_BASE', // CI/test seam: relocates the ~/.ruflo pinned-cache root in metaharness smoke tests — intentionally env-only, plugin scripts have no CLI-flag surface
+ 'RUFLO_FUNNEL', // Read inside the generated hook-handler.cjs (ADR-312/313 rate-limit nudge), not a typed CLI invocation — no command surface to attach a flag to
+ 'RUFLO_STATUSLINE_HYPERLINKS', // Terminal-capability opt-out for OSC 8 hyperlinks in the statusline hook, same pattern as NO_COLOR — the statusline runs as a hook script, never a user-typed CLI command
+ 'RUFLO_STATUSLINE_HYPERLINKS_TMUX', // Opt-in override of the tmux OSC 8 mangling workaround above — same hook-script context, no CLI surface
+ 'RUFLO_ADVISOR_MAX_BUDGET_USD', // Advisor-tip spend cap read from generated hook code (funnel/advisor-tip.ts) — background nudge, no CLI invocation to attach a flag to
+ 'RUFLO_FUNNEL_CLICK_ENDPOINT', // Staging/self-hosted override for the funnel click-redirect endpoint — deployment config, not a per-invocation CLI flag
+ 'RUFLO_FUNNEL_EVENTS_ENDPOINT', // Staging/self-hosted override for the funnel events endpoint — same deployment-config pattern as CLICK_ENDPOINT above
+ 'RUFLO_FUNNEL_MESSAGES_ENDPOINT', // Staging/self-hosted override for the funnel messages endpoint — same deployment-config pattern as CLICK_ENDPOINT above
+ 'RUFLO_STATE_DIR', // Test/CI isolation seam for the funnel state directory (defaults to ~/.ruflo) — background hook state, no CLI command reads it
// ── Embedding substrate toggles (3.25.x — opt-in tier + fail-closed ops flag) ─
'RUFLO_REQUIRE_REAL_EMBEDDINGS', // Fail-closed "no stubs" strict mode — deploy/CI ops toggle, not a per-invocation CLI flag (ADR-176)
diff --git a/scripts/regen-statusline-artifact.mjs b/scripts/regen-statusline-artifact.mjs
new file mode 100644
index 0000000000..81aef749c7
--- /dev/null
+++ b/scripts/regen-statusline-artifact.mjs
@@ -0,0 +1,30 @@
+#!/usr/bin/env node
+/**
+ * Regenerate .claude/helpers/statusline.cjs from the compiled generator.
+ * Run after any edit to v3/@claude-flow/cli/src/init/statusline-generator.ts
+ * so the committed root artifact matches the source of truth. The drift-guard
+ * test in v3/@claude-flow/cli/__tests__/statusline-cost-display.test.ts pins
+ * that these stay in lockstep.
+ */
+import { readFileSync, writeFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, resolve } from 'node:path';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const repoRoot = resolve(here, '..');
+const generatorPath = resolve(repoRoot, 'v3/@claude-flow/cli/dist/src/init/statusline-generator.js');
+const { generateStatuslineScript } = await import(generatorPath);
+
+const script = generateStatuslineScript({
+ statusline: { enabled: true, style: 'compact' },
+ runtime: { maxAgents: 15 },
+});
+
+const rootTarget = resolve(repoRoot, '.claude/helpers/statusline.cjs');
+const pkgTarget = resolve(repoRoot, 'v3/@claude-flow/cli/.claude/helpers/statusline.cjs');
+writeFileSync(rootTarget, script, 'utf-8');
+writeFileSync(pkgTarget, script, 'utf-8');
+
+console.log(`regenerated ${script.length} bytes`);
+console.log(` → ${rootTarget}`);
+console.log(` → ${pkgTarget}`);
diff --git a/services/cognitum-analytics/README.md b/services/cognitum-analytics/README.md
new file mode 100644
index 0000000000..7916ca4a0f
--- /dev/null
+++ b/services/cognitum-analytics/README.md
@@ -0,0 +1,17 @@
+# cognitum-analytics — moved out
+
+The RuFlo funnel analytics endpoint now lives in its own repo:
+
+**https://github.com/cognitum-one/ruflo-funnel-api**
+
+per ADR-311 (server-side split from OSS CLI lifecycle).
+
+Client contract (`POST /v1/events`) unchanged — see
+[ADR-308](../../v3/docs/adr/ADR-308-cognitum-public-api-contract.md).
+Server implementation, Cloud Function source, Firestore schema, and
+deploy scripts are all in the dedicated repo.
+
+Client transport (this repo) points at `https://funnel.ruv.io/v1/events`
+by default — the Cloud Run domain mapping onto the deployed function.
+Override with the `RUFLO_FUNNEL_EVENTS_ENDPOINT` env var for staging or
+self-hosted deployments.
diff --git a/v3/@claude-flow/cli-core/src/output.ts b/v3/@claude-flow/cli-core/src/output.ts
index 17ca465caf..6a299418f9 100644
--- a/v3/@claude-flow/cli-core/src/output.ts
+++ b/v3/@claude-flow/cli-core/src/output.ts
@@ -182,31 +182,33 @@ export class OutputFormatter {
}
printWarning(message: string): void {
- // Warnings suppressed in quiet mode
+ // Warnings suppressed in quiet mode. Like printError, this goes to
+ // stderr — stdout is reserved for command results (e.g. --format json)
+ // and must never be interleaved with incidental warnings.
if (this.verbosity === 'quiet') return;
const icon = this.color('[WARN]', 'yellow', 'bold');
- this.writeln(`${icon} ${message}`);
+ this.writeErrorln(`${icon} ${message}`);
}
printInfo(message: string): void {
- // Info suppressed in quiet mode
+ // Info suppressed in quiet mode. stderr, same reasoning as printWarning.
if (this.verbosity === 'quiet') return;
const icon = this.color('[INFO]', 'blue', 'bold');
- this.writeln(`${icon} ${message}`);
+ this.writeErrorln(`${icon} ${message}`);
}
printDebug(message: string): void {
- // Debug only shows in verbose/debug mode
+ // Debug only shows in verbose/debug mode. stderr, same reasoning as printWarning.
if (this.verbosity !== 'verbose' && this.verbosity !== 'debug') return;
const icon = this.color('[DEBUG]', 'gray');
- this.writeln(`${icon} ${this.dim(message)}`);
+ this.writeErrorln(`${icon} ${this.dim(message)}`);
}
printTrace(message: string): void {
- // Trace only shows in debug mode
+ // Trace only shows in debug mode. stderr, same reasoning as printWarning.
if (this.verbosity !== 'debug') return;
const icon = this.color('[TRACE]', 'gray', 'dim');
- this.writeln(`${icon} ${this.dim(message)}`);
+ this.writeErrorln(`${icon} ${this.dim(message)}`);
}
// ============================================
diff --git a/v3/@claude-flow/cli/.claude/helpers/.helpers-version b/v3/@claude-flow/cli/.claude/helpers/.helpers-version
index 6f0e719e09..52ef0b37f4 100644
--- a/v3/@claude-flow/cli/.claude/helpers/.helpers-version
+++ b/v3/@claude-flow/cli/.claude/helpers/.helpers-version
@@ -1 +1 @@
-3.23.0
\ No newline at end of file
+3.25.6
\ No newline at end of file
diff --git a/v3/@claude-flow/cli/.claude/helpers/helpers.manifest.json b/v3/@claude-flow/cli/.claude/helpers/helpers.manifest.json
index 81e7507aea..139886c50e 100644
--- a/v3/@claude-flow/cli/.claude/helpers/helpers.manifest.json
+++ b/v3/@claude-flow/cli/.claude/helpers/helpers.manifest.json
@@ -3,10 +3,11 @@
"version": "3.25.6",
"files": {
"auto-memory-hook.mjs": "68be7e9a9eba7bf9c4e8a230db7bf61a243b965639f8504842799d6c6ca28762",
- "hook-handler.cjs": "bc4d2d26823d49b3ab1dded2946b66369f1f67bd76b4c30dca9f3b6df3cca8f0",
- "intelligence.cjs": "bd1f8e4b034944aee1df0391dc47ac2e8cc4b3aa542c65407a59d49620bbf76b"
+ "hook-handler.cjs": "887e99fbeb64f5ff64c85b74da3fbd9adc6b39907fd6a1044d4626db6fc4c042",
+ "intelligence.cjs": "bd1f8e4b034944aee1df0391dc47ac2e8cc4b3aa542c65407a59d49620bbf76b",
+ "statusline.cjs": "765f1af97a78f1c8ebf60ca63e67e490043e3c0322b7d63a438dd213e77e1672"
}
},
- "signature": "3D6EGXwOvFuWMNrgRU9zcNzvyxyzmDMdsCaOOs74M9sTouS2soV0yrNhyybgbqFf8bhy08KDLW0O7tohDYLbBg==",
+ "signature": "jY9HPQhEBB2azzRSrBBuhFoB9u/Z4OMjJ3CriyEY6nk2XArfpENCYqDzvTc/bqCaYNcb338yZ6yXhw2SHXykBw==",
"algorithm": "ed25519"
}
diff --git a/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs b/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs
index b2b91a8c75..c187d8e60c 100755
--- a/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs
+++ b/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs
@@ -15,9 +15,79 @@
const path = require('path');
const fs = require('fs');
+const os = require('os');
const helpersDir = __dirname;
+// Resolve an installed @claude-flow/cli (or ruflo) bin — mirrors
+// statusline-generator.ts's resolveCliBin() candidate list. Used only to
+// spawn the detached funnel-refresh helper below; failures are silent (no
+// candidate found just means the refresh never fires this session).
+function resolveCliBinForHook() {
+ try {
+ const home = os.homedir();
+ const cwd = process.cwd();
+ const candidates = [
+ 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'),
+ // helpersDir is .claude/helpers/ inside the package itself when this
+ // file is running from a real @claude-flow/cli install (not a project
+ // that merely copied the helper) — its bin/ is two levels up.
+ path.join(helpersDir, '..', '..', 'bin', 'cli.js'),
+ ];
+ for (const p of candidates) {
+ if (fs.existsSync(p)) return p;
+ }
+ } catch (e) { /* ignore */ }
+ return null;
+}
+
+// Fire-and-forget doesn't work when the CALLER is itself a short-lived
+// subprocess (confirmed live: two consecutive statusline renders 5s apart
+// both saw an empty funnel-messages-cache, because the async HTTPS fetch
+// inside a `void refreshRemoteMessages()` call gets killed when the spawning
+// process exits before the request completes). Spawning fully DETACHED +
+// unref'd decouples the refresh's lifetime from this hook's — it keeps
+// running (up to message-transport.ts's own 4s fetch timeout) even after
+// session-restore's own process has already exited, so it actually gets a
+// chance to write the cache. Never awaited here — must not add to
+// SessionStart's own timeout budget.
+function spawnDetachedFunnelRefresh() {
+ try {
+ const cliBin = resolveCliBinForHook();
+ if (!cliBin) return;
+ const { spawn } = require('child_process');
+ const child = spawn(process.execPath, [cliBin, 'hooks', 'refresh-funnel', '--quiet'], {
+ detached: true,
+ stdio: 'ignore',
+ env: process.env,
+ });
+ child.unref();
+ } catch (e) { /* best-effort only */ }
+}
+
+// Same detached/unref'd pattern as spawnDetachedFunnelRefresh() above, for
+// ADR-316's co-pilot advisor tip. Safe to call on EVERY session-restore:
+// refresh-advisor's own action checks consent + a 24h TTL BEFORE spending
+// anything, so an unconsented or already-fresh install is a fast no-op file
+// read, never a network call. Never awaited here — must not add to
+// SessionStart's own timeout budget.
+function spawnDetachedAdvisorRefresh() {
+ try {
+ const cliBin = resolveCliBinForHook();
+ if (!cliBin) return;
+ const { spawn } = require('child_process');
+ const child = spawn(process.execPath, [cliBin, 'hooks', 'refresh-advisor', '--quiet'], {
+ detached: true,
+ stdio: 'ignore',
+ env: process.env,
+ });
+ child.unref();
+ } catch (e) { /* best-effort only */ }
+}
+
// Safe require with stdout suppression - the helper modules have CLI
// sections that run unconditionally on require(), so we mute console
// during the require to prevent noisy output.
@@ -168,6 +238,57 @@ const handlers = {
} else {
console.log('[INFO] Router not available, using default routing');
}
+
+ // Rate-limit -> sponsored-capacity nudge (ADR-312/313). Fires here,
+ // client-side, BEFORE the API call this prompt would make — so it still
+ // reaches the transcript even if that call then fails from the rate
+ // limit. Cheap local file reads only; never a network call or a child
+ // process, so it cannot add latency to prompt submission.
+ try {
+ const rlFunnelEnv = process.env.RUFLO_FUNNEL;
+ const rlDisabledByEnv = rlFunnelEnv !== undefined && /^(0|false|off|no)$/i.test(String(rlFunnelEnv).trim());
+ const rlCiVars = ['CI', 'GITHUB_ACTIONS', 'GITLAB_CI', 'CIRCLECI', 'TRAVIS', 'BUILDKITE', 'JENKINS_URL', 'TEAMCITY_VERSION', 'TF_BUILD'];
+ const rlIsCi = rlCiVars.some((v) => {
+ const val = process.env[v];
+ return val !== undefined && val !== '' && val !== '0' && String(val).toLowerCase() !== 'false';
+ });
+ const rlHome = path.join(os.homedir(), '.ruflo');
+ let rlUserDisabled = false;
+ try {
+ const rlUserCfg = JSON.parse(fs.readFileSync(path.join(rlHome, 'funnel.json'), 'utf8'));
+ rlUserDisabled = !!(rlUserCfg && rlUserCfg.enabled === false);
+ } catch (e) { /* absent/malformed = not disabled */ }
+ let rlProjectDisabled = false;
+ try {
+ const rlProjCfg = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'claude-flow.config.json'), 'utf8'));
+ rlProjectDisabled = !!(rlProjCfg && rlProjCfg.funnel && rlProjCfg.funnel.enabled === false);
+ } catch (e) { /* absent/malformed = not disabled */ }
+
+ if (!rlDisabledByEnv && !rlIsCi && !rlUserDisabled && !rlProjectDisabled) {
+ let rlStatus = null;
+ try { rlStatus = JSON.parse(fs.readFileSync(path.join(rlHome, 'rate-limit-status.json'), 'utf8')); } catch (e) { /* not flagged */ }
+ let rlIsLimited = false;
+ if (rlStatus && rlStatus.limited) {
+ if (rlStatus.since) {
+ const rlSinceMs = Date.parse(rlStatus.since);
+ rlIsLimited = isNaN(rlSinceMs) ? true : (Date.now() - rlSinceMs) < 6 * 60 * 60 * 1000;
+ } else {
+ rlIsLimited = true;
+ }
+ }
+ if (rlIsLimited) {
+ let rlConsented = false;
+ try {
+ const rlConsentFile = JSON.parse(fs.readFileSync(path.join(rlHome, 'consent.json'), 'utf8'));
+ const rlReceipt = rlConsentFile && rlConsentFile['sponsored-downtime'];
+ rlConsented = !!(rlReceipt && rlReceipt.granted === true && rlReceipt.at !== null && rlReceipt.policyVersion === 1);
+ } catch (e) { /* not consented */ }
+ if (!rlConsented) {
+ console.log('[COGNITUM] Hit your Claude usage limit? Free sponsored capacity is available at cognitum.one/meta-llm — run: ruflo proxy sponsor-enable --yes');
+ }
+ }
+ }
+ } catch (e) { /* nudge must never break the hook */ }
},
'pre-bash': () => {
@@ -234,6 +355,14 @@ const handlers = {
console.log(`[INTELLIGENCE] Loaded ${initResult.nodes} patterns, ${initResult.edges} edges`);
}
}
+ // Warm the funnel message cache once per session (see
+ // spawnDetachedFunnelRefresh's doc comment for why this must happen
+ // here, detached, rather than as the statusline's own fire-and-forget).
+ spawnDetachedFunnelRefresh();
+ // ADR-316 co-pilot advisor tip — same detached pattern; cheap no-op
+ // when not consented or still within the 24h TTL (see refresh-advisor's
+ // own doc comment).
+ spawnDetachedAdvisorRefresh();
},
'session-end': async () => {
diff --git a/v3/@claude-flow/cli/.claude/helpers/statusline.cjs b/v3/@claude-flow/cli/.claude/helpers/statusline.cjs
index d5231eb041..5751c656f4 100644
--- a/v3/@claude-flow/cli/.claude/helpers/statusline.cjs
+++ b/v3/@claude-flow/cli/.claude/helpers/statusline.cjs
@@ -1,604 +1,870 @@
#!/usr/bin/env node
/**
- * RuFlo V3.5 Statusline Generator
- * Displays real-time V3 implementation progress and system status
+ * RuFlo V3 Statusline — delegation build (#2195)
*
- * Usage: node statusline.cjs [options]
+ * 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.
*
- * Options:
- * (default) Safe multi-line output with collision zone avoidance
- * --single Single-line output (completely avoids collision)
- * --unsafe Legacy multi-line without collision avoidance
- * --legacy Alias for --unsafe
- * --json JSON output with pretty printing
- * --compact JSON output without formatting
+ * 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.
*
- * Collision Zone Fix (Issue #985):
- * Claude Code writes its internal status (e.g., "7s • 1p") at absolute
- * terminal coordinates (columns 15-25 on second-to-last line). The safe
- * mode pads the collision line with spaces to push content past column 25.
+ * 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/).
*
- * IMPORTANT: This file uses .cjs extension to work in ES module projects.
- * The require() syntax is intentional for CommonJS compatibility.
+ * 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');
-const { execSync, execFileSync } = require('child_process');
-
-// Read the installed plugin version once at startup. Probe the plugin's own
-// install location first (`~/.claude/plugins/marketplaces/ruflo/package.json`),
-// then npm-style installs, then the source-checkout location. The previous
-// code hardcoded `RuFlo V3.5` in the header — so users on alpha.27+ still
-// saw V3.5 in the statusline even though `ruflo doctor` reported the real
-// version (#1951).
-let RUFLO_VERSION = '3.6';
-try {
- const home = os.homedir();
- const cwd = process.cwd();
- 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'),
- ];
- for (const p of pkgPaths) {
- if (!fs.existsSync(p)) continue;
- try {
- const pkg = JSON.parse(fs.readFileSync(p, 'utf-8'));
- if (pkg && typeof pkg.version === 'string' && pkg.version.length > 0) {
- RUFLO_VERSION = pkg.version;
- break;
- }
- } catch { /* malformed package.json — try next */ }
- }
-} catch { /* fall through to the hardcoded default */ }
// Configuration
const CONFIG = {
- enabled: true,
- showProgress: true,
- showSecurity: true,
- showSwarm: true,
- showHooks: true,
- showPerformance: true,
- refreshInterval: 5000,
maxAgents: 15,
- topology: 'hierarchical-mesh',
+ // 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 || ''),
};
-// Cross-platform helpers
-const isWindows = process.platform === 'win32';
-const nullDevice = isWindows ? 'NUL' : '/dev/null';
-
-// 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',
-};
+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.
+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;
+
+// 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 { return fs.existsSync(p); } catch { return false; } });
+}
-// Get user info
-function getUserInfo() {
- let name = 'user';
- let gitBranch = '';
- let modelName = 'Unknown';
-
- // audit_1776853149979: previously used execSync with a shell string. Switched
- // to execFileSync('git', argv) on both platforms so there is no shell
- // interpretation. Cross-platform behavior is preserved by relying on git's
- // own exit code instead of `|| echo` fallbacks: missing repo / no user.name
- // throws, caught below, defaults retained.
+// 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 {
- name = execFileSync('git', ['config', 'user.name'], { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || 'user';
- } catch { /* keep default */ }
+ 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 {
- gitBranch = execFileSync('git', ['branch', '--show-current'], { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
- } catch { /* keep empty */ }
+ 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 */ }
+}
- // Auto-detect model from Claude Code's config
+// 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 {
- const homedir = require('os').homedir();
- const claudeConfigPath = path.join(homedir, '.claude.json');
- if (fs.existsSync(claudeConfigPath)) {
- const claudeConfig = JSON.parse(fs.readFileSync(claudeConfigPath, 'utf-8'));
- // Try to find lastModelUsage - check current dir and parent dirs
- let lastModelUsage = null;
- const cwd = process.cwd();
- if (claudeConfig.projects) {
- // Try exact match first, then check if cwd starts with any project path
- for (const [projectPath, projectConfig] of Object.entries(claudeConfig.projects)) {
- if (cwd === projectPath || cwd.startsWith(projectPath + '/')) {
- lastModelUsage = projectConfig.lastModelUsage;
- break;
- }
- }
- }
- if (lastModelUsage) {
- const modelIds = Object.keys(lastModelUsage);
- if (modelIds.length > 0) {
- // Take the last model (most recently added to the object)
- // Or find the one with most tokens (most actively used this session)
- let modelId = modelIds[modelIds.length - 1];
- if (modelIds.length > 1) {
- // If multiple models, pick the one with most total tokens
- let maxTokens = 0;
- for (const id of modelIds) {
- const usage = lastModelUsage[id];
- const total = (usage.inputTokens || 0) + (usage.outputTokens || 0);
- if (total > maxTokens) {
- maxTokens = total;
- modelId = id;
- }
- }
- }
- // Parse model ID to human-readable name
- if (modelId.includes('opus')) modelName = 'Opus 4.6 (1M context)';
- else if (modelId.includes('sonnet')) modelName = 'Sonnet 4.6';
- else if (modelId.includes('haiku')) modelName = 'Haiku 4.5';
- else modelName = modelId.split('-').slice(1, 3).join(' ');
- }
- }
+ 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 (e) {
- // Fallback to Unknown if can't read config
- }
+ } catch { /* ignore */ }
+ return null;
+}
- return { name, gitBranch, modelName };
+/**
+ * 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;
}
-// Get learning stats from intelligence loop data (ADR-050)
-function getLearningStats() {
- let patterns = 0;
- let sessions = 0;
- let trajectories = 0;
- let edges = 0;
- let confidenceMean = 0;
- let accessedCount = 0;
- let trend = 'STABLE';
-
- // PRIMARY: Read from intelligence loop data files
- const dataDir = path.join(process.cwd(), '.claude-flow', 'data');
-
- // 1. graph-state.json — authoritative node/edge counts
- const graphPath = path.join(dataDir, 'graph-state.json');
- if (fs.existsSync(graphPath)) {
+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.
+ const cmds = resolveCliBinCandidates()
+ .map((bin) => '"' + process.execPath + '" "' + bin + '" hooks statusline --json 2>/dev/null')
+ .concat(['npx --prefer-offline @claude-flow/cli hooks statusline --json 2>/dev/null']);
+ for (const cmd of cmds) {
try {
- const graph = JSON.parse(fs.readFileSync(graphPath, 'utf-8'));
- patterns = graph.nodes ? Object.keys(graph.nodes).length : 0;
- edges = Array.isArray(graph.edges) ? graph.edges.length : 0;
- } catch (e) { /* ignore */ }
+ 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 */ }
}
- // 2. ranked-context.json — confidence and access data
- const rankedPath = path.join(dataDir, 'ranked-context.json');
- if (fs.existsSync(rankedPath)) {
- try {
- const ranked = JSON.parse(fs.readFileSync(rankedPath, 'utf-8'));
- if (ranked.entries && ranked.entries.length > 0) {
- patterns = Math.max(patterns, ranked.entries.length);
- let confSum = 0;
- let accCount = 0;
- for (let i = 0; i < ranked.entries.length; i++) {
- confSum += (ranked.entries[i].confidence || 0);
- if ((ranked.entries[i].accessCount || 0) > 0) accCount++;
- }
- confidenceMean = confSum / ranked.entries.length;
- accessedCount = accCount;
- }
- } catch (e) { /* ignore */ }
+ // 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;
}
- // 3. intelligence-snapshot.json — trend history
- const snapshotPath = path.join(dataDir, 'intelligence-snapshot.json');
- if (fs.existsSync(snapshotPath)) {
+ // 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 {
- const snapshot = JSON.parse(fs.readFileSync(snapshotPath, 'utf-8'));
- if (snapshot.history && snapshot.history.length >= 2) {
- const first = snapshot.history[0];
- const last = snapshot.history[snapshot.history.length - 1];
- const confDrift = (last.confidenceMean || 0) - (first.confidenceMean || 0);
- trend = confDrift > 0.01 ? 'IMPROVING' : confDrift < -0.01 ? 'DECLINING' : 'STABLE';
- sessions = Math.max(sessions, snapshot.history.length);
+ 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 (e) { /* ignore */ }
+ } catch { /* ignore */ }
}
+ return { count: total, implemented: total, compliance: 0 };
+}
- // 4. auto-memory-store.json — fallback entry count
- if (patterns === 0) {
- const autoMemPath = path.join(dataDir, 'auto-memory-store.json');
- if (fs.existsSync(autoMemPath)) {
- try {
- const data = JSON.parse(fs.readFileSync(autoMemPath, 'utf-8'));
- patterns = Array.isArray(data) ? data.length : (data.entries ? data.entries.length : 0);
- } catch (e) { /* ignore */ }
- }
- }
+// ─── 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.
- // FALLBACK: Legacy memory.db file-size estimation
- if (patterns === 0) {
- const memoryPaths = [
- path.join(process.cwd(), '.swarm', 'memory.db'),
- path.join(process.cwd(), '.claude', 'memory.db'),
- path.join(process.cwd(), 'data', 'memory.db'),
- ];
- for (let j = 0; j < memoryPaths.length; j++) {
- if (fs.existsSync(memoryPaths[j])) {
- try {
- const dbStats = fs.statSync(memoryPaths[j]);
- patterns = Math.floor(dbStats.size / 1024 / 2);
- break;
- } catch (e) { /* ignore */ }
- }
+// 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;
+}
- // Session count from session files
- const sessionsPath = path.join(process.cwd(), '.claude', 'sessions');
- if (fs.existsSync(sessionsPath)) {
+// 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 {
- const sessionFiles = fs.readdirSync(sessionsPath).filter(f => f.endsWith('.json'));
- sessions = Math.max(sessions, sessionFiles.length);
- } catch (e) { /* ignore */ }
+ 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 };
+}
- trajectories = Math.floor(patterns / 5);
+// 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;
+}
- return { patterns, sessions, trajectories, edges, confidenceMean, accessedCount, trend };
+// 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;
}
-// Get V3 progress from learning state (grows as system learns)
-function getV3Progress() {
- const learning = getLearningStats();
-
- // DDD progress based on actual learned patterns
- // New install: 0 patterns = 0/5 domains, 0% DDD
- // As patterns grow: 10+ patterns = 1 domain, 50+ = 2, 100+ = 3, 200+ = 4, 500+ = 5
- let domainsCompleted = 0;
- if (learning.patterns >= 500) domainsCompleted = 5;
- else if (learning.patterns >= 200) domainsCompleted = 4;
- else if (learning.patterns >= 100) domainsCompleted = 3;
- else if (learning.patterns >= 50) domainsCompleted = 2;
- else if (learning.patterns >= 10) domainsCompleted = 1;
-
- const totalDomains = 5;
- const dddProgress = Math.min(100, Math.floor((domainsCompleted / totalDomains) * 100));
-
- return {
- domainsCompleted,
- totalDomains,
- dddProgress,
- patternsLearned: learning.patterns,
- sessionsCompleted: learning.sessions
- };
+// 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;
}
-// Get security status based on actual scans
-function getSecurityStatus() {
- // Check for security scan results in memory
- const scanResultsPath = path.join(process.cwd(), '.claude', 'security-scans');
- let cvesFixed = 0;
- const totalCves = 3;
+// 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(),
+ });
+}
- if (fs.existsSync(scanResultsPath)) {
- try {
- const scans = fs.readdirSync(scanResultsPath).filter(f => f.endsWith('.json'));
- // Each successful scan file = 1 CVE addressed
- cvesFixed = Math.min(totalCves, scans.length);
- } catch (e) {
- // Ignore
- }
+// 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 '';
}
+}
- // Also check .swarm/security for audit results
- const auditPath = path.join(process.cwd(), '.swarm', 'security');
- if (fs.existsSync(auditPath)) {
- try {
- const audits = fs.readdirSync(auditPath).filter(f => f.includes('audit'));
- cvesFixed = Math.min(totalCves, Math.max(cvesFixed, audits.length));
- } catch (e) {
- // Ignore
+// Safe JSON file reader (returns null on failure)
+function readJSON(filePath) {
+ try {
+ if (fs.existsSync(filePath)) {
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
}
- }
+ } catch { /* ignore */ }
+ return null;
+}
- const status = cvesFixed >= totalCves ? 'CLEAN' : cvesFixed > 0 ? 'IN_PROGRESS' : 'PENDING';
+// ─── Git info (pure-Node / single exec — needed for branch display) ──────────
- return {
- status,
- cvesFixed,
- totalCves,
+function getGitInfo() {
+ const result = {
+ name: 'user', gitBranch: '', modified: 0, untracked: 0,
+ staged: 0, ahead: 0, behind: 0,
};
-}
-
-// Get swarm status
-function getSwarmStatus() {
- let activeAgents = 0;
- let coordinationActive = false;
- try {
- if (isWindows) {
- // Windows: use tasklist and findstr
- const ps = execSync('tasklist 2>NUL | findstr /I "agentic-flow" 2>NUL | find /C /V "" 2>NUL || echo 0', { encoding: 'utf-8' });
- activeAgents = Math.max(0, parseInt(ps.trim()) || 0);
- } else {
- const ps = execSync('ps aux 2>/dev/null | grep -c agentic-flow || echo "0"', { encoding: 'utf-8' });
- activeAgents = Math.max(0, parseInt(ps.trim()) - 1);
+ 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++;
+ }
}
- coordinationActive = activeAgents > 0;
- } catch (e) {
- // Ignore errors - default to 0 agents
+
+ const ab = (parts[3] || '0 0').split(/\s+/);
+ result.ahead = parseInt(ab[0]) || 0;
+ result.behind = parseInt(ab[1]) || 0;
}
- return {
- activeAgents,
- maxAgents: CONFIG.maxAgents,
- coordinationActive,
- };
+ return result;
}
-// Get system metrics (dynamic based on actual state)
-function getSystemMetrics() {
- let memoryMB = 0;
- let subAgents = 0;
-
+// Detect model name from Claude config (pure file reads, no exec)
+function getModelName() {
try {
- if (isWindows) {
- // Windows: use tasklist for memory info, fallback to process.memoryUsage
- // tasklist memory column is complex to parse, use Node.js API instead
- memoryMB = Math.floor(process.memoryUsage().heapUsed / 1024 / 1024);
- } else {
- const mem = execSync('ps aux | grep -E "(node|agentic|claude)" | grep -v grep | awk \'{sum += $6} END {print int(sum/1024)}\'', { encoding: 'utf-8' });
- memoryMB = parseInt(mem.trim()) || 0;
+ 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 (e) {
- // Fallback
- memoryMB = Math.floor(process.memoryUsage().heapUsed / 1024 / 1024);
+ } 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';
+}
- // Get learning stats for intelligence %
- const learning = getLearningStats();
-
- // Intelligence % from REAL intelligence loop data (ADR-050)
- // Composite: 40% confidence mean + 30% access ratio + 30% pattern density
- let intelligencePct = 0;
- if (learning.confidenceMean > 0 || (learning.patterns > 0 && learning.accessedCount > 0)) {
- const confScore = Math.min(100, Math.floor(learning.confidenceMean * 100));
- const accessRatio = learning.patterns > 0 ? (learning.accessedCount / learning.patterns) : 0;
- const accessScore = Math.min(100, Math.floor(accessRatio * 100));
- const densityScore = Math.min(100, Math.floor(learning.patterns / 5));
- intelligencePct = Math.floor(confScore * 0.4 + accessScore * 0.3 + densityScore * 0.3);
+// ─── 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;
+ } catch {
+ _stdinData = null;
}
- // Fallback: legacy pattern count
- if (intelligencePct === 0 && learning.patterns > 0) {
- intelligencePct = Math.min(100, Math.floor(learning.patterns / 10));
+ 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;
+}
- // Context % based on session history
- const contextPct = Math.min(100, Math.floor(learning.sessions * 5));
+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;
+}
- // Count active sub-agents from process list
+// Read package version from the first package.json we find.
+function getPkgVersion() {
+ let ver = '3.6';
try {
- if (isWindows) {
- // Windows: use tasklist and findstr for agent counting
- const agents = execSync('tasklist 2>NUL | findstr /I "claude-flow" 2>NUL | find /C /V "" 2>NUL || echo 0', { encoding: 'utf-8' });
- subAgents = Math.max(0, parseInt(agents.trim()) || 0);
- } else {
- const agents = execSync('ps aux 2>/dev/null | grep -c "claude-flow.*agent" || echo "0"', { encoding: 'utf-8' });
- subAgents = Math.max(0, parseInt(agents.trim()) - 1);
+ 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 */ }
+ for (const p of pkgPaths) {
+ if (!fs.existsSync(p)) continue;
+ try {
+ const pkg = JSON.parse(fs.readFileSync(p, 'utf-8'));
+ if (pkg && typeof pkg.version === 'string' && pkg.version.length > 0) { ver = pkg.version; break; }
+ } catch { /* ignore */ }
}
- } catch (e) {
- // Ignore - default to 0
- }
-
- return {
- memoryMB,
- contextPct,
- intelligencePct,
- subAgents,
- };
+ } catch { /* ignore */ }
+ return ver;
}
-// Generate progress bar
+// ─── Rendering ──────────────────────────────────────────────────
+
function progressBar(current, total) {
const width = 5;
const filled = Math.round((current / total) * width);
- const empty = width - filled;
- return '[' + '\u25CF'.repeat(filled) + '\u25CB'.repeat(empty) + ']';
+ return '[' + '●'.repeat(filled) + '○'.repeat(width - filled) + ']';
}
-// Generate full statusline
function generateStatusline() {
- const user = getUserInfo();
- const progress = getV3Progress();
- const security = getSecurityStatus();
- const swarm = getSwarmStatus();
- const system = getSystemMetrics();
+ 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 = [];
- // Header Line
- let header = `${c.bold}${c.brightPurple}▊ RuFlo V${RUFLO_VERSION} ${c.reset}`;
- header += `${swarm.coordinationActive ? c.brightCyan : c.dim}● ${c.brightCyan}${user.name}${c.reset}`;
- if (user.gitBranch) {
- header += ` ${c.dim}│${c.reset} ${c.brightBlue}⎇ ${user.gitBranch}${c.reset}`;
+ // 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;
}
- header += ` ${c.dim}│${c.reset} ${c.purple}${user.modelName}${c.reset}`;
lines.push(header);
- // Separator
- lines.push(`${c.dim}─────────────────────────────────────────────────────${c.reset}`);
-
- // Line 1: DDD Domain Progress
- const domainsColor = progress.domainsCompleted >= 3 ? c.brightGreen : progress.domainsCompleted > 0 ? c.yellow : c.red;
- lines.push(
- `${c.brightCyan}🏗️ DDD Domains${c.reset} ${progressBar(progress.domainsCompleted, progress.totalDomains)} ` +
- `${domainsColor}${progress.domainsCompleted}${c.reset}/${c.brightWhite}${progress.totalDomains}${c.reset} ` +
- `${c.brightYellow}⚡ 1.0x${c.reset} ${c.dim}→${c.reset} ${c.brightYellow}2.49x-7.47x${c.reset}`
- );
-
- // Line 2: Swarm + CVE + Memory + Context + Intelligence
- const swarmIndicator = swarm.coordinationActive ? `${c.brightGreen}◉${c.reset}` : `${c.dim}○${c.reset}`;
- const agentsColor = swarm.activeAgents > 0 ? c.brightGreen : c.red;
- let securityIcon = security.status === 'CLEAN' ? '🟢' : security.status === 'IN_PROGRESS' ? '🟡' : '🔴';
- let securityColor = security.status === 'CLEAN' ? c.brightGreen : security.status === 'IN_PROGRESS' ? c.brightYellow : c.brightRed;
-
- lines.push(
- `${c.brightYellow}🤖 Swarm${c.reset} ${swarmIndicator} [${agentsColor}${String(swarm.activeAgents).padStart(2)}${c.reset}/${c.brightWhite}${swarm.maxAgents}${c.reset}] ` +
- `${c.brightPurple}👥 ${system.subAgents}${c.reset} ` +
- `${securityIcon} ${securityColor}CVE ${security.cvesFixed}${c.reset}/${c.brightWhite}${security.totalCves}${c.reset} ` +
- `${c.brightCyan}💾 ${system.memoryMB}MB${c.reset} ` +
- `${c.brightGreen}📂 ${String(system.contextPct).padStart(3)}%${c.reset} ` +
- `${c.dim}🧠 ${String(system.intelligencePct).padStart(3)}%${c.reset}`
- );
-
- // Line 3: Architecture status
- const dddColor = progress.dddProgress >= 50 ? c.brightGreen : progress.dddProgress > 0 ? c.yellow : c.red;
- lines.push(
- `${c.brightPurple}🔧 Architecture${c.reset} ` +
- `${c.cyan}DDD${c.reset} ${dddColor}●${String(progress.dddProgress).padStart(3)}%${c.reset} ${c.dim}│${c.reset} ` +
- `${c.cyan}Security${c.reset} ${securityColor}●${security.status}${c.reset} ${c.dim}│${c.reset} ` +
- `${c.cyan}Memory${c.reset} ${c.brightGreen}●AgentDB${c.reset} ${c.dim}│${c.reset} ` +
- `${c.cyan}Integration${c.reset} ${swarm.coordinationActive ? c.brightCyan : c.dim}●${c.reset}`
- );
-
- return lines.join('\n');
-}
+ // ─── 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);
+ }
+ }
+ 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);
+ }
-// Generate JSON data
-function generateJSON() {
- return {
- user: getUserInfo(),
- v3Progress: getV3Progress(),
- security: getSecurityStatus(),
- swarm: getSwarmStatus(),
- system: getSystemMetrics(),
- performance: {
- flashAttentionTarget: '2.49x-7.47x',
- searchImprovement: '150x-12,500x',
- memoryReduction: '50-75%',
- },
- lastUpdated: new Date().toISOString(),
- };
+ // 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';
}
-/**
- * Generate single-line output for Claude Code compatibility
- * This avoids the collision zone issue entirely by using one line
- * @see https://github.com/ruvnet/claude-flow/issues/985
- */
-function generateSingleLine() {
- if (!CONFIG.enabled) return '';
-
- const user = getUserInfo();
- const progress = getV3Progress();
- const security = getSecurityStatus();
- const swarm = getSwarmStatus();
- const system = getSystemMetrics();
-
- const swarmIndicator = swarm.coordinationActive ? '●' : '○';
- const securityStatus = security.status === 'CLEAN' ? '✓' :
- security.cvesFixed > 0 ? '~' : '✗';
-
- return `${c.brightPurple}RuFlo${c.reset} ${c.dim}|${c.reset} ` +
- `${c.cyan}D:${progress.domainsCompleted}/${progress.totalDomains}${c.reset} ${c.dim}|${c.reset} ` +
- `${c.yellow}S:${swarmIndicator}${swarm.activeAgents}/${swarm.maxAgents}${c.reset} ${c.dim}|${c.reset} ` +
- `${security.status === 'CLEAN' ? c.green : c.red}CVE:${securityStatus}${security.cvesFixed}/${security.totalCves}${c.reset} ${c.dim}|${c.reset} ` +
- `${c.dim}🧠${system.intelligencePct}%${c.reset}`;
+// ─── 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;
}
-/**
- * Generate safe multi-line statusline that avoids Claude Code collision zone
- * The collision zone is columns 15-25 on the second-to-last line.
- * We pad that line with spaces to push content past column 25.
- * @see https://github.com/ruvnet/claude-flow/issues/985
- */
-function generateSafeStatusline() {
- if (!CONFIG.enabled) return '';
-
- const user = getUserInfo();
- const progress = getV3Progress();
- const security = getSecurityStatus();
- const swarm = getSwarmStatus();
- const system = getSystemMetrics();
- const lines = [];
+// 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 + '\\';
+}
- // Header Line
- let header = `${c.bold}${c.brightPurple}▊ RuFlo V${RUFLO_VERSION} ${c.reset}`;
- header += `${swarm.coordinationActive ? c.brightCyan : c.dim}● ${c.brightCyan}${user.name}${c.reset}`;
- if (user.gitBranch) {
- header += ` ${c.dim}│${c.reset} ${c.brightBlue}⎇ ${user.gitBranch}${c.reset}`;
+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
}
- header += ` ${c.dim}│${c.reset} ${c.purple}${user.modelName}${c.reset}`;
- lines.push(header);
+}
- // Separator
- lines.push(`${c.dim}─────────────────────────────────────────────────────${c.reset}`);
-
- // Line 1: DDD Domain Progress
- const domainsColor = progress.domainsCompleted >= 3 ? c.brightGreen : progress.domainsCompleted > 0 ? c.yellow : c.red;
- lines.push(
- `${c.brightCyan}🏗️ DDD Domains${c.reset} ${progressBar(progress.domainsCompleted, progress.totalDomains)} ` +
- `${domainsColor}${progress.domainsCompleted}${c.reset}/${c.brightWhite}${progress.totalDomains}${c.reset} ` +
- `${c.brightYellow}⚡ 1.0x${c.reset} ${c.dim}→${c.reset} ${c.brightYellow}2.49x-7.47x${c.reset}`
- );
-
- // Line 2 (COLLISION LINE): Swarm status with padding after label
- // The emoji+label is ~10 columns. Padding pushes content past collision zone (cols 15-25)
- const swarmIndicator = swarm.coordinationActive ? `${c.brightGreen}◉${c.reset}` : `${c.dim}○${c.reset}`;
- const agentsColor = swarm.activeAgents > 0 ? c.brightGreen : c.red;
- let securityIcon = security.status === 'CLEAN' ? '🟢' : security.status === 'IN_PROGRESS' ? '🟡' : '🔴';
- let securityColor = security.status === 'CLEAN' ? c.brightGreen : security.status === 'IN_PROGRESS' ? c.brightYellow : c.brightRed;
-
- // Padding after "🤖 Swarm" (emoji 2 cols + " Swarm" 6 cols = 8, pad 18 to reach col 26)
- lines.push(
- `${c.brightYellow}🤖 Swarm${c.reset} ` + // 18 spaces padding
- `${swarmIndicator} [${agentsColor}${String(swarm.activeAgents).padStart(2)}${c.reset}/${c.brightWhite}${swarm.maxAgents}${c.reset}] ` +
- `${c.brightPurple}👥 ${system.subAgents}${c.reset} ` +
- `${securityIcon} ${securityColor}CVE ${security.cvesFixed}${c.reset}/${c.brightWhite}${security.totalCves}${c.reset} ` +
- `${c.brightCyan}💾 ${system.memoryMB}MB${c.reset} ` +
- `${c.dim}🧠 ${system.intelligencePct}%${c.reset}`
- );
-
- // Line 3: Architecture status (this is the last line, not in collision zone)
- const dddColor = progress.dddProgress >= 50 ? c.brightGreen : progress.dddProgress > 0 ? c.yellow : c.red;
- lines.push(
- `${c.brightPurple}🔧 Architecture${c.reset} ` +
- `${c.cyan}DDD${c.reset} ${dddColor}●${String(progress.dddProgress).padStart(3)}%${c.reset} ${c.dim}│${c.reset} ` +
- `${c.cyan}Security${c.reset} ${securityColor}●${security.status}${c.reset} ${c.dim}│${c.reset} ` +
- `${c.cyan}Memory${c.reset} ${c.brightGreen}●AgentDB${c.reset} ${c.dim}│${c.reset} ` +
- `${c.cyan}Integration${c.reset} ${swarm.coordinationActive ? c.brightCyan : c.dim}●${c.reset}`
- );
-
- return lines.join('\n');
+// 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
+// ─── 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 if (process.argv.includes('--single')) {
- // Single-line mode - completely avoids collision zone
- console.log(generateSingleLine());
-} else if (process.argv.includes('--unsafe') || process.argv.includes('--legacy')) {
- // Legacy mode - original multi-line without collision avoidance
- console.log(generateStatusline());
} else {
- // Default: Safe multi-line mode with collision zone avoidance
- // Use --unsafe or --legacy to get the original behavior
- console.log(generateSafeStatusline());
+ console.log(generateStatusline());
}
diff --git a/v3/@claude-flow/cli/__tests__/advisor-tip.test.ts b/v3/@claude-flow/cli/__tests__/advisor-tip.test.ts
new file mode 100644
index 0000000000..e4a74a5863
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/advisor-tip.test.ts
@@ -0,0 +1,143 @@
+/**
+ * advisor-tip.ts — ADR-316 co-pilot advisor tip.
+ *
+ * Every test injects a fake FableHarness-shaped object (or a fully
+ * constructed FableHarness with an injected spawnClaude) so no test ever
+ * shells out to `claude` or spends a cent. Coverage:
+ * • consent gate (never refreshes without 'advisor-tips' consent)
+ * • TTL gate (never re-spends within ADVISOR_REFRESH_TTL_MS)
+ * • cache read/write shape, including the "no-tip" case (still stamps
+ * _ts so a "nothing to say" answer isn't re-asked all window long)
+ * • readAdvisorTip() is a pure, synchronous cache reader — TTL-expired
+ * entries return null
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+
+import { recordConsent } from '../src/funnel/consent.js';
+import {
+ ADVISOR_REFRESH_TTL_MS,
+ readAdvisorTip,
+ refreshAdvisorTipIfStale,
+} from '../src/funnel/advisor-tip.js';
+import type { FableHarness as FableHarnessType } from '../src/services/fable-harness.js';
+
+let stateDir: string;
+let savedEnv: NodeJS.ProcessEnv;
+
+beforeEach(() => {
+ stateDir = fs.mkdtempSync(path.join(os.tmpdir(), 'advisor-tip-test-'));
+ savedEnv = { ...process.env };
+ process.env.RUFLO_STATE_DIR = stateDir;
+});
+
+afterEach(() => {
+ process.env = savedEnv;
+ fs.rmSync(stateDir, { recursive: true, force: true });
+});
+
+describe('refreshAdvisorTipIfStale — consent gate', () => {
+ it('never calls the harness without advisor-tips consent', async () => {
+ let called = false;
+ const harness = { adviseCoPilotTip: async () => { called = true; return null; } } as unknown as FableHarnessType;
+ const result = await refreshAdvisorTipIfStale({}, { harness });
+ expect(result).toEqual({ refreshed: false, reason: 'not-consented' });
+ expect(called).toBe(false);
+ });
+
+ it('calls the harness once consent is granted', async () => {
+ recordConsent('advisor-tips', true, 'test');
+ let called = false;
+ const harness = {
+ adviseCoPilotTip: async () => { called = true; return { headline: 'x', detail: 'y', confidence: 0.5 }; },
+ } as unknown as FableHarnessType;
+ const result = await refreshAdvisorTipIfStale({}, { harness });
+ expect(result).toEqual({ refreshed: true });
+ expect(called).toBe(true);
+ });
+});
+
+describe('refreshAdvisorTipIfStale — TTL gate (at most once per window)', () => {
+ it('does not re-spend within the TTL window', async () => {
+ recordConsent('advisor-tips', true, 'test');
+ let calls = 0;
+ const harness = {
+ adviseCoPilotTip: async () => { calls++; return { headline: 'tip', detail: 'd', confidence: 0.9 }; },
+ } as unknown as FableHarnessType;
+ const t0 = new Date(0);
+ const first = await refreshAdvisorTipIfStale({}, { now: t0, harness });
+ expect(first.refreshed).toBe(true);
+ expect(calls).toBe(1);
+
+ const stillFresh = new Date(t0.getTime() + ADVISOR_REFRESH_TTL_MS - 1000);
+ const second = await refreshAdvisorTipIfStale({}, { now: stillFresh, harness });
+ expect(second).toEqual({ refreshed: false, reason: 'fresh' });
+ expect(calls).toBe(1); // no second spawn
+ });
+
+ it('re-spends once the TTL window has elapsed', async () => {
+ recordConsent('advisor-tips', true, 'test');
+ let calls = 0;
+ const harness = {
+ adviseCoPilotTip: async () => { calls++; return { headline: 'tip', detail: 'd', confidence: 0.9 }; },
+ } as unknown as FableHarnessType;
+ const t0 = new Date(0);
+ await refreshAdvisorTipIfStale({}, { now: t0, harness });
+ const afterTtl = new Date(t0.getTime() + ADVISOR_REFRESH_TTL_MS + 1000);
+ const result = await refreshAdvisorTipIfStale({}, { now: afterTtl, harness });
+ expect(result.refreshed).toBe(true);
+ expect(calls).toBe(2);
+ });
+});
+
+describe('refreshAdvisorTipIfStale — cache write shape', () => {
+ it('writes headline+detail to the cache on a real tip', async () => {
+ recordConsent('advisor-tips', true, 'test');
+ const harness = {
+ adviseCoPilotTip: async () => ({ headline: 'Commit your work', detail: '50 files uncommitted.', confidence: 0.8 }),
+ } as unknown as FableHarnessType;
+ const now = new Date();
+ await refreshAdvisorTipIfStale({ gitUncommittedCount: 50 }, { now, harness });
+ const tip = readAdvisorTip(now);
+ expect(tip).toEqual({ headline: 'Commit your work', detail: '50 files uncommitted.' });
+ });
+
+ it('stamps the cache even when the model finds nothing worth surfacing (no re-ask within the window)', async () => {
+ recordConsent('advisor-tips', true, 'test');
+ let calls = 0;
+ const harness = { adviseCoPilotTip: async () => { calls++; return null; } } as unknown as FableHarnessType;
+ const now = new Date();
+ const first = await refreshAdvisorTipIfStale({}, { now, harness });
+ expect(first).toEqual({ refreshed: true, reason: 'no-tip' });
+ expect(readAdvisorTip(now)).toBeNull(); // nothing to show, but...
+ const second = await refreshAdvisorTipIfStale({}, { now: new Date(now.getTime() + 1000), harness });
+ expect(second).toEqual({ refreshed: false, reason: 'fresh' }); // ...not re-asked
+ expect(calls).toBe(1);
+ });
+
+ it('surfaces harness errors as refreshed:false without throwing', async () => {
+ recordConsent('advisor-tips', true, 'test');
+ const harness = { adviseCoPilotTip: async () => { throw new Error('spawn failed'); } } as unknown as FableHarnessType;
+ const result = await refreshAdvisorTipIfStale({}, { harness });
+ expect(result).toEqual({ refreshed: false, reason: 'error' });
+ });
+});
+
+describe('readAdvisorTip — pure cache reader', () => {
+ it('returns null when nothing has been cached', () => {
+ expect(readAdvisorTip()).toBeNull();
+ });
+
+ it('returns null for an expired cache entry', async () => {
+ recordConsent('advisor-tips', true, 'test');
+ const harness = {
+ adviseCoPilotTip: async () => ({ headline: 'tip', detail: 'd', confidence: 0.9 }),
+ } as unknown as FableHarnessType;
+ const t0 = new Date(0);
+ await refreshAdvisorTipIfStale({}, { now: t0, harness });
+ const expired = new Date(t0.getTime() + ADVISOR_REFRESH_TTL_MS + 1);
+ expect(readAdvisorTip(expired)).toBeNull();
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/daemon-autostart.test.ts b/v3/@claude-flow/cli/__tests__/daemon-autostart.test.ts
index 3e53dc8314..a8aa2cd428 100644
--- a/v3/@claude-flow/cli/__tests__/daemon-autostart.test.ts
+++ b/v3/@claude-flow/cli/__tests__/daemon-autostart.test.ts
@@ -52,6 +52,42 @@ describe('ensureDaemonRunning', () => {
expect(r.started).toBe(false);
expect(spawned).toBe(0);
});
+
+ it('respects a project-local claude-flow.config.json opt-out (survives env vars not propagating)', () => {
+ // The real-world gap this closes: a non-interactive shell never sources
+ // ~/.bashrc (its own top-of-file `case $- in *i*) ;; *) return;; esac`
+ // guard skips it outright), so `export RUFLO_DAEMON_AUTOSTART=0` in one
+ // such shell does not carry to the next command's shell. A file on disk
+ // has no such gap.
+ delete process.env.RUFLO_DAEMON_AUTOSTART;
+ const cwd = project();
+ writeFileSync(join(cwd, 'claude-flow.config.json'), JSON.stringify({ daemon: { autostart: false } }));
+ let spawned = 0;
+ const r = ensureDaemonRunning(cwd, { isAlive: () => false, spawnFn: () => { spawned++; } });
+ expect(r.started).toBe(false);
+ expect(r.reason).toMatch(/disabled/);
+ expect(spawned).toBe(0);
+ });
+
+ it('a malformed claude-flow.config.json is treated as not-disabled (fails open on parse errors, not silently blocking)', () => {
+ delete process.env.RUFLO_DAEMON_AUTOSTART;
+ const cwd = project();
+ writeFileSync(join(cwd, 'claude-flow.config.json'), 'this is not valid json {{{');
+ let spawned = 0;
+ const r = ensureDaemonRunning(cwd, { isAlive: () => false, spawnFn: () => { spawned++; } });
+ expect(r.started).toBe(true);
+ expect(spawned).toBe(1);
+ });
+
+ it('a config file present but without daemon.autostart:false does not disable it', () => {
+ delete process.env.RUFLO_DAEMON_AUTOSTART;
+ const cwd = project();
+ writeFileSync(join(cwd, 'claude-flow.config.json'), JSON.stringify({ funnel: { enabled: false } }));
+ let spawned = 0;
+ const r = ensureDaemonRunning(cwd, { isAlive: () => false, spawnFn: () => { spawned++; } });
+ expect(r.started).toBe(true);
+ expect(spawned).toBe(1);
+ });
});
describe('isDaemonAlive', () => {
diff --git a/v3/@claude-flow/cli/__tests__/funnel-e2e-live.test.ts b/v3/@claude-flow/cli/__tests__/funnel-e2e-live.test.ts
new file mode 100644
index 0000000000..0c58876c8e
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/funnel-e2e-live.test.ts
@@ -0,0 +1,159 @@
+/**
+ * Live end-to-end verification of the funnel analytics integration (ADR-308/311)
+ * against the REAL deployed GCP service (funnel.ruv.io -> cognitum-analytics
+ * Cloud Function -> Firestore, project cognitum-20260110).
+ *
+ * Every other funnel test (funnel.test.ts) deliberately stays network-free —
+ * this file is the one place that intentionally isn't, because "the client is
+ * wired to a remote contract" and "the remote contract actually works when
+ * you hit it for real" are different claims, and only this file proves the
+ * second one. Skipped by default (network + a live GCP dependency neither CI
+ * nor most local runs should require) — opt in with:
+ *
+ * RUFLO_FUNNEL_LIVE_E2E=1 npx vitest run __tests__/funnel-e2e-live.test.ts
+ *
+ * Every event this test posts uses messageId 'e2e-smoke-test' specifically so
+ * it's trivially identifiable and never collides with a real rotation-pool
+ * message id (real ids come from the seeded message pool, see
+ * ruflo-funnel-api/seed-messages.mjs). The afterAll hook best-effort deletes
+ * everything this test wrote, using the SAME Firestore REST endpoint gcloud
+ * ADC already authenticates against — if ADC isn't available the cleanup is
+ * skipped with a console.warn (never fails the run), same fail-open discipline
+ * as the transport code itself.
+ */
+import { describe, it, expect, afterAll } from 'vitest';
+import { randomUUID } from 'crypto';
+import { execSync } from 'child_process';
+
+const LIVE = process.env.RUFLO_FUNNEL_LIVE_E2E === '1';
+const PROJECT_ID = 'cognitum-20260110';
+const TEST_MESSAGE_ID = 'e2e-smoke-test';
+
+function getAccessToken(): string | null {
+ try {
+ return execSync('gcloud auth print-access-token', { encoding: 'utf-8', timeout: 5000 }).trim();
+ } catch {
+ return null;
+ }
+}
+
+async function firestoreQuery(collection: string, token: string): Promise<Array<{ name: string }>> {
+ const res = await fetch(
+ `https://firestore.googleapis.com/v1/projects/${PROJECT_ID}/databases/(default)/documents:runQuery`,
+ {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ structuredQuery: {
+ from: [{ collectionId: collection }],
+ where: {
+ fieldFilter: {
+ field: { fieldPath: 'messageId' },
+ op: 'EQUAL',
+ value: { stringValue: TEST_MESSAGE_ID },
+ },
+ },
+ limit: 20,
+ },
+ }),
+ },
+ );
+ const rows = (await res.json()) as Array<{ document?: { name: string } }>;
+ return rows.filter((r) => r.document).map((r) => ({ name: r.document!.name }));
+}
+
+async function firestoreDelete(docName: string, token: string): Promise<void> {
+ await fetch(`https://firestore.googleapis.com/v1/${docName}`, {
+ method: 'DELETE',
+ headers: { Authorization: `Bearer ${token}` },
+ });
+}
+
+describe.skipIf(!LIVE)('funnel analytics — LIVE end-to-end (real funnel.ruv.io + Firestore)', () => {
+ const writtenEventDocs: string[] = [];
+
+ it('POST /v1/events: a real promo_impression batch is accepted', async () => {
+ const batchId = `e2e-smoke-${randomUUID()}`;
+ const batch = {
+ batchId,
+ release: '3.25.6',
+ emittedAt: new Date().toISOString(),
+ events: [
+ {
+ schemaVersion: 1,
+ event: 'promo_impression',
+ surface: 'statusline',
+ release: '3.25.6',
+ messageId: TEST_MESSAGE_ID,
+ timestampBucket: new Date().toISOString().slice(0, 10),
+ },
+ ],
+ };
+
+ const res = await fetch('https://funnel.ruv.io/v1/events', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Idempotency-Key': batchId,
+ 'User-Agent': 'ruflo-funnel/3.25.6',
+ },
+ body: JSON.stringify(batch),
+ });
+
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { ok: boolean; accepted: number; dropped: number };
+ expect(body.ok).toBe(true);
+ expect(body.accepted).toBe(1);
+ expect(body.dropped).toBe(0);
+ });
+
+ it('GET /v1/click/{messageId}: redirects to the allowlisted target', async () => {
+ const to = encodeURIComponent('https://cognitum.one/?utm_source=e2e-smoke-test');
+ const res = await fetch(`https://funnel.ruv.io/v1/click/${TEST_MESSAGE_ID}?to=${to}`, {
+ redirect: 'manual',
+ });
+ expect(res.status).toBe(302);
+ expect(res.headers.get('location')).toBe('https://cognitum.one/?utm_source=e2e-smoke-test');
+ });
+
+ it('GET /v1/click with a non-allowlisted host is refused, not redirected', async () => {
+ const to = encodeURIComponent('https://evil-example-not-allowlisted.test/');
+ const res = await fetch(`https://funnel.ruv.io/v1/click/${TEST_MESSAGE_ID}?to=${to}`, {
+ redirect: 'manual',
+ });
+ // Must NOT be a 302 to the disallowed host — server-side allowlist (ADR-311 §7) must hold.
+ expect(res.status).not.toBe(302);
+ });
+
+ it('the impression and the click both actually landed in Firestore (funnel_events)', async () => {
+ const token = getAccessToken();
+ if (!token) {
+ console.warn('[funnel-e2e-live] gcloud ADC unavailable — skipping Firestore verification step');
+ return;
+ }
+ // Give the Cloud Function's Firestore writes a moment to become queryable.
+ await new Promise((r) => setTimeout(r, 3000));
+ const docs = await firestoreQuery('funnel_events', token);
+ writtenEventDocs.push(...docs.map((d) => d.name));
+ const events = docs.length; // both promo_impression (client POST) and promo_open (click redirect)
+ expect(events).toBeGreaterThanOrEqual(1);
+ });
+
+ afterAll(async () => {
+ const token = getAccessToken();
+ if (!token) {
+ console.warn('[funnel-e2e-live] gcloud ADC unavailable — leaving any test docs for manual cleanup');
+ return;
+ }
+ try {
+ // Re-query in case the last `it` above was skipped/short-circuited before populating writtenEventDocs.
+ const events = await firestoreQuery('funnel_events', token);
+ const aggregates = await firestoreQuery('funnel_aggregates', token);
+ for (const doc of [...events, ...aggregates]) {
+ await firestoreDelete(doc.name, token);
+ }
+ } catch (err) {
+ console.warn('[funnel-e2e-live] cleanup failed (non-fatal):', err);
+ }
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/funnel.test.ts b/v3/@claude-flow/cli/__tests__/funnel.test.ts
new file mode 100644
index 0000000000..89561e8a62
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/funnel.test.ts
@@ -0,0 +1,1300 @@
+/**
+ * Funnel release-gate invariants — ADR-301..310.
+ *
+ * Every test here maps to a hard gate in ADR-310:
+ * - promo output in CI: 0
+ * - promotional display before disclosure: 0
+ * - control-sequence injection through message copy: 0
+ * - lower-precedence source re-enabling a higher disable: 0
+ * - credit-recovery on anything but COGNITUM_CREDIT_EXHAUSTED: 0
+ * - funnel events without telemetry consent: 0
+ */
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+
+import {
+ isValidMessage,
+ isAllowedUrl,
+ containsForbiddenSequences,
+ displayWidth,
+ MESSAGES,
+ MAX_MESSAGE_COLUMNS,
+} from '../src/funnel/messages.js';
+import {
+ selectMessage,
+ ROTATION_SLOT_MS,
+ PROMO_SLOT_MODULO,
+ PROMO_REPEAT_CAP_MS,
+} from '../src/funnel/rotation.js';
+import { resolveFunnelEnabled } from '../src/funnel/precedence.js';
+import {
+ DISCLOSURE_GRACE_MS,
+ DISCLOSURE_ROTATION_SLOT_MS,
+ getDisclosure,
+ promoEligible,
+ recordDisclosureDeclined,
+ recordDisclosureShown,
+ selectDisclosureMessage,
+} from '../src/funnel/disclosure.js';
+import { getConsent, hasConsent, recordConsent } from '../src/funnel/consent.js';
+import { CONSENT_POLICY_VERSION, CreditErrorCode } from '../src/funnel/types.js';
+import {
+ classifyCreditError,
+ shouldShowCreditRecovery,
+ renderCreditRecovery,
+} from '../src/funnel/credit-errors.js';
+import { getFunnelId, recordFunnelEvent, deleteFunnelData } from '../src/funnel/events.js';
+import { attributionUrl } from '../src/funnel/attribution.js';
+import {
+ flushEvents,
+ DEFAULT_ENDPOINT,
+ MAX_BATCH,
+ MIN_FLUSH_INTERVAL_MS,
+ FLUSH_TIMEOUT_MS,
+} from '../src/funnel/event-transport.js';
+import {
+ markCreditExhausted,
+ clearCreditStatus,
+ readCreditStatus,
+ creditExhaustedNotice,
+} from '../src/funnel/credit-notifier.js';
+import { getFunnelPromo } from '../src/funnel/promo.js';
+import { isCI } from '../src/funnel/environment.js';
+import {
+ RATE_LIMIT_TTL_MS,
+ clearRateLimitStatus,
+ markRateLimited,
+ rateLimitNotice,
+ readRateLimitStatus,
+} from '../src/funnel/rate-limit-notifier.js';
+import {
+ QUOTA_LOW_TTL_MS,
+ clearQuotaLowStatus,
+ markQuotaLow,
+ quotaLowNotice,
+ readQuotaLowStatus,
+} from '../src/funnel/power-saver-notifier.js';
+import { TOGGLE_COOLDOWN_MS, cooldownActive, cooldownRemainingMin } from '../src/funnel/toggle-cooldown.js';
+import { computeLocalInsights, selectLocalInsight } from '../src/funnel/insights.js';
+import { shouldOfferEnrollment, recordEnrollmentOutcome, getEnrollmentRecord } from '../src/funnel/enrollment.js';
+import { generateStatuslineScript } from '../src/init/statusline-generator.js';
+
+let stateDir: string;
+let savedEnv: NodeJS.ProcessEnv;
+
+const CLEAN_ENV_KEYS = [
+ 'RUFLO_FUNNEL', 'RUFLO_ENTERPRISE_POLICY', 'CI', 'GITHUB_ACTIONS', 'GITLAB_CI',
+ 'CIRCLECI', 'TRAVIS', 'BUILDKITE', 'JENKINS_URL', 'TEAMCITY_VERSION', 'TF_BUILD',
+];
+
+beforeEach(() => {
+ stateDir = fs.mkdtempSync(path.join(os.tmpdir(), 'funnel-test-'));
+ savedEnv = { ...process.env };
+ process.env.RUFLO_STATE_DIR = stateDir;
+ for (const k of CLEAN_ENV_KEYS) delete process.env[k];
+});
+
+/**
+ * Seed the local remote-message cache exactly the way message-transport.ts's
+ * writeCache() would after a successful GET /v1/messages — ADR-311 makes
+ * this the ONLY content source (MESSAGES ships empty), so every test that
+ * exercises rotation/disclosure must seed this cache first.
+ */
+function seedRemoteMessages(messages: unknown[]): void {
+ fs.writeFileSync(
+ path.join(stateDir, 'funnel-messages-cache.json'),
+ JSON.stringify({ _ts: Date.now(), messages }),
+ 'utf-8',
+ );
+}
+
+const TEST_DISCLOSURE_POOL = [
+ { id: 'disclosure-1', schemaVersion: 1, class: 'disclosure', text: '✨ Tips, features and Cognitum updates here · manage: ruflo settings', url: 'https://cognitum.one/ruflo' },
+ { id: 'disclosure-2', schemaVersion: 1, class: 'disclosure', text: '✨ Additional AI capabilities from Cognitum · manage: ruflo settings', url: 'https://cognitum.one/ruflo' },
+ { id: 'disclosure-3', schemaVersion: 1, class: 'disclosure', text: '✨ Tips and Cognitum updates appear here · manage: ruflo settings', url: 'https://cognitum.one/ruflo' },
+];
+
+const TEST_ROTATION_POOL = [
+ { id: 'edu-test-1', schemaVersion: 1, class: 'educational', text: 'edu tip one' },
+ { id: 'edu-test-2', schemaVersion: 1, class: 'educational', text: 'edu tip two' },
+ { id: 'edu-test-3', schemaVersion: 1, class: 'educational', text: 'edu tip three' },
+ { id: 'edu-test-4', schemaVersion: 1, class: 'educational', text: 'edu tip four' },
+ { id: 'promo-test-1', schemaVersion: 1, class: 'promotional', text: 'promo one', url: 'https://cognitum.one' },
+];
+
+afterEach(() => {
+ process.env = savedEnv;
+ fs.rmSync(stateDir, { recursive: true, force: true });
+});
+
+// ─── ADR-301: signed content boundaries ─────────────────────────────────────
+
+describe('message content boundaries (ADR-301)', () => {
+ const base = { id: 'test', schemaVersion: 1 as const, class: 'educational' as const };
+
+ it('accepts a plain valid message', () => {
+ expect(isValidMessage({ ...base, text: 'hello world' })).toBe(true);
+ });
+
+ it('drops ANSI escape sequences', () => {
+ expect(isValidMessage({ ...base, text: 'hi \u001b[31mred\u001b[0m' })).toBe(false);
+ });
+
+ it('drops OSC sequences (terminal title / hyperlink injection)', () => {
+ expect(isValidMessage({ ...base, text: 'x\u001b]0;pwned\u0007' })).toBe(false);
+ });
+
+ it('drops C0/C1 control characters', () => {
+ expect(isValidMessage({ ...base, text: 'a\u0008b' })).toBe(false);
+ expect(isValidMessage({ ...base, text: 'a\u009bb' })).toBe(false);
+ });
+
+ it('drops bidirectional override characters', () => {
+ expect(isValidMessage({ ...base, text: 'a‮evil' })).toBe(false);
+ expect(isValidMessage({ ...base, text: 'a⁦evil⁩' })).toBe(false);
+ });
+
+ it('drops over-length messages instead of truncating', () => {
+ expect(isValidMessage({ ...base, text: 'x'.repeat(MAX_MESSAGE_COLUMNS + 1) })).toBe(false);
+ expect(isValidMessage({ ...base, text: 'x'.repeat(MAX_MESSAGE_COLUMNS) })).toBe(true);
+ });
+
+ it('counts wide characters as 2 columns', () => {
+ expect(displayWidth('あ')).toBe(2);
+ expect(displayWidth('ab')).toBe(2);
+ // 41 CJK chars = 82 display columns > 80 even though length is 41
+ expect(isValidMessage({ ...base, text: 'あ'.repeat(41) })).toBe(false);
+ });
+
+ it('drops wrong schema version and bad class', () => {
+ expect(isValidMessage({ ...base, schemaVersion: 2, text: 'x' })).toBe(false);
+ expect(isValidMessage({ ...base, class: 'urgent', text: 'x' })).toBe(false);
+ });
+
+ it('drops expired messages', () => {
+ const past = new Date(Date.now() - 1000).toISOString();
+ expect(isValidMessage({ ...base, text: 'x', expiresAt: past })).toBe(false);
+ });
+
+ it('URL allowlist: exact hosts only, https only, no lookalikes', () => {
+ expect(isAllowedUrl('https://cognitum.one/routing')).toBe(true);
+ expect(isAllowedUrl('https://github.com/ruvnet/ruflo')).toBe(true);
+ expect(isAllowedUrl('http://cognitum.one')).toBe(false); // not https
+ expect(isAllowedUrl('https://cognitum.one.evil.com')).toBe(false); // lookalike
+ expect(isAllowedUrl('https://evilcognitum.one')).toBe(false);
+ expect(isAllowedUrl('https://github.com/attacker/repo')).toBe(false); // wrong org
+ expect(isAllowedUrl('https://1.2.3.4/')).toBe(false); // IP literal
+ expect(isAllowedUrl('javascript:alert(1)')).toBe(false);
+ expect(isAllowedUrl('not a url')).toBe(false);
+ });
+
+ it('ships ZERO local messages (ADR-311 "zero local promo content" guarantee)', () => {
+ // The in-code MESSAGES pool is intentionally empty — all rotation
+ // content (tips, promos, disclosure) is remote-sourced. This test
+ // pins that guarantee; a future PR that adds a local message back
+ // in must consciously fail this test to do so.
+ expect(MESSAGES).toEqual([]);
+ });
+
+ it('a disclosure-class message without the manage tail is rejected, never repaired', () => {
+ const base = { id: 'disclosure-x', schemaVersion: 1 as const, class: 'disclosure' as const };
+ expect(isValidMessage({ ...base, text: '✨ Missing the tail entirely' })).toBe(false);
+ expect(isValidMessage({ ...base, text: '✨ Has it · manage: ruflo settings' })).toBe(true);
+ });
+
+ it('selectDisclosureMessage returns null when no remote disclosure pool is cached (fail-closed)', () => {
+ // No seedRemoteMessages() call — cache is empty, matching a cold start
+ // or an unreachable remote feed. Per ADR-311, this means "show nothing".
+ expect(selectDisclosureMessage(new Date())).toBeNull();
+ });
+
+ it('selectDisclosureMessage is deterministic per 5-minute slot once seeded', () => {
+ seedRemoteMessages(TEST_DISCLOSURE_POOL);
+ const t0 = new Date('2026-07-10T12:00:00.000Z');
+ const t0plus1s = new Date(t0.getTime() + 1000);
+ expect(selectDisclosureMessage(t0)?.id).toBe(selectDisclosureMessage(t0plus1s)?.id);
+ const seen = new Set<string>();
+ for (let i = 0; i < TEST_DISCLOSURE_POOL.length * 2; i++) {
+ seen.add(selectDisclosureMessage(new Date(t0.getTime() + i * DISCLOSURE_ROTATION_SLOT_MS))?.id ?? '');
+ }
+ // Rotation must cover every variant.
+ expect(seen.size).toBe(TEST_DISCLOSURE_POOL.length);
+ });
+});
+
+// ─── ADR-301: rotation ratio ────────────────────────────────────────────────
+
+describe('rotation scheduler (ADR-301 content ratio)', () => {
+ it('returns null when no remote pool is cached (fail-closed, ADR-311)', () => {
+ // No seedRemoteMessages() call — MESSAGES ships empty, so an unseeded
+ // cache means nothing to rotate through. This is deliberate, not a bug.
+ expect(selectMessage(new Date())).toBeNull();
+ });
+
+ it('promotional content appears only in 1-of-5 slots and honors the 30-min cap', () => {
+ seedRemoteMessages(TEST_ROTATION_POOL);
+ const base = Date.UTC(2026, 6, 10, 12, 0, 0);
+ let promos = 0;
+ let educational = 0;
+ const slots = 200; // 200 slots × 20s ≈ 66 minutes
+ for (let i = 0; i < slots; i++) {
+ const now = new Date(base + i * ROTATION_SLOT_MS);
+ const msg = selectMessage(now);
+ expect(msg).not.toBeNull();
+ if (msg!.class === 'promotional') {
+ promos++;
+ // structural ratio: promo only in the designated slot
+ const slot = Math.floor(now.getTime() / ROTATION_SLOT_MS);
+ expect(slot % PROMO_SLOT_MODULO).toBe(PROMO_SLOT_MODULO - 1);
+ } else {
+ educational++;
+ }
+ }
+ // 30-min repeat cap over ~66 minutes → at most 3 promos
+ const maxPromos = Math.floor((slots * ROTATION_SLOT_MS) / PROMO_REPEAT_CAP_MS) + 1;
+ expect(promos).toBeLessThanOrEqual(maxPromos);
+ expect(promos).toBeGreaterThan(0);
+ // ratio: far better than 4:1
+ expect(educational / Math.max(promos, 1)).toBeGreaterThanOrEqual(4);
+ });
+
+ it('is deterministic for a fixed time slot', () => {
+ seedRemoteMessages(TEST_ROTATION_POOL);
+ const now = new Date(Date.UTC(2026, 6, 10, 12, 0, 1));
+ const a = selectMessage(now);
+ const b = selectMessage(now);
+ expect(a?.id).toBe(b?.id);
+ });
+});
+
+// ─── ADR-305: control precedence ────────────────────────────────────────────
+
+describe('control precedence (ADR-305)', () => {
+ it('defaults to enabled by package default', () => {
+ expect(resolveFunnelEnabled(stateDir)).toEqual({ enabled: true, decidedBy: 'package-default' });
+ });
+
+ it('RUFLO_FUNNEL=0 disables at the top of the chain', () => {
+ for (const v of ['0', 'false', 'off', 'no', 'FALSE']) {
+ expect(resolveFunnelEnabled(stateDir, { ...process.env, RUFLO_FUNNEL: v }).decidedBy).toBe('env');
+ }
+ });
+
+ it('enterprise policy disables below env', () => {
+ const policyFile = path.join(stateDir, 'policy.json');
+ fs.writeFileSync(policyFile, JSON.stringify({ funnel: { enabled: false } }));
+ const decision = resolveFunnelEnabled(stateDir, { ...process.env, RUFLO_ENTERPRISE_POLICY: policyFile });
+ expect(decision).toEqual({ enabled: false, decidedBy: 'enterprise-policy' });
+ });
+
+ it('a lower-precedence source never re-enables a higher-precedence disable', () => {
+ // user config says enabled=true, env says off → env wins
+ fs.writeFileSync(path.join(stateDir, 'funnel.json'), JSON.stringify({ enabled: true }));
+ const decision = resolveFunnelEnabled(stateDir, { ...process.env, RUFLO_FUNNEL: '0' });
+ expect(decision.enabled).toBe(false);
+ expect(decision.decidedBy).toBe('env');
+ });
+
+ it('user config disable wins over project config and default', () => {
+ fs.writeFileSync(path.join(stateDir, 'funnel.json'), JSON.stringify({ enabled: false }));
+ expect(resolveFunnelEnabled(stateDir).decidedBy).toBe('user-config');
+ });
+
+ it('project claude-flow.config.json funnel.enabled=false disables', () => {
+ fs.writeFileSync(path.join(stateDir, 'claude-flow.config.json'), JSON.stringify({ funnel: { enabled: false } }));
+ expect(resolveFunnelEnabled(stateDir).decidedBy).toBe('project-config');
+ });
+
+ it('a stored remote policy can disable but sits at the bottom', () => {
+ fs.writeFileSync(path.join(stateDir, 'funnel-remote-policy.json'), JSON.stringify({ funnelEnabled: false }));
+ expect(resolveFunnelEnabled(stateDir).decidedBy).toBe('remote-policy');
+ // remote enable=true must NOT override user disable
+ fs.writeFileSync(path.join(stateDir, 'funnel-remote-policy.json'), JSON.stringify({ funnelEnabled: true }));
+ fs.writeFileSync(path.join(stateDir, 'funnel.json'), JSON.stringify({ enabled: false }));
+ expect(resolveFunnelEnabled(stateDir).decidedBy).toBe('user-config');
+ });
+});
+
+// ─── ADR-301: disclosure gate ───────────────────────────────────────────────
+
+describe('disclosure gate (ADR-301)', () => {
+ it('starts never_seen; no promo before disclosure', () => {
+ expect(getDisclosure().state).toBe('never_seen');
+ expect(promoEligible()).toBe(false);
+ });
+
+ it('first render records disclosed_enabled but promo waits for the grace window', () => {
+ const t0 = new Date();
+ recordDisclosureShown(t0);
+ expect(getDisclosure().state).toBe('disclosed_enabled');
+ expect(promoEligible(t0)).toBe(false);
+ expect(promoEligible(new Date(t0.getTime() + DISCLOSURE_GRACE_MS - 1000))).toBe(false);
+ expect(promoEligible(new Date(t0.getTime() + DISCLOSURE_GRACE_MS + 1000))).toBe(true);
+ });
+
+ it('declining disables all funnel surfaces through the precedence chain', () => {
+ recordDisclosureDeclined();
+ expect(getDisclosure().state).toBe('disclosed_disabled');
+ expect(promoEligible()).toBe(false);
+ expect(resolveFunnelEnabled(stateDir)).toEqual({ enabled: false, decidedBy: 'disclosure-declined' });
+ });
+});
+
+// ─── ADR-301/305: promo orchestrator gates ──────────────────────────────────
+
+describe('promo orchestrator (getFunnelPromo)', () => {
+ it('renders nothing in CI regardless of state', () => {
+ expect(getFunnelPromo({ interactive: true, env: { ...process.env, CI: 'true' } })).toBeNull();
+ expect(getFunnelPromo({ interactive: true, env: { ...process.env, GITHUB_ACTIONS: 'true' } })).toBeNull();
+ });
+
+ it('renders nothing when not interactive', () => {
+ expect(getFunnelPromo({ interactive: false })).toBeNull();
+ });
+
+ it('renders nothing when disabled by any precedence source', () => {
+ expect(getFunnelPromo({ interactive: true, env: { ...process.env, RUFLO_FUNNEL: '0' } })).toBeNull();
+ });
+
+ it('renders nothing on first render when no remote pool is cached (fail-closed, ADR-311)', () => {
+ // No seedRemoteMessages() — this is a cold start or an unreachable API.
+ // Zero local content means zero row, not a fallback to hardcoded text.
+ expect(getFunnelPromo({ interactive: true, cwd: stateDir })).toBeNull();
+ });
+
+ it('first interactive render is the disclosure, never a promotion', () => {
+ seedRemoteMessages(TEST_DISCLOSURE_POOL);
+ const row = getFunnelPromo({ interactive: true, cwd: stateDir });
+ expect(row).not.toBeNull();
+ expect(row!.kind).toBe('disclosure');
+ // Row text is one of the seeded disclosure variants.
+ expect(TEST_DISCLOSURE_POOL.map((m) => m.text)).toContain(row!.text);
+ // The URL is click-tracked (routes through the server redirect) — the
+ // real cognitum.one/ruflo target rides in the `to` query param.
+ expect(row!.url).toBeDefined();
+ const outer = new URL(row!.url!);
+ expect(outer.pathname).toMatch(/^\/v1\/click\/disclosure-\d+$/);
+ const to = outer.searchParams.get('to');
+ expect(to).toBeTruthy();
+ const parsed = new URL(to!);
+ expect(parsed.origin + parsed.pathname).toBe('https://cognitum.one/ruflo');
+ expect(parsed.searchParams.get('utm_source')).toBe('ruflo');
+ expect(parsed.searchParams.get('utm_medium')).toBe('statusline');
+ expect(parsed.searchParams.get('utm_campaign')).toBe('disclosure');
+ expect(parsed.searchParams.get('utm_content')).toMatch(/^disclosure-\d+$/);
+ // Without telemetry consent (default in this test suite), no fid rides along.
+ expect(parsed.searchParams.get('fid')).toBeNull();
+ });
+
+ it('keeps showing the disclosure through the grace window, then rotates messages', () => {
+ seedRemoteMessages([...TEST_DISCLOSURE_POOL, ...TEST_ROTATION_POOL]);
+ const t0 = new Date();
+ recordDisclosureShown(t0);
+ const during = getFunnelPromo({ interactive: true, cwd: stateDir, now: new Date(t0.getTime() + 1000) });
+ expect(during!.kind).toBe('disclosure');
+ const after = getFunnelPromo({
+ interactive: true,
+ cwd: stateDir,
+ now: new Date(t0.getTime() + DISCLOSURE_GRACE_MS + 60_000),
+ });
+ expect(after).not.toBeNull();
+ expect(['educational', 'promotional']).toContain(after!.kind);
+ });
+});
+
+// ─── ADR-302: consent receipts ──────────────────────────────────────────────
+
+describe('consent receipts (ADR-302)', () => {
+ it('unasked domains are not consented and have a null timestamp', () => {
+ expect(hasConsent('account')).toBe(false);
+ expect(getConsent('account').at).toBeNull();
+ });
+
+ it('records grant AND decline as decisions', () => {
+ recordConsent('account', true, 'post-init');
+ recordConsent('telemetry', false, 'post-init');
+ expect(hasConsent('account')).toBe(true);
+ expect(hasConsent('telemetry')).toBe(false);
+ expect(getConsent('telemetry').at).not.toBeNull(); // decline is recorded
+ });
+
+ it('a stale policyVersion is not consent (re-ask, never carry forward)', () => {
+ recordConsent('cloud-routing', true, 'test');
+ // simulate a policy bump by rewriting the receipt with an older version
+ const file = path.join(stateDir, 'consent.json');
+ const data = JSON.parse(fs.readFileSync(file, 'utf-8'));
+ data['cloud-routing'].policyVersion = CONSENT_POLICY_VERSION - 1;
+ fs.writeFileSync(file, JSON.stringify(data));
+ expect(hasConsent('cloud-routing')).toBe(false);
+ });
+
+ it('accepting account consent enables nothing else (domains are separate)', () => {
+ recordConsent('account', true, 'post-init');
+ expect(hasConsent('cloud-routing')).toBe(false);
+ expect(hasConsent('telemetry')).toBe(false);
+ expect(hasConsent('proxy-install')).toBe(false);
+ });
+});
+
+describe('training-data-sharing consent domain (ADR-315 Tier 2)', () => {
+ it('is unconsented by default, independent of sponsored-downtime', () => {
+ recordConsent('sponsored-downtime', true, 'proxy-sponsor-enable');
+ expect(hasConsent('sponsored-downtime')).toBe(true);
+ expect(hasConsent('training-data-sharing')).toBe(false);
+ });
+
+ it('granting sponsored-downtime never implicitly grants training-data-sharing', () => {
+ recordConsent('sponsored-downtime', true, 'proxy-sponsor-enable');
+ recordConsent('power-saver', true, 'proxy-power-saver-enable');
+ expect(hasConsent('training-data-sharing')).toBe(false);
+ });
+
+ it('records grant and decline as explicit decisions, same as every other domain', () => {
+ recordConsent('training-data-sharing', true, 'proxy-training-share-enable');
+ expect(hasConsent('training-data-sharing')).toBe(true);
+ recordConsent('training-data-sharing', false, 'proxy-training-share-disable');
+ expect(hasConsent('training-data-sharing')).toBe(false);
+ expect(getConsent('training-data-sharing').at).not.toBeNull(); // decline recorded, not absent
+ });
+
+ it('granting training-data-sharing does not implicitly grant sponsored-downtime', () => {
+ recordConsent('training-data-sharing', true, 'proxy-training-share-enable');
+ expect(hasConsent('sponsored-downtime')).toBe(false);
+ });
+
+ it('the funnel event schema accepts training_share_enabled/disabled once telemetry is consented', () => {
+ recordConsent('telemetry', true, 'test');
+ expect(recordFunnelEvent('training_share_enabled', 'statusline', '3.25.6')).toBe(true);
+ expect(recordFunnelEvent('training_share_disabled', 'statusline', '3.25.6')).toBe(true);
+ });
+});
+
+describe('advisor-tips consent domain (ADR-316)', () => {
+ it('is unconsented by default, independent of every other domain', () => {
+ recordConsent('sponsored-downtime', true, 'proxy-sponsor-enable');
+ recordConsent('power-saver', true, 'proxy-power-saver-enable');
+ recordConsent('training-data-sharing', true, 'proxy-training-share-enable');
+ expect(hasConsent('advisor-tips')).toBe(false);
+ });
+
+ it('granting advisor-tips does not implicitly grant any other domain', () => {
+ recordConsent('advisor-tips', true, 'advisor-enable');
+ expect(hasConsent('sponsored-downtime')).toBe(false);
+ expect(hasConsent('power-saver')).toBe(false);
+ expect(hasConsent('training-data-sharing')).toBe(false);
+ });
+
+ it('records grant and decline as explicit decisions', () => {
+ recordConsent('advisor-tips', true, 'advisor-enable');
+ expect(hasConsent('advisor-tips')).toBe(true);
+ recordConsent('advisor-tips', false, 'advisor-disable');
+ expect(hasConsent('advisor-tips')).toBe(false);
+ expect(getConsent('advisor-tips').at).not.toBeNull();
+ });
+
+ it('the funnel event schema accepts advisor_tip_enabled/disabled once telemetry is consented', () => {
+ recordConsent('telemetry', true, 'test');
+ expect(recordFunnelEvent('advisor_tip_enabled', 'statusline', '3.25.6')).toBe(true);
+ expect(recordFunnelEvent('advisor_tip_disabled', 'statusline', '3.25.6')).toBe(true);
+ });
+});
+
+// ─── ADR-303: credit-error classifier ───────────────────────────────────────
+
+describe('credit-error classifier (ADR-303, fail-closed)', () => {
+ it('only COGNITUM_CREDIT_EXHAUSTED triggers the recovery surface', () => {
+ const session = { creditPromptShown: false };
+ const fire = classifyCreditError({ providerCode: 'cognitum_credit_exhausted' });
+ expect(fire.code).toBe(CreditErrorCode.COGNITUM_CREDIT_EXHAUSTED);
+ expect(shouldShowCreditRecovery(fire, session)).toBe(true);
+
+ for (const code of ['insufficient_quota', 'rate_limit_exceeded', 'authentication_error', 'api_error']) {
+ const e = classifyCreditError({ providerCode: code });
+ expect(shouldShowCreditRecovery(e, session), `${code} must not fire`).toBe(false);
+ }
+ });
+
+ it('provider quota exhaustion maps to PROVIDER_QUOTA_EXHAUSTED, never Cognitum', () => {
+ const e = classifyCreditError({ providerCode: 'insufficient_quota' });
+ expect(e.code).toBe(CreditErrorCode.PROVIDER_QUOTA_EXHAUSTED);
+ });
+
+ it('unmapped codes stay unclassified with confidence 0', () => {
+ const e = classifyCreditError({ providerCode: 'weird_new_error' });
+ expect(e.code).toBeNull();
+ expect(e.confidence).toBe(0);
+ expect(shouldShowCreditRecovery(e, { creditPromptShown: false })).toBe(false);
+ });
+
+ it('a bare 429 with no code is ambiguous → unmapped', () => {
+ const e = classifyCreditError({ status: 429 });
+ expect(e.code).toBeNull();
+ expect(e.confidence).toBe(0);
+ });
+
+ it('never parses message text (only codes and status)', () => {
+ const e = classifyCreditError({
+ providerCode: undefined,
+ // message text saying "credits exhausted" is NOT a signal
+ } as never);
+ expect(e.code).toBeNull();
+ });
+
+ it('caps at one prompt per session', () => {
+ const fire = classifyCreditError({ providerCode: 'cognitum_credit_exhausted' });
+ expect(shouldShowCreditRecovery(fire, { creditPromptShown: true })).toBe(false);
+ });
+
+ it('recovery screen distinguishes signed-in vs signed-out', () => {
+ expect(renderCreditRecovery(false)).toContain('ruflo auth login');
+ expect(renderCreditRecovery(true)).toContain('ruflo proxy enable');
+ });
+});
+
+// ─── ADR-305/309: events, consent-gated, bucketed ───────────────────────────
+
+describe('funnel events (ADR-305/309)', () => {
+ it('records nothing without telemetry consent', () => {
+ expect(recordFunnelEvent('disclosure_shown', 'statusline', '3.25.6')).toBe(false);
+ expect(fs.existsSync(path.join(stateDir, 'funnel-events.jsonl'))).toBe(false);
+ expect(getFunnelId()).toBeNull();
+ });
+
+ it('with consent: daily buckets only, closed event set, pseudonymous id', () => {
+ recordConsent('telemetry', true, 'test');
+ expect(recordFunnelEvent('signup_opened', 'init', '3.25.6')).toBe(true);
+ const lines = fs.readFileSync(path.join(stateDir, 'funnel-events.jsonl'), 'utf-8').trim().split('\n');
+ const evt = JSON.parse(lines[0]);
+ expect(evt.timestampBucket).toMatch(/^\d{4}-\d{2}-\d{2}$/); // daily, no time
+ expect(evt.pseudonymousId).toMatch(/^[0-9a-f-]{36}$/);
+ expect(Object.keys(evt).sort()).toEqual(
+ ['event', 'pseudonymousId', 'release', 'schemaVersion', 'surface', 'timestampBucket'],
+ );
+ // unknown event names are rejected
+ expect(recordFunnelEvent('exfiltrate_prompts' as never, 'init', 'x')).toBe(false);
+ });
+
+ it('opt-out deletes the id and the queue', () => {
+ recordConsent('telemetry', true, 'test');
+ recordFunnelEvent('signup_opened', 'init', '3.25.6');
+ const id = getFunnelId();
+ expect(id).not.toBeNull();
+ deleteFunnelData();
+ expect(fs.existsSync(path.join(stateDir, 'funnel-events.jsonl'))).toBe(false);
+ expect(fs.existsSync(path.join(stateDir, 'funnel-id.json'))).toBe(false);
+ });
+});
+
+// ─── ADR-302: enrollment gates ──────────────────────────────────────────────
+
+describe('enrollment gates (ADR-302)', () => {
+ it('never offers in CI, with --no-signup, or when funnel is disabled', () => {
+ expect(shouldOfferEnrollment({ noSignup: true, cwd: stateDir })).toBe(false);
+ expect(shouldOfferEnrollment({ noSignup: false, cwd: stateDir, env: { ...process.env, CI: '1' } })).toBe(false);
+ expect(
+ shouldOfferEnrollment({ noSignup: false, cwd: stateDir, env: { ...process.env, RUFLO_FUNNEL: '0' } }),
+ ).toBe(false);
+ });
+
+ it('is one-time: any recorded outcome suppresses future offers', () => {
+ recordEnrollmentOutcome(false);
+ expect(getEnrollmentRecord()?.outcome).toBe('skipped');
+ expect(shouldOfferEnrollment({ noSignup: false, cwd: stateDir })).toBe(false);
+ });
+
+ it('accepting records ONLY the account consent domain', () => {
+ recordEnrollmentOutcome(true);
+ expect(hasConsent('account')).toBe(true);
+ expect(hasConsent('telemetry')).toBe(false);
+ expect(hasConsent('cloud-routing')).toBe(false);
+ });
+});
+
+// ─── environment gates ──────────────────────────────────────────────────────
+
+describe('CI detection', () => {
+ it('recognizes the common CI environments', () => {
+ for (const v of ['CI', 'GITHUB_ACTIONS', 'GITLAB_CI', 'JENKINS_URL', 'TF_BUILD']) {
+ expect(isCI({ [v]: 'true' } as NodeJS.ProcessEnv), v).toBe(true);
+ }
+ expect(isCI({} as NodeJS.ProcessEnv)).toBe(false);
+ expect(isCI({ CI: 'false' } as NodeJS.ProcessEnv)).toBe(false);
+ });
+});
+
+// ─── generated statusline renderer (defense-in-depth) ──────────────────────
+
+describe('generated statusline promo row', () => {
+ const script = generateStatuslineScript({
+ runtime: { maxAgents: 8 },
+ statusline: { enabled: true },
+ } as never);
+
+ it('embeds the promo renderer with CI and RUFLO_FUNNEL gates', () => {
+ expect(script).toContain('getPromoRow');
+ expect(script).toContain('process.env.CI');
+ expect(script).toContain('RUFLO_FUNNEL');
+ });
+
+ it('re-sanitizes promo text at render time (control chars stripped, capped)', () => {
+ expect(script).toContain('\\u0000-\\u001f');
+ expect(script).toContain('.slice(0, 100)');
+ });
+
+ it('never renders promo styling from payload — colors come from a fixed kind map', () => {
+ // The row is styled by the renderer's own hardcoded color, chosen from the
+ // CLI-supplied `kind` enum (disclosure/promotional/educational). The payload
+ // text itself never provides ANSI — the sanitiser above strips all of it.
+ // The wrapping ALWAYS ends with c.reset so no color leaks into subsequent
+ // Claude Code UI. Guards against a future edit that lets payload styling in.
+ expect(script).toMatch(/promoColor \+ promoRow \+ c\.reset/);
+ expect(script).toMatch(/kind === 'promotional' \? c\.brightPurple/);
+ expect(script).toMatch(/kind === 'educational' \? c\.yellow/);
+ // Default branch stays a renderer-owned color, not a payload field.
+ expect(script).toMatch(/: c\.brightCyan/);
+ });
+});
+
+// ─── ADR-301/305 attribution — network-free fallback discipline ─────────────
+// The funnel row must render correctly even when the API is completely down.
+// These tests pin that invariant.
+
+describe('attributionUrl (ADR-305 measurement, no runtime network)', () => {
+ it('returns the base URL verbatim when it is malformed', () => {
+ // The URL builder must never synthesize a broken analytics endpoint —
+ // a malformed input passes through unchanged so downstream (OSC 8 host
+ // allowlist) can drop it safely.
+ const cases = ['not-a-url', '', 'javascript:evil()', 'ftp://cognitum.one'];
+ for (const bad of cases) {
+ expect(attributionUrl(bad, { medium: 's', campaign: 'c', content: 'x' })).toBe(bad);
+ }
+ });
+
+ it('appends UTM params and preserves any query already on the base URL', () => {
+ const out = attributionUrl('https://cognitum.one/ruflo?foo=1', {
+ medium: 'statusline', campaign: 'disclosure', content: 'test-1',
+ });
+ const parsed = new URL(out);
+ expect(parsed.searchParams.get('foo')).toBe('1');
+ expect(parsed.searchParams.get('utm_source')).toBe('ruflo');
+ expect(parsed.searchParams.get('utm_medium')).toBe('statusline');
+ expect(parsed.searchParams.get('utm_campaign')).toBe('disclosure');
+ expect(parsed.searchParams.get('utm_content')).toBe('test-1');
+ });
+
+ it('does NOT append fid when telemetry consent is absent (privacy default)', () => {
+ // Default test state has no consent grants. fid must not appear.
+ const out = attributionUrl('https://cognitum.one/ruflo', {
+ medium: 'statusline', campaign: 'disclosure', content: 'x',
+ });
+ expect(new URL(out).searchParams.has('fid')).toBe(false);
+ });
+
+ it('emits no network call — attribution is a pure link builder', () => {
+ // Guard: the function must be synchronous and side-effect-free with
+ // respect to the network. If someone later adds fetch/https here, this
+ // test will still pass but the *design* is documented.
+ const before = Date.now();
+ for (let i = 0; i < 1000; i++) {
+ attributionUrl('https://cognitum.one/ruflo', {
+ medium: 'statusline', campaign: 'disclosure', content: String(i),
+ });
+ }
+ const elapsed = Date.now() - before;
+ // 1000 URL builds must be sub-100ms (network calls would be nowhere near).
+ expect(elapsed).toBeLessThan(100);
+ });
+});
+
+describe('getFunnelPromo — API-down fallback discipline', () => {
+ it('generated statusline styles the label as a link and the command as bold-not-underlined', () => {
+ // CTA affordance: the OSC 8 label is wrapped in ANSI underline so terminals
+ // show it as a clickable link even when the OSC 8 hyperlink itself isn't
+ // supported.
+ //
+ // "manage: ruflo settings" is a shell command, not a URL -- a terminal can
+ // never safely execute a command from a click (that would let any
+ // server-served message run arbitrary commands), so it must NEVER be
+ // underlined or OSC-8-wrapped. Instead "ruflo settings" renders bold so it
+ // visually reads as "the important bit to copy/type", not a dead link.
+ const script = generateStatuslineScript({
+ 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/);
+ // "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/);
+ 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: '\)/);
+ });
+
+ it('generated statusline emits exactly 3 lines: header, ops, promo', () => {
+ // Claude Code truncates statusline past line 4 with the system guidance
+ // line. The 3-line design puts RuFlo header on line 1, then ops, then
+ // promo — sequence matches order of pushes in the generator source.
+ const script = generateStatuslineScript({
+ statusline: { enabled: true, style: 'compact' as const },
+ runtime: { maxAgents: 15 },
+ });
+ const headerIdx = script.indexOf('lines.push(header)');
+ const opsIdx = script.indexOf("lines.push(opsParts.join(");
+ const promoIdx = script.indexOf('lines.push(promoColor + promoRow');
+ expect(headerIdx).toBeGreaterThan(0);
+ expect(opsIdx).toBeGreaterThan(headerIdx);
+ expect(promoIdx).toBeGreaterThan(opsIdx);
+ });
+
+ it('generated statusline memoizes promo across renders (survives promoless CLI)', () => {
+ // A previously-installed older CLI cached by npx may succeed but omit
+ // the promo field. The memo overlay patches it back in so the row
+ // doesn't blink out mid-session.
+ const script = generateStatuslineScript({
+ statusline: { enabled: true, style: 'compact' as const },
+ runtime: { maxAgents: 15 },
+ });
+ expect(script).toMatch(/PROMO_MEMO_FILE/);
+ expect(script).toMatch(/function readPromoMemo/);
+ expect(script).toMatch(/function overlayMemoPromo/);
+ // Overlay must fire on every path (fresh cache, successful CLI, stale
+ // cache fallback, cold fallback) — grep the call count as a spot check.
+ const overlayCalls = (script.match(/overlayMemoPromo\(/g) || []).length;
+ expect(overlayCalls).toBeGreaterThanOrEqual(4);
+ });
+
+ it('generated statusline script implements stale-while-revalidate for promo row', () => {
+ // The fix for the flicker bug: the promo row must survive CLI hiccups
+ // and cache-expiry-mid-render. readCache() returns { fresh, data } and
+ // getStatuslineData falls back to stale cache when the CLI fails, so
+ // the last known promo persists. This test pins that design in the
+ // generator template so a future edit that breaks the pattern trips CI.
+ const script = generateStatuslineScript({
+ statusline: { enabled: true, style: 'compact' as const },
+ runtime: { maxAgents: 15 },
+ });
+ // Cache reader must expose freshness rather than gating data behind TTL.
+ expect(script).toMatch(/const cache = readCache\(\)/);
+ expect(script).toMatch(/cache\.fresh/);
+ // On CLI failure, must serve stale cache data (with local overlays) not
+ // a bare buildLocalFallback() that would drop the promo field.
+ expect(script).toMatch(/if \(cache\.data\)/);
+ expect(script).toMatch(/applyLocalOverlays\(cache\.data\)/);
+ });
+
+ it('the promo row has its own rotation-cadence freshness check, distinct from the general 60s cache TTL', () => {
+ // Bug report: "the promo area doesn't seem to be rotating every 20
+ // seconds." Root cause: CACHE_TTL_MS (60s, #2337's fix for excessive
+ // CLI re-invocation) let getStatuslineData() skip the CLI call — the
+ // ONLY place the rotation slot is recomputed — for up to 3 whole 20s
+ // rotation slots. A general cache.fresh check alone can never catch
+ // this; it must ALSO check a tighter, rotation-cadence-bound freshness
+ // signal before it's allowed to skip the CLI call.
+ const script = generateStatuslineScript({
+ statusline: { enabled: true, style: 'compact' as const },
+ runtime: { maxAgents: 15 },
+ });
+ expect(script).toMatch(/PROMO_ROTATION_SLOT_MS\s*=\s*20000/);
+ expect(script).toMatch(/promoFresh/);
+ // The early-return that skips the CLI call must require BOTH freshness
+ // signals — cache.fresh alone (the pre-fix bug) must not appear as the
+ // sole guard on that line.
+ expect(script).toMatch(/if \(cache\.fresh && cache\.promoFresh\)/);
+ });
+
+ it('renders the row without touching the network (no fetch import path)', async () => {
+ // The promo module is imported at test module load; if it pulled in a
+ // network library, this stringified module set would carry a fetch/https
+ // reference. This is a design lock — a future edit that adds network
+ // I/O to the render path breaks this test.
+ const promoSrc = await import('node:fs').then((fs) =>
+ fs.readFileSync(new URL('../src/funnel/promo.ts', import.meta.url), 'utf-8'),
+ );
+ expect(promoSrc).not.toMatch(/require\(\s*['"]https?['"]\s*\)/);
+ expect(promoSrc).not.toMatch(/from\s+['"]https?['"]/);
+ expect(promoSrc).not.toMatch(/fetch\s*\(/);
+ expect(promoSrc).not.toMatch(/XMLHttpRequest/);
+ });
+});
+
+// ─── ADR-308 client transport — consent-gated + failure-safe ────────────────
+
+describe('event transport (ADR-308 POST /v1/events)', () => {
+ it('exposes ADR-308 defaults: https endpoint, batch cap, backoff, timeout', () => {
+ expect(DEFAULT_ENDPOINT.startsWith('https://')).toBe(true);
+ expect(MAX_BATCH).toBeGreaterThan(0);
+ expect(MAX_BATCH).toBeLessThanOrEqual(1000);
+ expect(MIN_FLUSH_INTERVAL_MS).toBeGreaterThanOrEqual(10_000);
+ expect(FLUSH_TIMEOUT_MS).toBeGreaterThan(0);
+ expect(FLUSH_TIMEOUT_MS).toBeLessThanOrEqual(10_000); // never stall the CLI
+ });
+
+ it('no-ops without telemetry consent — zero network activity', async () => {
+ // No consent granted in the base test state.
+ const result = await flushEvents({ endpoint: 'https://127.0.0.1:1', now: new Date() });
+ expect(result).toEqual({ flushed: 0, skipped: 'no-consent' });
+ });
+
+ it('rejects non-https endpoints inside postBatch (via consent-gated caller)', async () => {
+ // Grant consent so the transport reaches postBatch, then pass an
+ // http:// endpoint — the module must refuse rather than open a plaintext
+ // connection.
+ recordConsent('telemetry', true, 'test');
+ // Also stage at least one event so we don't short-circuit on empty queue.
+ recordFunnelEvent('disclosure_shown', 'statusline', 'test');
+ const result = await flushEvents({ endpoint: 'http://127.0.0.1:1', force: true, now: new Date() });
+ expect(result.skipped).toMatch(/transport-failed|no-consent/);
+ // On the failed-transport path we expect a status of 0 (never opened).
+ if (result.skipped === 'transport-failed') expect(result.status).toBe(0);
+ });
+});
+
+describe('credit-notifier (ADR-303 out-of-band signal)', () => {
+ it('markCreditExhausted is idempotent — stable `since`', () => {
+ const t0 = new Date('2026-07-10T12:00:00.000Z');
+ markCreditExhausted(t0);
+ const first = readCreditStatus();
+ expect(first.exhausted).toBe(true);
+ expect(first.since).toBe(t0.toISOString());
+ // Second mark must not move the `since` timestamp forward.
+ markCreditExhausted(new Date('2026-07-10T13:00:00.000Z'));
+ const second = readCreditStatus();
+ expect(second.since).toBe(t0.toISOString());
+ });
+
+ it('clearCreditStatus stamps `cleared`, drops the exhausted flag', () => {
+ markCreditExhausted(new Date('2026-07-10T12:00:00.000Z'));
+ clearCreditStatus(new Date('2026-07-10T14:00:00.000Z'));
+ const status = readCreditStatus();
+ expect(status.exhausted).toBe(false);
+ expect(status.cleared).toBe('2026-07-10T14:00:00.000Z');
+ });
+
+ it('creditExhaustedNotice renders humanized "since" copy', () => {
+ markCreditExhausted(new Date('2026-07-10T12:00:00.000Z'));
+ // 3 hours later
+ const notice = creditExhaustedNotice(new Date('2026-07-10T15:00:00.000Z'));
+ expect(notice).not.toBeNull();
+ expect(notice).toContain('Cognitum credits exhausted');
+ expect(notice).toContain('ruflo funnel signup');
+ expect(notice).toContain('3h ago');
+ });
+
+ it('returns null when credit is not exhausted (no surface)', () => {
+ clearCreditStatus();
+ expect(creditExhaustedNotice()).toBeNull();
+ });
+});
+
+// ─── ADR-312/313: rate-limit notifier + sponsored downtime override ────────
+
+describe('rate-limit notifier (ADR-312 Phase 0 — manual, self-reported)', () => {
+ it('starts not-limited', () => {
+ expect(readRateLimitStatus().limited).toBe(false);
+ expect(rateLimitNotice()).toBeNull();
+ });
+
+ it('markRateLimited is idempotent — stable `since`', () => {
+ const t0 = new Date('2026-07-10T12:00:00.000Z');
+ markRateLimited(t0);
+ const first = readRateLimitStatus(t0);
+ expect(first.limited).toBe(true);
+ expect(first.since).toBe(t0.toISOString());
+ // Marking again later must not move `since`.
+ markRateLimited(new Date(t0.getTime() + 60_000));
+ const second = readRateLimitStatus(new Date(t0.getTime() + 60_000));
+ expect(second.since).toBe(t0.toISOString());
+ });
+
+ it('clearRateLimitStatus stamps `cleared` and flips `limited` false', () => {
+ const t0 = new Date('2026-07-10T12:00:00.000Z');
+ markRateLimited(t0);
+ // Past the ADR-314 §D1 toggle cooldown (10 min) — a clear inside that
+ // window is deliberately refused (covered separately below).
+ const t1 = new Date(t0.getTime() + 11 * 60 * 1000);
+ clearRateLimitStatus(t1);
+ const status = readRateLimitStatus(t1);
+ expect(status.limited).toBe(false);
+ expect(status.cleared).not.toBeNull();
+ });
+
+ it('auto-expires the flag after the TTL (a stale manual mark self-heals)', () => {
+ const t0 = new Date('2026-07-10T12:00:00.000Z');
+ markRateLimited(t0);
+ const justBefore = readRateLimitStatus(new Date(t0.getTime() + RATE_LIMIT_TTL_MS - 1000));
+ expect(justBefore.limited).toBe(true);
+ const justAfter = readRateLimitStatus(new Date(t0.getTime() + RATE_LIMIT_TTL_MS + 1000));
+ expect(justAfter.limited).toBe(false);
+ });
+
+ it('rateLimitNotice humanizes age and points at the sponsor command', () => {
+ const t0 = new Date('2026-07-10T12:00:00.000Z');
+ markRateLimited(t0);
+ const notice = rateLimitNotice(new Date(t0.getTime() + 5 * 60 * 1000));
+ expect(notice).toContain('5m ago');
+ expect(notice).toContain('ruflo proxy sponsor-enable');
+ });
+});
+
+describe('toggle cooldown (ADR-314 §D1 — anti-abuse friction)', () => {
+ it('is inactive with no prior toggle', () => {
+ expect(cooldownActive(null, new Date())).toBe(false);
+ });
+
+ it('is active just before the cooldown window elapses', () => {
+ const t0 = new Date('2026-07-10T12:00:00.000Z');
+ const justBefore = new Date(t0.getTime() + TOGGLE_COOLDOWN_MS - 1000);
+ expect(cooldownActive(t0.toISOString(), justBefore)).toBe(true);
+ });
+
+ it('clears just after the cooldown window elapses', () => {
+ const t0 = new Date('2026-07-10T12:00:00.000Z');
+ const justAfter = new Date(t0.getTime() + TOGGLE_COOLDOWN_MS + 1000);
+ expect(cooldownActive(t0.toISOString(), justAfter)).toBe(false);
+ });
+
+ it('reports remaining minutes, floored to zero once elapsed', () => {
+ const t0 = new Date('2026-07-10T12:00:00.000Z');
+ const fiveMinIn = new Date(t0.getTime() + 5 * 60 * 1000);
+ expect(cooldownRemainingMin(t0.toISOString(), fiveMinIn)).toBe(5);
+ expect(cooldownRemainingMin(t0.toISOString(), new Date(t0.getTime() + TOGGLE_COOLDOWN_MS + 1000))).toBe(0);
+ });
+
+ it('rate-limit mark→clear inside the cooldown window is refused', () => {
+ const t0 = new Date('2026-07-10T12:30:00.000Z');
+ expect(markRateLimited(t0)).toBe(true);
+ const stillCoolingDown = new Date(t0.getTime() + 1000);
+ expect(clearRateLimitStatus(stillCoolingDown)).toBe(false);
+ // The refusal must not have silently applied — still limited.
+ expect(readRateLimitStatus(stillCoolingDown).limited).toBe(true);
+ });
+
+ it('rate-limit mark→clear after the cooldown window succeeds', () => {
+ const t0 = new Date('2026-07-10T12:31:00.000Z');
+ expect(markRateLimited(t0)).toBe(true);
+ const afterCooldown = new Date(t0.getTime() + TOGGLE_COOLDOWN_MS + 1000);
+ expect(clearRateLimitStatus(afterCooldown)).toBe(true);
+ expect(readRateLimitStatus(afterCooldown).limited).toBe(false);
+ });
+
+ it('re-marking an already-limited flag is not a state change — cooldown does not apply', () => {
+ const t0 = new Date('2026-07-10T12:32:00.000Z');
+ expect(markRateLimited(t0)).toBe(true);
+ // Immediately re-marking (still limited) must succeed — it's a no-op idempotent call.
+ expect(markRateLimited(new Date(t0.getTime() + 1000))).toBe(true);
+ });
+});
+
+describe('power-saver notifier (ADR-314 §A — manual, self-reported, mirrors rate-limit)', () => {
+ it('starts not-low', () => {
+ expect(readQuotaLowStatus().low).toBe(false);
+ expect(quotaLowNotice()).toBeNull();
+ });
+
+ it('markQuotaLow is idempotent — stable `since`', () => {
+ const t0 = new Date('2026-07-10T13:00:00.000Z');
+ markQuotaLow(t0);
+ const first = readQuotaLowStatus(t0);
+ expect(first.low).toBe(true);
+ expect(first.since).toBe(t0.toISOString());
+ markQuotaLow(new Date(t0.getTime() + 60_000));
+ const second = readQuotaLowStatus(new Date(t0.getTime() + 60_000));
+ expect(second.since).toBe(t0.toISOString());
+ });
+
+ it('clearQuotaLowStatus stamps `cleared` and flips `low` false, past the cooldown', () => {
+ const t0 = new Date('2026-07-10T13:01:00.000Z');
+ markQuotaLow(t0);
+ const t1 = new Date(t0.getTime() + TOGGLE_COOLDOWN_MS + 1000);
+ expect(clearQuotaLowStatus(t1)).toBe(true);
+ const status = readQuotaLowStatus(t1);
+ expect(status.low).toBe(false);
+ expect(status.cleared).not.toBeNull();
+ });
+
+ it('auto-expires the flag after the TTL', () => {
+ const t0 = new Date('2026-07-10T13:02:00.000Z');
+ markQuotaLow(t0);
+ const justBefore = readQuotaLowStatus(new Date(t0.getTime() + QUOTA_LOW_TTL_MS - 1000));
+ expect(justBefore.low).toBe(true);
+ const justAfter = readQuotaLowStatus(new Date(t0.getTime() + QUOTA_LOW_TTL_MS + 1000));
+ expect(justAfter.low).toBe(false);
+ });
+
+ it('quotaLowNotice humanizes age and points at power-saver-disable', () => {
+ const t0 = new Date('2026-07-10T13:03:00.000Z');
+ markQuotaLow(t0);
+ const notice = quotaLowNotice(new Date(t0.getTime() + 5 * 60 * 1000));
+ expect(notice).toContain('5m ago');
+ expect(notice).toContain('ruflo proxy power-saver-disable');
+ });
+
+ it('mark→clear inside the cooldown window is refused, same as rate-limit', () => {
+ const t0 = new Date('2026-07-10T13:04:00.000Z');
+ expect(markQuotaLow(t0)).toBe(true);
+ expect(clearQuotaLowStatus(new Date(t0.getTime() + 1000))).toBe(false);
+ expect(readQuotaLowStatus(new Date(t0.getTime() + 1000)).low).toBe(true);
+ });
+});
+
+describe('sponsored-downtime priority override (ADR-313)', () => {
+ it('does not override when the rate-limit flag is unset', () => {
+ seedRemoteMessages([...TEST_DISCLOSURE_POOL, ...TEST_ROTATION_POOL]);
+ const t0 = new Date();
+ recordDisclosureShown(t0);
+ const after = new Date(t0.getTime() + DISCLOSURE_GRACE_MS + 60_000);
+ const row = getFunnelPromo({ interactive: true, cwd: stateDir, now: after });
+ expect(row).not.toBeNull();
+ expect(row!.text).not.toMatch(/sponsor/i);
+ });
+
+ it('shows the enable-CTA when rate-limited without sponsored consent', () => {
+ seedRemoteMessages([...TEST_DISCLOSURE_POOL, ...TEST_ROTATION_POOL]);
+ const t0 = new Date();
+ recordDisclosureShown(t0);
+ const after = new Date(t0.getTime() + DISCLOSURE_GRACE_MS + 60_000);
+ markRateLimited(after);
+ const row = getFunnelPromo({ interactive: true, cwd: stateDir, now: after });
+ expect(row).not.toBeNull();
+ expect(row!.text).toContain('Free Cognitum capacity');
+ expect(row!.text).toContain('manage: ruflo proxy sponsor-enable');
+ expect(displayWidth(row!.text)).toBeLessThanOrEqual(MAX_MESSAGE_COLUMNS);
+ });
+
+ it('shows the active-status line when rate-limited WITH sponsored consent granted', () => {
+ seedRemoteMessages([...TEST_DISCLOSURE_POOL, ...TEST_ROTATION_POOL]);
+ const t0 = new Date();
+ recordDisclosureShown(t0);
+ const after = new Date(t0.getTime() + DISCLOSURE_GRACE_MS + 60_000);
+ markRateLimited(after);
+ recordConsent('sponsored-downtime', true, 'test');
+ const row = getFunnelPromo({ interactive: true, cwd: stateDir, now: after });
+ expect(row).not.toBeNull();
+ expect(row!.text).toContain('Running on sponsored Cognitum capacity');
+ expect(row!.text).toContain('manage: ruflo proxy sponsor-disable');
+ expect(displayWidth(row!.text)).toBeLessThanOrEqual(MAX_MESSAGE_COLUMNS);
+ });
+
+ it('the override preempts rotation even mid-promo-slot', () => {
+ // Regression guard: without the override, a promotional slot would
+ // otherwise render a rotation message here — confirm sponsored wins.
+ seedRemoteMessages([...TEST_DISCLOSURE_POOL, ...TEST_ROTATION_POOL]);
+ const t0 = new Date();
+ recordDisclosureShown(t0);
+ const after = new Date(t0.getTime() + DISCLOSURE_GRACE_MS + 60_000);
+ markRateLimited(after);
+ const row = getFunnelPromo({ interactive: true, cwd: stateDir, now: after });
+ expect(row!.kind).toBe('promotional');
+ expect(TEST_ROTATION_POOL.map((m) => m.text)).not.toContain(row!.text);
+ });
+
+ it('never overrides before the disclosure invariant is satisfied', () => {
+ // ADR-301: no promotional content before disclosure — even a rate-limit
+ // flag must not bypass the first-render disclosure gate.
+ seedRemoteMessages(TEST_DISCLOSURE_POOL);
+ markRateLimited(new Date());
+ const row = getFunnelPromo({ interactive: true, cwd: stateDir });
+ expect(row).not.toBeNull();
+ expect(row!.kind).toBe('disclosure');
+ });
+});
+
+describe('local insight ticker (computeLocalInsights / selectLocalInsight)', () => {
+ it('returns nothing when no context signal applies', () => {
+ expect(computeLocalInsights({})).toEqual([]);
+ expect(selectLocalInsight({})).toBeNull();
+ });
+
+ it('surfaces pending CVEs at the highest priority', () => {
+ const insights = computeLocalInsights({ security: { status: 'IN_PROGRESS', cvesFixed: 1, totalCves: 3 } });
+ expect(insights).toHaveLength(1);
+ expect(insights[0].text).toContain('2 CVEs pending');
+ expect(insights[0].text).toContain('ruflo security scan --depth full');
+ });
+
+ it('singularizes "1 CVE" correctly', () => {
+ const insight = selectLocalInsight({ security: { status: 'IN_PROGRESS', cvesFixed: 2, totalCves: 3 } });
+ expect(insight!.text).toContain('1 CVE pending');
+ expect(insight!.text).not.toContain('1 CVEs');
+ });
+
+ it('falls back to "scan pending" only when there are zero pending CVEs but the scan itself is pending', () => {
+ const insight = selectLocalInsight({ security: { status: 'PENDING', cvesFixed: 3, totalCves: 3 } });
+ expect(insight!.text).toContain('Security scan pending');
+ });
+
+ it('is silent when security is CLEAN', () => {
+ expect(selectLocalInsight({ security: { status: 'CLEAN', cvesFixed: 3, totalCves: 3 } })).toBeNull();
+ });
+
+ it('surfaces uncommitted changes only above the threshold', () => {
+ expect(selectLocalInsight({ gitUncommittedCount: 20 })).toBeNull(); // at threshold, not over
+ const insight = selectLocalInsight({ gitUncommittedCount: 21 });
+ expect(insight!.text).toContain('21 uncommitted changes');
+ });
+
+ it('picks the highest-priority candidate when several apply at once', () => {
+ const insight = selectLocalInsight({
+ security: { status: 'IN_PROGRESS', cvesFixed: 2, totalCves: 3 }, // priority 90
+ gitUncommittedCount: 50, // priority 50
+ });
+ expect(insight!.id).toBe('insight-cves-pending');
+ });
+
+ it('surfaces power-saver mode only when both consented and flagged low', () => {
+ expect(selectLocalInsight({})).toBeNull();
+ recordConsent('power-saver', true, 'test');
+ expect(selectLocalInsight({})).toBeNull(); // consented but not flagged low
+ markQuotaLow(new Date());
+ const insight = selectLocalInsight({});
+ expect(insight!.text).toContain('Power saver mode active');
+ });
+
+ it('reads the ADR-315 flywheel-status cache when present and fresh', () => {
+ fs.writeFileSync(
+ path.join(stateDir, 'flywheel-status.json'),
+ JSON.stringify({ _ts: Date.now(), headline: 'test headline' }),
+ 'utf-8',
+ );
+ const insight = selectLocalInsight({});
+ expect(insight!.text).toContain('test headline');
+ });
+
+ it('ignores an expired flywheel-status cache', () => {
+ fs.writeFileSync(
+ path.join(stateDir, 'flywheel-status.json'),
+ JSON.stringify({ _ts: Date.now() - 25 * 60 * 60 * 1000, headline: 'stale headline' }),
+ 'utf-8',
+ );
+ expect(selectLocalInsight({})).toBeNull();
+ });
+
+ it('surfaces the ADR-316 advisor tip only when consented, and never a stale-past-TTL cache', () => {
+ fs.writeFileSync(
+ path.join(stateDir, 'advisor-tip.json'),
+ JSON.stringify({ _ts: Date.now(), headline: 'commit your work' }),
+ 'utf-8',
+ );
+ expect(selectLocalInsight({})).toBeNull(); // not consented — cache is ignored regardless
+ recordConsent('advisor-tips', true, 'test');
+ const insight = selectLocalInsight({});
+ expect(insight!.id).toBe('insight-advisor-tip');
+ expect(insight!.text).toContain('commit your work');
+ });
+
+ it('an expired advisor-tip cache is silent even when consented', () => {
+ recordConsent('advisor-tips', true, 'test');
+ fs.writeFileSync(
+ path.join(stateDir, 'advisor-tip.json'),
+ JSON.stringify({ _ts: Date.now() - 25 * 60 * 60 * 1000, headline: 'stale tip' }),
+ 'utf-8',
+ );
+ expect(selectLocalInsight({})).toBeNull();
+ });
+
+ it('CVEs pending still outrank the advisor tip', () => {
+ recordConsent('advisor-tips', true, 'test');
+ fs.writeFileSync(
+ path.join(stateDir, 'advisor-tip.json'),
+ JSON.stringify({ _ts: Date.now(), headline: 'a tip' }),
+ 'utf-8',
+ );
+ const insight = selectLocalInsight({ security: { status: 'IN_PROGRESS', cvesFixed: 0, totalCves: 1 } });
+ expect(insight!.id).toBe('insight-cves-pending');
+ });
+
+ it('the advisor tip outranks the flywheel-status placeholder', () => {
+ recordConsent('advisor-tips', true, 'test');
+ fs.writeFileSync(
+ path.join(stateDir, 'advisor-tip.json'),
+ JSON.stringify({ _ts: Date.now(), headline: 'a tip' }),
+ 'utf-8',
+ );
+ fs.writeFileSync(
+ path.join(stateDir, 'flywheel-status.json'),
+ JSON.stringify({ _ts: Date.now(), headline: 'flywheel news' }),
+ 'utf-8',
+ );
+ const insight = selectLocalInsight({});
+ expect(insight!.id).toBe('insight-advisor-tip');
+ });
+});
+
+describe('local insight ticker integration with getFunnelPromo (ADR §5)', () => {
+ it('never shows an insight when localInsights context is omitted (backward compatible)', () => {
+ seedRemoteMessages([...TEST_DISCLOSURE_POOL, ...TEST_ROTATION_POOL]);
+ const t0 = new Date();
+ recordDisclosureShown(t0);
+ // slot 2 (of 5) — the reserved insight slot — but no context passed.
+ const insightSlotTime = new Date(t0.getTime() + DISCLOSURE_GRACE_MS + 60_000 + 2 * ROTATION_SLOT_MS);
+ const row = getFunnelPromo({ interactive: true, cwd: stateDir, now: insightSlotTime });
+ expect(row).not.toBeNull();
+ expect(row!.kind).not.toBe('insight');
+ });
+
+ it('shows the insight on its reserved slot when context signals one', () => {
+ seedRemoteMessages([...TEST_DISCLOSURE_POOL, ...TEST_ROTATION_POOL]);
+ const t0 = new Date(0);
+ recordDisclosureShown(t0);
+ const after = new Date(t0.getTime() + DISCLOSURE_GRACE_MS + 60_000);
+ // Find the next slot boundary where slot % 5 === 2 (promo.ts's reserved phase).
+ let probe = after;
+ while (Math.floor(probe.getTime() / ROTATION_SLOT_MS) % 5 !== 2) {
+ probe = new Date(probe.getTime() + ROTATION_SLOT_MS);
+ }
+ const row = getFunnelPromo({
+ interactive: true,
+ cwd: stateDir,
+ now: probe,
+ localInsights: { security: { status: 'IN_PROGRESS', cvesFixed: 0, totalCves: 1 } },
+ });
+ expect(row).not.toBeNull();
+ expect(row!.kind).toBe('insight');
+ expect(row!.text).toContain('CVE');
+ });
+
+ it('falls through to normal rotation on the insight slot when nothing is actionable', () => {
+ seedRemoteMessages([...TEST_DISCLOSURE_POOL, ...TEST_ROTATION_POOL]);
+ const t0 = new Date(0);
+ recordDisclosureShown(t0);
+ const after = new Date(t0.getTime() + DISCLOSURE_GRACE_MS + 60_000);
+ let probe = after;
+ while (Math.floor(probe.getTime() / ROTATION_SLOT_MS) % 5 !== 2) {
+ probe = new Date(probe.getTime() + ROTATION_SLOT_MS);
+ }
+ const row = getFunnelPromo({
+ interactive: true,
+ cwd: stateDir,
+ now: probe,
+ localInsights: { security: { status: 'CLEAN', cvesFixed: 1, totalCves: 1 } },
+ });
+ expect(row).not.toBeNull();
+ expect(row!.kind).not.toBe('insight'); // no actionable insight -> normal rotation
+ });
+
+ it('the ADR-313 sponsored override still wins even on the insight slot', () => {
+ seedRemoteMessages([...TEST_DISCLOSURE_POOL, ...TEST_ROTATION_POOL]);
+ const t0 = new Date(0);
+ recordDisclosureShown(t0);
+ const after = new Date(t0.getTime() + DISCLOSURE_GRACE_MS + 60_000);
+ let probe = after;
+ while (Math.floor(probe.getTime() / ROTATION_SLOT_MS) % 5 !== 2) {
+ probe = new Date(probe.getTime() + ROTATION_SLOT_MS);
+ }
+ markRateLimited(probe);
+ const row = getFunnelPromo({
+ interactive: true,
+ cwd: stateDir,
+ now: probe,
+ localInsights: { security: { status: 'IN_PROGRESS', cvesFixed: 0, totalCves: 1 } },
+ });
+ expect(row!.text).toContain('Cognitum capacity');
+ expect(row!.kind).not.toBe('insight');
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/helper-refresh.test.ts b/v3/@claude-flow/cli/__tests__/helper-refresh.test.ts
index f8004f8a1d..e04584abec 100644
--- a/v3/@claude-flow/cli/__tests__/helper-refresh.test.ts
+++ b/v3/@claude-flow/cli/__tests__/helper-refresh.test.ts
@@ -7,13 +7,26 @@
* refresh path closes it: a stale-stamped project silently re-copies the
* current helpers on the next CLI startup; a current one is a no-op; and a
* non-ruflo directory is never touched.
+ *
+ * The successful-copy tests use an ISOLATED, throwaway-keypair-signed
+ * fixture (`makeSignedSource()`) rather than this repo's own real
+ * `.claude/helpers` + its real Ed25519 signature. That coupling is
+ * deliberately avoided: the real manifest is re-signed at publish time
+ * (scripts/sign-helpers.mjs, needs a GCP secret or a local PEM key) and is
+ * routinely stale mid-development whenever a critical helper changes without
+ * an immediate re-sign — this suite must pass regardless of that state, and
+ * only actually exercises `writeCriticalHelpers`' verify → hash → copy logic
+ * when it does.
*/
import { describe, it, expect, beforeEach } from 'vitest';
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
+import { generateKeyPairSync, sign as edSign } from 'node:crypto';
+import * as semver from 'semver';
import { autoRefreshHelpersIfStale, getInstalledCliVersion, HELPERS_STAMP_FILE } from '../src/init/helper-refresh.js';
+import { canonicalManifestBytes, sha256Hex } from '../src/init/helper-signing.js';
function makeProject(): { cwd: string; helpersDir: string } {
const cwd = mkdtempSync(join(tmpdir(), 'helper-refresh-'));
@@ -22,6 +35,28 @@ function makeProject(): { cwd: string; helpersDir: string } {
return { cwd, helpersDir };
}
+/**
+ * Build a throwaway-keypair-signed `.claude/helpers` source fixture:
+ * `hook-handler.cjs` with recognizable NEW content + a validly-signed
+ * manifest for it. Returns the source dir and the matching public key PEM
+ * to inject via `pubkeyPemOverride`.
+ */
+function makeSignedSource(version: string): { sourceDir: string; pubkeyPem: string } {
+ const sourceDir = mkdtempSync(join(tmpdir(), 'helper-refresh-source-'));
+ const content = 'intelligence.feedback(!toolFailed); // NEW, real failure capture\n';
+ writeFileSync(join(sourceDir, 'hook-handler.cjs'), content);
+
+ const { publicKey, privateKey } = generateKeyPairSync('ed25519');
+ const manifest = { version, files: { 'hook-handler.cjs': sha256Hex(content) } };
+ const signature = edSign(null, canonicalManifestBytes(manifest), privateKey).toString('base64');
+ writeFileSync(
+ join(sourceDir, 'helpers.manifest.json'),
+ JSON.stringify({ manifest, signature, algorithm: 'ed25519' }),
+ );
+
+ return { sourceDir, pubkeyPem: publicKey.export({ type: 'spki', format: 'pem' }).toString() };
+}
+
describe('autoRefreshHelpersIfStale', () => {
let version: string;
beforeEach(() => { version = getInstalledCliVersion(); });
@@ -31,8 +66,9 @@ describe('autoRefreshHelpersIfStale', () => {
// Old, hardcoded-success hook-handler + a stale stamp.
writeFileSync(join(helpersDir, 'hook-handler.cjs'), 'intelligence.feedback(true); // OLD, no failure capture\n');
writeFileSync(join(helpersDir, HELPERS_STAMP_FILE), '0.0.1-old');
+ const { sourceDir, pubkeyPem } = makeSignedSource(version);
- const r = await autoRefreshHelpersIfStale(cwd);
+ const r = await autoRefreshHelpersIfStale(cwd, { sourceDirOverride: sourceDir, pubkeyPemOverride: pubkeyPem });
expect(r.refreshed).toBe(true);
expect(r.from).toBe('0.0.1-old');
expect(r.to).toBe(version);
@@ -45,6 +81,24 @@ describe('autoRefreshHelpersIfStale', () => {
expect(refreshed).not.toContain('// OLD, no failure capture');
});
+ it('refuses to refresh when the source manifest signature does not verify (fail-closed)', async () => {
+ const { cwd, helpersDir } = makeProject();
+ const marker = 'PROJECT-HANDLER-UNTOUCHED-ON-BAD-SIGNATURE';
+ writeFileSync(join(helpersDir, 'hook-handler.cjs'), marker);
+ writeFileSync(join(helpersDir, HELPERS_STAMP_FILE), '0.0.1-old');
+ // Sign with one keypair, verify with an unrelated one — signature must fail.
+ const { sourceDir } = makeSignedSource(version);
+ const { publicKey: wrongPubkey } = generateKeyPairSync('ed25519');
+
+ const r = await autoRefreshHelpersIfStale(cwd, {
+ sourceDirOverride: sourceDir,
+ pubkeyPemOverride: wrongPubkey.export({ type: 'spki', format: 'pem' }).toString(),
+ });
+ expect(r.refreshed).toBe(false);
+ expect(r.blocked).toMatch(/signature invalid|missing/);
+ expect(readFileSync(join(helpersDir, 'hook-handler.cjs'), 'utf-8')).toBe(marker);
+ });
+
it('is a no-op when the stamp already matches the installed version', async () => {
const { cwd, helpersDir } = makeProject();
const marker = 'CURRENT-HANDLER-DO-NOT-OVERWRITE';
@@ -61,8 +115,9 @@ describe('autoRefreshHelpersIfStale', () => {
const { cwd, helpersDir } = makeProject();
writeFileSync(join(helpersDir, 'hook-handler.cjs'), 'intelligence.feedback(true);\n');
// no stamp file at all
+ const { sourceDir, pubkeyPem } = makeSignedSource(version);
- const r = await autoRefreshHelpersIfStale(cwd);
+ const r = await autoRefreshHelpersIfStale(cwd, { sourceDirOverride: sourceDir, pubkeyPemOverride: pubkeyPem });
expect(r.refreshed).toBe(true);
expect(r.from).toBe('(unstamped)');
expect(existsSync(join(helpersDir, HELPERS_STAMP_FILE))).toBe(true);
@@ -74,4 +129,36 @@ describe('autoRefreshHelpersIfStale', () => {
expect(r.refreshed).toBe(false);
expect(existsSync(join(cwd, '.claude'))).toBe(false); // did not scaffold anything
});
+
+ it('never downgrades — an OLDER installed version than the stamp is a no-op', async () => {
+ // Real trigger: a stray/older installed binary (stale npx cache,
+ // marketplace install lagging an unpublished dev-tree fix) running any
+ // command against a project whose helpers are stamped with a NEWER
+ // version than that binary reports. Must never silently overwrite the
+ // project's (fresher, hand-fixed) helpers with the older binary's own.
+ const { cwd, helpersDir } = makeProject();
+ const marker = 'NEWER-HANDLER-DO-NOT-DOWNGRADE';
+ writeFileSync(join(helpersDir, 'hook-handler.cjs'), marker);
+ const futureVersion = `${semver.major(version) + 1}.0.0`;
+ writeFileSync(join(helpersDir, HELPERS_STAMP_FILE), futureVersion);
+
+ const r = await autoRefreshHelpersIfStale(cwd);
+ expect(r.refreshed).toBe(false);
+ expect(readFileSync(join(helpersDir, 'hook-handler.cjs'), 'utf-8')).toBe(marker);
+ // Stamp itself is also left untouched — not silently rolled back either.
+ expect(readFileSync(join(helpersDir, HELPERS_STAMP_FILE), 'utf-8').trim()).toBe(futureVersion);
+ });
+
+ it('never downgrades — an EQUAL-but-differently-formatted stamp is a no-op', async () => {
+ // e.g. stamp has a build/prerelease suffix that string-compares unequal
+ // to the installed version but is semver-equal or newer.
+ const { cwd, helpersDir } = makeProject();
+ const marker = 'SAME-VERSION-DIFFERENT-STRING';
+ writeFileSync(join(helpersDir, 'hook-handler.cjs'), marker);
+ writeFileSync(join(helpersDir, HELPERS_STAMP_FILE), `${version}+build.1`);
+
+ const r = await autoRefreshHelpersIfStale(cwd);
+ expect(r.refreshed).toBe(false);
+ expect(readFileSync(join(helpersDir, 'hook-handler.cjs'), 'utf-8')).toBe(marker);
+ });
});
diff --git a/v3/@claude-flow/cli/__tests__/hook-handler-artifact-parity.test.ts b/v3/@claude-flow/cli/__tests__/hook-handler-artifact-parity.test.ts
new file mode 100644
index 0000000000..758517299e
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/hook-handler-artifact-parity.test.ts
@@ -0,0 +1,31 @@
+/**
+ * Drift guard: `.claude/helpers/hook-handler.cjs` (root) vs.
+ * `v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs` (package).
+ *
+ * These are two committed copies of the same critical helper (ADR-174) — the
+ * package copy is what ships; the root copy is this repo's own dogfood
+ * install. They are NOT generated from `helpers-generator.ts`'s
+ * `generateHookHandler()` — that function is a deliberately simpler inline
+ * fallback used only when copying the real file from the package fails
+ * (see its own doc comment), so comparing against it would be the wrong
+ * guard. The two committed .cjs files themselves must simply never diverge:
+ * a prior session's hand-edits DID diverge (the fix for the promo-cache bug
+ * and the ADR-312/313 rate-limit nudge landed in the package copy but never
+ * got synced to root), and the drift went unnoticed until this test was
+ * written, which is exactly the failure mode this guards against.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync, existsSync } from 'fs';
+import path from 'path';
+import { fileURLToPath } from 'url';
+
+describe('hook-handler.cjs — root/package artifact parity', () => {
+ it('the root and package copies are byte-identical', () => {
+ const here = path.dirname(fileURLToPath(import.meta.url));
+ const rootArtifact = path.resolve(here, '../../../../.claude/helpers/hook-handler.cjs');
+ const pkgArtifact = path.resolve(here, '../.claude/helpers/hook-handler.cjs');
+ if (!existsSync(rootArtifact)) return; // package tested in isolation; nothing to guard
+ expect(readFileSync(rootArtifact, 'utf-8')).toBe(readFileSync(pkgArtifact, 'utf-8'));
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/output.test.ts b/v3/@claude-flow/cli/__tests__/output.test.ts
index d1320ee137..0e02580e80 100644
--- a/v3/@claude-flow/cli/__tests__/output.test.ts
+++ b/v3/@claude-flow/cli/__tests__/output.test.ts
@@ -199,42 +199,49 @@ describe('OutputFormatter', () => {
expect(captured.join('')).not.toContain('warning');
});
- it('printWarning should output in normal mode', () => {
+ // printWarning/printInfo/printDebug/printTrace all write to STDERR, like
+ // printError — stdout is reserved for command results (e.g. --format
+ // json) and must never be interleaved with incidental warnings/info.
+ it('printWarning should output to stderr in normal mode', () => {
out.setVerbosity('normal');
out.printWarning('warning');
- expect(captured.join('')).toContain('warning');
+ expect(errorCaptured.join('')).toContain('warning');
+ expect(captured.join('')).not.toContain('warning');
});
it('printInfo should be suppressed in quiet mode', () => {
out.setVerbosity('quiet');
out.printInfo('information');
- expect(captured.join('')).not.toContain('information');
+ expect(errorCaptured.join('')).not.toContain('information');
});
- it('printInfo should output in normal mode', () => {
+ it('printInfo should output to stderr in normal mode', () => {
out.setVerbosity('normal');
out.printInfo('information');
- expect(captured.join('')).toContain('information');
+ expect(errorCaptured.join('')).toContain('information');
+ expect(captured.join('')).not.toContain('information');
});
- it('printDebug should only output in verbose/debug mode', () => {
+ it('printDebug should only output in verbose/debug mode, to stderr', () => {
out.setVerbosity('normal');
out.printDebug('debug msg');
- expect(captured.join('')).not.toContain('debug msg');
+ expect(errorCaptured.join('')).not.toContain('debug msg');
out.setVerbosity('verbose');
out.printDebug('debug msg');
- expect(captured.join('')).toContain('debug msg');
+ expect(errorCaptured.join('')).toContain('debug msg');
+ expect(captured.join('')).not.toContain('debug msg');
});
- it('printTrace should only output in debug mode', () => {
+ it('printTrace should only output in debug mode, to stderr', () => {
out.setVerbosity('verbose');
out.printTrace('trace msg');
- expect(captured.join('')).not.toContain('trace msg');
+ expect(errorCaptured.join('')).not.toContain('trace msg');
out.setVerbosity('debug');
out.printTrace('trace msg');
- expect(captured.join('')).toContain('trace msg');
+ expect(errorCaptured.join('')).toContain('trace msg');
+ expect(captured.join('')).not.toContain('trace msg');
});
});
diff --git a/v3/@claude-flow/cli/__tests__/security-scan-persistence.test.ts b/v3/@claude-flow/cli/__tests__/security-scan-persistence.test.ts
new file mode 100644
index 0000000000..f34f6c9966
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/security-scan-persistence.test.ts
@@ -0,0 +1,89 @@
+/**
+ * `security scan` persists its result (commit 7cf3b1084) so the statusline's
+ * getSecurityStatus (funnel/local-signals.ts) can reflect real scan state
+ * instead of being permanently stuck at PENDING/0 no matter how many real
+ * scans run. Black-box against the real built CLI binary — the same
+ * invocation shape used to manually verify this feature — rather than
+ * reconstructing CommandContext by hand (no existing test in this repo does
+ * that for any command; the CLI-binary route is the well-trodden path).
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { execFileSync } from 'child_process';
+import { mkdtempSync, rmSync, writeFileSync, existsSync, readFileSync, readdirSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { fileURLToPath } from 'url';
+import { getSecurityStatus } from '../src/funnel/local-signals.js';
+
+const CLI_BIN = fileURLToPath(new URL('../bin/cli.js', import.meta.url));
+
+let scanTarget: string;
+
+beforeEach(() => {
+ // A tiny, throwaway target with no real vulnerabilities and no source
+ // files to pattern-scan — keeps the real `npm audit` + secret/code scan
+ // fast and deterministic instead of running against this whole repo.
+ scanTarget = mkdtempSync(join(tmpdir(), 'security-scan-persist-'));
+ writeFileSync(
+ join(scanTarget, 'package.json'),
+ JSON.stringify({ name: 'security-scan-persist-fixture', version: '1.0.0' }),
+ );
+});
+
+afterEach(() => {
+ rmSync(scanTarget, { recursive: true, force: true });
+});
+
+describe('security scan — result persistence (statusline CVE counter wiring)', () => {
+ it('getSecurityStatus is PENDING/0 before any scan has run', () => {
+ const before = getSecurityStatus(scanTarget);
+ expect(before.status).toBe('PENDING');
+ expect(before.cvesFixed).toBe(0);
+ });
+
+ it('a real scan writes .claude/security-scans/scan-<type>-<depth>.json', () => {
+ execFileSync(
+ process.execPath,
+ [CLI_BIN, 'security', 'scan', '--target', scanTarget, '--depth', 'quick', '--type', 'deps'],
+ { encoding: 'utf-8', timeout: 30_000 },
+ );
+ const outFile = join(scanTarget, '.claude', 'security-scans', 'scan-deps-quick.json');
+ expect(existsSync(outFile)).toBe(true);
+ const record = JSON.parse(readFileSync(outFile, 'utf-8'));
+ expect(record.target).toBe(scanTarget);
+ expect(record.depth).toBe('quick');
+ expect(record.type).toBe('deps');
+ expect(typeof record.timestamp).toBe('string');
+ expect(record.summary).toMatchObject({
+ critical: expect.any(Number),
+ high: expect.any(Number),
+ medium: expect.any(Number),
+ low: expect.any(Number),
+ total: expect.any(Number),
+ });
+ });
+
+ it('getSecurityStatus reflects the real scan afterward — no longer stuck at PENDING/0', () => {
+ execFileSync(
+ process.execPath,
+ [CLI_BIN, 'security', 'scan', '--target', scanTarget, '--depth', 'quick', '--type', 'deps'],
+ { encoding: 'utf-8', timeout: 30_000 },
+ );
+ const after = getSecurityStatus(scanTarget);
+ expect(after.cvesFixed).toBeGreaterThanOrEqual(1);
+ expect(after.status).not.toBe('PENDING');
+ });
+
+ it('repeated scans overwrite the deterministic filename rather than accumulate', () => {
+ for (let i = 0; i < 3; i++) {
+ execFileSync(
+ process.execPath,
+ [CLI_BIN, 'security', 'scan', '--target', scanTarget, '--depth', 'quick', '--type', 'deps'],
+ { encoding: 'utf-8', timeout: 30_000 },
+ );
+ }
+ const scanDir = join(scanTarget, '.claude', 'security-scans');
+ const files = require('fs').readdirSync(scanDir).filter((f: string) => f.endsWith('.json'));
+ expect(files).toEqual(['scan-deps-quick.json']);
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/services/fable-harness.test.ts b/v3/@claude-flow/cli/__tests__/services/fable-harness.test.ts
index ecfe76c3c1..51ec59e2e8 100644
--- a/v3/@claude-flow/cli/__tests__/services/fable-harness.test.ts
+++ b/v3/@claude-flow/cli/__tests__/services/fable-harness.test.ts
@@ -156,6 +156,53 @@ describe('FableHarness — reflectFailures', () => {
});
});
+describe('FableHarness — adviseCoPilotTip (ADR-316)', () => {
+ it('makes ZERO spawns when no budget cap is set (off by default)', async () => {
+ const { fn, calls } = fakeSpawn(() => ({ stdout: envelope([]) }));
+ const h = new FableHarness({ spawnClaude: fn });
+ const tip = await h.adviseCoPilotTip({ gitUncommittedCount: 50 });
+ expect(tip).toBeNull();
+ expect(calls).toHaveLength(0);
+ });
+
+ it('returns a normalized tip when the model finds one worth surfacing', async () => {
+ const { fn, calls } = fakeSpawn(() => ({
+ stdout: envelope([{ headline: 'Commit your work', detail: 'You have 50 uncommitted files.', confidence: 1.4 }]),
+ }));
+ const h = new FableHarness({ maxBudgetUsd: 0.5, spawnClaude: fn });
+ const tip = await h.adviseCoPilotTip({ gitUncommittedCount: 50 });
+ expect(calls).toHaveLength(1);
+ expect(tip).toEqual({ headline: 'Commit your work', detail: 'You have 50 uncommitted files.', confidence: 1 });
+ });
+
+ it('returns null when the model explicitly finds nothing worth surfacing (empty array is not an error)', async () => {
+ const { fn, calls } = fakeSpawn(() => ({ stdout: envelope([]) }));
+ const h = new FableHarness({ maxBudgetUsd: 0.5, spawnClaude: fn });
+ const tip = await h.adviseCoPilotTip({});
+ expect(calls).toHaveLength(1);
+ expect(tip).toBeNull();
+ });
+
+ it('sends the snapshot as stdin JSON, never as an argv positional', async () => {
+ const { fn, calls } = fakeSpawn(() => ({ stdout: envelope([]) }));
+ const h = new FableHarness({ maxBudgetUsd: 0.5, spawnClaude: fn });
+ await h.adviseCoPilotTip({ gitUncommittedCount: 7 });
+ expect(calls[0].prompt).toContain('"gitUncommittedCount":7');
+ expect(calls[0].argv.join(' ')).not.toContain('7');
+ expect(calls[0].cwd).not.toBe(process.cwd());
+ });
+
+ it('never returns a tip once the harness is already at/over budget', async () => {
+ const { fn, calls } = fakeSpawn(() => ({ stdout: envelope([{ headline: 'x', detail: 'y', confidence: 0.5 }]), costUsd: 10 }));
+ const h = new FableHarness({ maxBudgetUsd: 0.1, spawnClaude: fn });
+ const first = await h.adviseCoPilotTip({});
+ expect(first).not.toBeNull(); // first call runs (spent starts at 0)
+ const second = await h.adviseCoPilotTip({});
+ expect(second).toBeNull(); // now over budget — refuses without spawning
+ expect(calls).toHaveLength(1);
+ });
+});
+
describe('extractVerdictArray', () => {
it('parses an enveloped result string', () => {
const arr = extractVerdictArray(envelope([{ id: 'x', resolved: true }]));
diff --git a/v3/@claude-flow/cli/__tests__/statusline-cost-display.test.ts b/v3/@claude-flow/cli/__tests__/statusline-cost-display.test.ts
index 67887486e2..0c5c10cd97 100644
--- a/v3/@claude-flow/cli/__tests__/statusline-cost-display.test.ts
+++ b/v3/@claude-flow/cli/__tests__/statusline-cost-display.test.ts
@@ -114,3 +114,38 @@ describe('statusline cost display — committed artifact drift guard', () => {
expect(readFileSync(artifact, 'utf-8')).toBe(SCRIPT);
});
});
+
+describe('statusline trailing newline — breathing room before the input prompt', () => {
+ it('generator source appends a trailing newline after joining lines', () => {
+ // Source-level pin: a future edit can't silently drop the `+ '\n'` without
+ // this test noticing, even before anyone runs the script.
+ expect(SCRIPT).toContain("lines.join('\\n') + '\\n'");
+ });
+
+ it('the rendered statusline output ends with a real newline character', () => {
+ const dir = mkdtempSync(path.join(tmpdir(), 'ruflo-statusline-nl-'));
+ const scriptPath = path.join(dir, 'statusline.cjs');
+ writeFileSync(scriptPath, SCRIPT, 'utf-8');
+ const payload = JSON.stringify({
+ model: { display_name: 'Opus 4.8' },
+ context_window: { used_percentage: 34 },
+ cost: { total_cost_usd: 1.3, total_duration_ms: 376000 },
+ });
+ try {
+ const out = execFileSync(process.execPath, [scriptPath], {
+ input: payload,
+ encoding: 'utf-8',
+ env: { PATH: '/nonexistent', HOME: dir },
+ timeout: 15000,
+ });
+ // console.log appends its own trailing newline on top of the one this
+ // fix adds, so the real output ends with the last content line, then
+ // exactly one blank line — not zero (no breathing room) and not two+
+ // (console.log double-counted the fix, or a duplicate `+ '\n'` crept in).
+ expect(out.endsWith('\n\n')).toBe(true);
+ expect(out.endsWith('\n\n\n')).toBe(false);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/version-anv.test.ts b/v3/@claude-flow/cli/__tests__/version-anv.test.ts
new file mode 100644
index 0000000000..fc8b277163
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/version-anv.test.ts
@@ -0,0 +1,104 @@
+/**
+ * `ruflo version` — ANV (Agent-Native Versioning) Phase 1.
+ * https://gist.github.com/ruvnet/0d858ad440a4439b4a2281a40c39b1a0
+ *
+ * Black-box against the real built CLI binary (same pattern as
+ * security-scan-persistence.test.ts) since the command's manifest
+ * resolution walks real package/dev-checkout paths — reconstructing that
+ * via mocks would test the mock, not the resolution logic.
+ */
+import { describe, it, expect } from 'vitest';
+import { execFileSync } from 'child_process';
+import { existsSync, readFileSync } from 'fs';
+import { fileURLToPath } from 'url';
+import { buildAdvisorySuffix } from '../src/commands/version.js';
+
+const CLI_BIN = fileURLToPath(new URL('../bin/cli.js', import.meta.url));
+const CLI_BUILT = existsSync(CLI_BIN);
+const MANIFEST_PATH = fileURLToPath(new URL('../catalog-manifest.json', import.meta.url));
+
+function cli(args: string[]): { out: string; code: number } {
+ try {
+ const out = execFileSync(process.execPath, [CLI_BIN, ...args], { encoding: 'utf-8', timeout: 15_000 });
+ return { out, code: 0 };
+ } catch (e) {
+ const err = e as { stdout?: string; status?: number };
+ return { out: err.stdout ?? '', code: err.status ?? 1 };
+ }
+}
+
+describe('buildAdvisorySuffix — pure function', () => {
+ it('omits the hal segment when no benchmark exists', () => {
+ const suffix = buildAdvisorySuffix({
+ schemaVersion: 1, generation: 5, generatedAt: '2026-01-01T00:00:00.000Z',
+ gitSha: 'abc12345', catalog: { agents: 1, tools: 2, skills: 3 }, benchmark: null,
+ });
+ expect(suffix).toBe('+ad.1.gabc12345.cat5');
+ });
+
+ it('appends the hal segment only when a real benchmark is present', () => {
+ const suffix = buildAdvisorySuffix({
+ schemaVersion: 1, generation: 5, generatedAt: '2026-01-01T00:00:00.000Z',
+ gitSha: 'abc12345', catalog: { agents: 1, tools: 2, skills: 3 },
+ benchmark: { tier: 74, verifiedAt: '2026-01-01T00:00:00.000Z' },
+ }, 2);
+ expect(suffix).toBe('+ad.2.gabc12345.cat5.hal74');
+ });
+
+ it('is legal semver build metadata — starts with a bare "+", npm-range-safe', () => {
+ const suffix = buildAdvisorySuffix({
+ schemaVersion: 1, generation: 1, generatedAt: '2026-01-01T00:00:00.000Z',
+ gitSha: 'deadbeef', catalog: { agents: 0, tools: 0, skills: 0 }, benchmark: null,
+ });
+ expect(suffix.startsWith('+')).toBe(true);
+ expect(suffix).not.toMatch(/[^a-z0-9.+-]/i);
+ });
+});
+
+describe.skipIf(!CLI_BUILT)('ruflo version — CLI black-box', () => {
+ it('bare "version" prints plain semver, no suffix', () => {
+ const { out, code } = cli(['version']);
+ expect(code).toBe(0);
+ expect(out.trim()).toMatch(/^\d+\.\d+\.\d+$/);
+ });
+
+ it('bare "--version" global flag is unaffected by ANV (still plain semver)', () => {
+ const { out, code } = cli(['--version']);
+ expect(code).toBe(0);
+ expect(out).toMatch(/v\d+\.\d+\.\d+/);
+ expect(out).not.toContain('+ad.');
+ });
+
+ it('"version --explain" renders the catalog breakdown when catalog-manifest.json exists', () => {
+ if (!existsSync(MANIFEST_PATH)) return; // dev checkout without a generated manifest — see next test
+ const { out, code } = cli(['version', '--explain']);
+ expect(code).toBe(0);
+ expect(out).toContain('Era: AD (Agent Descent)');
+ expect(out).toMatch(/Catalog:\s+generation \d+ \(agents: \d+ types, tools: \d+ MCP, skills: \d+\)/);
+ expect(out).toContain('+ad.1.g');
+ });
+
+ it('catalog-manifest.json counts are real numbers, never fabricated benchmark data', () => {
+ if (!existsSync(MANIFEST_PATH)) return;
+ const manifest = JSON.parse(readFileSync(MANIFEST_PATH, 'utf-8'));
+ expect(manifest.catalog.agents).toBeGreaterThan(0);
+ expect(manifest.catalog.tools).toBeGreaterThan(0);
+ expect(manifest.catalog.skills).toBeGreaterThan(0);
+ // No benchmark tier without a real signed submission for this generation.
+ if (manifest.benchmark !== null) {
+ expect(manifest.benchmark).toHaveProperty('tier');
+ expect(manifest.benchmark).toHaveProperty('verifiedAt');
+ }
+ });
+
+ it('"--require-catalog-gte" gates cleanly: pass at/under, fail over', () => {
+ if (!existsSync(MANIFEST_PATH)) return;
+ const manifest = JSON.parse(readFileSync(MANIFEST_PATH, 'utf-8'));
+ const under = cli(['version', '--require-catalog-gte', String(manifest.generation)]);
+ expect(under.code).toBe(0);
+ expect(under.out).toContain('OK');
+
+ const over = cli(['version', '--require-catalog-gte', String(manifest.generation + 1000)]);
+ expect(over.code).toBe(1);
+ });
+});
diff --git a/v3/@claude-flow/cli/catalog-manifest.json b/v3/@claude-flow/cli/catalog-manifest.json
new file mode 100644
index 0000000000..10397b0332
--- /dev/null
+++ b/v3/@claude-flow/cli/catalog-manifest.json
@@ -0,0 +1,12 @@
+{
+ "schemaVersion": 1,
+ "generation": 1,
+ "generatedAt": "2026-07-13T15:53:12.461Z",
+ "gitSha": "c4ece06d",
+ "catalog": {
+ "agents": 164,
+ "tools": 387,
+ "skills": 34
+ },
+ "benchmark": null
+}
diff --git a/v3/@claude-flow/cli/package-lock.json b/v3/@claude-flow/cli/package-lock.json
index d2018dc255..476d7fdaf8 100644
--- a/v3/@claude-flow/cli/package-lock.json
+++ b/v3/@claude-flow/cli/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@claude-flow/cli",
- "version": "3.25.6",
+ "version": "3.26.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@claude-flow/cli",
- "version": "3.25.6",
+ "version": "3.26.0",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.json
index 33234a6bbb..ccae90cd1c 100644
--- a/v3/@claude-flow/cli/package.json
+++ b/v3/@claude-flow/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@claude-flow/cli",
- "version": "3.25.6",
+ "version": "3.26.0",
"type": "module",
"description": "Ruflo CLI - Enterprise AI agent orchestration with 60+ specialized agents, swarm coordination, MCP server, self-learning hooks, and vector memory for Claude Code",
"main": "dist/src/index.js",
@@ -81,7 +81,8 @@
"scripts/postinstall.cjs",
".claude",
"plugins",
- "README.md"
+ "README.md",
+ "catalog-manifest.json"
],
"scripts": {
"build": "tsc",
@@ -89,7 +90,7 @@
"test:plugin-store": "npx tsx src/plugins/tests/standalone-test.ts",
"test:pattern-store": "npx tsx src/transfer/store/tests/standalone-test.ts",
"postinstall": "node ./scripts/postinstall.cjs",
- "prepublishOnly": "cp ../../../README.md ./README.md && rm -rf plugins && mkdir -p plugins && cp -r ../../../plugins/ruflo-metaharness plugins/ && node scripts/sign-helpers.mjs && node scripts/verify-helpers.mjs",
+ "prepublishOnly": "cp ../../../README.md ./README.md && rm -rf plugins && mkdir -p plugins && cp -r ../../../plugins/ruflo-metaharness plugins/ && node scripts/generate-catalog-manifest.mjs && node scripts/sign-helpers.mjs && node scripts/verify-helpers.mjs",
"release": "npm version prerelease --preid=alpha && npm run publish:all",
"publish:all": "./scripts/publish.sh"
},
@@ -119,6 +120,14 @@
"tag": "latest"
},
"overrides": {
- "protobufjs": ">=7.5.6"
+ "protobufjs": ">=7.5.6",
+ "js-yaml": ">=4.3.0",
+ "express": ">=4.22.2",
+ "qs": ">=6.15.2",
+ "@opentelemetry/core": ">=2.8.0",
+ "@opentelemetry/resources": ">=2.8.0",
+ "@opentelemetry/sdk-trace-base": ">=2.8.0",
+ "@opentelemetry/sdk-node": ">=0.220.0",
+ "agentdb": "$agentdb"
}
}
diff --git a/v3/@claude-flow/cli/scripts/generate-catalog-manifest.mjs b/v3/@claude-flow/cli/scripts/generate-catalog-manifest.mjs
new file mode 100644
index 0000000000..b3a170cf0e
--- /dev/null
+++ b/v3/@claude-flow/cli/scripts/generate-catalog-manifest.mjs
@@ -0,0 +1,96 @@
+#!/usr/bin/env node
+/**
+ * Generate catalog-manifest.json — ANV (Agent-Native Versioning) Phase 1.
+ * https://gist.github.com/ruvnet/0d858ad440a4439b4a2281a40c39b1a0
+ *
+ * Counts are computed from real, shipped files (git-tracked, not fabricated):
+ * - agents: git-tracked markdown files under .claude/agents and plugins agents dirs
+ * - tools: distinct `name: '...'` tool definitions across the mcp-tools sources
+ * - skills: directories under .claude/skills
+ *
+ * `generation` is a manually-bumped counter (increment when this run's counts
+ * differ from the committed manifest's) — NOT auto-incremented on every run,
+ * so a no-op regen doesn't silently claim a new catalog generation.
+ *
+ * `benchmark` stays null until a real, Ed25519-signed GAIA/HAL submission
+ * exists for this exact catalog generation — no fabricated tier numbers
+ * (ANV's own "verifiable, no unverifiable claims" principle).
+ *
+ * Run at publish time: node scripts/generate-catalog-manifest.mjs
+ */
+import { execFileSync } from 'node:child_process';
+import { readFileSync, writeFileSync, readdirSync, existsSync } from 'node:fs';
+import { join, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const PKG_ROOT = join(__dirname, '..');
+const REPO_ROOT = join(PKG_ROOT, '..', '..', '..');
+const MANIFEST_PATH = join(PKG_ROOT, 'catalog-manifest.json');
+
+function gitTrackedCount(patterns) {
+ try {
+ const out = execFileSync('git', ['ls-files', ...patterns], { cwd: REPO_ROOT, encoding: 'utf-8' });
+ return out.split('\n').filter(Boolean).length;
+ } catch {
+ return 0;
+ }
+}
+
+function countTools() {
+ const dir = join(PKG_ROOT, 'src', 'mcp-tools');
+ if (!existsSync(dir)) return 0;
+ const names = new Set();
+ for (const f of readdirSync(dir).filter((f) => f.endsWith('.ts'))) {
+ const text = readFileSync(join(dir, f), 'utf-8');
+ for (const m of text.matchAll(/name:\s*'([a-z_][a-z0-9_-]*)'/g)) names.add(m[1]);
+ }
+ return names.size;
+}
+
+function countSkills() {
+ const dir = join(PKG_ROOT, '.claude', 'skills');
+ if (!existsSync(dir)) return 0;
+ return readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory()).length;
+}
+
+function gitShortSha() {
+ try {
+ return execFileSync('git', ['rev-parse', '--short=8', 'HEAD'], { cwd: REPO_ROOT, encoding: 'utf-8' }).trim();
+ } catch {
+ return 'unknown';
+ }
+}
+
+const counts = {
+ agents: gitTrackedCount(['.claude/agents/*.md', 'plugins/*/agents/*.md']),
+ tools: countTools(),
+ skills: countSkills(),
+};
+
+let generation = 1;
+let previous = null;
+if (existsSync(MANIFEST_PATH)) {
+ try { previous = JSON.parse(readFileSync(MANIFEST_PATH, 'utf-8')); } catch { /* corrupt/missing — start fresh */ }
+}
+if (previous?.catalog) {
+ const changed = previous.catalog.agents !== counts.agents
+ || previous.catalog.tools !== counts.tools
+ || previous.catalog.skills !== counts.skills;
+ generation = changed ? (previous.generation ?? 0) + 1 : (previous.generation ?? 1);
+}
+
+const manifest = {
+ schemaVersion: 1,
+ generation,
+ generatedAt: new Date().toISOString(),
+ gitSha: gitShortSha(),
+ catalog: counts,
+ // No fabricated benchmark tier — filled in only by a real, signed GAIA/HAL
+ // submission for this exact catalog generation.
+ benchmark: previous?.benchmark?.generation === generation ? previous.benchmark : null,
+};
+
+writeFileSync(MANIFEST_PATH, JSON.stringify(manifest, null, 2) + '\n', 'utf-8');
+console.log(`[catalog-manifest] generation ${generation} — agents:${counts.agents} tools:${counts.tools} skills:${counts.skills} sha:${manifest.gitSha}`);
+console.log(` -> ${MANIFEST_PATH}`);
diff --git a/v3/@claude-flow/cli/scripts/sign-helpers.mjs b/v3/@claude-flow/cli/scripts/sign-helpers.mjs
index 4b49326ec7..eb1e085909 100644
--- a/v3/@claude-flow/cli/scripts/sign-helpers.mjs
+++ b/v3/@claude-flow/cli/scripts/sign-helpers.mjs
@@ -27,7 +27,8 @@ import { homedir } from 'node:os';
const __dirname = dirname(fileURLToPath(import.meta.url));
const PKG_ROOT = join(__dirname, '..');
const HELPERS_DIR = join(PKG_ROOT, '.claude', 'helpers');
-const CRITICAL = ['auto-memory-hook.mjs', 'hook-handler.cjs', 'intelligence.cjs'];
+// Keep in sync with src/init/helper-refresh.ts:CRITICAL_HELPERS.
+const CRITICAL = ['auto-memory-hook.mjs', 'hook-handler.cjs', 'intelligence.cjs', 'statusline.cjs'];
function loadPrivateKey() {
const secret = process.env.RUFLO_HELPERS_SIGNING_SECRET;
@@ -36,8 +37,12 @@ function loadPrivateKey() {
const project = process.env.RUFLO_HELPERS_SIGNING_PROJECT;
if (project) args.push('--project', project);
try {
- // stdio: key on stdout (captured), stderr inherited for auth prompts/errors.
- return execFileSync('gcloud', args, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'inherit'] });
+ // stdio: key on stdout (captured), stderr captured too — NOT inherited.
+ // Inheriting would forward gcloud's stderr verbatim into whatever log
+ // is capturing this process's output (CI, terminal); this key material
+ // is sensitive enough that we never want an uncontrolled passthrough,
+ // even though gcloud's normal error paths don't echo secret payloads.
+ return execFileSync('gcloud', args, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] });
} catch (e) {
console.error(`[sign-helpers] failed to read GCP secret '${secret}'. Is gcloud authed? (gcloud auth login)`);
process.exit(1);
diff --git a/v3/@claude-flow/cli/scripts/sign-proven-config.mjs b/v3/@claude-flow/cli/scripts/sign-proven-config.mjs
index ff580febce..d5eb123e3e 100644
--- a/v3/@claude-flow/cli/scripts/sign-proven-config.mjs
+++ b/v3/@claude-flow/cli/scripts/sign-proven-config.mjs
@@ -30,7 +30,10 @@ function loadPrivateKey() {
const project = process.env.RUFLO_CONFIG_SIGNING_PROJECT || 'ruv-dev';
if (project) args.push('--project', project);
try {
- return execFileSync('gcloud', args, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'inherit'] });
+ // stderr captured, not inherited — see sign-helpers.mjs::loadPrivateKey
+ // for why this key-fetch call never passes through a subprocess's raw
+ // stderr uncontrolled (CodeQL js/clear-text-logging).
+ return execFileSync('gcloud', args, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] });
} catch {
console.error(`[sign-proven-config] failed to read GCP secret '${secret}'. gcloud authed? (gcloud auth login)`);
process.exit(1);
diff --git a/v3/@claude-flow/cli/scripts/verify-helpers.mjs b/v3/@claude-flow/cli/scripts/verify-helpers.mjs
index 01885252f6..fa63948023 100644
--- a/v3/@claude-flow/cli/scripts/verify-helpers.mjs
+++ b/v3/@claude-flow/cli/scripts/verify-helpers.mjs
@@ -21,7 +21,8 @@ import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const PKG_ROOT = join(__dirname, '..');
const HELPERS_DIR = resolve(process.argv[2] || join(PKG_ROOT, '.claude', 'helpers'));
-const CRITICAL = ['auto-memory-hook.mjs', 'hook-handler.cjs', 'intelligence.cjs'];
+// Keep in sync with sign-helpers.mjs:CRITICAL and src/init/helper-refresh.ts:CRITICAL_HELPERS.
+const CRITICAL = ['auto-memory-hook.mjs', 'hook-handler.cjs', 'intelligence.cjs', 'statusline.cjs'];
const RUFLO_HELPERS_PUBKEY = `-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAhnFv74/CRcGWd0hL8zjyZ+52bIJ9SfcSgOutuKgo0Vg=
diff --git a/v3/@claude-flow/cli/src/commands/advisor.ts b/v3/@claude-flow/cli/src/commands/advisor.ts
new file mode 100644
index 0000000000..5cd58b2761
--- /dev/null
+++ b/v3/@claude-flow/cli/src/commands/advisor.ts
@@ -0,0 +1,99 @@
+/**
+ * `ruflo advisor` — Fable co-pilot advisor tip in the statusline insight
+ * ticker (ADR-316).
+ *
+ * Client-side only — unlike `proxy.ts`'s sponsored-downtime/power-saver/
+ * training-share domains, this feature has NO proxy-config.toml mirror,
+ * because it never talks to the meta-proxy Rust binary. It calls
+ * `claude -p` directly via services/fable-harness.ts (ADR-172's existing
+ * cost-disciplined harness) and caches the result for the insight ticker
+ * (funnel/insights.ts) to read synchronously.
+ */
+
+import type { Command, CommandResult } from '../types.js';
+import { output } from '../output.js';
+import { hasConsent, recordConsent, revokeConsent } from '../funnel/consent.js';
+import { recordFunnelEvent } from '../funnel/events.js';
+import { getInstalledCliVersion } from '../init/helper-refresh.js';
+import { readAdvisorTip, ADVISOR_DEFAULT_BUDGET_USD } from '../funnel/advisor-tip.js';
+
+const ADVISOR_DISCLOSURE = [
+ 'Enabling the co-pilot advisor tip.',
+ '',
+ 'At most once per day, ruflo will send a small STRUCTURAL snapshot of your',
+ 'session — security scan status, swarm/agent state, git uncommitted-file',
+ 'COUNT — never raw prompts, file contents, or commands — to a headless',
+ 'Fable model (via `claude -p`) and cache one short, actionable tip for the',
+ 'statusline insight ticker.',
+ '',
+ `This is a real, metered API call (~$${ADVISOR_DEFAULT_BUDGET_USD.toFixed(2)} budget cap per`,
+ 'refresh, at most once/day). Disable anytime: ruflo advisor disable',
+].join('\n');
+
+const enableSub: Command = {
+ name: 'enable',
+ description: 'Opt into the co-pilot advisor tip (ADR-316)',
+ options: [
+ { name: 'yes', description: 'Skip the confirmation prompt', type: 'boolean', default: false },
+ ],
+ action: async (ctx): Promise<CommandResult> => {
+ if (hasConsent('advisor-tips')) {
+ output.writeln('Advisor tip is already enabled.');
+ return { success: true, data: { alreadyEnabled: true } };
+ }
+ output.writeln(ADVISOR_DISCLOSURE);
+ output.writeln('');
+ if (!ctx.flags.yes) {
+ output.writeln('Re-run with --yes to confirm: ruflo advisor enable --yes');
+ return { success: true, data: { confirmed: false } };
+ }
+ recordConsent('advisor-tips', true, 'advisor-enable');
+ recordFunnelEvent('advisor_tip_enabled', 'statusline', getInstalledCliVersion());
+ output.printSuccess('Advisor tip enabled.');
+ output.writeln('It refreshes at most once/day, in the background, on session-restore.');
+ output.writeln('Disable anytime: ruflo advisor disable');
+ return { success: true, data: { confirmed: true } };
+ },
+};
+
+const disableSub: Command = {
+ name: 'disable',
+ description: 'Revoke advisor-tip consent and stop generating new tips',
+ action: async (): Promise<CommandResult> => {
+ revokeConsent('advisor-tips', 'advisor-disable');
+ recordFunnelEvent('advisor_tip_disabled', 'statusline', getInstalledCliVersion());
+ output.printSuccess('Advisor tip disabled.');
+ return { success: true };
+ },
+};
+
+const statusSub: Command = {
+ name: 'status',
+ description: 'Show advisor-tip consent state and the current cached tip',
+ action: async (): Promise<CommandResult> => {
+ const consented = hasConsent('advisor-tips');
+ output.writeln(`Advisor tip consent: ${consented ? 'granted' : 'not granted'}`);
+ const tip = consented ? readAdvisorTip() : null;
+ if (tip) {
+ output.writeln(`Current tip: ${tip.headline}`);
+ if (tip.detail) output.writeln(` ${tip.detail}`);
+ } else if (consented) {
+ output.writeln('No cached tip yet (refreshes at most once/day on session-restore).');
+ }
+ return { success: true, data: { consented, tip } };
+ },
+};
+
+export const advisorCommand: Command = {
+ name: 'advisor',
+ description: 'Fable co-pilot advisor tip in the statusline insight ticker (ADR-316)',
+ subcommands: [enableSub, disableSub, statusSub],
+ examples: [
+ { command: 'ruflo advisor enable --yes', description: 'Opt into the co-pilot advisor tip' },
+ { command: 'ruflo advisor status', description: 'Show consent state + current cached tip' },
+ { command: 'ruflo advisor disable', description: 'Revoke consent and stop generating tips' },
+ ],
+ action: statusSub.action,
+};
+
+export default advisorCommand;
diff --git a/v3/@claude-flow/cli/src/commands/doctor.ts b/v3/@claude-flow/cli/src/commands/doctor.ts
index 8813bff845..47fee84c65 100644
--- a/v3/@claude-flow/cli/src/commands/doctor.ts
+++ b/v3/@claude-flow/cli/src/commands/doctor.ts
@@ -154,8 +154,10 @@ async function checkConfigFile(): Promise<HealthCheck> {
* the broken commands).
*/
async function checkStaleSettingsNpx(): Promise<HealthCheck> {
- // Same regex pattern the executor migration uses — kept in sync.
- const BROKEN_RE = /npx\s+(?:--?\S+\s+)*@?claude-flow\/cli@latest\s+hooks\s+(?:statusline|\S+)/;
+ // Same regex pattern the executor migration uses — kept in sync. Flag-list
+ // repetition bounded at 10 (CodeQL js/redos — unbounded `*` here is
+ // exponential-backtracking-prone on a crafted settings.json).
+ const BROKEN_RE = /npx\s+(?:--?\S+\s+){0,10}@?claude-flow\/cli@latest\s+hooks\s+(?:statusline|\S+)/;
// Look in both project-local and home-dir settings.
const candidates = [
@@ -765,6 +767,77 @@ async function checkVersionFreshness(): Promise<HealthCheck> {
* - plugins/ruflo-metaharness/skills/harness-similarity/SKILL.md
* - plugins/ruflo-metaharness/skills/harness-drift-from-history/SKILL.md (iter 53)
*/
+/**
+ * ADR-305 — funnel state audit. Reports the effective enabled/disabled
+ * state and, critically for enterprise audit verification, WHICH
+ * precedence source decided it (env > enterprise > user > default).
+ * Informational: both states are `pass`; only a resolver failure warns.
+ */
+async function checkFunnel(): Promise<HealthCheck> {
+ try {
+ const { resolveFunnelEnabled, getDisclosure } = await import('../funnel/index.js');
+ const decision = resolveFunnelEnabled();
+ const disclosure = getDisclosure();
+ return {
+ name: 'Funnel (ADR-305)',
+ status: 'pass',
+ message: `${decision.enabled ? 'enabled' : 'disabled'} (decided by: ${decision.decidedBy}; disclosure: ${disclosure.state})`,
+ };
+ } catch (err) {
+ return {
+ name: 'Funnel (ADR-305)',
+ status: 'warn',
+ message: `state unreadable: ${err instanceof Error ? err.message : String(err)}`,
+ fix: 'ruflo funnel status',
+ };
+ }
+}
+
+/** Meta LLM Proxy — sponsored-downtime health (ADR-313). */
+async function checkProxy(): Promise<HealthCheck> {
+ try {
+ const { funnelStateDir, hasConsent, readRateLimitStatus, lastRecordedEvent } = await import('../funnel/index.js');
+ const dir = funnelStateDir();
+ const installed = existsSync(join(dir, 'proxy-token'));
+ const consented = hasConsent('sponsored-downtime');
+ const rateLimited = readRateLimitStatus();
+ const lastExhausted = lastRecordedEvent('sponsor_capacity_exhausted');
+
+ if (!installed) {
+ return {
+ name: 'Meta LLM Proxy (ADR-313)',
+ status: 'warn',
+ message: 'not installed — no proxy-token found; sponsored-downtime capacity is unavailable',
+ fix: 'See cognitum-one/meta-proxy (private) for install instructions',
+ };
+ }
+
+ const parts = [
+ `sponsored consent: ${consented ? 'granted' : 'not granted'}`,
+ `rate-limit flag: ${rateLimited.limited ? `set (since ${rateLimited.since})` : 'not set'}`,
+ ];
+ if (lastExhausted) parts.push(`last capacity-exhausted: ${lastExhausted}`);
+
+ if (rateLimited.limited && !consented) {
+ return {
+ name: 'Meta LLM Proxy (ADR-313)',
+ status: 'warn',
+ message: `${parts.join('; ')} — flagged rate-limited but sponsored capacity isn't enabled`,
+ fix: 'ruflo proxy sponsor-enable --yes',
+ };
+ }
+
+ return { name: 'Meta LLM Proxy (ADR-313)', status: 'pass', message: parts.join('; ') };
+ } catch (err) {
+ return {
+ name: 'Meta LLM Proxy (ADR-313)',
+ status: 'warn',
+ message: `state unreadable: ${err instanceof Error ? err.message : String(err)}`,
+ fix: 'ruflo proxy sponsor-status',
+ };
+ }
+}
+
async function checkMetaharnessIntegration(): Promise<HealthCheck> {
// Locate plugins dir.
//
@@ -1149,7 +1222,7 @@ export const doctorCommand: Command = {
{
name: 'component',
short: 'c',
- description: 'Check specific component (version, node, npm, config, daemon, memory, api, git, mcp, claude, disk, typescript, agentic-flow, encryption, federation, metaharness)',
+ description: 'Check specific component (version, node, npm, config, daemon, memory, api, git, mcp, claude, disk, typescript, agentic-flow, encryption, federation, funnel, proxy, metaharness)',
type: 'string'
},
{
@@ -1201,6 +1274,8 @@ export const doctorCommand: Command = {
checkFederationBreaker, // ADR-097 Phase 4
checkMetaharness, // ADR-150 — MetaHarness upstream package
checkMetaharnessIntegration, // iter 45 — ruflo-side integration layer
+ checkFunnel, // ADR-305 — effective funnel state + deciding precedence source
+ checkProxy, // ADR-313 — Meta LLM Proxy sponsored-downtime health
];
const componentMap: Record<string, () => Promise<HealthCheck>> = {
@@ -1226,6 +1301,8 @@ export const doctorCommand: Command = {
'federation': checkFederationBreaker, // ADR-097 Phase 4
'metaharness': checkMetaharness, // ADR-150 — upstream package
'metaharness-integration': checkMetaharnessIntegration, // iter 45 — ruflo-side
+ 'funnel': checkFunnel, // ADR-305
+ 'proxy': checkProxy, // ADR-313
};
let checksToRun = allChecks;
diff --git a/v3/@claude-flow/cli/src/commands/funnel.ts b/v3/@claude-flow/cli/src/commands/funnel.ts
new file mode 100644
index 0000000000..7321ecc4d9
--- /dev/null
+++ b/v3/@claude-flow/cli/src/commands/funnel.ts
@@ -0,0 +1,121 @@
+/**
+ * `ruflo funnel` — user control surface for the Cognitum lifecycle funnel
+ * (ADR-301/305/309).
+ *
+ * funnel status effective state and which precedence source decided it
+ * funnel disable user-level opt-out (all surfaces) + delete funnel data
+ * funnel enable re-enable at the user tier (cannot override env/enterprise)
+ * funnel id print the pseudonymous funnel ID, if one exists
+ */
+
+import type { Command, CommandContext, CommandResult } from '../types.js';
+import { output } from '../output.js';
+import {
+ deleteFunnelData,
+ funnelStateDir,
+ getDisclosure,
+ getFunnelId,
+ readConsents,
+ recordDisclosureDeclined,
+ recordDisclosureReenabled,
+ resolveFunnelEnabled,
+} from '../funnel/index.js';
+import { readStateJson, writeStateJson } from '../funnel/state.js';
+
+function setUserConfigEnabled(enabled: boolean): void {
+ const cfg = readStateJson<Record<string, unknown>>('funnel.json') ?? {};
+ cfg.enabled = enabled;
+ writeStateJson('funnel.json', cfg);
+}
+
+const statusSub: Command = {
+ name: 'status',
+ description: 'Show effective funnel state and which source decided it',
+ options: [
+ { name: 'json', description: 'Output as JSON', type: 'boolean', default: false },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const decision = resolveFunnelEnabled();
+ const disclosure = getDisclosure();
+ const consents = readConsents();
+ const data = {
+ enabled: decision.enabled,
+ decidedBy: decision.decidedBy,
+ disclosure: disclosure.state,
+ stateDir: funnelStateDir(),
+ consents,
+ };
+ if (ctx.flags.json) {
+ output.printJson(data);
+ } else {
+ output.writeln(`Funnel: ${decision.enabled ? 'enabled' : 'disabled'} (decided by: ${decision.decidedBy})`);
+ output.writeln(`Disclosure: ${disclosure.state}`);
+ output.writeln(`State dir: ${funnelStateDir()}`);
+ const domains = Object.keys(consents);
+ output.writeln(
+ domains.length
+ ? `Consents: ${domains.map((d) => `${d}=${(consents as Record<string, { granted?: boolean }>)[d]?.granted ? 'granted' : 'declined'}`).join(', ')}`
+ : 'Consents: none recorded'
+ );
+ }
+ return { success: true, data };
+ },
+};
+
+const disableSub: Command = {
+ name: 'disable',
+ description: 'Disable all funnel surfaces (user-level, persists across projects)',
+ action: async (): Promise<CommandResult> => {
+ setUserConfigEnabled(false);
+ recordDisclosureDeclined();
+ deleteFunnelData(); // opt-out deletes the pseudonymous ID + local event queue
+ output.printSuccess('Funnel disabled. All promotional surfaces are off; local funnel data deleted.');
+ return { success: true };
+ },
+};
+
+const enableSub: Command = {
+ name: 'enable',
+ description: 'Re-enable funnel surfaces at the user tier (env/enterprise disables still win)',
+ action: async (): Promise<CommandResult> => {
+ setUserConfigEnabled(true);
+ recordDisclosureReenabled();
+ const decision = resolveFunnelEnabled();
+ if (decision.enabled) {
+ output.printSuccess('Funnel enabled.');
+ } else {
+ // A lower-precedence source never overrides a higher-precedence disable.
+ output.printWarning(
+ `User preference recorded, but the funnel stays disabled by a higher-precedence source: ${decision.decidedBy}`
+ );
+ }
+ return { success: true, data: decision };
+ },
+};
+
+const idSub: Command = {
+ name: 'id',
+ description: 'Print the pseudonymous funnel ID (exists only with telemetry consent)',
+ action: async (): Promise<CommandResult> => {
+ const id = getFunnelId();
+ if (id) {
+ output.writeln(id);
+ } else {
+ output.writeln('No funnel ID (telemetry consent not granted, or funnel data deleted).');
+ }
+ return { success: true, data: { id } };
+ },
+};
+
+export const funnelCommand: Command = {
+ name: 'funnel',
+ description: 'Control the Cognitum lifecycle funnel surfaces (tips, enrollment, notices)',
+ subcommands: [statusSub, disableSub, enableSub, idSub],
+ examples: [
+ { command: 'ruflo funnel status', description: 'Effective state + deciding source' },
+ { command: 'ruflo funnel disable', description: 'Turn off every funnel surface' },
+ ],
+ action: statusSub.action,
+};
+
+export default funnelCommand;
diff --git a/v3/@claude-flow/cli/src/commands/hooks.ts b/v3/@claude-flow/cli/src/commands/hooks.ts
index 66b8b84aa8..95f12f0d9a 100644
--- a/v3/@claude-flow/cli/src/commands/hooks.ts
+++ b/v3/@claude-flow/cli/src/commands/hooks.ts
@@ -10,6 +10,11 @@ import { callMCPTool, MCPClientError } from '../mcp-client.js';
import { storeCommand } from './transfer-store.js';
import { existsSync, readFileSync, statSync } from 'node:fs';
import { join } from 'node:path';
+import {
+ getSecurityStatus as sharedGetSecurityStatus,
+ getSwarmStatus as sharedGetSwarmStatus,
+ getGitUncommittedCount as sharedGetGitUncommittedCount,
+} from '../funnel/local-signals.js';
/**
* #1686 — `?? 0` only defaults null/undefined; NaN slips through and
@@ -4127,55 +4132,11 @@ const statuslineCommand: Command = {
return { domainsCompleted, totalDomains, dddProgress, patternsLearned: learning.patterns, sessionsCompleted: learning.sessions };
}
- // Get security status
- function getSecurityStatus() {
- const scanResultsPath = path.join(process.cwd(), '.claude', 'security-scans');
- let cvesFixed = 0;
- const totalCves = 3;
-
- if (fs.existsSync(scanResultsPath)) {
- try {
- const scans = fs.readdirSync(scanResultsPath).filter((f: string) => f.endsWith('.json'));
- cvesFixed = Math.min(totalCves, scans.length);
- } catch {
- // Ignore
- }
- }
-
- const auditPath = path.join(process.cwd(), '.swarm', 'security');
- if (fs.existsSync(auditPath)) {
- try {
- const audits = fs.readdirSync(auditPath).filter((f: string) => f.includes('audit'));
- cvesFixed = Math.min(totalCves, Math.max(cvesFixed, audits.length));
- } catch {
- // Ignore
- }
- }
-
- const status = cvesFixed >= totalCves ? 'CLEAN' : cvesFixed > 0 ? 'IN_PROGRESS' : 'PENDING';
- return { status, cvesFixed, totalCves };
- }
-
- // Get swarm status
- function getSwarmStatus() {
- let activeAgents = 0;
- let coordinationActive = false;
- const maxAgents = 15;
- const isWindows = process.platform === 'win32';
-
- try {
- const psCmd = isWindows
- ? 'tasklist /FI "IMAGENAME eq node.exe" /NH 2>NUL | find /c /v "" 2>NUL || echo 0'
- : 'ps aux 2>/dev/null | grep -c agentic-flow || echo "0"';
- const ps = execSync(psCmd, { encoding: 'utf-8', timeout: 3000 });
- activeAgents = Math.max(0, parseInt(ps.trim()) - 1);
- coordinationActive = activeAgents > 0;
- } catch {
- // ps/tasklist unavailable or timed out — report zero
- }
-
- return { activeAgents, maxAgents, coordinationActive };
- }
+ // Security/swarm status — shared with the advisor-tip refresh (ADR-316)
+ // via funnel/local-signals.ts, a single source of truth so the two call
+ // sites can never silently drift on what these signals mean.
+ const getSecurityStatus = sharedGetSecurityStatus;
+ const getSwarmStatus = sharedGetSwarmStatus;
// Get system metrics
function getSystemMetrics() {
@@ -4274,6 +4235,23 @@ const statuslineCommand: Command = {
const swarm = getSwarmStatus();
const system = getSystemMetrics();
const user = getUserInfo();
+ const getGitUncommittedCount = sharedGetGitUncommittedCount;
+
+ // Funnel promo row (ADR-301). The statusline is spawned with piped stdio
+ // by an interactive host, so interactivity is asserted here; all other
+ // gates (RUFLO_FUNNEL, enterprise policy, config, CI, disclosure,
+ // rotation ratio) are enforced inside getFunnelPromo. Never allowed to
+ // break the statusline.
+ let promo: import('../funnel/types.js').PromoRow | null = null;
+ try {
+ const { getFunnelPromo } = await import('../funnel/index.js');
+ promo = getFunnelPromo({
+ interactive: true,
+ localInsights: { security, swarm, gitUncommittedCount: getGitUncommittedCount() },
+ });
+ } catch {
+ promo = null;
+ }
const statusData = {
user,
@@ -4281,6 +4259,7 @@ const statuslineCommand: Command = {
security,
swarm,
system,
+ promo,
timestamp: new Date().toISOString()
};
@@ -5249,6 +5228,90 @@ const notifyCommand: Command = {
}
};
+// Refresh-funnel subcommand — the fix for "promo doesn't load right away".
+//
+// refreshRemoteMessages() (funnel/message-transport.ts) is fire-and-forget
+// by design so the STATUSLINE's own per-render invocation never blocks on
+// a network call. But the statusline is spawned as a short-lived subprocess
+// per render (execSync from statusline-generator.ts) — a fire-and-forget
+// promise kicked off there has no "later" to run in; the process exits
+// before the HTTPS fetch can complete, so the local message cache never
+// actually gets written and the promo row never appears (confirmed live:
+// two consecutive cold-cache statusline renders, 5s apart, both returned
+// promo:null and the cache file was never created).
+//
+// This command exists to be invoked from a LONGER-LIVED context — the
+// SessionStart hook (see hook-handler.cjs's 'session-restore' handler,
+// which spawns this detached so it isn't killed when the hook's own
+// process exits, and isn't awaited so it doesn't add to the hook's own
+// timeout budget). One real, properly-awaited refresh attempt here, once
+// per session, is what actually gives refreshRemoteMessages() a chance to
+// finish before anything needs the cache.
+const refreshFunnelCommand: Command = {
+ name: 'refresh-funnel',
+ description: 'Best-effort background refresh of the funnel message cache (internal — see hook-handler.cjs session-restore)',
+ options: [
+ { name: 'quiet', description: 'Suppress output (used when spawned detached from a hook)', type: 'boolean', default: false },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ try {
+ const { refreshRemoteMessages } = await import('../funnel/index.js');
+ const result = await refreshRemoteMessages();
+ if (!ctx.flags.quiet) {
+ output.writeln(JSON.stringify(result));
+ }
+ return { success: true, data: result };
+ } catch (error) {
+ // Fail silent by design (matches message-transport.ts's own "fail
+ // silent" discipline) — a broken refresh must never surface as a
+ // hook error, only ever as "no promo this session."
+ if (!ctx.flags.quiet) {
+ output.printError(`refresh-funnel failed: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ return { success: true, data: { refreshed: false, skipped: 'error' } };
+ }
+ }
+};
+
+// Refresh-advisor subcommand — ADR-316's co-pilot tip. Mirrors
+// refreshFunnelCommand exactly: a properly-awaited CLI subcommand meant to
+// be spawned DETACHED from hook-handler.cjs's session-restore handler, so a
+// real (potentially multi-second, real-money) `claude -p` call gets a
+// chance to finish without ever blocking or being awaited by the hook's own
+// process. refreshAdvisorTipIfStale() itself is the safety net that makes
+// this cheap to call on every session-restore: it checks consent + a 24h
+// TTL BEFORE spending anything, so most invocations are a no-op file read.
+const refreshAdvisorCommand: Command = {
+ name: 'refresh-advisor',
+ description: 'Best-effort background refresh of the co-pilot advisor tip (internal — see hook-handler.cjs session-restore; ADR-316)',
+ options: [
+ { name: 'quiet', description: 'Suppress output (used when spawned detached from a hook)', type: 'boolean', default: false },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ try {
+ const { refreshAdvisorTipIfStale } = await import('../funnel/advisor-tip.js');
+ const { getSecurityStatus, getSwarmStatus, getGitUncommittedCount } = await import('../funnel/local-signals.js');
+ const result = await refreshAdvisorTipIfStale({
+ security: getSecurityStatus(),
+ swarm: getSwarmStatus(),
+ gitUncommittedCount: getGitUncommittedCount(),
+ });
+ if (!ctx.flags.quiet) {
+ output.writeln(JSON.stringify(result));
+ }
+ return { success: true, data: result };
+ } catch (error) {
+ // Fail silent by design (matches refresh-funnel's own discipline) — a
+ // broken advisor refresh must never surface as a hook error, only
+ // ever as "no tip this window."
+ if (!ctx.flags.quiet) {
+ output.printError(`refresh-advisor failed: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ return { success: true, data: { refreshed: false, reason: 'error' } };
+ }
+ }
+};
+
// Main hooks command
export const hooksCommand: Command = {
name: 'hooks',
@@ -5292,6 +5355,10 @@ export const hooksCommand: Command = {
// Agent Teams integration
teammateIdleCommand,
taskCompletedCommand,
+ // Funnel background refresh — see refreshFunnelCommand's own doc comment
+ refreshFunnelCommand,
+ // Advisor co-pilot tip background refresh — ADR-316
+ refreshAdvisorCommand,
],
options: [],
examples: [
diff --git a/v3/@claude-flow/cli/src/commands/index.ts b/v3/@claude-flow/cli/src/commands/index.ts
index 46cc06fa01..818bd0b6e9 100644
--- a/v3/@claude-flow/cli/src/commands/index.ts
+++ b/v3/@claude-flow/cli/src/commands/index.ts
@@ -40,6 +40,7 @@ const commandLoaders: Record<string, CommandLoader> = {
'hive-mind': () => import('./hive-mind.js'),
process: () => import('./process.js'),
daemon: () => import('./daemon.js'),
+ version: () => import('./version.js'),
// V3 Advanced Commands (less frequently used - lazy load)
neural: () => import('./neural.js'),
security: () => import('./security.js'),
@@ -82,6 +83,15 @@ const commandLoaders: Record<string, CommandLoader> = {
metaharness: () => import('./metaharness.js'),
// Eject (ADR-150 Phase 2) — lift ruflo project into a renamed standalone harness
eject: () => import('./eject.js'),
+ // Cognitum lifecycle funnel controls (ADR-301/305/309)
+ funnel: () => import('./funnel.js'),
+ // User-facing preferences wrapper (ADR-311 copy discipline — no "funnel" in
+ // the user surface). Forwards to the funnel primitives internally.
+ settings: () => import('./settings.js'),
+ // Meta LLM Proxy — sponsored downtime capacity (ADR-304/307/313)
+ proxy: () => import('./proxy.js'),
+ // Fable co-pilot advisor tip in the statusline insight ticker (ADR-316)
+ advisor: () => import('./advisor.js'),
};
// Cache for loaded commands
diff --git a/v3/@claude-flow/cli/src/commands/init.ts b/v3/@claude-flow/cli/src/commands/init.ts
index f1a3028073..c4e61750ae 100644
--- a/v3/@claude-flow/cli/src/commands/init.ts
+++ b/v3/@claude-flow/cli/src/commands/init.ts
@@ -17,6 +17,42 @@ import {
FULL_INIT_OPTIONS,
type InitOptions,
} from '../init/index.js';
+import {
+ ENROLLMENT_SCREEN,
+ recordEnrollmentOutcome,
+ shouldOfferEnrollment,
+} from '../funnel/enrollment.js';
+
+/**
+ * ADR-302 post-init capability enrollment. One-time, interactive-TTY-only,
+ * skippable with --no-signup, auto-skipped in CI/automation. Never throws
+ * and never affects init's exit code. Accepting records the `account`
+ * consent receipt only — no other capability is enabled by this prompt.
+ */
+async function offerCapabilityEnrollment(ctx: CommandContext): Promise<void> {
+ try {
+ const noSignup = Boolean(ctx.flags['no-signup'] || ctx.flags.noSignup);
+ if (ctx.flags.format === 'json') return; // scripted output stays pure
+ if (!shouldOfferEnrollment({ noSignup, cwd: ctx.cwd })) return;
+ output.writeln();
+ output.writeln(ENROLLMENT_SCREEN);
+ output.writeln();
+ const accepted = await confirm({
+ message: 'Create a free Cognitum account now?',
+ default: false,
+ });
+ recordEnrollmentOutcome(Boolean(accepted));
+ output.writeln();
+ if (accepted) {
+ output.printInfo('Create your free account at https://cognitum.one');
+ output.writeln(output.dim(' CLI sign-in (`ruflo auth login`) ships with the ADR-306 auth release.'));
+ } else {
+ output.writeln(output.dim('You can enable later at https://cognitum.one — this prompt will not repeat.'));
+ }
+ } catch {
+ // Enrollment is optional; init success is never affected.
+ }
+}
// Codex initialization action
async function initCodexAction(
@@ -525,6 +561,8 @@ const initAction = async (ctx: CommandContext): Promise<CommandResult> => {
output.printJson(result);
}
+ await offerCapabilityEnrollment(ctx);
+
return { success: true, data: result };
} catch (error) {
spinner.fail('Initialization failed');
@@ -788,6 +826,8 @@ const wizardCommand: Command = {
],
});
+ await offerCapabilityEnrollment(ctx);
+
return { success: true, data: result };
} catch (error) {
if (error instanceof Error && error.message === 'User cancelled') {
@@ -1165,6 +1205,13 @@ export const initCommand: Command = {
type: 'boolean',
default: false,
},
+ {
+ // ADR-302 — skip the one-time post-init capability enrollment prompt.
+ name: 'no-signup',
+ description: 'Skip the post-init Cognitum capability enrollment prompt',
+ type: 'boolean',
+ default: false,
+ },
{
name: 'only-claude',
description: 'Only create .claude/ directory (skip runtime)',
diff --git a/v3/@claude-flow/cli/src/commands/proxy.ts b/v3/@claude-flow/cli/src/commands/proxy.ts
new file mode 100644
index 0000000000..02e360f5f9
--- /dev/null
+++ b/v3/@claude-flow/cli/src/commands/proxy.ts
@@ -0,0 +1,331 @@
+/**
+ * `ruflo proxy` — Meta LLM Proxy control surface (ADR-304/307/313).
+ *
+ * This command currently implements the ADR-313 sponsored-downtime
+ * subcommands only (`sponsor-enable` / `sponsor-disable` / `sponsor-status`).
+ * The full lifecycle command set ADR-307 specifies
+ * (`install|start|stop|status|logs|update|uninstall`) manages the proxy
+ * *process* itself and is out of scope here — this surface only manages
+ * the consent-gated sponsored-mode flag the already-running proxy reads
+ * from its config mirror.
+ *
+ * Consent (ADR-302/313): granting `sponsored-downtime` consent here writes
+ * BOTH the ruflo-side consent receipt (source of truth) AND a mirror flag
+ * into ~/.ruflo/proxy-config.toml (the file the Rust proxy binary reads).
+ * The proxy never writes this file — ruflo does, exactly once per
+ * enable/disable action.
+ */
+
+import * as fs from 'fs';
+import type { Command, CommandResult } from '../types.js';
+import { output } from '../output.js';
+import { hasConsent, recordConsent, revokeConsent, funnelStateDir } from '../funnel/index.js';
+import { recordFunnelEvent } from '../funnel/events.js';
+import { clearRateLimitStatus, readRateLimitStatus } from '../funnel/rate-limit-notifier.js';
+import { clearQuotaLowStatus, readQuotaLowStatus } from '../funnel/power-saver-notifier.js';
+import { getInstalledCliVersion } from '../init/helper-refresh.js';
+import * as path from 'path';
+
+const PROXY_CONFIG_FILE = 'proxy-config.toml';
+
+/**
+ * Minimal hand-rolled TOML writer — this config has exactly one boolean
+ * field ruflo needs to set (`sponsored_consent_granted`); every other field
+ * the proxy binary defaults itself (ADR-307 "a malformed config must never
+ * crash the proxy — it degrades to safe defaults"). We read-modify-write
+ * the raw text so a user's own bind/backend customizations survive, only
+ * ever touching this one line. No TOML parser dependency needed for this.
+ */
+function readProxyConfigRaw(): string {
+ try {
+ return fs.readFileSync(path.join(funnelStateDir(), PROXY_CONFIG_FILE), 'utf-8');
+ } catch {
+ return '';
+ }
+}
+
+function writeConsentMirrorLine(field: string, value: boolean): void {
+ const dir = funnelStateDir();
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
+ const target = path.join(dir, PROXY_CONFIG_FILE);
+ const raw = readProxyConfigRaw();
+ const line = `${field} = ${value}`;
+ const pattern = new RegExp(`^${field}\\s*=.*$`, 'm');
+ let next: string;
+ if (pattern.test(raw)) {
+ next = raw.replace(pattern, line);
+ } else {
+ next = raw.length > 0 ? `${raw.trimEnd()}\n${line}\n` : `${line}\n`;
+ }
+ const tmp = `${target}.tmp`;
+ fs.writeFileSync(tmp, next, { encoding: 'utf-8', mode: 0o600 });
+ fs.renameSync(tmp, target);
+}
+
+function writeSponsoredConsentMirror(granted: boolean): void {
+ writeConsentMirrorLine('sponsored_consent_granted', granted);
+}
+
+function writePowerSaverConsentMirror(granted: boolean): void {
+ writeConsentMirrorLine('power_saver_consent_granted', granted);
+}
+
+function writeTrainingShareConsentMirror(granted: boolean): void {
+ writeConsentMirrorLine('training_share_consent_granted', granted);
+}
+
+const SPONSOR_DISCLOSURE = [
+ 'Enabling sponsored downtime mode.',
+ '',
+ "While your Claude usage limit resets, requests can be routed through",
+ "Cognitum's own model capacity, sponsored at no cost to you. This is a",
+ 'separate data plane from your own cloud-routing config — Cognitum sees',
+ 'these prompts (server-side, same handling as any api.cognitum.one',
+ 'request), never your own Claude account.',
+ '',
+ 'Sponsored capacity is rate-limited and best-effort — Cognitum may',
+ 'throttle or decline requests under load. Disable anytime:',
+ ' ruflo proxy sponsor-disable',
+].join('\n');
+
+const sponsorEnableSub: Command = {
+ name: 'sponsor-enable',
+ description: "Opt into Cognitum-sponsored downtime capacity (ADR-313)",
+ options: [
+ { name: 'yes', description: 'Skip the confirmation prompt', type: 'boolean', default: false },
+ ],
+ action: async (ctx): Promise<CommandResult> => {
+ if (hasConsent('sponsored-downtime')) {
+ output.writeln('Sponsored downtime mode is already enabled.');
+ return { success: true, data: { alreadyEnabled: true } };
+ }
+ output.writeln(SPONSOR_DISCLOSURE);
+ output.writeln('');
+ if (!ctx.flags.yes) {
+ output.writeln('Re-run with --yes to confirm: ruflo proxy sponsor-enable --yes');
+ return { success: true, data: { confirmed: false } };
+ }
+ recordConsent('sponsored-downtime', true, 'proxy-sponsor-enable');
+ writeSponsoredConsentMirror(true);
+ recordFunnelEvent('sponsor_mode_enabled', 'statusline', getInstalledCliVersion());
+ output.printSuccess('Sponsored downtime mode enabled.');
+ output.writeln('The proxy will use it automatically while ruflo settings notices');
+ output.writeln('rate-limited is flagged. Disable anytime: ruflo proxy sponsor-disable');
+ return { success: true, data: { confirmed: true } };
+ },
+};
+
+const sponsorDisableSub: Command = {
+ name: 'sponsor-disable',
+ description: 'Revoke sponsored-downtime consent and stop using sponsored capacity',
+ action: async (): Promise<CommandResult> => {
+ revokeConsent('sponsored-downtime', 'proxy-sponsor-disable');
+ writeSponsoredConsentMirror(false);
+ recordFunnelEvent('sponsor_mode_disabled', 'statusline', getInstalledCliVersion());
+ output.printSuccess('Sponsored downtime mode disabled.');
+ return { success: true };
+ },
+};
+
+const sponsorStatusSub: Command = {
+ name: 'sponsor-status',
+ description: 'Show sponsored-downtime consent + rate-limit flag state',
+ action: async (): Promise<CommandResult> => {
+ const consented = hasConsent('sponsored-downtime');
+ const rateLimited = readRateLimitStatus();
+ output.writeln(`Sponsored downtime consent: ${consented ? 'granted' : 'not granted'}`);
+ output.writeln(`Rate-limit flag: ${rateLimited.limited ? `set (since ${rateLimited.since})` : 'not set'}`);
+ if (rateLimited.limited && !consented) {
+ output.writeln('');
+ output.writeln('You are flagged as rate-limited but have not enabled sponsored');
+ output.writeln('capacity. Enable it with: ruflo proxy sponsor-enable --yes');
+ }
+ return { success: true, data: { consented, rateLimited } };
+ },
+};
+
+/** Convenience: clear the rate-limited flag once you're back to normal. */
+const sponsorClearSub: Command = {
+ name: 'sponsor-clear',
+ description: 'Clear the rate-limited flag (your Claude limit has reset)',
+ action: async (): Promise<CommandResult> => {
+ const changed = clearRateLimitStatus();
+ if (!changed) {
+ output.printError('Rate-limit flag was just toggled — try again in a few minutes (ADR-314 anti-abuse cooldown).');
+ return { success: false };
+ }
+ output.printSuccess('Rate-limit flag cleared.');
+ return { success: true };
+ },
+};
+
+const POWER_SAVER_DISCLOSURE = [
+ 'Enabling power saver mode.',
+ '',
+ "Everyday requests will route through Cognitum's own difficulty-based",
+ 'router (cognitum-auto) instead of your Claude subscription directly —',
+ 'simple messages stay cheap, genuinely hard reasoning still escalates to',
+ 'a comparable frontier model. This is billed to YOUR OWN Cognitum',
+ 'account (cloud-routing), not sponsored/free capacity — a separate',
+ 'decision from sponsored downtime mode.',
+ '',
+ 'Disable anytime: ruflo proxy power-saver-disable',
+].join('\n');
+
+const powerSaverEnableSub: Command = {
+ name: 'power-saver-enable',
+ description: 'Opt into power saver mode — route everyday requests through your own Cognitum account (ADR-314)',
+ options: [
+ { name: 'yes', description: 'Skip the confirmation prompt', type: 'boolean', default: false },
+ ],
+ action: async (ctx): Promise<CommandResult> => {
+ if (hasConsent('power-saver')) {
+ output.writeln('Power saver mode is already enabled.');
+ return { success: true, data: { alreadyEnabled: true } };
+ }
+ output.writeln(POWER_SAVER_DISCLOSURE);
+ output.writeln('');
+ if (!ctx.flags.yes) {
+ output.writeln('Re-run with --yes to confirm: ruflo proxy power-saver-enable --yes');
+ return { success: true, data: { confirmed: false } };
+ }
+ recordConsent('power-saver', true, 'proxy-power-saver-enable');
+ writePowerSaverConsentMirror(true);
+ recordFunnelEvent('power_saver_enabled', 'statusline', getInstalledCliVersion());
+ output.printSuccess('Power saver mode enabled.');
+ output.writeln('Flag it active with: ruflo settings notices quota-low');
+ output.writeln('Disable anytime: ruflo proxy power-saver-disable');
+ return { success: true, data: { confirmed: true } };
+ },
+};
+
+const powerSaverDisableSub: Command = {
+ name: 'power-saver-disable',
+ description: 'Revoke power-saver consent and stop routing through Cognitum for cost savings',
+ action: async (): Promise<CommandResult> => {
+ revokeConsent('power-saver', 'proxy-power-saver-disable');
+ writePowerSaverConsentMirror(false);
+ recordFunnelEvent('power_saver_disabled', 'statusline', getInstalledCliVersion());
+ output.printSuccess('Power saver mode disabled.');
+ return { success: true };
+ },
+};
+
+const powerSaverStatusSub: Command = {
+ name: 'power-saver-status',
+ description: 'Show power-saver consent + quota-low flag state',
+ action: async (): Promise<CommandResult> => {
+ const consented = hasConsent('power-saver');
+ const quotaLow = readQuotaLowStatus();
+ output.writeln(`Power saver consent: ${consented ? 'granted' : 'not granted'}`);
+ output.writeln(`Quota-low flag: ${quotaLow.low ? `set (since ${quotaLow.since})` : 'not set'}`);
+ if (quotaLow.low && !consented) {
+ output.writeln('');
+ output.writeln('You are flagged as running low but have not enabled power saver');
+ output.writeln('mode. Enable it with: ruflo proxy power-saver-enable --yes');
+ }
+ return { success: true, data: { consented, quotaLow } };
+ },
+};
+
+/** Convenience: clear the quota-low flag once you're back to normal. */
+const powerSaverClearSub: Command = {
+ name: 'power-saver-clear',
+ description: 'Clear the quota-low flag',
+ action: async (): Promise<CommandResult> => {
+ const changed = clearQuotaLowStatus();
+ if (!changed) {
+ output.printError('Quota-low flag was just toggled — try again in a few minutes (ADR-314 anti-abuse cooldown).');
+ return { success: false };
+ }
+ output.printSuccess('Quota-low flag cleared.');
+ return { success: true };
+ },
+};
+
+const TRAINING_SHARE_DISCLOSURE = [
+ 'Enabling training-data sharing.',
+ '',
+ 'When a request runs on the sponsored plane, the proxy will attach a',
+ 'consent header telling Cognitum it may retain that interaction —',
+ '(post safety-scan) — as input to its MicroLoRA training pipeline',
+ '(meta-llm ADR-251), gated through its existing SHADOW/promotion-rule',
+ 'safety net; adaptations are never auto-served. This is content, not',
+ 'just metadata, and is entirely separate from sponsored-downtime',
+ 'consent — using free capacity never implicitly means this is on.',
+ '',
+ 'Declining has zero effect on sponsored-capacity access.',
+ '',
+ 'Disable anytime: ruflo proxy training-share-disable',
+].join('\n');
+
+const trainingShareEnableSub: Command = {
+ name: 'training-share-enable',
+ description: 'Opt into sharing sponsored-plane interaction content for meta-llm training (ADR-315)',
+ options: [
+ { name: 'yes', description: 'Skip the confirmation prompt', type: 'boolean', default: false },
+ ],
+ action: async (ctx): Promise<CommandResult> => {
+ if (hasConsent('training-data-sharing')) {
+ output.writeln('Training-data sharing is already enabled.');
+ return { success: true, data: { alreadyEnabled: true } };
+ }
+ output.writeln(TRAINING_SHARE_DISCLOSURE);
+ output.writeln('');
+ if (!ctx.flags.yes) {
+ output.writeln('Re-run with --yes to confirm: ruflo proxy training-share-enable --yes');
+ return { success: true, data: { confirmed: false } };
+ }
+ recordConsent('training-data-sharing', true, 'proxy-training-share-enable');
+ writeTrainingShareConsentMirror(true);
+ recordFunnelEvent('training_share_enabled', 'statusline', getInstalledCliVersion());
+ output.printSuccess('Training-data sharing enabled.');
+ output.writeln('Only sponsored-plane requests carry the consent header. Disable anytime:');
+ output.writeln(' ruflo proxy training-share-disable');
+ return { success: true, data: { confirmed: true } };
+ },
+};
+
+const trainingShareDisableSub: Command = {
+ name: 'training-share-disable',
+ description: 'Revoke training-data-sharing consent — stop sending the training consent header',
+ action: async (): Promise<CommandResult> => {
+ revokeConsent('training-data-sharing', 'proxy-training-share-disable');
+ writeTrainingShareConsentMirror(false);
+ recordFunnelEvent('training_share_disabled', 'statusline', getInstalledCliVersion());
+ output.printSuccess('Training-data sharing disabled.');
+ return { success: true };
+ },
+};
+
+const trainingShareStatusSub: Command = {
+ name: 'training-share-status',
+ description: 'Show training-data-sharing consent state',
+ action: async (): Promise<CommandResult> => {
+ const consented = hasConsent('training-data-sharing');
+ output.writeln(`Training-data sharing consent: ${consented ? 'granted' : 'not granted'}`);
+ if (consented) {
+ output.writeln('Sponsored-plane requests carry X-Cognitum-Training-Consent: true.');
+ }
+ return { success: true, data: { consented } };
+ },
+};
+
+export const proxyCommand: Command = {
+ name: 'proxy',
+ description: 'Meta LLM Proxy — sponsored downtime + power saver + training-data sharing (ADR-304/307/313/314/315)',
+ subcommands: [
+ sponsorEnableSub, sponsorDisableSub, sponsorStatusSub, sponsorClearSub,
+ powerSaverEnableSub, powerSaverDisableSub, powerSaverStatusSub, powerSaverClearSub,
+ trainingShareEnableSub, trainingShareDisableSub, trainingShareStatusSub,
+ ],
+ examples: [
+ { command: 'ruflo proxy sponsor-status', description: 'Show current sponsored-mode state' },
+ { command: 'ruflo proxy sponsor-enable --yes', description: 'Opt into sponsored downtime capacity' },
+ { command: 'ruflo proxy power-saver-enable --yes', description: 'Opt into power saver mode' },
+ { command: 'ruflo proxy training-share-enable --yes', description: 'Opt into training-data sharing (ADR-315)' },
+ ],
+ action: sponsorStatusSub.action,
+};
+
+export default proxyCommand;
diff --git a/v3/@claude-flow/cli/src/commands/security.ts b/v3/@claude-flow/cli/src/commands/security.ts
index bd9c2c3730..f4c087af11 100644
--- a/v3/@claude-flow/cli/src/commands/security.ts
+++ b/v3/@claude-flow/cli/src/commands/security.ts
@@ -219,6 +219,35 @@ const scanCommand: Command = {
`Total Issues: ${findings.length}`,
].join('\n'), 'Scan Summary');
+ // Persist the scan result so downstream consumers (the statusline's
+ // getSecurityStatus in funnel/local-signals.ts, which reads
+ // `.claude/security-scans/*.json`) reflect real scan state. Best-effort:
+ // a failed write must never fail the scan itself.
+ try {
+ const scanDirOut = path.join(path.resolve(target), '.claude', 'security-scans');
+ fs.mkdirSync(scanDirOut, { recursive: true });
+ const record = {
+ timestamp: new Date().toISOString(),
+ target,
+ depth,
+ type: scanType,
+ summary: {
+ critical: criticalCount,
+ high: highCount,
+ medium: mediumCount,
+ low: lowCount,
+ total: findings.length,
+ },
+ findings,
+ };
+ // Deterministic name keyed on scan config so repeated runs overwrite
+ // rather than accumulate stale reports.
+ const outFile = path.join(scanDirOut, `scan-${scanType}-${depth}.json`);
+ fs.writeFileSync(outFile, JSON.stringify(record, null, 2));
+ } catch {
+ // Persistence is advisory only — ignore write failures.
+ }
+
// Auto-fix if requested
if (fix && criticalCount + highCount > 0) {
output.writeln();
diff --git a/v3/@claude-flow/cli/src/commands/settings.ts b/v3/@claude-flow/cli/src/commands/settings.ts
new file mode 100644
index 0000000000..8894de1b14
--- /dev/null
+++ b/v3/@claude-flow/cli/src/commands/settings.ts
@@ -0,0 +1,213 @@
+/**
+ * `ruflo settings` — user-facing preferences router (ADR-311 amendment).
+ *
+ * The name change from `ruflo funnel …` is deliberate copy discipline:
+ * "funnel" is internal analytics terminology; it should not appear in the
+ * command surface end users see. Every subcommand here forwards to the
+ * existing `ruflo funnel` primitives so behavior stays identical — this
+ * is a friendlier wrapper, not a re-implementation.
+ *
+ * Subcommands:
+ * ruflo settings Show effective settings + how to change them
+ * ruflo settings notices status Show whether the notices row is on
+ * ruflo settings notices off Turn off the notices row (persistent)
+ * ruflo settings notices on Re-enable the notices row
+ * ruflo settings notices id Show the pseudonymous notices id
+ */
+
+import type { Command, CommandResult } from '../types.js';
+import { output } from '../output.js';
+import {
+ deleteFunnelData,
+ funnelStateDir,
+ getDisclosure,
+ getFunnelId,
+ hasConsent,
+ readConsents,
+ recordDisclosureDeclined,
+ recordDisclosureReenabled,
+ resolveFunnelEnabled,
+} from '../funnel/index.js';
+import { readStateJson, writeStateJson } from '../funnel/state.js';
+import {
+ clearRateLimitStatus,
+ markRateLimited,
+ rateLimitNotice,
+ readRateLimitStatus,
+} from '../funnel/rate-limit-notifier.js';
+import {
+ clearQuotaLowStatus,
+ markQuotaLow,
+ quotaLowNotice,
+ readQuotaLowStatus,
+} from '../funnel/power-saver-notifier.js';
+
+function setUserConfigEnabled(enabled: boolean): void {
+ const cfg = readStateJson<Record<string, unknown>>('funnel.json') ?? {};
+ cfg.enabled = enabled;
+ writeStateJson('funnel.json', cfg);
+}
+
+const noticesStatusSub: Command = {
+ name: 'status',
+ description: 'Show whether notices are on and which source decided it',
+ action: async (): Promise<CommandResult> => {
+ const decision = resolveFunnelEnabled();
+ const disclosure = getDisclosure();
+ output.writeln(`Notices: ${decision.enabled ? 'enabled' : 'disabled'} (decided by: ${decision.decidedBy})`);
+ output.writeln(`Disclosure: ${disclosure.state}`);
+ output.writeln(`Telemetry: ${hasConsent('telemetry') ? 'consent granted' : 'no consent'}`);
+ return { success: true, data: { decision, disclosure: disclosure.state } };
+ },
+};
+
+const noticesOffSub: Command = {
+ name: 'off',
+ description: 'Turn off statusline notices (persistent, user-level)',
+ action: async (): Promise<CommandResult> => {
+ setUserConfigEnabled(false);
+ recordDisclosureDeclined();
+ deleteFunnelData();
+ output.printSuccess('Notices disabled. Local notice data deleted.');
+ return { success: true };
+ },
+};
+
+const noticesOnSub: Command = {
+ name: 'on',
+ description: 'Re-enable statusline notices',
+ action: async (): Promise<CommandResult> => {
+ setUserConfigEnabled(true);
+ recordDisclosureReenabled();
+ const decision = resolveFunnelEnabled();
+ if (decision.enabled) {
+ output.printSuccess('Notices enabled.');
+ } else {
+ output.printWarning(
+ `User preference recorded, but notices stay off (decided by: ${decision.decidedBy})`,
+ );
+ }
+ return { success: true, data: decision };
+ },
+};
+
+const noticesIdSub: Command = {
+ name: 'id',
+ description: 'Print the pseudonymous notices ID (telemetry consent required)',
+ action: async (): Promise<CommandResult> => {
+ const id = getFunnelId();
+ output.writeln(id ?? '(no id — telemetry consent not granted, or notices are off)');
+ return { success: true, data: { id } };
+ },
+};
+
+const rateLimitedSub: Command = {
+ name: 'rate-limited',
+ description: 'Manually flag that you have hit a Claude usage limit (ADR-312 Phase 0)',
+ options: [
+ { name: 'clear', description: 'Clear the flag', type: 'boolean', default: false },
+ ],
+ action: async (ctx): Promise<CommandResult> => {
+ if (ctx.flags.clear) {
+ const changed = clearRateLimitStatus();
+ if (!changed) {
+ output.printError('Rate-limit flag was just toggled — try again in a few minutes (ADR-314 anti-abuse cooldown).');
+ return { success: false };
+ }
+ output.printSuccess('Rate-limit flag cleared.');
+ return { success: true };
+ }
+ const changed = markRateLimited();
+ if (!changed) {
+ output.printError('Rate-limit flag was just toggled — try again in a few minutes (ADR-314 anti-abuse cooldown).');
+ return { success: false };
+ }
+ output.printSuccess('Rate-limit flag set.');
+ output.writeln('');
+ output.writeln('This is a manual, self-reported flag — ruflo cannot detect Claude\'s');
+ output.writeln('usage-limit state automatically today (see ADR-312). While flagged,');
+ output.writeln('the notices row may suggest sponsored Cognitum capacity as a bridge');
+ output.writeln('until your own limit resets: ruflo proxy sponsor-enable');
+ output.writeln('');
+ output.writeln('Clear it any time: ruflo settings notices rate-limited --clear');
+ const notice = rateLimitNotice();
+ return { success: true, data: { notice, status: readRateLimitStatus() } };
+ },
+};
+
+const quotaLowSub: Command = {
+ name: 'quota-low',
+ description: 'Manually flag that your Claude quota is running low (ADR-314 power saver)',
+ options: [
+ { name: 'clear', description: 'Clear the flag', type: 'boolean', default: false },
+ ],
+ action: async (ctx): Promise<CommandResult> => {
+ if (ctx.flags.clear) {
+ const changed = clearQuotaLowStatus();
+ if (!changed) {
+ output.printError('Quota-low flag was just toggled — try again in a few minutes (ADR-314 anti-abuse cooldown).');
+ return { success: false };
+ }
+ output.printSuccess('Quota-low flag cleared.');
+ return { success: true };
+ }
+ const changed = markQuotaLow();
+ if (!changed) {
+ output.printError('Quota-low flag was just toggled — try again in a few minutes (ADR-314 anti-abuse cooldown).');
+ return { success: false };
+ }
+ output.printSuccess('Quota-low flag set.');
+ output.writeln('');
+ output.writeln('This is a manual, self-reported flag — ruflo cannot read your actual');
+ output.writeln('quota percentage today (see ADR-312/314). While flagged, and once you');
+ output.writeln('enable power saver mode, everyday requests route through Cognitum\'s');
+ output.writeln('own difficulty-based router (billed to your own Cognitum account):');
+ output.writeln(' ruflo proxy power-saver-enable');
+ output.writeln('');
+ output.writeln('Clear it any time: ruflo settings notices quota-low --clear');
+ const notice = quotaLowNotice();
+ return { success: true, data: { notice, status: readQuotaLowStatus() } };
+ },
+};
+
+const noticesCommand: Command = {
+ name: 'notices',
+ description: 'Control the statusline notices row',
+ subcommands: [noticesStatusSub, noticesOffSub, noticesOnSub, noticesIdSub, rateLimitedSub, quotaLowSub],
+ action: noticesStatusSub.action,
+};
+
+const overviewAction: Command['action'] = async (): Promise<CommandResult> => {
+ const decision = resolveFunnelEnabled();
+ const disclosure = getDisclosure();
+ const consents = readConsents();
+ output.writeln('ruflo settings — user preferences');
+ output.writeln('');
+ output.writeln('Notices (statusline tips + product updates)');
+ output.writeln(' ruflo settings notices status Show current state');
+ output.writeln(' ruflo settings notices off Turn off all notices');
+ output.writeln(' ruflo settings notices on Re-enable');
+ output.writeln(' ruflo settings notices id Show pseudonymous notices id');
+ output.writeln('');
+ output.writeln(` current: ${decision.enabled ? 'enabled' : 'disabled'} (${decision.decidedBy})`);
+ output.writeln(` disclosure: ${disclosure.state}`);
+ const domains = Object.keys(consents);
+ if (domains.length) {
+ output.writeln(` consents: ${domains.join(', ')}`);
+ }
+ output.writeln(` state dir: ${funnelStateDir()}`);
+ return { success: true, data: { decision, disclosure: disclosure.state, consents } };
+};
+
+export const settingsCommand: Command = {
+ name: 'settings',
+ description: 'View and change user preferences (notices, consents)',
+ subcommands: [noticesCommand],
+ examples: [
+ { command: 'ruflo settings', description: 'Overview + current state' },
+ { command: 'ruflo settings notices off', description: 'Turn off statusline notices' },
+ { command: 'ruflo settings notices status', description: 'Show current notices state' },
+ ],
+ action: overviewAction,
+};
+
diff --git a/v3/@claude-flow/cli/src/commands/version.ts b/v3/@claude-flow/cli/src/commands/version.ts
new file mode 100644
index 0000000000..aff20ca788
--- /dev/null
+++ b/v3/@claude-flow/cli/src/commands/version.ts
@@ -0,0 +1,132 @@
+/**
+ * `ruflo version` — ANV (Agent-Native Versioning) Phase 1.
+ * https://gist.github.com/ruvnet/0d858ad440a4439b4a2281a40c39b1a0
+ *
+ * Plain `ruflo --version` / `-V` (index.ts's showVersion()) is UNCHANGED —
+ * it stays bare semver so scripts parsing that output never see a surprise
+ * suffix. This is a separate subcommand: `ruflo version` prints the same
+ * bare semver by default, and `--explain` additionally renders the ANV
+ * catalog/benchmark breakdown when a catalog-manifest.json ships with this
+ * install. No catalog-manifest.json (e.g. an old install, or a dev checkout
+ * that hasn't run the generator) degrades to bare semver — the suffix is
+ * advisory, never load-bearing for npm range resolution or CLI behavior.
+ */
+import type { Command, CommandContext, CommandResult } from '../types.js';
+import { output } from '../output.js';
+import { existsSync, readFileSync } from 'fs';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { createRequire } from 'module';
+import { getInstalledCliVersion } from '../init/helper-refresh.js';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+
+interface CatalogManifest {
+ schemaVersion: number;
+ generation: number;
+ generatedAt: string;
+ gitSha: string;
+ catalog: { agents: number; tools: number; skills: number };
+ benchmark: { tier: number; verifiedAt: string; signature?: string } | null;
+}
+
+/** Locate catalog-manifest.json next to the installed package root. */
+function findCatalogManifest(): CatalogManifest | null {
+ const candidates: string[] = [];
+ try {
+ const esmRequire = createRequire(import.meta.url);
+ const pkgRoot = dirname(esmRequire.resolve('@claude-flow/cli/package.json'));
+ candidates.push(join(pkgRoot, 'catalog-manifest.json'));
+ } catch { /* not resolvable via package resolution */ }
+ // Dev checkout fallback: this compiled file lives at dist/src/commands/version.js
+ // (three levels under the package root) when built, or is run via tsx one level
+ // shallower from src/commands/version.ts — try both.
+ candidates.push(join(__dirname, '..', '..', 'catalog-manifest.json'));
+ candidates.push(join(__dirname, '..', '..', '..', 'catalog-manifest.json'));
+ for (const c of candidates) {
+ if (!existsSync(c)) continue;
+ try {
+ const parsed = JSON.parse(readFileSync(c, 'utf-8'));
+ if (parsed && typeof parsed.generation === 'number' && parsed.catalog) return parsed as CatalogManifest;
+ } catch { /* corrupt manifest — treat as absent */ }
+ }
+ return null;
+}
+
+/**
+ * The advisory suffix itself (semver build metadata, `+` prefix — legal per
+ * semver.org §10, ignored by npm for range resolution/precedence).
+ * +ad.<release-sequence>.g<gitSha>.cat<generation>[.hal<tier>]
+ * `.hal<tier>` is only appended when a real, signed benchmark submission
+ * exists for THIS catalog generation — never fabricated (ANV's own
+ * "verifiable, no unverifiable claims" principle).
+ */
+export function buildAdvisorySuffix(manifest: CatalogManifest, releaseSequence = 1): string {
+ const parts = [`ad.${releaseSequence}`, `g${manifest.gitSha}`, `cat${manifest.generation}`];
+ if (manifest.benchmark) parts.push(`hal${manifest.benchmark.tier}`);
+ return `+${parts.join('.')}`;
+}
+
+export const versionCommand: Command = {
+ name: 'version',
+ description: 'Show installed version, with --explain for the ANV catalog breakdown',
+ options: [
+ {
+ name: 'explain',
+ description: 'Show the full ANV breakdown (catalog generation, counts, benchmark status)',
+ type: 'boolean',
+ default: false,
+ },
+ {
+ name: 'require-catalog-gte',
+ description: 'Exit non-zero unless the installed catalog generation is >= N (capability gating for scripts)',
+ type: 'number',
+ },
+ ],
+ examples: [
+ { command: 'ruflo version', description: 'Print the installed semver' },
+ { command: 'ruflo version --explain', description: 'Print the full ANV catalog/benchmark breakdown' },
+ { command: 'ruflo version --require-catalog-gte 40', description: 'Gate a script on a minimum catalog generation' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const version = getInstalledCliVersion();
+ const manifest = findCatalogManifest();
+ const requireGte = ctx.flags.requireCatalogGte as number | undefined;
+
+ if (typeof requireGte === 'number') {
+ const generation = manifest?.generation ?? 0;
+ if (generation >= requireGte) {
+ output.writeln(`OK (installed catalog is ${generation})`);
+ return { success: true };
+ }
+ output.printError(`Installed catalog generation ${generation} is below required ${requireGte}`);
+ return { success: false };
+ }
+
+ if (!ctx.flags.explain) {
+ output.writeln(`${version}`);
+ return { success: true };
+ }
+
+ if (!manifest) {
+ output.writeln(`Installed: ruflo@${version}`);
+ output.writeln(output.dim(' (no catalog-manifest.json — plain semver, pre-ANV or dev checkout)'));
+ return { success: true };
+ }
+
+ const suffix = buildAdvisorySuffix(manifest);
+ output.writeln(`Installed: ${output.bold(`ruflo@${version}${suffix}`)}`);
+ output.writeln();
+ output.writeln(`Era: AD (Agent Descent) — 1st generation`);
+ output.writeln(
+ `Catalog: generation ${manifest.generation} ` +
+ `(agents: ${manifest.catalog.agents} types, tools: ${manifest.catalog.tools} MCP, skills: ${manifest.catalog.skills})`,
+ );
+ if (manifest.benchmark) {
+ output.writeln(`Benchmark: GAIA tier ${manifest.benchmark.tier} (verified ${manifest.benchmark.verifiedAt.slice(0, 10)}, signed)`);
+ } else {
+ output.writeln(output.dim('Benchmark: not yet submitted (no verified GAIA/HAL score for this catalog generation)'));
+ }
+ return { success: true };
+ },
+};
diff --git a/v3/@claude-flow/cli/src/funnel/advisor-tip.ts b/v3/@claude-flow/cli/src/funnel/advisor-tip.ts
new file mode 100644
index 0000000000..b2d7ba3834
--- /dev/null
+++ b/v3/@claude-flow/cli/src/funnel/advisor-tip.ts
@@ -0,0 +1,111 @@
+/**
+ * Advisor co-pilot tip — ADR-316. A periodic, consent-gated, budget-capped
+ * suggestion generated by ruflo's existing Fable Advisor Harness
+ * (services/fable-harness.ts, ADR-172), surfaced in the local insight
+ * ticker (insights.ts) alongside the CVE/uncommitted/power-saver signals.
+ *
+ * This is the ONE insight source that spends real money and makes a real
+ * network call — every other source in insights.ts is synchronous, local,
+ * $0 by construction. Three hard gates keep that safe:
+ * 1. consent: 'advisor-tips' domain (types.ts/consent.ts), never bundled
+ * with anything else, off by default.
+ * 2. cooldown: at most once per ADVISOR_REFRESH_TTL_MS regardless of how
+ * many sessions run in that window — a file-based TTL checked BEFORE
+ * spawning, not a per-call budget hope.
+ * 3. budget: FableHarness's own --max-budget-usd hard cap, passed through
+ * to the underlying `claude -p` call.
+ *
+ * The snapshot sent to the model is built ONLY from the same structural
+ * signals insights.ts already uses (funnel/local-signals.ts) — never raw
+ * prompts, commands, or file contents. Matches ADR-309's "no raw content,
+ * ever" bar even though ADR-309 is about telemetry and this is a different,
+ * separately-consented data flow (an opt-in advisor query, not analytics).
+ *
+ * Cheapness/latency discipline for the CALLER (never this module itself):
+ * refreshAdvisorTipIfStale performs a real network-bound `claude -p` spawn
+ * when stale — callers MUST run it from a properly-awaited, DETACHED
+ * background process (mirroring the funnel-cache fix's
+ * spawnDetachedFunnelRefresh pattern), never inline in a statusline render.
+ */
+
+import { hasConsent } from './consent.js';
+import { readStateJson, writeStateJson } from './state.js';
+import { FableHarness, type CoPilotSnapshot } from '../services/fable-harness.js';
+
+const ADVISOR_CACHE_FILE = 'advisor-tip.json';
+/** At most one real spend per real day, regardless of session count. */
+export const ADVISOR_REFRESH_TTL_MS = 24 * 60 * 60 * 1000;
+/** Conservative default — one adviseCoPilotTip call is a single, unbatched
+ * item, so the ~$0.34 clean-cwd anchor (not the $0.02 batched anchor)
+ * applies. Override via RUFLO_ADVISOR_MAX_BUDGET_USD for advanced users. */
+export const ADVISOR_DEFAULT_BUDGET_USD = 0.4;
+
+interface AdvisorTipCache {
+ _ts: number;
+ headline?: string;
+ detail?: string;
+}
+
+export interface CachedAdvisorTip {
+ headline: string;
+ detail: string;
+}
+
+/** Synchronous, $0, no network — safe to call from the insight ticker's hot path. */
+export function readAdvisorTip(now: Date = new Date()): CachedAdvisorTip | null {
+ const cache = readStateJson<AdvisorTipCache>(ADVISOR_CACHE_FILE);
+ // `!cache._ts` would wrongly treat a legitimate epoch-zero timestamp as
+ // absent (0 is falsy) — check the type explicitly instead.
+ if (!cache || !cache.headline || typeof cache._ts !== 'number') return null;
+ if (now.getTime() - cache._ts >= ADVISOR_REFRESH_TTL_MS) return null;
+ return { headline: cache.headline, detail: cache.detail ?? '' };
+}
+
+function isCacheStale(now: Date): boolean {
+ const cache = readStateJson<AdvisorTipCache>(ADVISOR_CACHE_FILE);
+ if (!cache || typeof cache._ts !== 'number') return true;
+ return now.getTime() - cache._ts >= ADVISOR_REFRESH_TTL_MS;
+}
+
+function resolveBudgetUsd(): number {
+ const raw = process.env.RUFLO_ADVISOR_MAX_BUDGET_USD;
+ const n = raw !== undefined ? Number(raw) : NaN;
+ return Number.isFinite(n) && n > 0 ? n : ADVISOR_DEFAULT_BUDGET_USD;
+}
+
+export interface AdvisorRefreshResult {
+ refreshed: boolean;
+ reason?: 'not-consented' | 'fresh' | 'no-tip' | 'error';
+}
+
+/**
+ * Refresh the cached advisor tip if consent is granted AND the cache is
+ * stale. Spends real money via FableHarness exactly once per call site,
+ * gated by the TTL check above — callers get to decide cadence (e.g.
+ * "call this on every session-restore"; the TTL makes repeated calls cheap
+ * no-ops within the same window).
+ */
+export async function refreshAdvisorTipIfStale(
+ snapshot: CoPilotSnapshot,
+ opts: { now?: Date; harness?: FableHarness } = {},
+): Promise<AdvisorRefreshResult> {
+ const now = opts.now ?? new Date();
+ if (!hasConsent('advisor-tips')) return { refreshed: false, reason: 'not-consented' };
+ if (!isCacheStale(now)) return { refreshed: false, reason: 'fresh' };
+
+ const harness = opts.harness ?? new FableHarness({ maxBudgetUsd: resolveBudgetUsd() });
+ try {
+ const tip = await harness.adviseCoPilotTip(snapshot);
+ if (!tip) {
+ // The model looked and found nothing worth surfacing — still stamp
+ // _ts so we don't re-spend inside the same TTL window re-asking the
+ // same question and getting the same "nothing to say" answer.
+ writeStateJson(ADVISOR_CACHE_FILE, { _ts: now.getTime() });
+ return { refreshed: true, reason: 'no-tip' };
+ }
+ writeStateJson(ADVISOR_CACHE_FILE, { _ts: now.getTime(), headline: tip.headline, detail: tip.detail });
+ return { refreshed: true };
+ } catch {
+ return { refreshed: false, reason: 'error' };
+ }
+}
diff --git a/v3/@claude-flow/cli/src/funnel/attribution.ts b/v3/@claude-flow/cli/src/funnel/attribution.ts
new file mode 100644
index 0000000000..8c584ba612
--- /dev/null
+++ b/v3/@claude-flow/cli/src/funnel/attribution.ts
@@ -0,0 +1,110 @@
+/**
+ * Attribution URL builder — appends UTM parameters and the pseudonymous funnel
+ * ID to outbound funnel links so cognitum.one traffic analytics can attribute
+ * a landing back to the surface, message, and campaign that produced it
+ * (ADR-305 measurement plane).
+ *
+ * Failure discipline (ADR-301 no-runtime-network invariant, Phase 1):
+ * - This function is PURE — it never makes a network call. Attribution is
+ * shipped as query params on a link the user's own browser resolves; the
+ * CLI has zero runtime dependency on cognitum.one being reachable.
+ * If the whole API is down, the OSC 8 label still renders correctly, the
+ * click still leaves the terminal, and only the landing page fails (which
+ * is a browser-visible problem, not a statusline problem).
+ * - If the base URL is malformed, we return it verbatim rather than
+ * synthesizing a broken analytics endpoint. The OSC 8 renderer then
+ * re-validates the host against its allowlist and, on failure, drops
+ * the escape entirely and shows the plain label — never a raw URL.
+ *
+ * Privacy discipline (ADR-309):
+ * - `fid` (the pseudonymous funnel ID) is appended only when telemetry
+ * consent is present. Without consent, getFunnelId() returns null and
+ * the URL carries only the UTM fields — same landing page, no join key.
+ * - The base URL must already be an allowlisted https target; the OSC 8
+ * renderer re-validates the host at render time regardless.
+ */
+import { getFunnelId } from './events.js';
+
+export interface AttributionInput {
+ /** UTM `medium` — the surface (e.g. 'statusline', 'enrollment', 'exhaustion'). */
+ medium: string;
+ /** UTM `campaign` — the message kind ('disclosure' | 'promotional' | 'educational'). */
+ campaign: string;
+ /** UTM `content` — the specific message id ('promo-meta-llm-routing' etc.). */
+ content: string;
+ /** Static UTM `source` — always 'ruflo' but overridable for tests. */
+ source?: string;
+ /** Injectable for deterministic tests. Defaults to the live clock. */
+ now?: Date;
+}
+
+/**
+ * Server-side click-redirect endpoint. When set, promotional URLs route
+ * through here so the server can record a `promo_open` event + coarse
+ * geo (from CF-IPCountry / X-Appengine-Country) before 302ing to the
+ * real cognitum.one / agentics.org / etc. target.
+ */
+const CLICK_ENDPOINT_BASE =
+ process.env.RUFLO_FUNNEL_CLICK_ENDPOINT ?? 'https://funnel.ruv.io/v1/click';
+
+/**
+ * Return `url` with UTM parameters appended, and — when telemetry consent is
+ * granted — a `fid` query parameter carrying the pseudonymous funnel ID.
+ * Preserves any query parameters the base URL already carried.
+ */
+export function attributionUrl(url: string, input: AttributionInput): string {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return url;
+ }
+ // Defense in depth: reject non-https schemes at the builder stage. The OSC 8
+ // renderer allowlist would drop them at render time too, but decorating a
+ // `javascript:` or `data:` URL with a valid-looking `fid` would still be a
+ // record we don't want to emit. Fail closed by returning the input verbatim.
+ if (parsed.protocol !== 'https:') return url;
+
+ const params = parsed.searchParams;
+ params.set('utm_source', input.source ?? 'ruflo');
+ params.set('utm_medium', input.medium);
+ params.set('utm_campaign', input.campaign);
+ params.set('utm_content', input.content);
+
+ const fid = getFunnelId(input.now ?? new Date());
+ if (fid) params.set('fid', fid);
+
+ return parsed.toString();
+}
+
+/**
+ * Wrap the target URL in a server-side click-redirect so the analytics
+ * function fires a `promo_open` event + records coarse geo before 302ing to
+ * the real destination.
+ *
+ * Only applied to promotional messages (they have a real URL destination).
+ * Disclosure/educational rows call attributionUrl directly.
+ *
+ * The click endpoint URL structure is:
+ * https://funnel.ruv.io/v1/click/{messageId}?to=<utm-decorated-target>
+ *
+ * The server validates `to` against its own host allowlist, records the
+ * event, and 302s. If the click endpoint is unreachable at OSC 8 time,
+ * the browser falls back to the terminal's normal error page — but since
+ * this is a rare failure path and impressions are already recorded, the
+ * loss is bounded.
+ */
+export function clickTrackedUrl(messageId: string, targetUrl: string, input: AttributionInput): string {
+ const attributed = attributionUrl(targetUrl, input);
+ // If attribution rejected the URL (non-https, malformed), pass through
+ // verbatim — never smuggle a bad URL into the click endpoint.
+ if (attributed === targetUrl) {
+ try { const p = new URL(targetUrl); if (p.protocol !== 'https:') return targetUrl; }
+ catch { return targetUrl; }
+ }
+ // Sanitize the message id — allowlist [a-z0-9-] so a malformed id can't
+ // shape-shift the click endpoint path.
+ if (!/^[a-z0-9][a-z0-9-]{0,63}$/i.test(messageId)) return attributed;
+ const params = new URLSearchParams({ to: attributed });
+ return `${CLICK_ENDPOINT_BASE}/${encodeURIComponent(messageId)}?${params.toString()}`;
+}
diff --git a/v3/@claude-flow/cli/src/funnel/consent.ts b/v3/@claude-flow/cli/src/funnel/consent.ts
new file mode 100644
index 0000000000..209e07f340
--- /dev/null
+++ b/v3/@claude-flow/cli/src/funnel/consent.ts
@@ -0,0 +1,70 @@
+/**
+ * Consent domains and versioned receipts — ADR-302.
+ *
+ * Four+ distinct decisions, never bundled: account, proxy-install,
+ * telemetry, cloud-routing, hosted-memory. A receipt is written on both
+ * grant AND decline (a decline is a decision, not an absence). A stale
+ * policyVersion means the consent must be re-asked before the capability
+ * activates — never silently carried forward.
+ */
+
+import type { ConsentDomain, ConsentFile, ConsentReceipt } from './types.js';
+import { CONSENT_POLICY_VERSION } from './types.js';
+import { readStateJson, writeStateJson } from './state.js';
+
+const CONSENT_FILE = 'consent.json';
+
+export const CONSENT_DOMAINS: ConsentDomain[] = [
+ 'account',
+ 'proxy-install',
+ 'telemetry',
+ 'cloud-routing',
+ 'hosted-memory',
+ 'sponsored-downtime',
+ 'power-saver',
+ 'training-data-sharing',
+ 'advisor-tips',
+];
+
+export function readConsents(): ConsentFile {
+ return readStateJson<ConsentFile>(CONSENT_FILE) ?? {};
+}
+
+export function getConsent(domain: ConsentDomain): ConsentReceipt {
+ const file = readConsents();
+ return (
+ file[domain] ?? { granted: false, policyVersion: CONSENT_POLICY_VERSION, at: null, surface: null }
+ );
+}
+
+/**
+ * Effective consent: granted AND at the current policy version. A receipt
+ * from an older policy version is treated as not-consented (re-ask, never
+ * carry forward).
+ */
+export function hasConsent(domain: ConsentDomain): boolean {
+ const r = getConsent(domain);
+ return r.granted === true && r.at !== null && r.policyVersion === CONSENT_POLICY_VERSION;
+}
+
+export function recordConsent(
+ domain: ConsentDomain,
+ granted: boolean,
+ surface: string,
+ now: Date = new Date(),
+): ConsentReceipt {
+ const file = readConsents();
+ const receipt: ConsentReceipt = {
+ granted,
+ policyVersion: CONSENT_POLICY_VERSION,
+ at: now.toISOString(),
+ surface,
+ };
+ file[domain] = receipt;
+ writeStateJson(CONSENT_FILE, file);
+ return receipt;
+}
+
+export function revokeConsent(domain: ConsentDomain, surface: string): ConsentReceipt {
+ return recordConsent(domain, false, surface);
+}
diff --git a/v3/@claude-flow/cli/src/funnel/credit-errors.ts b/v3/@claude-flow/cli/src/funnel/credit-errors.ts
new file mode 100644
index 0000000000..fd6c827577
--- /dev/null
+++ b/v3/@claude-flow/cli/src/funnel/credit-errors.ts
@@ -0,0 +1,109 @@
+/**
+ * Credit-error taxonomy and fail-closed classifier — ADR-303.
+ *
+ * Adapters map machine-readable provider codes into the canonical
+ * CreditErrorCode enum. Message text is NEVER parsed. Anything unmapped
+ * stays unclassified (confidence 0) and falls through to the ordinary
+ * error path. Only COGNITUM_CREDIT_EXHAUSTED — asserted by the Cognitum
+ * ledger, the single credit authority — may trigger the funnel surface.
+ */
+
+import { CreditErrorCode, type NormalizedCreditError } from './types.js';
+
+/**
+ * Provider-code → canonical-code table. Keys are exact machine-readable
+ * code strings from provider error payloads (mirrors the ADR-308 server
+ * taxonomy 1:1). Versioned by code review; unmapped codes land nowhere.
+ */
+const PROVIDER_CODE_TABLE: Record<string, { code: CreditErrorCode; retryable: boolean }> = {
+ // Cognitum ledger (the single credit authority — ADR-303)
+ cognitum_credit_exhausted: { code: CreditErrorCode.COGNITUM_CREDIT_EXHAUSTED, retryable: false },
+ // Upstream provider quota/billing — NOT a Cognitum upsell moment
+ insufficient_quota: { code: CreditErrorCode.PROVIDER_QUOTA_EXHAUSTED, retryable: false },
+ billing_hard_limit_reached: { code: CreditErrorCode.PROVIDER_QUOTA_EXHAUSTED, retryable: false },
+ quota_exceeded: { code: CreditErrorCode.PROVIDER_QUOTA_EXHAUSTED, retryable: false },
+ // Retryable rate limits
+ rate_limit_exceeded: { code: CreditErrorCode.PROVIDER_RATE_LIMITED, retryable: true },
+ rate_limit_error: { code: CreditErrorCode.PROVIDER_RATE_LIMITED, retryable: true },
+ overloaded_error: { code: CreditErrorCode.SERVICE_UNAVAILABLE, retryable: true },
+ // Auth
+ authentication_error: { code: CreditErrorCode.AUTHENTICATION_FAILED, retryable: false },
+ invalid_api_key: { code: CreditErrorCode.AUTHENTICATION_FAILED, retryable: false },
+ permission_error: { code: CreditErrorCode.AUTHENTICATION_FAILED, retryable: false },
+ // Outages
+ api_error: { code: CreditErrorCode.SERVICE_UNAVAILABLE, retryable: true },
+ service_unavailable: { code: CreditErrorCode.SERVICE_UNAVAILABLE, retryable: true },
+};
+
+export interface ProviderErrorLike {
+ /** Machine-readable provider error code (e.g. `error.type` / `error.code`). */
+ providerCode?: string;
+ /** HTTP status, when the transport exposes one. */
+ status?: number;
+}
+
+export function classifyCreditError(err: ProviderErrorLike): NormalizedCreditError {
+ const key = err.providerCode?.trim().toLowerCase();
+ if (key && Object.prototype.hasOwnProperty.call(PROVIDER_CODE_TABLE, key)) {
+ const mapped = PROVIDER_CODE_TABLE[key];
+ return { code: mapped.code, confidence: 1, retryable: mapped.retryable, cause: err };
+ }
+ // Status-only signals are structural (401/403 → auth; 5xx → outage), but a
+ // bare 429 is ambiguous between rate-limit and quota — leave it unmapped.
+ if (err.status === 401 || err.status === 403) {
+ return { code: CreditErrorCode.AUTHENTICATION_FAILED, confidence: 1, retryable: false, cause: err };
+ }
+ if (err.status !== undefined && err.status >= 500) {
+ return { code: CreditErrorCode.SERVICE_UNAVAILABLE, confidence: 1, retryable: true, cause: err };
+ }
+ return { code: null, confidence: 0, retryable: false, cause: err };
+}
+
+export interface CreditPromptSession {
+ creditPromptShown: boolean;
+}
+
+/**
+ * The ADR-303 gate, fail-closed and frequency-capped: fires only for a
+ * confident, non-retryable Cognitum-ledger exhaustion, at most once per
+ * session. Everything else falls through to the ordinary error path.
+ */
+export function shouldShowCreditRecovery(
+ error: NormalizedCreditError,
+ session: CreditPromptSession,
+): boolean {
+ return (
+ error.code === CreditErrorCode.COGNITUM_CREDIT_EXHAUSTED &&
+ error.confidence === 1 &&
+ !error.retryable &&
+ !session.creditPromptShown
+ );
+}
+
+/** Full contextual screen (interactive TTY, first occurrence). */
+export function renderCreditRecovery(authenticated: boolean): string {
+ const lines = [
+ 'Daily hosted credits exhausted.',
+ '',
+ 'Continue immediately by enabling',
+ 'your free local Meta LLM Proxy.',
+ '',
+ 'Benefits',
+ ' ✓ Unlimited local requests',
+ ' ✓ Automatic model routing',
+ ' ✓ Lower latency',
+ ' ✓ Privacy preserving',
+ ' ✓ Cloud fallback',
+ '',
+ ];
+ if (authenticated) {
+ lines.push('Start local proxy?', ' ruflo proxy enable');
+ } else {
+ lines.push('Sign in:', ' ruflo auth login');
+ }
+ return lines.join('\n');
+}
+
+/** Single-line hint (non-TTY, CI, or repeat occurrences in a session). */
+export const CREDIT_RECOVERY_HINT =
+ 'Hint: ruflo auth login enables the free local Meta LLM proxy';
diff --git a/v3/@claude-flow/cli/src/funnel/credit-notifier.ts b/v3/@claude-flow/cli/src/funnel/credit-notifier.ts
new file mode 100644
index 0000000000..66b5dcee64
--- /dev/null
+++ b/v3/@claude-flow/cli/src/funnel/credit-notifier.ts
@@ -0,0 +1,83 @@
+/**
+ * Credit-exhaustion notifier — writes a marker file so the ADR-303 recovery
+ * surface fires on the next appropriate command render, and keeps a short
+ * user-visible notification in `~/.ruflo/credit-status.json`.
+ *
+ * This is NOT the ADR-303 credit-error classifier — that lives in
+ * `credit-errors.ts` and reads provider error codes to decide when a
+ * credit surface fires *during* a command. This module is the OUT-OF-BAND
+ * signal path: the analytics transport detected a credit-exhausted
+ * response (HTTP 402 or ADR-303 machine-readable code), and we need to
+ * warn the user asynchronously.
+ *
+ * State is cheap and durable:
+ * ~/.ruflo/credit-status.json = { exhausted: bool, since: ISO, cleared: ISO|null }
+ *
+ * Cleared automatically when the user opens the enrollment / signup
+ * surface, or explicitly via `ruflo funnel credit-clear`.
+ */
+
+import { readStateJson, writeStateJson } from './state.js';
+
+export const CREDIT_STATUS_FILE = 'credit-status.json';
+
+export interface CreditStatus {
+ exhausted: boolean;
+ since: string | null;
+ cleared: string | null;
+}
+
+/** Read the current credit status. Never throws. */
+export function readCreditStatus(): CreditStatus {
+ const raw = readStateJson<CreditStatus>(CREDIT_STATUS_FILE);
+ return {
+ exhausted: raw?.exhausted ?? false,
+ since: raw?.since ?? null,
+ cleared: raw?.cleared ?? null,
+ };
+}
+
+/**
+ * Mark credit as exhausted — idempotent. Sets `since` on the first mark,
+ * leaves it alone on subsequent marks so the user sees a stable "since"
+ * timestamp until they clear it.
+ */
+export function markCreditExhausted(now: Date = new Date()): void {
+ const current = readCreditStatus();
+ if (current.exhausted && current.since) return; // already flagged
+ writeStateJson(CREDIT_STATUS_FILE, {
+ exhausted: true,
+ since: current.since ?? now.toISOString(),
+ cleared: null,
+ } satisfies CreditStatus);
+}
+
+/**
+ * Clear credit-exhaustion status. Called when the user completes signup or
+ * runs `ruflo funnel credit-clear`. `cleared` is stamped so the previous
+ * `since` remains inspectable for one recovery cycle.
+ */
+export function clearCreditStatus(now: Date = new Date()): void {
+ const current = readCreditStatus();
+ writeStateJson(CREDIT_STATUS_FILE, {
+ exhausted: false,
+ since: current.since,
+ cleared: now.toISOString(),
+ } satisfies CreditStatus);
+}
+
+/**
+ * User-facing single-line summary — plain text, no ANSI. Callers style it
+ * themselves. Returns null when credit isn't exhausted (no surface).
+ */
+export function creditExhaustedNotice(now: Date = new Date()): string | null {
+ const status = readCreditStatus();
+ if (!status.exhausted) return null;
+ const since = status.since ? Date.parse(status.since) : NaN;
+ if (Number.isNaN(since)) {
+ return 'Cognitum credits exhausted · run: ruflo funnel signup';
+ }
+ const ageHours = Math.max(0, Math.round((now.getTime() - since) / (60 * 60 * 1000)));
+ const when = ageHours < 1 ? 'just now' : ageHours < 24 ? `${ageHours}h ago` : `${Math.round(ageHours / 24)}d ago`;
+ return `Cognitum credits exhausted (${when}) · run: ruflo funnel signup`;
+}
diff --git a/v3/@claude-flow/cli/src/funnel/disclosure.ts b/v3/@claude-flow/cli/src/funnel/disclosure.ts
new file mode 100644
index 0000000000..027f78d4a8
--- /dev/null
+++ b/v3/@claude-flow/cli/src/funnel/disclosure.ts
@@ -0,0 +1,104 @@
+/**
+ * Existing-install disclosure gate — ADR-301, amended by ADR-311 to source
+ * the disclosure MESSAGE itself from the remote feed rather than hardcoding
+ * it in the CLI. Everything about WHETHER/WHEN to show a disclosure stays
+ * local (state machine below); everything about WHAT it says comes from
+ * the same remote pool as tips/promos, validated through the identical
+ * ADR-301 content pipeline (isValidMessage in messages.ts).
+ *
+ * Invariants (release-blocking, tested):
+ * - No promotional content before disclosure.
+ * - The manage instruction appears in the disclosure text itself.
+ * - Shown once per user (user-level receipt), not once per project.
+ * - Declining disables all funnel surfaces (enforced in precedence.ts).
+ * - Fail-closed: if the remote feed has never successfully populated a
+ * disclosure-class message, there is nothing to show — no local
+ * fallback text exists (ADR-311 "zero local promo content").
+ *
+ * The disclosure text stays on the promo row for a grace window after its
+ * first render so a single flash can't count as "the user was told"; only
+ * after the window do promotional messages become eligible.
+ */
+
+import type { DisclosureRecord, FunnelDisclosureState, FunnelMessage } from './types.js';
+import { readStateJson, writeStateJson } from './state.js';
+import { getRemoteMessages } from './message-transport.js';
+
+const DISCLOSURE_FILE = 'funnel-disclosure.json';
+
+/** How long the disclosure text keeps the row before promo becomes eligible. */
+export const DISCLOSURE_GRACE_MS = 24 * 60 * 60 * 1000; // 24h
+
+// One disclosure variant per 5-minute wall-clock slot. Longer than the
+// 20-second rotation cadence so a user watching the statusline sees the
+// same variant long enough to read it, but short enough that a fresh
+// session gets a different one than the previous one did.
+export const DISCLOSURE_ROTATION_SLOT_MS = 5 * 60 * 1000;
+
+/** Remote-cached messages tagged class==='disclosure' — the only source. */
+function getDisclosureMessagePool(): FunnelMessage[] {
+ return getRemoteMessages().filter((m) => m.class === 'disclosure');
+}
+
+/**
+ * Deterministic slot-based selection over the remote disclosure pool — no
+ * RNG so the choice is reproducible for a given wall-clock instant. Returns
+ * null when the pool is empty (cold start before first fetch, or the remote
+ * feed is unreachable) — the caller must treat null as "show nothing".
+ */
+export function selectDisclosureMessage(now: Date = new Date()): FunnelMessage | null {
+ const pool = getDisclosureMessagePool();
+ if (pool.length === 0) return null;
+ const slot = Math.floor(now.getTime() / DISCLOSURE_ROTATION_SLOT_MS);
+ return pool[slot % pool.length];
+}
+
+export function getDisclosure(): DisclosureRecord {
+ const rec = readStateJson<DisclosureRecord>(DISCLOSURE_FILE);
+ if (rec && isValidState(rec.state)) return rec;
+ return { state: 'never_seen', firstShownAt: null };
+}
+
+function isValidState(s: unknown): s is FunnelDisclosureState {
+ return s === 'never_seen' || s === 'disclosed_enabled' || s === 'disclosed_disabled';
+}
+
+/** Record that the disclosure text was rendered (idempotent). */
+export function recordDisclosureShown(now: Date = new Date()): DisclosureRecord {
+ const current = getDisclosure();
+ if (current.state !== 'never_seen') return current;
+ const rec: DisclosureRecord = { state: 'disclosed_enabled', firstShownAt: now.toISOString() };
+ writeStateJson(DISCLOSURE_FILE, rec);
+ return rec;
+}
+
+/** User explicitly declined (e.g. `ruflo funnel disable`). */
+export function recordDisclosureDeclined(now: Date = new Date()): DisclosureRecord {
+ const current = getDisclosure();
+ const rec: DisclosureRecord = {
+ state: 'disclosed_disabled',
+ firstShownAt: current.firstShownAt ?? now.toISOString(),
+ };
+ writeStateJson(DISCLOSURE_FILE, rec);
+ return rec;
+}
+
+/** Re-enable after a prior decline (explicit user action only). */
+export function recordDisclosureReenabled(now: Date = new Date()): DisclosureRecord {
+ const rec: DisclosureRecord = { state: 'disclosed_enabled', firstShownAt: now.toISOString() };
+ writeStateJson(DISCLOSURE_FILE, rec);
+ return rec;
+}
+
+/**
+ * Whether promotional/educational messages may render. True only after the
+ * disclosure was shown AND its grace window has elapsed. While the window is
+ * open the row must carry the disclosure text itself.
+ */
+export function promoEligible(now: Date = new Date()): boolean {
+ const rec = getDisclosure();
+ if (rec.state !== 'disclosed_enabled' || !rec.firstShownAt) return false;
+ const first = Date.parse(rec.firstShownAt);
+ if (Number.isNaN(first)) return false;
+ return now.getTime() - first >= DISCLOSURE_GRACE_MS;
+}
diff --git a/v3/@claude-flow/cli/src/funnel/enrollment.ts b/v3/@claude-flow/cli/src/funnel/enrollment.ts
new file mode 100644
index 0000000000..9b712764ea
--- /dev/null
+++ b/v3/@claude-flow/cli/src/funnel/enrollment.ts
@@ -0,0 +1,76 @@
+/**
+ * Post-initialization capability enrollment — ADR-302.
+ *
+ * One-time, non-blocking, skippable. Gates, all of which must pass:
+ * - interactive TTY (never in CI / piped / automation)
+ * - not skipped via --no-signup
+ * - funnel enabled under the ADR-305 precedence chain
+ * - never shown before (user-level record, not per-project)
+ *
+ * Accepting authorizes exactly ONE thing: a pointer to `ruflo auth login`.
+ * It does not install the proxy, does not enable telemetry, and does not
+ * enable cloud routing (separate consent domains — ADR-302). The enrollment
+ * outcome never affects init's exit code.
+ */
+
+import { isCI, isInteractive } from './environment.js';
+import { resolveFunnelEnabled } from './precedence.js';
+import { recordConsent } from './consent.js';
+import { readStateJson, writeStateJson } from './state.js';
+
+const ENROLLMENT_FILE = 'enrollment.json';
+
+interface EnrollmentRecord {
+ shownAt: string;
+ outcome: 'accepted' | 'skipped';
+}
+
+export function getEnrollmentRecord(): EnrollmentRecord | null {
+ return readStateJson<EnrollmentRecord>(ENROLLMENT_FILE);
+}
+
+export const ENROLLMENT_SCREEN = [
+ '────────────────────────────',
+ 'Unlock additional capabilities?',
+ '',
+ ' ✓ Local Meta LLM Proxy',
+ ' ✓ Multi-model routing',
+ ' ✓ Hosted memory',
+ ' ✓ Enterprise rate limits',
+ ' ✓ Premium agents',
+ ' ✓ Cloud synchronization',
+ '',
+ 'Free account: https://cognitum.one',
+].join('\n');
+
+export const ENROLLMENT_SKIP_TEXT = 'You can enable later:\n ruflo auth login';
+
+export interface EnrollmentGateContext {
+ noSignup: boolean;
+ cwd?: string;
+ env?: NodeJS.ProcessEnv;
+}
+
+/** All ADR-302 gates. Pure check — does not write state. */
+export function shouldOfferEnrollment(ctx: EnrollmentGateContext): boolean {
+ const env = ctx.env ?? process.env;
+ if (ctx.noSignup) return false;
+ if (isCI(env)) return false;
+ if (!isInteractive()) return false;
+ if (!resolveFunnelEnabled(ctx.cwd ?? process.cwd(), env).enabled) return false;
+ if (getEnrollmentRecord() !== null) return false; // one-time only
+ return true;
+}
+
+/**
+ * Record the user's decision. Both accept and skip are terminal — the
+ * prompt never reappears (ADR-302). Accepting records the `account`
+ * consent receipt; skipping records the decline.
+ */
+export function recordEnrollmentOutcome(accepted: boolean, now: Date = new Date()): void {
+ writeStateJson(ENROLLMENT_FILE, {
+ shownAt: now.toISOString(),
+ outcome: accepted ? 'accepted' : 'skipped',
+ } satisfies EnrollmentRecord);
+ recordConsent('account', accepted, 'post-init', now);
+}
diff --git a/v3/@claude-flow/cli/src/funnel/environment.ts b/v3/@claude-flow/cli/src/funnel/environment.ts
new file mode 100644
index 0000000000..ae5990d0d0
--- /dev/null
+++ b/v3/@claude-flow/cli/src/funnel/environment.ts
@@ -0,0 +1,44 @@
+/**
+ * Environment gates for funnel surfaces (ADR-301/302).
+ *
+ * CI and non-interactive environments never see funnel content; reduced
+ * motion / screen readers get static text only (which is all the funnel
+ * renders anyway — there is deliberately no animation path in this module).
+ */
+
+const CI_ENV_VARS = [
+ 'CI',
+ 'GITHUB_ACTIONS',
+ 'GITLAB_CI',
+ 'CIRCLECI',
+ 'TRAVIS',
+ 'BUILDKITE',
+ 'JENKINS_URL',
+ 'TEAMCITY_VERSION',
+ 'TF_BUILD', // Azure Pipelines
+];
+
+export function isCI(env: NodeJS.ProcessEnv = process.env): boolean {
+ return CI_ENV_VARS.some((v) => {
+ const val = env[v];
+ return val !== undefined && val !== '' && val !== '0' && val.toLowerCase?.() !== 'false';
+ });
+}
+
+export function isInteractive(): boolean {
+ return Boolean(process.stdout.isTTY && process.stdin.isTTY);
+}
+
+/**
+ * Statusline invocations are spawned by an interactive host (Claude Code)
+ * with piped stdio, so isTTY is false there even though the session is
+ * interactive. Surfaces pass their own interactivity signal; this helper is
+ * the strict check used by directly-invoked prompts (init enrollment).
+ */
+export function reducedMotion(env: NodeJS.ProcessEnv = process.env): boolean {
+ return Boolean(
+ env.NO_COLOR !== undefined ||
+ env.RUFLO_REDUCED_MOTION === '1' ||
+ env.TERM === 'dumb'
+ );
+}
diff --git a/v3/@claude-flow/cli/src/funnel/event-transport.ts b/v3/@claude-flow/cli/src/funnel/event-transport.ts
new file mode 100644
index 0000000000..f459027722
--- /dev/null
+++ b/v3/@claude-flow/cli/src/funnel/event-transport.ts
@@ -0,0 +1,228 @@
+/**
+ * Event transport — batches the local funnel event queue and posts it to the
+ * Cognitum analytics Cloud Function (ADR-308 endpoint contract).
+ *
+ * Design discipline (ADR-308 client failure policy — all normative):
+ * 1. Telemetry never blocks the CLI. Every network call is best-effort,
+ * capped by a short timeout, and swallows every error path.
+ * 2. Events are LOCAL FIRST. The queue in `events.ts` accumulates
+ * regardless of API reachability. This transport is the flush layer.
+ * 3. Idempotency: every batch carries a UUIDv4 idempotency key so a retry
+ * never double-counts (ADR-308 idempotent-batches invariant).
+ * 4. Exponential backoff on transient failures. Successful flushes stamp
+ * a "last flush" timestamp so we don't hammer the API each render.
+ * 5. Consent-gated. Zero network activity when telemetry consent is off.
+ * 6. Bounded. Never send more than MAX_BATCH events at once, so a large
+ * backlog doesn't blow the endpoint request-size limit.
+ * 7. Credit-exhaustion detection. If the endpoint replies 402 (Payment
+ * Required) or the body carries the ADR-303
+ * `COGNITUM_CREDIT_EXHAUSTED` code, we surface via `credit-notifier.ts`
+ * — the same recovery UX ADR-303 already ships.
+ */
+
+import * as fs from 'fs';
+import * as https from 'https';
+import { URL as NodeUrl } from 'url';
+import { randomUUID } from 'crypto';
+import { hasConsent } from './consent.js';
+import { readStateJson, statePath, writeStateJson } from './state.js';
+import { markCreditExhausted } from './credit-notifier.js';
+
+const EVENTS_FILE = 'funnel-events.jsonl';
+const FLUSH_STATE_FILE = 'funnel-events-flush.json';
+
+/**
+ * Default endpoint — the ruflo-funnel-analytics endpoint on the ruv.io
+ * domain, mapped via Cloud Run domain mapping to the cognitum-analytics
+ * Cloud Function on cognitum-20260110. Overridable by env for staging or
+ * self-hosted deploys. The domain choice is deliberate: an rUv-authored
+ * OSS project's telemetry endpoint belongs on rUv's own domain, not on
+ * cognitum.one — that keeps the CLI attribution honest.
+ */
+export const DEFAULT_ENDPOINT =
+ process.env.RUFLO_FUNNEL_EVENTS_ENDPOINT ?? 'https://funnel.ruv.io/v1/events';
+
+/** Cap per POST — server enforces its own limits too; this is a safety net. */
+export const MAX_BATCH = 100;
+
+/** Min interval between flushes (ms). Rate limits the client from within. */
+export const MIN_FLUSH_INTERVAL_MS = 60_000; // 1 min
+
+/** POST timeout — telemetry must not stall the CLI. */
+export const FLUSH_TIMEOUT_MS = 4_000;
+
+interface FlushState {
+ lastFlushAt: string | null;
+ consecutiveFailures: number;
+ lastError?: string;
+}
+
+interface EventBatch {
+ batchId: string;
+ events: unknown[];
+ release: string;
+ emittedAt: string;
+}
+
+/** Read the current flush bookkeeping state (never throws). */
+function readFlushState(): FlushState {
+ const raw = readStateJson<FlushState>(FLUSH_STATE_FILE);
+ return {
+ lastFlushAt: raw?.lastFlushAt ?? null,
+ consecutiveFailures: raw?.consecutiveFailures ?? 0,
+ lastError: raw?.lastError,
+ };
+}
+
+/** Persist flush bookkeeping. Never throws. */
+function writeFlushState(state: FlushState): void {
+ writeStateJson(FLUSH_STATE_FILE, state);
+}
+
+/** Read the local event queue as JSON lines. Returns [] when absent. */
+function readQueue(): unknown[] {
+ try {
+ const raw = fs.readFileSync(statePath(EVENTS_FILE), 'utf-8');
+ return raw
+ .split('\n')
+ .filter(Boolean)
+ .map((line) => {
+ try { return JSON.parse(line); } catch { return null; }
+ })
+ .filter((x): x is Record<string, unknown> => x !== null);
+ } catch {
+ return [];
+ }
+}
+
+/** Overwrite the local queue with the survivors (events we didn't flush). */
+function writeQueue(events: unknown[]): void {
+ try {
+ const body = events.length === 0 ? '' : events.map((e) => JSON.stringify(e)).join('\n') + '\n';
+ fs.writeFileSync(statePath(EVENTS_FILE), body, { encoding: 'utf-8', mode: 0o600 });
+ } catch {
+ /* telemetry must never block */
+ }
+}
+
+/** Exponential backoff — cap at 30 minutes. */
+function backoffElapsed(state: FlushState, now: Date): boolean {
+ if (!state.lastFlushAt) return true;
+ const last = Date.parse(state.lastFlushAt);
+ if (Number.isNaN(last)) return true;
+ const base = MIN_FLUSH_INTERVAL_MS;
+ const factor = Math.min(2 ** state.consecutiveFailures, 30); // cap at 30x → ~30 min
+ const nextAllowed = last + base * factor;
+ return now.getTime() >= nextAllowed;
+}
+
+/**
+ * POST a batch to the endpoint. Resolves to { ok, status } — never rejects.
+ * Kept internal so callers can't hand it a URL that dodges the allowlist.
+ */
+function postBatch(endpoint: string, batch: EventBatch): Promise<{ ok: boolean; status: number; body: string }> {
+ return new Promise((resolve) => {
+ let target: NodeUrl;
+ try { target = new NodeUrl(endpoint); } catch {
+ resolve({ ok: false, status: 0, body: 'bad-endpoint' });
+ return;
+ }
+ if (target.protocol !== 'https:') {
+ resolve({ ok: false, status: 0, body: 'non-https-endpoint' });
+ return;
+ }
+ const body = JSON.stringify(batch);
+ const req = https.request(
+ {
+ hostname: target.hostname,
+ port: target.port || 443,
+ path: target.pathname + target.search,
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Content-Length': Buffer.byteLength(body),
+ 'Idempotency-Key': batch.batchId,
+ 'User-Agent': `ruflo-funnel/${batch.release}`,
+ },
+ },
+ (res) => {
+ let chunks = '';
+ res.setEncoding('utf-8');
+ res.on('data', (chunk) => { chunks += chunk; });
+ res.on('end', () => {
+ const status = res.statusCode ?? 0;
+ resolve({ ok: status >= 200 && status < 300, status, body: chunks });
+ });
+ },
+ );
+ req.setTimeout(FLUSH_TIMEOUT_MS, () => {
+ req.destroy();
+ resolve({ ok: false, status: 0, body: 'timeout' });
+ });
+ req.on('error', (err) => resolve({ ok: false, status: 0, body: String(err) }));
+ req.write(body);
+ req.end();
+ });
+}
+
+/**
+ * Best-effort flush of the local event queue to the endpoint. Returns a
+ * summary the CLI can log at --verbose; the caller should never fail on it.
+ */
+export async function flushEvents(opts?: {
+ endpoint?: string;
+ release?: string;
+ force?: boolean;
+ now?: Date;
+}): Promise<{ flushed: number; skipped: string | null; status?: number }> {
+ const now = opts?.now ?? new Date();
+ const endpoint = opts?.endpoint ?? DEFAULT_ENDPOINT;
+
+ if (!hasConsent('telemetry')) return { flushed: 0, skipped: 'no-consent' };
+
+ const state = readFlushState();
+ if (!opts?.force && !backoffElapsed(state, now)) {
+ return { flushed: 0, skipped: 'backoff' };
+ }
+
+ const queue = readQueue();
+ if (queue.length === 0) {
+ // Nothing to send — record the check anyway so we don't retry every render.
+ writeFlushState({ ...state, lastFlushAt: now.toISOString() });
+ return { flushed: 0, skipped: 'empty-queue' };
+ }
+
+ const batchEvents = queue.slice(0, MAX_BATCH);
+ const batch: EventBatch = {
+ batchId: randomUUID(),
+ events: batchEvents,
+ release: opts?.release ?? 'unknown',
+ emittedAt: now.toISOString(),
+ };
+
+ const res = await postBatch(endpoint, batch);
+
+ // Credit-exhaustion detection (ADR-303 route in).
+ // 402 Payment Required → out of Cognitum credits.
+ // Body carrying the exact ADR-303 machine-readable code → same.
+ if (res.status === 402 || (typeof res.body === 'string' && res.body.includes('COGNITUM_CREDIT_EXHAUSTED'))) {
+ markCreditExhausted(now);
+ }
+
+ if (res.ok) {
+ // Drop the sent events; keep survivors.
+ writeQueue(queue.slice(batchEvents.length));
+ writeFlushState({
+ lastFlushAt: now.toISOString(),
+ consecutiveFailures: 0,
+ });
+ return { flushed: batchEvents.length, skipped: null, status: res.status };
+ }
+
+ writeFlushState({
+ lastFlushAt: now.toISOString(),
+ consecutiveFailures: state.consecutiveFailures + 1,
+ lastError: `HTTP ${res.status}`,
+ });
+ return { flushed: 0, skipped: `transport-failed`, status: res.status };
+}
diff --git a/v3/@claude-flow/cli/src/funnel/events.ts b/v3/@claude-flow/cli/src/funnel/events.ts
new file mode 100644
index 0000000000..b700caca8d
--- /dev/null
+++ b/v3/@claude-flow/cli/src/funnel/events.ts
@@ -0,0 +1,161 @@
+/**
+ * Funnel events — ADR-305 attribution / ADR-309 constrained schema.
+ *
+ * LOCAL-ONLY by design: this module performs no network I/O. Events are
+ * appended to a bounded local queue only when the telemetry consent domain
+ * is granted (ADR-302). Server-side ingestion (POST /v1/events, ADR-308)
+ * is a separate opt-in transport that does not exist in this build — until
+ * it does, the queue is simply a bounded local record the user can inspect
+ * and delete.
+ *
+ * Constraints enforced here, permanently (ADR-309): closed event set, daily
+ * timestamp buckets (never full timestamps), no raw prompts/commands/paths/
+ * repo names — the schema has no field that could carry them.
+ */
+
+import * as fs from 'fs';
+import { randomUUID } from 'crypto';
+import type { FunnelEvent, FunnelEventName, FunnelSurface } from './types.js';
+import { hasConsent } from './consent.js';
+import { deleteStateFile, funnelStateDir, readStateJson, statePath, writeStateJson } from './state.js';
+
+const EVENTS_FILE = 'funnel-events.jsonl';
+const FUNNEL_ID_FILE = 'funnel-id.json';
+
+/** Bounded queue: ≤ 1000 events / ≤ 256 KiB — telemetry never grows unbounded. */
+const MAX_QUEUE_BYTES = 256 * 1024;
+const MAX_QUEUE_EVENTS = 1000;
+
+const EVENT_NAMES: readonly FunnelEventName[] = [
+ 'disclosure_shown',
+ 'funnel_disabled',
+ 'signup_opened',
+ 'account_created',
+ 'proxy_activated',
+ 'promo_impression',
+ 'promo_open',
+ 'sponsor_mode_enabled',
+ 'sponsor_mode_disabled',
+ 'sponsor_capacity_exhausted',
+ 'power_saver_enabled',
+ 'power_saver_disabled',
+ 'toggle_cooldown_blocked',
+ 'training_share_enabled',
+ 'training_share_disabled',
+ 'advisor_tip_enabled',
+ 'advisor_tip_disabled',
+];
+const SURFACES: readonly FunnelSurface[] = ['statusline', 'init', 'credit_exhaustion'];
+
+interface FunnelIdRecord {
+ id: string;
+ createdAt: string;
+}
+
+/** Rotate the pseudonymous ID every 90 days (ADR-305). */
+const FUNNEL_ID_TTL_MS = 90 * 24 * 60 * 60 * 1000;
+
+/**
+ * Lazily created pseudonymous funnel ID — random UUID, derived from nothing
+ * (no hardware, account, email, or path). Exists only when attribution
+ * consent (telemetry domain) is granted; deleted on opt-out.
+ */
+export function getFunnelId(now: Date = new Date()): string | null {
+ if (!hasConsent('telemetry')) return null;
+ const existing = readStateJson<FunnelIdRecord>(FUNNEL_ID_FILE);
+ if (existing?.id) {
+ const created = Date.parse(existing.createdAt);
+ if (!Number.isNaN(created) && now.getTime() - created < FUNNEL_ID_TTL_MS) return existing.id;
+ }
+ const record: FunnelIdRecord = { id: randomUUID(), createdAt: now.toISOString() };
+ writeStateJson(FUNNEL_ID_FILE, record);
+ return record.id;
+}
+
+/** Opt-out: stop emission, delete the ID and the local queue (ADR-305). */
+export function deleteFunnelData(): void {
+ deleteStateFile(FUNNEL_ID_FILE);
+ deleteStateFile(EVENTS_FILE);
+}
+
+/**
+ * Most recent local record of `event`, as a daily bucket (`YYYY-MM-DD`) —
+ * events never carry a full timestamp (ADR-309). Returns null when nothing
+ * is recorded, which is also what you get with telemetry consent off (the
+ * queue is never written at all in that case) — this can't distinguish
+ * "never happened" from "not being recorded," by design.
+ */
+export function lastRecordedEvent(event: FunnelEventName): string | null {
+ try {
+ const raw = fs.readFileSync(statePath(EVENTS_FILE), 'utf-8');
+ const lines = raw.split('\n').filter(Boolean);
+ for (let i = lines.length - 1; i >= 0; i--) {
+ const parsed = JSON.parse(lines[i]) as FunnelEvent;
+ if (parsed.event === event) return parsed.timestampBucket;
+ }
+ return null;
+ } catch {
+ return null;
+ }
+}
+
+function dailyBucket(now: Date): string {
+ return now.toISOString().slice(0, 10);
+}
+
+/**
+ * Record a funnel event to the local queue. No-op (returns false) when
+ * telemetry consent is absent — consent-off means zero funnel records.
+ * `messageId` is only carried for promo_impression / promo_open events; on
+ * every other event it is dropped so the schema stays clean.
+ */
+export function recordFunnelEvent(
+ event: FunnelEventName,
+ surface: FunnelSurface,
+ release: string,
+ optsOrNow: Date | { now?: Date; messageId?: string } = new Date(),
+): boolean {
+ if (!EVENT_NAMES.includes(event) || !SURFACES.includes(surface)) return false;
+ if (!hasConsent('telemetry')) return false;
+ const now = optsOrNow instanceof Date ? optsOrNow : (optsOrNow.now ?? new Date());
+ const messageId = optsOrNow instanceof Date ? undefined : optsOrNow.messageId;
+ const payload: FunnelEvent = {
+ schemaVersion: 1,
+ event,
+ surface,
+ release,
+ timestampBucket: dailyBucket(now),
+ };
+ const id = getFunnelId(now);
+ if (id) payload.pseudonymousId = id;
+ // messageId is only carried on promo events; validated + length-capped so
+ // the schema stays predictable.
+ if (messageId && (event === 'promo_impression' || event === 'promo_open')) {
+ if (typeof messageId === 'string' && messageId.length > 0 && messageId.length <= 64) {
+ payload.messageId = messageId;
+ }
+ }
+ try {
+ fs.mkdirSync(funnelStateDir(), { recursive: true, mode: 0o700 });
+ const file = statePath(EVENTS_FILE);
+ let existing = '';
+ try {
+ existing = fs.readFileSync(file, 'utf-8');
+ } catch {
+ // first event
+ }
+ const lines = existing ? existing.split('\n').filter(Boolean) : [];
+ lines.push(JSON.stringify(payload));
+ let out = lines.slice(-MAX_QUEUE_EVENTS).join('\n') + '\n';
+ while (Buffer.byteLength(out, 'utf-8') > MAX_QUEUE_BYTES) {
+ const trimmed = out.split('\n').filter(Boolean);
+ trimmed.shift();
+ out = trimmed.join('\n') + '\n';
+ }
+ fs.writeFileSync(file, out, { encoding: 'utf-8', mode: 0o600 });
+ return true;
+ } catch {
+ // Telemetry must never block or break the CLI (ADR-308 failure policy).
+ return false;
+ }
+}
diff --git a/v3/@claude-flow/cli/src/funnel/index.ts b/v3/@claude-flow/cli/src/funnel/index.ts
new file mode 100644
index 0000000000..a87bbea5fb
--- /dev/null
+++ b/v3/@claude-flow/cli/src/funnel/index.ts
@@ -0,0 +1,75 @@
+/**
+ * Funnel module — ruflo → Cognitum lifecycle system (ADR-301..310).
+ * Local-only: nothing in this module performs network I/O.
+ */
+
+export * from './types.js';
+export { funnelStateDir } from './state.js';
+export { isCI, isInteractive, reducedMotion } from './environment.js';
+export { resolveFunnelEnabled } from './precedence.js';
+export {
+ CONSENT_DOMAINS,
+ getConsent,
+ hasConsent,
+ readConsents,
+ recordConsent,
+ revokeConsent,
+} from './consent.js';
+export {
+ DISCLOSURE_GRACE_MS,
+ DISCLOSURE_ROTATION_SLOT_MS,
+ getDisclosure,
+ promoEligible,
+ recordDisclosureDeclined,
+ recordDisclosureReenabled,
+ recordDisclosureShown,
+ selectDisclosureMessage,
+} from './disclosure.js';
+export {
+ MAX_MESSAGE_COLUMNS,
+ MESSAGES,
+ containsForbiddenSequences,
+ displayWidth,
+ eligibleMessages,
+ eligibleMessagesFromPools,
+ isAllowedUrl,
+ isValidMessage,
+} from './messages.js';
+export {
+ DEFAULT_MESSAGES_ENDPOINT,
+ getRemoteMessages,
+ refreshRemoteMessages,
+} from './message-transport.js';
+export {
+ PROMO_REPEAT_CAP_MS,
+ PROMO_SLOT_MODULO,
+ ROTATION_SLOT_MS,
+ selectMessage,
+} from './rotation.js';
+export {
+ CREDIT_RECOVERY_HINT,
+ classifyCreditError,
+ renderCreditRecovery,
+ shouldShowCreditRecovery,
+ type CreditPromptSession,
+ type ProviderErrorLike,
+} from './credit-errors.js';
+export { deleteFunnelData, getFunnelId, lastRecordedEvent, recordFunnelEvent } from './events.js';
+export { getFunnelPromo, type PromoContext } from './promo.js';
+export {
+ RATE_LIMIT_TTL_MS,
+ clearRateLimitStatus,
+ markRateLimited,
+ rateLimitNotice,
+ readRateLimitStatus,
+ type RateLimitStatus,
+} from './rate-limit-notifier.js';
+export {
+ QUOTA_LOW_TTL_MS,
+ clearQuotaLowStatus,
+ markQuotaLow,
+ quotaLowNotice,
+ readQuotaLowStatus,
+ type QuotaLowStatus,
+} from './power-saver-notifier.js';
+export { TOGGLE_COOLDOWN_MS, cooldownActive, cooldownRemainingMin } from './toggle-cooldown.js';
diff --git a/v3/@claude-flow/cli/src/funnel/insights.ts b/v3/@claude-flow/cli/src/funnel/insights.ts
new file mode 100644
index 0000000000..3b7045d048
--- /dev/null
+++ b/v3/@claude-flow/cli/src/funnel/insights.ts
@@ -0,0 +1,154 @@
+/**
+ * Local insight ticker — environment/task-aware suggestions sharing the
+ * promo row's screen real estate, but a deliberately SEPARATE data path
+ * from it.
+ *
+ * Why separate: the promo row is "zero local content, fully remote-served,
+ * fail-closed" (an explicit earlier design call — nothing about WHAT shows
+ * ships in the package). Insights are the opposite by nature — CVE counts,
+ * uncommitted changes, sponsored-mode state — none of that is knowable
+ * server-side. Conflating the two would mean either routing local logic
+ * through the remote-content validation pipeline (messages.ts's
+ * isValidMessage(), built for untrusted REMOTE content) or quietly giving
+ * the promo row a second, unrelated job. So: same rendered slot, same
+ * PromoRow shape, but a totally separate module, never touching
+ * message-transport.ts or the remote message cache.
+ *
+ * Cheapness discipline (learned the hard way — see the funnel-cache fix):
+ * every insight source here MUST be either (a) synchronous local file/state
+ * reads, already-computed data the caller passes in, or (b) a read of a
+ * cache some OTHER, separately-scheduled process populates. NEVER a network
+ * call from here — that would reintroduce the exact bug where a statusline
+ * render silently ate a multi-second fetch it could never actually finish.
+ */
+
+import { hasConsent } from './consent.js';
+import { readQuotaLowStatus } from './power-saver-notifier.js';
+import { readStateJson } from './state.js';
+import { readAdvisorTip } from './advisor-tip.js';
+
+export interface LocalInsight {
+ id: string;
+ text: string;
+ /** Higher = shown first when multiple insights are candidates this slot. */
+ priority: number;
+}
+
+export interface LocalInsightContext {
+ security?: { status: string; cvesFixed: number; totalCves: number };
+ swarm?: { activeAgents: number; maxAgents: number; coordinationActive: boolean };
+ /** Count of uncommitted-changed files (git status --short line count). */
+ gitUncommittedCount?: number;
+ now?: Date;
+}
+
+const GIT_UNCOMMITTED_THRESHOLD = 20;
+
+/**
+ * ADR-315 hook point — NOT yet populated by anything. The real flywheel
+ * self-optimization signal (e.g. "your sponsored traffic contributed to a
+ * new MicroLoRA candidate") depends on ADR-315's client-side consent wiring
+ * (the training-data-sharing domain + X-Cognitum-Training-Consent header),
+ * which doesn't exist yet — building the actual fetch-and-cache pipeline
+ * ahead of that consent groundwork would mean either faking data or wiring
+ * a network call with no real signal behind it. This reads a local cache
+ * file so the ticker is ready the moment that pipeline exists: whatever
+ * populates ~/.ruflo/flywheel-status.json (a future detached, session-start
+ * refresh — same pattern as the funnel message cache fix) is immediately
+ * picked up here with zero ticker-side changes needed.
+ */
+interface FlywheelStatusCache {
+ _ts: number;
+ headline?: string;
+}
+const FLYWHEEL_STATUS_TTL_MS = 24 * 60 * 60 * 1000;
+
+function flywheelInsight(now: Date): LocalInsight | null {
+ const cache = readStateJson<FlywheelStatusCache>('flywheel-status.json');
+ // `!cache._ts` would wrongly treat a legitimate epoch-zero timestamp as
+ // absent (0 is falsy) — check the type explicitly instead (ADR-316 found
+ // this exact defect pattern live via a test using new Date(0)).
+ if (!cache || !cache.headline || typeof cache._ts !== 'number') return null;
+ if (now.getTime() - cache._ts >= FLYWHEEL_STATUS_TTL_MS) return null;
+ return { id: 'insight-flywheel-status', text: `🧬 ${cache.headline}`, priority: 40 };
+}
+
+function securityInsight(ctx: LocalInsightContext): LocalInsight | null {
+ const s = ctx.security;
+ if (!s) return null;
+ const pending = s.totalCves - s.cvesFixed;
+ if (pending > 0) {
+ return {
+ id: 'insight-cves-pending',
+ text: `⚠ ${pending} CVE${pending === 1 ? '' : 's'} pending — Run ruflo security scan --depth full`,
+ priority: 90,
+ };
+ }
+ if (s.status === 'PENDING') {
+ return { id: 'insight-scan-pending', text: '🛡 Security scan pending — Run ruflo security scan --depth full', priority: 70 };
+ }
+ return null;
+}
+
+function gitInsight(ctx: LocalInsightContext): LocalInsight | null {
+ const n = ctx.gitUncommittedCount;
+ if (n === undefined || n <= GIT_UNCOMMITTED_THRESHOLD) return null;
+ return {
+ id: 'insight-uncommitted',
+ text: `📝 ${n} uncommitted changes — commit or stash before continuing`,
+ priority: 50,
+ };
+}
+
+/**
+ * Power-saver mode state — genuinely local (consent + a self-reported flag
+ * file, same pattern the rest of this module uses). Sponsored/rate-limited
+ * state is deliberately NOT duplicated here — promo.ts's own
+ * getSponsoredDowntimeOverride() already preempts rotation entirely for
+ * that case (ADR-313), with higher precedence than this slot-based ticker.
+ * Two insight sources for the same fact would mean picking which one wins;
+ * simpler to just not have two.
+ */
+function proxyModeInsight(now: Date): LocalInsight | null {
+ if (hasConsent('power-saver') && readQuotaLowStatus(now).low) {
+ return { id: 'insight-power-saver-active', text: '🔋 Power saver mode active — routing via cognitum-auto', priority: 55 };
+ }
+ return null;
+}
+
+/**
+ * ADR-316 — a co-pilot tip from ruflo's Fable Advisor Harness
+ * (services/fable-harness.ts, ADR-172). Consent-gated (never surfaces a
+ * stale cached tip after the user disables it, even though the cache file
+ * itself isn't deleted on disable — this check is what actually enforces
+ * "off means off"). Purely a cache read here — no network call, no spend;
+ * the real `claude -p` call happens in advisor-tip.ts's
+ * refreshAdvisorTipIfStale(), invoked from a detached background process,
+ * never from this hot path.
+ */
+function advisorTipInsight(now: Date): LocalInsight | null {
+ if (!hasConsent('advisor-tips')) return null;
+ const tip = readAdvisorTip(now);
+ if (!tip) return null;
+ return { id: 'insight-advisor-tip', text: `🧭 ${tip.headline}`, priority: 45 };
+}
+
+/** All candidate insights for this render, unsorted. */
+export function computeLocalInsights(ctx: LocalInsightContext): LocalInsight[] {
+ const now = ctx.now ?? new Date();
+ const candidates = [
+ securityInsight(ctx),
+ gitInsight(ctx),
+ proxyModeInsight(now),
+ advisorTipInsight(now),
+ flywheelInsight(now),
+ ];
+ return candidates.filter((i): i is LocalInsight => i !== null);
+}
+
+/** Highest-priority insight this render, or null if nothing is actionable. */
+export function selectLocalInsight(ctx: LocalInsightContext): LocalInsight | null {
+ const candidates = computeLocalInsights(ctx);
+ if (candidates.length === 0) return null;
+ return candidates.reduce((best, c) => (c.priority > best.priority ? c : best));
+}
diff --git a/v3/@claude-flow/cli/src/funnel/local-signals.ts b/v3/@claude-flow/cli/src/funnel/local-signals.ts
new file mode 100644
index 0000000000..10abc56157
--- /dev/null
+++ b/v3/@claude-flow/cli/src/funnel/local-signals.ts
@@ -0,0 +1,83 @@
+/**
+ * Local, synchronous, $0 structural signals shared by the statusline
+ * (commands/hooks.ts's statuslineCommand) and the advisor-tip refresh
+ * (funnel/advisor-tip.ts, ADR-316) — a single source of truth so the two
+ * call sites can never silently drift on what "security status" or "swarm
+ * status" means. Every function here is cheap, bounded, and never throws —
+ * matching the statusline's own "never allowed to break the render"
+ * discipline.
+ */
+import * as fs from 'fs';
+import * as path from 'path';
+import { execSync } from 'child_process';
+
+export interface SecurityStatus {
+ status: 'CLEAN' | 'IN_PROGRESS' | 'PENDING';
+ cvesFixed: number;
+ totalCves: number;
+}
+
+export function getSecurityStatus(cwd: string = process.cwd()): SecurityStatus {
+ const scanResultsPath = path.join(cwd, '.claude', 'security-scans');
+ let cvesFixed = 0;
+ const totalCves = 3;
+
+ if (fs.existsSync(scanResultsPath)) {
+ try {
+ const scans = fs.readdirSync(scanResultsPath).filter((f: string) => f.endsWith('.json'));
+ cvesFixed = Math.min(totalCves, scans.length);
+ } catch {
+ // Ignore
+ }
+ }
+
+ const auditPath = path.join(cwd, '.swarm', 'security');
+ if (fs.existsSync(auditPath)) {
+ try {
+ const audits = fs.readdirSync(auditPath).filter((f: string) => f.includes('audit'));
+ cvesFixed = Math.min(totalCves, Math.max(cvesFixed, audits.length));
+ } catch {
+ // Ignore
+ }
+ }
+
+ const status = cvesFixed >= totalCves ? 'CLEAN' : cvesFixed > 0 ? 'IN_PROGRESS' : 'PENDING';
+ return { status, cvesFixed, totalCves };
+}
+
+export interface SwarmStatus {
+ activeAgents: number;
+ maxAgents: number;
+ coordinationActive: boolean;
+}
+
+export function getSwarmStatus(): SwarmStatus {
+ let activeAgents = 0;
+ let coordinationActive = false;
+ const maxAgents = 15;
+ const isWindows = process.platform === 'win32';
+
+ try {
+ const psCmd = isWindows
+ ? 'tasklist /FI "IMAGENAME eq node.exe" /NH 2>NUL | find /c /v "" 2>NUL || echo 0'
+ : 'ps aux 2>/dev/null | grep -c agentic-flow || echo "0"';
+ const ps = execSync(psCmd, { encoding: 'utf-8', timeout: 3000 });
+ activeAgents = Math.max(0, parseInt(ps.trim()) - 1);
+ coordinationActive = activeAgents > 0;
+ } catch {
+ // ps/tasklist unavailable or timed out — report zero
+ }
+
+ return { activeAgents, maxAgents, coordinationActive };
+}
+
+/** Count of uncommitted-changed files (git status --short line count). */
+export function getGitUncommittedCount(): number | undefined {
+ try {
+ const out = execSync('git status --porcelain 2>/dev/null', { encoding: 'utf-8', timeout: 3000 });
+ const lines = out.split('\n').filter((l) => l.trim().length > 0);
+ return lines.length;
+ } catch {
+ return undefined;
+ }
+}
diff --git a/v3/@claude-flow/cli/src/funnel/message-transport.ts b/v3/@claude-flow/cli/src/funnel/message-transport.ts
new file mode 100644
index 0000000000..296d9f37cd
--- /dev/null
+++ b/v3/@claude-flow/cli/src/funnel/message-transport.ts
@@ -0,0 +1,166 @@
+/**
+ * Remote message transport — best-effort fetch of the ADR-311 message
+ * feed, cached locally, validated through the ADR-301 content pipeline
+ * BEFORE any message is displayed.
+ *
+ * Design discipline:
+ * 1. **Never blocks the render.** The statusline reads only the local
+ * cache. This module refreshes the cache in the background; a fresh
+ * install shows the in-code fallback pool until the first refresh
+ * lands (usually seconds after CLI startup).
+ * 2. **Content pipeline stays authoritative.** Every message the server
+ * returns is validated by `isValidMessage()` from `messages.ts` —
+ * same schema, same host allowlist, same control-char strip, same
+ * 80-column cap. A tampered or accidentally-broken remote feed can
+ * pollute nothing.
+ * 3. **Fail silent.** Any network/parse/validation failure leaves the
+ * previously-cached (or in-code) pool intact.
+ * 4. **Bounded cache size.** ≤ 128 KiB and ≤ 200 messages — matches
+ * ADR-309's bounded-local-queue discipline.
+ * 5. **Kill switch.** `RUFLO_FUNNEL_MESSAGES=0` (or `RUFLO_FUNNEL=0`)
+ * disables the fetcher entirely.
+ * 6. **Signature-verification hook.** Reserved for a future ADR-311
+ * amendment; currently the transport-layer TLS + host allowlist is
+ * the trust boundary. All content is treated as untrusted regardless.
+ */
+
+import * as fs from 'fs';
+import * as https from 'https';
+import { URL as NodeUrl } from 'url';
+import type { FunnelMessage } from './types.js';
+import { isValidMessage } from './messages.js';
+import { readStateJson, writeStateJson } from './state.js';
+
+const CACHE_FILE = 'funnel-messages-cache.json';
+const CACHE_TTL_MS = 6 * 60 * 60 * 1000; // 6h — matches server Cache-Control
+const CACHE_MAX_BYTES = 128 * 1024;
+const CACHE_MAX_MESSAGES = 200;
+const FETCH_TIMEOUT_MS = 4_000;
+
+/** Endpoint the client hits — overridable for staging / self-hosted. */
+export const DEFAULT_MESSAGES_ENDPOINT =
+ process.env.RUFLO_FUNNEL_MESSAGES_ENDPOINT ?? 'https://funnel.ruv.io/v1/messages';
+
+interface CacheEnvelope {
+ _ts: number;
+ messages: FunnelMessage[];
+}
+
+function readCache(): { fresh: boolean; messages: FunnelMessage[] } {
+ const raw = readStateJson<CacheEnvelope>(CACHE_FILE);
+ if (!raw || !Array.isArray(raw.messages)) return { fresh: false, messages: [] };
+ const age = Date.now() - (raw._ts ?? 0);
+ return { fresh: age < CACHE_TTL_MS, messages: raw.messages };
+}
+
+function writeCache(messages: FunnelMessage[]): void {
+ // Bound the cache before persisting — messages come from an untrusted
+ // source, so we cap size regardless of server behavior.
+ let trimmed = messages.slice(0, CACHE_MAX_MESSAGES);
+ let body = JSON.stringify({ _ts: Date.now(), messages: trimmed } satisfies CacheEnvelope);
+ while (Buffer.byteLength(body, 'utf-8') > CACHE_MAX_BYTES && trimmed.length > 0) {
+ trimmed = trimmed.slice(0, trimmed.length - 1);
+ body = JSON.stringify({ _ts: Date.now(), messages: trimmed } satisfies CacheEnvelope);
+ }
+ writeStateJson(CACHE_FILE, { _ts: Date.now(), messages: trimmed });
+}
+
+interface FetchResult {
+ status: number;
+ body: string;
+}
+
+function httpsGet(url: string): Promise<FetchResult> {
+ return new Promise((resolve) => {
+ let target: NodeUrl;
+ try { target = new NodeUrl(url); } catch {
+ resolve({ status: 0, body: 'bad-url' });
+ return;
+ }
+ if (target.protocol !== 'https:') {
+ resolve({ status: 0, body: 'non-https' });
+ return;
+ }
+ const req = https.request(
+ {
+ hostname: target.hostname,
+ port: target.port || 443,
+ path: target.pathname + target.search,
+ method: 'GET',
+ headers: {
+ 'User-Agent': 'ruflo-funnel/messages',
+ 'Accept': 'application/json',
+ },
+ },
+ (res) => {
+ let chunks = '';
+ res.setEncoding('utf-8');
+ res.on('data', (chunk) => { chunks += chunk; });
+ res.on('end', () => resolve({ status: res.statusCode ?? 0, body: chunks }));
+ },
+ );
+ req.setTimeout(FETCH_TIMEOUT_MS, () => {
+ req.destroy();
+ resolve({ status: 0, body: 'timeout' });
+ });
+ req.on('error', () => resolve({ status: 0, body: 'error' }));
+ req.end();
+ });
+}
+
+function killSwitched(env: NodeJS.ProcessEnv = process.env): boolean {
+ const kill = (v?: string) => v !== undefined && /^(0|false|off|no)$/i.test(v.trim());
+ return kill(env.RUFLO_FUNNEL_MESSAGES) || kill(env.RUFLO_FUNNEL);
+}
+
+/**
+ * Best-effort refresh of the cache. Safe to call at any point in the
+ * CLI lifecycle — returns a summary; never throws; never blocks longer
+ * than FETCH_TIMEOUT_MS + write time.
+ */
+export async function refreshRemoteMessages(opts?: {
+ endpoint?: string;
+ force?: boolean;
+ env?: NodeJS.ProcessEnv;
+}): Promise<{ refreshed: boolean; skipped?: string; accepted?: number; rejected?: number; status?: number }> {
+ const env = opts?.env ?? process.env;
+ if (killSwitched(env)) return { refreshed: false, skipped: 'kill-switch' };
+
+ const cache = readCache();
+ if (!opts?.force && cache.fresh) return { refreshed: false, skipped: 'fresh-cache' };
+
+ const endpoint = opts?.endpoint ?? DEFAULT_MESSAGES_ENDPOINT;
+ const res = await httpsGet(endpoint);
+ if (res.status !== 200) return { refreshed: false, skipped: `http-${res.status}`, status: res.status };
+
+ let parsed: unknown;
+ try { parsed = JSON.parse(res.body); } catch { return { refreshed: false, skipped: 'json-parse-error' }; }
+ if (!parsed || typeof parsed !== 'object') return { refreshed: false, skipped: 'not-object' };
+ const raw = (parsed as { messages?: unknown }).messages;
+ if (!Array.isArray(raw)) return { refreshed: false, skipped: 'no-messages-field' };
+
+ // Every message goes through the SAME pipeline the in-code pool uses.
+ // This is where trust boundary enforcement actually lives.
+ const now = new Date();
+ const accepted: FunnelMessage[] = [];
+ let rejected = 0;
+ for (const candidate of raw) {
+ if (isValidMessage(candidate, now)) {
+ accepted.push(candidate);
+ } else {
+ rejected += 1;
+ }
+ }
+ writeCache(accepted);
+ return { refreshed: true, accepted: accepted.length, rejected, status: res.status };
+}
+
+/**
+ * Read the cached remote pool. Returns [] when the cache is empty or
+ * stale enough to distrust — callers should merge with the in-code
+ * fallback pool.
+ */
+export function getRemoteMessages(): FunnelMessage[] {
+ const cache = readCache();
+ return cache.messages;
+}
diff --git a/v3/@claude-flow/cli/src/funnel/messages.ts b/v3/@claude-flow/cli/src/funnel/messages.ts
new file mode 100644
index 0000000000..fc9015382c
--- /dev/null
+++ b/v3/@claude-flow/cli/src/funnel/messages.ts
@@ -0,0 +1,156 @@
+/**
+ * Funnel message registry and content pipeline — ADR-301 signed content
+ * boundaries.
+ *
+ * Messages are inert data. Regardless of how a message reached this process
+ * (in-package today; the signed helper channel later), the renderer treats
+ * it as untrusted and enforces, before display:
+ * - schema validation (invalid → dropped, never repaired)
+ * - length bound (≤ 80 display columns → over-length dropped)
+ * - URL host allowlist (exact hosts, in code — lookalikes/IPs dropped)
+ * - expiry
+ * - zero terminal control sequences (any control char, ANSI/OSC/DCS
+ * escape, or bidi override → dropped, not stripped-and-shown)
+ *
+ * There is no eval path and no styling in the payload: color comes only
+ * from the renderer's own fixed styles.
+ */
+
+import type { FunnelMessage } from './types.js';
+
+export const MAX_MESSAGE_COLUMNS = 80;
+
+/**
+ * Exact-host allowlist (ADR-301). Ships in code, never in the payload.
+ * github.com is allowed only under /ruvnet/.
+ */
+const ALLOWED_URL_HOSTS = new Set([
+ 'cognitum.one', 'www.cognitum.one', 'docs.cognitum.one',
+ // agentics.org — the rUv-authored OSS foundation. Distinct sponsor from
+ // cognitum.one; carries its own promotional messages in the rotation.
+ 'agentics.org', 'www.agentics.org',
+]);
+const GITHUB_HOST = 'github.com';
+const GITHUB_PATH_PREFIX = '/ruvnet/';
+
+/**
+ * C0/C1 controls (incl. ESC, so every ANSI/OSC/DCS sequence trips this),
+ * DEL, and Unicode bidirectional overrides/isolates.
+ */
+// eslint-disable-next-line no-control-regex
+const FORBIDDEN_CHARS = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/;
+
+export function containsForbiddenSequences(text: string): boolean {
+ return FORBIDDEN_CHARS.test(text);
+}
+
+/** Approximate terminal display width: wide CJK/emoji count 2. */
+export function displayWidth(text: string): number {
+ let width = 0;
+ for (const ch of text) {
+ const cp = ch.codePointAt(0) ?? 0;
+ if (cp === 0xfe0f || cp === 0x200d) continue; // variation selector / ZWJ
+ const wide =
+ (cp >= 0x1100 && cp <= 0x115f) ||
+ (cp >= 0x2e80 && cp <= 0xa4cf) ||
+ (cp >= 0xac00 && cp <= 0xd7a3) ||
+ (cp >= 0xf900 && cp <= 0xfaff) ||
+ (cp >= 0xff00 && cp <= 0xff60) ||
+ (cp >= 0x1f000 && cp <= 0x1faff) ||
+ (cp >= 0x20000 && cp <= 0x3fffd);
+ width += wide ? 2 : 1;
+ }
+ return width;
+}
+
+export function isAllowedUrl(url: string): boolean {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return false;
+ }
+ if (parsed.protocol !== 'https:') return false;
+ if (ALLOWED_URL_HOSTS.has(parsed.hostname)) return true;
+ if (parsed.hostname === GITHUB_HOST && parsed.pathname.startsWith(GITHUB_PATH_PREFIX)) return true;
+ return false;
+}
+
+/**
+ * Full validation gate. Returns true only when every ADR-301 content
+ * boundary passes. Failures are silent drops by design — a bad message
+ * must never produce a visible error in the statusline.
+ */
+export function isValidMessage(msg: unknown, now: Date = new Date()): msg is FunnelMessage {
+ if (typeof msg !== 'object' || msg === null) return false;
+ const m = msg as Record<string, unknown>;
+ if (m.schemaVersion !== 1) return false;
+ if (typeof m.id !== 'string' || m.id.length === 0 || m.id.length > 64) return false;
+ if (m.class !== 'educational' && m.class !== 'promotional' && m.class !== 'disclosure') return false;
+ if (typeof m.text !== 'string' || m.text.length === 0) return false;
+ if (containsForbiddenSequences(m.text)) return false;
+ if (displayWidth(m.text) > MAX_MESSAGE_COLUMNS) return false;
+ // Disclosure messages MUST carry the exact ADR-301 manage-instruction tail
+ // — losing that on a truncated/malformed remote message is an invariant
+ // violation, not a cosmetic issue. Never repaired; dropped instead.
+ if (m.class === 'disclosure' && !m.text.includes(' · manage: ruflo settings')) return false;
+ if (m.url !== undefined) {
+ if (typeof m.url !== 'string' || !isAllowedUrl(m.url)) return false;
+ }
+ if (m.expiresAt !== undefined) {
+ if (typeof m.expiresAt !== 'string') return false;
+ const exp = Date.parse(m.expiresAt);
+ if (Number.isNaN(exp) || exp <= now.getTime()) return false;
+ }
+ return true;
+}
+
+/**
+ * Local promo/message content: INTENTIONALLY EMPTY (ADR-311 amendment).
+ *
+ * All rotation content (educational tips, promotional messages, and the
+ * disclosure notice) is served exclusively from the remote message feed
+ * (GET /v1/messages -> message-transport.ts -> Firestore). Zero message
+ * text or URLs ship in the CLI package.
+ *
+ * Fail-closed by design: if the remote feed is unreachable (network down,
+ * cert issue, server outage) and no prior successful fetch has populated
+ * the local cache, the rotation has nothing to show and the promo row
+ * simply does not render that cycle. There is no local content to fall
+ * back to -- this is a deliberate choice, not an oversight.
+ */
+export const MESSAGES: FunnelMessage[] = [];
+
+/** Messages that survive every content boundary right now. */
+export function eligibleMessages(now: Date = new Date()): FunnelMessage[] {
+ return MESSAGES.filter((m) => isValidMessage(m, now));
+}
+
+/**
+ * Merge the remote (cached) message pool with the in-code fallback pool.
+ * The remote pool is authoritative when populated; the in-code pool
+ * covers cold starts and API-down periods. Deduplication is by `id` —
+ * remote wins over in-code for a given id so admins can override without
+ * a client release.
+ */
+export function eligibleMessagesFromPools(
+ inCodePool: readonly FunnelMessage[],
+ remotePool: readonly FunnelMessage[],
+ now: Date = new Date(),
+): FunnelMessage[] {
+ const seen = new Set<string>();
+ const out: FunnelMessage[] = [];
+ for (const m of remotePool) {
+ if (!isValidMessage(m, now)) continue;
+ if (seen.has(m.id)) continue;
+ seen.add(m.id);
+ out.push(m);
+ }
+ for (const m of inCodePool) {
+ if (!isValidMessage(m, now)) continue;
+ if (seen.has(m.id)) continue;
+ seen.add(m.id);
+ out.push(m);
+ }
+ return out;
+}
diff --git a/v3/@claude-flow/cli/src/funnel/power-saver-notifier.ts b/v3/@claude-flow/cli/src/funnel/power-saver-notifier.ts
new file mode 100644
index 0000000000..b1317feb75
--- /dev/null
+++ b/v3/@claude-flow/cli/src/funnel/power-saver-notifier.ts
@@ -0,0 +1,100 @@
+/**
+ * Power-saver notifier — ADR-314 §A out-of-band signal path.
+ *
+ * Structural mirror of rate-limit-notifier.ts, same self-reported/manual
+ * constraint (ADR-312's detection gap applies unchanged — ruflo cannot read
+ * "your account is at 20%" any more than it can read "you are rate
+ * limited"). Deliberately a SEPARATE flag from rate-limited: "running low,
+ * want to proactively conserve" (still have capacity) and "blocked" (zero
+ * capacity left) are different urgencies — conflating them would mean
+ * power-saver mode never fires until you're already blocked (too late to
+ * have conserved anything).
+ *
+ * State is cheap and durable:
+ * ~/.ruflo/quota-status.json = { low: bool, since: ISO, cleared: ISO|null, lastToggleAt: ISO|null }
+ *
+ * Same 6h TTL rationale as rate-limit-notifier.ts, and the same ADR-314 §D1
+ * toggle cooldown (10 min) — a self-reported flag with zero server-side
+ * verification needs at least this much client-side friction against
+ * casual always-on gaming.
+ */
+
+import { readStateJson, writeStateJson } from './state.js';
+import { cooldownActive } from './toggle-cooldown.js';
+
+export const QUOTA_STATUS_FILE = 'quota-status.json';
+
+/** Auto-expire a forgotten manual flag after 6h (see module doc). */
+export const QUOTA_LOW_TTL_MS = 6 * 60 * 60 * 1000;
+
+export interface QuotaLowStatus {
+ low: boolean;
+ since: string | null;
+ cleared: string | null;
+ lastToggleAt: string | null;
+}
+
+/** Read the current power-saver status. Never throws. Applies the TTL. */
+export function readQuotaLowStatus(now: Date = new Date()): QuotaLowStatus {
+ const raw = readStateJson<QuotaLowStatus>(QUOTA_STATUS_FILE);
+ const status: QuotaLowStatus = {
+ low: raw?.low ?? false,
+ since: raw?.since ?? null,
+ cleared: raw?.cleared ?? null,
+ lastToggleAt: raw?.lastToggleAt ?? null,
+ };
+ if (status.low && status.since) {
+ const since = Date.parse(status.since);
+ if (!Number.isNaN(since) && now.getTime() - since >= QUOTA_LOW_TTL_MS) {
+ return { low: false, since: status.since, cleared: now.toISOString(), lastToggleAt: status.lastToggleAt };
+ }
+ }
+ return status;
+}
+
+/**
+ * Mark quota as running low — idempotent, cooldown-gated (ADR-314 §D1).
+ * Returns false when the cooldown blocks the flip (not yet applied).
+ */
+export function markQuotaLow(now: Date = new Date()): boolean {
+ const current = readQuotaLowStatus(now);
+ if (current.low && current.since) return true; // already flagged, not a change
+ if (cooldownActive(current.lastToggleAt, now)) return false;
+ writeStateJson(QUOTA_STATUS_FILE, {
+ low: true,
+ since: current.since ?? now.toISOString(),
+ cleared: null,
+ lastToggleAt: now.toISOString(),
+ } satisfies QuotaLowStatus);
+ return true;
+}
+
+/** Clear power-saver status. Cooldown-gated the same way as the mark direction. */
+export function clearQuotaLowStatus(now: Date = new Date()): boolean {
+ const current = readQuotaLowStatus(now);
+ if (!current.low) return true; // already clear, not a change
+ if (cooldownActive(current.lastToggleAt, now)) return false;
+ writeStateJson(QUOTA_STATUS_FILE, {
+ low: false,
+ since: current.since,
+ cleared: now.toISOString(),
+ lastToggleAt: now.toISOString(),
+ } satisfies QuotaLowStatus);
+ return true;
+}
+
+/**
+ * User-facing single-line summary — plain text, no ANSI. Returns null when
+ * not flagged low (no surface).
+ */
+export function quotaLowNotice(now: Date = new Date()): string | null {
+ const status = readQuotaLowStatus(now);
+ if (!status.low) return null;
+ const since = status.since ? Date.parse(status.since) : NaN;
+ if (Number.isNaN(since)) {
+ return 'Power saver mode active · manage: ruflo proxy power-saver-disable';
+ }
+ const ageMin = Math.max(0, Math.round((now.getTime() - since) / (60 * 1000)));
+ const when = ageMin < 1 ? 'just now' : ageMin < 60 ? `${ageMin}m ago` : `${Math.round(ageMin / 60)}h ago`;
+ return `Power saver mode active (${when}) · manage: ruflo proxy power-saver-disable`;
+}
diff --git a/v3/@claude-flow/cli/src/funnel/precedence.ts b/v3/@claude-flow/cli/src/funnel/precedence.ts
new file mode 100644
index 0000000000..77d101aee8
--- /dev/null
+++ b/v3/@claude-flow/cli/src/funnel/precedence.ts
@@ -0,0 +1,88 @@
+/**
+ * Control precedence resolver — ADR-305 (normative).
+ *
+ * 1. RUFLO_FUNNEL=0 (environment)
+ * 2. Enterprise managed policy
+ * 3. User config (funnel.enabled — user-level and project-level)
+ * 4. Package default
+ * 5. Remote signed policy (only when the freshness feed is enabled)
+ *
+ * A lower-precedence source must never re-enable a higher-precedence
+ * disable — implemented as a strict AND chain: every source can veto,
+ * none can override a veto above it.
+ */
+
+import * as fs from 'fs';
+import * as path from 'path';
+import type { FunnelEnabledDecision } from './types.js';
+import { readStateJson } from './state.js';
+import { getDisclosure } from './disclosure.js';
+
+interface FunnelUserConfig {
+ enabled?: boolean;
+}
+
+function envDisabled(env: NodeJS.ProcessEnv): boolean {
+ const v = env.RUFLO_FUNNEL;
+ return v !== undefined && /^(0|false|off|no)$/i.test(v.trim());
+}
+
+function enterprisePolicyDisabled(env: NodeJS.ProcessEnv): boolean {
+ const candidates: string[] = [];
+ if (env.RUFLO_ENTERPRISE_POLICY) candidates.push(env.RUFLO_ENTERPRISE_POLICY);
+ if (process.platform === 'win32') {
+ if (env.ProgramData) candidates.push(path.join(env.ProgramData, 'ruflo', 'policy.json'));
+ } else {
+ candidates.push('/etc/ruflo/policy.json');
+ }
+ for (const p of candidates) {
+ try {
+ const policy = JSON.parse(fs.readFileSync(p, 'utf-8'));
+ if (policy?.funnel?.enabled === false) return true;
+ } catch {
+ // unreadable/absent policy is not a policy
+ }
+ }
+ return false;
+}
+
+function userConfigDisabled(): boolean {
+ const cfg = readStateJson<FunnelUserConfig>('funnel.json');
+ return cfg?.enabled === false;
+}
+
+function projectConfigDisabled(cwd: string): boolean {
+ try {
+ const cfg = JSON.parse(fs.readFileSync(path.join(cwd, 'claude-flow.config.json'), 'utf-8'));
+ return cfg?.funnel?.enabled === false;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Remote signed policy (ADR-305 freshness kill switch). The feed is opt-in
+ * and OFF by default; when a validated policy has been stored locally it can
+ * only disable — sitting at the bottom of the chain guarantees it can never
+ * re-enable anything a higher source turned off.
+ */
+function remotePolicyDisabled(): boolean {
+ const policy = readStateJson<{ funnelEnabled?: boolean }>('funnel-remote-policy.json');
+ return policy?.funnelEnabled === false;
+}
+
+export function resolveFunnelEnabled(
+ cwd: string = process.cwd(),
+ env: NodeJS.ProcessEnv = process.env,
+): FunnelEnabledDecision {
+ if (envDisabled(env)) return { enabled: false, decidedBy: 'env' };
+ if (enterprisePolicyDisabled(env)) return { enabled: false, decidedBy: 'enterprise-policy' };
+ if (userConfigDisabled()) return { enabled: false, decidedBy: 'user-config' };
+ if (projectConfigDisabled(cwd)) return { enabled: false, decidedBy: 'project-config' };
+ // Declining the disclosure disables all funnel surfaces (ADR-301 invariant).
+ if (getDisclosure().state === 'disclosed_disabled') {
+ return { enabled: false, decidedBy: 'disclosure-declined' };
+ }
+ if (remotePolicyDisabled()) return { enabled: false, decidedBy: 'remote-policy' };
+ return { enabled: true, decidedBy: 'package-default' };
+}
diff --git a/v3/@claude-flow/cli/src/funnel/promo.ts b/v3/@claude-flow/cli/src/funnel/promo.ts
new file mode 100644
index 0000000000..cdca0a31a4
--- /dev/null
+++ b/v3/@claude-flow/cli/src/funnel/promo.ts
@@ -0,0 +1,171 @@
+/**
+ * Promo-row orchestrator — the single entry point the statusline hook calls
+ * (ADR-301). Applies, in order:
+ *
+ * 1. Control precedence (env / enterprise / user / project / remote) —
+ * any disable → nothing renders, ever.
+ * 2. Environment gates — CI never sees funnel content.
+ * 3. Disclosure gate — an upgraded install shows the disclosure text
+ * (with the disable instruction) before any message; promotional
+ * content only after the grace window.
+ * 4. ADR-313 sponsored-downtime override — preempts everything below
+ * while rate-limited (unconditional, not slot-based).
+ * 5. Local insight ticker (insights.ts) — a reserved 1-in-5 slot shows an
+ * environment/task-aware suggestion (CVEs, uncommitted changes,
+ * power-saver state) when one exists; otherwise falls through.
+ * 6. Rotation — 4:1 educational:promotional, 30-min promo repeat cap.
+ *
+ * Output is plain text (no ANSI — the renderer applies its own fixed
+ * style), ≤ 80 columns, already sanitized by the message pipeline.
+ */
+
+import type { PromoRow } from './types.js';
+import { resolveFunnelEnabled } from './precedence.js';
+import { isCI } from './environment.js';
+import {
+ getDisclosure,
+ promoEligible,
+ recordDisclosureShown,
+ selectDisclosureMessage,
+} from './disclosure.js';
+import { clickTrackedUrl } from './attribution.js';
+import { selectMessage, ROTATION_SLOT_MS } from './rotation.js';
+import { recordFunnelEvent } from './events.js';
+import { getInstalledCliVersion } from '../init/helper-refresh.js';
+import { hasConsent } from './consent.js';
+import { readRateLimitStatus } from './rate-limit-notifier.js';
+import { selectLocalInsight, type LocalInsightContext } from './insights.js';
+
+/**
+ * ADR-313 priority override: when the user has manually flagged a Claude
+ * usage limit (ADR-312 Phase 0), preempt normal rotation with a dedicated
+ * CTA — same precedent as ADR-303's credit-exhaustion recovery surface.
+ * Two states depending on whether sponsored-downtime consent is granted:
+ * - not yet enabled: an actionable CTA to enable it
+ * - already enabled: a quiet status line confirming it's active
+ * Both message strings use the exact " · manage: " anchor the renderer
+ * already splits on (statusline-generator.ts getPromoRow) — no renderer
+ * change needed; the command portion renders bold, never as a fake link.
+ * Returns null when the rate-limit flag isn't set (no override).
+ */
+function getSponsoredDowntimeOverride(now: Date): PromoRow | null {
+ const status = readRateLimitStatus(now);
+ if (!status.limited) return null;
+
+ if (hasConsent('sponsored-downtime')) {
+ return {
+ text: '⚡ Running on sponsored Cognitum capacity · manage: ruflo proxy sponsor-disable',
+ kind: 'promotional',
+ };
+ }
+ return {
+ text: '⚡ Free Cognitum capacity while you wait · manage: ruflo proxy sponsor-enable',
+ kind: 'promotional',
+ };
+}
+
+export interface PromoContext {
+ cwd?: string;
+ env?: NodeJS.ProcessEnv;
+ now?: Date;
+ /**
+ * Whether the calling surface is an interactive session. The statusline
+ * hook is spawned with piped stdio by an interactive host, so the caller
+ * asserts interactivity; directly-run non-TTY invocations pass false.
+ */
+ interactive: boolean;
+ /**
+ * Local environment/task signal for the insight ticker (insights.ts) —
+ * optional and additive. Callers that don't pass it simply never see a
+ * local insight; the remote rotation is entirely unaffected either way.
+ */
+ localInsights?: LocalInsightContext;
+}
+
+/** 1 in 5 slots, a different phase than rotation.ts's promo slot (slot%5==4)
+ * so the two never collide — reserved for a local insight IF one exists;
+ * otherwise falls through to the normal remote rotation untouched. This is
+ * the "ticker" cadence: insights appear periodically, never permanently
+ * take over the row, and never appear at all when nothing is actionable. */
+const INSIGHT_SLOT_MODULO = 5;
+const INSIGHT_SLOT_PHASE = 2;
+
+function isInsightSlot(now: Date): boolean {
+ const slot = Math.floor(now.getTime() / ROTATION_SLOT_MS);
+ return slot % INSIGHT_SLOT_MODULO === INSIGHT_SLOT_PHASE;
+}
+
+export function getFunnelPromo(ctx: PromoContext): PromoRow | null {
+ const env = ctx.env ?? process.env;
+ const now = ctx.now ?? new Date();
+
+ if (!ctx.interactive) return null;
+ if (isCI(env)) return null;
+
+ const decision = resolveFunnelEnabled(ctx.cwd ?? process.cwd(), env);
+ if (!decision.enabled) return null;
+
+ const release = getInstalledCliVersion();
+
+ // Disclosure gate: never a message before the disclosure has been shown
+ // and its grace window has passed. The disclosure MESSAGE itself is now
+ // remote-sourced (ADR-311) — selectDisclosureMessage() returns null when
+ // the remote pool hasn't populated yet (cold start / outage), and per the
+ // "zero local promo content" design, null means show nothing this cycle.
+ const disclosure = getDisclosure();
+ if (disclosure.state === 'never_seen') {
+ const msg = selectDisclosureMessage(now);
+ if (!msg) return null; // fail-closed: no remote disclosure cached yet
+ recordDisclosureShown(now);
+ recordFunnelEvent('disclosure_shown', 'statusline', release, { now, messageId: msg.id });
+ const url = msg.url ? clickTrackedUrl(msg.id, msg.url, {
+ medium: 'statusline', campaign: 'disclosure', content: msg.id, now,
+ }) : undefined;
+ return { text: msg.text, kind: 'disclosure', url };
+ }
+ if (!promoEligible(now)) {
+ if (disclosure.state === 'disclosed_enabled') {
+ const msg = selectDisclosureMessage(now);
+ if (!msg) return null; // fail-closed
+ const url = msg.url ? clickTrackedUrl(msg.id, msg.url, {
+ medium: 'statusline', campaign: 'disclosure', content: msg.id, now,
+ }) : undefined;
+ return { text: msg.text, kind: 'disclosure', url };
+ }
+ return null; // disclosed_disabled is caught by precedence, but stay fail-closed
+ }
+
+ // ADR-313 priority override: a self-reported usage-limit flag preempts
+ // normal rotation, exactly the way ADR-303's credit-exhaustion recovery
+ // is designed to preempt it. Only reachable here — i.e. only after the
+ // disclosure invariant (ADR-301 "no promotional content before
+ // disclosure") has already been satisfied above.
+ const override = getSponsoredDowntimeOverride(now);
+ if (override) return override;
+
+ // Local insight ticker: on its reserved 1-in-5 slot, show the highest-
+ // priority environment/task insight if one exists — CVEs pending,
+ // uncommitted changes, power-saver active, etc. (insights.ts). No
+ // insight this render (or no context passed) → fall straight through to
+ // the untouched remote rotation below, same as any other slot.
+ if (ctx.localInsights && isInsightSlot(now)) {
+ const insight = selectLocalInsight(ctx.localInsights);
+ if (insight) return { text: insight.text, kind: 'insight' };
+ }
+
+ const msg = selectMessage(now, release);
+ if (!msg) return null;
+ // Any message carrying a URL (educational tips included) routes through
+ // the server click-redirect so `promo_open` + coarse geo are captured
+ // before 302ing to the real target — click counting is uniform across
+ // the whole rotation, not just the promotional slot. If the click
+ // endpoint chain rejects the URL for any reason, fall back to the
+ // UTM-decorated direct link so the click still lands where it should.
+ let url: string | undefined;
+ if (msg.url) {
+ url = clickTrackedUrl(msg.id, msg.url, {
+ medium: 'statusline', campaign: msg.class, content: msg.id, now,
+ });
+ }
+ return { text: msg.text, kind: msg.class, url };
+}
diff --git a/v3/@claude-flow/cli/src/funnel/rate-limit-notifier.ts b/v3/@claude-flow/cli/src/funnel/rate-limit-notifier.ts
new file mode 100644
index 0000000000..bba35f6c6f
--- /dev/null
+++ b/v3/@claude-flow/cli/src/funnel/rate-limit-notifier.ts
@@ -0,0 +1,111 @@
+/**
+ * Rate-limit notifier — ADR-312 Phase 0 out-of-band signal path.
+ *
+ * Structural mirror of credit-notifier.ts. This is NOT automatic detection
+ * — ADR-312 established that Claude Code does not currently expose any way
+ * to detect its own usage-limit state from outside its process (verified
+ * against the actual installed CLI source, not assumed). This module is the
+ * MANUAL, self-reported alternative: the user tells ruflo they've hit a
+ * limit, ruflo remembers it, and the funnel promo row can react.
+ *
+ * State is cheap and durable:
+ * ~/.ruflo/rate-limit-status.json = { limited: bool, since: ISO, cleared: ISO|null }
+ *
+ * A TTL (default 6h) auto-expires a forgotten flag so a stale manual mark
+ * doesn't linger indefinitely if the user forgets to clear it — Claude
+ * usage limits reset on hours-to-days cadences (five_hour / seven_day per
+ * ADR-312's grounded research), so 6h is a reasonable "the user probably
+ * forgot to clear this" bound without requiring per-type precision we
+ * don't have.
+ */
+
+import { readStateJson, writeStateJson } from './state.js';
+import { cooldownActive } from './toggle-cooldown.js';
+
+export const RATE_LIMIT_STATUS_FILE = 'rate-limit-status.json';
+
+/** Auto-expire a forgotten manual flag after 6h (see module doc). */
+export const RATE_LIMIT_TTL_MS = 6 * 60 * 60 * 1000;
+
+export interface RateLimitStatus {
+ limited: boolean;
+ since: string | null;
+ cleared: string | null;
+ /** ADR-314 §D1 — last time `limited` actually changed value; gates the toggle cooldown. */
+ lastToggleAt: string | null;
+}
+
+/** Read the current rate-limit status. Never throws. Applies the TTL. */
+export function readRateLimitStatus(now: Date = new Date()): RateLimitStatus {
+ const raw = readStateJson<RateLimitStatus>(RATE_LIMIT_STATUS_FILE);
+ const status: RateLimitStatus = {
+ limited: raw?.limited ?? false,
+ since: raw?.since ?? null,
+ cleared: raw?.cleared ?? null,
+ lastToggleAt: raw?.lastToggleAt ?? null,
+ };
+ if (status.limited && status.since) {
+ const since = Date.parse(status.since);
+ if (!Number.isNaN(since) && now.getTime() - since >= RATE_LIMIT_TTL_MS) {
+ return { limited: false, since: status.since, cleared: now.toISOString(), lastToggleAt: status.lastToggleAt };
+ }
+ }
+ return status;
+}
+
+/**
+ * Mark as rate-limited — idempotent. Sets `since` on the first mark, leaves
+ * it alone on subsequent marks so the user sees a stable "since" timestamp
+ * until they clear it or the TTL expires. Refuses to flip false→true inside
+ * the ADR-314 §D1 cooldown window (returns false; a no-op re-mark of an
+ * already-true flag is unaffected — that's not a state change).
+ */
+export function markRateLimited(now: Date = new Date()): boolean {
+ const current = readRateLimitStatus(now);
+ if (current.limited && current.since) return true; // already flagged, not a change
+ if (cooldownActive(current.lastToggleAt, now)) return false;
+ writeStateJson(RATE_LIMIT_STATUS_FILE, {
+ limited: true,
+ since: current.since ?? now.toISOString(),
+ cleared: null,
+ lastToggleAt: now.toISOString(),
+ } satisfies RateLimitStatus);
+ return true;
+}
+
+/**
+ * Clear rate-limited status. Called via `ruflo settings notices
+ * rate-limited --clear`, automatically by the TTL, or once a real Phase 1/2
+ * signal (ADR-312) confirms the limit has reset. Refuses to flip true→false
+ * inside the cooldown window (returns false); clearing an already-clear
+ * flag is always allowed (not a state change, and TTL auto-clear must never
+ * be blocked by a cooldown it didn't itself trigger).
+ */
+export function clearRateLimitStatus(now: Date = new Date()): boolean {
+ const current = readRateLimitStatus(now);
+ if (!current.limited) return true; // already clear, not a change
+ if (cooldownActive(current.lastToggleAt, now)) return false;
+ writeStateJson(RATE_LIMIT_STATUS_FILE, {
+ limited: false,
+ since: current.since,
+ cleared: now.toISOString(),
+ lastToggleAt: now.toISOString(),
+ } satisfies RateLimitStatus);
+ return true;
+}
+
+/**
+ * User-facing single-line summary — plain text, no ANSI. Callers style it
+ * themselves. Returns null when not rate-limited (no surface).
+ */
+export function rateLimitNotice(now: Date = new Date()): string | null {
+ const status = readRateLimitStatus(now);
+ if (!status.limited) return null;
+ const since = status.since ? Date.parse(status.since) : NaN;
+ if (Number.isNaN(since)) {
+ return 'Claude usage limit flagged · run: ruflo proxy sponsor-enable';
+ }
+ const ageMin = Math.max(0, Math.round((now.getTime() - since) / (60 * 1000)));
+ const when = ageMin < 1 ? 'just now' : ageMin < 60 ? `${ageMin}m ago` : `${Math.round(ageMin / 60)}h ago`;
+ return `Claude usage limit flagged (${when}) · run: ruflo proxy sponsor-enable`;
+}
diff --git a/v3/@claude-flow/cli/src/funnel/rotation.ts b/v3/@claude-flow/cli/src/funnel/rotation.ts
new file mode 100644
index 0000000000..99ea06123d
--- /dev/null
+++ b/v3/@claude-flow/cli/src/funnel/rotation.ts
@@ -0,0 +1,80 @@
+/**
+ * Rotation scheduler — ADR-301 content ratio, enforced structurally.
+ *
+ * - Educational: at least 4 of every 5 rotation slots.
+ * - Promotional: at most 1 of every 5 slots (slot % 5 === 4), and only
+ * when no promotion has shown in the last 30 minutes.
+ * - Deterministic: selection is a pure function of (time slot, registry,
+ * last-promo state) — no Math.random, so renders are reproducible and
+ * the statusline cache can't skew the ratio.
+ */
+
+import type { FunnelMessage } from './types.js';
+import { MESSAGES, eligibleMessagesFromPools } from './messages.js';
+import { getRemoteMessages, refreshRemoteMessages } from './message-transport.js';
+import { readStateJson, writeStateJson } from './state.js';
+import { recordFunnelEvent } from './events.js';
+
+const ROTATION_FILE = 'funnel-rotation.json';
+
+/** One rotation slot — ADR-301 allows 15–30s; 20s sits inside the band. */
+export const ROTATION_SLOT_MS = 20_000;
+/** The same promotion appears at most once every 30 minutes (ADR-301). */
+export const PROMO_REPEAT_CAP_MS = 30 * 60 * 1000;
+/** 1 promotional slot per 5 (ADR-301: ≤ 1 in 5 rotations). */
+export const PROMO_SLOT_MODULO = 5;
+
+interface RotationState {
+ lastPromoAt?: string;
+ lastPromoId?: string;
+}
+
+export function selectMessage(now: Date = new Date(), release: string = 'unknown'): FunnelMessage | null {
+ // Kick a background refresh — never awaited, never blocks render. The
+ // remote pool becomes visible on subsequent selects once cached.
+ void refreshRemoteMessages();
+ // Merge: remote pool authoritative, in-code pool fallback (by id).
+ const pool = eligibleMessagesFromPools(MESSAGES, getRemoteMessages(), now);
+ const educational = pool.filter((m) => m.class === 'educational');
+ const promotional = pool.filter((m) => m.class === 'promotional');
+ if (educational.length === 0 && promotional.length === 0) return null;
+
+ const slot = Math.floor(now.getTime() / ROTATION_SLOT_MS);
+ const promoSlot = slot % PROMO_SLOT_MODULO === PROMO_SLOT_MODULO - 1;
+
+ let selected: FunnelMessage | null = null;
+ if (promoSlot && promotional.length > 0 && promoCapClear(now)) {
+ selected = promotional[Math.floor(slot / PROMO_SLOT_MODULO) % promotional.length];
+ recordPromoShown(selected, now);
+ } else if (educational.length > 0) {
+ selected = educational[slot % educational.length];
+ }
+
+ // Fire an impression event for whichever message was selected. Consent-gated
+ // (recordFunnelEvent no-ops without telemetry consent). Idempotency across
+ // renders in the same slot is handled by the same-slot deduplication in
+ // the events transport — we don't try to dedupe here because the slot
+ // math already returns the same id for the same slot, giving downstream
+ // aggregation a per-slot boolean.
+ if (selected) {
+ recordFunnelEvent('promo_impression', 'statusline', release, {
+ now, messageId: selected.id,
+ });
+ }
+ return selected;
+}
+
+function promoCapClear(now: Date): boolean {
+ const state = readStateJson<RotationState>(ROTATION_FILE);
+ if (!state?.lastPromoAt) return true;
+ const last = Date.parse(state.lastPromoAt);
+ if (Number.isNaN(last)) return true;
+ return now.getTime() - last >= PROMO_REPEAT_CAP_MS;
+}
+
+function recordPromoShown(msg: FunnelMessage, now: Date): void {
+ writeStateJson(ROTATION_FILE, {
+ lastPromoAt: now.toISOString(),
+ lastPromoId: msg.id,
+ } satisfies RotationState);
+}
diff --git a/v3/@claude-flow/cli/src/funnel/state.ts b/v3/@claude-flow/cli/src/funnel/state.ts
new file mode 100644
index 0000000000..95d5a4f2ba
--- /dev/null
+++ b/v3/@claude-flow/cli/src/funnel/state.ts
@@ -0,0 +1,53 @@
+/**
+ * Funnel state storage — user-level JSON files under ~/.ruflo (ADR-302/305).
+ *
+ * User-level (not project-level) so dismissals, consent, and disclosure
+ * persist across projects. Files are written 0600 and never committed.
+ * RUFLO_STATE_DIR overrides the directory (tests, unusual $HOME setups).
+ */
+
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+
+export function funnelStateDir(): string {
+ const override = process.env.RUFLO_STATE_DIR;
+ if (override && override.trim()) return override;
+ return path.join(os.homedir(), '.ruflo');
+}
+
+export function statePath(name: string): string {
+ return path.join(funnelStateDir(), name);
+}
+
+export function readStateJson<T>(name: string): T | null {
+ try {
+ const raw = fs.readFileSync(statePath(name), 'utf-8');
+ return JSON.parse(raw) as T;
+ } catch {
+ return null;
+ }
+}
+
+export function writeStateJson(name: string, value: unknown): boolean {
+ try {
+ const dir = funnelStateDir();
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
+ const target = statePath(name);
+ // Write-then-rename so a crash never leaves a truncated state file.
+ const tmp = `${target}.tmp`;
+ fs.writeFileSync(tmp, JSON.stringify(value, null, 2), { encoding: 'utf-8', mode: 0o600 });
+ fs.renameSync(tmp, target);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function deleteStateFile(name: string): void {
+ try {
+ fs.unlinkSync(statePath(name));
+ } catch {
+ // already absent — fine
+ }
+}
diff --git a/v3/@claude-flow/cli/src/funnel/toggle-cooldown.ts b/v3/@claude-flow/cli/src/funnel/toggle-cooldown.ts
new file mode 100644
index 0000000000..4db5be6904
--- /dev/null
+++ b/v3/@claude-flow/cli/src/funnel/toggle-cooldown.ts
@@ -0,0 +1,30 @@
+/**
+ * Shared toggle cooldown — ADR-314 §D1.
+ *
+ * Self-reported flags (rate-limited, quota-low) have zero server-side
+ * verification (ADR-312's Phase 0 constraint carries over unchanged). A
+ * cooldown on how often the flag can actually CHANGE state is cheap,
+ * purely client-side friction against casual "always on" gaming or a
+ * scripted flip-flop loop — it does not stop a determined abuser (that
+ * needs the per-identity server-side quota ADR-314 flags as the real fix),
+ * but it raises the bar above "one line in a shell script."
+ */
+
+export const TOGGLE_COOLDOWN_MS = 10 * 60 * 1000;
+
+/** True when `lastToggleAt` is within the cooldown window of `now`. */
+export function cooldownActive(lastToggleAt: string | null, now: Date): boolean {
+ if (!lastToggleAt) return false;
+ const t = Date.parse(lastToggleAt);
+ if (Number.isNaN(t)) return false;
+ return now.getTime() - t < TOGGLE_COOLDOWN_MS;
+}
+
+/** Minutes remaining in the cooldown window — for user-facing messages. */
+export function cooldownRemainingMin(lastToggleAt: string | null, now: Date): number {
+ if (!lastToggleAt) return 0;
+ const t = Date.parse(lastToggleAt);
+ if (Number.isNaN(t)) return 0;
+ const remainingMs = TOGGLE_COOLDOWN_MS - (now.getTime() - t);
+ return Math.max(0, Math.ceil(remainingMs / (60 * 1000)));
+}
diff --git a/v3/@claude-flow/cli/src/funnel/types.ts b/v3/@claude-flow/cli/src/funnel/types.ts
new file mode 100644
index 0000000000..3f98e17b3c
--- /dev/null
+++ b/v3/@claude-flow/cli/src/funnel/types.ts
@@ -0,0 +1,185 @@
+/**
+ * Funnel type definitions — ADR-301..310.
+ *
+ * The funnel is the ruflo → Cognitum lifecycle system: promotional status
+ * surface (ADR-301), post-init enrollment (ADR-302), credit-exhaustion
+ * recovery (ADR-303), governed by consent receipts (ADR-302), control
+ * precedence (ADR-305), and the governance/privacy rules of ADR-309.
+ *
+ * Everything in this module is local-only: no code path here performs
+ * network I/O. Events are queued locally and only when telemetry consent
+ * is granted (ADR-308 failure policy: telemetry never blocks the CLI).
+ */
+
+// ─── ADR-301: disclosure ────────────────────────────────────────────────────
+
+export type FunnelDisclosureState =
+ | 'never_seen'
+ | 'disclosed_enabled'
+ | 'disclosed_disabled';
+
+export interface DisclosureRecord {
+ state: FunnelDisclosureState;
+ /** ISO timestamp of the first render of the disclosure text. */
+ firstShownAt: string | null;
+}
+
+// ─── ADR-301: messages ──────────────────────────────────────────────────────
+
+// 'disclosure' is a server-sourced message class (ADR-311 amendment) — the
+// existing-install disclosure notice is now fetched from the same remote
+// message feed as tips/promos, not hardcoded in the CLI. This keeps the
+// "zero local promo content" guarantee: nothing about WHAT is shown ships
+// in the package, only the mechanism for showing it (state tracking,
+// content pipeline, host allowlist).
+export type FunnelMessageClass = 'educational' | 'promotional' | 'disclosure';
+
+export interface FunnelMessage {
+ id: string;
+ schemaVersion: 1;
+ text: string;
+ /** Optional link; must pass the in-code host allowlist or the message is dropped. */
+ url?: string;
+ class: FunnelMessageClass;
+ /** ISO timestamp; expired messages leave the rotation immediately. */
+ expiresAt?: string;
+}
+
+export interface PromoRow {
+ text: string;
+ // 'insight' is deliberately NOT part of FunnelMessageClass — insights are
+ // computed locally from environment/task state (CVEs, git, swarm), never
+ // remote-served, never run through the remote-content validation pipeline
+ // (messages.ts's isValidMessage()). Keeping it a separate literal here
+ // means "every FunnelMessageClass came from the remote/in-code content
+ // pipeline" stays a true invariant elsewhere in the codebase.
+ kind: 'disclosure' | FunnelMessageClass | 'insight';
+ url?: string;
+}
+
+// ─── ADR-302: consent domains ───────────────────────────────────────────────
+
+export type ConsentDomain =
+ | 'account'
+ | 'proxy-install'
+ | 'telemetry'
+ | 'cloud-routing'
+ | 'hosted-memory'
+ // ADR-313: separate from cloud-routing — sponsored capacity is Cognitum's
+ // own model traffic, billed to Cognitum, not the user's cloud config.
+ | 'sponsored-downtime'
+ // ADR-314: separate from both — power saver routes through the user's OWN
+ // Cognitum account (Cloud plane), not sponsored/free capacity, but it's
+ // still a distinct decision from generic cloud-routing (auto-rewrites the
+ // model to cognitum-auto, which cloud-routing consent alone doesn't imply).
+ | 'power-saver'
+ // ADR-315 Tier 2: separate from sponsored-downtime — using free/sponsored
+ // capacity must never implicitly mean donating prompt content for model
+ // training. This is the one consent domain in the whole family that
+ // gates raw interaction CONTENT leaving the client, not just a routing
+ // decision, so it is never bundled with anything else.
+ | 'training-data-sharing'
+ // ADR-316: separate again — a periodic, budget-capped `claude -p` call to
+ // a headless Fable model for a proactive statusline tip. The payload is
+ // structural signals only (never raw prompt/command/file content, unlike
+ // the concern training-data-sharing gates), but it's still a real, opt-in
+ // network call with a real cost, and gets its own never-bundled decision
+ // like every other domain in this family.
+ | 'advisor-tips';
+
+export interface ConsentReceipt {
+ granted: boolean;
+ policyVersion: number;
+ /** ISO timestamp of the decision; null = never asked. */
+ at: string | null;
+ surface: string | null;
+}
+
+export type ConsentFile = Partial<Record<ConsentDomain, ConsentReceipt>>;
+
+/** Bump when the meaning of a consent domain changes materially (ADR-302). */
+export const CONSENT_POLICY_VERSION = 1;
+
+// ─── ADR-305: control precedence ────────────────────────────────────────────
+
+export type FunnelDecisionSource =
+ | 'env' // RUFLO_FUNNEL=0
+ | 'enterprise-policy'
+ | 'user-config'
+ | 'project-config'
+ | 'package-default'
+ | 'remote-policy'
+ | 'disclosure-declined';
+
+export interface FunnelEnabledDecision {
+ enabled: boolean;
+ decidedBy: FunnelDecisionSource;
+}
+
+// ─── ADR-303: credit error taxonomy ─────────────────────────────────────────
+
+export enum CreditErrorCode {
+ /** Cognitum ledger says balance is spent — the ONLY funnel trigger. */
+ COGNITUM_CREDIT_EXHAUSTED = 'COGNITUM_CREDIT_EXHAUSTED',
+ /** Upstream provider's own quota, not Cognitum credits. */
+ PROVIDER_QUOTA_EXHAUSTED = 'PROVIDER_QUOTA_EXHAUSTED',
+ PROVIDER_RATE_LIMITED = 'PROVIDER_RATE_LIMITED',
+ AUTHENTICATION_FAILED = 'AUTHENTICATION_FAILED',
+ SERVICE_UNAVAILABLE = 'SERVICE_UNAVAILABLE',
+}
+
+export interface NormalizedCreditError {
+ code: CreditErrorCode | null;
+ /** 1 only when an explicit machine-readable provider code mapped; else 0. */
+ confidence: 0 | 1;
+ retryable: boolean;
+ /** Original provider error, preserved verbatim for --verbose paths. */
+ cause?: unknown;
+}
+
+// ─── ADR-309: funnel events (closed set, constrained schema) ────────────────
+
+export type FunnelEventName =
+ // ADR-305 core lifecycle events
+ | 'disclosure_shown'
+ | 'funnel_disabled'
+ | 'signup_opened'
+ | 'account_created'
+ | 'proxy_activated'
+ // ADR-311 impression + click tracking (server-side click-redirect fires
+ // 'promo_open' after the client has fired 'promo_impression' on render).
+ | 'promo_impression'
+ | 'promo_open'
+ // ADR-313 sponsored downtime mode
+ | 'sponsor_mode_enabled'
+ | 'sponsor_mode_disabled'
+ | 'sponsor_capacity_exhausted'
+ // ADR-314 power saver mode + anti-abuse
+ | 'power_saver_enabled'
+ | 'power_saver_disabled'
+ | 'toggle_cooldown_blocked'
+ // ADR-315 Tier 2 training-data-sharing consent
+ | 'training_share_enabled'
+ | 'training_share_disabled'
+ // ADR-316 advisor co-pilot tip consent
+ | 'advisor_tip_enabled'
+ | 'advisor_tip_disabled';
+
+export type FunnelSurface = 'statusline' | 'init' | 'credit_exhaustion';
+
+export interface FunnelEvent {
+ schemaVersion: 1;
+ event: FunnelEventName;
+ surface: FunnelSurface;
+ release: string;
+ region?: string;
+ pseudonymousId?: string;
+ /**
+ * Message id for promo_impression / promo_open — lets the analyst
+ * attribute clicks + impressions to a specific rotation entry without
+ * carrying prompt/URL/PII data.
+ */
+ messageId?: string;
+ /** Daily bucket ("2026-07-10") — full timestamps are never recorded. */
+ timestampBucket: string;
+}
diff --git a/v3/@claude-flow/cli/src/init/executor.ts b/v3/@claude-flow/cli/src/init/executor.ts
index 2e9e03eee2..48d236c368 100644
--- a/v3/@claude-flow/cli/src/init/executor.ts
+++ b/v3/@claude-flow/cli/src/init/executor.ts
@@ -402,7 +402,11 @@ function mergeSettingsForUpgrade(existing: Record<string, unknown>): Record<stri
// load the ONNX model on every fire (~1s); Claude Code times out and hides
// the status bar (#2450). The migration replaces the whole command with
// NEW_STATUSLINE_CMD which invokes the local helper directly via `node -e`.
- const BROKEN_STATUSLINE_RE = /(?:npx\s+(?:--?\S+\s+)*)?@?claude-flow(?:\/cli)?(?:@\S+)?\s+hooks\s+statusline/;
+ // Flag-list repetition bounded at 10 (real invocations never carry more) —
+ // an unbounded `*` here is exponential-backtracking-prone (CodeQL
+ // js/redos): a crafted settings.json command string with dozens of
+ // dash-token repetitions can hang this check for minutes.
+ const BROKEN_STATUSLINE_RE = /(?:npx\s+(?:--?\S+\s+){0,10})?@?claude-flow(?:\/cli)?(?:@\S+)?\s+hooks\s+statusline/;
const existingStatusLine = existing.statusLine as Record<string, unknown> | undefined;
if (existingStatusLine) {
const existingCmd = typeof existingStatusLine.command === 'string' ? existingStatusLine.command : '';
@@ -423,7 +427,8 @@ function mergeSettingsForUpgrade(existing: Record<string, unknown>): Record<stri
// We walk each hook event's `hooks[]` and swap any command matching the
// broken pattern for the local-helper form. Idempotent: re-running this
// migration on already-correct settings is a no-op.
- const BROKEN_HOOK_RE = /npx\s+(?:--?\S+\s+)*@?claude-flow\/cli@latest\s+hooks\s+(\S+)/;
+ // Bounded for the same reason as BROKEN_STATUSLINE_RE above (CodeQL js/redos).
+ const BROKEN_HOOK_RE = /npx\s+(?:--?\S+\s+){0,10}@?claude-flow\/cli@latest\s+hooks\s+(\S+)/;
const localHookCmd = (sub: string): string => {
// POSIX form mirrors settings-generator.ts::hookCmd() exactly.
// Windows users hit a separate code path (cmd /c …) — Claude Code on
@@ -520,7 +525,8 @@ export async function executeUpgrade(targetDir: string, upgradeSettings = false)
// 0. ALWAYS update critical helpers (force overwrite)
const sourceHelpersForUpgrade = findSourceHelpersDir();
if (sourceHelpersForUpgrade) {
- const criticalHelpers = ['auto-memory-hook.mjs', 'hook-handler.cjs', 'intelligence.cjs'];
+ // Keep in sync with helper-refresh.ts:CRITICAL_HELPERS.
+ const criticalHelpers = ['auto-memory-hook.mjs', 'hook-handler.cjs', 'intelligence.cjs', 'statusline.cjs'];
for (const helperName of criticalHelpers) {
const targetPath = path.join(targetDir, '.claude', 'helpers', helperName);
const sourcePath = path.join(sourceHelpersForUpgrade, helperName);
diff --git a/v3/@claude-flow/cli/src/init/helper-refresh.ts b/v3/@claude-flow/cli/src/init/helper-refresh.ts
index abe4aab67b..3790700bd5 100644
--- a/v3/@claude-flow/cli/src/init/helper-refresh.ts
+++ b/v3/@claude-flow/cli/src/init/helper-refresh.ts
@@ -17,15 +17,57 @@ import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';
import { createRequire } from 'module';
+import * as semver from 'semver';
import {
verifyHelpersManifest, sha256Hex, HELPERS_MANIFEST_FILE, type HelpersManifest,
} from './helper-signing.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
+/**
+ * Walk up from `startDir` to the nearest ancestor whose `package.json` names
+ * `@claude-flow/cli` — depth-independent, unlike a hardcoded `'..','..',
+ * '..'`. That fixed count assumed this module always runs compiled, three
+ * levels under the package root (`dist/src/init/helper-refresh.js`); it
+ * silently breaks whenever the module runs from a different depth — e.g.
+ * loaded straight from `src/init/helper-refresh.ts` (one level shallower:
+ * ts-node, tsx, or a test runner that transforms TS in place rather than
+ * requiring a prior `tsc` build). When that happened here, BOTH
+ * `getInstalledCliVersion()` silently fell back to the placeholder `'0.0.0'`
+ * AND `findPackageHelpersDir()` silently failed to resolve the real package
+ * helpers dir — with no error surfaced, just wrong values propagating into
+ * version-comparison and refresh-source-selection logic. Real ceiling on the
+ * walk (`maxUp`) so a package.json-less filesystem can't loop forever.
+ */
+function findPackageRoot(startDir: string, maxUp = 6): string | null {
+ let dir = startDir;
+ for (let i = 0; i < maxUp; i++) {
+ try {
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf-8'));
+ if (pkg && pkg.name === '@claude-flow/cli') return dir;
+ } catch { /* no package.json here, or unreadable — keep climbing */ }
+ const parent = path.dirname(dir);
+ if (parent === dir) break; // reached filesystem root
+ dir = parent;
+ }
+ return null;
+}
+
export const HELPERS_STAMP_FILE = '.helpers-version';
-/** ruflo-owned helpers that carry hook logic and must track the package version. */
-export const CRITICAL_HELPERS = ['auto-memory-hook.mjs', 'hook-handler.cjs', 'intelligence.cjs'];
+/**
+ * ruflo-owned helpers that carry hook logic (or the render surface for the
+ * funnel disclosure row) and must track the package version. Adding to this
+ * list REQUIRES re-signing `helpers.manifest.json` at publish time — the
+ * integrity gate below refuses any file it doesn't have a signed hash for.
+ */
+export const CRITICAL_HELPERS = [
+ 'auto-memory-hook.mjs',
+ 'hook-handler.cjs',
+ 'intelligence.cjs',
+ // statusline.cjs is here so the funnel disclosure row (ADR-301) reaches
+ // existing installs on the next `ruflo` command, not only fresh `ruflo init`.
+ 'statusline.cjs',
+];
/** Installed @claude-flow/cli version — the value the helpers are stamped with. */
export function getInstalledCliVersion(): string {
@@ -34,9 +76,10 @@ export function getInstalledCliVersion(): string {
const pkg = JSON.parse(fs.readFileSync(esmRequire.resolve('@claude-flow/cli/package.json'), 'utf-8'));
return String(pkg.version || '0.0.0');
} catch {
- // dist/src/init → package root
+ const root = findPackageRoot(__dirname);
+ if (!root) return '0.0.0';
try {
- const pkg = JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', '..', '..', 'package.json'), 'utf-8'));
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf-8'));
return String(pkg.version || '0.0.0');
} catch { return '0.0.0'; }
}
@@ -50,7 +93,8 @@ function findPackageHelpersDir(): string | null {
const pkgRoot = path.dirname(esmRequire.resolve('@claude-flow/cli/package.json'));
candidates.push(path.join(pkgRoot, '.claude', 'helpers'));
} catch { /* not resolvable */ }
- candidates.push(path.resolve(__dirname, '..', '..', '..', '.claude', 'helpers'));
+ const root = findPackageRoot(__dirname);
+ if (root) candidates.push(path.join(root, '.claude', 'helpers'));
for (const c of candidates) {
if (fs.existsSync(path.join(c, 'hook-handler.cjs'))) return c;
}
@@ -71,13 +115,20 @@ function findPackageHelpersDir(): string | null {
async function writeCriticalHelpers(
helpersDir: string,
version: string,
+ opts: { sourceDirOverride?: string; pubkeyPemOverride?: string } = {},
): Promise<{ wrote: boolean; blocked?: string }> {
- const source = findPackageHelpersDir();
+ const source = opts.sourceDirOverride ?? findPackageHelpersDir();
if (source) {
- // 1. Verify the signed manifest against the baked public key.
+ // 1. Verify the signed manifest against the baked public key (or, in
+ // tests, an injected throwaway key — see autoRefreshHelpersIfStale's
+ // opts.pubkeyPemOverride doc comment for why that injection point
+ // exists at all).
let trusted: HelpersManifest | null = null;
try {
- trusted = verifyHelpersManifest(fs.readFileSync(path.join(source, HELPERS_MANIFEST_FILE), 'utf-8'));
+ trusted = verifyHelpersManifest(
+ fs.readFileSync(path.join(source, HELPERS_MANIFEST_FILE), 'utf-8'),
+ opts.pubkeyPemOverride,
+ );
} catch { trusted = null; }
if (!trusted) return { wrote: false, blocked: 'signed helpers manifest missing or signature invalid' };
@@ -111,10 +162,19 @@ async function writeCriticalHelpers(
// Fallback: source unresolvable (broken npx paths) — regenerate from the CLI's
// OWN compiled generators (the trust root; no external file to verify).
const gen = await import('./helpers-generator.js');
+ const statusGen = await import('./statusline-generator.js');
const files: Record<string, string> = {
'hook-handler.cjs': gen.generateHookHandler(),
'intelligence.cjs': gen.generateIntelligenceStub(),
'auto-memory-hook.mjs': gen.generateAutoMemoryHook(),
+ // Fallback needs the same generator inputs `ruflo init` uses. We match the
+ // hardcoded default (maxAgents 15) because the fallback fires when the
+ // installed package is unresolvable — no way to read the user's project
+ // config from here. Fresh `ruflo init` still generates a per-project value.
+ 'statusline.cjs': statusGen.generateStatuslineScript({
+ statusline: { enabled: true, style: 'compact' },
+ runtime: { maxAgents: 15 },
+ } as any),
};
let wrote = false;
for (const [name, content] of Object.entries(files)) {
@@ -135,18 +195,49 @@ async function writeCriticalHelpers(
* stamp read + string compare (sub-ms); the copy runs at most once per version
* bump. Best-effort, never throws. No-op outside a ruflo project (requires an
* existing hook-handler.cjs — never creates files in an unrelated directory).
+ *
+ * FORWARD-ONLY (never downgrades): refreshing on any mere INEQUALITY, rather
+ * than only when the installed version is semver-NEWER, is a real corruption
+ * vector — confirmed live: a stray/older installed binary (a stale `npx`
+ * cache, a marketplace install lagging behind an unpublished dev-tree fix)
+ * running `daemon start` (or any command) against THIS project directory
+ * would see its own older version != the project's newer stamp and silently
+ * overwrite hand-fixed `hook-handler.cjs`/`intelligence.cjs` with its own
+ * older, already-superseded bundled copies. Comparing with `semver.gt`
+ * instead of `!==` makes that impossible: an older or equal installed
+ * version is always a no-op, regardless of how it got invoked.
+ *
+ * `opts` exists for tests ONLY (mirrors daemon-autostart.ts's injectable
+ * `SpawnDaemonFn` pattern): the real signed-copy path is otherwise coupled to
+ * THIS repo's actual current `.claude/helpers` + its real Ed25519 signature —
+ * fine for production (that coupling to the real source IS the point), but
+ * it means a test exercising that path for real would only pass when this
+ * repo's manifest happens to be currently re-signed, which is a separately-
+ * gated, occasionally-stale publish-time step. `sourceDirOverride` +
+ * `pubkeyPemOverride` let a test build its own tiny, throwaway-keypair-
+ * signed fixture and get real, deterministic coverage of the verify → hash →
+ * copy logic without depending on that.
*/
export async function autoRefreshHelpersIfStale(
cwd: string,
+ opts: { sourceDirOverride?: string; pubkeyPemOverride?: string; versionOverride?: string } = {},
): Promise<{ refreshed: boolean; from?: string; to?: string; blocked?: string }> {
try {
const helpersDir = path.join(cwd, '.claude', 'helpers');
if (!fs.existsSync(path.join(helpersDir, 'hook-handler.cjs'))) return { refreshed: false };
- const version = getInstalledCliVersion();
+ const version = opts.versionOverride ?? getInstalledCliVersion();
let stamped = '';
try { stamped = fs.readFileSync(path.join(helpersDir, HELPERS_STAMP_FILE), 'utf-8').trim(); } catch { /* pre-feature: unstamped */ }
if (stamped === version) return { refreshed: false }; // up to date — fast path
- const res = await writeCriticalHelpers(helpersDir, version);
+ if (stamped && semver.valid(stamped) && semver.valid(version) && semver.gte(stamped, version)) {
+ // Stamped version is already >= what this binary reports — refreshing
+ // would silently DOWNGRADE the project's helpers. Skip, untouched.
+ return { refreshed: false };
+ }
+ const res = await writeCriticalHelpers(helpersDir, version, {
+ sourceDirOverride: opts.sourceDirOverride,
+ pubkeyPemOverride: opts.pubkeyPemOverride,
+ });
// A blocked refresh is a SECURITY signal (tampered source/manifest) — surface
// it, don't advance the stamp, and leave the project's existing helpers intact.
if (res.blocked) return { refreshed: false, blocked: res.blocked };
diff --git a/v3/@claude-flow/cli/src/init/helpers-generator.ts b/v3/@claude-flow/cli/src/init/helpers-generator.ts
index 4f46ec5520..bb51ef54c0 100644
--- a/v3/@claude-flow/cli/src/init/helpers-generator.ts
+++ b/v3/@claude-flow/cli/src/init/helpers-generator.ts
@@ -456,6 +456,7 @@ export function generateHookHandler(): string {
'',
"const path = require('path');",
"const fs = require('fs');",
+ "const os = require('os');",
'',
'const helpersDir = __dirname;',
'',
@@ -545,6 +546,57 @@ export function generateHookHandler(): string {
' } else {',
" console.log('[INFO] Router not available, using default routing');",
' }',
+ '',
+ ' // Rate-limit -> sponsored-capacity nudge (ADR-312/313). Fires here,',
+ ' // client-side, BEFORE the API call this prompt would make - so it',
+ ' // still reaches the transcript even if that call then fails from the',
+ ' // rate limit. Cheap local file reads only; never a network call or a',
+ ' // child process, so it cannot add latency to prompt submission.',
+ ' try {',
+ " var rlFunnelEnv = process.env.RUFLO_FUNNEL;",
+ ' var rlDisabledByEnv = rlFunnelEnv !== undefined && /^(0|false|off|no)$/i.test(String(rlFunnelEnv).trim());',
+ " var rlCiVars = ['CI', 'GITHUB_ACTIONS', 'GITLAB_CI', 'CIRCLECI', 'TRAVIS', 'BUILDKITE', 'JENKINS_URL', 'TEAMCITY_VERSION', 'TF_BUILD'];",
+ ' var rlIsCi = rlCiVars.some(function (v) {',
+ ' var val = process.env[v];',
+ " return val !== undefined && val !== '' && val !== '0' && String(val).toLowerCase() !== 'false';",
+ ' });',
+ " var rlHome = path.join(os.homedir(), '.ruflo');",
+ ' var rlUserDisabled = false;',
+ ' try {',
+ " var rlUserCfg = JSON.parse(fs.readFileSync(path.join(rlHome, 'funnel.json'), 'utf8'));",
+ ' rlUserDisabled = !!(rlUserCfg && rlUserCfg.enabled === false);',
+ ' } catch (e) { /* absent/malformed = not disabled */ }',
+ ' var rlProjectDisabled = false;',
+ ' try {',
+ " var rlProjCfg = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'claude-flow.config.json'), 'utf8'));",
+ ' rlProjectDisabled = !!(rlProjCfg && rlProjCfg.funnel && rlProjCfg.funnel.enabled === false);',
+ ' } catch (e) { /* absent/malformed = not disabled */ }',
+ '',
+ ' if (!rlDisabledByEnv && !rlIsCi && !rlUserDisabled && !rlProjectDisabled) {',
+ ' var rlStatus = null;',
+ " try { rlStatus = JSON.parse(fs.readFileSync(path.join(rlHome, 'rate-limit-status.json'), 'utf8')); } catch (e) { /* not flagged */ }",
+ ' var rlIsLimited = false;',
+ ' if (rlStatus && rlStatus.limited) {',
+ ' if (rlStatus.since) {',
+ ' var rlSinceMs = Date.parse(rlStatus.since);',
+ ' rlIsLimited = isNaN(rlSinceMs) ? true : (Date.now() - rlSinceMs) < 6 * 60 * 60 * 1000;',
+ ' } else {',
+ ' rlIsLimited = true;',
+ ' }',
+ ' }',
+ ' if (rlIsLimited) {',
+ ' var rlConsented = false;',
+ ' try {',
+ " var rlConsentFile = JSON.parse(fs.readFileSync(path.join(rlHome, 'consent.json'), 'utf8'));",
+ " var rlReceipt = rlConsentFile && rlConsentFile['sponsored-downtime'];",
+ ' rlConsented = !!(rlReceipt && rlReceipt.granted === true && rlReceipt.at !== null && rlReceipt.policyVersion === 1);',
+ ' } catch (e) { /* not consented */ }',
+ ' if (!rlConsented) {',
+ " console.log('[COGNITUM] Hit your Claude usage limit? Free sponsored capacity is available at cognitum.one/meta-llm -- run: ruflo proxy sponsor-enable --yes');",
+ ' }',
+ ' }',
+ ' }',
+ ' } catch (e) { /* nudge must never break the hook */ }',
' },',
'',
" 'pre-bash': () => {",
diff --git a/v3/@claude-flow/cli/src/init/statusline-generator.ts b/v3/@claude-flow/cli/src/init/statusline-generator.ts
index 7f92070334..de3ee09389 100644
--- a/v3/@claude-flow/cli/src/init/statusline-generator.ts
+++ b/v3/@claude-flow/cli/src/init/statusline-generator.ts
@@ -76,6 +76,28 @@ const CWD = process.cwd();
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;
+// 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
@@ -83,18 +105,30 @@ const CACHE_TTL_MS = 60000;
// multiple concurrent Claude Code sessions this storms the host (reporter
// saw load average 40-65 on a 12-core box).
//
-// Returns the absolute path to bin/cli.js or null. Mirrors getPkgVersion()'s
-// path probing (project, monorepo, plugin marketplace, global node_modules
-// including custom-prefix layouts like ~/.npm-global).
-function resolveCliBin() {
+// 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();
- const candidates = [
+ 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')];
@@ -108,27 +142,54 @@ function resolveCliBin() {
);
}
} catch { /* ignore */ }
- for (const p of candidates) {
- if (fs.existsSync(p)) return p;
- }
} catch { /* ignore */ }
- return null;
+ return candidates.filter((p) => { try { return fs.existsSync(p); } 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 && (Date.now() - raw._ts) < CACHE_TTL_MS) {
- return raw.data;
+ 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 null;
+ 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;
}
/**
@@ -139,37 +200,65 @@ function writeCache(data) {
* (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 cached = readCache();
- if (cached) return cached;
+ 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.
+ const cmds = resolveCliBinCandidates()
+ .map((bin) => '"' + process.execPath + '" "' + bin + '" hooks statusline --json 2>/dev/null')
+ .concat(['npx --prefer-offline @claude-flow/cli hooks statusline --json 2>/dev/null']);
+ 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 */ }
+ }
- try {
- // #2337: prefer an already-installed CLI bin via direct \`node\` invocation
- // — no npx, no registry round-trip, no @latest re-resolve per render.
- // Fall back to \`npx --prefer-offline @claude-flow/cli\` (no @latest) only
- // when nothing is installed locally, so a cold environment still works.
- const cliBin = resolveCliBin();
- const cmd = cliBin
- ? '"' + process.execPath + '" "' + cliBin + '" hooks statusline --json 2>/dev/null'
- : 'npx --prefer-offline @claude-flow/cli hooks statusline --json 2>/dev/null';
- 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);
- writeCache(data);
- return data;
- } catch { /* CLI unavailable or timed out */ }
-
- // Fallback: use local file probes only (will be less accurate, but non-zero
- // when CLI is available and accurate when it's not).
- return buildLocalFallback();
+ // 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
@@ -569,7 +658,11 @@ function generateStatusline() {
const modelName = getModelFromStdin() || (d.user && d.user.modelName) || 'Claude Code';
const ctxInfo = getContextFromStdin();
const costInfo = getCostFromStdin();
- const pkgVersion = getPkgVersion();
+ // 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 || {};
@@ -605,8 +698,14 @@ function generateStatusline() {
const lines = [];
- // Header
- let header = c.bold + c.brightPurple + '▊ RuFlo V' + pkgVersion + ' ' + c.reset;
+ // 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;
@@ -633,81 +732,148 @@ function generateStatusline() {
}
lines.push(header);
- // Separator
- lines.push(c.dim + '─'.repeat(53) + c.reset);
-
- // Line 1: DDD Domains
- const domainsColor = domainsCompleted >= 3 ? c.brightGreen : domainsCompleted > 0 ? c.yellow : c.red;
- let perfIndicator;
- if (hasHnsw && vectorCount > 0) {
- const speedup = vectorCount > 10000 ? '12500x' : vectorCount > 1000 ? '150x' : '10x';
- perfIndicator = c.brightGreen + '⚡ HNSW ' + speedup + c.reset;
- } else if (patternsLearned > 0) {
- const pk = patternsLearned >= 1000 ? (patternsLearned / 1000).toFixed(1) + 'k' : String(patternsLearned);
- perfIndicator = c.brightYellow + '📚 ' + pk + ' patterns' + c.reset;
- } else {
- perfIndicator = c.dim + '⚡ target: 150x-12500x' + c.reset;
- }
- lines.push(
- c.brightCyan + '🏗️ DDD Domains' + c.reset + ' ' + progressBar(domainsCompleted, totalDomains) + ' ' +
- domainsColor + domainsCompleted + c.reset + '/' + c.brightWhite + totalDomains + c.reset + ' ' + perfIndicator
- );
-
- // Line 2: Swarm + Hooks + CVE + Memory + Intelligence
- const swarmInd = coordinationActive ? c.brightGreen + '◉' + c.reset : c.dim + '○' + c.reset;
- const agentsColor = activeAgents > 0 ? c.brightGreen : c.red;
- const secIcon = secStatus === 'CLEAN' ? '🟢' : (secStatus === 'IN_PROGRESS' || secStatus === 'STALE') ? '🟡' : (secStatus === 'NONE' ? '⚪' : '🔴');
- const secColor = secStatus === 'CLEAN' ? c.brightGreen : (secStatus === 'IN_PROGRESS' || secStatus === 'STALE') ? c.brightYellow : (secStatus === 'NONE' ? c.dim : c.brightRed);
+ // ─── 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);
+ }
+ }
+ 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';
+}
- lines.push(
- c.brightYellow + '🤖 Swarm' + c.reset + ' ' + swarmInd + ' [' + agentsColor + String(activeAgents).padStart(2) + c.reset + '/' + c.brightWhite + maxAgents + c.reset + '] ' +
- c.brightPurple + '👥 ' + subAgents + c.reset + ' ' +
- c.brightBlue + '🪝 ' + hooksColor + hooksEnabled + c.reset + '/' + c.brightWhite + hooksTotal + c.reset + ' ' +
- secIcon + ' ' + secColor + 'CVE ' + cvesFixed + c.reset + '/' + c.brightWhite + totalCves + c.reset + ' ' +
- c.brightCyan + '💾 ' + memoryMB + 'MB' + c.reset + ' ' +
- intellColor + '🧠 ' + String(intelligencePct).padStart(3) + '%' + c.reset
- );
-
- // Line 3: Architecture
- const dddColor = dddProgress >= 50 ? c.brightGreen : dddProgress > 0 ? c.yellow : c.red;
- const adrColor = adrCount > 0 ? (adrImpl === adrCount ? c.brightGreen : c.yellow) : c.dim;
- const adrDisplay = adrColor + '●' + adrImpl + '/' + adrCount + c.reset;
-
- lines.push(
- c.brightPurple + '🔧 Architecture' + c.reset + ' ' +
- c.cyan + 'ADRs' + c.reset + ' ' + adrDisplay + ' ' + c.dim + '│' + c.reset + ' ' +
- c.cyan + 'DDD' + c.reset + ' ' + dddColor + '●' + String(dddProgress).padStart(3) + '%' + c.reset + ' ' + c.dim + '│' + c.reset + ' ' +
- c.cyan + 'Security' + c.reset + ' ' + secColor + '●' + secStatus + c.reset
- );
-
- // Line 4: AgentDB, Tests, Integration
- const hnswInd = hasHnsw ? c.brightGreen + '⚡' + c.reset : '';
- const sizeDisp = dbSizeKB >= 1024 ? (dbSizeKB / 1024).toFixed(1) + 'MB' : dbSizeKB + 'KB';
- const vectorColor = vectorCount > 0 ? c.brightGreen : c.dim;
- const testColor = testFiles > 0 ? c.brightGreen : c.dim;
-
- // MCP / DB integration from data
- const integration = d.integration || {};
- const mcpServers = (integration.mcpServers) || {};
- let integStr = '';
- if (mcpServers.total > 0) {
- const mcpCol = mcpServers.enabled === mcpServers.total ? c.brightGreen : mcpServers.enabled > 0 ? c.brightYellow : c.red;
- integStr += c.cyan + 'MCP' + c.reset + ' ' + mcpCol + '●' + mcpServers.enabled + '/' + mcpServers.total + c.reset;
+// ─── 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 (integration.hasDatabase) integStr += (integStr ? ' ' : '') + c.brightGreen + '◆' + c.reset + 'DB';
- if (!integStr) integStr = c.dim + '● none' + c.reset;
-
- lines.push(
- c.brightCyan + '📊 AgentDB' + c.reset + ' ' +
- c.cyan + 'Vectors' + c.reset + ' ' + vectorColor + '●' + vectorCount + hnswInd + c.reset + ' ' + c.dim + '│' + c.reset + ' ' +
- c.cyan + 'Size' + c.reset + ' ' + c.brightWhite + sizeDisp + c.reset + ' ' + c.dim + '│' + c.reset + ' ' +
- c.cyan + 'Tests' + c.reset + ' ' + testColor + '●' + testFiles + c.reset + ' ' + c.dim + '(~' + testCases + ' cases)' + c.reset + ' ' + c.dim + '│' + c.reset + ' ' +
- integStr
- );
-
- return lines.join('\\n');
}
// JSON output — delegates to CLI for accuracy; caller can use --json flag
diff --git a/v3/@claude-flow/cli/src/services/daemon-autostart.ts b/v3/@claude-flow/cli/src/services/daemon-autostart.ts
index 2c9b0cd3d0..03a85a217c 100644
--- a/v3/@claude-flow/cli/src/services/daemon-autostart.ts
+++ b/v3/@claude-flow/cli/src/services/daemon-autostart.ts
@@ -10,7 +10,17 @@
* own lock + checkExistingDaemon() — so a race spawns at most one survivor,
* - bounded lifetime: the daemon self-terminates on TTL/idle (12h default,
* RUFLO_DAEMON_TTL_SECS) — auto-start never means "runs forever",
- * - opt-out: RUFLO_DAEMON_AUTOSTART=0|false|no disables it entirely,
+ * - opt-out: RUFLO_DAEMON_AUTOSTART=0|false|no disables it entirely, OR a
+ * project-local `daemon.autostart: false` in claude-flow.config.json —
+ * the file-based opt-out exists because the env var only reaches a
+ * process that inherited it. A non-interactive shell (cron, CI, many
+ * tool-invoked shells — bash skips ~/.bashrc entirely for these; see
+ * its own `case $- in *i*) ;; *) return;; esac` guard) never re-sources
+ * a shell rc file per invocation, so `export RUFLO_DAEMON_AUTOSTART=0`
+ * in one such shell does NOT persist to the next one. A project config
+ * field has no such gap — it's read fresh from disk every time,
+ * independent of which shell (or whether any shell at all) launched
+ * the command,
* - cheap: a pidfile read + a signal-0 liveness check on the fast path,
* - best-effort + silent: never blocks or fails a command.
*
@@ -37,8 +47,20 @@ export function isDaemonAlive(projectRoot: string): boolean {
}
}
-function autostartDisabled(): boolean {
- return /^(0|false|no|off)$/i.test(process.env.RUFLO_DAEMON_AUTOSTART ?? '');
+/** Project-local opt-out: `{ "daemon": { "autostart": false } }` in claude-flow.config.json. */
+function autostartDisabledByProjectConfig(projectRoot: string): boolean {
+ try {
+ const raw = fs.readFileSync(path.join(projectRoot, 'claude-flow.config.json'), 'utf-8');
+ const cfg = JSON.parse(raw);
+ return cfg?.daemon?.autostart === false;
+ } catch {
+ return false; // absent/malformed config = not disabled
+ }
+}
+
+function autostartDisabled(projectRoot: string): boolean {
+ if (/^(0|false|no|off)$/i.test(process.env.RUFLO_DAEMON_AUTOSTART ?? '')) return true;
+ return autostartDisabledByProjectConfig(projectRoot);
}
export interface EnsureResult { started: boolean; reason?: string }
@@ -66,7 +88,7 @@ export function ensureDaemonRunning(
opts: { spawnFn?: SpawnDaemonFn; isAlive?: (root: string) => boolean } = {},
): EnsureResult {
try {
- if (autostartDisabled()) return { started: false, reason: 'disabled (RUFLO_DAEMON_AUTOSTART=0)' };
+ if (autostartDisabled(projectRoot)) return { started: false, reason: 'disabled (RUFLO_DAEMON_AUTOSTART=0 or project config)' };
// Only in an initialized project (avoid scaffolding a daemon in a random dir).
if (!fs.existsSync(path.join(projectRoot, '.claude-flow')) && !fs.existsSync(path.join(projectRoot, '.claude'))) {
return { started: false, reason: 'not a ruflo project' };
diff --git a/v3/@claude-flow/cli/src/services/fable-harness.ts b/v3/@claude-flow/cli/src/services/fable-harness.ts
index 6bd2c33e64..6aa8dfd095 100644
--- a/v3/@claude-flow/cli/src/services/fable-harness.ts
+++ b/v3/@claude-flow/cli/src/services/fable-harness.ts
@@ -102,6 +102,30 @@ export interface ReflectResult {
mutationHint: string;
}
+/**
+ * ADR-316 — a compact, STRUCTURAL-ONLY snapshot of the current coding
+ * session for the statusline's co-pilot advisor tip. Every field here
+ * mirrors funnel/insights.ts's LocalInsightContext — no raw prompt/command/
+ * file content, ever (same bar as ADR-309, applied to a different, opt-in
+ * data flow). The model sees only what's already surfaced structurally
+ * elsewhere in the statusline.
+ */
+export interface CoPilotSnapshot {
+ security?: { status: string; cvesFixed: number; totalCves: number };
+ swarm?: { activeAgents: number; maxAgents: number; coordinationActive: boolean };
+ gitUncommittedCount?: number;
+ contextPctUsed?: number;
+}
+
+/** A single proactive suggestion for the insight ticker. */
+export interface CoPilotTip {
+ /** Short enough for a single statusline row (caller truncates further). */
+ headline: string;
+ /** One actionable sentence of extra detail. */
+ detail: string;
+ confidence: number;
+}
+
/** Result of a raw claude spawn. */
export interface ClaudeSpawnResult {
stdout: string;
@@ -159,6 +183,18 @@ const REFLECT_SYSTEM_PROMPT = [
'[{"id":"...","failureClass":"<short label>","diagnosis":"<one sentence>","mutationHint":"<actionable>"}]',
].join('\n');
+const ADVISOR_SYSTEM_PROMPT = [
+ "You are RuFlo's co-pilot advisor: ONE short, proactive, actionable tip for",
+ 'a developer, based on a single JSON object describing STRUCTURAL signals',
+ 'from their current coding session (security scan status, swarm/agent',
+ 'state, count of uncommitted files, context-window usage). There is no',
+ 'prompt, command, or file content in the input — never assume or invent any.',
+ 'If nothing in the snapshot genuinely warrants a tip, say so by returning',
+ 'an empty array. Never pad with generic advice not grounded in the snapshot.',
+ 'Reply with ONLY a JSON array containing zero or one object, no prose:',
+ '[] or [{"headline":"<=60 chars","detail":"<one actionable sentence>","confidence":0.0-1.0}]',
+].join('\n');
+
// ── Default spawner (real CLI) ───────────────────────────────────────────────
/**
@@ -290,6 +326,22 @@ export class FableHarness {
return out;
}
+ /**
+ * ADR-316 — one proactive co-pilot tip from a structural session snapshot
+ * (no raw prompt/command/file content). A single-item "batch" — same
+ * budget/cwd/parsing discipline as judgeBatch/reflectFailures, just with
+ * exactly one call instead of a loop. Returns null when disabled, over
+ * budget, or the model found nothing worth surfacing (an empty verdict
+ * array is a valid, non-error answer here, not a parse failure).
+ */
+ async adviseCoPilotTip(snapshot: CoPilotSnapshot): Promise<CoPilotTip | null> {
+ if (!this.isEnabled()) return null;
+ if (this.spentUsd >= this.maxBudgetUsd) return null;
+ const parsed = await this.runBatch(ADVISOR_SYSTEM_PROMPT, [snapshot]);
+ if (parsed.length === 0) return null;
+ return normalizeCoPilotTip(parsed[0]);
+ }
+
/** Build the argv for a `claude -p` call. Exposed shape for testability. */
buildArgv(systemPrompt: string): string[] {
const perCallCap = Math.max(0, this.maxBudgetUsd - this.spentUsd);
@@ -395,6 +447,17 @@ function normalizeReflect(raw: unknown): ReflectResult | null {
};
}
+function normalizeCoPilotTip(raw: unknown): CoPilotTip | null {
+ if (!raw || typeof raw !== 'object') return null;
+ const o = raw as Record<string, unknown>;
+ if (typeof o.headline !== 'string' || !o.headline.trim()) return null;
+ return {
+ headline: o.headline.slice(0, 80),
+ detail: typeof o.detail === 'string' ? o.detail.slice(0, 200) : '',
+ confidence: clamp01(typeof o.confidence === 'number' ? o.confidence : Number(o.confidence)),
+ };
+}
+
function tryParseJson(s: string): unknown {
try { return JSON.parse(s); } catch { return undefined; }
}
diff --git a/v3/docs/adr/ADR-301-promotional-status-surface.md b/v3/docs/adr/ADR-301-promotional-status-surface.md
new file mode 100644
index 0000000000..a9c801307a
--- /dev/null
+++ b/v3/docs/adr/ADR-301-promotional-status-surface.md
@@ -0,0 +1,184 @@
+# ADR-301 — Promotional Status Surface for CLI Runtime
+
+- **Status:** Proposed
+- **Date:** 2026-07-10
+- **Deciders:** ruflo core
+- **Related:** [ADR-302](ADR-302-post-init-capability-enrollment.md) (post-init enrollment), [ADR-303](ADR-303-credit-exhaustion-experience.md) (credit exhaustion), [ADR-304](ADR-304-local-meta-llm-proxy.md) (local Meta LLM proxy), [ADR-305](ADR-305-customer-lifecycle-funnel.md) (funnel overview), [ADR-174](ADR-174-memory-distillation-self-optimization.md) / [ADR-177](ADR-177-signed-config-propagation-to-installs.md) (signed helper auto-refresh channel used to reach existing installs), [ADR-309](ADR-309-funnel-governance-privacy-ecosystem.md) (content approval, privacy), [ADR-310](ADR-310-funnel-rollout-measurement-emergency-controls.md) (rollout, release gates)
+
+## Context
+
+RuFlo has a large active install base that interacts with the CLI many times a day. The statusline (`.claude/helpers/statusline.cjs`, generated by `v3/@claude-flow/cli/src/init/statusline-generator.ts`) currently communicates operational state only — swarm status, hooks, memory, architecture progress. Its bottom row is a persistent, high-frequency communication channel that carries no discovery value.
+
+Users often remain unaware of adjacent capabilities, including:
+
+- Meta LLM routing
+- Cloud acceleration
+- Hosted memory
+- Premium agents
+- Enterprise features
+- Cognitum One services (https://cognitum.one)
+
+Rather than introducing disruptive prompts, the CLI can reserve a small non-critical area for rotating promotional and educational messages.
+
+## Decision
+
+Reserve the bottom status row for a rotating promotional surface.
+
+### Characteristics
+
+- Never replaces operational status — only uses the currently unused bottom row.
+- Rotates every 15–30 seconds.
+- Pauses during interactive prompts.
+- Disabled in non-TTY environments.
+- Disabled in CI (`CI`, `GITHUB_ACTIONS`, and equivalents).
+- Respects `NO_COLOR` and accessibility modes: **marquee and all animation are disabled for screen readers and reduced-motion terminals** — messages render as static plain text or not at all.
+- Fully disableable, with strict precedence (see Control Precedence below): `RUFLO_FUNNEL=0` env var, enterprise managed policy, and `funnel.enabled: false` in config all suppress the surface.
+
+### Message classes
+
+- New feature announcements
+- Performance tips
+- Package updates
+- Cognitum One capabilities
+- Enterprise features
+- Community events
+- Documentation pointers
+- Upgrade suggestions
+
+Example:
+
+```
+✨ Unlock Meta LLM routing → cognitum.one
+⚡ Run Claude + GPT + Gemini behind one local endpoint
+🚀 Free local proxy available. Learn more.
+```
+
+### Renderer capabilities
+
+- Marquee scrolling
+- Fading rotation
+- Alternating messages
+- Configurable timing
+
+### Rollout: new init AND existing installations
+
+- **New installs:** `statusline-generator.ts` emits the promo row by default (subject to the gates above).
+- **Existing installs:** the statusline is a generated helper covered by the ADR-174/ADR-177 signed helper auto-refresh channel — `autoRefreshHelpersIfStale()` re-copies signed helpers on version-stamp mismatch on the next CLI command. Shipping the new statusline bumps the helpers manifest version, so previously initialized projects pick it up with zero re-init, Ed25519-verified and fail-closed. No new distribution mechanism is required.
+
+### Existing-install disclosure gate
+
+An upgraded install must never wake up to promotional content it was not told about. Before the promo row renders for the first time on an upgraded installation, a one-time disclosure is shown:
+
+```ts
+type FunnelDisclosureState =
+ | "never_seen"
+ | "disclosed_enabled"
+ | "disclosed_disabled";
+
+if (
+ isInteractiveTTY &&
+ installationWasUpgraded &&
+ disclosureState === "never_seen"
+) {
+ showDisclosure({
+ message:
+ "Ruflo now displays occasional tips and Cognitum capability notices in the status line.",
+ disable:
+ "Set RUFLO_FUNNEL=0 or funnel.enabled=false to disable.",
+ });
+ persistDisclosureReceipt();
+}
+```
+
+Invariants:
+
+- Existing installs **never display promotional content before disclosure** (release-blocking gate in ADR-310).
+- The disable instruction appears **in the first disclosure itself**, not behind a link.
+- Disclosure is shown **once per user** (user-level receipt in `~/.ruflo/`), not once per project.
+- **Declining disables all funnel surfaces** (ADR-301, 302, and 303), recorded as `disclosed_disabled`.
+- New installs satisfy disclosure through the ADR-302 enrollment screen; this gate exists for upgrades.
+
+## Content Policy
+
+Maximum length and pacing:
+
+- 80 columns maximum
+- 2 seconds minimum visibility per message
+- No animation on slow terminals
+
+Promotional frequency and content ratio (enforced by the rotation scheduler, reviewed per ADR-309):
+
+- **Educational content: at least 4 of every 5 rotations.**
+- **Promotional content: at most 1 of every 5 rotations.**
+- **The same promotion appears at most once every 30 minutes.**
+- **No urgency, countdowns, scarcity, or dark patterns** — messages state a capability and a link, nothing more.
+- Never more than one message displayed simultaneously
+- Never blocks user input
+- Never appears interleaved with command output
+
+Message content ships in-package (curated list, reviewed in PR like any code change). No runtime fetch of remote message payloads — remote content would be an injection surface into every user's terminal and would violate the no-runtime-network posture of the helper channel.
+
+## Signed Content Boundaries
+
+The helper *code* is signed (ADR-174/177), but message *copy* delivered through that channel is still remotely supplied content that lands in user terminals. The renderer therefore treats messages as untrusted data regardless of transport, enforcing all of the following before display:
+
+- **Data only.** Messages are inert JSON — never code, never template strings evaluated by the renderer, never shell-expanded. The renderer has no eval path.
+- **Schema validated.** Every message must validate against a versioned schema before entering the rotation; invalid messages are dropped, not repaired:
+
+ ```json
+ {
+ "id": "meta-llm-routing-2026-07",
+ "schemaVersion": 1,
+ "text": "✨ Unlock Meta LLM routing",
+ "url": "https://cognitum.one/routing",
+ "class": "cognitum",
+ "expiresAt": "2026-10-01T00:00:00Z"
+ }
+ ```
+
+- **Length bounded.** `text` ≤ 80 columns after grapheme-aware width measurement; over-length messages are dropped, not truncated mid-escape.
+- **URL allowlisted.** `url` must match an in-package allowlist of exact hosts (`cognitum.one`, `github.com/ruvnet/*`, official docs domains). Any other host — including lookalikes and IP literals — drops the message. The allowlist ships in code, not in the message payload.
+- **Cached with expiry.** Messages carry `expiresAt`; expired messages leave the rotation immediately. The rotation cache honors the same 60s delegation-cache discipline and never re-fetches.
+- **No terminal control sequences.** `text` is sanitized to printable characters plus emoji: all C0/C1 control bytes, ANSI/OSC/DCS escape sequences, and bidirectional override characters are stripped or the message is dropped. Styling (color, marquee) is applied exclusively by the renderer from its own fixed styles — copy can never emit its own escapes.
+
+A message that fails any check is skipped silently; the promo row falls back to the next valid message or renders nothing. Failure to validate never produces a visible error in the statusline.
+
+## Telemetry
+
+Only anonymous aggregate metrics, and only when telemetry is already enabled:
+
+- Impressions
+- Dismissals
+- Sign-up conversions (attributed via URL campaign parameter, not client identity)
+- Click/open events
+
+No prompt content or user data is collected. Telemetry-off means zero promo-related network calls.
+
+## Expected Benefits
+
+- Increased awareness of adjacent capabilities
+- Low-friction education
+- Continuous feature discovery
+- Higher Cognitum conversion
+- Zero workflow interruption
+
+## Control Precedence
+
+The promo surface honors the funnel-wide precedence chain (normative definition in ADR-305):
+
+```
+1. RUFLO_FUNNEL=0 (environment)
+2. Enterprise managed policy
+3. User config: funnel.enabled
+4. Package default
+5. Remote signed policy (only when freshness feed is enabled)
+```
+
+A lower-precedence source can never re-enable what a higher-precedence source disabled.
+
+## Guardrails / Consequences
+
+- Statusline render cost must stay within the existing cache discipline (60s delegation cache, #2337); promo rotation is purely local string selection and adds no CLI invocations.
+- CLI startup latency target (<500ms) unchanged.
+- Dismissal and opt-out state persists per user (not per project) so a user who opts out is never re-prompted across projects.
+- If the promo row ever conflicts with an operational message, the operational message wins unconditionally.
diff --git a/v3/docs/adr/ADR-302-post-init-capability-enrollment.md b/v3/docs/adr/ADR-302-post-init-capability-enrollment.md
new file mode 100644
index 0000000000..3a216ea052
--- /dev/null
+++ b/v3/docs/adr/ADR-302-post-init-capability-enrollment.md
@@ -0,0 +1,105 @@
+# ADR-302 — Post-Initialization Capability Enrollment
+
+- **Status:** Proposed
+- **Date:** 2026-07-10
+- **Deciders:** ruflo core
+- **Related:** [ADR-301](ADR-301-promotional-status-surface.md) (promo status surface), [ADR-303](ADR-303-credit-exhaustion-experience.md) (credit exhaustion), [ADR-304](ADR-304-local-meta-llm-proxy.md) (local Meta LLM proxy), [ADR-305](ADR-305-customer-lifecycle-funnel.md) (funnel overview)
+
+## Context
+
+Immediately after installation represents the highest-intent moment in the user lifecycle: the user has just chosen ruflo, is looking at the terminal, and has not yet formed workflow habits.
+
+Today, initialization (`npx ruflo init`, `v3/@claude-flow/cli/src/commands/init.ts` → `src/init/executor.ts`) ends with a success summary and no presentation of additional capabilities.
+
+## Decision
+
+Introduce an optional, one-time enrollment experience after successful initialization.
+
+### Flow
+
+```
+✓ Ruflo installed
+────────────────────────────
+Unlock additional capabilities?
+
+ ✓ Local Meta LLM Proxy
+ ✓ Multi-model routing
+ ✓ Hosted memory
+ ✓ Enterprise rate limits
+ ✓ Premium agents
+ ✓ Cloud synchronization
+
+Free account.
+
+Press Enter to continue
+or visit: https://cognitum.one
+```
+
+**If accepted**, the CLI hands off to:
+
+```
+ruflo auth login
+```
+
+or
+
+```
+ruflo proxy install
+```
+
+depending on platform (see ADR-304 for the proxy).
+
+**If skipped:**
+
+```
+You can enable later:
+ ruflo auth login
+```
+
+No repeated prompting after dismissal — the dismissal is recorded in user-level state (`~/.ruflo/enrollment.json`), not project-level, so re-running `init` in another project does not re-prompt.
+
+## Consent Domains (separate, never bundled)
+
+Accepting the enrollment screen is **not** blanket authorization. The flow involves four distinct decisions, each with its own consent, its own prompt moment, and its own record:
+
+| Domain | What it authorizes | Where consent is asked |
+|--------|--------------------|------------------------|
+| `account` | Creating/signing into a Cognitum account | This screen → `ruflo auth login` |
+| `proxy-install` | Installing the local Meta LLM proxy binary/service | `ruflo proxy install` (ADR-304) |
+| `telemetry` | Anonymous aggregate funnel metrics | Existing telemetry opt-in only — enrollment never toggles it |
+| `cloud-routing` | Prompts leaving the machine via api.cognitum.one | Explicit `ruflo proxy config --cloud` step (ADR-304); default **off** |
+
+Pressing Enter on the enrollment screen authorizes exactly one thing: launching `ruflo auth login`. It does not install the proxy, does not enable telemetry, and does not enable cloud routing.
+
+### Versioned consent receipts
+
+Each domain records an independent, versioned receipt in `~/.ruflo/consent.json`:
+
+```json
+{
+ "account": { "granted": true, "policyVersion": 1, "at": "2026-07-10T18:02:11Z", "surface": "post-init" },
+ "proxy-install": { "granted": true, "policyVersion": 1, "at": "2026-07-10T18:03:40Z", "surface": "proxy-install" },
+ "telemetry": { "granted": false, "policyVersion": 1, "at": "2026-07-10T18:02:11Z", "surface": "post-init" },
+ "cloud-routing": { "granted": false, "policyVersion": 1, "at": null, "surface": null }
+}
+```
+
+- A receipt is written on both grant **and** decline (a decline is a decision, not an absence).
+- `policyVersion` bumps when the meaning of a domain changes materially; a stale version means the consent must be re-asked before the capability activates — never silently carried forward.
+- Receipts are user-level, `0600`, never committed, never transmitted.
+- `ruflo auth logout` / `ruflo proxy uninstall` revoke the corresponding receipt.
+
+## Requirements
+
+- **One-time only** — dismissal or completion is terminal; the prompt never reappears.
+- **Non-blocking** — the prompt has a default (skip) and never gates init success; init exit code is unaffected by the enrollment outcome.
+- **Skippable explicitly** — `--no-signup` flag on `init`.
+- **Skipped in automation** — non-TTY stdin/stdout skips silently.
+- **Skipped in CI** — `CI` and equivalents skip silently.
+- **No credentials handled inline** — enrollment only launches the existing `ruflo auth login` flow; the init path itself never touches tokens (input validation and secret handling remain in `@claude-flow/security` per existing boundaries).
+
+## Consequences
+
+- Init wizard (`init --wizard`) gains one final screen; non-wizard init gains one prompt with an Enter-to-skip default.
+- The enrollment screen is the top of the lifecycle funnel described in ADR-305; conversion from this screen is a North Star metric there.
+- Telemetry: acceptance/dismissal counted only as anonymous aggregates, only when telemetry is enabled (same policy as ADR-301).
diff --git a/v3/docs/adr/ADR-303-credit-exhaustion-experience.md b/v3/docs/adr/ADR-303-credit-exhaustion-experience.md
new file mode 100644
index 0000000000..e649aed54a
--- /dev/null
+++ b/v3/docs/adr/ADR-303-credit-exhaustion-experience.md
@@ -0,0 +1,108 @@
+# ADR-303 — Intelligent Credit Exhaustion Experience
+
+- **Status:** Proposed
+- **Date:** 2026-07-10
+- **Deciders:** ruflo core
+- **Related:** [ADR-301](ADR-301-promotional-status-surface.md) (promo status surface), [ADR-302](ADR-302-post-init-capability-enrollment.md) (post-init enrollment), [ADR-304](ADR-304-local-meta-llm-proxy.md) (local Meta LLM proxy), [ADR-305](ADR-305-customer-lifecycle-funnel.md) (funnel overview), [ADR-308](ADR-308-cognitum-public-api-contract.md) (`GET /v1/credits`, error taxonomy)
+
+## Context
+
+Users currently encounter failed requests after exhausting available hosted resources (daily hosted credits, provider quota, rate limits). The failure is a generic error with no recovery path — maximum frustration at exactly the moment the user most wants to keep working.
+
+This is simultaneously the funnel's highest-conversion moment: the user has a concrete, immediate problem that a Cognitum account and the local Meta LLM proxy (ADR-304) directly solve.
+
+## Decision
+
+Replace generic quota failures with contextual upgrade messaging that presents an immediate recovery path.
+
+### Unauthenticated user
+
+```
+Daily hosted credits exhausted.
+
+Continue immediately by enabling
+your free local Meta LLM Proxy.
+
+Benefits
+ ✓ Unlimited local requests
+ ✓ Automatic model routing
+ ✓ Lower latency
+ ✓ Privacy preserving
+ ✓ Cloud fallback
+
+Sign in:
+ ruflo auth login
+```
+
+### Authenticated user
+
+```
+Start local proxy?
+[Y/n]
+```
+
+If accepted, the CLI runs:
+
+```
+ruflo proxy enable
+```
+
+### Required clarity
+
+The experience must clearly distinguish between:
+
+- **Local inference** — requests served by local models (Ollama, vLLM, SGLang) with no cloud involvement
+- **Cloud inference** — requests routed through api.cognitum.one to hosted providers
+- **Premium hosted services** — paid Cognitum tiers (hosted memory, enterprise rate limits, premium agents)
+
+so that "unlimited local requests" is never conflated with unlimited cloud usage.
+
+## Credit Authority
+
+There is exactly one source of truth for credit balances: the **Cognitum account service**. The CLI and proxy query `GET /v1/credits` (ADR-308) — they never infer balances from provider errors, local counters, or heuristics. "Daily hosted credits exhausted" may only ever be asserted by the service that owns the ledger.
+
+## Error Taxonomy (deterministic, fail-closed)
+
+The recovery experience is gated on a **deterministic classifier over explicit provider codes** — never on text-matching provider messages, which will eventually misclassify outages or authentication failures as exhaustion.
+
+Each provider adapter maps its native, machine-readable error codes into a canonical taxonomy:
+
+```ts
+enum CreditErrorCode {
+ COGNITUM_CREDIT_EXHAUSTED, // Cognitum ledger says balance is spent — the ONLY funnel trigger
+ PROVIDER_QUOTA_EXHAUSTED, // upstream provider's own quota, not Cognitum credits
+ PROVIDER_RATE_LIMITED, // retryable 429
+ AUTHENTICATION_FAILED, // 401/403
+ SERVICE_UNAVAILABLE, // 5xx, timeouts, connection resets
+}
+```
+
+Mapping rules:
+
+- Adapters map **codes, never message text**. An error with no mapped code stays unclassified (`confidence: 0`) — it is never coerced into `COGNITUM_CREDIT_EXHAUSTED`.
+- The mapping table lives in one versioned module per provider adapter and mirrors the ADR-308 server-side error taxonomy 1:1.
+- `PROVIDER_QUOTA_EXHAUSTED` is deliberately distinct from `COGNITUM_CREDIT_EXHAUSTED`: a provider's own quota running out is not a Cognitum upsell moment and must not claim to be one.
+
+The gate is fail-closed — **only** `COGNITUM_CREDIT_EXHAUSTED` triggers the funnel surface:
+
+```ts
+showCreditRecovery =
+ error.code === CreditErrorCode.COGNITUM_CREDIT_EXHAUSTED &&
+ error.confidence === 1 &&
+ !error.retryable &&
+ !session.creditPromptShown;
+```
+
+`PROVIDER_QUOTA_EXHAUSTED`, `PROVIDER_RATE_LIMITED`, `AUTHENTICATION_FAILED`, `SERVICE_UNAVAILABLE`, and unclassified errors always fall through to the ordinary error path. A missed upsell opportunity is acceptable; a wrong "out of credits" claim during a provider outage is not.
+
+## Requirements
+
+- The upgrade message appears **only** when the classifier above fires — never on transient network failures, auth errors, provider outages, or unmapped errors.
+- The original error remains available (`--verbose` / exit code unchanged) — the contextual message wraps the failure, it does not mask it.
+- Non-TTY and CI environments get the plain error plus a single-line pointer (`Hint: ruflo auth login enables the free local Meta LLM proxy`), no interactive prompt.
+- Frequency-capped: at most one full contextual screen per session; subsequent exhaustions in the same session show the single-line hint.
+- Fully disableable via config (`funnel.creditExhaustionUpsell: false`), consistent with ADR-305 opt-out principles.
+
+## Goals
+
+Convert failure into education rather than frustration: the user leaves the error with a working path forward, and Cognitum gains a signup at the moment of demonstrated need.
diff --git a/v3/docs/adr/ADR-304-local-meta-llm-proxy.md b/v3/docs/adr/ADR-304-local-meta-llm-proxy.md
new file mode 100644
index 0000000000..e35e924158
--- /dev/null
+++ b/v3/docs/adr/ADR-304-local-meta-llm-proxy.md
@@ -0,0 +1,107 @@
+# ADR-304 — Local Meta LLM Proxy Product
+
+- **Status:** Proposed
+- **Date:** 2026-07-10
+- **Deciders:** ruflo core
+- **Related:** [ADR-302](ADR-302-post-init-capability-enrollment.md) (enrollment entry point), [ADR-303](ADR-303-credit-exhaustion-experience.md) (exhaustion entry point), [ADR-305](ADR-305-customer-lifecycle-funnel.md) (funnel overview), [ADR-306](ADR-306-cognitum-authentication-account-linking.md) (auth), [ADR-307](ADR-307-proxy-runtime-packaging-lifecycle.md) (runtime, packaging, service lifecycle), [ADR-308](ADR-308-cognitum-public-api-contract.md) (API contract), [ADR-148](ADR-148-fastgrnn-router-artifact-lifecycle.md) / [ADR-149](ADR-149-per-model-cost-optimal-routing.md) (cost-optimal routing the proxy builds on), [ADR-150](ADR-150-metaharness-integration-surfaces.md) (optional-dependency + removability constraint this must satisfy)
+
+> This ADR defines the **product**: what the proxy does, its data-plane semantics, and its consent gates. The deployable runtime — binary, packaging, bind semantics, platform services, update integrity — is defined in [ADR-307](ADR-307-proxy-runtime-packaging-lifecycle.md).
+
+## Context
+
+Many RuFlo users already run local models or use multiple providers. Managing endpoints, API keys, and routing policies individually increases friction.
+
+Cognitum provides Meta LLM orchestration through https://api.cognitum.one. A local proxy can expose a single OpenAI-compatible endpoint while transparently routing requests to the optimal provider — the same tier-routing discipline the repo already applies internally (3-tier model routing, `metallm_ask`/`metallm_delegate` gateway delegation, ADR-149 cost-optimal routing).
+
+## Decision
+
+Offer an optional local proxy during onboarding (ADR-302), on credit exhaustion (ADR-303), and on demand via `ruflo proxy install` / `ruflo proxy enable`.
+
+### Architecture
+
+```
+Client (any OpenAI-compatible SDK / ruflo agents)
+ ↓
+localhost:11435
+ ↓
+Meta Proxy (local process, ruflo-managed)
+ ↓
+api.cognitum.one
+ ↓
+Claude │ GPT │ Gemini │ DeepSeek │ OpenRouter │ Local Ollama │ vLLM │ SGLang
+```
+
+Local backends (Ollama, vLLM, SGLang) are routed to directly by the local proxy without a cloud round-trip; api.cognitum.one is in the path only for cloud providers and for routing-policy updates.
+
+### Capabilities
+
+- OpenAI-compatible API surface
+- Automatic routing (difficulty-tiered, cheap-tier-first — same policy family as `cognitum-auto`)
+- Cost optimization
+- Latency optimization
+- Retry policies
+- Provider failover
+- Request receipts (metered cost + resolved tier/model returned in-band, matching the `metallm_ask` contract)
+- Local caching
+- Future harness-evolution integration (ADR-150/151 surfaces)
+
+### Authentication
+
+```
+ruflo auth login
+```
+
+obtains credentials for proxy operation.
+
+### Data-plane disclosure (cloud routing is off by default)
+
+"Local proxy" is easily read as "local inference." The two must never be conflated:
+
+- **Default state after `ruflo proxy install` is local-only.** The proxy routes exclusively to local backends (Ollama, vLLM, SGLang). No prompt leaves the machine, and no request is made to api.cognitum.one for inference.
+- **Cloud routing requires a separate explicit step** — `ruflo proxy config --cloud` — gated on the `cloud-routing` consent domain (ADR-302). Neither enrollment acceptance, `auth login`, nor proxy installation enables it.
+- **Pre-activation disclosure is mandatory.** Before cloud routing turns on, the UI states in plain terms what changes:
+
+ ```
+ Enabling cloud routing.
+
+ With cloud routing ON, prompts for cloud-tier requests are sent to
+ api.cognitum.one and forwarded to the selected provider
+ (Claude / GPT / Gemini / DeepSeek / OpenRouter).
+
+ Requests routed to local backends never leave this machine.
+
+ Enable cloud routing? [y/N]
+ ```
+
+ The default answer is No.
+- **Visible at runtime.** `ruflo proxy status` and every request receipt state the data plane used (`local` vs `cloud:<provider>`), so the user can verify where any given prompt went.
+- Cloud routing can be disabled at any time (`ruflo proxy config --local-only`), reverting to a purely local multi-backend router and revoking the `cloud-routing` consent receipt.
+
+## Relationship to the metallm dev-bridge
+
+The repository already carries an internal meta-llm gateway surface (`metallm_ask` / `metallm_delegate`, the dev-bridge MCP server). This proxy is related but **not** the same thing, and the boundary is explicit:
+
+| | metallm dev-bridge | ADR-304 proxy |
+|---|---|---|
+| Audience | Internal orchestration interface for development of ruflo itself | Supported, customer-facing product |
+| Contract | Best-effort, may change with the gateway | Versioned public API (ADR-308) |
+| Routing core | Shared (cognitum tier-routing policy family) | Shared |
+| Network contract | **No implicit dependency in either direction** | ADR-308 |
+
+- The shared routing core is a library boundary; the dev-bridge and the proxy consume it independently.
+- A **compatibility layer, explicitly versioned**, mediates anywhere the two must interoperate — the internal dev-bridge never becomes the de facto public contract, and public-contract changes never break internal tooling silently.
+- Deprecating or changing the dev-bridge has no effect on proxy customers, and vice versa.
+
+## Constraints
+
+- **Optional and removable** (ADR-150 discipline): the proxy ships as an optional component; ruflo remains fully operational with it absent or uninstalled. No `dependencies` entry — install is an explicit user action.
+- **No credentials in the repo or config files**: tokens live in the OS keychain where available, else `~/.ruflo/credentials` with `0600` permissions; never in project config, never committed (existing `@claude-flow/security` boundary rules apply).
+- **Local-first privacy posture**: prompts routed to local backends never leave the machine; the cloud path is explicit and visible in request receipts.
+- **Default port 11435** (adjacent to Ollama's 11434, non-conflicting), configurable.
+- **Failure isolation**: if the proxy is down, clients get a normal connection error — the proxy must never silently fall back from local-only mode to cloud routing.
+
+## Consequences
+
+- New CLI surface: `ruflo proxy …` — full lifecycle command set (`install|start|stop|status|logs|update|uninstall`) specified in ADR-307, plus `proxy config` for routing mode.
+- `ruflo doctor` gains a proxy health check component (details in ADR-307).
+- This is the conversion product the ADR-301/302/303 touchpoints funnel toward; activation rate is a North Star metric in ADR-305.
diff --git a/v3/docs/adr/ADR-305-customer-lifecycle-funnel.md b/v3/docs/adr/ADR-305-customer-lifecycle-funnel.md
new file mode 100644
index 0000000000..1c959ed862
--- /dev/null
+++ b/v3/docs/adr/ADR-305-customer-lifecycle-funnel.md
@@ -0,0 +1,150 @@
+# ADR-305 — Customer Lifecycle Funnel (RuFlo → Cognitum)
+
+- **Status:** Proposed
+- **Date:** 2026-07-10
+- **Deciders:** ruflo core
+- **Related:** [ADR-301](ADR-301-promotional-status-surface.md) (promo status surface), [ADR-302](ADR-302-post-init-capability-enrollment.md) (post-init enrollment), [ADR-303](ADR-303-credit-exhaustion-experience.md) (credit exhaustion), [ADR-304](ADR-304-local-meta-llm-proxy.md) (local Meta LLM proxy product), [ADR-306](ADR-306-cognitum-authentication-account-linking.md) (auth), [ADR-307](ADR-307-proxy-runtime-packaging-lifecycle.md) (proxy runtime), [ADR-308](ADR-308-cognitum-public-api-contract.md) (API contract), [ADR-309](ADR-309-funnel-governance-privacy-ecosystem.md) (governance/privacy), [ADR-310](ADR-310-funnel-rollout-measurement-emergency-controls.md) (rollout, measurement, emergency controls)
+
+## Context
+
+RuFlo has millions of monthly package downloads and a large active user base, but relatively little product discovery beyond the CLI itself. Cognitum One (https://cognitum.one) offers adjacent paid capabilities — Meta LLM routing, hosted memory, premium agents, enterprise features — that most ruflo users never encounter.
+
+The objective is a low-friction progression from open-source user to Cognitum customer without interrupting developer workflows. ADRs 301–304 define the individual touchpoints; this ADR defines the funnel they compose, its principles, and how success is measured.
+
+## Decision
+
+Establish a lifecycle funnel integrated into natural product touchpoints:
+
+```
+npm install ruflo
+ ↓
+Initialization
+ ↓
+Optional capability enrollment (ADR-302)
+ ↓
+CLI usage
+ ↓
+Rotating status messages (ADR-301)
+ ↓
+Feature discovery
+ ↓
+Credit exhaustion guidance (ADR-303)
+ ↓
+Authentication (ruflo auth login)
+ ↓
+Local Meta Proxy (ADR-304)
+ ↓
+Multi-model routing
+ ↓
+Premium capabilities
+ ↓
+Enterprise adoption
+```
+
+Each stage is independently valuable to the user (a working install, a useful tip, a recovery path, a free local proxy) — conversion is a byproduct of delivered value, not a gate in front of it.
+
+## Design Principles
+
+- **Helpful before promotional.** Every message provides immediate user value.
+- **One action per prompt.** No multi-step upsell flows inside the CLI.
+- **Never interrupt active workflows.** Touchpoints live in idle surfaces (status row, post-init, post-failure) only.
+- **Respect prior dismissal and opt-out preferences.** Dismissals persist at the user level, across projects.
+- **Fully disableable through configuration.** A single `funnel.enabled: false` (plus per-surface flags in ADRs 301–303) turns every touchpoint off; CI and non-TTY environments are always off.
+- **Open-source ruflo stays whole.** No existing capability moves behind the funnel; ADR-150 removability discipline applies to every funnel component.
+
+## Control Precedence (normative)
+
+Suppression sources are strictly ordered. **A lower-precedence source must never re-enable a higher-precedence disable.**
+
+```
+1. RUFLO_FUNNEL=0 (environment — shells, dev containers, CI images, MDM-pushed profiles)
+2. Enterprise managed policy (managed settings file deployed by endpoint management)
+3. User config: funnel.enabled (claude-flow.config.json / user-level config)
+4. Package default
+5. Remote signed policy (only when the freshness feed is enabled; see kill switches below)
+```
+
+```ts
+effectiveFunnelEnabled =
+ env !== false &&
+ enterprisePolicy !== false &&
+ userConfig !== false &&
+ packageDefault === true &&
+ remotePolicy !== false;
+```
+
+Enterprise documentation must cover: shell-environment deployment, dev-container configuration, CI environment defaults, MDM/endpoint-management deployment, air-gapped configuration, and audit verification (`ruflo doctor` prints the effective state and which source decided it).
+
+## Attribution Rules
+
+Conversion numbers are meaningless unless they are reproducible. The following are defined **before** implementation, and no funnel event ships without them:
+
+- **Event vocabulary (closed set).** `promo_impression`, `promo_dismiss`, `promo_open`, `enroll_shown`, `enroll_accept`, `enroll_skip`, `exhaustion_shown`, `exhaustion_accept`, `auth_login_started`, `auth_login_completed`, `proxy_installed`, `proxy_activated`, `cloud_routing_enabled`, `funnel_opt_out`. New events require an ADR amendment.
+- **Anonymous identifiers.** Events carry a random, locally generated funnel ID (UUIDv4 in `~/.ruflo/funnel-id`) that is: not derived from hardware, account, email, or install path; rotated every 90 days; deleted on opt-out. It exists solely to deduplicate impressions and to join a signup back to its originating surface. It is never joined to the Cognitum account ID server-side beyond the attribution window.
+- **Attribution windows.** A signup attributes to a surface (301/302/303) only if `auth_login_completed` occurs within **7 days** of the surface event; proxy activation attributes to a signup within **30 days**. Outside the window, the conversion counts as organic.
+- **Retention windows.** Raw events retained ≤ 90 days; only aggregates persist beyond that. Aggregates contain no identifiers.
+- **Deletion behavior.** `funnel_opt_out` (or telemetry off) stops emission immediately, deletes the local funnel ID, and triggers server-side deletion of that ID's raw events. Deletion is verifiable via a documented endpoint.
+- All measurement follows the ADR-301 telemetry policy: emitted only when telemetry is enabled; attribution via campaign parameters and the funnel ID above, never client identity.
+
+## Gate Hierarchy
+
+Gates are ordered: a failure at any level makes the levels below it irrelevant. Growth metrics can never be traded against integrity metrics.
+
+| Level | Gate | Threshold |
+|-------|------|-----------|
+| 0 — Integrity | Security regressions | **0** |
+| 0 — Integrity | Consent violations (any capability active without its ADR-302 receipt) | **0** |
+| 1 — Product health | CLI latency p95 increase | **< 10 ms** |
+| 1 — Product health | Command failure rate increase | **< 0.1 percentage points** |
+| 2 — Trust | Opt-out rate | **< 10%** |
+| 3 — Growth | Signup conversion | **> 1%** |
+| 3 — Growth | Thirty-day activated retention | **> 20%** |
+| 3 — Growth | Paid conversion (of activated accounts) | **> 2%** |
+
+Level 3 targets are goals; levels 0–2 are hard gates.
+
+### Automatic disable (kill switches — two mechanisms, honestly characterized)
+
+The biggest failure mode is optimizing signup rate while degrading developer trust. Guardrails therefore act, not just report. But the transport matters: the ADR-174/177 signed helper channel is **release-bound, not immediate** — it propagates on the next installed upgrade, not on demand. Claiming "immediate fleet-wide shutdown" over that channel would be false. Two distinct mechanisms, each with its real latency:
+
+| | Release kill switch | Freshness kill switch |
+|---|---|---|
+| Transport | Policy flag ships in the npm package (ADR-174/177 stamp propagates to initialized projects) | Optional signed remote fetch: `GET /v1/funnel-policy` (ADR-308) |
+| Activation latency | **Next installed upgrade** | **Bounded by polling interval** |
+| Works offline | Yes | No (falls back to last valid signed policy) |
+| Default | **On — the default mechanism for all users** | **Off** — enabled only by explicit user or enterprise-administrator opt-in |
+| Payload | Policy data in-package | Signed, schema-validated policy data — **never executable code** |
+
+Policy:
+
+- **Consumer default: release-bound only.** No runtime network activity is introduced by the kill-switch mechanism itself.
+- **Enterprise managed deployments:** may opt into the signed freshness feed at a **6-hour** polling interval.
+- **Emergency revocation TTL: 24 hours maximum** — freshness-delivered *enables* expire unless renewed; freshness-delivered *disables* persist locally (see ADR-310 for full semantics).
+- **Failure mode: last known valid signed policy**, else package default. Invalid signature or schema → the fetched policy is discarded entirely.
+- A level-0 breach (security regression or consent violation) triggers both mechanisms: immediate policy publication to the freshness feed (reaches opted-in fleets within the polling interval) and an expedited release (reaches everyone else on upgrade).
+- A sustained level-1 or level-2 breach disables the offending surface in the next release; re-enabling requires the metric back under threshold plus an ADR amendment noting the cause.
+- Remote policy sits at the **bottom** of the control precedence — it can disable surfaces but can never re-enable anything a higher-precedence source turned off.
+- The state is inspectable: `ruflo doctor` reports whether funnel surfaces are active, disabled by user config, disabled by enterprise policy, or disabled by guardrail — and which mechanism delivered the decision.
+
+### Two measurement planes
+
+Opt-in production telemetry cannot enforce release gates — its sample is biased (opt-outs correlate with telemetry-off), and correctness must be provable before shipping, not observed after. Measurement therefore splits into two planes:
+
+1. **Release qualification (CI, enforces the hard gates).** Deterministic benchmarks and failure injection on every funnel-touching release — cold/warm startup percentiles, memory delta, output correctness, TTY/non-TTY/CI behavior, offline behavior, corrupt-policy and missing-credential injection — across the full platform × install-state × accessibility matrix. Levels 0–2 of the gate hierarchy are enforced **here**. Full specification in ADR-310.
+2. **Product analytics (production, adoption only).** Disclosure acceptance, disable rate, signup initiation and completion, proxy activation, 7/30-day retention, paid conversion — under the ADR-309 event schema and consent rules. Level-3 growth metrics are read **here**, and **never override release safety gates**.
+
+## Rollout and Acceptance
+
+Staged rollout (phases, cohort mechanics, promotion criteria, rollback discipline) and the full release-gate acceptance test are owned by [ADR-310](ADR-310-funnel-rollout-measurement-emergency-controls.md). In summary, the funnel does not ship until this passes end-to-end on an existing **offline** installation, upgraded in place, across TTY, non-TTY, CI, screen-reader/reduced-motion, and enterprise-disabled configurations:
+
+1. The signed helper refresh fires (manifest stamp updated, signature verified, `statusline.cjs` replaced) without running `ruflo init`.
+2. **No promotional content appears before the ADR-301 disclosure.**
+3. **No network request occurs without opt-in** (packet-capture verified).
+4. **`RUFLO_FUNNEL=0` suppresses every funnel surface** (ADR-301, 302, 303).
+5. All core ruflo commands remain behaviorally identical — exit codes, operational output, and latency within gate thresholds — in every configuration.
+
+## Future Extensions
+
+The same promotion framework can surface context-aware recommendations, such as suggesting GPU acceleration when local hardware is detected, enterprise features in team environments, or relevant MetaHarness integrations based on observed usage patterns. This creates a scalable discovery system while keeping the CLI experience lightweight and developer-focused.
+
+Any such extension inherits this ADR's principles and guardrails and requires its own ADR before shipping.
diff --git a/v3/docs/adr/ADR-306-cognitum-authentication-account-linking.md b/v3/docs/adr/ADR-306-cognitum-authentication-account-linking.md
new file mode 100644
index 0000000000..d6f0f857ae
--- /dev/null
+++ b/v3/docs/adr/ADR-306-cognitum-authentication-account-linking.md
@@ -0,0 +1,56 @@
+# ADR-306 — Cognitum Authentication and Account Linking
+
+- **Status:** Proposed
+- **Date:** 2026-07-10
+- **Deciders:** ruflo core
+- **Related:** [ADR-302](ADR-302-post-init-capability-enrollment.md) (consent domains), [ADR-304](ADR-304-local-meta-llm-proxy.md) (proxy product), [ADR-307](ADR-307-proxy-runtime-packaging-lifecycle.md) (proxy runtime), [ADR-308](ADR-308-cognitum-public-api-contract.md) (API contract), [ADR-309](ADR-309-funnel-governance-privacy-ecosystem.md) (governance)
+
+## Context
+
+ADRs 302–304 all hand off to `ruflo auth login`, which does not exist. The funnel cannot ship on an unspecified identity system: token handling, revocation, and storage are security-critical, and every consent decision in ADR-302 ultimately anchors to an account. This ADR specifies the complete identity lifecycle.
+
+## Decision
+
+### Authentication flows
+
+| Environment | Flow |
+|---|---|
+| Interactive desktop (browser reachable) | OAuth 2.0 Authorization Code + **PKCE**, loopback redirect |
+| Headless / SSH / no browser | **Device authorization flow** (RFC 8628): CLI shows user code + verification URL |
+| CI / non-TTY | `auth login` refuses interactively; service credentials only via explicit `--token-stdin` for enterprise automation |
+| Enterprise SSO | OIDC federation brokered by Cognitum (IdP-initiated flows land on the same token contract); detailed in a follow-up amendment before enterprise GA |
+
+### Token model
+
+- **Access token:** 10–15 minute lifetime, held in process memory; short-lived enough that server-side revocation is honored within one lifetime.
+- **Refresh token:** stored in the **OS keychain only** — macOS Keychain, Linux Secret Service (libsecret), Windows Credential Manager. **Never in plain-text config**, never in `claude-flow.config.json`, never in `.env`.
+- **No keychain available** (typical headless Linux): tokens are session-only; the CLI re-runs the device flow on expiry rather than writing a refresh token to disk. This is a deliberate usability cost in exchange for never persisting plain-text credentials.
+- The CLI's on-disk state (`~/.ruflo/auth.json`, `0600`) stores only: account ID, granted scopes, access-token expiry, keychain entry reference, profile name. No token material.
+
+### Scopes (map 1:1 onto ADR-302 consent domains)
+
+```
+account.create ← consent domain: account
+proxy.use ← consent domain: proxy-install
+cloud.route ← consent domain: cloud-routing
+telemetry.write ← consent domain: telemetry
+hosted.memory.use ← consent domain: hosted-memory (new; same receipt rules)
+```
+
+- Scopes are requested **incrementally**: `auth login` requests `account.create` only. Each further scope is requested at the moment its capability is enabled, gated on the corresponding ADR-302 consent receipt.
+- Accepting account creation **must not** implicitly grant `cloud.route` or `telemetry.write`. A token bearing a scope without a matching local consent receipt is a level-0 consent violation (ADR-305 gate hierarchy).
+
+### Lifecycle
+
+- **Account creation / linking:** first `auth login` offers create-or-link on the Cognitum side; the CLI only ever receives tokens, never passwords.
+- **Refresh:** silent, keychain-backed; failure degrades to logged-out state with a clear message — never a retry storm.
+- **Revocation:** `ruflo auth logout` calls `POST /v1/auth/revoke` (ADR-308), removes the keychain entry, clears `auth.json`, and revokes the `account` consent receipt. Server-side revocation (dashboard) takes effect within one access-token lifetime.
+- **Multiple accounts:** named profiles — `ruflo auth login --profile work`; one default profile; `ruflo auth status` lists all with scopes and expiry.
+- **Offline:** cached identity metadata is readable; no refresh occurs; capabilities requiring auth fail with a clear "offline, sign-in required" error. Core ruflo functionality is never affected by auth being unavailable (ADR-308 failure policy).
+
+## Consequences
+
+- New CLI surface: `ruflo auth login|logout|status [--profile <name>]`.
+- `@claude-flow/security` owns token handling primitives (keychain adapters, PKCE verifier generation); no other package touches token material.
+- `ruflo doctor` gains an auth component (keychain availability, token expiry, scope-vs-receipt consistency check).
+- The scope-vs-receipt consistency check is enforced client-side on every authenticated call: a scope with no receipt drops the capability and reports, fail-closed.
diff --git a/v3/docs/adr/ADR-307-proxy-runtime-packaging-lifecycle.md b/v3/docs/adr/ADR-307-proxy-runtime-packaging-lifecycle.md
new file mode 100644
index 0000000000..01a0458c21
--- /dev/null
+++ b/v3/docs/adr/ADR-307-proxy-runtime-packaging-lifecycle.md
@@ -0,0 +1,67 @@
+# ADR-307 — Proxy Runtime, Packaging, and Service Lifecycle
+
+- **Status:** Proposed
+- **Date:** 2026-07-10
+- **Deciders:** ruflo core
+- **Related:** [ADR-304](ADR-304-local-meta-llm-proxy.md) (product definition), [ADR-306](ADR-306-cognitum-authentication-account-linking.md) (auth), [ADR-308](ADR-308-cognitum-public-api-contract.md) (API contract), [ADR-150](ADR-150-metaharness-integration-surfaces.md) (removability discipline)
+
+## Context
+
+ADR-304 defines what the local Meta LLM proxy *is*; nothing defines the deployable runtime — language, packaging, bind semantics, service management, or update path. Those decisions determine the security surface of a long-running local process and must precede implementation.
+
+## Decision
+
+### Runtime
+
+- **Rust single binary.** No runtime dependency on Node; the ruflo CLI manages it but does not host it.
+- **OpenAI-compatible HTTP server.**
+- **Default bind: `127.0.0.1:11435`.** Loopback only. External bind requires explicit configuration (`proxy.bind` in config or `RUFLO_PROXY_BIND`) and prints a warning at startup.
+- **No privileged port.** The proxy never requires elevation to install or run.
+- **Foreground mode by default.** `ruflo proxy start` runs attached; managed service install is a separate, explicit step.
+- **Local access control:** loopback is reachable by every local user on multi-user systems, so the proxy requires a per-user bearer token generated at install (`~/.ruflo/proxy-token`, `0600`) on every request.
+
+### Platform service model (optional, explicit)
+
+| Platform | Managed mode |
+|---|---|
+| macOS | launchd **user agent** (never a system daemon) |
+| Linux | systemd **user service** |
+| Windows | per-user background process, or Windows service for enterprise deployments |
+| Containers | foreground process only; no service install inside containers |
+
+### Lifecycle commands
+
+```
+ruflo proxy install # fetch + verify binary, write config, generate local token
+ruflo proxy start # foreground by default; --service to use the managed unit
+ruflo proxy stop
+ruflo proxy status # includes data plane per ADR-304: local vs cloud:<provider>
+ruflo proxy logs
+ruflo proxy update # explicit only — the proxy never self-updates
+ruflo proxy uninstall # removes binary, service unit, token, and consent receipt
+```
+
+### Packaging and update integrity
+
+- The binary is **not** bundled in the npm packages (size, and ADR-150 removability: ruflo works with the proxy absent). `proxy install` downloads a platform artifact from the official release channel, verifies **checksum + Ed25519 signature** before writing to disk, and refuses on any mismatch.
+- `proxy update` repeats the same verification. There is no auto-update path; the statusline may *suggest* an update (educational message class, ADR-301), but only the explicit command applies one.
+- Version compatibility between CLI and proxy is declared in the proxy's `/status` response; incompatibility degrades to a clear error, never undefined behavior.
+
+## Key invariant
+
+**"Local proxy" means the proxy *process* is local. It does not imply inference is local.**
+
+Every cloud-bound request path exposes routing before first use (per ADR-304's disclosure gate):
+
+```
+This request may send prompt content to api.cognitum.one
+and the selected provider.
+```
+
+Default state after install is local-only routing; cloud routing activates only through the ADR-304 disclosure flow backed by the ADR-302 `cloud-routing` consent receipt and the ADR-306 `cloud.route` scope.
+
+## Consequences
+
+- A new repository/workspace for the Rust proxy with its own release pipeline; ruflo pins compatible proxy versions per release.
+- `ruflo doctor --component proxy` checks: binary signature, version compatibility, bind address, token file permissions, service unit state.
+- Failure isolation holds (ADR-304): proxy down → normal connection error; the proxy never silently reroutes local-only traffic to cloud (ADR-308 failure policy).
diff --git a/v3/docs/adr/ADR-308-cognitum-public-api-contract.md b/v3/docs/adr/ADR-308-cognitum-public-api-contract.md
new file mode 100644
index 0000000000..84920d6274
--- /dev/null
+++ b/v3/docs/adr/ADR-308-cognitum-public-api-contract.md
@@ -0,0 +1,54 @@
+# ADR-308 — Cognitum Public API and Server Contract
+
+- **Status:** Proposed
+- **Date:** 2026-07-10
+- **Deciders:** ruflo core
+- **Related:** [ADR-303](ADR-303-credit-exhaustion-experience.md) (error taxonomy), [ADR-305](ADR-305-customer-lifecycle-funnel.md) (attribution, kill switches), [ADR-306](ADR-306-cognitum-authentication-account-linking.md) (auth flows), [ADR-307](ADR-307-proxy-runtime-packaging-lifecycle.md) (proxy runtime), [ADR-309](ADR-309-funnel-governance-privacy-ecosystem.md) (privacy/retention)
+
+## Context
+
+The funnel spans an organizational boundary: ruflo is open source; api.cognitum.one is a proprietary service. Auth (ADR-306), attribution events (ADR-305), deletion (ADR-305/309), funnel policy (ADR-305 freshness kill switch), routing (ADR-304/307), and credits (ADR-303) all cross it. Without a versioned, independently testable contract, every one of those ADRs has an unspecified dependency, and conversion numbers are irreproducible.
+
+## Decision
+
+Define a versioned public API contract, owned jointly and checked into both repositories.
+
+### Endpoints (v1)
+
+```
+POST /v1/auth/device # device authorization flow (RFC 8628)
+POST /v1/auth/token # code/refresh exchange
+POST /v1/auth/revoke # token + session revocation
+POST /v1/events # funnel event ingestion (idempotent)
+DELETE /v1/events/{subject_id} # verifiable deletion (ADR-305/309)
+GET /v1/funnel-policy # signed policy feed (freshness kill switch, opt-in only)
+POST /v1/proxy/chat/completions # OpenAI-compatible cloud routing
+GET /v1/credits # credit balances (the single credit authority, ADR-303)
+```
+
+### Contract requirements
+
+- **OpenAPI specification** checked into **both** repositories (ruflo: `v3/docs/api/cognitum-v1.openapi.yaml`; server repo mirrors it). CI in both repos validates against the shared spec; drift fails the build.
+- **Semantic API versioning.** `/v1` is stable; breaking changes require `/v2` with a documented overlap window. The CLI declares the API versions it supports.
+- **Idempotency keys** required on `POST /v1/events` (client-generated UUID per event batch) — retries never double-count impressions or conversions.
+- **Explicit rate limits**, documented in the spec and returned in headers; the CLI backs off and never retries into a limit.
+- **Error taxonomy:** all errors return machine-readable codes that map 1:1 onto the ADR-303 `CreditErrorCode` / category tables. No client ever parses human-readable message text.
+- **Data retention guarantees** in the contract itself: raw events ≤ 90 days, aggregates thereafter (ADR-305); deletion honored per ADR-309.
+- **Service degradation behavior** documented per endpoint (see failure policy below).
+- **Terms and privacy-policy version receipt:** token and event responses carry the policy versions in force; a version bump beyond the recorded consent receipt triggers re-consent (ADR-302 `policyVersion` rules).
+
+### Failure policy (client-side, normative)
+
+| Unavailable | Client behavior |
+|---|---|
+| Auth | Local ruflo continues working fully; auth-gated capabilities degrade with a clear error |
+| Telemetry (`/v1/events`) | Drop, or bounded local queue (≤ 24 h, ≤ 1 MB); **never block or slow the CLI** |
+| Funnel policy | Use last valid **signed** policy, else package default; never fail open into showing promo |
+| Proxy backend | Normal error to caller; **never silently reroute** to another paid or cloud provider |
+| Deletion | Return a durable request receipt to the user and retry server-side until confirmed |
+
+## Consequences
+
+- The OpenAPI spec is the review artifact for any server change that touches the CLI; PRs to either repo that change the boundary must update the shared spec first.
+- Contract tests run in ruflo CI against a mock server generated from the spec — the funnel surfaces are testable with zero network and no Cognitum dependency.
+- `GET /v1/funnel-policy` responses are Ed25519-signed with the same key-management discipline as the helper channel; the CLI validates signature + policy schema before honoring anything (ADR-305 freshness kill switch is inert otherwise).
diff --git a/v3/docs/adr/ADR-309-funnel-governance-privacy-ecosystem.md b/v3/docs/adr/ADR-309-funnel-governance-privacy-ecosystem.md
new file mode 100644
index 0000000000..a56e421913
--- /dev/null
+++ b/v3/docs/adr/ADR-309-funnel-governance-privacy-ecosystem.md
@@ -0,0 +1,64 @@
+# ADR-309 — Funnel Governance, Privacy, and Ecosystem Policy
+
+- **Status:** Proposed
+- **Date:** 2026-07-10
+- **Deciders:** ruflo core
+- **Related:** [ADR-301](ADR-301-promotional-status-surface.md) (content policy), [ADR-302](ADR-302-post-init-capability-enrollment.md) (consent receipts), [ADR-305](ADR-305-customer-lifecycle-funnel.md) (attribution), [ADR-308](ADR-308-cognitum-public-api-contract.md) (retention/deletion contract), [ADR-310](ADR-310-funnel-rollout-measurement-emergency-controls.md) (rollout)
+
+## Context
+
+The funnel turns an open-source developer tool into an acquisition channel for a proprietary service. That carries package-ecosystem risk, privacy-regulation obligations, and a content-governance burden that no technical ADR covers. This ADR is the single place those are decided.
+
+## Package-ecosystem policy
+
+- **Precedent:** npm banned install-time terminal advertising after the 2019 `funding`/`standard` incident. The funnel is materially different — runtime, first-party, in ruflo's own CLI, fully disableable — but the reputational blast radius of that precedent is the reference point for every content decision.
+- **Commitments (normative):**
+ - Zero output at `npm install` / postinstall time. The funnel exists only inside interactive ruflo commands.
+ - First-party promotion only — never third-party advertising, sponsorships, or paid placements.
+ - All funnel code, message copy, and policy files live in the open repository, reviewable like any code.
+ - Forks may strip the funnel freely; no license term, technical measure, or update mechanism may penalize doing so.
+
+## Privacy classification and lawful basis
+
+- The pseudonymous funnel ID (ADR-305) plus server-side raw events constitute **personal data** under GDPR and are treated as such under CCPA/CPRA. "Anonymous" is not claimed anywhere identifiers exist.
+- **Operational telemetry** (crash/health, disable rates): **legitimate-interest** basis, with a documented, minimized Legitimate Interest Assessment checked into the repo.
+- **Marketing attribution** (signup/conversion events): **explicit opt-in only** — rides the telemetry consent domain (ADR-302), never inferred from product usage.
+- **No cross-product behavioral profiling** without a separate, explicit consent — a Cognitum account must not silently enrich funnel events, and vice versa.
+- **Prohibited in any funnel event, permanently:** raw prompts, command lines, file paths, repository names, model inputs/outputs, hostnames, usernames.
+- Regional handling: EU-originating events stored in-region; region derived from coarse request geography, never collected from the client beyond an optional self-declared region field.
+- **Rights handling:** deletion and access requests flow through `DELETE /v1/events/{subject_id}` (ADR-308) keyed by the local funnel ID, which the CLI can print on demand (`ruflo funnel id`). Deletion returns a durable receipt.
+- **Privacy-notice versioning:** the notice version rides API responses (ADR-308); a bump beyond the recorded consent receipt forces re-consent (ADR-302 `policyVersion`).
+
+## Event schema (constrained, closed)
+
+```ts
+interface FunnelEvent {
+ schemaVersion: 1;
+ event:
+ | "disclosure_shown"
+ | "funnel_disabled"
+ | "signup_opened"
+ | "account_created"
+ | "proxy_activated";
+ surface: "statusline" | "init" | "credit_exhaustion";
+ release: string; // ruflo version, e.g. "3.8.0"
+ region?: string; // coarse, self-declared only
+ pseudonymousId?: string; // ADR-305 funnel ID; absent when attribution consent is off
+ timestampBucket: string; // "2026-07-10" or "2026-07-10T18" — never full timestamps
+}
+```
+
+- The event union is **closed**; adding a member requires amending this ADR.
+- `timestampBucket` is daily by default, hourly at most. Full timestamps are never transmitted — bucket granularity is chosen per metric, and daily suffices for every ADR-305 North Star metric.
+- Schema-validated client-side before emission; invalid events are dropped locally, never "fixed" server-side.
+
+## Content approval ownership
+
+- A named content owner (role, recorded in `MAINTAINERS`/`CODEOWNERS`) approves every message entering the ADR-301 rotation; message changes are PRs with the owner as required reviewer.
+- Review checklist enforced in PR template: schema-valid, ratio-compliant (≥ 4:1 educational:promotional, ADR-301), no urgency/scarcity/dark patterns, allowlisted URL, accessibility-clean (no reliance on color or motion), localization key present.
+- **Localization:** messages ship as keyed strings; untranslated locales fall back to English rather than machine translation. **Accessibility:** every message must read correctly as static plain text, since marquee and color are stripped under reduced-motion/screen-reader/`NO_COLOR` modes (ADR-301).
+
+## Consequences
+
+- Legal review of the LIA, privacy notice, and regional storage design is a Phase-0 exit criterion in ADR-310 — no funnel event leaves a client before it completes.
+- This ADR is the governance anchor: ADR-301's content rules, ADR-302's receipts, ADR-305's attribution, and ADR-308's retention clauses all cite it; conflicts resolve in favor of the stricter rule.
diff --git a/v3/docs/adr/ADR-310-funnel-rollout-measurement-emergency-controls.md b/v3/docs/adr/ADR-310-funnel-rollout-measurement-emergency-controls.md
new file mode 100644
index 0000000000..2d667ea9e4
--- /dev/null
+++ b/v3/docs/adr/ADR-310-funnel-rollout-measurement-emergency-controls.md
@@ -0,0 +1,85 @@
+# ADR-310 — Funnel Rollout, Measurement, and Emergency Controls
+
+- **Status:** Proposed
+- **Date:** 2026-07-10
+- **Deciders:** ruflo core
+- **Related:** [ADR-301](ADR-301-promotional-status-surface.md)–[ADR-305](ADR-305-customer-lifecycle-funnel.md) (funnel surfaces and gates), [ADR-308](ADR-308-cognitum-public-api-contract.md) (policy feed), [ADR-309](ADR-309-funnel-governance-privacy-ecosystem.md) (governance)
+
+## Context
+
+ADR-305 defines gates and two measurement planes; nothing defines how the funnel actually reaches the install base, in what order, with what promotion criteria, or how it is rolled back. Shipping all surfaces to 100% of installs at once maximizes exactly the failure mode the whole set guards against: trust damage at fleet scale before guardrail data exists.
+
+## Staged rollout
+
+Cohort assignment for percentage phases is a deterministic local hash of the funnel ID into buckets — decided client-side, no network call, stable across sessions, re-rolled if the ID rotates.
+
+| Phase | Population | Surfaces active |
+|---|---|---|
+| 0 | CI and maintainer dogfood only | All, behind explicit env flag |
+| 1 | New installs only | Disclosure + **educational content only** |
+| 2 | 5% of upgraded installs | Same; disclosure required before anything renders |
+| 3 | 25% of upgraded installs | Same; monitor disable and issue rates |
+| 4 | 100% | Educational surface |
+| 5 | 100% | Introduce promotional content, capped at the 1-in-5 ratio (ADR-301) |
+| 6 | 100% | Credit-exhaustion recovery (ADR-303) + proxy activation (ADR-304/307) |
+
+**Phase-0 exit criteria** additionally include: ADR-309 legal review complete (LIA, privacy notice, regional storage) and the acceptance test below green on all platforms.
+
+### Promotion criteria (each phase → next)
+
+- Disable rate **< 5%** in the current phase's cohort.
+- Complaint rate **< 0.1%** of active users (funnel-labeled GitHub issues / support contacts).
+- No regression in CLI latency or command failures (ADR-305 level-1 gates, measured by the release-qualification plane).
+- No open policy, legal, or accessibility blocker.
+
+A failed criterion holds the phase; two consecutive failed evaluation windows roll back one phase.
+
+## Rollback and release discipline
+
+- Rollback ships through the same three-package publication sequence as any release: `@claude-flow/cli` → `claude-flow` → `ruflo`, with all dist-tags updated and verified per the repo's publishing rules.
+- A release gate verifies **all three packages carry the same funnel schema version and policy version** — a mixed fleet where the umbrella and the CLI disagree about funnel policy is a release-blocking error.
+- Rollback restores the prior signed policy and prior helper manifest version; the ADR-174/177 stamp mechanism propagates it to initialized projects on their next command.
+
+## Emergency controls
+
+Operationalizes the ADR-305 kill-switch model:
+
+- **Release kill switch** (default, all users): a policy flag in the npm package. Activation latency: next installed upgrade. Works offline.
+- **Freshness kill switch** (opt-in only): signed `GET /v1/funnel-policy` fetch (ADR-308). Consumer default **off**; enterprise managed deployments may enable a **6-hour** polling interval. Never carries executable code — schema-validated policy data only.
+- **Emergency revocation TTL: 24 hours maximum** — a freshness-delivered disable persists locally and does not require the feed to stay reachable; a freshness-delivered *enable* expires after its TTL unless renewed, so a compromised or stale feed can never durably re-enable anything.
+- **Failure mode:** last known valid signed policy, else package default. Signature or schema failure → the fetched policy is discarded entirely.
+- Precedence always holds (ADR-301/305): no remote policy can override `RUFLO_FUNNEL=0`, enterprise managed policy, or user config.
+
+## Release qualification (measurement plane 1 — CI, enforces gates)
+
+CI benchmark on every funnel-touching release:
+
+- Cold and warm startup: p50, p95, p99.
+- Memory delta, output correctness (byte-for-byte on operational output), TTY vs non-TTY behavior, CI suppression.
+- Failure injection: proxy unavailable, policy corrupt, credential unavailable.
+
+Test matrix: {funnel on, off} × {new install, upgraded install} × {Linux, macOS, Windows} × {interactive TTY, pipe} × {standard, screen-reader/reduced-motion} × {online, offline}.
+
+Hard gates (release-blocking):
+
+| Gate | Threshold |
+|---|---|
+| Startup p95 regression | < 10 ms |
+| Memory regression | < 5 MB |
+| Command failure delta | 0 |
+| Unexpected network calls | 0 |
+| Promo output in CI or non-TTY | 0 |
+| Promotional display before disclosure on upgraded install | 0 |
+
+## Product analytics (measurement plane 2 — adoption only)
+
+Disclosure acceptance, disable rate, signup initiation, account completion, proxy activation, 7-day and 30-day retention, paid conversion — per the ADR-305/309 event schema and consent rules. **These metrics never override release safety gates.**
+
+## Acceptance test (release-gate regression test)
+
+Take an existing **offline** installation, upgrade it, and run the CLI in TTY, non-TTY, CI, screen-reader/reduced-motion, and enterprise-disabled configurations. Prove that:
+
+1. No promotional content appears before the ADR-301 disclosure.
+2. No network request occurs without opt-in (verified by the zero-unexpected-network-calls gate under packet capture).
+3. `RUFLO_FUNNEL=0` suppresses every funnel surface (ADR-301, 302, 303).
+4. All core ruflo commands remain behaviorally identical — exit codes, operational output, and latency within gate thresholds — across every configuration above.
diff --git a/v3/docs/adr/ADR-311-funnel-analytics-endpoint-deployment.md b/v3/docs/adr/ADR-311-funnel-analytics-endpoint-deployment.md
new file mode 100644
index 0000000000..a5a5f09efc
--- /dev/null
+++ b/v3/docs/adr/ADR-311-funnel-analytics-endpoint-deployment.md
@@ -0,0 +1,177 @@
+# ADR-311: Funnel analytics endpoint — deployment & repo split
+
+**Status:** Accepted
+**Date:** 2026-07-10
+**Amends:** ADR-308 (public API contract), ADR-309 (governance & privacy)
+**Companion of:** ADR-305 (customer lifecycle funnel), ADR-303 (credit-exhaustion recovery)
+
+## Context
+
+ADR-308 defined the client-facing contract for the funnel event endpoint
+(`POST /v1/events`, idempotency key, closed vocabulary, 90-day retention,
+402 credit-exhausted signal). It intentionally left the **server** side out
+of the ruflo repo — the CLI ships without a bundled backend, and the
+contract is what the two sides agree on.
+
+The ADR-308 endpoint has now been implemented, deployed, and verified live.
+This ADR records the concrete decisions that came out of standing it up.
+
+## Decisions
+
+### 1. Server home: separate repo, separate lifecycle
+
+The server implementation lives in
+[**`github.com/cognitum-one/ruflo-funnel-api`**](https://github.com/cognitum-one/ruflo-funnel-api),
+not in the ruflo repo, so that:
+
+- The commercial-side ADR-311 evolution (rate limits, tenant model,
+ BigQuery export, dashboards) doesn't churn the OSS CLI's PR history.
+- The client contract in ADR-308 stays the single source of truth for what
+ the wire looks like — the server can be swapped or forked without
+ changing what the CLI sends.
+- Server security surface (Firestore rules, service-account IAM, key
+ rotation) is owned by whoever runs the endpoint. Not tangled with CLI
+ release cadence.
+
+The `services/cognitum-analytics/` directory in the ruflo repo has been
+replaced with a `README.md` pointing at the dedicated repo.
+
+### 2. Domain: `funnel.ruv.io` (Cloud Run mapping)
+
+Client `DEFAULT_ENDPOINT` is `https://funnel.ruv.io/v1/events`. Reasoning:
+
+- **rUv authors ruflo → telemetry lives on rUv's domain.** Putting analytics
+ on `cognitum.one` would conflate OSS-tool telemetry with the commercial
+ Cognitum product's URLs. The OSS/commercial line stays visible.
+- **Cloud Run domain mapping decouples URL from Cloud Run hostname hash.**
+ A redeploy assigning a new random hash doesn't break the client.
+- **DNS is Cloudflare-managed; CNAME is unproxied** so Cloud Run terminates
+ TLS directly (Cloud Run cannot use Cloudflare's TLS).
+
+### 3. Runtime: Cloud Function gen2, Node 22, us-central1, 256 MiB
+
+Deployed via `gcloud functions deploy --gen2` from
+`ruflo-funnel-api/deploy.sh`. Configuration:
+
+| Setting | Value | Reason |
+|---|---|---|
+| Runtime | `nodejs22` | LTS at deploy time, matches ruflo build env |
+| Region | `us-central1` | Cheapest tier + closest to Firestore `nam5` |
+| Memory | `256Mi` | Handler is stateless + O(batch size); no ML |
+| Concurrency | `80` | Cloud Run default; batches are small + fast |
+| Max instances | `100` | Adjust up when we know the impression volume |
+| Timeout | `30s` | Firestore batch writes finish in ms; padding for cold starts |
+| Allow unauthenticated | `--allow-unauthenticated` | CLI has no auth; abuse gated by ceiling + Cloudflare in front |
+
+### 4. Storage: Firestore native, 4 collections
+
+| Collection | Purpose | ADR-309 retention |
+|---|---|---|
+| `funnel_events` | Raw events, one doc per event, includes `receivedAt` | ≤ 90 days |
+| `funnel_aggregates` | Rolling counts by (surface, event, day, release) | Indefinite (no PII) |
+| `funnel_credit` | Per-tenant daily counter — triggers 402 when exceeded | Rolling |
+| `funnel_idem` | `Idempotency-Key` → { at, count } — dedup journal | Rolling |
+
+The `funnel_events` `receivedAt` field is a server-side timestamp for
+retention scheduling; it does NOT replace the client's `timestampBucket`
+(day-only, ADR-309 privacy invariant).
+
+### 5. Credit-exhaustion signal (ADR-303 wire-in)
+
+Server replies **HTTP 402 Payment Required** with body
+`{"error": "COGNITUM_CREDIT_EXHAUSTED", ...}` when the per-tenant daily
+counter exceeds `CREDIT_CEILING_PER_DAY` (default `1000000`). Client
+transport picks up either signal:
+
+- `res.status === 402`, OR
+- `res.body` string-contains `'COGNITUM_CREDIT_EXHAUSTED'`
+
+and calls `markCreditExhausted()` in `funnel/credit-notifier.ts`. The
+recovery surface fires on the next appropriate CLI render, per ADR-303.
+
+### 6. Impression + click tracking (ADR-305 vocabulary amendment)
+
+The event vocabulary in `funnel/types.ts` is expanded (amends ADR-305)
+with two new terms:
+
+| Event | Fired by | Carries |
+|---|---|---|
+| `promo_impression` | Client — every `rotation.selectMessage()` | `messageId` |
+| `promo_open` | Server — on every `/v1/click/{id}` redirect | `messageId`, `country` |
+
+`FunnelEvent` gains an optional `messageId` field (length ≤ 64, matches
+`[a-z0-9-]`). Any event WITHOUT the promo_impression / promo_open name
+drops `messageId` server-side so the schema stays predictable.
+
+### 7. Click redirect (`GET /v1/click/{messageId}`)
+
+Promotional messages route through a server-side redirect so the click
+can be recorded before the user leaves the terminal:
+
+```
+✨ Unlock Meta LLM routing → funnel.ruv.io/v1/click/promo-cognitum-meta-llm?to=…
+```
+
+Server flow:
+1. Validate `messageId` against `MESSAGE_ID_RE` (`/^[a-z0-9][a-z0-9-]{0,63}$/i`)
+2. Validate the `to` URL: must be https AND host must be in
+ `CLICK_ALLOWED_HOSTS` (`cognitum.one` variants + `agentics.org`
+ variants — allowlist ships in code, NOT in Firestore so a compromised
+ admin can't redirect users off-platform)
+3. Extract coarse geo (`extractCountry(req)`): ISO-3166 alpha-2 country
+ ONLY, from `CF-IPCountry` or `X-Appengine-Country`. Never city, never
+ lat/long — ADR-309 privacy invariant
+4. Firestore write: `funnel_events` doc + `funnel_aggregates` row keyed by
+ `(surface, event, day, release, messageId, country)`
+5. Firestore write failure **never blocks the redirect** — user intent to
+ navigate wins over analytics precision (ADR-308 failure policy)
+6. 302 to the target with `Cache-Control: no-store` so caches don't
+ swallow subsequent clicks
+
+Client wraps promotional URLs via `attribution.clickTrackedUrl(msgId, target, input)`
+before OSC 8 rendering. If the client-side wrap fails (unknown id, malformed
+target), it falls back to the direct UTM-decorated link.
+
+### 8. Coverage summary
+
+The Phase 2 analytics plane now answers:
+
+| Question | How |
+|---|---|
+| How many impressions per message per day? | `promo_impression` events + aggregates |
+| How many clicks per message per day? | `promo_open` events + aggregates |
+| Click-through rate | ratio of the two above |
+| Where in the world are clicks coming from? | `country` field on `promo_open` |
+| Conversions | `signup_opened`, `account_created`, `proxy_activated` (existing) |
+| Which install disabled notices | `funnel_disabled` (existing) |
+
+Zero PII, zero prompt content, zero paths — everything is either a closed
+enum, a message id (allowlisted shape), a country code (ISO alpha-2), or
+a daily bucket.
+
+## Verified state at time of adoption
+
+- Cloud Run endpoint `cognitum-analytics-63rzcdswba-uc.a.run.app` — live
+- Domain mapping `funnel.ruv.io` — created; DNS live; TLS cert issuance
+ polled hourly by Cloud Run (Google side, asynchronous)
+- **API contract (8/8 tests green)** — see the dedicated repo's README
+- **Firestore writes** — 9 raw events, 5 aggregates, 5 idempotency journal
+ entries, 1 credit counter row from initial smoke + verification batches
+
+## Consequences
+
+- Anyone forking ruflo who wants their own telemetry endpoint clones
+ `cognitum-one/ruflo-funnel-api`, deploys to their own project, and sets
+ `RUFLO_FUNNEL_EVENTS_ENDPOINT=…` in their env or configures a fork of
+ `event-transport.ts` — the ADR-308 contract is what they conform to,
+ not this specific deployment.
+- Server-side changes to the endpoint are documented in the dedicated
+ repo; only wire-format changes need a corresponding ADR-308 amendment
+ in ruflo.
+
+## References
+
+- [ADR-308: Public API contract](ADR-308-cognitum-public-api-contract.md)
+- [ADR-309: Governance, privacy, ecosystem](ADR-309-funnel-governance-privacy-ecosystem.md)
+- [ADR-303: Credit-exhaustion recovery](ADR-303-credit-exhaustion-experience.md)
+- [Server repo: cognitum-one/ruflo-funnel-api](https://github.com/cognitum-one/ruflo-funnel-api)
diff --git a/v3/docs/adr/ADR-312-usage-limit-downtime-prevention.md b/v3/docs/adr/ADR-312-usage-limit-downtime-prevention.md
new file mode 100644
index 0000000000..2f8fd77788
--- /dev/null
+++ b/v3/docs/adr/ADR-312-usage-limit-downtime-prevention.md
@@ -0,0 +1,137 @@
+# ADR-312: Usage-limit downtime prevention (Cognitum meta-LLM fallback CTA)
+
+**Status:** Proposed — Phase 0 buildable now; Phase 1 blocked on an upstream Claude Code capability that does not exist today
+**Date:** 2026-07-10
+**Relates to:** ADR-301 (promotional status surface), ADR-303 (credit-exhaustion experience), ADR-311 (remote message feed)
+
+## Context
+
+The user wants: when a Claude Code session is approaching or has hit its usage/rate limit (the kind of event that produces a UI banner like *"You've used 97% of your session limit · resets 6:10pm"*), ruflo should detect this and surface a message in the statusline directing the user to `cognitum.one`'s meta-LLM proxy — framed as **downtime prevention / session extension**: keep working on ruflo/Claude Code via a local or hosted alternative model until the Anthropic-side limit resets. This is opt-in, gated by existing consent (ADR-302 `proxy-install` / `cloud-routing` domains), and would use the same remote-message + click-tracking plane ADR-311 already built.
+
+The 97% example the user gave was illustrative, not literal — the ask is the general capability: **detect approaching-or-hit usage limits and act on it.**
+
+## Research performed this session (grounded, not assumed)
+
+Per direct instruction, the installed Claude Code CLI source was inspected directly — not just documentation — to determine whether this signal is actually available to a script like ruflo's statusline hook.
+
+**Installed version inspected:** `@anthropic-ai/[email protected]` at `/usr/lib/node_modules/@anthropic-ai/claude-code/cli.js` (minified bundle, 17,466 lines / ~59K-char lines).
+
+### Finding 1 — the signal is real and exists inside Claude Code's process
+
+Grepping the bundle for rate-limit-related identifiers turned up a live, actively-used internal state object (module-level variable, referred to here by its minified name `Lv` — this WILL rename on every Claude Code release since the bundle is unstably minified):
+
+```js
+Lv = {
+ status: "allowed" | "allowed_warning" | "rejected",
+ resetsAt?: number, // epoch SECONDS (confirmed: formatter does `new Date(q*1000)`)
+ rateLimitType?: "five_hour" | "seven_day" | "seven_day_opus" | "seven_day_sonnet" | "overage",
+ utilization?: number, // 0.0–1.0 float; UI does Math.floor(u*100) for the %
+ unifiedRateLimitFallbackAvailable: boolean,
+ isUsingOverage: boolean,
+}
+```
+
+`rateLimitType` maps to exactly the limit types real users see: `"five_hour"` → *"session limit"* (this is what produced the 97% banner), `"seven_day"` → *"weekly limit"*, `"seven_day_opus"` / `"seven_day_sonnet"` → per-model weekly limits, `"overage"` → *"extra usage"*.
+
+The literal banner text the user saw is generated by a UI-only string formatter reading exactly this object:
+```
+`You've used ${pct}% of your ${limitName} · resets ${resetTimeStr}`
+```
+confirmed via direct string match in the bundle.
+
+### Finding 2 — the data is sourced from real Anthropic API response headers
+
+The state object is populated by parsing actual HTTP response headers on `/v1/messages` calls:
+
+```
+anthropic-ratelimit-unified-status
+anthropic-ratelimit-unified-reset
+anthropic-ratelimit-unified-fallback
+anthropic-ratelimit-unified-representative-claim
+anthropic-ratelimit-unified-overage-status
+anthropic-ratelimit-unified-overage-reset
+anthropic-ratelimit-unified-overage-disabled-reason
+anthropic-ratelimit-unified-upgrade-paths
+anthropic-ratelimit-unified-{type}-utilization (per rateLimitType)
+```
+
+This confirms the signal is genuine server-side rate-limit telemetry, not a client-side heuristic Claude Code invented.
+
+### Finding 3 — this state is NOT exposed through any current extension point
+
+Checked exhaustively, with empirical verification (not just documentation reading):
+
+| Extension point | Result |
+|---|---|
+| **statusLine stdin JSON** | Confirmed absent. The only fields present (verified against ruflo's own `statusline.cjs` parser, which already reads this payload) are `model.display_name`, `context_window.used_percentage`, `cost.total_cost_usd`, `cost.total_duration_ms`. No rate-limit field exists in this schema today. |
+| **Hook events** | 28 hook event names exist in the bundle (`PreToolUse`, `PostToolUse`, `Notification`, `SessionStart`, `SessionEnd`, `Stop`, `PreCompact`, etc.). None is documented or confirmed to fire on a rate-limit status change. A `Notification` hook exists generically but its trigger conditions for this specific case could not be confirmed from the bundle in the time available — worth testing empirically, not confirmed either way. |
+| **Debug logs** | Empirically checked: `~/.claude/debug/latest` (an existing 11,424-line debug log from a real prior session) contains **zero** occurrences of `anthropic-ratelimit`, even at the default debug log level. The headers are read and discarded internally; they are not logged even in the debug artifact. |
+| **CLI command / MCP resource** | None found. |
+| **React UI hook (`v96()`)** | Exists, but it's an internal React hook wired into Claude Code's own ink/TUI rendering — not reachable from outside Claude Code's process. |
+
+### Conclusion
+
+**Detecting Claude Code's actual usage-limit state from outside its process is not currently possible through any documented or discovered mechanism.** The signal exists and is real, but Claude Code does not surface it. This is a hard blocker on the literal ask ("detect the usage limit"), not a ruflo implementation gap.
+
+This finding should NOT be treated as permanent — Anthropic could add this to the statusLine schema or a hook payload in a future release, and the exact identifiers above will very likely be renamed/reshuffled on any Claude Code version bump (this is a minified bundle inspected for research purposes, not a stable API ruflo should build automated tooling directly against).
+
+## Decision
+
+Ship this in three phases. Phase 0 is real, useful, and buildable today. Phase 1 is a documented dependency on Anthropic shipping a capability ruflo cannot build itself. Phase 2 is the actual downtime-prevention UX, unblocked once Phase 1 lands.
+
+### Phase 0 — ship now: opt-in, self-reported "I'm rate limited" signal
+
+Since ruflo cannot detect the real signal, give the user (or a wrapper script they control) an explicit way to flip a local state flag when they notice the banner themselves:
+
+```bash
+ruflo settings notices rate-limited # user manually flags: "I just got rate-limited"
+ruflo settings notices rate-limited --clear # clears it (also auto-clears after a TTL)
+```
+
+This reuses the exact `credit-notifier.ts` pattern already shipped in ADR-311/ADR-303 (`markCreditExhausted` / `clearCreditStatus` / `*Notice()`) — a new sibling module `rate-limit-notifier.ts` with:
+- `markRateLimited(rateLimitType, resetsAt?, now)` — persists `~/.ruflo/rate-limit-status.json`
+- `clearRateLimitStatus(now)`
+- `rateLimitNotice(now)` — user-facing single line, same shape as `creditExhaustedNotice()`
+- A TTL (default 6h) so a stale manual flag doesn't linger forever if the user forgets to clear it
+
+The statusline promo row, when this flag is set, overrides normal rotation with a dedicated CTA (server-served per ADR-311 — a new `class: 'rate-limit'` message class, same content pipeline, same click-tracking, same "zero local content" discipline) pointing at `cognitum.one`'s meta-LLM proxy setup flow.
+
+This is honest about being manual/self-reported — it is NOT automatic detection, and should be labeled as such in any UI copy (e.g. `ruflo settings notices rate-limited` help text should say "tell ruflo you've hit a Claude usage limit" not "ruflo detected...").
+
+### Phase 1 — blocked on upstream: request the real signal from Claude Code
+
+File the concrete ask (as a Claude Code feature request / GitHub issue against `anthropics/claude-code`, not something ruflo can implement unilaterally): expose the internal rate-limit state via **either**:
+
+- (a) A new field on the existing statusLine stdin JSON, e.g.:
+ ```json
+ { "rate_limit": { "status": "allowed_warning", "type": "five_hour", "utilization_pct": 97, "resets_at": 1783720200 } }
+ ```
+- (b) A new hook event fired on rate-limit status transitions, e.g. `RateLimitStatusChanged`, with the same payload shape.
+
+Either is sufficient; (a) is simpler for Claude Code to ship since the statusLine hook already re-renders on a fast cadence and the data already exists in the process that spawns it.
+
+**Do not build speculative detection against the current minified bundle's internal variable/function names** (`Lv`, `di1`, `xI4`, etc.) — those are not a stable interface, will silently break on any Claude Code version bump, and reverse-engineering them further to build a production dependency would be fragile in a way that actively hurts users when it breaks (a stale/wrong rate-limit banner is worse than none). This research exists to ground THIS ADR's decision, not to become load-bearing production code.
+
+### Phase 2 — once Phase 1 lands: the real downtime-prevention UX
+
+With a real, Anthropic-sanctioned signal available:
+
+1. **Detection** — `rotation.ts` (or a new `rate-limit-gate.ts`) reads the real `rate_limit` field from the statusline JSON each render.
+2. **Threshold logic** — surface the CTA when `status === "allowed_warning"` (approaching) OR `status === "rejected"` (hit). Different copy for each (per the existing `messages.ts` class discipline — new classes `rate-limit-warning` / `rate-limit-exhausted`, remote-served, same content pipeline).
+3. **Priority override** — a rate-limit CTA should preempt the normal 4:1 educational:promotional rotation (this is directly analogous to how ADR-303's credit-exhaustion recovery surface already overrides normal rotation — reuse that precedent, don't invent a new priority system).
+4. **Consent gate** — the CTA itself is fine to show unconditionally (informational: "you're rate limited, here's an alternative") since it's not tracking anything by showing it; the *click* still routes through the existing consent-gated attribution/click-tracking pipeline (ADR-311 §7) exactly like any other promo.
+5. **Event vocabulary** — add `rate_limit_warning_shown` / `rate_limit_exhausted_shown` to the closed event set (`types.ts` `FunnelEventName`), following the exact pattern `promo_impression`/`promo_open` already established.
+6. **Auto-clear** — once `status` returns to `"allowed"` in a subsequent render, the override lifts automatically; no manual clear needed (Phase 0's manual flag becomes redundant once Phase 1 ships, but should stay as a fallback for any user manually invoking it in the interim, or for other agent-harness integrations that don't have Phase 1 data).
+
+## Consequences
+
+- **Phase 0 ships a real, if manual, capability today** — no dependency on Anthropic, reuses proven ADR-303 patterns, small diff.
+- **The literal ask ("detect approaching or met") is NOT achievable automatically without Phase 1.** This ADR is explicit about that rather than shipping a fragile heuristic (e.g., scraping stdout for the banner string, or guessing from `context_window.used_percentage` — which measures a completely different thing, context window fill, not usage/rate limit) that would silently produce wrong signals and erode trust exactly the way ADR-301's copy discipline was designed to avoid.
+- **This ADR should be revisited** the moment Claude Code ships any version of Phase 1's data — at that point Phase 2 is a small, mechanical extension of the existing rotation/promo/click-tracking machinery, not a new subsystem.
+
+## References
+
+- [ADR-301: Promotional status surface](ADR-301-promotional-status-surface.md)
+- [ADR-303: Credit-exhaustion experience](ADR-303-credit-exhaustion-experience.md) — the priority-override + notifier pattern this Phase 0/2 design reuses verbatim
+- [ADR-311: Funnel analytics endpoint deployment](ADR-311-funnel-analytics-endpoint-deployment.md) — the remote message feed, click-tracking, and "zero local content" discipline this design extends
+- Upstream: `anthropics/claude-code` — Phase 1's feature request target (not yet filed)
diff --git a/v3/docs/adr/ADR-313-sponsored-downtime-proxy-mode.md b/v3/docs/adr/ADR-313-sponsored-downtime-proxy-mode.md
new file mode 100644
index 0000000000..522dafe9e5
--- /dev/null
+++ b/v3/docs/adr/ADR-313-sponsored-downtime-proxy-mode.md
@@ -0,0 +1,168 @@
+# ADR-313: Sponsored downtime mode — free Cognitum capacity during rate limits
+
+- **Status:** Proposed
+- **Date:** 2026-07-10
+- **Deciders:** ruflo core
+- **Related:** [ADR-304](ADR-304-local-meta-llm-proxy.md) (proxy product), [ADR-307](ADR-307-proxy-runtime-packaging-lifecycle.md) (proxy runtime), [ADR-303](ADR-303-credit-exhaustion-experience.md) (credit-exhaustion recovery pattern this reuses), [ADR-312](ADR-312-usage-limit-downtime-prevention.md) (usage-limit detection research this depends on), [ADR-309](ADR-309-funnel-governance-privacy-ecosystem.md) (consent/privacy discipline)
+
+## Context
+
+ADR-304/307 already define the Meta LLM Proxy product and its Rust runtime. ADR-312 established that Claude Code does not currently expose a way to *automatically* detect an approaching or exhausted usage limit, and proposed a phased plan: a manual self-reported flag now (Phase 0), an upstream capability request (Phase 1), and full automatic detection once that lands (Phase 2).
+
+This ADR adds a new, orthogonal capability to the proxy itself: **sponsored downtime**. When a user tells ruflo (via the Phase 0 flag, or eventually the Phase 2 automatic signal) that they've hit a Claude usage limit, the Meta LLM Proxy can route their traffic through Cognitum's own model capacity **at Cognitum's expense, not the user's** — free, time-boxed, rate-limited on Cognitum's side to bound cost exposure — so the user can keep working in ruflo/Claude Code until their own Claude quota resets.
+
+This is explicitly a **marketing-and-goodwill product**, not a credit-purchase upsell (that's already ADR-303's job). The framing is: *"Free capacity sponsored by Cognitum.one — keep working while you wait for your Claude limit to reset."*
+
+## Decision
+
+### New proxy capability: sponsored mode
+
+The Meta LLM Proxy (ADR-304/307, Rust binary, `127.0.0.1:11435`) gains a **sponsored-mode** on top of its existing local/cloud routing:
+
+```
+Client (Claude Code / any OpenAI-compatible SDK)
+ ↓
+localhost:11435 (existing ADR-304/307 proxy)
+ ↓
+ ├─ normal mode: local backends OR user's own cloud-routing (ADR-304, unchanged)
+ └─ sponsored mode: api.cognitum.one/v1/sponsor/* (NEW — this ADR)
+ ↓
+ Cognitum-hosted model capacity, billed to Cognitum, not the user
+```
+
+Sponsored mode is a **distinct data-plane state**, not a variant of the existing `local` / `cloud:<provider>` states — `ruflo proxy status` reports it as a third value: `sponsored:cognitum`. This keeps ADR-304's data-plane disclosure invariant intact: a request receipt always says exactly which plane handled it.
+
+### Activation
+
+Sponsored mode requires **all** of:
+
+1. **Explicit consent** — a new consent domain, `sponsored-downtime`, alongside the existing `account` / `proxy-install` / `telemetry` / `cloud-routing` / `hosted-memory` domains (ADR-302). Granted once via `ruflo proxy sponsor-enable`, which shows the disclosure text below before asking.
+2. **A rate-limited signal** — either the Phase 0 manual flag (`ruflo settings notices rate-limited`, ADR-312) or, once it exists, the real Phase 1/2 automatic signal. Sponsored mode auto-activates ONLY while this flag is set; it deactivates automatically when the flag clears (manually, or on its TTL).
+3. **The proxy installed and running** (ADR-307 lifecycle). If not installed, the CTA offers `ruflo proxy install` first.
+
+Sponsored mode is never silently entered. The pre-activation disclosure (mirroring ADR-304 §"Data-plane disclosure"):
+
+```
+Enabling sponsored downtime mode.
+
+While your Claude usage limit resets, requests can be routed through
+Cognitum's own model capacity, sponsored at no cost to you. This is a
+separate data plane from your own cloud-routing config — Cognitum sees
+these prompts (server-side, same handling as any api.cognitum.one
+request), never your own Claude account.
+
+Sponsored capacity is rate-limited and best-effort — Cognitum may throttle
+or decline requests under load. Disable anytime: ruflo proxy sponsor-disable.
+
+Enable sponsored downtime mode? [y/N]
+```
+
+Default answer is No, same as every other consent gate in this system (ADR-302/309 discipline).
+
+### Server-side: rate limiting Cognitum's own exposure
+
+`cognitum-one/meta-proxy` (the Rust binary repo ADR-307 already calls for as a consequence) implements the client half; the sponsored-mode backend lives in the existing `cognitum-one/ruflo-funnel-api` Cloud Function family (or a sibling function) with:
+
+- **Per-user daily/hourly sponsored-token ceiling** — mirrors the existing `funnel_credit` ceiling pattern already shipped in ADR-311's Cloud Function (`checkCreditBudget`/`bumpCreditCounter`), but keyed to a distinct `funnel_sponsored_usage` collection so sponsored consumption never touches or inflates the user's real Cognitum credit ledger.
+- **Global daily cap** — a circuit breaker independent of per-user ceilings, so a traffic spike can't blow Cognitum's sponsorship budget; when tripped, sponsored mode returns a clear `SPONSORED_CAPACITY_EXHAUSTED` error and the proxy falls back to whatever the user's normal (non-sponsored) routing would have done.
+- **Model selection is Cognitum's to make**, not the user's — sponsored mode intentionally does not let the client pick the model; a cheap-tier model keeps the sponsorship sustainable. This is stated plainly in the disclosure and in `ruflo proxy status` output.
+
+### Client wiring (ruflo)
+
+- `funnel/rate-limit-notifier.ts` (ADR-312 Phase 0) — new module, exact structural mirror of `credit-notifier.ts`: `markRateLimited()` / `clearRateLimitStatus()` / `rateLimitNotice()`, state at `~/.ruflo/rate-limit-status.json`.
+- `ruflo settings notices rate-limited [--clear]` — the manual flag command (ADR-312).
+- `ruflo proxy sponsor-enable` / `ruflo proxy sponsor-disable` / `ruflo proxy sponsor-status` — new subcommands under the existing `ruflo proxy` command family (ADR-307), following its exact lifecycle-command conventions.
+- **Statusline priority override** — when `rate-limited` is flagged AND `sponsored-downtime` consent is granted AND the proxy is running, the funnel promo row (ADR-301/311 rotation) is preempted by a dedicated CTA, exactly the way ADR-303's credit-exhaustion recovery already preempts normal rotation. Two states:
+ - Sponsored mode available but not yet enabled: *"⚡ Free Cognitum capacity available while you wait → ruflo proxy sponsor-enable"*
+ - Sponsored mode active: *"⚡ Running on sponsored Cognitum capacity · resets when your Claude limit does"*
+- **Event vocabulary** — `sponsor_mode_enabled` / `sponsor_mode_disabled` / `sponsor_capacity_exhausted` added to the closed `FunnelEventName` set (ADR-305/309 discipline), following the exact pattern `promo_impression`/`promo_open` established in ADR-311.
+
+### Repository
+
+**`cognitum-one/meta-proxy`** (private) — the Rust proxy binary ADR-307 already specifies as a "new repository/workspace" consequence. This ADR is the trigger to actually create it. Scope of the initial scaffold:
+
+- `axum`-based OpenAI-compatible HTTP server (`/v1/chat/completions`, `/v1/models`, `/status`)
+- Bind `127.0.0.1:11435` per ADR-307, loopback-only by default
+- Per-user bearer token at `~/.ruflo/proxy-token` (`0600`), required on every request
+- `/v1/sponsor/chat/completions` — the sponsored-mode route, forwards to `api.cognitum.one` with a distinct auth header (`X-Cognitum-Sponsored: true`) so the server side can apply the sponsored ceiling independently of the user's own credit ledger
+- `/status` reports `{ data_plane: "local" | "cloud:<provider>" | "sponsored:cognitum", version, proxy_token_valid }`
+- Config file `~/.ruflo/proxy-config.toml`: bind address, default data plane, sponsored-mode consent flag mirror (source of truth stays client-side in ruflo's consent store; the proxy reads it, never writes it)
+
+### Addendum (2026-07-10): the wire protocol had to be Anthropic's, not OpenAI's
+
+The initial scaffold above (`/v1/chat/completions`, `/v1/sponsor/chat/completions`) shipped
+before anyone verified the claim in this ADR's title against the actual Claude Code binary.
+Direct inspection of the installed CLI showed it POSTs `{ANTHROPIC_BASE_URL}/v1/messages`
+(the Anthropic Messages API), authenticating with `Authorization: Bearer <ANTHROPIC_AUTH_TOKEN>`,
+defaulting to `stream: true` — never the OpenAI chat-completions shape the scaffold assumed.
+As built, every Claude Code request through the proxy would have 404'd.
+
+The proxy now also serves `POST /v1/messages` — the endpoint Claude Code actually calls, with
+JSON and SSE-streaming passthrough and a `cognitum_api_key` config field forwarded as `x-api-key`
+to `cognitum_api_base` (Cognitum's gateway requires this on both Cloud and Sponsored calls; there
+was previously no way to authenticate to it at all). Because Claude Code has no way to select a
+data plane per request — it only ever calls this one path — the plane decision moved server-side:
+`/v1/messages` reads `~/.ruflo/rate-limit-status.json` directly (same file, same 6h TTL ruflo's
+own reader applies) and activates the Sponsored plane automatically whenever
+`sponsored_consent_granted` is set and the flag is currently active, falling back to
+`default_data_plane` the instant it clears. The original OpenAI-shaped routes are unchanged and
+still served, for any non-Claude-Code client that wants them.
+
+Verified live end-to-end (2026-07-10): the real installed Claude Code CLI, pointed at the fixed
+proxy via `ANTHROPIC_BASE_URL`/`ANTHROPIC_AUTH_TOKEN`, completed real requests through to the live
+`apicompletions` Cloud Run service and back — both plain JSON and SSE streaming, both the normal
+plane and the rate-limit-triggered sponsored override, and confirmed the override reverting once
+the flag cleared.
+
+Still open: there is no automated way for `ruflo proxy sponsor-enable` to provision a real,
+per-user, scoped `cognitum_api_key` — the field must be populated manually today. Minting a
+sponsored-tier key automatically on enable is server-side work (Cognitum key-issuance) tracked as
+follow-up, not blocking today's fix.
+
+### Addendum (2026-07-10): a fourth data plane — Passthrough, now the default
+
+The fix above still left a real gap, surfaced by direct question rather than found proactively:
+none of Local/Cloud/Sponsored routes to the user's own Anthropic subscription. Setting
+`ANTHROPIC_BASE_URL`/`ANTHROPIC_AUTH_TOKEN` — required to reach this proxy at all — makes Claude
+Code stop managing its own Max/Pro OAuth session entirely for as long as they're set (confirmed in
+the installed CLI's own source: the literal string `"Unset the environment variable to use your
+subscription instead"`). So with the proxy in the loop, **every** request bypassed the user's paid
+subscription, all the time — not just during the rate-limited window this feature exists for.
+
+Added `DataPlane::Passthrough`, now `default_data_plane`'s default value: the proxy reads Claude
+Code's own `~/.claude/.credentials.json` (read-only, never modified) and forwards unaltered to the
+real `https://api.anthropic.com/v1/messages` using the actual OAuth access token —
+`Authorization: Bearer <token>` plus `anthropic-beta: oauth-2025-04-20`, the exact mechanism Claude
+Code itself uses, merged with any beta flags the client already sent (e.g. prompt-caching). The
+proxy never attempts an OAuth refresh itself — an expired token fails Passthrough closed with a
+message pointing at a normal (non-proxied) `claude` run to refresh it, rather than reimplementing
+Anthropic's private refresh flow.
+
+Net effect: with the proxy always in the loop (`ANTHROPIC_BASE_URL` permanently set), a single
+continuous Claude Code session now gets genuine per-request dynamic behavior — real subscription
+usage by default, live diversion to Cognitum sponsored capacity the moment the rate-limit flag is
+set, and an automatic revert to the subscription the instant it clears. No session restart needed
+at either transition. Verified live: Passthrough returns a real Anthropic response using the actual
+subscription token (confirmed via response fields — `cache_creation`, `service_tier` — that only
+real Anthropic returns, never Cognitum); the sponsored/passthrough transition was verified in both
+directions within one running proxy process.
+
+OpenAI-shaped `/v1/chat/completions`/`/v1/sponsor/chat/completions` have no Anthropic↔OpenAI
+translator and treat Passthrough as Local — moot today since only `/v1/messages` is reachable from
+Claude Code.
+
+## Consequences
+
+- Sponsored mode is a **goodwill / acquisition feature**, and its entire cost-control burden sits server-side (Cognitum's ceiling + circuit breaker) — the client never needs to reason about Cognitum's sponsorship budget, only about the boolean "is sponsored mode currently available/active."
+- This ADR does **not** solve ADR-312's core detection gap — sponsored mode activation still depends on the same Phase 0 manual flag (or a future Phase 1/2 automatic signal) that ADR-312 already scoped. When Phase 1 lands, sponsored mode's activation trigger upgrades automatically; no change needed here.
+- New closed-vocabulary events and a new consent domain are additive, backwards-compatible extensions of ADR-302/305/309's existing schemas — no breaking change to any already-shipped funnel surface.
+- `ruflo doctor --component proxy` (ADR-307) gains a sponsored-mode health check: consent state, rate-limited flag state, and last-known sponsored-capacity-exhausted timestamp.
+
+## References
+
+- [ADR-304: Local Meta LLM Proxy Product](ADR-304-local-meta-llm-proxy.md)
+- [ADR-307: Proxy Runtime, Packaging, and Service Lifecycle](ADR-307-proxy-runtime-packaging-lifecycle.md)
+- [ADR-303: Credit-Exhaustion Experience](ADR-303-credit-exhaustion-experience.md) — the priority-override UX pattern this design reuses
+- [ADR-312: Usage-Limit Downtime Prevention](ADR-312-usage-limit-downtime-prevention.md) — the detection research and phased plan this activates on top of
+- [ADR-311: Funnel Analytics Endpoint Deployment](ADR-311-funnel-analytics-endpoint-deployment.md) — the credit-ceiling pattern the sponsored-usage ceiling mirrors
+- Server repo: `cognitum-one/meta-proxy` (private, created by this ADR)
diff --git a/v3/docs/adr/ADR-314-power-saver-mode-and-sponsored-abuse-prevention.md b/v3/docs/adr/ADR-314-power-saver-mode-and-sponsored-abuse-prevention.md
new file mode 100644
index 0000000000..179a204100
--- /dev/null
+++ b/v3/docs/adr/ADR-314-power-saver-mode-and-sponsored-abuse-prevention.md
@@ -0,0 +1,170 @@
+# ADR-314: Power saver mode (auto-route lesser requests) + sponsored-capacity abuse prevention
+
+- **Status**: Proposed
+- **Date**: 2026-07-10
+- **Deciders**: ruv
+- **Related**: [ADR-304](ADR-304-local-meta-llm-proxy.md), [ADR-307](ADR-307-proxy-runtime-packaging-lifecycle.md), [ADR-312](ADR-312-usage-limit-downtime-prevention.md), [ADR-313](ADR-313-sponsored-downtime-proxy-mode.md)
+
+## Context
+
+Two requests, and they turn out to share a root cause:
+
+1. "Include a power saver mode: if your Claude Code Max/Pro account is below 20%, auto-route
+ lesser requests that don't need the extra intelligence to the meta-llm."
+2. "Include anti-cheating and abuse capabilities" for the sponsored-capacity system ADR-313 built.
+
+The connection: widening the trigger for routing through Cognitum (from "only when actually
+rate-limited" to "proactively, whenever quota looks low") widens the abuse surface at the same
+time. This ADR designs both together rather than bolting anti-abuse on afterward.
+
+**A constraint carries over directly from ADR-312 and has to be stated up front:** ruflo cannot
+read "your account is at 20%." ADR-312 already established, by direct inspection of the installed
+Claude Code CLI, that rate-limit/quota state is populated from response headers
+(`anthropic-ratelimit-unified-status`, `-utilization`, etc.) that are **not exposed** to hooks, the
+statusline JSON payload, or anywhere else a third-party CLI extension can read. That finding
+applies unchanged here — "20%" can't be measured any more precisely than "rate-limited or not" can
+be. Building this as if the number were readable would ship something that silently never
+activates, or activates on a fabricated value. The design below is honest about that gap.
+
+## Decision
+
+### A. Power saver mode is self-reported, not measured (Phase 0, same pattern as ADR-312)
+
+`ruflo settings notices quota-low [--clear]` sets a manual flag — structurally identical to
+`rate-limited` in `rate-limit-notifier.ts`, same 6h TTL, same file-based mechanism
+(`~/.ruflo/quota-status.json`). This is **not** automatic detection; it's the same honest
+workaround ADR-312 already shipped for the binary case, generalized to a second, lower-severity
+signal: "not blocked yet, but I want to start conserving." A future Phase 1/2 (per ADR-312) that
+gets real quota data from Anthropic would replace the self-report with a real threshold check —
+no design here depends on staying manual forever.
+
+Separate flag from `rate-limited` deliberately: "I'm running low" (proactive, user still has
+capacity) and "I'm blocked" (reactive, zero capacity left) are different urgencies with different
+correct responses — conflating them would mean either power-saver mode never fires until you're
+already blocked (too late to have saved anything) or a false-rate-limited claim silently piggybacks
+onto power-saver's less-scrutinized activation path.
+
+### B. Power saver mode routes through the Cloud plane with the model rewritten to `cognitum-auto`
+
+This is the part that makes "auto-route lesser requests" actually work without ruflo building its
+own prompt-difficulty classifier — Cognitum's gateway already has one, and it exists for exactly
+this purpose (ADR-201's cost-Pareto thesis, `docs/ARCHITECTURE.md` in the meta-llm repo: "cheap
+traffic stays cheap and only the hard tail escalates").
+
+**The mechanism that makes this necessary, not just convenient**: Cognitum's `/v1/messages`
+translation adapter maps a *named* Anthropic model to a tier by name — opus→high, sonnet→mid,
+haiku→low (confirmed reading `src/routes/messages.ts` in the meta-llm repo). The existing
+Cloud/Sponsored planes in the proxy forward whatever model Claude Code requested, unchanged. Since
+a Claude Code session runs on one model for its whole lifetime (typically opus or sonnet, chosen
+once, not varied per-message by task complexity), forwarding the *name* verbatim would map to the
+*same* tier — usually high — on every single request. That is not cost savings; it just moves the
+same spend to a different biller. Power saver mode instead rewrites the outgoing `model` field to
+the literal string `cognitum-auto` before forwarding, so Cognitum's real per-prompt difficulty
+scorer (not a name lookup) decides low/mid/high per request. Everyday messages get cheap; a
+genuinely hard reasoning turn still escalates to a comparable frontier model — that's the "lesser
+requests... don't need the extra intelligence" distinction, made by the router that already exists
+for it, not reimplemented client-side.
+
+Power saver mode uses the **Cloud** plane (the user's own `cognitum_api_key`, their own Cognitum
+account/billing) — **not** Sponsored. This is the user choosing to spend their own Cognitum credit
+to conserve their own Anthropic quota; it is not free capacity, and shouldn't share Sponsored's
+"billed to Cognitum, not you" framing or its abuse surface. A user can independently also be
+rate-limited and sponsored-consented; if both apply, Sponsored wins (ADR-313's existing precedence
+is unchanged — being actually blocked outranks proactively conserving).
+
+### C. Sponsored capacity is now capped at low/mid tier, never high — a direct abuse-surface fix
+
+Independent of power saver mode, this closes a real gap in the shipped ADR-313 sponsored plane:
+today it forwards the client's requested model name unchanged, which (per the mapping above) means
+a session running on opus forwards as `high` tier every time — Cognitum's *most expensive* tier,
+on *Cognitum's own dime*, for every sponsored request, with no client-side ceiling. **Sponsored
+requests now always rewrite `model` to a fixed low/mid-capable alias, never a tier that can resolve
+to a frontier/high-cost model**, regardless of what Claude Code originally requested. This bounds
+Cognitum's worst-case per-request exposure on the free plane independent of anything else in this
+ADR, and independent of whether the difficulty scorer itself could ever be gamed into
+over-escalating (see the vector list below) — the cap holds even if the scorer is fooled, because
+the tier ceiling is enforced before the scorer's decision is even relevant.
+
+### D. Anti-abuse: the vectors, ranked, and what's buildable now vs. blocked on Cognitum-side work
+
+Ranked by severity — most severe first:
+
+1. **Fabricated rate-limited/quota-low claims for free Sponsored capacity — the most severe, and
+ currently the ONLY thing standing between "opt-in for genuine downtime" and "unlimited free
+ inference on request."** Phase 0 detection (ADR-312) is entirely self-reported with zero
+ server-side verification; nothing today distinguishes an honest user who actually hit their
+ limit from someone who runs `ruflo proxy sponsor-enable --yes` once and never looks back.
+ - **Buildable now (this ADR ships it)**: a cooldown on the `rate-limited`/`quota-low` toggle
+ commands — no more than one flip per 10 minutes each. Cheap, purely client-side friction; it
+ doesn't stop a determined abuser but it stops casual/accidental always-on gaming and raises
+ the bar on scripted abuse.
+ - **Blocked on Cognitum-side work**: per-identity sponsored quotas (see #2) are the real fix —
+ a cooldown only slows down abuse from a single identity; it can't cap total abuse without a
+ stable per-user identity to cap it *against*.
+2. **The shared/unattributable API key.** ADR-313's addendum already flagged this as open: there
+ is no automated way to provision a real, per-user, scoped `cognitum_api_key` — every sponsored
+ user today would share one key (in this session's testing, `COGNITUM_TEST_API_KEY`). A shared
+ key means zero per-user accountability, no way to revoke one abuser without cutting off
+ everyone, and unlimited blast radius if it ever leaks. **This is the prerequisite for
+ meaningfully addressing #1, #4, and #5 below — it is Cognitum-backend work (a key-minting
+ endpoint `sponsor-enable` calls on first activation), not something this proxy or ruflo's CLI
+ can build unilaterally.** Flagging it here as the single highest-priority follow-up, not
+ re-flagging it as "still fine to defer indefinitely."
+3. **Power-saver's own difficulty-scorer gaming.** A user could pad trivial prompts to trick
+ Cognitum's scorer into escalating to a costlier tier than the content warrants. On the **Cloud**
+ plane this is the user spending *their own* credit inefficiently — not a security abuse vector,
+ just a self-defeated feature, out of scope to defend against. The reason this is listed at all:
+ the same gaming, if it ever applied to **Sponsored** traffic, WOULD be a real abuse vector
+ (tricking free capacity into the expensive tier) — which is exactly why mitigation C above
+ (hard tier ceiling, enforced before the scorer runs) matters independent of whether the scorer
+ itself can be foxed.
+4. **Proxy config/token copied across machines to multiply effective throughput.** Buildable
+ server-side once #2 lands: per-key concurrent-request and requests/minute caps (not just a
+ daily $ cap) bound this regardless of how many machines share one key.
+5. **Scripted volume abuse — pure spam against the shared sponsored pool, no benefit to the
+ attacker beyond degrading the pool for everyone.** Same fix as #4: per-key rate limiting,
+ Cognitum-side, blocked on #2.
+6. **Sponsored anonymity as a lower-accountability vector for policy-violating content.**
+ Recommend Cognitum's existing opt-in `safety:scan` guardrail layer (documented in the meta-llm
+ repo) become **mandatory**, not opt-in, specifically on Sponsored-plane traffic — pseudonymous
+ free capacity is exactly the surface this class of abuse would target. Cognitum-backend policy
+ change, not a proxy change.
+
+### E. What ships in this ADR's implementation vs. what's tracked as follow-up
+
+**Ships now** (ruflo + meta-proxy, no Cognitum backend changes required):
+- `ruflo settings notices quota-low [--clear]` — the power-saver self-report flag
+- `power-saver` consent domain (mirrors `sponsored-downtime`'s pattern exactly)
+- Proxy: Cloud-plane model rewrite to `cognitum-auto` when power-saver is active and Sponsored
+ isn't (precedence: Sponsored > Power-saver > default Passthrough)
+- Proxy: Sponsored-plane model rewrite to a fixed low/mid-only alias, always, independent of
+ power-saver — this is a standalone hardening fix to the already-shipped ADR-313 plane
+- Cooldown (10 min) on `rate-limited`/`quota-low` flag toggles
+
+**Tracked as follow-up, explicitly not solvable from ruflo's side alone:**
+- Per-user Cognitum key minting (the real fix for abuse vectors #1, #2, #4, #5)
+- Per-key concurrent-request / requests-per-minute caps (Cognitum backend)
+- Mandatory safety-scan on Sponsored traffic (Cognitum backend policy)
+
+## Consequences
+
+- Power saver mode's actual value depends entirely on Cognitum's difficulty scorer being good —
+ this ADR does not re-litigate or re-verify that scorer's accuracy, it just routes to it.
+- The Sponsored tier cap (C) is a behavior change to the already-shipped ADR-313 plane: sponsored
+ users lose access to high-tier models entirely, unconditionally. This is intentional — sponsored
+ capacity was never framed as "free frontier access," and ADR-313's own text already describes it
+ as "best-effort... Cognitum may throttle or decline requests under load."
+- Every mitigation ranked "blocked on Cognitov-side work" above means the abuse-prevention story
+ for Sponsored mode remains genuinely incomplete until that work lands — this ADR does not claim
+ Sponsored mode is abuse-proof, only that it is more bounded than before (D3) and that the
+ concrete missing piece is named (D2), not hand-waved.
+- No change to the Passthrough plane (ADR-313 addendum) — power saver mode and its abuse surface
+ are additive, not a replacement for "normal usage still means your own subscription by default."
+
+## References
+
+- [ADR-304: Local Meta LLM Proxy Product](ADR-304-local-meta-llm-proxy.md)
+- [ADR-307: Proxy Runtime, Packaging, and Service Lifecycle](ADR-307-proxy-runtime-packaging-lifecycle.md)
+- [ADR-312: Usage-Limit Downtime Prevention](ADR-312-usage-limit-downtime-prevention.md) — the detection-gap constraint this ADR inherits unchanged
+- [ADR-313: Sponsored Downtime Mode](ADR-313-sponsored-downtime-proxy-mode.md) — the plane this ADR hardens (tier cap) and extends (power saver's Cloud-plane sibling)
+- meta-llm `src/routes/messages.ts`, `docs/ARCHITECTURE.md` — the difficulty-based tier router this design routes to rather than reimplements
diff --git a/v3/docs/adr/ADR-315-free-user-flywheel-training-pipeline.md b/v3/docs/adr/ADR-315-free-user-flywheel-training-pipeline.md
new file mode 100644
index 0000000000..aead0f3686
--- /dev/null
+++ b/v3/docs/adr/ADR-315-free-user-flywheel-training-pipeline.md
@@ -0,0 +1,149 @@
+# ADR-315: Self-optimizing flywheel — training meta-llm from free/sponsored-user traffic
+
+- **Status**: Partially implemented — ruflo-side (Tier 2 client wiring) shipped 2026-07-11; meta-llm-side (consent-gated capture + scheduled tick) not started, tracked separately in meta-llm's own scope
+- **Date**: 2026-07-10
+- **Deciders**: ruv
+- **Related**: [ADR-313](ADR-313-sponsored-downtime-proxy-mode.md), [ADR-314](ADR-314-power-saver-mode-and-sponsored-abuse-prevention.md), meta-llm's [ADR-251](https://github.com/cognitum-one/meta-llm/blob/main/docs/adr/ADR-251-microlora-flywheel-service.md) (`POST /v1/microlora/evolve` — the training mechanism this ADR feeds, not reinvents)
+
+## Implementation status (2026-07-11)
+
+**ruflo client-side wiring — shipped**: `training-data-sharing` consent domain
+(`src/funnel/types.ts`/`consent.ts`), `ruflo proxy training-share-enable/-disable/-status`
+(`src/commands/proxy.ts`), `training_share_enabled/disabled` funnel events. Mirrors the
+ADR-313/314 pattern exactly — never bundled with `sponsored-downtime`, its own disclosure text,
+its own `training_share_consent_granted` mirror field in `proxy-config.toml`.
+
+**meta-proxy header relay — not yet implemented**: the Sponsored-plane
+`X-Cognitum-Training-Consent: true` header (reading the `training_share_consent_granted` mirror
+flag, omitted entirely rather than sent `false`) is still open work in `cognitum-one/meta-proxy`'s
+`src/routes/messages.rs`.
+
+**meta-llm consent-gated capture + scheduled tick — not started**: this is meta-llm's own scope
+per the "Server-side" section below; nothing in this ADR's client-side work depends on it existing
+yet — the header is emitted (once meta-proxy adds it) whether or not anything downstream reads it.
+
+## Context
+
+"Create a self-optimizing flywheel to optimize and train meta-llm based on free users."
+
+**This is not a new training mechanism to build — meta-llm already has one, shipped.** ADR-251
+(meta-llm) built `POST /v1/microlora/evolve`: a real MicroLoRA/SONA adaptation service that takes
+`qualitySignal` + `interactionSummaries` as input, runs a round through the frozen, packaged
+`@metaharness/flywheel` promotion gate (`meetsPromotionRule`), and produces a SHADOW candidate that
+an operator promotes separately — never auto-serves an unverified adaptation. That machinery is
+real, tested (26 tests, full suite 1126/1126 at ship time), and running today.
+
+**What's actually missing, and what this ADR scopes, is two things:**
+1. A consent-gated pipeline that turns real sponsored/free-tier traffic into the
+ `interactionSummaries` input ADR-251's service already accepts — today nothing feeds it that
+ automatically; it's called on-demand, by hand.
+2. A scheduled trigger that calls it periodically instead of manually — meta-llm already proved
+ this exact pattern for the pod loop (`terraform/pods_scheduler.tf`, Cloud Scheduler cron
+ driving a tick job) — reuse it, don't invent a second scheduling mechanism.
+
+This ADR lives in **meta-proxy** per the request, but its center of gravity is properly
+server-side (meta-llm) — meta-proxy's own scope here is narrow and specific: it is the boundary
+that knows a request is sponsored AND knows the client's consent state, so it's the natural place
+to attach (or withhold) the training-data signal before the request ever reaches Cognitum. The
+scheduler, the ledger aggregation, and the actual `/v1/microlora/evolve` calls are meta-llm's job,
+already built, referenced but not re-specified here.
+
+### The tension this ADR has to resolve honestly, not paper over
+
+Every consent-and-privacy decision in this whole system so far (ADR-302, ADR-305, ADR-309) has
+converged on one rule: closed vocabularies, daily-not-precise timestamps, **no raw prompt/command/
+path content, ever** — that's ruflo's own local telemetry, and it's permanent by ADR-309's own
+wording. Training a model (even via MicroLoRA's lightweight rank-1–4 adaptation) is fundamentally
+different from that telemetry: it needs actual interaction *content* — prompts, completions, or at
+minimum content-derived quality signals — to produce any adaptation worth shipping. Metadata alone
+(latency, tier, cache hit/miss) is exactly what the EXISTING flywheel (ADR-251's macro-loop
+precursor, `src/flywheel/`) already uses for routing-parameter calibration, and that part needs no
+new consent — it's using data Cognitum already necessarily touches to serve the request at all, for
+a purpose (improving the router that serves that same traffic) already implicit in operating the
+service. **Content-based training is not that** — it's a second, materially different data use, and
+this ADR treats it as such: a separate, explicit, never-bundled consent domain, exactly like every
+other consent decision in this codebase.
+
+## Decision
+
+### Two tiers, two different consent bars — do not conflate them
+
+**Tier 1 — Routing calibration (metadata only, already covered by ADR-251's precursor flywheel).**
+No new consent needed: this uses usage-ledger data (tier resolved, latency, escalation, cache
+hit/miss, tool-use presence, success signal — never prompt/completion text) that Cognitum already
+necessarily processes to serve any request. Sponsored/free traffic is simply MORE of the same
+input this flywheel already ingests for every tier — nothing new to build here beyond, optionally,
+weighting sponsored-traffic volume appropriately in the aggregation (it's zero-marginal-cost data
+from Cognitum's side, unlike paid traffic, so there's no reason to exclude it; that's a meta-llm
+`src/flywheel/` tuning question, not a new pipeline).
+
+**Tier 2 — Content-based MicroLoRA training (the actual "train meta-llm" ask).** Feeding real
+prompt/completion content (or content-derived `interactionSummaries`) into `/v1/microlora/evolve`
+requires a **new, separate, opt-in-only consent domain — `training-data-sharing`** — that is:
+- **Never bundled with `sponsored-downtime` consent.** Using free capacity must not implicitly mean
+ donating your prompts for training; these remain two separate decisions, exactly like every other
+ consent pair in this system.
+- **Disclosed in plain language before grant**, mirroring `SPONSOR_DISCLOSURE`'s pattern: what data
+ (interaction content, not just metadata), what it's used for (MicroLoRA adaptation candidates,
+ gated through the existing SHADOW/promotion-rule safety net — never auto-served), and that
+ declining has zero effect on sponsored-capacity access.
+- **Passed through the SAME opt-in `safety:scan` PII/secret-detection layer** the meta-llm README
+ already documents, as a mandatory pre-training filter on this specific data path (not opt-in here
+ — training data specifically warrants it, independent of whether a given caller has that scope
+ enabled elsewhere).
+- **Revocable**, with a real deletion story: revoking consent stops future capture; ADR-315's
+ implementation must also define how a user requests deletion of already-captured interaction data
+ before it's folded into a training round (a real, not just documented, story — this is the part
+ most likely to be treated as a checkbox and skipped, so it's called out explicitly here as a
+ requirement, not a nice-to-have).
+
+### Client-side (meta-proxy's actual scope)
+
+- New consent domain wired the same way `sponsored-downtime` and `power-saver` are (ADR-313/314
+ pattern): `ruflo proxy training-share-enable/-disable/-status`, its own disclosure text, its own
+ `power_saver`-shaped consent mirror field (`training_share_consent_granted`) in
+ `proxy-config.toml`.
+- When a request is on the Sponsored plane AND `training_share_consent_granted` is true, the proxy
+ adds `X-Cognitum-Training-Consent: true` alongside the existing `X-Cognitum-Sponsored: true`
+ header. Absent or false → header omitted entirely (not sent as `false` — an omitted header is a
+ clearer "no" than a spoofable boolean value a bug could flip).
+- No other proxy behavior changes — no request/response shape changes, no new data captured or
+ buffered client-side. The proxy is a consent-signal relay here, nothing more; meta-llm decides
+ what to do with the header entirely server-side.
+
+### Server-side (meta-llm — named here as the dependency, not specified in full; that's meta-llm's
+own ADR to write against ADR-251)
+
+- `X-Cognitum-Training-Consent: true` on an inbound request is meta-llm's signal to retain that
+ interaction (post safety-scan) as flywheel training input; its absence means the interaction is
+ used exactly as today — served, metered, and NOT retained for training.
+- A new scheduled tick (Cloud Scheduler, same pattern as `pods_scheduler.tf`) periodically batches
+ accumulated consented interactions into `interactionSummaries` and calls the EXISTING
+ `/v1/microlora/evolve` — this ADR does not change that service's own safety posture
+ (SHADOW-only, `meetsPromotionRule`-gated, human-promoted) in any way; the new work is purely
+ "where the input now comes from and on what cadence," not "how adaptation or promotion works."
+
+## Consequences
+
+- Tier 1 (routing calibration) ships with effectively no new privacy surface — it's an existing
+ system consuming more of the same kind of data it already consumes.
+- Tier 2 (content training) is real new surface, and this ADR is deliberately conservative about
+ it: opt-in only, never bundled, safety-scanned, revocable with an actual deletion path. If any of
+ those four properties can't be delivered at implementation time, Tier 2 should not ship until
+ they can — this is the one place in the whole sponsored-downtime feature family where getting the
+ consent story wrong has consequences beyond a UX papercut.
+- This ADR deliberately does NOT re-specify `/v1/microlora/evolve`, its promotion gate, or its
+ lineage/replay verification — all of that is ADR-251's, shipped, and unchanged. Duplicating that
+ design here would risk the two documents drifting out of sync with the real implementation.
+- Add to the implementation loop as: (1) meta-proxy consent wiring + header (small, self-contained,
+ same shape as ADR-313/314's client work), (2) meta-llm consent-gated capture + scheduled tick
+ (larger, backend work, meta-llm's own scope to design and ship against this ADR + ADR-251).
+
+## References
+
+- [ADR-313: Sponsored Downtime Mode](ADR-313-sponsored-downtime-proxy-mode.md)
+- [ADR-314: Power Saver Mode + Abuse Prevention](ADR-314-power-saver-mode-and-sponsored-abuse-prevention.md) — the consent-domain and disclosure pattern this ADR reuses exactly
+- meta-llm ADR-251 (MicroLoRA flywheel service) — the training mechanism this ADR feeds
+- meta-llm `src/flywheel/`, `docs/ARCHITECTURE.md` §"Flywheel — assumed → measured" — the existing metadata-only routing calibration (Tier 1)
+- meta-llm `terraform/pods_scheduler.tf` — the scheduled-tick pattern the new training cadence should reuse, not reinvent
+- ADR-309 (ruflo) — the "no raw prompt content, ever" constraint this ADR explicitly distinguishes itself from (that's ruflo's own local telemetry; this is Cognitum's server-side training pipeline, a different data flow with its own, separately-designed consent bar)
diff --git a/v3/docs/adr/ADR-316-advisor-copilot-tip-insight-ticker.md b/v3/docs/adr/ADR-316-advisor-copilot-tip-insight-ticker.md
new file mode 100644
index 0000000000..1d7c17602b
--- /dev/null
+++ b/v3/docs/adr/ADR-316-advisor-copilot-tip-insight-ticker.md
@@ -0,0 +1,79 @@
+# ADR-316: Fable co-pilot advisor tip in the statusline insight ticker
+
+- **Status**: Implemented
+- **Date**: 2026-07-11
+- **Deciders**: ruv
+- **Related**: [ADR-172](ADR-172-fable-advisor-harness.md) (the cost-disciplined Fable harness this ADR reuses, not reinvents), the local insight ticker built earlier this session (`src/funnel/insights.ts`, priority-ordered candidates: CVEs pending, uncommitted changes, power-saver active, flywheel status), [ADR-313](ADR-313-sponsored-downtime-proxy-mode.md)/[ADR-314](ADR-314-power-saver-mode-and-sponsored-abuse-prevention.md)/[ADR-315](ADR-315-free-user-flywheel-training-pipeline.md) (the consent-domain pattern this ADR follows exactly)
+
+## Context
+
+"Integrate ruflo's copilot advisor into the promo ticker."
+
+There is no existing "ruflo copilot advisor" feature — grounded against the real corpus (RuvNet Brain `search_ruvnet`, direct source reads), the closest real, shipped primitive is **ADR-172's Fable Advisor Harness** (`src/services/fable-harness.ts`): a cost-disciplined, opt-in, budget-capped headless `claude -p --model claude-fable-5` judge/reflector, currently consumed only by the memory-distillation oracle (`distill-oracle.ts`) for judging trajectory completions and GEPA reflective mutation. Nothing wires it into the statusline. `ADR-147` (Copilot SDK adapter) and `agent-harness-generator`'s Copilot-as-host ADR are both unrelated — different products (GitHub Copilot integration, a third agent platform), not an advisor tip.
+
+This ADR is the missing wiring: reuse the existing Fable harness to generate ONE proactive, actionable tip and surface it through the local insight ticker already built this session — without violating either subsystem's existing invariants:
+
+- The insight ticker (`insights.ts`) is deliberately synchronous, local, $0 — its own doc comment states "NEVER a network call from here." A Fable call is a real network-bound `claude -p` spawn with real cost, so it categorically cannot live in the ticker's hot path.
+- ADR-309's "no raw prompt/command/path content, ever" bar is about a *different* data flow (ruflo's own telemetry) but the same discipline applies here for a different reason: anything sent to Fable is visible to that model call, so the query must never carry raw session content — only the same closed set of structural signals the ticker already surfaces (security scan status, swarm state, git-uncommitted count).
+- ADR-172's harness is OFF by default and spends nothing unless a budget cap is explicitly configured — this feature must preserve that (a new, separate, never-bundled consent domain, exactly like every other decision in this feature family).
+
+## Decision
+
+### Data flow
+
+```
+consent + 24h TTL gate (advisor-tip.ts)
+ │ (only when both pass)
+ ▼
+FableHarness.adviseCoPilotTip(structuralSnapshot) [services/fable-harness.ts]
+ │ writes
+ ▼
+~/.ruflo/advisor-tip.json { _ts, headline, detail }
+ │ read synchronously, $0, no network
+ ▼
+insights.ts's advisorTipInsight() → local insight ticker → statusline
+```
+
+### 1. `FableHarness.adviseCoPilotTip()` (services/fable-harness.ts)
+
+A third entry point alongside `judgeBatch`/`reflectFailures`, same cost/cwd/parsing discipline (fresh empty temp cwd, `--append-system-prompt`, `--max-budget-usd`, stdin-piped payload — never an argv positional). Takes a `CoPilotSnapshot` (security status, swarm state, git-uncommitted count, context-window %) and returns one `CoPilotTip { headline, detail, confidence }` or `null`. The system prompt explicitly instructs the model: no prompt/command/file content is present in the input, never invent facts not present in the snapshot, and an empty array is a valid "nothing worth saying" answer — not a parse failure.
+
+### 2. `funnel/advisor-tip.ts` — the safety wrapper
+
+Three hard gates before any spend:
+1. **Consent** — new `advisor-tips` domain (`types.ts`/`consent.ts`), never bundled with `sponsored-downtime`/`power-saver`/`training-data-sharing` or anything else.
+2. **TTL** — `readStateJson`-backed cache, checked BEFORE constructing the harness. At most one real spend per `ADVISOR_REFRESH_TTL_MS` (24h) regardless of session count. A "no tip" answer still stamps `_ts` so the same question isn't re-asked (and re-billed) within the same window.
+3. **Budget** — `ADVISOR_DEFAULT_BUDGET_USD` (0.40 — a single unbatched call uses the ~$0.34 clean-cwd cost anchor, not the ~$0.02 batched anchor which only applies across ~20 items), overridable via `RUFLO_ADVISOR_MAX_BUDGET_USD`, enforced by FableHarness's own `--max-budget-usd` pass-through to the real `claude -p` call.
+
+### 3. CLI surface (`src/commands/advisor.ts`)
+
+`ruflo advisor enable --yes` / `disable` / `status`, mirroring the disclosure-then-confirm shape of `proxy.ts`'s sponsored/power-saver/training-share subcommands. Unlike those, `advisor` has **no proxy-config.toml mirror** — this feature never touches the meta-proxy Rust binary; it calls `claude -p` directly, client-side only. Registered as its own top-level lazy-loaded command (`commands/index.ts`), not nested under `proxy`.
+
+### 4. Background refresh wiring (mirrors the ADR-311 promo-cache fix exactly)
+
+`ruflo hooks refresh-advisor` (new subcommand in `commands/hooks.ts`, alongside the existing `refresh-funnel`) builds a snapshot via the shared `funnel/local-signals.ts` helpers (see below) and calls `refreshAdvisorTipIfStale`. `hook-handler.cjs`'s `session-restore` handler spawns this **detached + unref'd**, same pattern as `spawnDetachedFunnelRefresh` — this is load-bearing: a fire-and-forget call from a short-lived subprocess never completes (the exact bug the promo-cache fix addressed earlier this session), so the refresh needs a properly-awaited, longer-lived invocation. Safe to call unconditionally on every session-restore: the TTL/consent checks inside `refreshAdvisorTipIfStale` make an unconsented or already-fresh install a fast local file read, never a network call.
+
+### 5. Shared structural-signal extraction (`funnel/local-signals.ts`, new)
+
+`getSecurityStatus()`, `getSwarmStatus()`, `getGitUncommittedCount()` were previously private closures inside `commands/hooks.ts`'s `statuslineCommand` action. Extracted to a shared module so the statusline and the (separately-invoked) `refresh-advisor` CLI subcommand can never silently drift on what these signals mean — a single source of truth, same behavior, zero duplication.
+
+### 6. Insight ticker wiring (`insights.ts`)
+
+`advisorTipInsight()` — priority 45 (between uncommitted-changes at 50 and flywheel-status at 40) — re-checks `hasConsent('advisor-tips')` even though it's just reading a cache: this is what actually enforces "disable means off" the instant a user revokes consent, without needing to also delete the cache file on disable.
+
+## A real bug found and fixed along the way
+
+Both `advisor-tip.ts`'s `isCacheStale`/`readAdvisorTip` and the pre-existing `flywheelInsight` in `insights.ts` used `!cache._ts` to check for a missing timestamp. Since `0` is falsy in JS, a legitimate `_ts: 0` (epoch) is indistinguishable from "no timestamp at all" — surfaced by a test using `new Date(0)` for a deterministic clock. Fixed in both places: `typeof cache._ts !== 'number'`. Benign in production (`Date.now()` is never 0), but a real latent defect, now closed in both call sites since it's the identical pattern.
+
+## Consequences
+
+- Reuses ADR-172's harness exactly as designed — no new cost-discipline primitive invented, no duplicate `claude -p` wrapper.
+- The one insight source in the whole ticker family that spends real money and makes a real network call is isolated behind three independent gates (consent, TTL, budget), any one of which alone would make runaway spend impossible.
+- `local-signals.ts` extraction is a pure refactor (no behavior change) that removes a source of future drift between the statusline and any other consumer of the same structural signals.
+- Not addressed here (future work, if ever wanted): a settings surface to tune `ADVISOR_REFRESH_TTL_MS` per-user, or feeding `contextPctUsed` into the snapshot (the type field exists in `CoPilotSnapshot` but nothing populates it yet — deliberately left for a future iteration rather than wiring a rough estimate now).
+
+## References
+
+- [ADR-172: Fable Advisor Harness](ADR-172-fable-advisor-harness.md) — the harness this ADR wires up, unchanged in its own cost model
+- [ADR-315: Free-user flywheel training pipeline](ADR-315-free-user-flywheel-training-pipeline.md) — the consent-domain pattern (`training-data-sharing`) this ADR's `advisor-tips` domain mirrors exactly
+- `src/funnel/insights.ts` — the local insight ticker this ADR adds a fifth source to
diff --git a/v3/docs/adr/README.md b/v3/docs/adr/README.md
index 7fbd97e326..413c7651aa 100644
--- a/v3/docs/adr/README.md
+++ b/v3/docs/adr/README.md
@@ -29,6 +29,16 @@ All ADRs are located in [`/v3/implementation/adrs/`](../../implementation/adrs/)
| [ADR-046](../../implementation/adrs/ADR-046-ruflo-rebrand.md) | Dual Umbrella: claude-flow + ruflo | Accepted |
| [ADR-047](../../implementation/adrs/ADR-047-fast-mode-integration.md) | Fast Mode Integration | Proposed |
| [ADR-178](ADR-178-dream-cycle-security-vmg-repe-ipi.md) | Verifiable Memory Governance and RepE IPI Detection | Proposed |
+| [ADR-301](ADR-301-promotional-status-surface.md) | Promotional Status Surface for CLI Runtime | Proposed |
+| [ADR-302](ADR-302-post-init-capability-enrollment.md) | Post-Initialization Capability Enrollment | Proposed |
+| [ADR-303](ADR-303-credit-exhaustion-experience.md) | Intelligent Credit Exhaustion Experience | Proposed |
+| [ADR-304](ADR-304-local-meta-llm-proxy.md) | Local Meta LLM Proxy Product | Proposed |
+| [ADR-305](ADR-305-customer-lifecycle-funnel.md) | Customer Lifecycle Funnel (RuFlo → Cognitum) | Proposed |
+| [ADR-306](ADR-306-cognitum-authentication-account-linking.md) | Cognitum Authentication and Account Linking | Proposed |
+| [ADR-307](ADR-307-proxy-runtime-packaging-lifecycle.md) | Proxy Runtime, Packaging, and Service Lifecycle | Proposed |
+| [ADR-308](ADR-308-cognitum-public-api-contract.md) | Cognitum Public API and Server Contract | Proposed |
+| [ADR-309](ADR-309-funnel-governance-privacy-ecosystem.md) | Funnel Governance, Privacy, and Ecosystem Policy | Proposed |
+| [ADR-310](ADR-310-funnel-rollout-measurement-emergency-controls.md) | Funnel Rollout, Measurement, and Emergency Controls | Proposed |
## Summary Documents
diff --git a/v3/docs/api/cognitum-v1.openapi.yaml b/v3/docs/api/cognitum-v1.openapi.yaml
new file mode 100644
index 0000000000..e87ec91a37
--- /dev/null
+++ b/v3/docs/api/cognitum-v1.openapi.yaml
@@ -0,0 +1,343 @@
+openapi: 3.1.0
+# ADR-308 — Cognitum Public API and Server Contract (v1).
+# This spec is the cross-organization boundary: it is checked into BOTH the
+# ruflo repository (this file) and the Cognitum server repository; CI in both
+# validates against it, and drift fails the build. Breaking changes require
+# /v2 with a documented overlap window.
+info:
+ title: Cognitum Public API
+ version: 1.0.0
+ description: >
+ Public contract between the open-source ruflo CLI / local Meta LLM proxy
+ and api.cognitum.one. Client failure policy is normative (ADR-308):
+ auth unavailable → local ruflo keeps working; telemetry unavailable →
+ drop or bounded local queue, never block the CLI; funnel policy
+ unavailable → last valid signed policy, else package default; proxy
+ backend unavailable → error to caller, never silent rerouting; deletion
+ unavailable → durable receipt + server-side retry.
+servers:
+ - url: https://api.cognitum.one
+security:
+ - bearerAuth: []
+paths:
+ /v1/auth/device:
+ post:
+ operationId: startDeviceAuthorization
+ summary: Start an RFC 8628 device authorization flow (ADR-306)
+ security: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [client_id, scope]
+ properties:
+ client_id: { type: string }
+ scope:
+ type: string
+ description: >
+ Space-separated scopes. Requested incrementally; each maps
+ 1:1 onto an ADR-302 consent domain (account.create,
+ proxy.use, cloud.route, telemetry.write, hosted.memory.use).
+ responses:
+ '200':
+ description: Device code issued
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [device_code, user_code, verification_uri, expires_in, interval]
+ properties:
+ device_code: { type: string }
+ user_code: { type: string }
+ verification_uri: { type: string, format: uri }
+ expires_in: { type: integer }
+ interval: { type: integer }
+ '429': { $ref: '#/components/responses/RateLimited' }
+ /v1/auth/token:
+ post:
+ operationId: exchangeToken
+ summary: Exchange a device/authorization code or refresh token (ADR-306)
+ security: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [grant_type]
+ properties:
+ grant_type:
+ type: string
+ enum: [urn:ietf:params:oauth:grant-type:device_code, authorization_code, refresh_token]
+ device_code: { type: string }
+ code: { type: string }
+ code_verifier: { type: string, description: PKCE verifier }
+ refresh_token: { type: string }
+ responses:
+ '200':
+ description: >
+ Token issued. Access-token lifetime is 10–15 minutes (ADR-306).
+ Responses carry the terms/privacy policy versions in force; a
+ version beyond the client's recorded consent receipt forces
+ re-consent (ADR-302 policyVersion rules).
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [access_token, token_type, expires_in, policy_versions]
+ properties:
+ access_token: { type: string }
+ token_type: { type: string, enum: [Bearer] }
+ expires_in: { type: integer, minimum: 600, maximum: 900 }
+ refresh_token: { type: string }
+ scope: { type: string }
+ policy_versions: { $ref: '#/components/schemas/PolicyVersions' }
+ '400': { $ref: '#/components/responses/ApiError' }
+ '429': { $ref: '#/components/responses/RateLimited' }
+ /v1/auth/revoke:
+ post:
+ operationId: revokeToken
+ summary: Revoke a refresh token / session (ruflo auth logout)
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [token]
+ properties:
+ token: { type: string }
+ responses:
+ '200': { description: Revoked (idempotent — revoking a revoked token succeeds) }
+ /v1/events:
+ post:
+ operationId: ingestFunnelEvents
+ summary: Ingest funnel events (ADR-305/309 — consent-gated, idempotent)
+ description: >
+ Requires telemetry.write scope. Retention guarantee is contractual:
+ raw events ≤ 90 days, aggregates only thereafter (no identifiers in
+ aggregates). Events must conform to the closed ADR-309 schema —
+ daily/hourly timestamp buckets, no prompts/paths/repo names.
+ parameters:
+ - name: Idempotency-Key
+ in: header
+ required: true
+ schema: { type: string, format: uuid }
+ description: Client-generated per batch; retries never double-count.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [events]
+ properties:
+ events:
+ type: array
+ maxItems: 100
+ items: { $ref: '#/components/schemas/FunnelEvent' }
+ responses:
+ '202': { description: Accepted }
+ '401': { $ref: '#/components/responses/ApiError' }
+ '429': { $ref: '#/components/responses/RateLimited' }
+ /v1/events/{subject_id}:
+ delete:
+ operationId: deleteFunnelEvents
+ summary: Verifiable deletion of a pseudonymous subject's raw events (ADR-309)
+ parameters:
+ - name: subject_id
+ in: path
+ required: true
+ schema: { type: string, format: uuid }
+ description: The pseudonymous funnel ID (printable via `ruflo funnel id`).
+ responses:
+ '200':
+ description: Deletion completed; durable receipt returned
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [receipt_id, deleted]
+ properties:
+ receipt_id: { type: string }
+ deleted: { type: boolean }
+ '202':
+ description: >
+ Deletion queued (service degraded) — durable receipt returned and
+ the server retries until confirmed (ADR-308 failure policy).
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [receipt_id]
+ properties:
+ receipt_id: { type: string }
+ /v1/funnel-policy:
+ get:
+ operationId: getFunnelPolicy
+ summary: Signed funnel policy feed (ADR-305 freshness kill switch — opt-in only)
+ security: []
+ description: >
+ Ed25519-signed, schema-validated policy DATA — never executable code.
+ Clients validate signature + schema before honoring anything; invalid
+ → discarded entirely, last valid signed policy (or package default)
+ stays in force. A policy can only DISABLE surfaces below the local
+ precedence chain; enables expire after ttl_hours (max 24).
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [policy, signature, key_id]
+ properties:
+ policy:
+ type: object
+ required: [schemaVersion, funnelEnabled, issued_at, ttl_hours]
+ properties:
+ schemaVersion: { type: integer, const: 1 }
+ funnelEnabled: { type: boolean }
+ disabledSurfaces:
+ type: array
+ items: { type: string, enum: [statusline, init, credit_exhaustion] }
+ issued_at: { type: string, format: date-time }
+ ttl_hours: { type: integer, minimum: 1, maximum: 24 }
+ signature: { type: string, description: Ed25519 over canonical policy JSON }
+ key_id: { type: string }
+ description: Current signed policy
+ /v1/proxy/chat/completions:
+ post:
+ operationId: proxyChatCompletions
+ summary: OpenAI-compatible cloud routing (ADR-304/307)
+ description: >
+ Requires cloud.route scope backed by the ADR-302 cloud-routing consent
+ receipt. Responses carry a request receipt: metered cost + resolved
+ tier/model + data plane, in-band. Backend unavailability returns an
+ error — the proxy never silently reroutes to another paid provider.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [model, messages]
+ properties:
+ model: { type: string, description: 'Concrete model or routing alias (cognitum-auto|low|mid|high)' }
+ messages: { type: array, items: { type: object } }
+ additionalProperties: true
+ responses:
+ '200':
+ description: Completion with request receipt
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ receipt: { $ref: '#/components/schemas/RequestReceipt' }
+ additionalProperties: true
+ '402':
+ description: Credit exhaustion — the ONLY source of COGNITUM_CREDIT_EXHAUSTED
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/ApiErrorBody' }
+ '429': { $ref: '#/components/responses/RateLimited' }
+ /v1/credits:
+ get:
+ operationId: getCredits
+ summary: Credit balances — the single credit authority (ADR-303)
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [daily_remaining, daily_limit, resets_at]
+ properties:
+ daily_remaining: { type: integer }
+ daily_limit: { type: integer }
+ resets_at: { type: string, format: date-time }
+ description: Current balances
+ '401': { $ref: '#/components/responses/ApiError' }
+components:
+ securitySchemes:
+ bearerAuth:
+ type: http
+ scheme: bearer
+ responses:
+ ApiError:
+ description: Machine-readable error (codes map 1:1 to the ADR-303 client taxonomy)
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/ApiErrorBody' }
+ RateLimited:
+ description: Rate limited — limits documented per endpoint and echoed in headers
+ headers:
+ Retry-After: { schema: { type: integer } }
+ X-RateLimit-Limit: { schema: { type: integer } }
+ X-RateLimit-Remaining: { schema: { type: integer } }
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/ApiErrorBody' }
+ schemas:
+ ApiErrorBody:
+ type: object
+ required: [error]
+ properties:
+ error:
+ type: object
+ required: [code, message]
+ properties:
+ code:
+ type: string
+ description: >
+ Machine-readable code — clients classify on THIS, never on
+ message text (ADR-303). Canonical set mirrors the client
+ enum.
+ enum:
+ - cognitum_credit_exhausted
+ - insufficient_quota
+ - rate_limit_exceeded
+ - authentication_error
+ - permission_error
+ - service_unavailable
+ - invalid_request
+ message: { type: string }
+ retryable: { type: boolean }
+ PolicyVersions:
+ type: object
+ required: [terms, privacy]
+ properties:
+ terms: { type: integer }
+ privacy: { type: integer }
+ RequestReceipt:
+ type: object
+ required: [cost_usd, tier, model, data_plane]
+ properties:
+ cost_usd: { type: number }
+ tier: { type: string }
+ model: { type: string }
+ data_plane:
+ type: string
+ description: '"local" or "cloud:<provider>" — visible per request (ADR-304)'
+ FunnelEvent:
+ type: object
+ description: Closed ADR-309 schema — extending the event enum requires an ADR amendment.
+ required: [schemaVersion, event, surface, release, timestampBucket]
+ additionalProperties: false
+ properties:
+ schemaVersion: { type: integer, const: 1 }
+ event:
+ type: string
+ enum: [disclosure_shown, funnel_disabled, signup_opened, account_created, proxy_activated]
+ surface:
+ type: string
+ enum: [statusline, init, credit_exhaustion]
+ release: { type: string }
+ region: { type: string, description: Coarse, self-declared only }
+ pseudonymousId: { type: string, format: uuid }
+ timestampBucket:
+ type: string
+ pattern: '^\d{4}-\d{2}-\d{2}(T\d{2})?$'
+ description: Daily (default) or hourly bucket — full timestamps are rejected.
diff --git a/v3/package.json b/v3/package.json
index ae71564b59..c0d86531a9 100644
--- a/v3/package.json
+++ b/v3/package.json
@@ -70,7 +70,14 @@
"@vitest/coverage-v8": ">=4.1.0",
"handlebars": ">=4.7.9",
"protobufjs": ">=8.6.0",
- "@ruvector/ruvllm": ">=2.6.0"
+ "@ruvector/ruvllm": ">=2.6.0",
+ "js-yaml": ">=4.3.0",
+ "express": ">=4.22.2",
+ "qs": ">=6.15.2",
+ "@opentelemetry/core": ">=2.8.0",
+ "@opentelemetry/resources": ">=2.8.0",
+ "@opentelemetry/sdk-trace-base": ">=2.8.0",
+ "@opentelemetry/sdk-node": ">=0.220.0"
}
}
}
diff --git a/v3/pnpm-lock.yaml b/v3/pnpm-lock.yaml
index 025dc0a050..218e3e03d3 100644
--- a/v3/pnpm-lock.yaml
+++ b/v3/pnpm-lock.yaml
@@ -16,6 +16,13 @@ overrides:
handlebars: '>=4.7.9'
protobufjs: '>=8.6.0'
'@ruvector/ruvllm': '>=2.6.0'
+ js-yaml: '>=4.3.0'
+ express: '>=4.22.2'
+ qs: '>=6.15.2'
+ '@opentelemetry/core': '>=2.8.0'
+ '@opentelemetry/resources': '>=2.8.0'
+ '@opentelemetry/sdk-trace-base': '>=2.8.0'
+ '@opentelemetry/sdk-node': '>=0.220.0'
importers:
@@ -36,13 +43,13 @@ importers:
version: 5.9.3
vitest:
specifier: '>=4.1.0'
- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
'@claude-flow/aidefence':
dependencies:
agentdb:
specifier: '>=2.0.0-alpha.1'
devDependencies:
'@types/node':
specifier: ^20.10.0
@@ -102,7 +109,7 @@ importers:
version: 5.9.3
vitest:
specifier: '>=4.1.0'
- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
'@claude-flow/cli':
dependencies:
@@ -197,7 +204,7 @@ importers:
version: 5.9.3
vitest:
specifier: '>=4.1.0'
- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
'@claude-flow/deployment':
dependencies:
@@ -210,7 +217,7 @@ importers:
version: 25.0.2([email protected])
vitest:
specifier: '>=4.1.0'
- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
'@claude-flow/embeddings':
dependencies:
@@ -260,7 +267,7 @@ importers:
version: 5.9.3
vitest:
specifier: '>=4.1.0'
- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
'@claude-flow/hooks':
dependencies:
@@ -292,7 +299,7 @@ importers:
version: 5.9.3
vitest:
specifier: '>=4.1.0'
- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
'@claude-flow/integration':
dependencies:
@@ -317,8 +324,8 @@ importers:
specifier: ^2.8.5
version: 2.8.5
express:
- specifier: ^4.18.2
- version: 4.22.1
+ specifier: '>=4.22.2'
+ version: 5.2.1
helmet:
specifier: ^7.1.0
version: 7.2.0
@@ -337,7 +344,7 @@ importers:
version: 8.18.1
vitest:
specifier: '>=4.1.0'
- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
'@claude-flow/memory':
dependencies:
@@ -386,7 +393,7 @@ importers:
devDependencies:
vitest:
specifier: '>=4.1.0'
- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
'@claude-flow/plugin-agent-federation':
dependencies:
@@ -436,7 +443,7 @@ importers:
version: 5.9.3
vitest:
specifier: '>=4.1.0'
- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
'@claude-flow/plugins':
dependencies:
@@ -464,7 +471,7 @@ importers:
version: 5.9.3
vitest:
specifier: '>=4.1.0'
- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
'@claude-flow/providers':
dependencies:
@@ -489,7 +496,7 @@ importers:
version: 5.9.3
vitest:
specifier: '>=4.1.0'
- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
'@claude-flow/security':
dependencies:
@@ -505,7 +512,7 @@ importers:
devDependencies:
vitest:
specifier: '>=4.1.0'
- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
'@claude-flow/shared':
dependencies:
@@ -532,14 +539,14 @@ importers:
specifier: ^2.8.5
version: 2.8.5
express:
- specifier: ^4.21.0
- version: 4.22.1
+ specifier: '>=4.22.2'
+ version: 5.2.1
helmet:
specifier: ^7.1.0
version: 7.2.0
vitest:
specifier: '>=4.1.0'
- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
ws:
specifier: ^8.16.0
version: 8.19.0
@@ -551,7 +558,7 @@ importers:
devDependencies:
vitest:
specifier: '>=4.1.0'
- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
'@claude-flow/testing':
devDependencies:
@@ -569,7 +576,7 @@ importers:
version: 5.9.3
vitest:
specifier: '>=4.1.0'
- version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
packages:
@@ -729,7 +736,7 @@ packages:
dependencies:
ajv: 8.18.0
cors: 2.8.6
- express: 4.22.1
+ express: 5.2.1
helmet: 7.2.0
ws: 8.20.0
transitivePeerDependencies:
@@ -1014,7 +1021,7 @@ packages:
globals: 13.24.0
ignore: 5.3.2
import-fresh: 3.3.1
- js-yaml: 4.1.1
+ js-yaml: 5.2.1
minimatch: 3.1.2
strip-json-comments: 3.1.1
transitivePeerDependencies:
@@ -1966,8 +1973,8 @@ packages:
dev: false
optional: true
- /@opentelemetry/[email protected]:
- resolution: {integrity: sha512-fmEWp5kXlGEc3i/lR698Hz41DfGyN4Tbe4g7L1AxSc7fF8Xeh/FQ9Quqpa9dVA413Q1Ad43QOLzU4JoXgbFPWw==}
+ /@opentelemetry/[email protected]:
+ resolution: {integrity: sha512-CmVa4ImJ+ynfrPMNaAXHET6Bhb44SwzmfyVJFq9ni2jgXJR/l7C6gfVFddNmHP+ZOkP9cf4f9DBe68qVLTHc9w==}
engines: {node: '>=8.0.0'}
requiresBuild: true
dependencies:
@@ -2045,8 +2052,8 @@ packages:
'@opentelemetry/resource-detector-azure': 0.2.12(@opentelemetry/[email protected])
'@opentelemetry/resource-detector-container': 0.3.11(@opentelemetry/[email protected])
'@opentelemetry/resource-detector-gcp': 0.29.13(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.30.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-node': 0.52.1(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-node': 0.220.0(@opentelemetry/[email protected])
transitivePeerDependencies:
- encoding
- supports-color
@@ -2105,29 +2112,42 @@ packages:
'@opentelemetry/resource-detector-azure': 0.2.12(@opentelemetry/[email protected])
'@opentelemetry/resource-detector-container': 0.3.11(@opentelemetry/[email protected])
'@opentelemetry/resource-detector-gcp': 0.29.13(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.30.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-node': 0.52.1(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-node': 0.220.0(@opentelemetry/[email protected])
transitivePeerDependencies:
- encoding
- supports-color
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-W8wIz7H2R1pufR5jfjb3gU2XkMpm2x/7b1RJcsuzvd70Il/rWWE+g5/Od7hQKrxRTSrTrOWlru101PWXz5I1EQ==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-glfIVKnZevRin8fY/9uES/mhRtMT1lGINLHc9MIo5fTQZXswEEHamJtgjv4MTtzgnhHGC92mIS/0lzAUZMyE0w==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ requiresBuild: true
+ peerDependencies:
+ '@opentelemetry/api': ^1.9.0
+ dependencies:
+ '@opentelemetry/api': 1.9.0
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ yaml: 2.9.0
+ dev: false
+ optional: true
+
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-glfIVKnZevRin8fY/9uES/mhRtMT1lGINLHc9MIo5fTQZXswEEHamJtgjv4MTtzgnhHGC92mIS/0lzAUZMyE0w==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': ^1.9.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
- yaml: 2.8.2
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ yaml: 2.9.0
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-UW/ge9zjvAEmRWVapOP0qyCvPulWU6cQxGxDbWEFfGOj1VBBZAuOqTo3X6yWmDTD3Xe15ysCZChHncr2xFMIfQ==}
- engines: {node: '>=14'}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-OQ0vzvbZBiUhjqLnUaoNfYmP8553Crr3aggB4y0ZUi815mZ7idpdJXQmoKdeBKJelYttoBlLSSHubmyw3wvX4w==}
+ engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': '>=1.0.0 <1.10.0'
@@ -2136,164 +2156,196 @@ packages:
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-UW/ge9zjvAEmRWVapOP0qyCvPulWU6cQxGxDbWEFfGOj1VBBZAuOqTo3X6yWmDTD3Xe15ysCZChHncr2xFMIfQ==}
- engines: {node: '>=14'}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-OQ0vzvbZBiUhjqLnUaoNfYmP8553Crr3aggB4y0ZUi815mZ7idpdJXQmoKdeBKJelYttoBlLSSHubmyw3wvX4w==}
+ engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': '>=1.0.0 <1.10.0'
dependencies:
'@opentelemetry/api': 1.9.1
+ optional: true
+
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-m2nckMT80NnmjTYSPjJQObBJ+8dgkoajEOUbznL8AHZ3T3yHRk2P7gI1PhEBc1+lOnrYE9UWrWHqJDsmqjmNbw==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ requiresBuild: true
+ peerDependencies:
+ '@opentelemetry/api': '>=1.0.0 <1.10.0'
+ dependencies:
+ '@opentelemetry/api': 1.9.0
+ '@opentelemetry/semantic-conventions': 1.40.0
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-OPFBYuXEn1E4ja3Y6eeA7O+ZnLBNcXTV5Cgsn1VaqBZ6hC5FnpZPLBNme1LJY8ZtF4aOujPKFoeWN4ik487KuQ==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-m2nckMT80NnmjTYSPjJQObBJ+8dgkoajEOUbznL8AHZ3T3yHRk2P7gI1PhEBc1+lOnrYE9UWrWHqJDsmqjmNbw==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': '>=1.0.0 <1.10.0'
dependencies:
'@opentelemetry/api': 1.9.1
+ '@opentelemetry/semantic-conventions': 1.40.0
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-GeT/l6rBYWVQ4XArluLVB6WWQ8flHbdb6r2FCHC3smtdOAbrJBIv35tpV/yp9bmYUJf+xmZpu9DRTIeJVhFbEQ==}
- engines: {node: '>=14'}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-s0sRPCSlXYqlgObOpCftomJllp3LfUL9FobQ5csg2172ydVhSEnu1ptpsVBJadazs5nUNp7vDuLE03FAFWTLOQ==}
+ engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
- '@opentelemetry/api': '>=1.0.0 <1.10.0'
+ '@opentelemetry/api': ^1.3.0
dependencies:
+ '@grpc/grpc-js': 1.14.3
'@opentelemetry/api': 1.9.0
- '@opentelemetry/semantic-conventions': 1.25.1
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-grpc-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-logs': 0.220.0(@opentelemetry/[email protected])
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-GeT/l6rBYWVQ4XArluLVB6WWQ8flHbdb6r2FCHC3smtdOAbrJBIv35tpV/yp9bmYUJf+xmZpu9DRTIeJVhFbEQ==}
- engines: {node: '>=14'}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-s0sRPCSlXYqlgObOpCftomJllp3LfUL9FobQ5csg2172ydVhSEnu1ptpsVBJadazs5nUNp7vDuLE03FAFWTLOQ==}
+ engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
- '@opentelemetry/api': '>=1.0.0 <1.10.0'
+ '@opentelemetry/api': ^1.3.0
dependencies:
+ '@grpc/grpc-js': 1.14.3
'@opentelemetry/api': 1.9.1
- '@opentelemetry/semantic-conventions': 1.25.1
- dev: false
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-grpc-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-logs': 0.220.0(@opentelemetry/[email protected])
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-OOCM2C/QIURhJMuKaekP3TRBxBKxG/TWWA0TL2J6nXUtDnuCtccy49LUJF8xPFXMX+0LMcxFpCo8M9cGY1W6rQ==}
- engines: {node: '>=14'}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-8186thl+pTw64iz/qEEen5oJZoZ/gO73XruChdaGlYdWOdBIQ42r+vHLf6a7vIDqTD4b8ZOoMlyxptanECaI9A==}
+ engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
- '@opentelemetry/api': '>=1.0.0 <1.10.0'
+ '@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/semantic-conventions': 1.28.0
+ '@opentelemetry/api-logs': 0.220.0
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-logs': 0.220.0(@opentelemetry/[email protected])
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-OOCM2C/QIURhJMuKaekP3TRBxBKxG/TWWA0TL2J6nXUtDnuCtccy49LUJF8xPFXMX+0LMcxFpCo8M9cGY1W6rQ==}
- engines: {node: '>=14'}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-8186thl+pTw64iz/qEEen5oJZoZ/gO73XruChdaGlYdWOdBIQ42r+vHLf6a7vIDqTD4b8ZOoMlyxptanECaI9A==}
+ engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
- '@opentelemetry/api': '>=1.0.0 <1.10.0'
+ '@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/semantic-conventions': 1.28.0
+ '@opentelemetry/api-logs': 0.220.0
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-logs': 0.220.0(@opentelemetry/[email protected])
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-QAqIj32AtK6+pEVNG7EOVxHdE06RP+FM5qpiEJ4RtDcFIqKUZHYhl7/7UY5efhwmwNAg7j8QbJVBLxMerc0+gw==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-8LZAxdJ0ENDAFwr4j0oY35mHBltiSzvlhdQAPGiC7p9VnxtuSq4SW1gfBAdW6t6hiQG6OwUl8w7KHaOdJPKHWg==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
- '@opentelemetry/api': '>=1.0.0 <1.10.0'
+ '@opentelemetry/api': ^1.3.0
dependencies:
- '@opentelemetry/api': 1.9.1
- '@opentelemetry/semantic-conventions': 1.40.0
+ '@opentelemetry/api': 1.9.0
+ '@opentelemetry/otlp-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-logs': 0.220.0(@opentelemetry/[email protected])
+ dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-hoxrNH1l/Xy6F9WTJ5IK+6j1r9nQFlPOmrnTlhYHTySdunfXLmUCPv3bQtKYntxag9h3wLYBZQ2HI6FOx+BT2g==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-8LZAxdJ0ENDAFwr4j0oY35mHBltiSzvlhdQAPGiC7p9VnxtuSq4SW1gfBAdW6t6hiQG6OwUl8w7KHaOdJPKHWg==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': ^1.3.0
dependencies:
- '@grpc/grpc-js': 1.14.3
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/otlp-exporter-base': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/otlp-grpc-exporter-base': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/otlp-transformer': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/sdk-logs': 0.218.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-logs': 0.220.0(@opentelemetry/[email protected])
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-Qx+4rpVHzgg89dawcWRHyt+XRXeLnhFz/qBtvggmjkcgPUdr+NAB0/u/eIPA8yAeJV0J80Vz43JZCh/XFvZFGw==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-U128izvJfX/dW9jRGP0gIfadR1Hg7ft3UEGIeRxLFK70m2BWw6AtNCOnsUygpw2zCgR/ygdWbGpcL6TmhW0ZGw==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': ^1.3.0
dependencies:
- '@opentelemetry/api': 1.9.1
- '@opentelemetry/api-logs': 0.218.0
- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/otlp-exporter-base': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/otlp-transformer': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/sdk-logs': 0.218.0(@opentelemetry/[email protected])
+ '@grpc/grpc-js': 1.14.3
+ '@opentelemetry/api': 1.9.0
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-metrics-otlp-http': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-grpc-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-metrics': 2.9.0(@opentelemetry/[email protected])
+ dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-1/noQNsp9gXD75HPzgjBrcF1+XTtry7pFAUfxVEJgg7mPv2AawKQuYkhMmJ8qjxz4Ubc3Y8bwvfxevXsKTq4cg==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-U128izvJfX/dW9jRGP0gIfadR1Hg7ft3UEGIeRxLFK70m2BWw6AtNCOnsUygpw2zCgR/ygdWbGpcL6TmhW0ZGw==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': ^1.3.0
dependencies:
+ '@grpc/grpc-js': 1.14.3
'@opentelemetry/api': 1.9.1
- '@opentelemetry/api-logs': 0.218.0
- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/otlp-exporter-base': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/otlp-transformer': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-logs': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-metrics-otlp-http': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-grpc-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-metrics': 2.9.0(@opentelemetry/[email protected])
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-YapQ9vNMX0NSZF6LK5pWAFfjpJleV2O9uYWfYGeb/5F1Kb9rPGK8tZDMJFa/sOksgdFuflDvYuA0B4qjDB4fjQ==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-Yqt3RBw/bRVncaE9qIIhk4WfjbAQqXuP9FgAaU+IKPndnLEp/cUqZlSC324+bpmduRz7DoTjig8Ub0PeILWXUA==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': ^1.3.0
dependencies:
- '@grpc/grpc-js': 1.14.3
- '@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/exporter-metrics-otlp-http': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/otlp-exporter-base': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/otlp-grpc-exporter-base': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/otlp-transformer': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-metrics': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/api': 1.9.0
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-metrics': 2.9.0(@opentelemetry/[email protected])
+ dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-bV7d2OuMpZu2+gAaxUAhzfZ0h3WVZk8ETQUEE3DNSntbTaMpuITjtm8I0rNyHFdm7Ax57K6ty7SgFXlBmOLIvQ==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-Yqt3RBw/bRVncaE9qIIhk4WfjbAQqXuP9FgAaU+IKPndnLEp/cUqZlSC324+bpmduRz7DoTjig8Ub0PeILWXUA==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/otlp-exporter-base': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/otlp-transformer': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-metrics': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-metrics': 2.9.0(@opentelemetry/[email protected])
optional: true
/@opentelemetry/[email protected](@opentelemetry/[email protected]):
@@ -2304,10 +2356,10 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/otlp-exporter-base': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/otlp-transformer': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/sdk-metrics': 1.25.1(@opentelemetry/[email protected])
dev: false
optional: true
@@ -2320,41 +2372,73 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/otlp-exporter-base': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/otlp-transformer': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/sdk-metrics': 1.25.1(@opentelemetry/[email protected])
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-ubLddKjWULhla9YZRCj/rTBeppjJYE4e9w0icx5mTu3eFhWjQzbV75NYjXuIlEG+NJsBl6d+sTFw5Qu+oej4oQ==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-lyO+IQBdSvqHN/ZOW/OzrSWemtfD+HgWngn+HBNLhjy0YrCQQTz0OE/kSekH2Pl340dn9DWzhqHdz5Eftr+HLA==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ requiresBuild: true
+ peerDependencies:
+ '@opentelemetry/api': ^1.3.0
+ dependencies:
+ '@opentelemetry/api': 1.9.0
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-metrics-otlp-http': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-metrics': 2.9.0(@opentelemetry/[email protected])
+ dev: false
+ optional: true
+
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-lyO+IQBdSvqHN/ZOW/OzrSWemtfD+HgWngn+HBNLhjy0YrCQQTz0OE/kSekH2Pl340dn9DWzhqHdz5Eftr+HLA==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/exporter-metrics-otlp-http': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/otlp-exporter-base': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/otlp-transformer': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-metrics': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-metrics-otlp-http': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-metrics': 2.9.0(@opentelemetry/[email protected])
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-RT5oEyu1kddZJ1vt7/BUo5wV+P7hpNAESsR3dUd3+8deHuX7gWNoCOZn+SfDT+hJHlIJ5h/AxiCLXIrutswDJg==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-JZD5DL/NBpVd2BHefvYosm3G40UZ/KzExLv5tc0eZe0CtrsHHtcOk3YPUxR2EINmUeBf8+w5UReTV8fFPn95lA==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ requiresBuild: true
+ peerDependencies:
+ '@opentelemetry/api': ^1.3.0
+ dependencies:
+ '@opentelemetry/api': 1.9.0
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-metrics': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/semantic-conventions': 1.40.0
+ dev: false
+ optional: true
+
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-JZD5DL/NBpVd2BHefvYosm3G40UZ/KzExLv5tc0eZe0CtrsHHtcOk3YPUxR2EINmUeBf8+w5UReTV8fFPn95lA==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-metrics': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-metrics': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
optional: true
@@ -2366,8 +2450,8 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/sdk-metrics': 1.25.1(@opentelemetry/[email protected])
dev: false
optional: true
@@ -2380,76 +2464,72 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/sdk-metrics': 1.25.1(@opentelemetry/[email protected])
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-3fXxVQEj9TNAFaCi79JeFKfeLd0sDtInaR3gaZDVlzNSPHtz8PZuCV34JKWjD4XXzT20IdMe8IpX6mRVNDA4Tw==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-bv1xmNhmNwIM6MdUBw4yYuJeVcEViVLk3uD69vOQMwueHBnfyl/u0HnBlB1FNY/Te0UOzJzvcbyR8wN6b+iGbA==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': ^1.3.0
dependencies:
'@grpc/grpc-js': 1.14.3
- '@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/otlp-exporter-base': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/otlp-grpc-exporter-base': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/otlp-transformer': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/api': 1.9.0
+ '@opentelemetry/otlp-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-grpc-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace': 2.9.0(@opentelemetry/[email protected])
+ dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-pVkSH20crBwMTqB3nIN4jpQKUEoB0Z94drIHpYyEqs7UBr+I0cpYyOR3bqjA/UasQUMROb3GX8ZX4/9cVRqGBQ==}
- engines: {node: '>=14'}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-bv1xmNhmNwIM6MdUBw4yYuJeVcEViVLk3uD69vOQMwueHBnfyl/u0HnBlB1FNY/Te0UOzJzvcbyR8wN6b+iGbA==}
+ engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
- '@opentelemetry/api': ^1.0.0
+ '@opentelemetry/api': ^1.3.0
dependencies:
'@grpc/grpc-js': 1.14.3
- '@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/otlp-grpc-exporter-base': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/otlp-transformer': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 1.25.1(@opentelemetry/[email protected])
- dev: false
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/otlp-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-grpc-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace': 2.9.0(@opentelemetry/[email protected])
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-pVkSH20crBwMTqB3nIN4jpQKUEoB0Z94drIHpYyEqs7UBr+I0cpYyOR3bqjA/UasQUMROb3GX8ZX4/9cVRqGBQ==}
- engines: {node: '>=14'}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-/+ExB3lRkf+erv4PnoywyL7RHKITidxtUpUTS55k7OQ0dB42S7gEF1gry7swb9MSm1hYLUhJg4QQh9W8SpwwqA==}
+ engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
- '@opentelemetry/api': ^1.0.0
+ '@opentelemetry/api': ^1.3.0
dependencies:
- '@grpc/grpc-js': 1.14.3
- '@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/otlp-grpc-exporter-base': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/otlp-transformer': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/api': 1.9.0
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace': 2.9.0(@opentelemetry/[email protected])
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-8dqezsmPhtKitIK/eTipZhYl9EX2/gNQ5zUMhaz3uxEURwfkNf8IPvo6yNfrzbxdtpAOybS/+h7wmIWYqFSpiw==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-/+ExB3lRkf+erv4PnoywyL7RHKITidxtUpUTS55k7OQ0dB42S7gEF1gry7swb9MSm1hYLUhJg4QQh9W8SpwwqA==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/otlp-exporter-base': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/otlp-transformer': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace': 2.9.0(@opentelemetry/[email protected])
optional: true
/@opentelemetry/[email protected](@opentelemetry/[email protected]):
@@ -2460,11 +2540,11 @@ packages:
'@opentelemetry/api': ^1.0.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/otlp-exporter-base': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/otlp-transformer': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace-base': 2.9.0(@opentelemetry/[email protected])
dev: false
optional: true
@@ -2476,102 +2556,71 @@ packages:
'@opentelemetry/api': ^1.0.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/otlp-exporter-base': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/otlp-transformer': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace-base': 2.9.0(@opentelemetry/[email protected])
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-r1Msf8SNLRmwh9J6XQ5uh82D7CdDWMNHnPB7LAVHjzut0TkSeKc5KcIvr4SvHvfk/xwN5gxC+VLKQ1k0o8PSPw==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-voTAD8XgJxlK7zLkXh8EzMB09zrQr3tyY/BsnDTlDiQU/UdK58MZ63A3mUjdEDrxMjCVmBHU3WQJhRmQe+Dvzg==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': ^1.3.0
- dependencies:
- '@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/otlp-exporter-base': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/otlp-transformer': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/[email protected])
- optional: true
-
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-pt6uX0noTQReHXNeEslQv7x311/F1gJzMnp1HD2qgypLRPbXDeMzzeTngRTUaUbP6hqWNtPxuLr4DEoZG+TcEQ==}
- engines: {node: '>=14'}
- requiresBuild: true
- peerDependencies:
- '@opentelemetry/api': ^1.0.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/otlp-exporter-base': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/otlp-transformer': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace': 2.9.0(@opentelemetry/[email protected])
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-pt6uX0noTQReHXNeEslQv7x311/F1gJzMnp1HD2qgypLRPbXDeMzzeTngRTUaUbP6hqWNtPxuLr4DEoZG+TcEQ==}
- engines: {node: '>=14'}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-voTAD8XgJxlK7zLkXh8EzMB09zrQr3tyY/BsnDTlDiQU/UdK58MZ63A3mUjdEDrxMjCVmBHU3WQJhRmQe+Dvzg==}
+ engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
- '@opentelemetry/api': ^1.0.0
+ '@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/otlp-exporter-base': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/otlp-transformer': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 1.25.1(@opentelemetry/[email protected])
- dev: false
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace': 2.9.0(@opentelemetry/[email protected])
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-RmOwSvkimg7ETwJbUOPTMhJm9A9bG1U8s7Zo3ajDh4zM7eYcycQ0dM7FbLD6NXWbI2yj7UY4q8BKinKYBQksyw==}
- engines: {node: '>=14'}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-RwINoce2BH8T4obT5pMcAla2sWma1YZvYuaktWmTluQ0PkQdvv5D060rWI1+kawX+J2qBRcMbwrZJJNcMJUauQ==}
+ engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': ^1.0.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/semantic-conventions': 1.25.1
- dev: false
- optional: true
-
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-RmOwSvkimg7ETwJbUOPTMhJm9A9bG1U8s7Zo3ajDh4zM7eYcycQ0dM7FbLD6NXWbI2yj7UY4q8BKinKYBQksyw==}
- engines: {node: '>=14'}
- requiresBuild: true
- peerDependencies:
- '@opentelemetry/api': ^1.0.0
- dependencies:
- '@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/semantic-conventions': 1.25.1
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/semantic-conventions': 1.40.0
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-mfsD9bKAxcKrh5+y08TPodvClBO0CznBE3p79YAGnO81WI4LrdsGA65T53e4iTSbCalW4WaUpkbeJcbpyIUHfg==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-RwINoce2BH8T4obT5pMcAla2sWma1YZvYuaktWmTluQ0PkQdvv5D060rWI1+kawX+J2qBRcMbwrZJJNcMJUauQ==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': ^1.0.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
optional: true
@@ -2583,7 +2632,7 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
transitivePeerDependencies:
@@ -2599,7 +2648,7 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
transitivePeerDependencies:
@@ -2617,7 +2666,7 @@ packages:
'@opentelemetry/api': 1.9.0
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/propagator-aws-xray': 1.26.2(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
'@types/aws-lambda': 8.10.122
transitivePeerDependencies:
@@ -2635,7 +2684,7 @@ packages:
'@opentelemetry/api': 1.9.1
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/propagator-aws-xray': 1.26.2(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
'@types/aws-lambda': 8.10.122
transitivePeerDependencies:
@@ -2651,7 +2700,7 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/propagation-utils': 0.30.16(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
@@ -2668,7 +2717,7 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/propagation-utils': 0.30.16(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
@@ -2747,7 +2796,7 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
'@types/connect': 3.4.36
@@ -2764,7 +2813,7 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
'@types/connect': 3.4.36
@@ -2869,7 +2918,7 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
transitivePeerDependencies:
@@ -2885,7 +2934,7 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
transitivePeerDependencies:
@@ -2901,7 +2950,7 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
transitivePeerDependencies:
@@ -2917,7 +2966,7 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
transitivePeerDependencies:
@@ -2933,7 +2982,7 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
transitivePeerDependencies:
- supports-color
@@ -2948,7 +2997,7 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
transitivePeerDependencies:
- supports-color
@@ -3049,7 +3098,7 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
transitivePeerDependencies:
@@ -3065,7 +3114,7 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
transitivePeerDependencies:
@@ -3081,7 +3130,7 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.25.1
semver: 7.7.3
@@ -3098,7 +3147,7 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.25.1
semver: 7.7.3
@@ -3177,7 +3226,7 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
'@types/koa': 2.14.0
@@ -3195,7 +3244,7 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
'@types/koa': 2.14.0
@@ -3305,7 +3354,7 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
transitivePeerDependencies:
@@ -3321,7 +3370,7 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
transitivePeerDependencies:
@@ -3589,7 +3638,7 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
transitivePeerDependencies:
@@ -3605,7 +3654,7 @@ packages:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
transitivePeerDependencies:
@@ -3713,7 +3762,7 @@ packages:
'@opentelemetry/api': ^1.7.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
transitivePeerDependencies:
- supports-color
@@ -3728,7 +3777,7 @@ packages:
'@opentelemetry/api': ^1.7.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
transitivePeerDependencies:
- supports-color
@@ -3765,15 +3814,31 @@ packages:
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-mIZil8Es+sYDK5m+DQiwAwF57F14TF2YlEqvIjZ/RQWcxDBwRGsKfdK2Tv65OU9meQKCMzSIFS9mxAcnAb6Bkg==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-xQx3E2WxP1mDvKzxLxX+CTCtNLa560YJZ3087qYHerl2YmiKpv7AH+dAy7vmx+eVrZ5BwhfWUAVoKOoxCNHcpw==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ requiresBuild: true
+ peerDependencies:
+ '@opentelemetry/api': ^1.3.0
+ dependencies:
+ '@opentelemetry/api': 1.9.0
+ '@opentelemetry/api-logs': 0.220.0
+ import-in-the-middle: 3.0.1
+ require-in-the-middle: 8.0.1
+ transitivePeerDependencies:
+ - supports-color
+ dev: false
+ optional: true
+
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-xQx3E2WxP1mDvKzxLxX+CTCtNLa560YJZ3087qYHerl2YmiKpv7AH+dAy7vmx+eVrZ5BwhfWUAVoKOoxCNHcpw==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/api-logs': 0.218.0
+ '@opentelemetry/api-logs': 0.220.0
import-in-the-middle: 3.0.1
require-in-the-middle: 8.0.1
transitivePeerDependencies:
@@ -3818,16 +3883,29 @@ packages:
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-ZwqpkNL5W7RyGJPDZ9g06DvKp8KFTWPJPN12anpMQYSKpTSU0z3EIZuPq9vPGpS8siFyOqDYDAuCwlNO9FqgbA==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-CXYo8UD5Mn9YbgebO2EL4wejtA+gxLmLiu6HCk2KH2BR7XhFN6/6p1UlCb23DYCjeYkndevLHuejCCN1yx4+OQ==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ requiresBuild: true
+ peerDependencies:
+ '@opentelemetry/api': ^1.3.0
+ dependencies:
+ '@opentelemetry/api': 1.9.0
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.220.0(@opentelemetry/[email protected])
+ dev: false
+ optional: true
+
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-CXYo8UD5Mn9YbgebO2EL4wejtA+gxLmLiu6HCk2KH2BR7XhFN6/6p1UlCb23DYCjeYkndevLHuejCCN1yx4+OQ==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/otlp-transformer': 0.218.0(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.220.0(@opentelemetry/[email protected])
optional: true
/@opentelemetry/[email protected](@opentelemetry/[email protected]):
@@ -3838,7 +3916,7 @@ packages:
'@opentelemetry/api': ^1.0.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/otlp-transformer': 0.52.1(@opentelemetry/[email protected])
dev: false
optional: true
@@ -3851,69 +3929,71 @@ packages:
'@opentelemetry/api': ^1.0.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/otlp-transformer': 0.52.1(@opentelemetry/[email protected])
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-H/lCGJ536N98VpYJOaWTQOkv4Dx6TnmStK6Rqfu1W7KkFbPAx04hjdYEMZF/YbnHzPUSIK4kM6OE2GKGBTpV9A==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-/eIkBPMBTIvM3x/0mDX4aJeSkYifYClnBPr68PL1h5LV4VQv4+SV6CGrpiZ4fIWDnobVmhTWCm1J/QRdAWUfvA==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': ^1.3.0
dependencies:
'@grpc/grpc-js': 1.14.3
- '@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/otlp-exporter-base': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/otlp-transformer': 0.218.0(@opentelemetry/[email protected])
+ '@opentelemetry/api': 1.9.0
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.220.0(@opentelemetry/[email protected])
+ dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-zo/YrSDmKMjG+vPeA9aBBrsQM9Q/f2zo6N04WMB3yNldJRsgpRBeLLwvAt/Ba7dpehDLOEFBd1i2JCoaFtpCoQ==}
- engines: {node: '>=14'}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-/eIkBPMBTIvM3x/0mDX4aJeSkYifYClnBPr68PL1h5LV4VQv4+SV6CGrpiZ4fIWDnobVmhTWCm1J/QRdAWUfvA==}
+ engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
- '@opentelemetry/api': ^1.0.0
+ '@opentelemetry/api': ^1.3.0
dependencies:
'@grpc/grpc-js': 1.14.3
- '@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/otlp-exporter-base': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/otlp-transformer': 0.52.1(@opentelemetry/[email protected])
- dev: false
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.220.0(@opentelemetry/[email protected])
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-zo/YrSDmKMjG+vPeA9aBBrsQM9Q/f2zo6N04WMB3yNldJRsgpRBeLLwvAt/Ba7dpehDLOEFBd1i2JCoaFtpCoQ==}
- engines: {node: '>=14'}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-lXGrv7KXZ0gNH9SVNUaa6vv6phVYGvJxfXAlMbzbakiXru75f5MZl8Z7oqiMMQD77riVHJCFlQvbZs/VVN2/4A==}
+ engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
- '@opentelemetry/api': ^1.0.0
+ '@opentelemetry/api': ^1.3.0
dependencies:
- '@grpc/grpc-js': 1.14.3
- '@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/otlp-exporter-base': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/otlp-transformer': 0.52.1(@opentelemetry/[email protected])
+ '@opentelemetry/api': 1.9.0
+ '@opentelemetry/api-logs': 0.220.0
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-logs': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-metrics': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace': 2.9.0(@opentelemetry/[email protected])
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-CFaKH87WAzjuJ4awowTTLzUvMfaRfiOFG5+qm5S5ncyalRtN4ecQ+YmuANJSCrVPuvZFEkUgKhBPBndxi3rHsQ==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-lXGrv7KXZ0gNH9SVNUaa6vv6phVYGvJxfXAlMbzbakiXru75f5MZl8Z7oqiMMQD77riVHJCFlQvbZs/VVN2/4A==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': ^1.3.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/api-logs': 0.218.0
- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-logs': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/sdk-metrics': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/api-logs': 0.220.0
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-logs': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-metrics': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace': 2.9.0(@opentelemetry/[email protected])
optional: true
/@opentelemetry/[email protected](@opentelemetry/[email protected]):
@@ -3925,11 +4005,11 @@ packages:
dependencies:
'@opentelemetry/api': 1.9.0
'@opentelemetry/api-logs': 0.52.1
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/sdk-logs': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/sdk-metrics': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace-base': 2.9.0(@opentelemetry/[email protected])
protobufjs: 8.6.5
dev: false
optional: true
@@ -3943,11 +4023,11 @@ packages:
dependencies:
'@opentelemetry/api': 1.9.1
'@opentelemetry/api-logs': 0.52.1
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/sdk-logs': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/sdk-metrics': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace-base': 2.9.0(@opentelemetry/[email protected])
protobufjs: 8.6.5
dev: false
optional: true
@@ -3996,74 +4076,50 @@ packages:
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-p6HFscpjrv7//kE+7L+3Vn00VEDUJB0n6ZrjkTYHrJ58QZ8B3ajSJhRbCcY6guQ3PDjTbxWklyvIN2ojVbIb1A==}
- engines: {node: '>=14'}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-WrOT1WsOUG+B7hstD2RYoMPIOK76G8E9AQHhMjUvrQaGx/oA7rPWQvvr1Rqv7+yy4R0ZMVwWLC4vW2xnkgWPAQ==}
+ engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': '>=1.0.0 <1.10.0'
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- dev: false
- optional: true
-
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-p6HFscpjrv7//kE+7L+3Vn00VEDUJB0n6ZrjkTYHrJ58QZ8B3ajSJhRbCcY6guQ3PDjTbxWklyvIN2ojVbIb1A==}
- engines: {node: '>=14'}
- requiresBuild: true
- peerDependencies:
- '@opentelemetry/api': '>=1.0.0 <1.10.0'
- dependencies:
- '@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-RJid6E2CKyeGfKBzXKF21ejabGMHypFkPAh3qZ+NvI+SGjuIye79t3PmiqcDgtRzdKH6ynXzbfslQ8DfpRUg2A==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-WrOT1WsOUG+B7hstD2RYoMPIOK76G8E9AQHhMjUvrQaGx/oA7rPWQvvr1Rqv7+yy4R0ZMVwWLC4vW2xnkgWPAQ==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': '>=1.0.0 <1.10.0'
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-nBprRf0+jlgxks78G/xq72PipVK+4or9Ypntw0gVZYNTCSK8rg5SeaGV19tV920CMqBD/9UIOiFr23Li/Q8tiA==}
- engines: {node: '>=14'}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-4mYGty27rYvSM0jtp1ZUOqd3LfVRCYg9H5G9OFzSx5HViYToU21MFhWfco7x1HwXr7ER8yGOiCIHZUwjPksc0Q==}
+ engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': '>=1.0.0 <1.10.0'
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- dev: false
- optional: true
-
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-nBprRf0+jlgxks78G/xq72PipVK+4or9Ypntw0gVZYNTCSK8rg5SeaGV19tV920CMqBD/9UIOiFr23Li/Q8tiA==}
- engines: {node: '>=14'}
- requiresBuild: true
- peerDependencies:
- '@opentelemetry/api': '>=1.0.0 <1.10.0'
- dependencies:
- '@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-KMjVBHzP4N60bOzxja76M1F1hZZ43lGPga5ix+mkv9+kk1nx9SbkxSvJsMbuVUxdPQmsPTqGShmhN8ulrMOg6Q==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-4mYGty27rYvSM0jtp1ZUOqd3LfVRCYg9H5G9OFzSx5HViYToU21MFhWfco7x1HwXr7ER8yGOiCIHZUwjPksc0Q==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': '>=1.0.0 <1.10.0'
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
optional: true
/@opentelemetry/[email protected]:
@@ -4081,7 +4137,7 @@ packages:
'@opentelemetry/api': ^1.0.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/resources': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
dev: false
optional: true
@@ -4094,7 +4150,7 @@ packages:
'@opentelemetry/api': ^1.0.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/resources': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
dev: false
optional: true
@@ -4107,8 +4163,8 @@ packages:
'@opentelemetry/api': ^1.0.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
dev: false
optional: true
@@ -4121,8 +4177,8 @@ packages:
'@opentelemetry/api': ^1.0.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
dev: false
optional: true
@@ -4135,8 +4191,8 @@ packages:
'@opentelemetry/api': ^1.0.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
dev: false
optional: true
@@ -4149,8 +4205,8 @@ packages:
'@opentelemetry/api': ^1.0.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
dev: false
optional: true
@@ -4163,7 +4219,7 @@ packages:
'@opentelemetry/api': ^1.0.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/resources': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
dev: false
optional: true
@@ -4176,7 +4232,7 @@ packages:
'@opentelemetry/api': ^1.0.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/resources': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
dev: false
optional: true
@@ -4189,8 +4245,8 @@ packages:
'@opentelemetry/api': ^1.0.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
gcp-metadata: 6.1.1
transitivePeerDependencies:
@@ -4207,8 +4263,8 @@ packages:
'@opentelemetry/api': ^1.0.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
gcp-metadata: 6.1.1
transitivePeerDependencies:
@@ -4217,80 +4273,57 @@ packages:
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-pkZT+iFYIZsVn6+GzM0kSX+u3MSLCY9md+lIJOoKl/P+gJFfxJte/60Usdp8Ce4rOs8GduUpSPNe1ddGyDT1sQ==}
- engines: {node: '>=14'}
- requiresBuild: true
- peerDependencies:
- '@opentelemetry/api': '>=1.0.0 <1.10.0'
- dependencies:
- '@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/semantic-conventions': 1.25.1
- dev: false
- optional: true
-
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-pkZT+iFYIZsVn6+GzM0kSX+u3MSLCY9md+lIJOoKl/P+gJFfxJte/60Usdp8Ce4rOs8GduUpSPNe1ddGyDT1sQ==}
- engines: {node: '>=14'}
- requiresBuild: true
- peerDependencies:
- '@opentelemetry/api': '>=1.0.0 <1.10.0'
- dependencies:
- '@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/semantic-conventions': 1.25.1
- dev: false
- optional: true
-
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-5UxZqiAgLYGFjS4s9qm5mBVo433u+dSPUFWVWXmLAD4wB65oMCoXaJP1KJa9DIYYMeHu3z4BZcStG3LC593cWA==}
- engines: {node: '>=14'}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-jyA5MBLQ+Dkl3+JsZkUoUvL7yHvU64kLsvpXKarWm6347Sl1t1bXFTFykUePNpT5WH5pm9a2Qtt03iIYQhZ1Fg==}
+ engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
- '@opentelemetry/api': '>=1.0.0 <1.10.0'
+ '@opentelemetry/api': '>=1.3.0 <1.10.0'
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
- '@opentelemetry/semantic-conventions': 1.28.0
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/semantic-conventions': 1.40.0
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-5UxZqiAgLYGFjS4s9qm5mBVo433u+dSPUFWVWXmLAD4wB65oMCoXaJP1KJa9DIYYMeHu3z4BZcStG3LC593cWA==}
- engines: {node: '>=14'}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-jyA5MBLQ+Dkl3+JsZkUoUvL7yHvU64kLsvpXKarWm6347Sl1t1bXFTFykUePNpT5WH5pm9a2Qtt03iIYQhZ1Fg==}
+ engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
- '@opentelemetry/api': '>=1.0.0 <1.10.0'
+ '@opentelemetry/api': '>=1.3.0 <1.10.0'
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
- '@opentelemetry/semantic-conventions': 1.28.0
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/semantic-conventions': 1.40.0
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-DeT6KKolmC4e/dRQvMQ/RwlnzhaqeiFOXY5ngoOPJ07GgVVKxZOg9EcrNZb5aTzUn+iCrJldAgOfQm1O/QfPAQ==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-WywcTkQtv2iNmt+6y5Kcd4rzvx9bLVsBa2Nwcmg01IUaBTkTow3W4d9KE5vNBpEDtb9tp21WcRBY/lANRrApYA==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
- '@opentelemetry/api': '>=1.3.0 <1.10.0'
+ '@opentelemetry/api': '>=1.4.0 <1.10.0'
dependencies:
- '@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/api': 1.9.0
+ '@opentelemetry/api-logs': 0.220.0
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
+ dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-QvnNdugatFTVCJXH0Mcu7GOOJSylA9j127kIezOE4YwTI4YbowRons2K4WZTv5FMS8T4q9P0NdaRHdkSmeAIag==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-WywcTkQtv2iNmt+6y5Kcd4rzvx9bLVsBa2Nwcmg01IUaBTkTow3W4d9KE5vNBpEDtb9tp21WcRBY/lANRrApYA==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': '>=1.4.0 <1.10.0'
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/api-logs': 0.218.0
- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/api-logs': 0.220.0
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
optional: true
@@ -4303,8 +4336,8 @@ packages:
dependencies:
'@opentelemetry/api': 1.9.0
'@opentelemetry/api-logs': 0.52.1
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
dev: false
optional: true
@@ -4317,8 +4350,8 @@ packages:
dependencies:
'@opentelemetry/api': 1.9.1
'@opentelemetry/api-logs': 0.52.1
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
dev: false
optional: true
@@ -4330,8 +4363,8 @@ packages:
'@opentelemetry/api': '>=1.3.0 <1.10.0'
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
lodash.merge: 4.6.2
dev: false
optional: true
@@ -4344,8 +4377,8 @@ packages:
'@opentelemetry/api': '>=1.3.0 <1.10.0'
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.25.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
lodash.merge: 4.6.2
dev: false
optional: true
@@ -4358,8 +4391,8 @@ packages:
'@opentelemetry/api': '>=1.3.0 <1.10.0'
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
dev: false
optional: true
@@ -4371,226 +4404,196 @@ packages:
'@opentelemetry/api': '>=1.3.0 <1.10.0'
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-MpDJdkiFDs3Pm1RHO3KByuZbuBdJEXEAkiC0+yJdsZGVCdf1RpHR6n+LHDcS7ffmfrt5kVCzJSCfm4z2C7v0uQ==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-Xx8RGS4H5XEBl01WuCreMIpiah9cCXMbSkeuIePPdD2cUpq/vUzYmj8E/MK1OsbOc93FuAD4jfn2WOacKwLn7Q==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': '>=1.9.0 <1.10.0'
dependencies:
- '@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/api': 1.9.0
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-tPMjHrLV5gsfNdYqoRHjeGbCAZBXXD9c1Qo/2ut7VwnUABDNh76xNxrT0SEhkIIJuCN45bbN1vZnYL1gY0IkOg==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-Xx8RGS4H5XEBl01WuCreMIpiah9cCXMbSkeuIePPdD2cUpq/vUzYmj8E/MK1OsbOc93FuAD4jfn2WOacKwLn7Q==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
- '@opentelemetry/api': '>=1.3.0 <1.10.0'
+ '@opentelemetry/api': '>=1.9.0 <1.10.0'
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/api-logs': 0.218.0
- '@opentelemetry/configuration': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/context-async-hooks': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/exporter-logs-otlp-grpc': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/exporter-logs-otlp-http': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/exporter-logs-otlp-proto': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/exporter-metrics-otlp-grpc': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/exporter-metrics-otlp-http': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/exporter-metrics-otlp-proto': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/exporter-prometheus': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/exporter-trace-otlp-grpc': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/exporter-trace-otlp-http': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/exporter-trace-otlp-proto': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/exporter-zipkin': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/instrumentation': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/otlp-exporter-base': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/propagator-b3': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/propagator-jaeger': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-logs': 0.218.0(@opentelemetry/[email protected])
- '@opentelemetry/sdk-metrics': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-node': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/semantic-conventions': 1.40.0
- transitivePeerDependencies:
- - supports-color
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-uEG+gtEr6eKd8CVWeKMhH2olcCHM9dEK68pe0qE0be32BcCRsvYURhHaD1Srngh1SQcnQzZ4TP324euxqtBOJA==}
- engines: {node: '>=14'}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-wHtGyHhSKHNH3fym33xRu4Ef/HXTFvX8eQ42xdQdEO9LYx9Y2qNyBDJytyqVlvmo6abWZlNYTUthuAGUMYqYnQ==}
+ engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': '>=1.3.0 <1.10.0'
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/api-logs': 0.52.1
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/exporter-trace-otlp-grpc': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/exporter-trace-otlp-http': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/exporter-trace-otlp-proto': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/exporter-zipkin': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-logs': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-metrics': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-node': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/semantic-conventions': 1.25.1
+ '@opentelemetry/api-logs': 0.220.0
+ '@opentelemetry/configuration': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/context-async-hooks': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-logs-otlp-grpc': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-logs-otlp-http': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-logs-otlp-proto': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-metrics-otlp-grpc': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-metrics-otlp-http': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-metrics-otlp-proto': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-prometheus': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-trace-otlp-grpc': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-trace-otlp-http': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-trace-otlp-proto': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-zipkin': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/instrumentation': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-grpc-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/propagator-b3': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/propagator-jaeger': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-logs': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-metrics': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace-base': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace-node': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/semantic-conventions': 1.40.0
transitivePeerDependencies:
- supports-color
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-uEG+gtEr6eKd8CVWeKMhH2olcCHM9dEK68pe0qE0be32BcCRsvYURhHaD1Srngh1SQcnQzZ4TP324euxqtBOJA==}
- engines: {node: '>=14'}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-wHtGyHhSKHNH3fym33xRu4Ef/HXTFvX8eQ42xdQdEO9LYx9Y2qNyBDJytyqVlvmo6abWZlNYTUthuAGUMYqYnQ==}
+ engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': '>=1.3.0 <1.10.0'
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/api-logs': 0.52.1
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/exporter-trace-otlp-grpc': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/exporter-trace-otlp-http': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/exporter-trace-otlp-proto': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/exporter-zipkin': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/instrumentation': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-logs': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-metrics': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-node': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/semantic-conventions': 1.25.1
+ '@opentelemetry/api-logs': 0.220.0
+ '@opentelemetry/configuration': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/context-async-hooks': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-logs-otlp-grpc': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-logs-otlp-http': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-logs-otlp-proto': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-metrics-otlp-grpc': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-metrics-otlp-http': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-metrics-otlp-proto': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-prometheus': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-trace-otlp-grpc': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-trace-otlp-http': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-trace-otlp-proto': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-zipkin': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/instrumentation': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-grpc-exporter-base': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/propagator-b3': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/propagator-jaeger': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-logs': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-metrics': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace-base': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace-node': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/semantic-conventions': 1.40.0
transitivePeerDependencies:
- supports-color
- dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-C8k4hnEbc5FamuZQ92nTOp8X/diCY56XUTnMiv9UTuJitCzaNNHAVsdm5+HLCdI8SLQsLWIrG38tddMxLVoftw==}
- engines: {node: '>=14'}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-cp9zmTl62R8PJrpvFcmc8N2JQU/xfa0S+61q511Nji+QxCfZ8Ifvg7H27G8cANe4crg4RTrWsVvanHiXjSp6ag==}
+ engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
- '@opentelemetry/api': '>=1.0.0 <1.10.0'
+ '@opentelemetry/api': '>=1.3.0 <1.10.0'
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/semantic-conventions': 1.25.1
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/semantic-conventions': 1.40.0
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-C8k4hnEbc5FamuZQ92nTOp8X/diCY56XUTnMiv9UTuJitCzaNNHAVsdm5+HLCdI8SLQsLWIrG38tddMxLVoftw==}
- engines: {node: '>=14'}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-cp9zmTl62R8PJrpvFcmc8N2JQU/xfa0S+61q511Nji+QxCfZ8Ifvg7H27G8cANe4crg4RTrWsVvanHiXjSp6ag==}
+ engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
- '@opentelemetry/api': '>=1.0.0 <1.10.0'
+ '@opentelemetry/api': '>=1.3.0 <1.10.0'
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/semantic-conventions': 1.25.1
- dev: false
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/semantic-conventions': 1.40.0
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-jVPgBbH1gCy2Lb7X0AVQ8XAfgg0pJ4nvl8/IiQA6nxOsPvS+0zMJaFSs2ltXe0J6C8dqjcnpyqINDJmU30+uOg==}
- engines: {node: '>=14'}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-ec9a7ps37huy5itYk0MalaZdSLlM6AXWp/FhtEjgMpp5leEGojBDvAl/UWttQnkMZOvFHKzRESn8TD3yKTF5nQ==}
+ engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': '>=1.0.0 <1.10.0'
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.30.1(@opentelemetry/[email protected])
- '@opentelemetry/semantic-conventions': 1.28.0
+ '@opentelemetry/context-async-hooks': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace-base': 2.9.0(@opentelemetry/[email protected])
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-jVPgBbH1gCy2Lb7X0AVQ8XAfgg0pJ4nvl8/IiQA6nxOsPvS+0zMJaFSs2ltXe0J6C8dqjcnpyqINDJmU30+uOg==}
- engines: {node: '>=14'}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-ec9a7ps37huy5itYk0MalaZdSLlM6AXWp/FhtEjgMpp5leEGojBDvAl/UWttQnkMZOvFHKzRESn8TD3yKTF5nQ==}
+ engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': '>=1.0.0 <1.10.0'
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.30.1(@opentelemetry/[email protected])
- '@opentelemetry/semantic-conventions': 1.28.0
- dev: false
+ '@opentelemetry/context-async-hooks': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace-base': 2.9.0(@opentelemetry/[email protected])
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-NAYIlsF8MPUsKqJMiDQJTMPOmlbawC1Iz/omMLygZ1C9am8fTKYjTaI+OZM+WTY3t3Glo0wnOg/6/pac6RGPPw==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-sGA19HvtrrSKYsseHphluH6j3p6Xa3fqc7c7y8f/7mYWejc1lyDFcpSdD1kYa50HCLUeEo4zA5bW0pniaPszuw==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
'@opentelemetry/api': '>=1.3.0 <1.10.0'
- dependencies:
- '@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/semantic-conventions': 1.40.0
- optional: true
-
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-nMcjFIKxnFqoez4gUmihdBrbpsEnAX/Xj16sGvZm+guceYE0NE00vLhpDVK6f3q8Q4VFI5xG8JjlXKMB/SkTTQ==}
- engines: {node: '>=14'}
- requiresBuild: true
- peerDependencies:
- '@opentelemetry/api': '>=1.0.0 <1.10.0'
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/context-async-hooks': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/propagator-b3': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/propagator-jaeger': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 1.25.1(@opentelemetry/[email protected])
- semver: 7.7.3
- dev: false
- optional: true
-
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-nMcjFIKxnFqoez4gUmihdBrbpsEnAX/Xj16sGvZm+guceYE0NE00vLhpDVK6f3q8Q4VFI5xG8JjlXKMB/SkTTQ==}
- engines: {node: '>=14'}
- requiresBuild: true
- peerDependencies:
- '@opentelemetry/api': '>=1.0.0 <1.10.0'
- dependencies:
- '@opentelemetry/api': 1.9.1
- '@opentelemetry/context-async-hooks': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/core': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/propagator-b3': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/propagator-jaeger': 1.25.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 1.25.1(@opentelemetry/[email protected])
- semver: 7.7.3
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/semantic-conventions': 1.40.0
dev: false
optional: true
- /@opentelemetry/[email protected](@opentelemetry/[email protected]):
- resolution: {integrity: sha512-pCpQxU68lV+I9s9svqMyVu5iHdDDUnqUpSxqwyCU8A9ejEsSnMPCbearwsUO4yk08ZJzAIUCFuReMdVQvHrdvg==}
+ /@opentelemetry/[email protected](@opentelemetry/[email protected]):
+ resolution: {integrity: sha512-sGA19HvtrrSKYsseHphluH6j3p6Xa3fqc7c7y8f/7mYWejc1lyDFcpSdD1kYa50HCLUeEo4zA5bW0pniaPszuw==}
engines: {node: ^18.19.0 || >=20.6.0}
requiresBuild: true
peerDependencies:
- '@opentelemetry/api': '>=1.0.0 <1.10.0'
+ '@opentelemetry/api': '>=1.3.0 <1.10.0'
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/context-async-hooks': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/semantic-conventions': 1.40.0
optional: true
/@opentelemetry/[email protected]:
@@ -4600,12 +4603,6 @@ packages:
dev: false
optional: true
- /@opentelemetry/[email protected]:
- resolution: {integrity: sha512-lp4qAiMTD4sNWW4DbKLBkfiMZ4jbAboJIGOQr5DvciMRI494OapieI9qiODpOt0XBr1LjIDy1xAGAnVs5supTA==}
- engines: {node: '>=14'}
- requiresBuild: true
- optional: true
-
/@opentelemetry/[email protected]:
resolution: {integrity: sha512-cifvXDhcqMwwTlTK04GBNeIe7yyo28Mfby85QXFe1Yk8nmi36Ab/5UQwptOx84SsoGNRg+EVSjwzfSZMy6pmlw==}
engines: {node: '>=14'}
@@ -4620,7 +4617,7 @@ packages:
'@opentelemetry/api': ^1.1.0
dependencies:
'@opentelemetry/api': 1.9.0
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
dev: false
optional: true
@@ -4632,7 +4629,7 @@ packages:
'@opentelemetry/api': ^1.1.0
dependencies:
'@opentelemetry/api': 1.9.1
- '@opentelemetry/core': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.9.0(@opentelemetry/[email protected])
dev: false
optional: true
@@ -6330,7 +6327,7 @@ packages:
obug: 2.1.1
std-env: 4.1.0
tinyrainbow: 3.1.0
- vitest: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
+ vitest: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])
dev: true
@@ -6435,13 +6432,6 @@ packages:
dev: false
optional: true
- resolution: {integrity: sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==}
- engines: {node: '>= 0.6'}
- dependencies:
- mime-types: 2.1.35
- negotiator: 0.6.3
-
resolution: {integrity: sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==}
engines: {node: '>= 0.6'}
@@ -6541,7 +6531,7 @@ packages:
dev: false
optional: true
resolution: {integrity: sha512-bUqO5o2VpWomh2xGOHdQoX00CGrPcIAH6zDCt5oa0SeJWAO+bbB7SiElb1TxwcrJQKe96HkiSh2T8z4vFypsxg==}
engines: {node: '>=18.0.0'}
hasBin: true
@@ -6573,16 +6563,16 @@ packages:
'@opentelemetry/exporter-metrics-otlp-http': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/exporter-prometheus': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/exporter-trace-otlp-http': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/sdk-metrics': 1.30.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-node': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-node': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace-base': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
'@xenova/transformers': 2.17.2
argon2: 0.44.0
bcrypt: 6.0.0
better-sqlite3: 11.10.0
- express-rate-limit: 8.3.2([email protected])
+ express-rate-limit: 8.3.2([email protected])
helmet: 8.1.0
hnswlib-node: 3.0.0
sharp: 0.32.6
@@ -6634,10 +6624,10 @@ packages:
'@opentelemetry/exporter-metrics-otlp-http': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/exporter-prometheus': 0.52.1(@opentelemetry/[email protected])
'@opentelemetry/exporter-trace-otlp-http': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/resources': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/sdk-metrics': 1.30.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-node': 0.52.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 1.30.1(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-node': 0.220.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace-base': 2.9.0(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
'@xenova/transformers': 2.17.2
argon2: 0.44.0
@@ -6672,8 +6662,8 @@ packages:
jsonwebtoken: 9.0.3
sql.js: 1.14.1
optionalDependencies:
- '@opentelemetry/resources': 1.30.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-node': 0.218.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.9.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-node': 0.220.0(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.40.0
'@ruvector/attention': 0.1.32
'@ruvector/gnn': 0.1.25
@@ -7230,9 +7220,6 @@ packages:
resolution: {integrity: sha512-F2+Hkm9xFaRg+GkaNnbwXNDV5O6pnCFEmqyhvfC/Ic5LbgOWjJh3L+mN/s91rxVL3znE7DYVpW0GJFT+4YBgWw==}
- resolution: {integrity: sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==}
-
resolution: {integrity: sha512-c5AMf34bKdvPhQ7tBGhqkgKNUzMr4WUs+WDtC2ZUGOUncbxKMTvqxYctiseW3+L4bA8ec+GcZ6/A/FW4m8ukng==}
@@ -7439,25 +7426,6 @@ packages:
readable-stream: 3.6.2
dev: false
- resolution: {integrity: sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA==}
- engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16}
- dependencies:
- bytes: 3.1.2
- content-type: 1.0.5
- debug: 2.6.9
- depd: 2.0.0
- destroy: 1.2.0
- http-errors: 2.0.1
- iconv-lite: 0.4.24
- on-finished: 2.4.1
- qs: 6.14.1
- raw-body: 2.5.3
- type-is: 1.6.18
- unpipe: 1.0.0
- transitivePeerDependencies:
- - supports-color
-
resolution: {integrity: sha512-nfDwkulwiZYQIGwxdy0RUmowMhKcFVcYXUU7m4QlKYim1rUtg83xm2yjZ40QjDuc291AJjjeSc9b++AWHSgSHw==}
engines: {node: '>=18'}
@@ -7468,7 +7436,7 @@ packages:
http-errors: 2.0.1
iconv-lite: 0.7.2
on-finished: 2.4.1
- qs: 6.14.1
+ qs: 6.15.3
raw-body: 3.0.2
type-is: 2.0.1
transitivePeerDependencies:
@@ -7864,12 +7832,6 @@ packages:
dev: false
optional: true
- resolution: {integrity: sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==}
- engines: {node: '>= 0.6'}
- dependencies:
- safe-buffer: 5.2.1
-
resolution: {integrity: sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==}
engines: {node: '>=18'}
@@ -7913,9 +7875,6 @@ packages:
resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}
dev: true
- resolution: {integrity: sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==}
-
resolution: {integrity: sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==}
engines: {node: '>=6.6.0'}
@@ -7957,7 +7916,7 @@ packages:
dependencies:
env-paths: 2.2.1
import-fresh: 3.3.1
- js-yaml: 4.1.1
+ js-yaml: 5.2.1
parse-json: 5.2.0
typescript: 5.9.3
@@ -7994,16 +7953,6 @@ packages:
engines: {node: '>= 12'}
requiresBuild: true
- resolution: {integrity: sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==}
- peerDependencies:
- supports-color: '*'
- peerDependenciesMeta:
- supports-color:
- optional: true
- dependencies:
- ms: 2.0.0
-
resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}
engines: {node: '>=6.0'}
@@ -8068,10 +8017,6 @@ packages:
resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==}
engines: {node: '>= 0.8'}
- resolution: {integrity: sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==}
- engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16}
-
resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
engines: {node: '>=8'}
@@ -8342,7 +8287,7 @@ packages:
imurmurhash: 0.1.4
is-glob: 4.0.3
is-path-inside: 3.0.3
- js-yaml: 4.1.1
+ js-yaml: 5.2.1
json-stable-stringify-without-jsonify: 1.0.1
levn: 0.4.1
lodash.merge: 4.6.2
@@ -8476,71 +8421,21 @@ packages:
resolution: {integrity: sha512-7iN8iPMDzOMHPUYllBEsQdWVB6fPDMPqwjBaFrgr4Jgr/+okjvzAy+UHlYYL/Vs0OsOrMkwS6PJDkFlJwoxUnw==}
engines: {node: '>= 16'}
peerDependencies:
- express: '>= 4.11'
+ express: '>=4.22.2'
dependencies:
express: 5.2.1
dev: false
- resolution: {integrity: sha512-77VmFeJkO0/rvimEDuUC5H30oqUC4EyOhyGccfqoLebB0oiEYfM7nwPrsDsBL1gsTpwfzX8SFy2MT3TDyRq+bg==}
- engines: {node: '>= 16'}
- requiresBuild: true
- peerDependencies:
- express: '>= 4.11'
- dependencies:
- express: 4.22.1
- ip-address: 10.1.0
- dev: false
- optional: true
-
resolution: {integrity: sha512-77VmFeJkO0/rvimEDuUC5H30oqUC4EyOhyGccfqoLebB0oiEYfM7nwPrsDsBL1gsTpwfzX8SFy2MT3TDyRq+bg==}
engines: {node: '>= 16'}
requiresBuild: true
peerDependencies:
- express: '>= 4.11'
+ express: '>=4.22.2'
dependencies:
express: 5.2.1
ip-address: 10.1.0
- resolution: {integrity: sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==}
- engines: {node: '>= 0.10.0'}
- dependencies:
- accepts: 1.3.8
- array-flatten: 1.1.1
- body-parser: 1.20.4
- content-disposition: 0.5.4
- content-type: 1.0.5
- cookie: 0.7.2
- cookie-signature: 1.0.7
- debug: 2.6.9
- depd: 2.0.0
- encodeurl: 2.0.0
- escape-html: 1.0.3
- etag: 1.8.1
- finalhandler: 1.3.2
- fresh: 0.5.2
- http-errors: 2.0.1
- merge-descriptors: 1.0.3
- methods: 1.1.2
- on-finished: 2.4.1
- parseurl: 1.3.3
- path-to-regexp: 0.1.12
- proxy-addr: 2.0.7
- qs: 6.14.1
- range-parser: 1.2.1
- safe-buffer: 5.2.1
- send: 0.19.2
- serve-static: 1.16.3
- setprototypeof: 1.2.0
- statuses: 2.0.2
- type-is: 1.6.18
- utils-merge: 1.0.1
- vary: 1.1.2
- transitivePeerDependencies:
- - supports-color
-
resolution: {integrity: sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==}
engines: {node: '>= 18'}
@@ -8565,7 +8460,7 @@ packages:
once: 1.4.0
parseurl: 1.3.3
proxy-addr: 2.0.7
- qs: 6.14.1
+ qs: 6.15.3
range-parser: 1.2.1
router: 2.2.0
send: 1.2.1
@@ -8700,20 +8595,6 @@ packages:
dependencies:
to-regex-range: 5.0.1
- resolution: {integrity: sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==}
- engines: {node: '>= 0.8'}
- dependencies:
- debug: 2.6.9
- encodeurl: 2.0.0
- escape-html: 1.0.3
- on-finished: 2.4.1
- parseurl: 1.3.3
- statuses: 2.0.2
- unpipe: 1.0.0
- transitivePeerDependencies:
- - supports-color
-
resolution: {integrity: sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==}
engines: {node: '>= 18.0.0'}
@@ -8824,10 +8705,6 @@ packages:
resolution: {integrity: sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==}
dev: false
- resolution: {integrity: sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==}
- engines: {node: '>= 0.6'}
-
resolution: {integrity: sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==}
engines: {node: '>= 0.8'}
@@ -9345,12 +9222,6 @@ packages:
resolution: {integrity: sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA==}
engines: {node: '>=20.0.0'}
- resolution: {integrity: sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==}
- engines: {node: '>=0.10.0'}
- dependencies:
- safer-buffer: 2.1.2
-
resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==}
engines: {node: '>=0.10.0'}
@@ -9678,8 +9549,8 @@ packages:
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
- resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==}
+ resolution: {integrity: sha512-zfLtNfQqxVqq3uaTqSkh4x4hZw3KHobGUA0fJUj4wawW8bsQLTVqpHdXSIzidh7o+4lEW36tANuAGdaFx6Zgnw==}
hasBin: true
dependencies:
argparse: 2.0.1
@@ -10033,10 +9904,6 @@ packages:
resolution: {integrity: sha512-Vawdc8vi36fXxKCaDpluRvbGcmrUXJdvXcDhkh30HYsws8XqX2rWPBflZpavzeS+6SwijRFV7g+9ypQRJZlrEQ==}
hasBin: true
- resolution: {integrity: sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==}
- engines: {node: '>= 0.6'}
-
resolution: {integrity: sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==}
engines: {node: '>= 0.8'}
@@ -10045,9 +9912,6 @@ packages:
resolution: {integrity: sha512-pxQJQzB6djGPXh08dacEloMFopsOqGVRKFPYvPOt9XDZ1HasbgDZA74CJGreSU4G3Ak7EFJGoiH2auq+yXISgA==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==}
-
resolution: {integrity: sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==}
engines: {node: '>=18'}
@@ -10055,10 +9919,6 @@ packages:
resolution: {integrity: sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==}
- resolution: {integrity: sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==}
- engines: {node: '>= 0.6'}
-
resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==}
engines: {node: '>=8.6'}
@@ -10110,11 +9970,6 @@ packages:
dependencies:
mime-db: 1.54.0
- resolution: {integrity: sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==}
- engines: {node: '>=4'}
- hasBin: true
-
resolution: {integrity: sha512-X5ju04+cAzsojXKes0B/S4tcYtFAJ6tTMuSPBEn9CPGlrWr8Fiw7qYeLT0XyH80HSoAoqWCaz+MWKh22P7G1cw==}
engines: {node: '>=16'}
@@ -10264,9 +10119,6 @@ packages:
requiresBuild: true
optional: true
- resolution: {integrity: sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==}
-
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
@@ -10302,10 +10154,6 @@ packages:
resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==}
dev: true
- resolution: {integrity: sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==}
- engines: {node: '>= 0.6'}
-
resolution: {integrity: sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w==}
engines: {node: '>= 0.6'}
@@ -10889,9 +10737,6 @@ packages:
lru-cache: 11.2.4
minipass: 7.1.2
- resolution: {integrity: sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==}
-
resolution: {integrity: sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==}
@@ -11129,11 +10974,12 @@ packages:
engines: {node: '>=16.0.0'}
requiresBuild: true
- resolution: {integrity: sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==}
+ resolution: {integrity: sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==}
engines: {node: '>=0.6'}
dependencies:
- side-channel: 1.1.0
+ es-define-property: 1.0.1
+ side-channel: 1.1.1
resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==}
@@ -11143,15 +10989,6 @@ packages:
resolution: {integrity: sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==}
engines: {node: '>= 0.6'}
- resolution: {integrity: sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==}
- engines: {node: '>= 0.8'}
- dependencies:
- bytes: 3.1.2
- http-errors: 2.0.1
- iconv-lite: 0.4.24
- unpipe: 1.0.0
-
resolution: {integrity: sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==}
engines: {node: '>= 0.10'}
@@ -11674,26 +11511,6 @@ packages:
engines: {node: '>=10'}
hasBin: true
- resolution: {integrity: sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==}
- engines: {node: '>= 0.8.0'}
- dependencies:
- debug: 2.6.9
- depd: 2.0.0
- destroy: 1.2.0
- encodeurl: 2.0.0
- escape-html: 1.0.3
- etag: 1.8.1
- fresh: 0.5.2
- http-errors: 2.0.1
- mime: 1.6.0
- ms: 2.1.3
- on-finished: 2.4.1
- range-parser: 1.2.1
- statuses: 2.0.2
- transitivePeerDependencies:
- - supports-color
-
resolution: {integrity: sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==}
engines: {node: '>= 18'}
@@ -11719,17 +11536,6 @@ packages:
dependencies:
type-fest: 0.13.1
- resolution: {integrity: sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==}
- engines: {node: '>= 0.8.0'}
- dependencies:
- encodeurl: 2.0.0
- escape-html: 1.0.3
- parseurl: 1.3.3
- send: 0.19.2
- transitivePeerDependencies:
- - supports-color
-
resolution: {integrity: sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==}
engines: {node: '>= 18'}
@@ -11821,8 +11627,8 @@ packages:
dev: false
optional: true
- resolution: {integrity: sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==}
+ resolution: {integrity: sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==}
engines: {node: '>= 0.4'}
dependencies:
es-errors: 1.3.0
@@ -11847,13 +11653,13 @@ packages:
object-inspect: 1.13.4
side-channel-map: 1.0.1
- resolution: {integrity: sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==}
+ resolution: {integrity: sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==}
engines: {node: '>= 0.4'}
dependencies:
es-errors: 1.3.0
object-inspect: 1.13.4
- side-channel-list: 1.0.0
+ side-channel-list: 1.0.1
side-channel-map: 1.0.1
side-channel-weakmap: 1.0.2
@@ -12518,13 +12324,6 @@ packages:
dependencies:
tagged-tag: 1.0.0
- resolution: {integrity: sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==}
- engines: {node: '>= 0.6'}
- dependencies:
- media-typer: 0.3.0
- mime-types: 2.1.35
-
resolution: {integrity: sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==}
engines: {node: '>= 0.6'}
@@ -12647,10 +12446,6 @@ packages:
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
- resolution: {integrity: sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==}
- engines: {node: '>= 0.4.0'}
-
resolution: {integrity: sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==}
hasBin: true
@@ -13114,6 +12909,13 @@ packages:
engines: {node: '>= 14.6'}
hasBin: true
+ resolution: {integrity: sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==}
+ engines: {node: '>= 14.6'}
+ hasBin: true
+ requiresBuild: true
+ optional: true
+
resolution: {integrity: sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==}
engines: {node: '>=10'}