mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-11-25 06:36:49 +09:00
435deabd04d2cef44cdd171daeacdf22c98eadc9
317
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
ebea43a793 |
Merge pull request #3990 from ruvnet/sec/helper-cli-from-helper-root
fix(helpers): resolve the ruflo CLI from the helper root, not the project (replaces #3953) |
||
|
|
7047b8b030 |
Merge pull request #3949 from ruvnet/fix/helper-module-root-and-session-path
fix(helpers): resolve modules from the helper root and keep session writes in the project |
||
|
|
e625b7104a |
fix(helpers): resolve the ruflo CLI from the helper root, not the project
A home-level helper or a user-level plugin hook serves every opened project.
hook-handler.cjs and statusline.cjs executed a CLI found under the project
(<cwd>/node_modules/{@claude-flow/cli,ruflo}, <cwd>/v3/...), and every npx
fallback ran with the project as cwd, where npx prefers the project's own
install. The plugin shims also resolved `ruflo` through relative PATH
entries, which resolve against the cwd.
- hook-handler.cjs / statusline.cjs (package and repo copies): candidates
are built from the helper's install root; for a project-local helper that
is the project, so its behaviour is unchanged.
- npx fallbacks pass `--prefix <helper root>` (generated hook-handler and
ruflo-hook.cjs too) or, in the plugin shims, `--prefix <plugin data dir or
home>`. The spawned CLI still runs with the project as its cwd.
- ruflo-hook.cjs (all four copies): relative/empty PATH entries are skipped.
Test: helper-cli-resolution-trust.test.ts (11 cases, 10 fail on main);
hook-handler-artifact-parity follows the npx args into cliSpawnArgs().
The signed helpers changed, so the helpers manifest needs re-signing.
|
||
|
|
bc249a0a50 |
fix(helpers): check session dir containment before creating it
start() created SESSION_DIR (mkdirSync / ensureDir) before checking that it resolves inside the project, so a symlinked .claude-flow still got an empty sessions/ directory created at the symlink target. assertSessionDirContained() now resolves the deepest existing part of the path (lstat, so a symlink counts) and start() calls it before creating anything. Applied to all five session helper variants. Test: session-helper-trust.test.ts gains a symlinked-.claude-flow case per variant (5 cases, all fail without this change). |
||
|
|
16bd4ac948 |
fix(init): re-pin every legacy project-helper command form in user scope
pinToUserHelpers() only recognised the #1943 probes, the exact git-root statusline and the git-root ESM import without argv.splice, so `init --upgrade --settings` on the home directory left older shipped forms that always run the opened project's helper: - pre-#1943 `sh -c 'exec node "${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/<x>" <sub>'` and the Windows `cmd /c node %CLAUDE_PROJECT_DIR%/.claude/helpers/<x> <sub>`; - ADR-059 git-root node -e forms (CJS and ESM, with argv.splice); - relative `node .claude/helpers/<x> [sub]` hooks and statusline. It now re-pins any command whose target is a known ruflo helper under .claude/helpers reached through CLAUDE_PROJECT_DIR, %CLAUDE_PROJECT_DIR%, `git rev-parse --show-toplevel` or a relative path, keeping the subcommand. Commands with redirects/chaining, other scripts, or already pinned to HOME are left alone. executeUpgrade() created a missing settings.json with generateSettings(DEFAULT_INIT_OPTIONS), whose targetDir is the module-load cwd; it now passes the upgrade's targetDir. Tests: one case per legacy form, a user-authored/already-pinned case, an upgrade-merge case, and an executeUpgrade missing-settings case. |
||
|
|
d1d9df0891 |
fix(init): pin user-level hook and statusline commands to $HOME helpers
Settings written to ~/.claude/settings.json apply to every project the user opens. The #1943 probe ran `$CLAUDE_PROJECT_DIR/.claude/helpers/<script>` whenever that file existed, so in user-level settings the opened project decided which helper code ran. helper-commands.ts now owns the hook/statusline command forms: - project-level settings keep the #1943 project-first probe, unchanged; - user-level settings (init target is the home directory) get commands pinned to $HOME/.claude/helpers with no project lookup; - `init --upgrade --settings` on the home directory re-pins the probe and git-root forms ruflo generated earlier and leaves user-authored commands. The #1943/#1948 fix invariants now point at helper-commands.ts. Test: settings-user-level-helpers.test.ts (8 cases). |
||
|
|
4cc18753f9 |
fix(helpers): resolve modules from the helper root and keep session writes in the project
A home-level helper can serve whatever project Claude Code opens, so everything that project controls is untrusted input to the helper. auto-memory-hook.mjs / learning-service.mjs: since the #3286 change every module-resolution strategy (memory-package.json sidecar, local v3 dist, createRequire, node_modules walk-up, agentic-flow embedder) was rooted at CLAUDE_PROJECT_DIR, so a project could choose which JavaScript a home-level helper imports. Add MODULE_ROOT (the helper's install root) for module resolution; PROJECT_ROOT stays data-only, so #3286 still holds. session.cjs: end() archived to `${session.id}.json` with the id taken from the project's current.json, so a crafted id could write outside the session directory, and writes followed symlinks. The archive name must now match session-<digits>; current.json counts only as a regular file (lstat); writes use an exclusive temp file + rename; and the project session directory must resolve inside the project. Applied to the packaged helper, both generators (generateSessionManager / generateCrossPlatformSessionManager) and the repository copy. Tests: helper-module-root-trust and session-helper-trust (16 of 21 cases fail on main, all pass now); the #3286 test now places the mock memory package at the helper root. The helpers manifest is not re-signed here: auto-memory-hook.mjs changed, so it needs `scripts/sign-helpers.mjs` with the release key. |
||
|
|
3fb09bc31c | Merge branch 'pr-3528' into feat/release-3.56.0-batch | ||
|
|
610a2e1475 |
Merge pull request #3877 from ruvnet/feat/console-0.36
feat(console): 0.36.0 — Events and Timeline pages: history, sources, severity, query language, lanes, overlays |
||
|
|
1ac200432c |
feat(console): 0.36.0 integration: eventsPersist option, shared whole-batch append argv, hostile-time hardening, init ignores console/
- plugin.json declares eventsPersist (default true); version 0.36.0 in plugin.json, version.ts, smoke.sh - data/append-argv.ts: one dd argv (bs=1M iflag=fullblock) shared by the Events store and the autopilot journal; real-dd 8-writer test fails on the old argv - history decoders and Events/Timeline displays use #3874's timeOf/countOf/isoOf, so a hostile time or count cannot throw - cli init: .claude-flow/.gitignore template lists console/ - ADR-474 updated to the reviewed behaviour and the open low items Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
6258d60127 |
fix(guard): decode $'...' escapes as bash does; adversarial and benign tables for the root-delete guard (#3791)
$'\x2f' and $'\x72m' name the root and rm without any expansion, and a \' inside $'...' does not close the string. The scanner now decodes ANSI-C escapes (octal, \x, \u/\U, \c, the single-letter set, NUL ends the string) in all four copies, and the parity table gains wrapper, flag-spelling, benign look-alike and documented-limit rows. Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
5ae95050c7 |
fix(guard): a quoted empty substitution leaves the word as bash does; # after it stays in the word (#3791)
Real-bash oracle (bwrap, read-only root, logging fake rm; positive controls
detected) over a 63,696-command differential between main and this branch:
- a substitution inside double quotes is now dropped from the word, as its
empty output is, so "`true`"-rf reads as -rf; a placeholder is kept only
when a # follows, so bash -c "`true`#x; rm -rf /" is still read as one
word and caught;
- 1,260 commands main denies and this branch allows: 0 really delete
(bash parses each differently than main assumed);
- of 1,500 sampled commands this branch allows with a root operand, the
201 that really delete are all $(...) substitutions (stated follow-up, 189)
or $- expansions inside sh -c (12); main misses every one too.
Three parity rows added (309 pass). All four copies alike; the generator's
String.raw source keeps no backtick in comments.
(cherry picked from commit
|
||
|
|
94238f06ef |
fix(guard): a substitution starts its word, and an unterminated backtick is text (#3791)
Third review (by reading; its oracle run was cut short): the unquoted
backtick branch did not mark the word as started, so a # right after an
empty substitution was read as a comment and the rest of the line skipped,
`true`#x; rm -rf / among it; bash keeps # inside the word. main denied this
(the backtick was a word character there). Confirmed: the new parity row
fails on the previous head and passes now.
An unterminated backtick (quoted or not) is now literal text, as main read
it, instead of a substitution that swallows the rest of the input. Five rows
added (306 pass); all four copies alike.
(cherry picked from commit
|
||
|
|
b880b825ff |
fix(guard): unescape a substitution body as bash does, scan backticks inside double quotes, rescan any word with a separator (#3791)
Second review, against a real-bash oracle (sandboxed, logging fake rm) over
12k generated commands:
- the backtick body dropped every backslash; bash removes one only before
$, a backtick or a backslash (and " inside double quotes) and drops
backslash-newline, so escaped operands and line continuations inside a
substitution slipped through;
- a backtick inside "..." was kept as text, not scanned, so an empty
substitution inside a quoted operand hid the delete;
- a word was rescanned only if it contained "rm", so a nested shell whose
rm was split by a substitution or a backslash was never read.
One substitution helper now serves both contexts, and any word with a
separator or a backtick is rescanned (still bounded at four levels). All
four copies alike. The reviewer's oracle: misses 632 -> 26 (24 are the $(...)
follow-up, 2 real expansions), 0 regressions vs main. Five deny rows and one
allow row added to the parity table (301 pass; on the previous head exactly
the five new deny rows fail).
(cherry picked from commit
|
||
|
|
54d49ea898 |
fix(guard): scan a backtick substitution as a nested command instead of ending the rm being parsed (#3791)
Adversarial review: making the backtick a command separator reset the rm
state, so an empty substitution among rm's operands hid the delete. Four
commands main denied were allowed (rm -rf `true` /, rm `` -rf /,
rm -rf /tmp/x `:` /, rm -r `:` -f /); the shell drops the empty word, so
each runs as a root delete.
The backtick is no longer a separator. Its body is scanned as its own
command (bounded at four levels, as other rescans), and the enclosing word
and rm state are left alone. All four copies changed alike; the parity
table gains those four rows plus two safe look-alikes (295 pass; on the
previous head exactly the four new deny rows fail).
(cherry picked from commit
|
||
|
|
574e5dd6da |
fix(guard): root-delete scanner catches backticks, $'…' quoting and abbreviated long options (#3791)
The #3698 scanner kept `$` in front of a quote, did not separate on a
backtick, and accepted only the exact `--recursive`/`--force`. So
``echo `rm -rf /` ``, `$'rm' -rf /`, `bash -c $'rm -rf /'` and
`rm --r --f /*` passed the mod and both classic pre-bash helpers. GNU rm
runs each of them as a root delete.
- A backtick separates words and ends a command, as `(` and `)` already do,
and a quoted word that contains one is rescanned.
- A `$` immediately before `'` or `"` is ANSI-C/locale quoting, not part of the word.
- Any unambiguous `--` prefix of --recursive / --force counts as that flag,
as getopt_long does.
The same change is applied to all four copies: the mod, the generator
fallback and both shipped hook-handler.cjs. Fifteen cases are added to the
#3698 parity table (10 deny, 5 safe look-alikes).
(cherry picked from commit
|
||
|
|
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>
|
||
|
|
a0cffd2760 |
fix(init): stop pinning a Claude model in generated .claude/settings.json (#3527)
settings-generator.ts wrote `settings.model = 'claude-sonnet-5'` into every fresh `ruflo init` (and every `init --force`). Claude Code's project settings outrank the user's own ~/.claude/settings.json, so the pin silently overrode whatever model the user had chosen (e.g. the `opus` alias, which follows the newest Opus) and kept every ruflo-initialised project on an older model. The repo's own .claude/settings.json carried the same pin, so every clone and worktree of ruflo itself started Claude Code on it as well. Remove both pins. Ruflo's own routing preferences are unchanged: they live in claudeFlow.modelPreferences, which Claude Code does not read. Merge-mode init never touched `model`, so existing projects keep whatever they already have. Test: __tests__/init-no-model-pin-3527.test.ts (3 cases: generateSettings(), generateSettingsJson(), and the repo's own settings file). 3 failed before this change, 3 pass after. Co-Authored-By: ruflo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_01V1a8mGSFnqMQfDnhKgzf7K |
||
|
|
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>
|