mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-11-24 22:28:10 +09:00
616a7ebb015d5e481d6314562efbe80167cdff9d
300
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
668f99dc33 | fix: address Ruflo mod and console beta feedback (#3698) | ||
|
|
f65928eeaf |
fix(hooks): use blocking exit status for pre-bash denials
Require Claude Code PreToolUse exit 2 across shipped and generated handlers, with regression checks for command shapes and mod ownership. Prepared by Codex in Dragan’s authorized session. |
||
|
|
24c9c4a8d8 |
fix(mods): handshake in the generated helper; ENOENT-only missing; doctor reports the rollout switch (ADR-404)
- generateHookHandler() carries the same RUFLO_MODS_OWNS handshake, so a helper written by the refresh fallback still hands route/post-edit over - isMissing matches ENOENT only: a misread error must fail the guard closed, never read as 'no policy' - doctor: the server-side rollout switch decides whether the mod loads (observed live: loads with the enable variable unset while served on, not with it set while served off); the variable is reported, never sufficient - bin-level tests for init --mods, doctor --component mods, mods status - ADR: live-run evidence, final counts; README: where options are read Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
c1d425fafc |
Merge origin/main into fix/3555-3565-helpers
Resolves the helper-refresh.ts import conflict with #3576 (Nick Ruest's post-install integrity re-check) by keeping both imports, and runs ensureCommonJsCompanions after the #3565 heal path rewrites helpers too, so a healed install also gets its .cjs companions (#3555). Co-Authored-By: Nick Ruest <nicholas-ruest@users.noreply.github.com> Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
ef99017d45 |
fix(helpers): ship session and memory helpers as .cjs too (#3555)
hook-handler.cjs also safeRequire()s session.js and memory.js, which are CommonJS and fail in "type":"module" projects exactly as router.js did: session-restore/-end then fall back to placeholder output and no session is recorded. (In this repo the root copy already had session.cjs and memory.cjs, so the .js requires never loaded anything at all.) - rename the packaged session.js / memory.js to .cjs; hook-handler (both copies and the generated one), generateHelpers and the init generator fallback now use the .cjs names - neither helper is in the signed critical set, so a pre-rename install whose hook-handler gets refreshed would lose them: the refresh and `init --upgrade` now write any missing session.cjs / memory.cjs from the compiled generators (helper-companions.ts). Stale .js copies are left in place and ignored; existing .cjs files are never overwritten - hook-handler exports loadedHelpers so loading can be verified - helpers manifest re-signed (hook-handler.cjs content changed) Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
b72ca9f7d8 |
feat(doctor): report signed-helper integrity mismatches (#3565 follow-up)
Review finding on #3576: the issue asked that `ruflo doctor` report a helper integrity mismatch, and doctor had no such check. Startup now heals tampered helpers, but the paths it deliberately skips (.LOCKED, RUFLO_HELPERS_LOCKED, an unverifiable package manifest, an unresolvable package source) were invisible to doctor. Adds `checkHelperIntegrity`, which reuses Nick's `verifyInstalledCriticalHelpers` and the shared `CRITICAL_HELPERS` list (no second hard-coded copy), for both <cwd>/.claude/helpers and ~/.claude/helpers: - mismatch, not locked -> fail, naming the dir and files - mismatch under .LOCKED / RUFLO_HELPERS_LOCKED -> warn (deliberate edit) - manifest signature invalid -> fail closed - package source not found -> warn instead of a false pass Wired into the default run and `doctor --component helpers`. `findPackageHelpersDir` is exported for the check. 8 new tests. Co-Authored-By: Nick Ruest <nicholas-ruest@users.noreply.github.com> Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
9d026a8947 |
fix(helpers): ship router as .cjs so it loads in ESM projects (#3555)
`.claude/helpers/router.js` is CommonJS but shipped with a `.js` extension. In any project whose package.json declares "type":"module", Node loads it as ESM, `require` is undefined, it throws on load, and hook-handler.cjs silently falls back to "Router not available, using default routing" — so ADR-389's word-boundary routing fix never ran in exactly the projects most new Node code uses. Rename the shipped helper to router.cjs everywhere it is produced or consumed: the packaged copy, the repo-root copy's hook-handler require, helpers-generator (router + generated hook-handler), init executor (upgrade copy list + generator fallbacks), helper-refresh CRITICAL_HELPERS + generator fallback, sign/verify-helpers critical lists, and the helper-signing security smoke. The helpers manifest is re-signed. A stale router.js left in an existing install is harmless: nothing requires it any more. Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
3b885e5a7e |
fix(cli): re-verify signed critical helpers on every invocation, not just once (#3565)
`helper-refresh.ts` verified a critical helper's signature/hash once, at
copy time, then stamped the target dir with the installed CLI version.
Every later command short-circuited on "stamp already matches" with zero
further verification, so a critical helper (router.js, hook-handler.cjs,
etc.) modified on disk after that point — a sibling package's postinstall,
a losing writer from a concurrent-session race, direct tampering — stayed
silently modified through any number of subsequent commands, indefinitely.
Adds helper-integrity.ts: re-hashes each installed critical helper against
the signed manifest independent of the stamp. helper-refresh.ts now runs
this on every stamp-match call (both the lock-free fast path and the
under-lock authoritative path) and heals a mismatch via the existing
fail-closed verify-then-copy path. `.LOCKED`-marked installs are exempt —
a deliberate hand-edit is not tampering. index.ts surfaces a loud,
non-verbose-gated warning when tampering is detected and healed, for both
the project and global helper dirs.
Adds 4 new tests (heal-on-tamper, .LOCKED exemption, unverifiable-source
handling, genuine-no-op-when-intact) and updates one existing test whose
premise this fix intentionally changes (a same-version race between two
genuinely different signed sources has no real-world analog — production
always resolves one real trust root — so it's rewritten to assert no
redundant write happens once content is verified correct).
Verified: tsc --noEmit clean, full package build succeeds, compiled
dist/src/init/helper-refresh.js confirmed to no longer contain the bare
`if (stamped === version) return { refreshed: false }` #3565 flagged.
Full CLI test suite (4405 tests) passes except 4 pre-existing failures
unrelated to this change (confirmed against unmodified baseline / known
unbuilt-dependency issues in @claude-flow/mcp and @claude-flow/memory).
Fixes #3565
Co-Authored-By: RuFlo <ruv@ruv.net>
|
||
|
|
2203fa56dc | fix(memory): keep home-level helpers on the active project root | ||
|
|
82dac70fd7 |
feat(router): ADR-389–391 — refresh router helper, opt-in MiniLM embedder, benchmark gate (no default change) (#3410)
* docs(adr): ADR-389..391 — router: refresh the helper, use the real embedder, change defaults only on a measured win ADR-389: add router.js to CRITICAL_HELPERS + re-sign, so installed copies get the word-boundary fix (#3401); today they are frozen at first write. ADR-390: hooks_route embeds patterns and tasks with the local MiniLM chain (generateLocalEmbedding), hash embedder as the reported fallback. ADR-391: frozen, labelled 150-200 prompt corpus; A/B/C/D (current, MiniLM, typesafe-hash, typesafe-onnx); ADR-150-style AND-gate for promotion. Co-Authored-By: RuFlo <ruv@ruv.net> * feat(init): refresh router.js as a critical helper on upgrade (ADR-389, #3401) Installed copies of .claude/helpers/router.js never received the #2257 word-boundary fix: helper-refresh only re-copies CRITICAL_HELPERS and router.js was not on the list, so an April substring router kept routing "sync and review latest issues" to tester. - helper-refresh.ts: add router.js to CRITICAL_HELPERS; generator fallback also emits it (generateAgentRouter). - sign-helpers.mjs / verify-helpers.mjs / executor.ts executeUpgrade / smoke-helper-signing-security.mjs: keep their copies of the list in sync. - New test: stale April router.js is replaced by the package copy via the signed refresh path (throwaway key), after which the prompt no longer routes to tester. helpers.manifest.json is NOT re-signed here. Until it is, verify-helpers fails ("manifest has no entry for router.js") and the production refresh is fail-closed blocked for all helpers. Co-Authored-By: RuFlo <ruv@ruv.net> * bench(router): ADR-391 labelled evaluation corpus (197 prompts, frozen) Blind-labelled corpus for comparing routing candidates: 11 labels incl. none, 64 adversarial trap cases, deterministic stratified dev/test split (i%5 in {0,2} -> dev), dependency-free validator that recomputes the split and prints the sha256. Frozen at sha256 b0c1923b2813b61907304dff56c53d199b709797bfb9600a7c1f496cf0c0bf04. Co-Authored-By: RuFlo <ruv@ruv.net> * feat(hooks): ADR-390 — semantic router can use the real MiniLM embedder hooks_route compared tasks with pattern keywords using a character hash (generateSimpleEmbedding), which measures spelling, not meaning. This adds a router-embedder abstraction (src/ruvector/router-embedder.ts): - embedForRouter(texts, kind) -> { vectors, embedder: 'minilm'|'hash', reason? } - MiniLM path uses generateLocalEmbedding ONLY (never the bridge-first generateEmbedding, #2312). backend !== 'onnx', a throw, or a non-384-d vector degrades EVERY text in the call to the hash, with a reason. - Selection: CLAUDE_FLOW_ROUTER_EMBEDDER=minilm|hash; DEFAULT_ROUTER_EMBEDDER stays 'hash' until ADR-391's benchmark decides. getSemanticRouter builds both the native VectorDb and pure-JS indexes from one embedder, records which one actually built the index, embeds the query with that same embedder, rebuilds when the requested embedder changes, and shares one in-flight build between concurrent callers. If the query fails on MiniLM after a MiniLM index was built, the index is rebuilt with the hash so the two spaces never mix. hooks_route results gain `embedder` (+ `embedderReason` when degraded); existing fields are unchanged. routeTaskForBench(task, { embedder }) is an internal, bench-only entry that runs the same local path as hooks_route (skipping the AgentDB pre-route and the opt-in typesafe wrapper) for ADR-391. Co-Authored-By: RuFlo <ruv@ruv.net> * chore(audit): register CLAUDE_FLOW_ROUTER_EMBEDDER as a known env escape hatch ADR-390's router embedder selector is process-lifetime MCP router state, like CLAUDE_FLOW_DISABLE_NATIVE_ROUTER; the ADR-391 bench passes the embedder explicitly rather than through a CLI flag. Co-Authored-By: RuFlo <ruv@ruv.net> * bench(router): ADR-391 first run — no candidate promoted; fix typesafe-router test (e) Benchmark (run-bench.mjs) on the frozen 197-prompt corpus (sha256 b0c1923b…), test split n=113: A current (hash) 25.7% acc, p95 1.06 ms B MiniLM (ADR-390) 36.3% acc, p95 6.21 ms (+10.6 pts, +485% p95) C typesafe hash 26.5% acc, p95 1.20 ms D typesafe onnx 29.2% acc, p95 8.35 ms (raw pick 44.3%, gated to 5.6%) No candidate passes the ADR-391 AND-gate (B fails the relative latency bound), so DEFAULT_ROUTER_EMBEDDER stays 'hash' and typesafe stays opt-in. Receipt committed under benchmarks/router/results/. ADR-391 gains a Results section with the findings (structural ceiling: no pattern returns researcher/reviewer/none; latency criterion mis-specified for a ~1 ms base; typesafe gate too tight) as owner decisions, not applied. ADR-389 -> Implemented; ADR-390 -> Implemented as opt-in; ADR-391 -> Implemented. typesafe-router test (e) was red on main since #3402 made the keyword fallback word-bounded: it still asserted the old "latest"->tester fallback. It now asserts the typesafe override and that a legacy fallback is kept. Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
8080d872ac |
fix(hooks): match router keywords on word boundaries, not substrings (#3401) (#3402)
suggestAgentsForTask() in hooks-tools.ts used taskLower.includes(keyword), so 'test' matched "latest" (tester @ 0.95), 'auth' matched "author", 'fix' matched "prefix", 'api' matched "capitalize". It backs hooks_pre-task and the keyword fallback of hooks_route/hooks_explain. Precompile \b-anchored matchers with simple inflections instead. The repo-root .claude/helpers/router.cjs still carried the pre-#2257 substring table at 0.8 confidence; replace it with the word-boundary router. Add 'testing'/'specs' tester tokens to the generator and its snapshot copies, and guard the generated CLI block with require.main so requiring it from hook-handler.cjs doesn't execute it. |
||
|
|
c77d1b5062 |
fix(hooks): apply the Windows argv fix from #3322 to the other three shim copies (#3332)
#3322 escaped argv on the Windows shell:true path in plugins/ruflo-core/scripts/ruflo-hook.cjs. The same shim exists in three other places, which still pass hook-derived values (a Bash tool's `command`, a file path) to cmd.exe unescaped, and are broader than the copy that was fixed — a bare `process.platform === 'win32'` with no exemption for `node`: - .claude-plugin/scripts/ruflo-hook.cjs (published in the npm package) - plugin/scripts/ruflo-hook.cjs (byte-identical sibling) - generateRufloHookCjs() in helpers-generator.ts, which `ruflo init` writes to .claude/helpers/ruflo-hook.cjs All four now follow one pattern — resolve, then escape: - resolveCommandPath() walks PATH/PATHEXT with fs only. The previous probe was `execSync('where ' + cmd)`, which spawned a shell on every hook invocation. - resolveNpmShim() maps an npm .cmd shim to the .js entrypoint it would have run, read from the package's own `bin` field rather than a guessed filename, and required to resolve inside the package directory. Both npm layouts are handled (global prefix and node_modules/.bin), as is npx, whose command and package names differ. - invokeHook() spawns `node <entry>` with shell:false, so CreateProcess receives the argv array verbatim — no second cmd.exe tokenizer, and no %VAR% expansion, which quoting does not suppress and carets do not reliably escape. - escapeCmdArg() is unchanged from #3322 and remains as the fallback for the case where no entrypoint can be identified. Returning early there would silently drop the hook instead of surfacing the problem. escapeCmdArg, resolveCommandPath, resolveNpmShim and resolveInvocation are byte-identical across all four copies, and the suite asserts that for each of them — the divergence between copies is what let this persist after #3322. Verification. #3322 could only assert the string transform, with no Windows host available. Two changes address that: - resolveCommandPath/resolveInvocation take `platform` and `env` as arguments, so the Windows branch runs on any OS. The tests build a real npm layout in a temp dir, drive it with { platform: 'win32' }, and assert the payload reaches the recorded argv byte-for-byte while the sibling .cmd/.ps1 are resolved past, never executed. - the coverage is added to plugins/ruflo-core/scripts/test-hooks.mjs, whose "Plugin hooks smoke" job already runs on windows-latest. The existing cases there go through RUFLO_HOOK_CLI_OVERRIDE and so never reach the global-shim branch; these call invokeHook() directly, so the fallback is executed against a real cmd.exe. Tests: 11 vitest cases and 6 new harness cases, each mutation-checked — every one fails when the code it covers is reverted. test-hooks.mjs goes 19/24 to 25/30 against the recorder fixture; those 5 failures are pre-existing on main (the fixture does not echo argv) and pass in CI against the real built CLI. Windows result: the windows-latest leg ran green, 32/32, including the escaped fallback executed against a real cmd.exe. The %VAR% probe was included because carets are not a reliable escape for % and quoting does not suppress percent expansion, so expansion on the shim's second parse looked plausible; the runner measured otherwise and the value arrives literal, with no redirection performed. The probe stays as a regression guard and keeps reporting the observed value rather than asserting one. Out of scope: nine sites in plugins/ruflo-metaharness/scripts spawn with `shell: process.platform === 'win32'` and a dynamic argv element — _darwin.mjs:86/129 spread the caller's own ...argv, oia-audit.mjs:105 passes JSON.stringify(payload), and audit-list/audit-trend/similarity pass `--key <key>`. Same shape, different plugin, separate change. Two neighbours that look like the same problem and are not: the ten `shell:` flags across ruflo-cost-tracker are inert, because spawnNpxSync() discards the option and forces shell:false; and mcp-launch.cjs already prefers a resolved local bin with shell:false and only falls back to npx.cmd with constant args. |
||
|
|
0db381f7f7 |
dream(performance): #3129 remove unwired diskann-backend.ts, fix stale HNSW claims in generated CLAUDE.md (evaluated, ACCEPT) (#3130)
* dream(performance): remove unwired diskann-backend.ts, fix stale HNSW claims in generated CLAUDE.md
Dream Cycle 2026-08-30 (DEEP=performance, SCAN=security,hive-mind).
- v3/@claude-flow/cli/src/ruvector/diskann-backend.ts deleted: a full
diskann->hnsw->cosine-js fallback chain (375 lines) with zero call
sites anywhere in the monorepo; @ruvector/diskann is not a listed
dependency, so it never shipped.
- claudemd-generator.ts's performanceSection()/intelligenceSystem():
replaced "Use HNSW/DiskANN for vector search" and the unreproduced
"150x-12,500x faster search" figure with this repo's own measured
number ("~1.9x-4.7x vs brute force, recall@10 ~0.99", per
docs/reviews/intelligence-system-audit-2026-05-29.md) so every new
ruflo init project gets the same corrected claim already on record
in root CLAUDE.md, not the stale one.
- New regression test pins the corrected figure across every
CLAUDE.md template.
- Pulled forward the 2026-08-20..29 ledger backfill from
dream/2026-08-29-swarm (not yet on main) and appended this run
below it.
Full research report: docs/dream-cycle/dream-gist-2026-08-30.md
* dream(performance): finalize witness stamp, ledger row, issue/PR cross-refs (#3129, #3130)
* dream(performance): address review — port #3104 pnpm fix, trim ledger to 1 row, live benchmark receipt
- Port PR #3104's v3/pnpm-lock.yaml specifier fix (accepted, open) so v3-pnpm
CI jobs (Type Check V3, Test V3 Packages) install cleanly; root-npm side
(issue #3095) left to maintainer per that issue's own text.
- Trim LEDGER.md back to exactly one row for this run (2026-08-30); the
2026-08-20..29 backfill this branch had accumulated belongs to its own
ledger-repair effort, not this candidate's row.
- Replace the hardcoded "~1.9x-4.7x, recall@10 ~0.99" replacement claim
(itself sourced from a doc that self-contradicts ~0.9 vs ~0.99) with a
live re-run of scripts/benchmark-intelligence.mjs on this commit, and
point generated CLAUDE.md at the reproducible command instead of any
hardcoded multiplier so it cannot drift stale again.
---------
Co-authored-by: Claude <noreply@anthropic.com>
|
||
|
|
0e50fe7f57 |
dream(security): #3043 advisory scanner for untrusted settings.json hooks/allow-rules (evaluated, ACCEPT) (#3044)
* dream(security): #3043 advisory scanner for untrusted settings.json hooks/allow-rules carried forward by ruflo init/--upgrade mergeSettingsForUpgrade() and writeSettings() both read a target project's pre-existing .claude/settings.json and spread its hooks / permissions.allow entries into the merged output verbatim — the same trust shape as CVE-2025-59536 (settings.json hook payload achieving command execution with no review step), reached via ruflo init's own merge logic rather than Claude Code's loader. Neither of last night's flagged CVEs (2025-59536, 2025-6514) applies to Ruflo's own hook dispatch or OAuth client directly, but this distinct gap in the same family was genuinely unaddressed. Adds a static, advisory-only (non-blocking) scanner that inspects hook commands and Bash allow-rules for known-dangerous patterns before the merge and surfaces findings as CLI warnings. Merge/write behavior itself is completely unchanged. Hardened after an independent adversarial-critic pass found 6 concrete bypasses (intermediate-pipe-stage downloads, two-step download+exec, eval-wrapped base64, interpreter-mediated dangerous commands, absolute-path-prefixed commands, whitespace-evasive allow rules) — all fixed and pinned as a held-out regression set. Also fixes an ANSI/control-character injection risk in the warning output itself, self-identified during review. 87/87 relevant tests green (1 pre-existing environmental failure elsewhere in the package, unrelated — unbuilt sibling package). Dream Cycle 2026-08-16, security surface. Full research, evaluation receipts, and adversarial critique: issue #3043 and docs/dream-cycle/dream-gist-2026-08-16.md. Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_01NVdeUqt73Bv7vnPxYpZy7i * docs(dream-cycle): update ledger — backfill 2026-08-14/2026-08-15, add 2026-08-16 2026-08-14 (swarm, REJECT) and 2026-08-15 (performance, REJECT) both had fully-run pipelines whose live ledger rows never reached main (every dream-cycle PR to date is unmerged, so branch-local ledger commits never merge forward) — verified via git ls-remote / search_pull_requests before backfilling, not assumed. 2026-08-16 (security, ACCEPT): advisory scanner for untrusted settings.json hooks/allow-rules carried forward by ruflo init/--upgrade. Issue #3043, PR #3044. Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_01NVdeUqt73Bv7vnPxYpZy7i --------- Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
13cbd697db | fix(release): enforce CI and idle assignment safety | ||
|
|
fa11ee8c24 | fix(cli): honor helper refresh opt-out before locking | ||
|
|
0c73bab4d0 | fix(cli): serialize helper refreshes across processes | ||
|
|
87f4f8ab67 |
fix(mcp): mcp start -t http exits after false-success table + doc drift from #2985 (#2987)
* fix(migrate,mcp): unresolvable remediation command + false-success HTTP server exit Two independently-reported, freshly-filed defects: - #2985: `ruflo migrate status`'s ADR-128 removed-agent remediation (shipped today via #2973/ADR-382 Part B) printed a command that cannot succeed twice over: `ruflo plugins install <plugin>` requires -n/--name (not a positional) AND targets the npm-package plugin system, while the gap detector's own registry check (installed_plugins.json) is for the Claude Code marketplace system entirely. Fixed to print the correct `/plugin install <plugin>@ruflo` slash-command flow, with a one-time "run /plugin marketplace add ruvnet/ruflo first" hint. Also corrects three adjacent doc-drift items the reporter found while verifying: README/USERGUIDE's `claude mcp add ruflo` examples (should be the canonical `claude-flow` key per #2206 — the exact stray-key duplicate #2612's healing logic exists to clean up), README's blanket "MCP server registered: No" claim for the plugin path (ruflo-core ships its own .mcp.json and does register one), and a stale comment in executor.ts conflating the CLI-track's mcp__claude-flow__* tool refs with the marketplace plugin binding (mcp__plugin_<plugin>_<server>__*). - #2984: `ruflo mcp start -t http` printed a full "Status: Running" success table — PID, health/RPC URLs — then exited 0 within seconds, never actually leaving the port bound. Root cause: bin/cli.js's "normal CLI mode" branch (which any explicit non-stdio --transport always takes) unconditionally exits once the dispatched command's action() promise resolves (#1552's "one-shot command" assumption). mcp.ts's `start` action returned immediately after printing the table, so the freshly-bound http.Server was torn down within milliseconds of the printed success claim. Fixed by blocking in the foreground after a successful start (SIGINT/SIGTERM-driven graceful shutdown), matching daemon.ts's established `--foreground` pattern — `daemonize` isn't currently wired to fork/detach anywhere in MCPServerManager, so every successful start via this path is a foreground server regardless of the -d flag. Tests: migrate-agent-detection.test.ts updated for the corrected command string; new mcp-http-foreground-2984.test.ts spawns the built CLI exactly like the bug report and asserts the port actually accepts connections after the success table prints (not just that it printed), then confirms SIGTERM still produces a clean exit. Both verified via git-stash A/B: fail against the pre-fix code, pass against the fix. Full suite otherwise unaffected — same 9 pre-existing sandbox-environment failures (ruvector/wasm bindings, embedder model downloads) reproduced identically before this change. Closes #2985. Closes #2984. Co-Authored-By: RuFlo <ruv@ruv.net> * revert: drop migrate-agent-detection changes, superseded by PR #2986 An external contributor (pacphi) independently opened #2986 fixing the same #2985 with the identical installCommand correction plus a real `migrate fix --agents` restore command — strictly more complete than this branch's minimal fix. Dropping the overlapping files here to avoid a duplicate/conflicting PR; reviewed #2986 and recommended it for merge. Remaining on this branch: the #2984 mcp start -t http fix and the doc-drift items #2986 explicitly scoped out (README/USERGUIDE mcp-add key, executor.ts comment). Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
76453115a8 |
fix(security): fail closed on unvalidated security scan --depth/--type/--target (#2866)
`security scan` validated none of its three input flags, so a typo was
indistinguishable from a clean result:
- An unknown --type matched none of the three phase guards, so no phase ran at
all and the command still printed "No security issues found!" and exited 0.
The guards are case-sensitive, so `--type CODE` hit this too.
- An unknown --depth fell through the chained ternaries to the shallowest
traversal, so `--depth full` scanned *less* than the default `standard`
(3 levels vs 5). On a tree whose only HIGH finding sat below that budget it
also flipped the critical/high exit-code gate from 1 to 0 — the gate silently
stopped gating.
- A non-existent or non-directory --target read nothing, and the swallowed
dir-read catches turned that into zero findings, the clean banner, exit 0, and
a PERSISTED clean report that getSecurityStatus reports as CLEAN. mkdirSync
with recursive:true even created the tree to hold it. --target names what gets
scanned and is the likelier typo of the three.
All three now fail closed before anything is printed, scanned or written.
`--depth full` is deprecated, NOT rejected. It was never a supported depth, but
the CLI itself emitted that exact string in five places — the statusline insight,
the announcement, the release-notes blurb, the CLAUDE.md that `init` generates,
and two shipped agent definitions — across 21 tracked files. Hard-rejecting it
would break the invocations we told users to run, and would strand the statusline
insight in a loop: it fires on scan status PENDING, tells the user to run
`--depth full`, which would exit 1 and never write a report, leaving status
PENDING forever. It is normalised to `deep` (the depth the word promised) with a
warning, and the emitters we control now say `--depth deep`.
Also in this change:
- Chained ternaries replaced with exhaustive Record<ScanDepth, number> maps
behind real type predicates rather than `as` casts. The casts mattered: an
invalid key yields undefined, and `undefined <= 0` is false while
`undefined - 1` is NaN, so the recursion guard would never fire and the depth
limiter would silently disable itself. The guard now positive-tests its budget
(`!(depthLimit > 0)`) so a bad value stops traversal instead of unbounding it.
- `container` was advertised in --type's help since this command was written but
no phase implements it, so it validated fine, scanned nothing and reported
clean. Rejected explicitly, case-insensitively so `--type Container` gets the
accurate "not implemented" message rather than being called a misspelling.
Breaking for pipelines passing it; noted in CHANGELOG.
- The report path is built as scan-${scanType}-${depth}.json, so an unvalidated
--type could shape it: `--type ../../../escaped` wrote
<target>/.claude/escaped-deep.json. Validating the enums closes it.
Tests: 20 cases, black-box against the built CLI. Beyond the rejection paths they
pin the parts a previous revision of this suite left unconstrained — a level-6
fixture so `deep` is distinguishable from `standard` (a mutant cutting deep from
10 to 4 passed the earlier suite and now fails three tests), stdout/stderr kept
separate so a stdout-redirecting caller is provably not left with an empty
document and no diagnostic, and the --target and deprecation paths.
security-scan-persistence, security-audit, security-verification,
issue-2670-security-defend, fs-secure, funnel and funnel-messages-seed-pool all
pass. tsc error count is 17 with and without the patch, none in security.ts.
Note for anyone re-verifying: bin/cli.js loads dist/, tsconfig has
composite: true, and the build cache lives at dist/tsconfig.tsbuildinfo — an
incremental `npx tsc` will not re-emit after an out-of-band dist edit.
Reported privately via SECURITY.md by an external reporter, with a reproduction
and a proposed patch.
Co-Authored-By: Ruflo & AQE
|
||
|
|
401e02d511 |
fix: complete reports and consistent initialization for v3.32.37 (#2851)
* fix(metaharness): preserve readiness verdict payloads * test(metaharness): cover blocked genome verdicts * fix(adr): parse bullet metadata and relationships (#2659) * fix(adr): align adr-create with AgentDB schema (#2651) * fix(adr): make index updates idempotent (#2660) * fix(memory): bound session-end graph consolidation (#2628) * fix(memory): align active row visibility (#2652) * fix(memory): honor database path during init * fix(hooks): keep all shim fallback tags aligned * fix(codex): omit unbacked full-template skills * fix(init): generate complete native dual projects * test(memory): isolate path and legacy-row regressions * chore(release): prepare v3.32.37 |
||
|
|
67ff9898c0 |
fix: resolve current runtime and verification defects for v3.32.36 (#2850)
* fix(cli): make runtime status and learning signals truthful * fix(metaharness): accept padded scan severities * fix(codex): make core hooks and status skill native * fix(security): make witness verification hermetic * fix(metrics): expose grounded learning outcomes * fix(hooks): deduplicate project and plugin events * fix(verification): preserve security audit payloads * fix(runtime): stabilize dual memory skills and MCP schemas * fix(cli): harden helper signing and reflexion health * test(release): align helper and container invariants * chore(release): prepare v3.32.36 * test(funnel): align gates with cold-start seed pool * fix(ci): document MCP environment precedence |
||
|
|
ddd27576cb |
fix(release): ship Capability Brain as a self-contained 3.32.30 train (#2829)
* fix(release): bundle policy and Codex runtimes * fix(release): verify self-contained three-package archives |
||
|
|
9f6cf7d2a1 |
fix(security): statusline CVE counter reads real scan findings, not hardcoded 3 (#2694)
getSecurityStatus() hardcoded totalCves=3 and counted scan *files* as 'CVEs fixed', fabricating '⚠ 3 CVEs' for every project. Now reads the NEWEST scan in .claude/security-scans/ and surfaces its real findings count (summary.total ?? totalFindings ?? findings.length). cvesFixed stays 0 until a real fix-tracking mechanism exists. Fixed in all 5 copies: - v3/@claude-flow/cli/src/funnel/local-signals.ts (TS source of truth) - v3/@claude-flow/cli/.claude/helpers/statusline.js (cli helper) - v3/@claude-flow/mcp/.claude/helpers/statusline.cjs (mcp helper) - v3/@claude-flow/mcp/.claude/helpers/statusline.js (mcp helper) - v3/@claude-flow/hooks/src/statusline/index.ts (hooks statusline) Also: executor.ts init defaults totalCves 3->0 (2 sites); statusline/index.ts audit fallback defaults 3->0. Added regression test issue-2694-cve-counter.test.ts (pure unit, no CLI). Updated security-scan-persistence.test.ts to assert CLEAN/0/0 for the empty fixture (was asserting cvesFixed>=1, the fabricated behavior). |
||
|
|
8306ad8fe5 |
fix(helper-refresh): also refresh ~/.claude/helpers so global statusline picks up new features
Before 3.31.3, autoRefreshHelpersIfStale only touched <cwd>/.claude/helpers. But Claude Code's global settings.json falls back to ~/.claude/helpers/statusline.cjs when no project-local override exists (executor.ts:460-462), and that global file was frozen at whatever version was current when the user last ran `ruflo init` — nothing refreshed it. So when the 2026-07-13 funnel/promo Line-3 row shipped (PR #2622), users who init'd earlier couldn't see it even after upgrading @claude-flow/cli — their global statusline literally didn't have the render code. Fix: - Extract per-dir refresh into refreshOneHelpersDir() - Add alsoRefreshGlobal: boolean opt-in to autoRefreshHelpersIfStale — defaults FALSE so tests don't touch $HOME - Real CLI entry (src/index.ts) passes alsoRefreshGlobal:true, activating the global pass in production - Same forward-only semver.gte downgrade guard applies to both passes - Result type gains optional `global` sub-object; top-level fields still describe the project pass (API compat) Test additions: two new cases in helper-refresh.test.ts — one exercises the global pass end-to-end under a redirected HOME (proves the fix works), one asserts alsoRefreshGlobal:false is the default and never scaffolds under $HOME (invariant that keeps every other test in this file safe). All 9 tests pass. Bumps @claude-flow/cli, claude-flow, and ruflo to 3.31.3 (PATCH — behavior extension, no API surface change; existing single-object return shape unchanged for callers that don't opt in). Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
3e9122a310 |
feat(routing): default to latest Claude 5/4.x models in tier map + init template
- MODEL_MAP: `sonnet` alias bumped from claude-sonnet-4-6 → claude-sonnet-5 (matches the current Claude 5 family default). Prior pin remains reachable via new `sonnet-4.6` alias for back-compat. - DEFAULT_ANTHROPIC_MODEL and `inherit` now resolve to claude-sonnet-5. - ruflo init template (settings-generator.ts): top-level `model` set to claude-sonnet-5 (previously commented out with a stale sonnet-4-5 hint); `claudeFlow.modelPreferences.default` bumped from opus-4-8 → claude-sonnet-5. - Project `.claude/settings.json` synced with the new template output (model + modelPreferences); removed the stale skillListingBudgetFraction rationale comment (kept the 0.06 value — #1834 still has 358 SKILL.md duplicates, workaround is still load-bearing). - Test updates for #2232 / #1906 regression guards to assert the new sonnet-5 resolution and the new `sonnet-4.6` back-compat alias. Bumps @claude-flow/cli, claude-flow, and ruflo to 3.30.4 (PATCH — no API change, default-model refresh only). All 30 model-resolution/sampling-params tests + 400 commands-deep tests green. Follow-up: sampling-params regex in agent-execute-core.ts (#2357) may need `sonnet-5` added if Sonnet 5 rejects temperature/top_p/top_k like the rest of the Claude 5 family — not touched here because I don't have that behavior confirmed. Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
30e41c23f3 |
fix(#2679): sync statusline-generator with committed helper (read+substitute pattern) (#2680)
* fix(#2679): sync statusline-generator with committed .claude/helpers/statusline.cjs Closes #2679. Replaces the 946-line inline template string in generateStatuslineScript() with a read-committed-helper-and-substitute pattern. Single source of truth = the shipped .claude/helpers/statusline.cjs. ## Root cause of the drift The generator's inline template shipped as the pre-#2195 non-delegation build. Meanwhile the deployed helper got continuous v3.29.0 improvements (whole-row-clickable OSC 8, (domain) suffix, ellipsis on truncation, bright-white bold command styling, 300s cache TTL, windowsHide on every subprocess spawn). No mechanism kept them in sync — every `ruflo init` regressed a user's install to the older shape. ## Fix generateStatuslineScript() now: 1. Walks up from `__dirname_sg` looking for `@claude-flow/cli`'s package.json. Reads `.claude/helpers/statusline.cjs` relative to that. Falls back to `createRequire.resolve` for the installed-CLI case where walk-up misses (shipped tarball extracted outside a workspace). 2. Substitutes two known values: - `maxAgents: 15,` → `maxAgents: <options.runtime.maxAgents>,` - `let ver = "…";` → `let ver = <bakedVersion>;` (with non-downgrade guard so test environments that resolve to an older node_modules install can't clobber a fresh committed helper) Function body: ~1050 lines → ~60 lines. Every future edit to the helper now propagates to init output automatically. ## Also synced (was silently drifted) `v3/@claude-flow/cli/.claude/helpers/statusline.cjs` was a stale pre-v3.29.0 copy. Copied the root `.claude/helpers/statusline.cjs` (the current v3.29.0 shape) over the top. Re-signed helpers manifest. ## Test updates Three test assertions updated to match the current v3.29.0 helper shape: 1. `statusline-cost-display.test.ts` drift guard — restored to strict byte-comparison after normalizing the version line (the ONE legitimately environment-dependent line — vitest resolves to a different pnpm-installed CLI than production). 2. `funnel.test.ts` "re-sanitizes promo text" — was asserting the old `.slice(0, 100)` truncation; now asserts the v3.29.0 MAX_LEN + ellipsis path. 3. `funnel.test.ts` "styles the label as a link" — was asserting the old `UL_ON + safeTerminalLink(label, promo.url) + UL_OFF` label-only OSC 8 wrap; now asserts the v3.29.0 whole-row wrap via `wrapWholeRowInHyperlink` + the bright-white bold command styling. ## Verified - Local: 135/135 pass across funnel.test.ts + statusline-cost-display.test.ts. - TypeScript build clean. - Direct node call: generator produces exact byte-for-byte match with committed helper (modulo the substituted maxAgents + version). ## Follow-ups tracked None blocking. The `wrapWholeRowInHyperlink` name assertion pins one implementation detail — worth revisiting if we ever refactor that path. Related: v3.30.0 release ( |
||
|
|
74bc81f8ef |
feat(adr-317): Phase 0 scaffold for developer revenue-share on the Cognitum funnel (#2676)
* feat(funnel,adr-317): Phase 0 scaffold for developer revenue-share on the Cognitum funnel
Response to "can we do something similar to kickbacks.ai?" — yes, and about 60-70%
of the plumbing (attribution, consent, rotation, disclosure grace, insight-slot
targeting) already ships in ADR-301..316. The gap is the payment rail. This ADR
scopes the smallest defensible slice: share existing Cognitum sponsor revenue
50/50 with users who explicitly opt in. Auction / advertiser self-serve are
DELIBERATELY OUT of scope (that would be ADR-320+ if we ever go marketplace).
Phase 0 (this PR, client-only scaffold):
- ADR-317 written in v3/docs/adr/ with data flow, consent-domain rationale,
phased delivery plan, and explicit "out of scope" list.
- New consent domain `rev-share-payout` — standalone, never bundled with the
funnel-on/off decision itself or with any other ADR-302-family domain.
- New funnel/payout.ts state module — opaque enrollment token storage,
`isEarningEligible()` gate (consent + verified token both required),
`getAttributionToken()` for future attribution enrichment.
- Three new subcommands: `ruflo funnel enroll` / `earnings` / `unenroll`.
All three refuse cleanly when the funnel is disabled or the disclosure has
been declined (same guard pattern as `accept`/`open` shipped in v3.29.0).
- Backend endpoint (funnel.ruv.io/v1/enrollment + /v1/earnings) is NOT live
yet — Phase 1 blocks on legal + Stripe Connect setup, called out in the ADR.
The subcommands ship with clear "coming soon" messaging that records local
consent and previews the URL.
Phases 1-3 (out of this PR, tracked in ADR):
- Phase 1: backend enrollment + earnings endpoints in cognitum-one/meta-proxy.
- Phase 2: attribution + payout engine, per-token ledger, monthly Stripe transfers.
- Phase 3: publisher TOS, docs, blog, public launch.
No breaking changes. Semver MINOR (new subcommands, additive).
Co-Authored-By: RuFlo <ruv@ruv.net>
* feat(spinner,adr-318): manage ruflo verbs in Claude Code's spinnerVerbs rotation
Ships alongside ADR-317 (per product decision) — same PR, but architecturally
distinct: this ADR is about a NEW placement surface (Claude Code's spinner
"✽ Channeling…" area, exposed via the documented `spinnerVerbs` settings key
in ~/.claude/settings.json), while ADR-317 is about a NEW consent model for
the existing statusline promo surface.
Key guarantees (from ADR-318):
- Append-only, never replace. Refuses if user already has replace mode.
- Backup ~/.claude/settings.json before every write (dated .bak-* files).
- Ruflo verbs tagged with a zero-width joiner triple (invisible in every
terminal), so `disable` strips ONLY ruflo verbs and leaves user-authored
ones intact.
- Full mix from day one (per product decision): Cognitum-branded verbs and
neutral tips both rotate together. The `enable` confirmation prompt IS
the disclosure — the pool is printed in full including Cognitum-tagged
entries before consent is recorded. This trades some ADR-311 "disclosure
before promotional content" invariant for user-visible transparency at
the consent moment.
Validation (rejects any pool entry that isn't):
- Present participle (some word ends in -ing). Was `/ing$/i.test(stripped)`
which required the WHOLE string end in "ing" — that rejected every
multi-word verb in the pool. Now checks per-word.
- ≤ 30 chars after marker strip.
- No control chars, ANSI, URL patterns, bidi overrides.
Subcommands (`src/commands/spinner.ts`, registered in commands/index.ts):
- `ruflo spinner list [--json]` — pool + installed + user-authored
- `ruflo spinner enable [--yes]` — preview + write (requires --yes to write)
- `ruflo spinner disable` — strip ruflo verbs only, preserve user verbs
- `ruflo spinner reset --yes` — restore most recent settings.json backup
New consent domain `spinner-verbs` in types.ts + consent.ts (never bundled).
v0 verb pool (baked into this PR; v1 will be remote-served from
funnel.ruv.io/v1/messages?class=spinner-verb per ADR-318 §Data flow):
Neutral: Optimizing your prompt, Consulting the memory graph, Warming
the HNSW index, Learning from the trajectory, Auditing for CVEs,
Sharpening the plan
Cognitum: Consulting Cognitum, Checking Cognitum credits, Routing via
Cognitum, Fetching a Cognitum tip
Verified end-to-end on Windows:
- enable --yes → 10 verbs appended, backup taken
- list → all 10 shown under "Currently installed ruflo verbs"
- settings.json direct inspection → mode="append", verbs[0] has trailing
ZWJ marker (hex e2808d×3)
- disable → strips all 10, preserves user-authored (0 in this test)
- No breaking changes; original settings.json restored via the backup
Co-Authored-By: RuFlo <ruv@ruv.net>
* feat(spinner,adr-318): expand v0 verb pool from 10 to 37 verbs
Per product decision — richer append-mode rotation. With Claude Code's
~50 built-in verbs and our 37 mixed in, users see a ruflo verb roughly
42% of the time (was ~17% at 10 verbs); Cognitum-tagged verbs sit at
~7% of all spins (6 of 37 ruflo, mixed with defaults).
Categories (see commands/spinner.ts):
- Memory & retrieval (7): Consulting the memory graph, Warming the
HNSW index, Recalling similar patterns, Searching semantic memory,
Reranking with MMR, Traversing knowledge graph, Loading trajectory context
- Optimization (6): Optimizing your prompt, Sharpening the plan,
Compacting the context, Distilling the trajectory, Reducing token spend,
Compressing the working set
- Learning & intelligence (6): Learning from the trajectory, Training
the router, Judging past verdicts, Consolidating memories, Reasoning
through the graph, Predicting the next step
- Security & audit (4): Auditing for CVEs, Scanning dependencies,
Verifying signatures, Guarding against injection
- Agents & swarm (4): Spawning subagents, Coordinating the swarm,
Reaching consensus, Balancing the workload
- Workflow (4): Routing to the best model, Warming background workers,
Analyzing the diff, Sharpening the review
- Cognitum-tagged (6): Consulting Cognitum, Checking Cognitum credits,
Routing via Cognitum, Fetching a Cognitum tip, Warming Cognitum cache,
Weighing Cognitum options
All 37 validated: at least one word ends in -ing, ≤ 30 chars, no
control chars / ANSI / URL patterns / bidi overrides.
Co-Authored-By: RuFlo <ruv@ruv.net>
* feat(announcements,adr-319): manage ruflo entries in Claude Code's companyAnnouncements startup rotation
Response to "can we include tip text also?" — turns out the "Tip: Double-tap
esc..." line specifically isn't documented as customizable, but Claude Code
DOES expose companyAnnouncements: string[] in ~/.claude/settings.json,
cycled at random on startup. That's the closest documented surface for
"give ruflo a place to speak" and it ships with the same guarantees as
ADR-318's spinner-verbs.
Ships in the same PR as ADR-317/318, sibling surface:
- Higher-attention (rendered prominently at startup) but lower-frequency
(once per Claude Code launch vs. every processing pause) than spinner-verbs
- Same architectural pattern: append-only, backup-first, ZWJ-marker-tagged
for clean removal, opt-in via consent domain, "full mix from day one"
(Cognitum-branded entries in the enable-time preview IS the disclosure)
Additions:
- ADR-319 documents the surface + guarantees + explicit out-of-scope list
- New consent domain `company-announcements` (never bundled, independent
from spinner-verbs — a user might reasonably want one without the other)
- funnel/consent.ts + funnel/types.ts additions
- commands/announcements.ts — new top-level subcommand group with
enable/disable/list/reset (mirror of commands/spinner.ts pattern)
- commands/index.ts registration
v0 pool (baked, 12 entries):
- 9 neutral product tips (memory graph, background workers, semantic search,
security scanner, doctor, cost routing, etc.)
- 3 Cognitum-tagged (sponsor mention, credits, overflow routing)
Validation bug fixed during smoke test — the naive `/[ - ... ]/`
character class regex from commands/spinner.ts, when written with raw
UTF-8 bytes in source, JavaScript (without the `u` flag) parses byte
sequences as literal byte ranges. Since every announcement starts with an
emoji (multi-byte UTF-8), all 12 falsely failed validation. Rewrote as
per-code-point iteration using String iterator + codePointAt — correct
Unicode semantics regardless of source encoding. Spinner-verbs verbs
happen to be plain ASCII so its identical regex works today by accident;
worth a follow-up to fix defensively (see ADR-319 §Consequences).
Verified end-to-end on Windows:
- list → shows all 12 in pool, 0 installed
- enable --yes → 12 written to settings.json companyAnnouncements array,
backup taken, sample verb has trailing ZWJ marker
- disable → removes all 12, preserves user-authored (0 in this test)
- reset (not exercised in this smoke) → available via the fourth subcommand
Co-Authored-By: RuFlo <ruv@ruv.net>
* feat(hook,adr-318,adr-319): first-run auto-enable for spinner + announcements, opt-in via RUFLO_AUTO_ENABLE_SURFACES=1
Per product decision — auto-enable-on-session-start for the two surfaces
(spinner verbs, startup announcements). Default OFF because shipping this
default-on is a company-level product call, not a mechanism call; this
commit ships the mechanism.
## Mechanism (hook-handler.cjs session-restore case)
New `firstRunAutoEnableIfEligible()` runs at the top of the session-restore
handler. Multiple gates — any TRUE skips:
- `RUFLO_AUTO_ENABLE_SURFACES` not truthy (default posture — no auto-enable)
- `RUFLO_NO_AUTO_ENABLE` truthy (explicit opt-out escape hatch)
- CI / GITHUB_ACTIONS truthy
- stdout is not a TTY (piped / non-interactive)
- Marker file at ~/.ruflo/first-run-enabled.json already exists
On success:
- Detached spawn `ruflo spinner enable --yes` + `ruflo announcements enable --yes`
(fully non-blocking — session-restore latency unchanged)
- Sync-write marker so a same-tick session-restore doesn't re-fire
- One-line stderr notification: what happened + how to disable + restart hint
## Additional fix — spinner.ts validator
Applied the same per-code-point isControlOrBidiOverride() fix to
commands/spinner.ts that commands/announcements.ts got when adding
emojis broke its validator. Today's spinner pool is pure ASCII so
the old naive `/[…]/` char-class regex worked by accident; this
prevents the same broken-emoji-validation trap the next time anyone
adds an emoji verb. Deleted the now-dead stub function.
## Verified live on Windows
Simulated session-restore with RUFLO_AUTO_ENABLE_SURFACES=1:
- Marker absent → wrote 37 verbs to spinnerVerbs + 12 to companyAnnouncements
- Marker written to ~/.ruflo/first-run-enabled.json
- Notification printed to stderr
- Second call (marker present) → silent no-op, correct
- Without the env var → silent no-op, correct
- No blocking of session-restore's own output
## Not shipped in this commit
- Default-on posture (still requires env opt-in) — deliberate; that's a
company/product decision, not a mechanism decision
- `disable` subcommands writing the marker (would prevent re-enable if
user disables BEFORE first-run auto-fires) — edge case, worth a
follow-up but not blocking
- User's existing hook-handler.cjs won't have this code until they upgrade
ruflo past this release
Co-Authored-By: RuFlo <ruv@ruv.net>
* feat(hook,adr-318): spinner default ON for new installs, announcements stays opt-in
Per product decision (ruv, this session) — flip spinner-verbs auto-enable from
opt-in (RUFLO_AUTO_ENABLE_SURFACES=1) to default-on. Announcements remain
opt-in via RUFLO_AUTO_ENABLE_ANNOUNCEMENTS=1 because the intrusion profile
is meaningfully different (prominent startup line vs. per-spin flash mixed
with Claude Code defaults).
## Split rationale (ADR-318 amended §First-run auto-enable)
Spinner verbs — default ON:
- Low intrusion: per-spin flash, ~40% of spins with 37 verbs + Claude Code's
~50 built-ins in append mode
- Reversible in one command: `ruflo spinner disable`
- Backup taken automatically before write; append-mode preserves defaults
- Notification-at-first-render IS the disclosure (satisfies ADR-311 for
this surface)
Announcements — default OFF:
- Higher intrusion: prominent line at every Claude Code startup
- Opt-in via RUFLO_AUTO_ENABLE_ANNOUNCEMENTS=1 or explicit
`ruflo announcements enable`
## Env-var summary (both surfaces)
Master opt-out: RUFLO_NO_AUTO_ENABLE=1 (kills both)
Spinner-only opt-out: RUFLO_NO_AUTO_ENABLE_SPINNER=1
Announcements opt-in: RUFLO_AUTO_ENABLE_ANNOUNCEMENTS=1
Plus auto-skip in CI / GITHUB_ACTIONS / non-TTY.
## Notification (stderr) reflects actual state
- Default: "enabled spinner verbs. Disable anytime with `ruflo spinner disable`.
Announcements stay opt-in — set RUFLO_AUTO_ENABLE_ANNOUNCEMENTS=1..."
- With announcements: "enabled spinner verbs + startup announcements. Disable anytime with..."
- Master opt-out: no notification (function returns early)
## Verified live on Windows (3-way)
- Default (no env): spinner enabled 37, announcements 0, notification correct
- With announcements opt-in: both enabled (37 + 12), notification names both
- With RUFLO_NO_AUTO_ENABLE=1: no notification, function returns before any spawn
## Not shipped here (follow-ups)
- `spinner disable` / `announcements disable` should write the marker so
disabling BEFORE first-run auto-fires doesn't get clobbered on next
session-restore. Edge case but worth fixing before default-on ships to
the whole user base.
- Release notes for the next stable bump need to call out the default
behavior change (existing users get spinner verbs added to their
settings.json on their next Claude Code session).
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(helper-refresh): opt-out via .LOCKED marker + RUFLO_HELPERS_LOCKED env
Fixes the recurring concurrent-session clobber documented in CLAUDE.md
(commit
|
||
|
|
0052b1b06d |
security: rotate helpers-signing key (RUFLO_HELPERS_PUBKEY v2) (#2673)
The previous Ed25519 private key was accidentally exposed in a Claude Code session transcript today while attempting the v3.29.0 publish flow — the gcloud secret fetch was invoked in a way that printed the PEM to the tool log, which is captured in the session's persistent transcript. Mitigation (already done at rotation time): - New Ed25519 keypair generated locally. - New private uploaded as GCP Secret Manager version 2 of `ruflo-helpers-signing-key` in the `ruv-dev` project. - Old GCP secret version 1 DESTROYED (not just disabled) — cannot be re-enabled from state or previous access tokens. - New public key baked into RUFLO_HELPERS_PUBKEY here. Compatibility (atomic per-version — no transition dance needed): - Users on ruflo <= 3.28.0 keep the old baked pubkey and continue to verify their locally-shipped manifest (also signed with the old key) successfully. Their helpers stay valid. - Users upgrading to ruflo >= 3.29.0 receive both the new baked pubkey AND the manifest signed with the new key in the same package — helper-refresh verifies cleanly on first run of the new CLI. Follow-up urgency: upgrade to v3.29.0 as soon as possible so any tampered tarball signed with the leaked v1 key can't survive against a fresh verifier. Old CLIs remain "trust v1 pubkey" until they upgrade — an attacker with the leaked key could still forge a manifest that verifies against those old installs. This is the last-mile risk of any rotation. Also updates scripts/verify-helpers.mjs, which duplicates the pubkey inline (prepublishOnly gate). Keep the two copies in sync on future rotations — worth a follow-up to make helper-signing.ts the single source of truth. |
||
|
|
f220882025 |
feat(daemon): repository supervisor, structured telemetry, budget CLI, migration warning (#2661) (#2663)
* feat(daemon): repository supervisor, structured telemetry, budget CLI, migration warning (#2661)
Closes the four gaps flagged as still-open against #2661's full root-fix
spec after the containment + dedup phases already shipped (#2662).
1. Repository-level supervisor + worktree leases (workspace-lease.ts,
repo-supervisor.ts). Ten worktree daemons of one repository independently
deciding "is it time to run audit" every tick was the redundant-scheduler
half of the cardinality bug — the budget ledger and job dedup already
bound and dedupe actual spend, but every daemon still ran its own timer.
Exactly one daemon per repositoryId is now elected supervisor (lock-
protected takeover, same pattern as global-ai-budget.ts) and owns the
recurring AI-worker schedule; every other worktree stays a lease-only
participant (15-min TTL heartbeat) running its cheap local-only workers.
An explicit `daemon trigger --headless` still bypasses the gate — it's a
one-off user action, still budget/dedup-governed like any other launch.
2. Structured per-launch token telemetry. `claude --print` now runs with
`--output-format json`; parseClaudePrintJsonEnvelope() extracts input/
output tokens, cost, and API duration, receipted via the budget ledger's
new recordUsage(). Lenient parsing — any schema mismatch degrades to
"no usage captured" rather than breaking existing analysis-output
parsing, since the raw `result` text still flows through unchanged.
3. `ruflo daemon budget show|pause|resume`. Budget state was previously
visible only inline in `daemon status --all`; these give it an
independently scriptable surface. pause()/resume() reuse the exact same
enforcement path as the automatic quota-triggered circuit breaker.
4. One-time upgrade migration warning. A pre-existing multi-daemon fleet
where AI workers were already enabled (old config/env from before this
fix) is exactly the P0 shape #2661 describes — warned once ever (a
persisted marker, not per-command), and only for that specific risky
shape, not a harmless AI-off fleet (already covered by the existing
always-shown fleet-size notice).
`daemon status --all` gains a "Repository Supervisors" panel alongside the
existing budget panel.
54 new tests across workspace-lease, repo-supervisor, claude-print-envelope,
global-ai-budget (extended), and daemon-migration-warning-2661 suites.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(statusline): don't import helper-refresh.js just for getInstalledCliVersion
statusline-generator.ts imported getInstalledCliVersion from helper-refresh.js
(added in
|
||
|
|
9e596df5af |
feat(init): turn on persistent AgentDB memory by default
runtime.memoryBackend already defaulted to 'hybrid' in DEFAULT_INIT_OPTIONS, but that only ever configured the DECLARED backend — the actual .swarm/memory.db file was never created until something eventually called `memory store`, or the user ran `memory init --force` by hand (both the generated CLAUDE.md and the quickstart docs told users to do this as a separate step). A fresh project could sit for days looking "configured for AgentDB" while genuinely capturing nothing, with no signal that the config and the on-disk reality had diverged. executeInit() now eagerly calls initializeMemoryDatabase() when runtime.memoryBackend !== 'memory', matching what the config already promised. MINIMAL_INIT_OPTIONS (memoryBackend: 'memory') opts out, matching its non-persistent intent — pinned by a new test alongside the positive case. Updated the printed "Next steps" list to drop the now-stale "run memory init" instruction. chore(release): bump @claude-flow/cli to 3.27.4. Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
b254e3215e |
fix(statusline): bake in the real CLI version, fixing the npx-only fallback
getPkgVersion()'s runtime candidate scan can't find any version when rendering via a pure npx invocation with no persistent local install: npx installs into an ephemeral, unpredictably-hashed ~/.npm/_npx/<hash>/ directory that none of the probed candidate paths (marketplace, project node_modules, global prefix) can locate. It silently fell back to a hardcoded "3.6" placeholder — confirmed live via an isolated fresh-machine simulation (fresh HOME + fresh npm cache, no prior npx history). generateStatuslineScript() now bakes in the CLI's own real version at generation time (via getInstalledCliVersion(), the same reliable createRequire/findPackageRoot resolution helper-refresh.ts already uses) as getPkgVersion()'s default, replacing the hardcoded placeholder. The runtime candidate scan still wins when it finds something newer (e.g. a later `npm update` in the same project) — this only fixes the fallback. chore(release): bump to 3.27.3 across cli/umbrella/wrapper. Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
6643d44d32 |
fix(statusline): pick highest local package version, not first-found
getPkgVersion() checked the marketplace plugin path first and returned as soon as ANY candidate's package.json existed, without comparing it to the others. Claude Code's plugin marketplace syncs on its own git-pull cadence, independent of npm publishes, so right after a publish the marketplace checkout can sit one (or more) releases behind while a newer install (e.g. this repo's own v3/@claude-flow/cli, or a plain `npm install`) is sitting right there — confirmed live on this machine: header showed 3.27.0 from a stale marketplace copy while the actual code running was already 3.27.1. compareVersions() now ranks every existing candidate and keeps the highest, so the header always reflects the newest install actually present rather than whichever candidate happens to be checked first. Also fixes this repo's own root .claude/helpers/hook-handler.cjs, which had drifted from the (correct, already-published) package copy due to the recurring concurrent-session helper corruption documented in CLAUDE.md — caught by the parity-guard test before this got shipped, since it's committed content, not what npm publish signs from. Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
dbcfe15f3c |
fix(hooks,statusline): validate a real compiled dist before trusting a local CLI candidate
Claude Code's own plugin marketplace mechanism installs by git clone/pull
with no build step, so ~/.claude/plugins/marketplaces/ruflo is a
source-only checkout by construction: bin/cli.js exists on disk but
importing dist/src/index.js from it throws ERR_MODULE_NOT_FOUND on every
real command (confirmed live on a real install — only --version survives
it, since it reads package.json directly).
Both resolveCliBinForHook() (hook-handler.cjs) and resolveCliBinCandidates()
(statusline-generator.ts) picked that doomed candidate first and had no
recovery:
- hook-handler.cjs's spawnDetachedFunnelRefresh()/spawnDetachedAdvisorRefresh()
just gave up silently (`if (!cliBin) return;`) — the funnel promo cache
and ADR-316 advisor tip could never populate for a marketplace install,
on any OS.
- statusline.cjs's getStatuslineData() DID already fall through to the
other candidates and finally npx, but wasted every render's time budget
failing against the broken candidate first — starving the 20s
promo-rotation clock and making the row look frozen/non-rotating even
once it did show something.
Fix: both resolvers now also check for dist/src/index.js next to bin/cli.js
before trusting a candidate. hook-handler.cjs additionally gains a shared
spawnDetachedHookRefresh() that falls back to `npx --prefer-offline
@claude-flow/cli` (detached/unref'd, so the slower cold-start costs nothing
perceptible) when no local candidate has a real dist — mirroring the
robustness the statusline path already had.
Existing installs pick this up automatically via autoRefreshHelpersIfStale
on the next `ruflo`/`@claude-flow/cli` command, no reinstall required.
Co-Authored-By: RuFlo <ruv@ruv.net>
|
||
|
|
87212ddbf7 |
fix(hooks): spawn funnel refresh from the inline hook-handler fallback
generateHookHandler()'s fallback template (used when copying the real package helper fails) never spawned refresh-funnel from session-restore, so a fallback-only install could never populate the promo cache. Mirrors the fix already shipped in the hand-maintained hook-handler.cjs, via a detached/unref'd npx spawn suited to the fallback's context. Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
e803cb2795 |
fix(statusline): remove Windows-breaking 2>/dev/null from CLI delegation
Root cause of a real user report (statusline showing only 2 lines -- missing the promo/insight row -- and the intelligence percentage stuck at 0%, on Windows). getStatuslineData()'s CLI delegation command appended `2>/dev/null` to every candidate, but the execSync call already sets stdio: ['pipe','pipe','pipe'], which captures/discards stderr at the Node level regardless of shell -- the redirect was redundant on POSIX and actively broke every candidate on Windows, since cmd.exe (execSync's default shell there) doesn't understand /dev/null. Every delegation attempt failed, so every render silently fell through to buildLocalFallback() (hardcoded 0% intelligence), and since the promo memo cache is only ever seeded by a SUCCESSFUL delegation, it could never populate on Windows either -- so the row stayed empty release over release. Pre-existing since the #2337 delegation-caching fix (2026-06-10), not introduced this session -- fixed now after a real Windows user hit it on 3.26.0. Left getGitInfo()'s separate `sh -c` usage (git username/branch in the header) untouched -- a related but distinct Windows gap (no `sh` on native Windows) that needs its own fix, not bundled in here to keep this change minimal and reviewable. Added a regression test pinning that the delegation command lines never carry `2>/dev/null` again. All 157 relevant tests pass. |
||
|
|
d0ac73d798 |
feat: Cognitum customer lifecycle funnel — ADR-301..310 + implementation (#2622)
* docs(adr): add ADR-301..305 — Cognitum customer lifecycle funnel New 300-series ADRs defining the ruflo → cognitum.one conversion funnel: - ADR-301: promotional status surface (rotating bottom status row; reaches existing installs via the ADR-174/177 signed helper auto-refresh channel) - ADR-302: one-time post-init capability enrollment prompt - ADR-303: contextual credit-exhaustion recovery/upgrade experience - ADR-304: optional local Meta LLM proxy (localhost:11435 → api.cognitum.one, OpenAI-compatible, local-first) - ADR-305: funnel overview, design principles, success + guardrail metrics Also indexes the new series in the ADR README. Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_013FqZGy1zZ49JivKUSyqDKH * docs(adr): harden ADR-301..305 per review — trust and funnel-integrity gates - ADR-301: signed content boundaries — messages are schema-validated data only, length-bounded, URL-allowlisted, expiry-cached, and sanitized so copy can never emit terminal control sequences - ADR-302: split enrollment into four independent consent domains (account, proxy-install, telemetry, cloud-routing) with versioned consent receipts; acceptance authorizes auth login only - ADR-303: deterministic error taxonomy with explicit provider codes and a fail-closed classifier; no text-matching of provider messages - ADR-304: mandatory data-plane disclosure before cloud routing; proxy installs local-only, cloud routing off until explicit opt-in - ADR-305: attribution rules (event vocabulary, anonymous rotating funnel ID, 7/30-day attribution windows, 90-day retention, verifiable deletion), ordered gate hierarchy with hard integrity/ health/trust gates, automatic circuit breaker via the signed config channel, and an end-to-end acceptance test for existing installs Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_013FqZGy1zZ49JivKUSyqDKH * docs(adr): amend ADR-301/303/304/305, add ADR-306..310 — deployable funnel system Amendments: - ADR-301: existing-install disclosure gate (never promo before disclosure, once per user, decline disables all surfaces), 4:1 educational:promotional content ratio, 30-min repeat cap, no dark patterns, marquee off for screen readers/reduced motion, control precedence chain - ADR-303: Cognitum account service as sole credit authority (GET /v1/credits), canonical CreditErrorCode enum; only COGNITUM_CREDIT_EXHAUSTED triggers the funnel surface - ADR-304: retitled as the proxy *product* ADR; explicit relationship to the internal metallm dev-bridge (shared routing core, versioned compat layer, no implicit contract dependency); runtime deferred to ADR-307 - ADR-305: kill-switch claim corrected — release-bound vs opt-in freshness mechanisms with honest latencies, 24h revocation TTL, last-valid-signed-policy failure mode; normative control precedence (env > enterprise > user > default > remote); two measurement planes (CI release qualification enforces gates; production analytics measures adoption only) New ADRs: - ADR-306: Cognitum auth — PKCE + device flow, keychain-only refresh tokens, incremental scopes mapped 1:1 to consent domains - ADR-307: proxy runtime — Rust single binary, loopback bind + per-user token, platform user services, explicit lifecycle commands, signed no-self-update packaging - ADR-308: versioned public API contract — OpenAPI in both repos, idempotent event ingestion, normative client failure policy - ADR-309: governance — npm-policy commitments, GDPR/CCPA basis, constrained closed event schema with timestamp bucketing, content approval ownership - ADR-310: staged rollout phases 0-6, promotion criteria, three- package rollback discipline, CI gate matrix, final acceptance test Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_013FqZGy1zZ49JivKUSyqDKH * feat(funnel): implement ADR-301/302/303/305 funnel system with release gates Core module (v3/@claude-flow/cli/src/funnel/, local-only, zero network I/O): - precedence.ts: ADR-305 control chain (env > enterprise policy > user config > project config > package default > remote policy); a lower source can never re-enable a higher disable - disclosure.ts: ADR-301 existing-install disclosure gate (never_seen / disclosed_enabled / disclosed_disabled), 72h grace window before any message, decline disables all surfaces - messages.ts: signed-content boundaries: schema validation, 80-col grapheme-aware bound, exact-host URL allowlist, expiry, and hard drop of any C0/C1/ANSI/OSC/bidi sequence (drop, never repair) - rotation.ts: deterministic scheduler; promo only in 1-of-5 slots, 30-min repeat cap, educational fills all other slots - consent.ts: ADR-302 versioned receipts for 5 separate domains; grant AND decline recorded; stale policyVersion means re-ask, never carry forward - credit-errors.ts: ADR-303 CreditErrorCode enum + fail-closed classifier over machine-readable provider codes (never message text); only COGNITUM_CREDIT_EXHAUSTED fires the recovery surface, once per session - events.ts: ADR-309 closed event schema, daily timestamp buckets, bounded local queue, telemetry-consent-gated, opt-out deletes ID+queue - enrollment.ts + promo.ts: surface orchestrators Surface integrations: - hooks statusline --json now computes a promo field (all gates run server-side; failures never break the statusline) - generated statusline.cjs renders the bottom promo row with defense-in-depth re-sanitization + env/CI gates at render time; repo-root artifact regenerated (drift guard green) - init: one-time post-init capability enrollment (--no-signup flag, CI/non-TTY auto-skip, records only the account consent domain) - new command: ruflo funnel status|disable|enable|id - doctor gains a funnel component reporting effective state + deciding precedence source (enterprise audit verification) Contracts and gates: - v3/docs/api/cognitum-v1.openapi.yaml: ADR-308 v1 contract (8 endpoints, error taxonomy mirrored 1:1, normative failure policy, signed policy feed schema with 24h TTL cap) - .github/workflows/funnel-gates.yml: ADR-310 hard gates: invariant suite + runtime suppression proofs (promo in CI = 0, RUFLO_FUNNEL=0 suppression, opt-out persistence, non-interactive init) - __tests__/funnel.test.ts: 50 tests mapping 1:1 to the ADR-310 gate list Verified: cli-core/swarm/memory/neural/security/cli builds green; funnel suite 50/50; statusline-cost-display drift guard + runtime 8/8; init-wizard-bugs and p1-commands green; live smoke of the funnel lifecycle, statusline promo gates (fresh shows disclosure, CI shows nothing, RUFLO_FUNNEL=0 shows nothing, post-grace rotates educational), doctor component, and init under CI. Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_013FqZGy1zZ49JivKUSyqDKH * fix(funnel-gates): mirror the green Build V3 setup (pnpm 8, frozen lockfile, workspace build) The runtime-suppression job failed on the PR because pnpm 9 with a filtered install resolved the bare-semver workspace deps (@claude-flow/cli-core etc.) from the npm registry instead of linking the workspace packages, so the cli tsc build could not find cli-core's dist. Copy the exact setup the passing Build V3 job in v3-ci.yml uses: pnpm/action-setup@v6 pinned to pnpm 8, pnpm install --frozen-lockfile over the full workspace, and a workspace-wide pnpm build. Also install pyyaml explicitly before the OpenAPI parse check. Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_013FqZGy1zZ49JivKUSyqDKH * chore(helpers): pending-insights runaway-storage guard in intelligence.cjs Captured from the session's self-learning hook runtime: recordEdit now caps the append-only pending-insights file at ~512KB by keeping the most recent 2000 lines when consolidation has not drained it, so it can never grow unbounded. Non-fatal, statSync-per-edit cost only. Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_013FqZGy1zZ49JivKUSyqDKH * feat(funnel): rotating sponsor disclosure, statusline redesign, auto-update ## Statusline (client render) Reorganized 4 rows by purpose (Architecture / Runtime / Health / AgentDB): - suppress zero/healthy fields; glyph-only for 🧠 memory % and 💾 RAM MB - drop DDD % duplicate, drop ADR denominator, drop opaque "◆ DB" marker - "Target 150x-12500x" → "Goal 150x-12500x" (plain language) - Health row hides on NONE; collapses to "✓ Security ✓ No CVEs" when clean, reads "N vulnerabilities" (not "CVE checks 0/3") on unfixed findings - kind-based row color: brightCyan for disclosure, brightPurple for promotional sponsor, yellow for educational — reads as *what it is* ## Funnel promo row (ADR-301/305/309) - Rotating disclosure: 3 copy variants on a deterministic 5-min slot with a shared Cognitum sponsor URL. Neutral framing — no "Sponsored by"/ "Powered by" (would read as advertising and lose OSS trust). - OSC 8 hyperlink wrapper: allowlist ships in renderer (cognitum.one hosts only), https-only, TMUX/CI/TERM=dumb suppression, kill-switch env var, defense-in-depth label re-sanitization. Broken URL / non-https / non-allowed host → plain label, never a raw escape. - Attribution: attributionUrl() decorates every outbound funnel link with utm_source=ruflo · utm_medium=statusline · utm_campaign=<kind> · utm_content=<msg-id>. Client-side link builder, ZERO runtime network call — API-down has no effect on render. `fid` (pseudonymous funnel ID) appended only under telemetry consent (ADR-309 privacy default). - Defense in depth: attributionUrl rejects non-https schemes at build time in addition to renderer's OSC 8 allowlist. ## Auto-update for existing installs - statusline.cjs added to CRITICAL_HELPERS + executor.ts + sign-helpers.mjs. - helper-refresh.ts fallback generates statusline.cjs when the installed package isn't resolvable. - Regen script scripts/regen-statusline-artifact.mjs keeps root artifact in lockstep with the generator (drift-guard test enforces). PUBLISH-TIME REQUIRED (only ruvnet-owned key can do): re-run scripts/sign-helpers.mjs with the Ed25519 signing key so helpers.manifest.json includes statusline.cjs's SHA-256. Without it, auto-refresh fail-closes (intended: tampered helper refuses install). ## Tests: 50 → 57 (+ statusline-cost-display drift guard passes) - parameterized invariant over every DISCLOSURE_TEXTS variant - sponsor URL shape (https + cognitum.one) - 5-min rotation determinism - attributionUrl: UTM shape, absent fid without consent, non-https rejection, malformed base URL verbatim - API-down design lock: promo.ts contains no fetch/https/XMLHttpRequest Co-Authored-By: RuFlo <ruv@ruv.net> * fix(statusline): promo row flicker — stale-while-revalidate cache The funnel promo row would appear on cache warm-up then vanish on the next render whenever the 60s cache TTL expired mid-session and the CLI call either failed, timed out, or was resolved to a bin that returned no promo. Root cause: getStatuslineData() fell through to buildLocalFallback() on CLI failure, and the fallback returned a stub object with no `promo` field. Fix: stale-while-revalidate on the /tmp cache. - readCache() now returns { fresh, data }. The TTL only decides whether the data is fresh; the payload comes back either way. - getStatuslineData(): fresh cache → return immediately. Else try the CLI. On CLI failure, if we have any prior cache data, re-apply local overlays and return it. Only if we've never had a good CLI response do we fall to buildLocalFallback(). Effect: the promo row survives CLI hiccups, timeouts, and cache-expiry mid-render. Live verified: cache backdated 5 min, all 3 CLI bins disabled — row still renders the last known disclosure. Test: pins the generator template shape so a future edit breaking the readCache freshness split or the stale-fallback path trips CI. 57 → 58. Co-Authored-By: RuFlo <ruv@ruv.net> * fix(statusline): 3-line design + persistent promo memo Two related fixes for observed live-session bugs. ## 3-line design (promo as line 1) Claude Code truncates the statusline past line 4 with the system-guidance / input-prompt line. The previous 6-row layout (header + separator + 4 purpose rows + promo) put the funnel row on line 6, so it was silently dropped by the viewport. New layout, exactly 3 lines: Line 1 — Promo / disclosure (funnel row, ADR-301 surface) Line 2 — Header (version · git · model · timing · ctx · cost) Line 3 — Compressed ops (Swarm · Hooks · 🧠 · 💾 · Health) Everything on the previous 4 individual rows is now on the ops line, dot- separated. Diagnostic detail (Domains, ADRs count, vectors, MCP count, DB marker) moves behind `ruflo status --verbose` per the earlier design discipline you documented ("Show healthy state only when it confirms readiness. Show zero values only when zero is actionable. Show failures immediately."). ## Persistent promo memo Even with stale-while-revalidate cache, promo would blink out when an older `@claude-flow/cli` cached by npx succeeded but returned JSON with NO promo field. Cause: the older version predates ADR-301, so its statusline JSON schema is missing our field. The cache path only fires when the CLI THROWS — a promoless success clean-writes. Fix: `~/.ruflo/statusline-promo.json` — a 6h-TTL memo of the last known good promo. Every successful render writes it. Every code path (fresh-cache / CLI-success / stale-cache / cold-fallback) calls `overlayMemoPromo(data)` which injects the memo IFF `data.promo` is missing. The funnel row now survives: - fresh cold cache + working CLI ← memo not needed - stale cache + CLI timeout ← stale-while-revalidate path - cache wiped + CLI down ← memo overlay (proven live) - working CLI, promoless response ← memo overlay (the new fix) Live proof: cache wiped, all 5 known `cli.js` bins renamed to `.disabled`, render still emits the 3-line output with promo on line 1. ## Tests: 58 → 60 in funnel suite, 66 → 68 total Pinned in the generator template: - 3-line ordering (promo push before header push before ops push) - PROMO_MEMO_FILE + readPromoMemo + overlayMemoPromo helpers exist - overlay is called on every code path (spot-checked by call count) Co-Authored-By: RuFlo <ruv@ruv.net> * fix(statusline): 3-line order — RuFlo header · ops · promo (top-to-bottom) Per user preference: RuFlo header must be line 1 (not the promo/disclosure row). Reordering the render: Line 1 — Header (▊ RuFlo · git · model · timing · ctx · cost) Line 2 — Ops (Swarm · Hooks · 🧠 · 💾 · Health) Line 3 — Promo (funnel disclosure / educational tip / sponsor) Promo stays within the visible 3-line viewport so Claude Code doesn't truncate it with the system-guidance line. Memo + stale-while-revalidate safety net from the previous commit is unchanged — promo remains visible even when the CLI returns a promoless response. Test invariant updated to pin the new order (header push < ops push < promo push in the generator source). 68/68 tests still pass. Co-Authored-By: RuFlo <ruv@ruv.net> * feat(statusline): underline the promo label as a clickable CTA The sponsor / disclosure row currently reads as flat text — users don't know it's clickable. Two visual affordances added: 1. ANSI underline ([4m / [24m) on the label portion so terminals show it as a clickable link even when they don't render OSC 8 hyperlinks (a universal cue: underline = interactive text). Combined with the existing OSC 8 wrap, modern terminals get a real hyperlink; legacy terminals get a visual affordance. 2. The trailing "· disable: ruflo funnel disable" instruction now renders dim + non-underlined + outside the OSC 8 wrap. It reads as metadata ("here's how to turn it off") rather than as part of the link target (which would falsely imply that clicking anywhere on that text goes to Cognitum). Split happens on the exact anchor " · disable" — educational tips with no disable tail keep their whole text rendered plainly (no underline, no OSC 8, since they have no URL). Test locks the split-and-underline pattern in the generator template so a future refactor that reunifies the row trips CI. 60 → 61 funnel tests · 68 → 69 total. Co-Authored-By: RuFlo <ruv@ruv.net> * feat(funnel): ADR-308 event transport + Cloud Function reference impl Phase 2 client-side telemetry + reference server. Wires the funnel event queue (v3/@claude-flow/cli/src/funnel/events.ts already exists) to the Cognitum analytics endpoint via a fail-silent HTTP batcher, plus an out-of-band credit-exhaustion notifier. ## Client transport (v3/@claude-flow/cli/src/funnel/event-transport.ts) ADR-308 contract: - POST /v1/events with Idempotency-Key header (UUIDv4 per batch) - Consent-gated: zero network activity when `telemetry` consent is off - Bounded batches (MAX_BATCH = 100), exponential backoff on failure, capped at 30x base interval (~30 min) - 4s POST timeout — telemetry never stalls the CLI - Rejects non-https endpoints inside the transport (defense in depth on top of the client-side allowlist) - Credit-exhaustion detection: 402 response OR body containing the exact ADR-303 machine-readable code triggers the notifier ## Credit notifier (v3/@claude-flow/cli/src/funnel/credit-notifier.ts) Persistent user-visible flag at ~/.ruflo/credit-status.json: - markCreditExhausted() — idempotent, stable `since` timestamp - clearCreditStatus() — stamps `cleared`, drops the exhausted flag - creditExhaustedNotice() — user-facing single line with humanized age - readCreditStatus() — inspector for status/tools ## Server reference (services/cognitum-analytics/) Cloud Function reference implementation: - index.js — POST /v1/events handler, Firestore writes to funnel_events + funnel_aggregates + funnel_credit + funnel_idem collections - package.json — Node 22 + functions-framework + Firestore SDK - deploy.sh — gcloud CLI deploy (gen2, us-central1, 402-on-cap ceiling) - sample-batch.json — fixture for smoke tests - README.md — layout, local run, deploy, verification DEPLOY IS HUMAN-DRIVEN. The autonomous loop does not run deploy.sh — that requires a live gcloud session with cloudfunctions.admin on cognitum-20260110 and is outside the hard-fence for automated actions. Everything up to the deploy is scripted; the human runs `./deploy.sh` when ready. ## Tests: 68 total funnel tests (61 → 68, +7 new) - Transport defaults (https + batch cap + backoff floor + timeout ceiling) - No-consent no-op (zero network activity) - Non-https endpoint rejected inside transport - markCreditExhausted idempotence (stable `since`) - clearCreditStatus stamps `cleared` - creditExhaustedNotice humanized age copy - Null return when not exhausted (no false surface) Co-Authored-By: RuFlo <ruv@ruv.net> * feat(funnel): funnel.ruv.io domain mapping for analytics endpoint The cognitum-analytics Cloud Function is now deployed on cognitum-20260110 and reachable at funnel.ruv.io/v1/events (Cloud Run domain mapping) as well as the raw Cloud Run URL. The client's DEFAULT_ENDPOINT points at the ruv.io subdomain so it: 1. survives Cloud Run hostname-hash changes on redeploy, 2. keeps analytics attribution on rUv's own domain (not cognitum.one, which is a separate product surface), 3. reads honestly to users: telemetry for the OSS CLI lives with the OSS author, not with the cognitum.one commercial product. DNS is a Cloudflare CNAME funnel.ruv.io → ghs.googlehosted.com, unproxied so Cloud Run terminates TLS directly. README documents the recreate-from-scratch flow using the CLOUDFLARE_API_TOKEN in Secret Manager on cognitum-20260110. Live infrastructure state: - Cloud Function cognitum-analytics deployed us-central1, revision 00001 - Firestore collections funnel_events / funnel_aggregates / funnel_credit / funnel_idem writing on first accepted batch - Smoke test at deploy time returned {"ok":true,"accepted":1} - Domain mapping created, DNS resolving, cert provisioning pending (Cloud Run polls hourly) Co-Authored-By: RuFlo <ruv@ruv.net> * docs(adr-311): funnel analytics — server-side split to dedicated repo Server implementation of the ADR-308 /v1/events endpoint has been extracted to its own repo: github.com/cognitum-one/ruflo-funnel-api Reasoning captured in ADR-311: - Commercial-side changes (rate limits, tenant model, BigQuery export) don't churn the OSS CLI PR history. - ADR-308 client contract remains the single source of truth for the wire format; the server can be forked or swapped without touching the CLI. - Server security surface (Firestore rules, IAM, key rotation) belongs with whoever runs the endpoint, not tangled with CLI release cadence. Also captures the concrete deployment decisions that came out of standing up the endpoint against cognitum-20260110: - Runtime: Cloud Function gen2, Node 22, us-central1, 256 MiB - Domain: funnel.ruv.io (Cloud Run mapping, Cloudflare CNAME unproxied) - Storage: 4 Firestore collections (funnel_events / _aggregates / _credit / _idem) with ADR-309 retention rules - Credit signal: HTTP 402 + body 'COGNITUM_CREDIT_EXHAUSTED' wires directly into the ADR-303 recovery surface via credit-notifier.ts services/cognitum-analytics/ in this repo is now a pointer README to the dedicated repo; the four source files were verbatim-committed as the initial commit there. Live-verified 8/8 API contract tests + Firestore writes across all 4 collections at time of adoption. Co-Authored-By: RuFlo <ruv@ruv.net> * feat(funnel): remote-served message rotation + agentics.org sponsor + settings command Three linked changes to the funnel rotation surface. ## Remote-served messages (ADR-311 amendment) New client transport `message-transport.ts`: - GET https://funnel.ruv.io/v1/messages (raw: https://cognitum-analytics-63rzcdswba-uc.a.run.app/v1/messages) - 6h TTL local cache at ~/.ruflo/funnel-messages-cache.json - Every fetched message validated through ADR-301 isValidMessage() — schema, host allowlist, control-char strip, 80-col cap — before it can display - Best-effort: fetch failures leave cache intact; no network call blocks render (fire-and-forget from rotation.selectMessage) - Kill switch: RUFLO_FUNNEL_MESSAGES=0 or RUFLO_FUNNEL=0 - Bounded cache: ≤ 128 KiB, ≤ 200 messages - Non-https rejected at builder AND host allowlist (defense in depth) New pool merger `eligibleMessagesFromPools()` in messages.ts: - Remote pool authoritative (admin edits without a CLI release) - In-code pool fallback (cold starts, API-down, kill-switched) - Dedup by `id` — remote wins over in-code for the same id Rotation kicks a background refresh on every selectMessage() call so the first fresh render after CLI startup lands within seconds. ## Server side (cognitum-one/ruflo-funnel-api@521205a) - Added GET /v1/messages handler (single router by req.path in the same function; POST /v1/events unchanged) - Firestore collection funnel_messages with { id, class, text, url?, active } - Cache-Control: public, max-age=21600 for CDN + client caches - Firestore seeded with 23 initial messages (via seed-messages-rest.sh): 16 educational (ruflo tips + tricks) 4 promotional Cognitum 3 promotional agentics.org - Verified live: 200 OK, 23 messages, all 0 rejected by client pipeline ## Copy discipline + settings command - ALLOWED_URL_HOSTS + PROMO_LINK_HOSTS gain agentics.org (both wire layers need it for OSC 8 to render the link) - DISCLOSURE_TEXTS copy: "· disable: ruflo funnel disable" → "· manage: ruflo settings" — user-facing command surface no longer leaks the internal "funnel" term - New `ruflo settings` command (settings.ts) as a friendly wrapper over the existing funnel primitives: ruflo settings Overview + current state ruflo settings notices status Notices row state ruflo settings notices off Turn off (persistent) ruflo settings notices on Re-enable ruflo settings notices id Pseudonymous notices ID - getPromoRow split anchor moved from " · disable" → " · manage" (so only the linked label is OSC 8 wrapped, tail stays dim/plain) ## Tests: 68 → 76 (+8) - Every disclosure variant: no `\bfunnel\b`, contains `manage`, contains `ruflo settings`, ≤ 80 cols, Cognitum-attributed - Split anchor in generator: " · manage" (not " · disable") Co-Authored-By: RuFlo <ruv@ruv.net> * feat(funnel): impressions + click tracking + coarse geo (ADR-311 amend) Adds the analytics coverage that PR #2622's initial funnel work deferred: impressions, clicks, and coarse geo. Consent-gated end-to-end; nothing new about privacy — same closed vocabulary, same daily-bucket timestamps, same pseudonymous UUID discipline. Wired against the live Cloud Function on cognitum-20260110 + Firestore. ## Client — impression firing + click-tracked URLs - FunnelEventName vocabulary gains `promo_impression` + `promo_open` (matches server; ADR-305 amendment recorded in ADR-311 §6) - FunnelEvent schema gains optional `messageId` (≤ 64 chars, [a-z0-9-]) — the join key across impression → click → conversion - recordFunnelEvent() accepts an options object for `messageId` + `now` (backwards-compat with the Date positional form) - rotation.selectMessage() fires `promo_impression` for the selected message on every render — consent-gated, batched via existing transport - attribution.clickTrackedUrl() wraps promotional URLs in the server-side click-redirect so `promo_open` fires before the browser leaves. Disclosure/educational rows still use attributionUrl direct (no click tracking on disclosure) - promo.ts uses clickTrackedUrl for `msg.class === 'promotional'` ## Server (cognitum-one/ruflo-funnel-api@37f584b — deployed live) - KNOWN_EVENTS gains promo_impression + promo_open - validEvent() accepts optional messageId via MESSAGE_ID_RE allowlist - New `GET /v1/click/{messageId}?to=<https-url>` handler: - messageId validated against MESSAGE_ID_RE (prevents path-traversal or forged doc lookups) - `to` must be https AND host must be in CLICK_ALLOWED_HOSTS (cognitum.one + agentics.org variants — compiled in, not Firestore-editable; no open-redirect vector) - Coarse geo from CF-IPCountry / X-Appengine-Country (ISO-3166 alpha-2 country ONLY — never city, never lat/long; ADR-309 privacy invariant) - Firestore write: funnel_events doc + funnel_aggregates row keyed by (surface, event, day, release, messageId, country) - Firestore hiccup NEVER blocks the redirect — user intent > analytics - 302 with Cache-Control: no-store so aggregators see every click - Router extended to match /v1/click/{msgId} paths ## Verified live at commit | Test | Result | |---|---| | Click w/ good target + fake CF-IPCountry:US | 302 → cognitum.one; Firestore captured US | | Click w/ non-allowed target (evil.com) | 400 DISALLOWED_TARGET | | Click w/ http:// target | 400 DISALLOWED_TARGET | | Click w/ `..` path traversal | 405 (routed as method-not-allowed) | | POST promo_impression event | 200 accepted:1 | | POST promo_open event | 200 accepted:1 | | POST event w/ malformed messageId | 200 accepted:0 dropped:1 | Firestore verified: promo_open with `country: US`, `via: click-redirect`, `messageId: promo-cognitum-meta-llm`. Aggregate row present with `count: 1` keyed by messageId+country. ## Coverage summary (ADR-311 §8) - Impressions per message per day: `promo_impression` events + aggregates - Clicks per message per day: `promo_open` events + aggregates - CTR: ratio of the two above - Geo distribution: `country` field on `promo_open` - Conversions: existing `signup_opened` / `account_created` / `proxy_activated` - Notices disabled rate: existing `funnel_disabled` Zero PII, zero prompt content, zero paths — everything remains closed enum, allowlisted message id, ISO country code, or daily bucket. Co-Authored-By: RuFlo <ruv@ruv.net> * fix(statusline): style "ruflo settings" as bold command, not a dead link User feedback: "the area don't link to anything, manage: ruflo settings" — clarified they expected "manage: ruflo settings" to be clickable/actionable. It can't be a real link: a terminal has no safe way to execute a shell command from a click — that would let any server-served promo message run arbitrary commands on the user's machine. So instead of leaving it looking like inert plain text (which reads as broken/half-finished), it now gets its own visual treatment: ✨ <label, underlined + OSC 8 link> · manage: <ruflo settings, BOLD> - "manage: " stays dim (a connector word, no action implied) - "ruflo settings" renders BOLD, deliberately WITHOUT underline or OSC 8 — bold signals "this is the important bit, copy/type it" without the false affordance of "click me" that underline would carry Split changed from `text.indexOf(' · manage')` to the more precise `text.indexOf(' · manage: ')` so the exact command substring can be isolated for its own styling. getPromoRow() now returns three concatenated segments instead of two: label(+OSC8), dim connector, bold command. Test updated to assert: label sandwiched in UL_ON/UL_OFF + OSC8, connector in DIM_ON/DIM_OFF, command in BOLD_ON/BOLD_OFF, and — critically — that the command is NEVER wrapped in underline or safeTerminalLink (regression guard against accidentally making a "command" look clickable again). Verified via hex dump of the live render: ESC[1m immediately before "ruflo settings", ESC[22m immediately after, no ESC[4m or OSC 8 escape anywhere near it. Co-Authored-By: RuFlo <ruv@ruv.net> * fix(funnel): use raw Cloud Run URL until funnel.ruv.io cert lands funnel.ruv.io's TLS cert has not yet provisioned (Cloud Run domain mapping created 2026-07-10 18:33 UTC; Google's cert issuance is async and still pending as of this commit — verified: curl to funnel.ruv.io returns curl exit 35 / HTTP 000, raw Cloud Run URL returns 200). Every client fetch to messages/events/click was silently timing out (by design — fail-silent), so: - the remote 23-message pool never reached any installed CLI - message-transport's cache file never got created - rotation only ever showed the 3 static in-code disclosure variants All three endpoint defaults now point at the raw Cloud Run URL: https://cognitum-analytics-63rzcdswba-uc.a.run.app/v1/{events,messages,click} Marked TEMP in comments. Flip back to funnel.ruv.io once its cert is live (monitor: curl -o /dev/null -w '%{http_code}' https://funnel.ruv.io/v1/messages). ## Live verification performed this commit 1. Forced message-pool refresh — 23/23 messages accepted, 0 rejected 2. Selected messages across 8 consecutive 20s rotation slots — 8 distinct ids returned (7 educational + 1 promotional), confirming rotation moves 3. Impressions queued locally (8/8), consent-gated 4. Flushed queue to live server — 8/8 accepted, queue drained to 0 5. Fired the click-redirect for the selected promotional message with a forged CF-IPCountry: CA header — 302 to agentics.org with UTM+fid intact 6. Firestore confirmed both events landed: promo_impression messageId=promo-agentics-community promo_open messageId=promo-agentics-community country=CA via=click-redirect 7. Total promo_impression docs in funnel_events: 9 (8 new + 1 prior) Co-Authored-By: RuFlo <ruv@ruv.net> * feat(funnel): zero local promo content — fully remote-served, fail-closed Per explicit direction: no local promo content or URLs should ship in the CLI at all. This completes the ADR-311 remote-message architecture: disclosure text, educational tips, and promotional messages are now ALL served exclusively from the Cloud Function / Firestore feed. If the feed is unreachable and no prior fetch has succeeded, the promo row renders nothing — there is no local fallback content to degrade to. ## What changed - messages.ts: MESSAGES array emptied to []. Zero message text/URLs ship in the package. isValidMessage() extended to accept a new 'disclosure' class alongside educational/promotional, with an invariant that disclosure-class text must retain the exact " · manage: ruflo settings" tail (dropped, never repaired, if missing). - types.ts: FunnelMessageClass extended to 'educational' | 'promotional' | 'disclosure'. - disclosure.ts: removed the hardcoded DISCLOSURE_TEXTS/DISCLOSURE_TEXT/ DISCLOSURE_SPONSOR_URL constants and selectDisclosureText(). Replaced with selectDisclosureMessage() — deterministic 5-min-slot selection over the remote pool filtered to class==='disclosure', returning null when that pool is empty (cold start / API down). The disclosure state MACHINE (never_seen / disclosed_enabled / disclosed_disabled tracking) stays 100% local — that's app state, not promo content. - promo.ts: getFunnelPromo() now sources the disclosure row from selectDisclosureMessage(); returns null (fail-closed) when unavailable. Also wires the previously-defined-but-never-fired 'disclosure_shown' event so disclosure impressions are now tracked alongside promo_impression. - statusline-generator.ts: PROMO_LINK_HOSTS gains the click-redirect hosts (funnel.ruv.io + the raw Cloud Run hostname) — these are DIFFERENT from the final-destination hosts (cognitum.one/agentics.org); without this the renderer's independent host-allowlist check correctly refused to OSC-8- wrap click-tracked URLs, which was silently breaking every clickable link this session had just added. ## Server (cognitum-one/ruflo-funnel-api@698aa73 — deployed live) - All 16 educational tips now carry url: https://cognitum.one and a trailing 🔗 glyph (checked to fit the 80-col bound, max observed 78/78). - 3 disclosure-class messages seeded (disclosure-1/2/3), matching the copy this session iterated on, now server-authoritative instead of hardcoded. - promo.ts routes EVERY message with a url (not just class==='promotional') through the server click-redirect, so click tracking is uniform across the whole rotation. - Firestore funnel_messages collection: 26 total (16 educational + 7 promotional + 3 disclosure), all verified live via GET /v1/messages. ## Verified live end-to-end - GET /v1/messages returns 26 messages, 16/16 educational have url set. - Rendered statusline shows a real educational tip (edu-doctor) with a working OSC 8 hyperlink to the click-redirect, underline, 🔗ical suffix. - Click-redirect → 302 to cognitum.one with UTM + fid intact; Firestore captured both promo_impression and promo_open for the same messageId. - Fail-closed proven via test: selectMessage()/selectDisclosureMessage()/ getFunnelPromo() all return null when the remote cache is unseeded. ## Tests: 68 → 70 funnel (78 total incl. drift-guard), all green - New: "ships ZERO local messages" pins MESSAGES === []. - New: disclosure-class validation (manage tail required). - New: 3 fail-closed tests (selectDisclosureMessage / selectMessage / getFunnelPromo all null on unseeded cache). - Rewrote disclosure-variant + promo-orchestrator tests to seed a mock remote cache (matching message-transport.ts's on-disk shape) instead of asserting against removed local constants. Co-Authored-By: RuFlo <ruv@ruv.net> * docs(adr-312): usage-limit downtime prevention — researched, phased plan Direct instruction was to review Claude Code's actual CLI source (not just docs) to determine feasibility of detecting approaching/hit usage limits and surfacing a Cognitum meta-LLM proxy CTA as a downtime- prevention / session-extension mechanism. ## Research performed (grounded against @anthropic-ai/claude-code@2.1.107) Inspected /usr/lib/node_modules/@anthropic-ai/claude-code/cli.js directly. Findings: 1. A real internal rate-limit state object exists (module var, referred to in the ADR by its minified name since it will rename on any version bump): { status: allowed|allowed_warning|rejected, resetsAt (epoch sec), rateLimitType: five_hour|seven_day|seven_day_opus| seven_day_sonnet|overage, utilization (0-1 float), unifiedRateLimitFallbackAvailable, isUsingOverage }. 2. It's sourced from REAL Anthropic API response headers (anthropic-ratelimit-unified-status/-reset/-fallback/-{type}- utilization etc.) — confirmed via string match in the bundle. The exact "You've used N% of your session limit · resets HH:MM" banner text is generated from this exact object by a UI-only formatter. 3. This state is NOT exposed through any current extension point — checked exhaustively, empirically: - statusLine stdin JSON: confirmed absent (only model/context_window/ cost fields exist — verified against ruflo's own parser) - Hook events: 28 hook names exist, none confirmed to fire on rate-limit transitions - Debug logs: EMPIRICALLY checked an existing 11,424-line debug log at default level — zero occurrences of any rate-limit header - No CLI command / MCP resource surfaces it - The only consumer is an internal React hook wired to Claude Code's own TUI, unreachable from outside its process ## Decision: 3-phase plan - Phase 0 (buildable now): manual/self-reported flag — `ruflo settings notices rate-limited` — reusing the exact credit-notifier.ts pattern from ADR-303/311. Honest that this is user-reported, not detected. - Phase 1 (blocked on upstream): file a Claude Code feature request to expose the real signal via statusLine JSON or a new hook event. Explicitly does NOT recommend building against the current minified internal names — fragile, version-coupled, would silently break. - Phase 2 (once Phase 1 lands): wire the real signal into rotation with a priority override analogous to ADR-303's credit-exhaustion surface; new closed-vocabulary events rate_limit_warning_shown / rate_limit_exhausted_shown; same consent-gated click-tracking as every other promo message. No code changes in this commit — ADR only, per the explicit request. Co-Authored-By: RuFlo <ruv@ruv.net> * feat(funnel): sponsored-downtime capacity via cognitum-one/meta-proxy (ADR-312/313) ADR-312 documents grounded research into detecting an approaching/hit Claude usage limit: direct inspection of the installed Claude Code CLI (v2.1.107) found the rate-limit state is populated from response headers (anthropic-ratelimit-unified-status/-reset/-fallback/-*-utilization) that are NOT exposed to hooks, the statusline JSON, or the debug log today (confirmed by grep — zero occurrences in an 11k-line debug log). Automatic detection is blocked on Anthropic exposing this state; documents a 3-phase plan (manual flag now, wait on upstream, auto-wire once available). ADR-313 implements Phase 0: a manually-set rate-limit flag (`ruflo settings notices rate-limited [--clear]`) that, once set, preempts normal promo rotation with a sponsored-capacity CTA — same precedent as ADR-303's credit-exhaustion override. Two states depending on consent: an enable CTA, or a quiet "active" confirmation once `ruflo proxy sponsor-enable --yes` has been run. Client-side (this commit): - funnel/rate-limit-notifier.ts — TTL'd flag read/write/clear, mirrors credit-notifier.ts's shape - funnel/promo.ts — priority-override hook, reachable only after the disclosure invariant is satisfied (ADR-301 compliance preserved) - commands/proxy.ts — sponsor-enable/disable/status/clear subcommands; writes both the consent receipt (source of truth) and a mirror flag into ~/.ruflo/proxy-config.toml, the file the Rust proxy binary reads - funnel/types.ts, consent.ts, events.ts — new 'sponsored-downtime' consent domain and sponsor_mode_enabled/disabled/capacity_exhausted events - 10 new tests (rate-limit notifier + priority override), 80/80 passing Server-side (separate private repo, already built/tested/pushed): cognitum-one/meta-proxy — Rust/axum binary routing local/cloud/sponsored data planes, per-user bearer token, loopback-only bind by default, never falls back to sponsored capacity implicitly. Verified end-to-end: the Rust binary correctly reads the same ~/.ruflo/proxy-config.toml this commit's `sponsor-enable` command writes. * docs(adr-313): addendum — proxy needed /v1/messages, not /v1/chat/completions Verification found the shipped meta-proxy scaffold spoke the wrong wire protocol for Claude Code (OpenAI chat-completions instead of the Anthropic Messages API Claude Code actually POSTs to). Fixed in cognitum-one/meta-proxy and verified live end-to-end with the real installed Claude Code CLI against the live apicompletions Cloud Run service. Documents the fix and the remaining gap (no automated sponsored-key provisioning yet). * docs(adr-313): addendum — fourth Passthrough plane preserves subscription usage Setting the env vars needed to reach the proxy at all previously meant giving up subscription-based auth entirely, all the time, not just when rate-limited. Documents the new default Passthrough plane (real Anthropic via the user's own OAuth token, read-only from Claude Code's own credentials file) and the live verification of all four planes switching correctly within one continuous session. * fix(statusline): trailing blank line so the input prompt gets breathing room The statusline's last row butted directly against Claude Code's input prompt with no visual separation. generateStatusline() now returns lines.join('\n') + '\n', so combined with console.log's own trailing newline the rendered output ends in exactly one blank line. Regenerated both committed .claude/helpers/statusline.cjs copies (root + package) so the drift-guard test stays in lockstep. Two new tests: a source-level pin on the generator (can't silently regress) and a runtime check on the actual rendered bytes (exactly one blank line — not zero, not two). * fix(helpers): re-sign manifest for the statusline trailing-newline fix The earlier statusline fix ( |
||
|
|
1d5b06e4a2 |
fix(federation): unblock main — TS shim types + dispatcher import + witness re-sign (#2604)
* fix(federation): sync shim types + guard optional close() to unblock Build V3
Fixes 7 TS errors on main that block Build V3 across all 3 platforms:
- src/transport/midstream-aware-loader.ts:39-52 — local AgentMessage/
AgentTransport shim was over-minimized by #2578. Restored required
{id, type, payload, metadata?} on AgentMessage and made send/onMessage
2-arg (address, message) to match how plugin.ts actually calls them.
- src/transport/midstream-aware-loader.ts:84 — cast dynamic import()
through `unknown` since upstream's exported AgentTransport carries a
richer InboundMessageHandler surface we intentionally hide behind the
minimal shim.
- src/plugin.ts:481 — this.transport.close is optional (`?`) on the
shim; guard with optional chaining `close?.()`.
Local tsc build clean after fix.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(federation): dispatcher import + re-sign witness manifests (3.25.3 drift)
Two more preexisting main-red root causes, in the same fix:
(1) inbound-dispatcher.ts:22 still imported `AgentMessage` from
`agentic-flow/transport/loader` — the exact phantom subpath #2578
eliminated in midstream-aware-loader.ts. Repointed to the local
shim. This is the residual site #2578 missed; the graph schema smoke
(ADR-130 P1) failure was a cascade of this same TS type collision.
(2) Re-signed verification/{linux,macos,windows}/manifest.md.json via
plugins/ruflo-core/scripts/witness/regen.mjs. The 3.25.3 release
(PR #2602) edited the ADR-104-transport `desc` string in all 3 per-OS
manifests but did not re-run regen.mjs, so the stored
integrity.manifestHash no longer matched sha256(JSON.stringify(
manifest)) and Witness verify exited 1 across all 3 platforms.
Manifests now verify cleanly (117 pass, 0 drift, 0 regressed).
Note: witness/regen.mjs takes --manifest + --history and re-signs
deterministically from manifest.gitCommit; already wired but the
3.25.3 release process skipped it.
Local verify: pass=117 drift=0 regressed=0 missing=0 on all 3 OSes.
Local tsc build: clean.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(hooks): PreToolUse hook emits valid JSON verdict (#2613)
Cursor imports third-party Claude Code hooks under its stricter
`preToolUse` contract, which requires stdout to be a valid JSON
permission verdict (`{"permission":"allow"|"deny"|"ask"}`) and
fail-closes on any other text. The prior PreToolUse commands ran the
ruflo hook shim which prints telemetry to stdout — Cursor then blocked
every Bash/Write/Edit tool call across every workspace.
Fix:
1. ruflo-hook.sh (all three copies) — redirect stdout to /dev/null in
addition to stderr. Claude Code doesn't consume this stdout either,
so silencing it is a pure cleanup with no functional cost.
2. hooks.json PreToolUse commands — after invoking the shim, always
`printf` a well-formed `{"permission":"allow"}` verdict. Valid for
both Claude Code's JSON-hook contract and Cursor's stricter
preToolUse contract, so telemetry keeps working while nothing is
blocked. Also guard `${CLAUDE_PLUGIN_ROOT:-}` so an unset env var
collapses to the safe empty branch instead of a bash parse error.
Simulated Cursor invocation (CLAUDE_PLUGIN_ROOT unset) now emits:
{"permission":"allow"}
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ci): indirect optional-dep imports in cli — @ruvector/*, @metaharness/router (#2608)
Same install-safety anti-pattern as #2586's prime-radiant fix, now
surfaced in @claude-flow/cli once plugin-agent-federation's TS2307
stopped masking it (
|
||
|
|
cd8a9c0988 |
feat: memory distillation self-learning loop (ADR-174) + page-agent browser intent (ADR-175) (#2570)
* feat(memory): distillation service — mine memory_entries into intelligence substrate (ADR-174 M0+M1) Root cause the goal-planner surfaced: the daemon's consolidate worker (worker-daemon.ts:1443) is a STUB writing hardcoded zeros — 6000+ commits recorded to memory_entries but never distilled. reasoning_patterns / episodes / pattern_embeddings / causal_edges were all empty (hence 🧠 0%). M0 (safety) + M1 (service): runDistillation() mines memory_entries into episodes → reasoning_patterns (+pattern_embeddings) → causal_edges. - $0: reuses structured-distill.ts extractor + the embeddings already on each row; no LLM, no re-embedding. - Incremental: distill_state rowid cursor per namespace; never rescans. - Non-destructive: only inserts into the empty target tables; never touches memory_entries. Per-batch transactions. - Safe on the just-recovered DB: quick_check gate skips corrupt DBs; better-sqlite3 optional (silent no-op). - Provenance (ADR-171): feedback outcomes = oracle:test-exec (promotable); everything else = proxy:structural (written, NEVER promoted). Measured on a copy of the real 7,900-entry DB: 7,899 → 4,260 patterns (182 promoted, 4,078 proxy), 4,259 embeddings, 4,258 edges; source unchanged; dry-run wrote nothing; 2nd run processed 0. 6 tests green. ADR-174 records the decision, root cause, param surface, self-opt plan, alternatives, rollback. Follow-ups on branch: M2 CLI, M3 daemon (replace the stub), M4 self-optimization, M5 platform default. Co-Authored-By: RuFlo <ruv@ruv.net> * feat(memory): distill CLI, daemon auto-distill, self-optimization (ADR-174 M2+M3+M4) M2 — CLI: 'memory distill run|status|config' consuming the frozen M1 runDistillation. Full param surface: --dry-run, --namespace, --batch-size, --dedup-distance, --max-entries, --since, --budget-usd, --judge (fable gated on budget per ADR-172), --aggressive/--conservative presets, --config, --db. status reports substrate counts + cursor + provenance breakdown; degrades gracefully. 12 tests. M3 — daemon: replaced the runConsolidateWorker STUB (the root cause — it wrote hardcoded zeros) with a real runDistillation call every 30-min tick, bounded to 1000 entries/tick (cursor drains a backlog across ticks, stays well under the 16-min worker timeout). Real DistillReport written to the metrics file. Opt-out via --no-distill / RUFLO_DAEMON_NO_DISTILL and the existing 'daemon enable -w consolidate --disable'. Never throws (corrupt/ skipped surfaced, not fatal). 7 tests. The loop is now self-sustaining. M4 — self-optimization ('ruflo tuning ruflo'): tuneDistillation grid- searches {batchSize, dedupDistance, promoteThreshold} on ISOLATED copies, scored by MRR@10/recall@10 on a rowid-based held-out split (train/held-out disjointness asserted; held-out scored once). Source checksum unchanged. Honest measured result on the real 7.9k-entry corpus: winner batchSize=200 dedupDistance=0.2 promoteThreshold=execution+corroborated, held-out MRR@10 0.753 vs 0.749 baseline — roughly on par (the substrate/training value is the payoff, not raw retrieval uplift; measured-not-marketing). 11 tests. Combined M1+M2+M3+M4: 30 tests green. Co-Authored-By: RuFlo <ruv@ruv.net> * feat(browser): page-agent natural-language intent layer — browser_act (ADR-175) Adds an in-page NL intent tool on top of the selector-based browser tools: browser_act injects page-agent (Alibaba, MIT) into the agent-browser-driven page and runs 'execute(task)' — one natural-language call instead of manual selector orchestration. Verified against the real page-agent@1.11.0 (ESM-only, split @page-agent/* packages) — three load-bearing deviations handled: - import('page-agent') throws 'window is not defined' in Node even when installed → availability probed via require.resolve (path only, no eval), like browser-session-tools.ts. - the injectable IIFE auto-constructs a second PageAgent pointed at Alibaba's PUBLIC test endpoint (data leak on every call) → stripped before injection (stripDemoAutoInit). - execute() returns { success, data, history } → mapped to { result, steps }. Safety + routing: - Optional dependency (~1.11.0) + v3 pnpm-lock regenerated same change; browser_act returns { degraded:true } (never throws) when absent. - LLM routed through this CLI's Tier-3 ladder (OPENROUTER/OLLAMA, OpenAI- compatible); bare ANTHROPIC_API_KEY degrades (wrong API shape). - KEY SAFETY: page-agent runs in page context, so the real key never enters the injected string — startLocalLLMProxy holds it server-side on a loopback http server and injects Authorization itself; page sees 127.0.0.1 + a placeholder. Tests assert no key substring in the injection. - Trajectory → memory namespace 'browser' (feeds ADR-174 distillation). - AIDefence gates returned content (optional; passes through if absent). ADR-175 records the decision, the outer-harness/in-page split, constraints, the 6 follow-on use cases, alternatives, and rollback. 16 tool tests + 145 mcp-client regression tests green; full build clean. Co-Authored-By: RuFlo <ruv@ruv.net> * fix(browser): fail-closed demo-endpoint firewall for page-agent injection The demo auto-connect (page content → Alibaba's public sandbox at page-ag-testing-*.fcapp.run) was only neutralized by a best-effort text strip that fell OPEN — stripDemoAutoInit returned the source unchanged if the DEMO_MODEL marker moved, silently re-enabling the leak on an upstream bundle change. Verified via the real tarball: the demo endpoint lives ONLY in dist/iife/page-agent.demo.js (6 refs); the library core ESM entry is clean (0 refs). So no fork is needed — the leak is a property of the demo bundle, not the library. Fix: findDemoLeak() firewall + DemoLeakError. buildPageAgentInjection now scans the stripped bundle for known demo-endpoint signatures (page-ag-testing, .fcapp.run, DEMO_MODEL) and THROWS if any survive; the browser_act handler catches it and degrades rather than injecting. This is version-independent and fail-CLOSED — a moved/renamed marker can no longer leak, because the guarantee is 'endpoint absent', not 'marker found'. +4 tests (signature detection, clean-bundle pass, moved-marker refusal, clean-bundle injection). 20/20 green. ADR-175 updated with the fork-vs-fix rationale. Co-Authored-By: RuFlo <ruv@ruv.net> * fix(browser): add ADR-112 discoverability guidance to browser_act description CI failed 4 checks (tool-description audit + 3 smoke contracts that run it): browser_act was the 1 tool of 361 without a 'Use when …' guidance signal. The audit regex captures only the FIRST quoted segment of a multi-line description, so the guidance phrase must lead. Reworded to open with 'Use when …' + 'Prefer … over …' + 'pair with …' + 'Falls back …'. Audit now 361/361, exit 0. Co-Authored-By: RuFlo <ruv@ruv.net> * feat(memory): M5 — promote M4 winning distill config as daemon default (ADR-174) The daemon's consolidate worker now runs the M4-tuned config (dedupDistance=0.2, chosen by the self-optimization grid-search on the real corpus). Honest note in code + ADR: held-out MRR@10 0.753 vs 0.749 baseline — on-par, the substrate/training value is the payoff. Overridable per-run via 'memory distill'. Completes ADR-174 M0-M5. Co-Authored-By: RuFlo <ruv@ruv.net> * docs+fix(memory): address ADR-174 review — honest default, edge contract, invariants (ADR-174) Review fixes: - STATUS: Proposed → Accepted (M0-M5 implemented+tested, pending #2570 merge). - TUNED DEFAULT honestly justified: the M4 retrieval delta (0.753 vs 0.749) is a TIE, so dedupDistance=0.2 is sold as COMPRESSION, not retrieval lift — measured 2,723 vs 4,350 patterns (37% fewer) at 11.6ms/batch, 0 violations. Added an explicit promotion rule (retrieval-neutral within 0.002 AND >=15% compression AND <250ms/batch AND 0 proxy violations). - PARAM TABLE / DEFAULT consistency: dedup default is 0.2 everywhere (service, CLI, daemon). Presets now bracket it: --aggressive 0.3 / --conservative 0.1. - CAUSAL_EDGES OVERCLAIM: edges now carry an explicit contract (edge_type=cooccurrence, provenance_tier=proxy:structural, confidence=0.3, promoted=false) with the rule 'may rank retrieval, must NOT justify autonomous action'. Also fixed a latent bug: edges linked epId-1 (assumed consecutive rowids) → now the actual previous episode id. - EMBEDDING 1:1 invariant enforced: a cluster with no parseable vector is skipped, so every pattern has exactly one embedding (was off-by-one on a malformed source vector). - ADR adds operational invariants + audit SQL, business-value framing, and an acceptance test. +2 invariant tests (embedding coverage, edge contract). 32 distill tests green. Co-Authored-By: RuFlo <ruv@ruv.net> * feat(hooks): capture edit/task FAILURES, not just successes (ADR-174) The DB analysis found 898 feedback records — 100% success, 0 failures — because the post-edit/post-task hooks recorded a hardcoded success:true and never inspected the tool outcome. With no negative examples the oracle tier can't teach good-vs-bad, which caps what distillation can learn. Fix: read Claude Code's PostToolUse tool_response and record the REAL outcome. - isToolFailure(hookInput): conservative detector (positive error signal only) — tool_response.is_error / error / success:false, non-zero Bash exit code, or an error string. Exported + unit-tested (5 cases). - Generated hook (helpers-generator.ts) + the shipped .claude/helpers/ hook-handler.cjs both inline it: post-edit → recordEdit(file, !toolFailed), post-task → feedback(!toolFailed) (feedback() already boosts on success / decays on failure — it was just never called with false). - intelligence.cjs recordEdit(file, success) persists success to pending-insights so consolidation/distillation gets the negative example. The distillation JUDGE (memory-distillation.ts judgeFeedback) already maps success:false → reward 0 / not-promoted, so the substrate is failure-ready; this closes the upstream gap that never produced failures. End-to-end: a failed-edit PostToolUse payload now logs '[LEARN] Edit FAILURE recorded' through the actual shipped hook; a success stays '[OK] Edit recorded'. Co-Authored-By: RuFlo <ruv@ruv.net> * feat(init): version-stamped auto-refresh of critical helpers — hook fixes reach all users, no re-init (ADR-174) The propagation gap: Claude Code hooks run the PROJECT-LOCAL .claude/helpers/*.cjs copies, not the npm package — so npx ruflo@latest never updated them, and users didn't know to re-run init. Any hook fix (e.g. the ADR-174 failure-capture change) reached only people who happened to re-init. Fix: stamp the critical helpers (hook-handler.cjs, intelligence.cjs, auto-memory-hook.mjs) with the installed CLI version; on the next CLI command, if a project's stamp is older than the installed version, silently re-copy them. New lightweight src/init/helper-refresh.ts (fs/path/module only at load; lazily imports the heavy generators only on the rare source-unresolvable fallback). Wired AWAITED into index.ts startup so a fast command can't exit before the copy lands — fast path is a stamp read + string compare (sub-ms); the copy runs at most once per version bump. No-op outside a ruflo project (never scaffolds files in an unrelated dir). Skipped for init/update. executeUpgrade also stamps so an explicit upgrade is current. Verified end-to-end: a stale-stamped project with an OLD (no-failure-capture) hook silently upgrades to the toolFailed logic on a plain 'ruflo --help', and a current project is a no-op (a marker file survives). +4 tests. Co-Authored-By: RuFlo <ruv@ruv.net> * feat(security): Ed25519 signed provenance gate for the helper auto-refresh (ADR-174) The auto-refresh copies auto-EXECUTING hook code from the installed package into projects. npm verifies the tarball at install, not the files on disk after — a sibling package's postinstall (or disk tamper) could overwrite the helpers and the refresh would faithfully propagate the malicious code. Fix (fail-closed): every helper is verified against a ruflo-signed manifest before install. - helper-signing.ts: baked RUFLO_HELPERS_PUBKEY + verifyHelpersManifest() (native Ed25519, same primitive as rvfa-signing.ts). Fail-closed — any bad signature / tampered hash / wrong algorithm → null → refuse. - scripts/sign-helpers.mjs: publish-time signer; private key from $RUFLO_HELPERS_SIGNING_KEY, NEVER committed (kept out of the repo tree). Not shipped (scripts/ is narrowed to postinstall.cjs in files). - helper-refresh.writeCriticalHelpers: verifies the signed manifest + every source helper's SHA-256 BEFORE copying anything; a mismatch is refused and the project's existing helpers are left intact. The generator fallback needs no manifest (it's the CLI's own compiled code = trust root). - index.ts warns loudly on a blocked refresh (potential tampering signal). Threat model: closes post-install/on-disk tampering of the helper files; does not defend a wholesale-compromised CLI (which could swap the baked key too — but then it owns the binary you run). A CI test ('hashes match shipped files') fails if a helper changes without re-signing, so a stale manifest can't ship. Verified end-to-end: a tampered shipped helper → refresh REFUSED (blocked, project helper untouched); restored → refresh succeeds. +6 signing tests. Co-Authored-By: RuFlo <ruv@ruv.net> * chore(security): source helper-signing key from GCP Secret Manager sign-helpers.mjs now resolves the private key from GCP Secret Manager (RUFLO_HELPERS_SIGNING_SECRET, via gcloud secrets versions access) as the preferred source for CI/publish, with the local-PEM fallback (RUFLO_HELPERS_SIGNING_KEY) for air-gapped signing. Key never committed. ADR-174 security note updated. Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
5e29dc1a0d |
fix(statusline): real vector count + self-heal missing vector_indexes on init (#2569)
* fix(statusline): show real vector count + self-heal missing vector_indexes on init Statusline showed 'Vectors ●0' despite thousands of stored vectors. Two root causes, two fixes: 1. DISPLAY (statusline-generator.ts): the vector count and the HNSW row count were fetched in ONE combined SQL statement. On a DB with no vector_indexes table (older CLI / 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 -> 0. Split into two independent statements: the count now always works; a missing vector_indexes can only zero the HNSW flag, never the count. 2. DATA (memory-initializer.ts repairVectorIndexes): such DBs genuinely lack the vector_indexes table + per-namespace rows, which also breaks the HNSW flag and #1941 namespace routing in memory_search. New self-heal provisions the table and backfills accurate total_vectors per namespace. Wired into the existing-DB path of initializeMemoryDatabase (hit on every MCP start + memory init) and into ruflo init, so any ruflo repairs itself automatically. Self-heal is conservative: - No-op (zero writes) once healed — skips work on the common path. - Runs PRAGMA quick_check before ANY write and SKIPS the repair if the DB reports corruption (returns corrupt:true) rather than writing into a malformed btree. Recover via: sqlite3 db .recover | sqlite3 db.new - Does NOT checkpoint (mode=ro readers already see committed WAL frames; forcing a checkpoint on a torn WAL could persist latent damage). - better-sqlite3 optional; silent no-op if the native module is absent. Tests: 5 new heal tests (provision+backfill, statusline queries, healed no-op idempotency, missing-db no-op, no memory_entries no-op). Adjacent init + memory-search suites green. Co-Authored-By: RuFlo <ruv@ruv.net> * feat(memory): auto-recover corrupt memory DB on init (npx deployments self-heal) Extends the vector_indexes self-heal: when the memory DB is structurally corrupt, any npx-deployed ruflo now AUTO-RECOVERS it on init / MCP start instead of just skipping. recoverMemoryDatabase() is safe by construction and universal (better- sqlite3 only — no external sqlite3 CLI dependency): 1. Confirms corruption via quick_check (no-op on healthy DBs). 2. Acquires an EXCLUSIVE lock (BEGIN IMMEDIATE); if another process is writing it SKIPS (reason:'writer-active') rather than racing a writer and losing in-flight writes. 3. Rebuilds a fresh DB table-by-table, skipping any single unreadable table so one bad table can't abort the whole rebuild. 4. VERIFIES the rebuild (integrity_check==ok AND recovered rows >= source readable rows) BEFORE touching the original. 5. Backs up the corrupt DB to <db>.corrupt-<ts>.bak, then atomically swaps in the verified rebuild and drops stale -wal/-shm. On any failure the original + backup are left intact — never destructive. Wired via repairVectorIndexes({autoRecover:true}) at the existing-DB path of initializeMemoryDatabase (MCP start / memory init) and ruflo init. Tests: +3 (backup/rebuild/verify/swap on a synthetically-corrupted DB, healthy no-op, autoRecover recover-then-heal in one call). 8/8 green. Co-Authored-By: RuFlo <ruv@ruv.net> * fix(build): hide better-sqlite3 specifier behind a variable (optional-dep types) CI Build V3 failed on all 3 platforms: TS2307 'Cannot find module better-sqlite3' — a string-literal await import() makes TS statically resolve the optional native dep's types, which CI doesn't install. Use the established variable-specifier pattern (graph-edge-writer.ts) so resolution is deferred to runtime, gated by the surrounding try/catch. Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
46228841d4 |
fix(init): wire self-learning memory bridge on the npx path (#2545) (#2564)
The documented `npx ruflo init` path left self-learning a silent no-op:
`@claude-flow/memory` is an optionalDependency of the CLI, so on the npx
install it lands in the npx cache (`~/.npm/_npx/<hash>/node_modules`), which
is NOT on the node_modules walk-up path from the user's project. The
SessionStart auto-memory hook could never resolve it and degraded to a single
dim "skipping" line at exit 0 — nothing (doctor, statusline, MCP) surfaced it.
Make the documented path actually work, and fail loud when it can't:
- new memory-package-resolver.ts: at init time resolve @claude-flow/memory from
the CLI's own module context (where it IS present) and record its absolute
path in a machine-local sidecar `.claude-flow/memory-package.json`. Reuses the
copy npx already downloaded — no second install, no vendoring.
- executor.ts: init (and upgrade) write the sidecar right after deploying helpers.
- auto-memory-hook.mjs + helpers-generator fallback: read the sidecar first
(Strategy 0), and when memory is genuinely unresolvable, fail LOUD to stdout
AND stderr with actionable remediation instead of a silent dim skip.
- doctor.ts: new "Learning Bridge" check resolves @claude-flow/memory the same
way the hook does; `doctor --fix` repairs it by writing the sidecar.
- README quickstart: add `daemon start` + `doctor --fix` step (issue Part 2).
Before: `doctor -c learning` FAILs ("silent no-op"); hook prints dim skip, no
store created. After: `ruflo init` writes the sidecar, hook activates (Package
✅ Available); when unresolvable the hook says "self-learning imports are
DISABLED" with a fix. Regression test covers resolver + both hook paths.
|
||
|
|
acb5705b70 |
fix(init): #2450 detect bare \claude-flow hooks statusline\ form in migration
The #2448 migration in `executor.ts` only rewrote settings.json entries that ran the statusline via `npx @claude-flow/cli@latest hooks statusline`. Users on v3.13.3 reported (#2450) that their settings still contain the older bare-command form: "claude-flow hooks statusline 2>/dev/null || node .claude/helpers/statusline.cjs ..." That form was not matched by BROKEN_STATUSLINE_RE so the migration left it in place. The bare command cold-loads the ONNX embedding model on every fire (~1s), Claude Code's statusLine refresh times out, and the status bar never renders. Broadened the regex to catch `(npx [flags])? [@]claude-flow[/cli][@<tag>]? hooks statusline` — covers npx + tag, npx + prefer-offline, and the bare form (with or without `||` fallback chains). Migration now rewrites all forms to the local-helper NEW_STATUSLINE_CMD which runs in <20ms. Regex test: catches all 5 broken forms, correctly skips the new `node -e "..."` replacement and the bare local-helper invocation. Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
8009a152f8 |
fix(init,doctor): #2448 — migrate stale npx @latest statusLine + hooks
CRITICAL — affected user reported load average 49 / jetsam / kernel
watchdog panic on macOS 26.1 / 48 GB. Pre-#2337 init wrote
`npx @claude-flow/cli@latest hooks <sub>` into ~/.claude/settings.json
for both the statusLine and the per-action hooks. Each invocation cold-
spawns a Node process (~130 MB) plus an npm registry round-trip to
re-resolve @latest. The statusLine refires every few hundred ms; hooks
fire per tool use. They stack faster than they exit.
The current source already emits the local-helper form
(`sh -c '… exec node "$D/.claude/helpers/<helper>" <sub>'`), but
executor.ts:362 preserved the user's existing `statusLine.command`
verbatim on re-init — so anyone who installed pre-#2337 and upgraded
to 3.13.2 still has the runaway commands.
Two changes:
1. v3/@claude-flow/cli/src/init/executor.ts
- Detect the broken `npx @claude-flow/cli@latest hooks …` pattern
in `existing.statusLine.command` AND walk every hooks.<event>[]
hooks[].command — regenerate to the local-helper form when
matched. Idempotent on already-correct settings.
- Captures the subcommand from the broken string (pre-bash,
post-edit, route, etc.) so the regenerated command preserves
the user's intent.
2. v3/@claude-flow/cli/src/commands/doctor.ts
- New `checkStaleSettingsNpx` health check. Scans both
project-local AND $HOME/.claude/settings.json for the broken
pattern in statusLine + hooks. Reports `fail` with file path
+ offending sections when found, with fix instruction
(`npx ruflo init` to migrate). Reports `pass` otherwise.
- Registered as `stale-settings` in the component map so users
can run `ruflo doctor --component stale-settings` directly.
Smoke-verified against a synthetic fixture containing all three
offender shapes (statusLine, PreToolUse hook, UserPromptSubmit hook
with --prefer-offline prefix). Doctor correctly flagged all three.
Release: 3.13.2 → 3.13.3 (PATCH per semver — pure bug fix).
Published with all three dist-tags (latest/alpha/v3alpha) for
@claude-flow/cli, claude-flow, and ruflo.
Closes #2448.
Co-Authored-By: RuFlo <ruv@ruv.net>
|
||
|
|
499e69a840 |
fix: community bug batch — stale claude-flow@v3alpha references (#2369, #2370, #2371) (#2375)
Three related bugs reported by @dskarasev — all from the claude-flow→ruflo rename leaving runtime references to the deprecated `claude-flow@v3alpha` (or `claude-flow@alpha`) dist-tag. Each one silently routes users / workers / detection to a pre-rename build that lacks autopilot, browser, wasm-agent, and other current MCP tools. #2369 — init/executor: detectExistingRufloMCP misses legacy MCP keys Scenario B (the original report): if a parent directory has a stale `claude-flow@alpha` key, detection doesn't match it, so init writes a NEW `claude-flow`-keyed entry and both servers run simultaneously under different prefixes — duplicate-tool noise everywhere. → detectExistingRufloMCP now also recognises `claude-flow@alpha` and `claude-flow@v3alpha` in both the top-level and project-scoped registration paths. Scenario A (the silent-failure mode): if the LOCAL .mcp.json already exists with a stale key, writeMCPConfig early-returned with a generic "skipped" message, leaving the user with no clue that their MCP server was pointed at a pre-rename build. → writeMCPConfig now parses the existing file and, when it finds a stale key, surfaces a loud message naming the deprecated key and explaining how to fix it (delete .mcp.json + re-init, or --force). #2370 — swarm.ts: swarm_init failure hint pointed at the wrong package The MCP-down error hint told users to run `claude mcp add claude-flow npx claude-flow@v3alpha mcp start` which installs the wrong package and lacks the `-y`/`--` flags that ensure a fresh fetch and avoid claude-mcp flag ambiguity. → Hint now reads `claude mcp add claude-flow -- npx -y ruflo@latest mcp start`. #2371 — ContainerWorkerPool spawns workers with the deprecated tag `buildWorkerCommand()` returned `['npx', 'claude-flow@v3alpha', ...]` — the deprecated tag plus no `-y`, so npx could silently fall back to a locally-installed stale `claude-flow` (e.g. 2.7.35) without fetching. Container workers were running pre-rename builds. → Returns `['npx', '-y', 'ruflo@latest', ...]` instead. Tests - v3/@claude-flow/cli/__tests__/stale-mcp-key-2369.test.ts (10 tests): pins all three runtime contracts, plus a sanity sweep over the whole cli src/ tree (comment-stripped, legacy-key recognition lists excepted) to catch future re-introductions of the deprecated dist-tag. - All 11 init-wizard-bugs tests still pass — no regression in the surrounding init paths. - tsc clean. Co-authored-by: dskarasev <dskarasev@users.noreply.github.com> |
||
|
|
a553da3439 |
fix(daemon): self-terminating TTL + idle shutdown, global status --all, honest HNSW/init footguns (#2361)
Carry-forward of the still-open, fixable-in-ruflo findings from pacphi/ruflo-machine-ref (token-leak + honesty investigations). Most of that kit's findings already landed upstream (#2219 SQLite, #2222 route persistence, #2239 encoder collapse in 3.10.11); this addresses what remained. Daemon token-leak (root cause of multi-day background token burn): - worker-daemon: self-terminating lifecycle. New ttlMs (default 24h) + idleShutdownMs (opt-in) config, sourced constructor > config.json (daemon.ttlSecs/idleSecs) > env (RUFLO_DAEMON_TTL_SECS/IDLE_SECS) > default. A monitor (unref'd, 60s) grace-shuts-down via stop()+exit(0), mirroring the signal path so the foreground ref'd keep-alive can't leave a zombie. An explicit 0 disables (preserves run-until-stopped). - daemon command: --ttl flag (forwarded through the background fork) and TTL shown in the status/start boxes. - daemon status --all: global view across every workspace via the same ps/tasklist scan used by kill-stale, reading each workspace's daemon-state.json for age + TTL and flagging daemons past their TTL/12h. Leaked daemons in other workspaces were previously invisible. Honest status / init footguns: - neural status: getHNSWStatus() now reports real capability (@ruvector/core resolvable) vs in-process load, ending the false "HNSW Not loaded" when the package is installed. - init: keep auth-gated cloud MCP servers (ruv-swarm, flow-nexus) opt-in even under --full via a new --cloud-mcp flag (committed .mcp.json + per-session token cost). - claudemd-generator: emit `ruflo@latest mcp start` (matches the actual generated .mcp.json) instead of legacy `@claude-flow/cli@latest`, and note the daemon's token cost + TTL. Tests: TTL/idle precedence + 0-disable + monitor arming; the extractWorkspaceFromDaemonLine helper behind --all; HNSW status contract updated to assert initialized-vs-available separation. Credit: investigation, reproductions, and statistical eval by @pacphi (https://github.com/pacphi/ruflo-machine-ref). |
||
|
|
eaaf59d1bd |
fix: community bug batch — session atomic writes (#2307), hive-mind await (#2297), statusline storm (#2337) (#2346)
* fix(session): atomic writes to current.json + corrupted-file self-heal (#2307) Apply BIWizzard's diff from the issue verbatim. Same class as #1707 (metrics partial-JSON corruption) and #1637 (daemon-state.json write-race) which were both fixed elsewhere with atomic writes; session.js was missed in that sweep. Changes: - Add atomicWrite(file, data) helper: writes to `${file}.tmp.${pid}` then rename()s into place. rename() is atomic on the same filesystem, so concurrent writers (session-restore, metric, daemon workers, teammates) can't interleave partial content. - Replace all 5 fs.writeFileSync calls on session files with atomicWrite. - In restore(): wrap JSON.parse in try/catch so existing corrupt session files self-heal — log the error and start a fresh session rather than throwing out of the hook. Why this matters: per-fd offsets in writeFileSync mean writer B can overwrite the first N bytes of writer A's payload but cannot shrink the file — A's tail dangles past B's end, producing valid JSON + trailing garbage. session-restore then throws on the bare JSON.parse. Closes #2307. Co-Authored-By: BIWizzard <noreply@github.com> Co-Authored-By: RuFlo <ruv@ruv.net> * fix(hive-mind): await spawned claude before returning (#2297) Per clement-livdeo's root-cause: spawnClaudeCodeInstance() spawned the `claude` child with stdio:'inherit', registered an exit handler for logging only, then returned `{ success: true, promptFile }` immediately. The command handler resolved, the CLI process finished, and the still-initializing `claude` child lost its controlling terminal and was killed/orphaned. The signature tell that confirms the diagnosis: a stray XTVERSION reply ("iTerm2 3.6.1064;1;2;4;6;17;18;21;22;52") leaked onto the next shell prompt — the terminal queried for capabilities, but the child died before reading the answer. Also explains why the existing `claudeProcess.on('exit', ...)` log lines ("Claude Code completed successfully", "Claude Code exited with code N") never printed — the parent was already gone. Fix: await the child's exit (or error) before returning. The existing exit- handler logging now works, and the non-interactive (-p / --non-interactive) path completes only after Claude Code does. Different cause from #1748 (which fixed an MCP-config issue where workers exited because they lacked mcp__ruflo__* tools via --mcp-config). Closes #2297. Co-Authored-By: clement-livdeo <noreply@github.com> Co-Authored-By: RuFlo <ruv@ruv.net> * fix(statusline): resolve installed CLI bin + bump cache TTL 10s→60s (#2337) Per shaal's report: the statusline helper ran `npx --yes @claude-flow/cli@latest hooks statusline --json` on every uncached render, cached only 10 s. Because of the `@latest` tag, npx re-resolves the package from the registry and relaunches the entire @claude-flow/cli on each call. Claude Code refreshes the statusline several times a second while streaming, and with multiple concurrent sessions this spawned a near-continuous storm of `npm exec` / node processes: - load average 40-65 on a 12-core machine (~6 concurrent sessions) - each live `npm exec` process burned 55-90 % of a core - new PIDs every 1-2 s as the storm cycled Raising the local cache TTL alone dropped the reporter's load from ~43 to ~2.3, confirming this delegation as the dominant source. Fix (applied to BOTH the committed dogfood helper at `.claude/helpers/statusline.cjs` AND the init generator template at `v3/@claude-flow/cli/src/init/statusline-generator.ts` so existing and future installs both benefit): 1. New `resolveCliBin()` — mirrors getPkgVersion()'s install-location probing and returns the absolute path to a usable `bin/cli.js` (project / monorepo / plugin marketplace / global node_modules, incl. custom-prefix layouts like ~/.npm-global). 2. `getStatuslineData()` now invokes the CLI directly via `process.execPath` + the resolved bin — no npx, no registry round-trip, no @latest re-resolve. Falls back to `npx --prefer-offline @claude-flow/cli` (no @latest) only when nothing is installed locally, so cold environments still work. 3. `CACHE_TTL_MS` 10_000 → 60_000. Closes #2337. Co-Authored-By: shaal <noreply@github.com> Co-Authored-By: RuFlo <ruv@ruv.net> --------- Co-authored-by: BIWizzard <noreply@github.com> |
||
|
|
0f98c80a9e |
fix(statusline): resolve version for custom npm prefix + populate AgentDB/Tests/Hooks/Integration segments (#2331)
@Tomi2k fix for two real statusline bugs that survived #2195 / #2221: 1. Custom npm prefix (e.g. ~/.npm-global) → version probe missed → hard-coded '3.6' fallback. Adds env-aware probes (npm_config_prefix, PREFIX, ~/.npm-global default) alongside the binDir-relative ones. 2. AgentDB / Tests / Hooks / Integration segments rendered permanent 0/'none' because 'hooks statusline --json' only returns user/v3Progress/security/swarm/system. Adds 4 local-overlay helpers (getLocalAgentDB via read-only sqlite3, getLocalTests via bounded dir walk, getLocalHooks via .claude/settings.json, getLocalIntegration via .mcp.json + ~/.claude.json) wired through applyLocalOverlays(). Security review: clean. sqlite3 query uses mode=ro (no write-lock contention with the daemon), statically-formed SQL (no injection), bounded depth-4 walk, all catches degrade to zeros. |
||
|
|
cc8830d798 |
fix(init): correct MCP allow rule mcp__claude-flow__:* -> mcp__claude-flow__* (#2306)
Closes #2302. One-character fix removing a stray colon from the MCP allow-rule template in settings-generator.ts. The pattern `mcp__claude-flow__:*` is invalid (the colon makes it not match any tool); the correct form is `mcp__claude-flow__*`. Verified the only occurrence in the tree is the one this PR fixes. |
||
|
|
4c01443712 |
fix: #2267 #2257 #2256 #2253 — CI/router/ONNX bug cluster
Four open issues fixed on this branch; #2246 already shipped in source, #2243 and #2259 documented as out-of-scope here (see body). #2267 — v3-ci.yml YAML parse failure on main (5 consecutive failures, 0 jobs created). Root cause: unquoted ": " inside step name "Guard 2 — smoke: generate .cjs ..." — YAML parser saw `smoke:` as a second mapping key. Quote the name. File now parses to 52 jobs. #2257 — `.claude/helpers/router.js` mis-routes at 80% confidence via unanchored regex. Tokens like `cd`/`ci`/`ui`/`add`/`structure` matched inside `decision`/ `infrastructure`/`address`/`addendum`. Switch to a token-list schema with `\b` word boundaries on single tokens (phrases keep whitespace as a natural boundary), drop matched-confidence 0.8→0.6 and fall-through 0.5→0.3 since this is a static heuristic, not a learned classifier. Fixed in canonical generator (`src/init/helpers-generator.ts::generateAgentRouter`) plus the two in-repo snapshots (`v3/@claude-flow/cli/.claude/helpers/`, `v3/@claude-flow/mcp/.claude/helpers/`). Validated against all 11 reported mis-route cases; generator output verified. #2256 — `--version` blocks 60+ s on cold ONNX cache (SIGTERM under 60s timeouts including npx default and MCP stdio 30s window). Short-circuit `--version`/`-V` in bin/cli.js *before* any heavy import — read version straight from package.json and exit. Measured: 60s+ → ~31ms. Does not affect `<cmd> --help` lazy command loading. #2253 — MCP stdio mode pollutes stdout with ONNX init progress, corrupting JSON-RPC and breaking Codex/strict clients. Extend log-filters.ts to redirect known third-party embedder progress prefixes (`Loading model: `, ` Downloading: `, ` Cache hit: `, ` Disk cache hit: `, `Model cache cleared`, `🚀 Initializing `, `✅ `) from console.log to stderr. Filter installed in BOTH `bin/cli.js` (so MCP-mode path benefits before mcp-client.js imports) and `src/log-filters.ts` (CLI mode). Verified end-to-end: `echo '<jsonrpc>' | node bin/cli.js` now returns clean `{"jsonrpc":"2.0","id":1,"result":...}` on stdout with all noise on stderr. #2246 (memory_search_unified 6-namespace hardcode) — already fixed in source (3.10.29, ADR-089). Reporter's environment was 3.10.22 dist. Confirmed present in v3/@claude-flow/cli/dist/src/mcp-tools/memory-tools.js. Ships in the next published version. No code change. #2243 (verify.mjs cannot load @noble/ed25519) — not a code bug. Script already handles missing dep with a clear "Fix:" message and exits 2 (precondition failure). Confirmed signatureValid=true on this checkout. The issue is operational: the external scheduled runner is a source-only checkout that needs to run `npm ci` before invoking verify.mjs. Fix belongs in that runner's config (not in this repo). #2259 (memory-store/list contradictory persistence surfaces) — out of scope for this branch. Architectural fix in memory-bridge.ts dispatch; needs its own PR + tests. Shape: storeEntry/listEntries both call getBridge() but the bridge's read path diverges from its write path. Tracked separately. Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
455152da03 |
fix(intelligence): 4-issue bug cluster — Opus 4.8 + uptime + MCP orphan + Q-encoder
Fixes four user-reported bugs from the same triage round, each with a regression test and the minimal honest fix: #2232 (Opus 4.8 / silent-downgrade): bump `opus` alias to claude-opus-4-8 (keep `opus-4.7` reachable), and route `executeAgentTask` through the existing `resolveAnthropicModel` so literal claude-* ids stop silently collapsing to Sonnet 4.6 via the bare MODEL_MAP||DEFAULT fold. Widens the agent-tools alias whitelist, JSON-schema enum, and updates the statusline / settings defaults. #2235(B) (stale system_status.uptime): read live `process.uptime()` instead of the persisted metrics.startTime, which was the file's creation timestamp and reported ~8.8-day uptime on a freshly-spawned server. (Note: part A — agentdb db-unified legacy SQLite never engaging better-sqlite3 — is in the bundled agentdb package and is upstream-only.) #2234 (MCP server orphan / ~1 GB leak): add a parent-death watchdog to `ruflo mcp start` that exits cleanly when the process is reparented to launchd/init (ppid===1) — i.e. Claude Code has exited. Stops ~50 MB orphans accumulating across restarts and a stale orphan winning the stdio handshake. #2239 (Q-state encoder discards keyword block): replace the 31-bit truncating fold (which silently dropped features 0–31, collapsing keyword-distinct tasks to one Q-state) with a 32-bit FNV-1a fold over the full quantized vector. Bump encoder version to 2 in the persisted model; loadModel resets the Q-table on a v1→v2 mismatch (keeps stats/epsilon). Tests: 17 new regression tests across all four issues; full CLI suite 62 files / 2104 passed / 46 skipped / 0 failed. Closes #2232, #2234, #2239. Closes #2235 (B); #2235 (A) tracked upstream. Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
bb34896656 |
fix: #2219 #2221 #2222 #2215 #2226 — memory/routing/statusline bug cluster (3.10.6) (#2227)
* fix: #2219 #2221 #2222 #2215 #2226 — memory/routing/statusline bug cluster (3.10.6) Five reproducible bugs reported by external contributors (pacphi, casparml, HF-teamdev), each verified against source and covered by a regression test. #2219 (silent write loss, Node 24/26) — agentdb pins better-sqlite3 as an OPTIONAL dep at ^11.8.1, which has no Node 24/25/26 prebuild; the native build fails silently and AgentDB drops to a non-persistent backend. Override better-sqlite3 to >=12.8.0 (ships Node 20–26 prebuilds) in BOTH the root umbrella and the ruflo wrapper (#2112: root overrides don't reach the wrapper). New CI guard audit-better-sqlite3-override.mjs prevents regression. #2226 (pattern store/search backend mismatch) — agentdb_pattern-store and agentdb_pattern-search hit disjoint backends, so stored patterns were never found. Two paths fixed: (a) when the ReasoningBank controller is present, bridgeSearchPatterns now reads LocalReasoningBank.findSimilar/getAll (the same backend store writes to); (b) when the controller is absent (the common real-world state), the memory-store-fallback search Tier-2 now hydrates entry content via getEntry — listEntries returns metadata only (see #2014), so the substring scan previously matched nothing. #2222 (route feedback no-op) — `route feedback` applied the Q-update in memory but the CLI exits before the Q-learner's autoSaveInterval fires, so learning never persisted. Add an explicit awaited router.saveModel() after feedback. #2221 (statusline shows V3.6 on global installs) — getPkgVersion() never probed the global npm root, so `npm i -g ruflo` fell back to the hard-coded default. Derive the global node_modules dir from process.execPath (no npm spawn) and probe it; covers nvm/mise and Windows layouts. Regenerated statusline.cjs. #2215 (flashAttention contradictory state) — system_info emitted a hard-coded `flashAttention: false` while hooks_intelligence reported the live probe. system_info now runs the same getFlashAttention() probe as the authoritative path so the two tools can't disagree. Tests: __tests__/bug-cluster-2219-2226.test.ts (5/5), statusline drift guard still byte-identical (8/8), tsc clean, targeted sweep 120/120. Co-Authored-By: RuFlo <ruv@ruv.net> * fix(deps): #2219 — sync package-lock to better-sqlite3@12.10.0 override npm ci validates lockfile against package.json; the override bumped the resolved version but the committed lockfile still pinned 11.10.0, failing 'npm ci' in CI. Regenerated with --package-lock-only. Co-Authored-By: RuFlo <ruv@ruv.net> |