Commit Graph
7782 Commits
Author SHA1 Message Date
Mr. MakandClaude Opus 5 3fc37ef4c1 fix(embeddings): report a skipped model download as failure, not success (#3376)
`embeddings init` skipped the ONNX download whenever the optional
`@claude-flow/embeddings` package was absent — which is every plain
`npm i -g ruflo`, since that package is not declared in the CLI's
package.json at all. It then slept 500ms faking progress, printed a dimmed
"(Skipped — …)" note on the spinner's tail, and fell through to the success
path: "Embedding subsystem initialized", a settings table asserting the model
and 384 dimensions, a `.claude-flow/embeddings.json` recording a `modelPath`
that contains no model, and exit 0.

This is the command `memory/embedding-policy.ts` points users at in its
`[no-stub]` error, so the documented repair for broken embeddings reported
success and changed nothing.

- A download that was requested and did not happen now ends in
  `spinner.fail` + `output.printWarning` + `{ success: false, exitCode: 1 }`,
  per the CLI command contract in docs/MCP_CLIENT_GUIDE.md. `--no-download`
  still exits 0: no download was asked for.
- `embeddings.json` gains additive optional `modelDownloaded` and
  `modelSkipReason` keys. Every pre-existing key keeps its name and meaning,
  so older readers are unaffected.
- Both `setTimeout(r, 500)` fake-progress delays are gone. The second, in
  `embeddings models --download`, also reported `success: true` for a skip;
  it now fails the same way.

Scope is items 1-3 of the issue. The missing `status`/`download` subcommands
(item 4) are deliberately left alone.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KTedGmPKpEdArVBMMn3JaP
2026-09-20 11:55:56 -04:00
Mr. MakandClaude Opus 5 0a2df2bfd2 fix(metaharness): use the @metaharness/* and ruflo CLI already installed instead of npm-installing at tool-call time (#3366)
On a stock ruflo 3.42.4 install every metaharness_* MCP tool reached for the
npm registry at tool-call time, although the packages it needs are already on
disk. Two causes, in the same six helper files, which is why they ship
together: the helper PINS rejected what ruflo installs, and three code paths
never looked for an installed copy at all. Fixing only the pins leaves darwin
and the memory tools on npx; fixing only the lookups leaves them resolving a
pin that nothing on disk satisfies.

1. Pins (metaharness, @metaharness/darwin)

The metaharness_* tools resolve MetaHarness through the plugin helpers' own
tilde pins, not through package.json. Those pins were never bumped:
_harness.mjs stayed at ~0.3.0 after the CLI declared metaharness ^0.4.1
(b8ec03f34), and _darwin.mjs stayed at ~0.8.0 while the CLI moved
@metaharness/darwin to ~0.9.0 (#2958) and ~0.10.2 (#3262). On a stock install
(metaharness 0.4.2, darwin 0.10.2) findLocalPackageDir() therefore rejected
the bundled metaharness, and every score / genome / mcp_scan / threat_model /
oia_audit / learn call ran
`npm install --prefix ~/.ruflo/metaharness-cache-0.3.0 metaharness@~0.3.0`
at tool-call time — a download of the older 0.3.2 (180 s install budget inside
a 120 s MCP subprocess budget), degraded offline. The darwin tools fetched
darwin 0.8.x through npx while gepa imported the bundled 0.10.2.

- _harness.mjs: METAHARNESS_PIN_VERSION ~0.3.0 -> ~0.4.1 (= CLI ^0.4.1)
- _darwin.mjs:  DARWIN_PIN_VERSION      ~0.8.0 -> ~0.10.2 (= CLI ~0.10.2)
- scripts/check-metaharness-pins.mjs: the watcher compared only the CLI's
  declared ranges (and MH_DARWIN_PIN), so it reported "all current" while the
  pins that decide what runs were two minors behind. It now reads each
  helper's *_PIN_VERSION: the pin must be a `~X.Y.Z` range (the only form
  _invoke.satisfiesTildeRange accepts), and must cover the declared range, or
  admit npm latest when the CLI declares nothing (redblue). An unreadable
  constant is fatal. `satisfies` now shares a `bounds()` helper with the new
  `covers()`; the results for the existing rows are unchanged.
- metaharness-pin-drift.yml also triggers on the three helper files.
- The two current-pin comments in TypeScript (distill-oracle.ts MH_DARWIN_PIN,
  metaharness-tools.ts ADR-153 header) named the old ~0.8.0 plugin pin; they
  now name ~0.10.2. Comments only, no behaviour.

2. No npm/npx at tool-call time (darwin, redblue, memory)

- _darwin.mjs ran `npx -y -p @metaharness/darwin@<pin> metaharness-darwin` on
  every evolve / bench / security_bench call: npm resolved the range each
  time, it ignored the optionalDependency the CLI ships, and it could run a
  different darwin than the gepa import in the same plugin. It now resolves
  like _harness.mjs — installed copy satisfying the pin, then the one-time
  versioned darwin-cache-<pin> that gepa already shares, then
  `process.execPath <abs bin>` with shell:false.
- _redblue.mjs always npm-installed into redblue-cache-<pin> on first use,
  never looking at the installed copy (ruflo 3.42.4 carries 0.1.4). It now
  checks the installed copy first. The chosen CLI path is realpath'd, because
  redblue only dispatches when import.meta.url === file://argv[1]; a
  pnpm-symlinked package dir (or a cache base under /tmp on macOS) otherwise
  makes it exit 0 having done nothing. Its spawn moves to process.execPath
  with shell:false: the argv carries MCP-supplied --config/--out/--in, which
  under the previous `shell: win32` went through cmd.exe unquoted.
- audit-list / audit-trend / oia-audit / similarity ran
  `npx @claude-flow/cli@latest memory ...` — an npm-registry resolution per
  call (the check _harness.mjs already removed for its own npx path), and
  possibly a different CLI version than the server that spawned the tool
  (#3306; cold-cache npx cost #3145/#3154). Without registry access oia_audit
  reported persisted:false and audit_list silently showed 0 records. They now
  call _invoke.runRufloCli(): process.execPath + bin/cli.js of the
  @claude-flow/cli that ships the plugin (<cli>/plugins/ruflo-metaharness, or
  v3/@claude-flow/cli in a checkout). A candidate needs dist/src/index.js next
  to bin/cli.js (mcp-launch.cjs's unbuilt-checkout guard) plus a package.json
  named @claude-flow/cli (a new check, so an unrelated parent directory can
  never qualify). CLI_CORE=1 still opts into `npx @claude-flow/cli-core@alpha`,
  and a layout with no usable local CLI still falls back to
  `npx @claude-flow/cli@latest`.
- drift-from-history.mjs: drop its unused CLI_PKG constant.

The two new lookups end in a spawn of a package bin with MCP-supplied argv, so
they pass findLocalPackageDir(..., { fromCwd: false }) and search only the
ruflo install that owns the plugin — never the tool's cwd or its ancestors.
The pre-existing metaharness lookup keeps its cwd walk unchanged.

Tests (both hermetic, published layout, stub packages, npm/npx PATH trap):

- test-pin-alignment.mjs (+ smoke 17z74a): 3 passed / 9 failed on main,
  12 / 0 here.
- test-no-tool-time-npx.mjs (+ smoke 17r2): 7 passed / 19 failed on main,
  26 / 0 here. It covers both darwin success branches (installed copy and the
  versioned cache), the memory round trip through the shipping CLI, the kept
  contracts (CLI_CORE, npx fallback, a bin/cli.js that is not
  @claude-flow/cli, darwin absent -> degraded exit 0), and the hardening
  above: a darwin/redblue in the tool's own cwd node_modules is never
  executed, a cache dir with package.json but no bin gets one reinstall
  instead of degrading forever, and neither helper spawns the resolved bin
  through a shell.

ADR-150 is unchanged: no static @metaharness import is added, no new
dependency, and every unresolvable path still returns the same
{degraded:true, reason} with exit 0.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KTedGmPKpEdArVBMMn3JaP
2026-09-20 11:55:51 -04:00
Mr. MakandClaude Opus 5 e64caaf372 fix(mcp): revalidate the stdio server's lifecycle, and give the PID record durable identity (#3364)
Review round 2 (@ruvnet on #3365). The first round kept a one-way "has served
stdio" flag so a second stop() could not delete another server's record. That
flag outlived the server it described: after start -> stop, an independent
status query still reported the manager running and checkHealth() still
reported it healthy. On upstream e558f0c0f the same replay reported
{"running":true,...} and {"healthy":false,"error":"No PID file found"} — the
status half is the pre-existing #2934 fallback, the health half was ours.

The flag is now the manager's live lifecycle ('idle' | 'running' | 'stopped'):

  - while it is serving stdio the manager IS the server, so it reports itself
    and never reads or clears the record it deliberately never wrote (the 30s
    health monitor calls checkHealth());
  - once stopped it reports running: false and healthy: false rather than
    whatever PID the shared file happens to hold;
  - 'idle' — a manager that never started, which is what `mcp status`,
    `mcp health` and `mcp stop` build — keeps today's behaviour exactly,
    including the #2934 stdio fallback.

stop() no longer needs a sticky flag: a stopped manager reports not running,
so a second stop() returns at its own guard.

The PID record now carries durable instance identity, the same model #3363
reached for the policy lock: host, platform, Linux PID namespace and kernel
boot id, and the owner's process start time (/proc/<pid>/stat field 22 on
Linux, `ps -o lstart=` elsewhere). A recorded PID is believed only while all
of it still matches, so a PID the OS has since handed to another process, or
one from another boot, host or namespace, is no longer treated as a live
server — it can no longer make an http start refuse, or be SIGKILLed by
`mcp start --force`. A server retracts its record only while the file still
holds, byte for byte, what it wrote.

Format compatibility: line 1 is still the bare PID, so an older ruflo's
parseInt and `head -1` both read it unchanged; line 2 is the identity. A
bare-integer record — an older ruflo's, or `start-mcp.sh --daemon`'s — parses
with no identity and behaves exactly as today. v3/scripts/start-mcp.sh now
reads the first line.

Not covered: PID reuse and boot detection need the identity line, so a record
written by an older ruflo keeps today's exposure; Windows has neither /proc
nor ps, so its records carry no start time and PID reuse stays unqualified
there, as isProcessRunning()'s process-name check already is.

Tests: 13 added (20 total in the file), covering start -> stop -> independent
status/health denial, concurrent ownership, PID reuse and non-owned processes,
and the Windows-shaped inputs. All 13 fail on 85c68888e except the two
labelled as pinning existing behaviour.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KTedGmPKpEdArVBMMn3JaP
2026-09-20 11:55:49 -04:00
Mr. MakandClaude Opus 5 6c2b5d7dff fix(mcp): stdio start no longer SIGKILLs sibling servers (#3364)
`mcp start` on the stdio transport force-"restarted" whatever server was
recorded in the shared PID file — a single slot per os.tmpdir() (per user
on macOS/Windows; the machine-wide /tmp on Linux unless TMPDIR is set).
It sent SIGKILL to that PID, because a stdio server "can't be health-
checked". The victim was simply the last server started through the
command parser: another terminal's stdio server, or a live http/websocket
server that other clients were using. For the same reason, a terminal
stdio server made a later `mcp start -t http` refuse with "MCP Server
already running".

A stdio server is owned by the client that spawned it, over its own
pipes, and any number can run side by side. Only a port-bound transport
is single-instance. ADR-071 made this singleton safe against
self-detection and PID reuse; a stdio server has no business claiming or
killing the shared slot at all. So:

- commands/mcp.ts: a stdio start kills a recorded server only on an
  explicit --force; http/websocket keep their guard unchanged.
- MCPServerManager: a stdio server no longer refuses to start over the
  PID file, writes it, removes it on stop(), or health-checks it. While
  it serves stdio, getStatus() and checkHealth() report the process
  itself rather than whatever PID is recorded. A stale record is still
  cleaned up by the pre-start status read, as before.

The documented piped-stdin `mcp start` (how MCP clients launch it) is
answered by bin/cli.js's inline fast path, which never touches the PID
file. A piped start whose argv does not begin with `mcp` (a leading
global flag) does reach the parser, and is covered too, because the fix
keys on the transport rather than on the TTY.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KTedGmPKpEdArVBMMn3JaP
2026-09-20 11:55:49 -04:00
Mr. MakandClaude Opus 5 cf2177bb4b fix(policy): reclaim state.lock when its owner process is dead (#3362)
acquireLock() records {pid, acquiredAt} in .claude-flow/policy/state.lock
but only ever reclaimed a lock by mtime age (LOCK_STALE_MS = 30 s). Every
MCP tool call, reads included, passes through authorizeMcpTool() ->
withPolicyTransaction() -> acquireLock(). When a server is killed inside a
transaction (SIGKILL, OOM, or a default-action SIGTERM: the bin/cli.js
stdio loop installs no handler), its finally block never releases the
lock, so each call on a fresh server waited LOCK_WAIT_MS and failed with
policy-state-lock-timeout until the orphan aged past 30 s: five 5 s
failures after every such crash.

Reclaim the lock at once when its owner is provably gone:
- The lock now also records host, platform and, on Linux, PID namespace
  and kernel boot id. The pid is trusted only when every field matches
  the reader's, because a sandboxed CLI (bwrap --unshare-pid), a
  container, another kernel boot or another machine sees ESRCH for a live
  owner. host alone is not an identity: two machines sharing a directory
  can report the same hostname, and every Linux init PID namespace has
  the same inode (PROC_PID_INIT_INO).
- Only ESRCH counts as dead (EPERM and any other error mean alive), and
  the pid must be a number, an integer, and in 1..2^31-1 (process.kill
  coerces a numeric string).
- The lock is read only if it is a small regular file (lstat, then
  O_NOFOLLOW|O_NONBLOCK, fstat, at most 1 KiB), so a symlinked FIFO or
  device cannot block the event loop.
- After the probe the lock is re-read and must be byte for byte the one
  that was read, so a lock that changed hands during the probe is not
  deleted. Comparing dev/ino/ctime instead is unsound on Linux: ext4
  reuses a freed inode number at once, and before kernel 6.13 two files
  created in one clock tick share a ctime. Replaying the handover on a
  non-multigrain ext3 mount, the stat triple deleted the live new owner's
  lock in 192 of 200 runs; the byte comparison in 0 of 200.

Every other lock, including one written by an older version, keeps the
30 s mtime rule. ADR-324's lock paragraph is updated to match.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KTedGmPKpEdArVBMMn3JaP
2026-09-20 11:55:48 -04:00
rUv 66f7e53756 docs: add ADR for repository local Git execution boundary 2026-09-20 14:59:45 +00:00
rUv 8ff8aeb4af test: ensure worktree status blocks fsmonitor payload 2026-09-20 14:59:14 +00:00
rUv 043545b079 security: protect workspace identity git calls 2026-09-20 14:58:55 +00:00
rUv 6250562c51 security: route worktree git through safe runner 2026-09-20 14:58:40 +00:00
rUv 6ad2203b1b test: reproduce and block core fsmonitor execution 2026-09-20 14:58:21 +00:00
rUv d1264a4410 security: add repository config safe git runner 2026-09-20 14:57:58 +00:00
rUv a4f219935f docs(adr): ADR-385 — streaming, interactive, long-horizon swarm execution (#3258)
Proposed. Root cause: `ruflo swarm start` (commands/swarm.ts:588-672) never
executes the objective — it prints a plan, calls MCP swarm_init, writes
state.json, prints "execution happens via claude -p / hive-mind spawn --claude"
and returns. Nothing invokes those, so the console's Swarms deploy sets up
coordination then finishes with no work, no artifacts, nothing to find/use/deploy
(agents are registry rows with no process).

Decision: swarm start becomes a streaming, steerable, long-horizon agentic
orchestrator that WIRES existing ruflo primitives (the nested-* / research-agent
recursive-fan-out pattern, claude -p, MCP tools, AgentDB memory, self-learning
hooks, hive-mind raft consensus, agentbbs federation, horizon-tracker) instead of
deferring. Streams NDJSON per-agent (works over the console SSE /run today); a
file-inbox session channel carries real-time guidance; a structured final
overview names artifacts + where to find/run/deploy them.

Hard dependencies stated: agents can't run without the ADR-069 per-tenant LLM
key (prerequisite for the console path); real-time steering needs a bidirectional
channel (file-inbox now, WebSocket later). Increments I1-I4 + an acceptance test.
2026-09-20 13:44:15 +00:00
ClaudeandRuFlo 066a18512a dream(performance): record PR #3378 in ledger row
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01VWUxwsNQVofSGXi8us9dEc
2026-09-20 06:28:21 +00:00
ClaudeandRuFlo 172cfb7322 dream(performance): #3377 event-driven UnifiedSwarmCoordinator task wait (evaluated, ACCEPT)
UnifiedSwarmCoordinator.waitForTaskCompletion()/waitForQueuedTask() busy-polled
state.tasks via setInterval(...,100) despite the coordinator already extending
EventEmitter and already firing task.completed/task.failed at every terminal
task-status transition. Rewritten to be event-driven with a synchronous
pre-check for an already-terminal task and a setTimeout fallback for the
timeout case; setMaxListeners raised to avoid spurious warnings at realistic
concurrency (adversarial-critic finding, fixed same session).

4 new discriminating tests (baseline fails 3/4, candidate passes 4/4 via
stash isolation); real wall-clock benchmark 100.359ms -> 0.206ms mean
(~487x, N=20); 234/234 full swarm-package suite, tsc clean.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01VWUxwsNQVofSGXi8us9dEc
2026-09-20 06:27:13 +00:00
ruv e558f0c0fc chore(release): 3.42.0 -> 3.42.4 — smart search score semantics fix (#3327/#3340)
Ships PR #3340 (fix(memory): preserve retrieval relevance in smart search
results): memory_search({smart:true}) was returning the RRF fusion score in
the `similarity` field instead of the underlying retrieval relevance;
`similarity` now carries the raw retrieval score, and the fused SmartRetrieval
ranking score is exposed separately as `rankingScore`.

Note: 3.42.1-3.42.3 were published to npm without matching version-bump
commits on main (no `chore(release)` commit, gitHead unset in npm metadata).
Verified via `v3.42.0`/`v3.42.1`/`v3.42.3` git tags: all are ancestors of this
commit, so 3.42.4 is a strict superset of what was previously published.

Co-Authored-By: RuFlo <ruv@ruv.net>
v3.42.4
2026-09-17 17:35:43 -04:00
rUv 702d146178 fix(memory): preserve retrieval relevance in smart search results (#3340)
Fixes Finding B of #3327: memory_search({smart:true}) was returning the RRF fusion score in the 'similarity' field instead of the underlying retrieval relevance score.

Merging despite the red 'Test Suite (ubuntu-latest)' check: it fails on doctor-memory-driver-3321.test.ts, a pre-existing test unrelated to this PR's diff (touches only smart-retrieval.ts/memory-tools.ts/memory-defs.ts and their tests). Confirmed: (1) doctor.ts/memory-initializer.ts/the failing test file are byte-identical between this PR's base and current main, (2) the same test passes on main's own latest CI run, (3) the test file's own comments acknowledge known vi.doMock concurrency fragility under parallel execution. main has no branch protection configured. Finding A of #3327 (ghost reasoningBank/vectorBackend controllers) remains open and out of scope for this PR.
2026-09-17 19:35:18 +01:00
rUv 6f0ed71128 fix(release): spawn npm.cmd with shell:true in prepare-root-publish too (#3348)
Same EINVAL bug as #3346 (stage-internal-runtime-bundles.mjs's runBuild),
one file over: prepare-root-publish.mjs's own npm.cmd spawnSync for
building v3/@claude-flow/swarm and cli lacked shell:true, blocking the
root claude-flow package's Windows publish the same way. Found
immediately after #3346 while publishing 3.42.3 end to end.

Single-string shell:true form, matching #3346's fix, to avoid Node's
DEP0190 warning. Still constant literals, no injection surface.
v3.42.3
2026-09-16 16:36:46 +00:00
rUv fcee45bc1d fix(release): spawn npm.cmd with shell:true on Windows (#3346)
* fix(release): spawn npm.cmd with shell:true on Windows

spawnSync('npm.cmd', ['run','build'], {stdio:'inherit'}) threw EINVAL on
Windows, blocking every @claude-flow/cli publish on this platform since
CreateProcess can't launch a .cmd directly and Node has refused to shell
out implicitly since CVE-2024-27980.

Found live while publishing 3.42.3: prepublishOnly -> prepare-publish.mjs
-> stageInternalRuntimeBundles() rebuilds the four internal runtime
packages (security/codex/mcp/plugin-agent-federation) and hit this on
the very first Windows publish attempt after upgrading past the Node
version where the implicit shell fallback still worked.

command/args here are constant literals ('npm.cmd', ['run','build']),
never hook-derived or user-controlled, so shell:true carries no
injection risk.
Co-Authored-By: RuFlo <ruv@ruv.net>

* fix(release): avoid DEP0190 warning in the npm.cmd shell:true fix

Single-string command form instead of args array — same shell:true
safety (still constant literals, nothing interpolated), no warning.
Co-Authored-By: RuFlo <ruv@ruv.net>
2026-09-16 16:11:14 +00:00
takagibit18 0f8a934dbd fix(sona): reject inherited keys in env mode validation 2026-09-17 00:05:01 +08:00
rUv cdc000fb41 fix(hooks): quote-aware split for RUFLO_HOOK_CLI_OVERRIDE (#3344)
override.split(' ') broke process.execPath into 'C:\Program' plus stray
tokens on a standard Windows Node install (C:\Program Files\nodejs\node.exe),
since the override string wasn't quote-aware. Found while verifying #3332's
Windows argv fix on a real Windows machine: 3 of 32 plugin-hooks-smoke cases
failed only on a stock Windows dev box, not on windows-latest CI (whose
hostedtoolcache Node path has no space).

RUFLO_HOOK_CLI_OVERRIDE is a test-only escape hatch, never set in
production, so this has no user-facing impact — it only unblocks the
test harness on the common case of a Program-Files Node install.

Adds splitCliOverride(), a minimal double-quote-aware tokenizer, and
quotes the two override strings test-hooks.mjs builds from
process.execPath.
2026-09-16 15:38:52 +00:00
rUv 5e634b3965 fix(test): use a UUID, not Date.now(), for mcp-policy-enforcer's per-test audit log path (#3337)
`beforeEach` built each test's "unique" audit-log/policy file path from
`Date.now()` alone (millisecond resolution). Two tests whose beforeEach
hooks fire within the same millisecond — easily happens in a fast
suite — get the identical filename, so one test's audit-log writes leak
into another's line-count assertions.

This is the root cause of an intermittent CI failure: "deny -> expiry ->
allow through the real stdio dispatcher" expects exactly 3 audit-log
lines but sometimes sees 5 — the extra 2 lines come from the preceding
"budget=1" test's two dispatch calls, when both tests' beforeEach hooks
land on the same Date.now() value. Confirmed the mechanism directly:
Date.now() collides trivially in a tight loop (2M iterations, first
try), while crypto.randomUUID() never collides across 200k calls.

Swapped both the audit-log and policy-file paths in this describe block
to use randomUUID() instead. Ran the file 9 times back-to-back post-fix:
31/31 passing every time.


Claude-Session: https://claude.ai/code/session_01SjxUvZnyBdwtx4Y1jKAqt6
2026-09-16 14:45:11 +00:00
rUv 4884f1f7cc ci(federation): build shared dependency before descriptor validation 2026-09-16 14:38:25 +00:00
Dragan Spiridonov 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.
2026-09-16 14:36:26 +00:00
rUv fd6014ac5a ci(federation): validate planner safe descriptor benchmark 2026-09-16 14:35:18 +00:00
rUv fbb39f4c45 docs(adr): record registration time planner trust boundary 2026-09-16 14:31:02 +00:00
rUv 95e8a0efbf chore(federation): wire planner descriptor benchmark 2026-09-16 14:30:34 +00:00
rUv 9824a6e2f6 bench(federation): add registration descriptor attack corpus 2026-09-16 14:30:20 +00:00
rUv 76f62e0bce test(federation): harden planner registration descriptor boundary 2026-09-16 14:29:38 +00:00
rUv 7133e38a89 feat(federation): export planner safe descriptor contract 2026-09-16 14:29:06 +00:00
rUv 7ed6b5b9f9 feat(federation): add planner safe agent descriptor boundary 2026-09-16 14:28:34 +00:00
takagibit18 79529c6cf6 fix(memory): preserve retrieval relevance in smart search results 2026-09-16 14:54:34 +08:00
rUv a65bdf683a fix(memory): pass a bare mode string to NeuralLearningSystem, not an object (#3336)
learning-bridge.ts's loadNeural() called
`new NeuralLearningSystem({ mode, ewcLambda })`, but the real constructor
signature is `constructor(mode: SONAMode = 'balanced')` — a bare string
(see @claude-flow/neural/src/index.ts and the CLI's own reference-correct
call site in memory/neural-package-bridge.ts). This never threw: SONAManager
resolves `MODE_CONFIGS[mode]`, which for an object argument coerces to the
key "[object Object]", finds nothing, and `{...undefined}` silently produces
an empty config instead of the intended mode's settings — so every
LearningBridge-driven neural session has been running with an unset,
default-less SONA config regardless of `sonaMode`/`RUFLO_INTELLIGENCE_MODE`.

`ewcLambda` was never a real constructor parameter either — each mode
carries its own fixed lambda via MODE_CONFIGS, with no override mechanism —
so it's dropped from the call rather than papered over.

Added a regression test that mocks the real `@claude-flow/neural` import
path (the existing 67 tests all inject a `neuralLoader`, which bypasses this
code path entirely — that's why this went uncaught). Confirmed the new test
fails against the pre-fix constructor call and passes with the fix.


Claude-Session: https://claude.ai/code/session_01SjxUvZnyBdwtx4Y1jKAqt6
2026-09-16 04:22:58 +00:00
dependabot[bot]andRuFlo 6debd74196 chore(deps): bump agent-browser from 0.27.0 to 0.37.1 in /v3/@claude-flow/browser (#3320)
* chore(deps): bump agent-browser in /v3/@claude-flow/browser

Bumps [agent-browser](https://github.com/vercel-labs/agent-browser) from 0.27.0 to 0.37.1.
- [Release notes](https://github.com/vercel-labs/agent-browser/releases)
- [Changelog](https://github.com/vercel-labs/agent-browser/blob/main/CHANGELOG.md)
- [Commits](https://github.com/vercel-labs/agent-browser/compare/v0.27.0...v0.37.1)

---
updated-dependencies:
- dependency-name: agent-browser
  dependency-version: 0.37.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* chore(deps): regenerate the v3 pnpm lockfile for agent-browser 0.37.1

Dependabot bumped v3/@claude-flow/browser/package.json and its npm
package-lock, but v3 is a pnpm workspace with its own lockfile. Every
frozen-lockfile job failed with ERR_PNPM_OUTDATED_LOCKFILE, which is what the
28 red checks on this PR were — not an agent-browser API break.

Co-Authored-By: RuFlo <ruv@ruv.net>

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: ruv <ruv@ruv.net>
v3.42.1
2026-09-16 02:24:23 +00:00
rUv c20b71f7b7 fix(swarm): report a real swarm id, and make swarm stop usable without one (#3253)
`swarm status --format json` returned the literal string 'no-active-swarm' as
the value of `id` while also returning `hasActiveSwarm: true` and 9 agents, and
bare `swarm stop` always failed with no CLI surface exposing an id to pass.

The id is persisted by three writers under two keys in two files:
`swarm init` -> `.swarm/state.json` `id`; `swarm start` -> the same file's
`swarmId`; MCP `swarm_init` -> `.claude-flow/swarm/swarm-state.json`. The reader
checked one. `swarm start` overwrites `init`'s file with a disjoint key set, so
the file existed (hasActiveSwarm true) but carried the id under a key nobody
read (id sentinel).

- resolve the id from all three writers, both local keys first
- emit `null`, never a sentinel, when the id is genuinely unknown
- default `stop` and `scale` to the resolved id; explicit arg still wins
- have `start` write `id` alongside `swarmId`
- stop a stopped state file from shadowing a live swarm, claiming to be
  active, or reporting `ready`
2026-09-16 02:24:20 +00:00
rUv 9cb9c8448e perf(agentbbs): dedup PeerHello spam, dedup watch replays, O(1) seq append (#3257)
Three optimizations to the ruflo-side AgentBBS federation integration
(ADR-164), all in v3/@claude-flow/cli/src/mcp-tools/agentbbs-tools.ts.

1. PeerHello dedup (register). `federation_bbs_register` appended a fresh
   PeerHello envelope on EVERY call even though the registry entry and nodeId
   were already idempotent — so a node retrying register N times emitted N
   near-identical hellos (observed live: one node published 8). Now a hello is
   emitted only for a genuinely new registration, or as a heartbeat refresh once
   FEDERATION_BBS_HELLO_WINDOW_SECS (default 60) has elapsed. Returns
   `helloEmitted` so the caller can see whether one was written (a silent
   suppression would otherwise be unverifiable).

2. Watch dedup. `federation_bbs_watch` now collapses duplicate envelopeIds
   before applying the limit, so a relay replay or a double-append cannot
   surface the same envelope twice to a watcher. Order preserved.

3. O(1) seq append. `nextSeq` re-parsed the whole room log on every
   publish/register (O(n) as the log grows). It now scans only the last 64 KiB
   to find the last seq, with a full-read fallback for the rare huge-line case.
   Monotonic seq (ADR-164 §3.2.2) is preserved and tested past the tail window.

Decision helpers (`shouldEmitHello`, `dedupEnvelopes`, `nextSeq`,
`lastPeerHelloMs`) are exported and unit-tested deterministically — the tool
handlers early-return `{degraded:true}` when the optional `agentbbs` package is
absent, so the pure logic is tested directly rather than through the wrapper.

Tests: 7 new cases; full file 15 passed / 4 skipped (the 4 are agentbbs-present
happy-path, skipped when the optional dep is absent). tsc --noEmit clean on the
changed file. Structural + degraded contract unchanged.

Scope: this is the ruflo-side integration only. Claim leases, signed result
receipts, and node reputation are agentbbs/relay-authority concerns (external
pkg + x.ruv.io gateway) — a separate track.
2026-09-16 02:24:16 +00:00
Lukas BuckandrUv 22c340e7f1 fix(cli): open the graph database with options, and refuse a volatile handle (#3318)
`getGraphDb()` built the persistent database as
`new mod.GraphDatabase(join(dataDir, 'agents.db'))`. `@ruvector/graph-node`
2.1.0 takes an options object; given a bare path string it does not throw --
it returns an in-memory instance with `isPersistent() === false` and
`getStoragePath() === null`. Writes succeed, reads succeed, and the graph is
gone at exit, so the catch/fallback never fired and nothing downstream could
tell.

Three changes, matching the acceptance list in #3313:

- Construct with `{ storagePath, dimensions, distanceMetric }`, using the
  8-dimensional embedding `textToMiniEmbedding` actually writes.
- Verify the handle before publishing it: a database that reports itself
  non-persistent, or reports a storage path other than the requested one, is
  closed and the backend reports unavailable. A build exposing neither
  accessor is accepted -- the check guards against a silent downgrade, not
  against an unfamiliar version.
- Serialize first initialization by memoizing the promise, and drop the
  silent in-memory fallback: an open failure now says what went wrong and
  leaves the backend unavailable, instead of substituting an empty graph that
  answers every query successfully and persists nothing.

Co-authored-by: rUv <ruv@ruv.net>
2026-09-16 02:23:44 +00:00
Lukas BuckandrUv 84950144f5 fix(cli): memory_stats answers from the store, not from a raw file probe (#3319)
`memory_stats` decided whether memory existed by calling
`checkMemoryInitialization`, which opens a whole-image sql.js snapshot of
the main database file. Such a snapshot cannot include live SQLite WAL
frames, so a store the AgentDB bridge reads and searches perfectly well
came back `initialized: false` from this one tool while `memory_retrieve`
and `memory_search` returned real records in the same session.

The listing now decides. The probe is still read for the version and
feature labels it is the only source of, in its own try/catch, so it can
fail without that meaning the store is missing.

Three more things the handler got wrong about its own inputs:

- `listEntries` returns `success` and `error`, and both were ignored: a
  refused query was read as a store with no entries and reported as
  `totalEntries: 0`. A failed or thrown listing is now `available: false`
  with the reason, and reports no counts at all rather than fabricated
  zeros. An empty store still reports as empty.
- The namespace tally was a plain object literal, so a namespace named
  `__proto__` set the prototype instead of counting anything and vanished
  from the breakdown while still being counted in the total.
- `limit: 100000` in one call meant a larger store had its breakdown and
  embedding coverage computed from a prefix. The listing is paged, and a
  count that still could not reach `total` is reported as `truncated`.

Refs #3311

Co-authored-by: rUv <ruv@ruv.net>
2026-09-16 02:23:41 +00:00
Sean Yu 6ccf25b3e0 fix(doctor): stop inferring memory driver history from table count (#3331) 2026-09-16 02:23:38 +00:00
Ayubu KayangeandrUv 1c594c7714 fix(witness): make WITNESS_ED25519_ROOT actually resolve @noble/ed25519 (#3200) (#3276)
loadEd25519() threw an error telling callers to set WITNESS_ED25519_ROOT
when @noble/ed25519 couldn't be found, but the function never read
process.env — the env var had no effect. Prepend it to the probe list
so the advertised escape hatch actually works.

Fixes #3200

Co-authored-by: rUv <ruv@ruv.net>
2026-09-16 02:22:56 +00:00
Ayubu KayangeandrUv 8764ac4a3d fix(doctor): resolve MetaHarness version from the installed package (#3187) (#3277)
`metaharness` implements no --version flag, so the previous check
(`npx -y metaharness@latest --version`) always fell through to the usage
banner and could never match a version-shaped string — the doctor check
was permanently stuck on "version-string not parseable". It also probed
whatever `npx` resolves from the registry rather than the version actually
installed, and hit the network on every doctor run.

Resolve the version from the installed package's own package.json instead,
via import.meta.resolve() (require('metaharness/package.json') is blocked
by the package's exports map, and createRequire().resolve() fails on its
ESM-only entry point).

Fixes #3187

Co-authored-by: rUv <ruv@ruv.net>
2026-09-16 02:22:54 +00:00
Wu Shuwen 9b98bf7ee6 fix(memory): close the sql.js handle in checkMemoryInitialization on every path (#3249) (#3280)
`checkMemoryInitialization` constructed its sql.js handle inside the `try` and
reached `db.close()` only on the success path. The schema query is exactly the
call that throws on an image sql.js cannot parse — an RFE1-encrypted `memory.db`
being the common case once encryption at rest is on — so the `catch` returned
`{ initialized: false }` and the handle was never released. Every memory MCP
tool call runs this check first (memory-tools.ts `ensureInitialized`), so each
call left another handle open.

Hoist the handle out of the `try` and release it in a `finally`, so the parsed
and the rejected path both close it. The returned value is unchanged, so this is
behaviour-preserving apart from the release itself. Decrypt-before-open is
deliberately out of scope: changing `initialized` for an encrypted store would
alter what every caller sees, which is a separate decision from the leak.

Verified against the real sql.js, not a mock: `new SQL.Database(<RFE1 bytes>)`
succeeds (the constructor does not check the SQLite header) and the schema query
then throws `file is not a database` — the exact throw that skipped the close.
Retention was measured one arm per process, since Emscripten linear memory only
grows and measuring both arms in one process lets the first contaminate the
second: 8 unclosed handles over a 4,235,264-byte image retain ~0.21x the image
each, versus ~0.08x when each is closed. The issue reports ~1.0x per call; that
larger figure is not reproduced here, so this commit claims the leak, not its
magnitude.

Regression coverage in __tests__/memory-init-handle-leak-3249.test.ts asserts
the handle is closed on the rejected path, still closed on the parsed path, and
never opened when the file is absent. The first case fails against the pre-fix
source with "expected false to be true" and passes after.
2026-09-16 02:22:51 +00:00
rUv 90889f4772 feat(sona): default the learning mode from RUFLO_INTELLIGENCE_MODE (#3334)
* feat(sona): default the learning mode from RUFLO_INTELLIGENCE_MODE

The SONA learning mode was only settable per call (`config.mode`), defaulting
to `balanced` otherwise. A deployment that wants every session to learn in a
specific profile — a managed desktop fleet running `research` for +55% quality,
or `edge` on constrained hosts — had no way to set that default short of
threading `mode` through every call site or patching a generated helper.

This reads `RUFLO_INTELLIGENCE_MODE` as the fleet-wide default in both the SONA
config merge (`@claude-flow/integration` sona-adapter) and the memory learning
bridge (`@claude-flow/memory`). Precedence is unchanged where a caller is
explicit: `config.mode` (or `sonaMode`) still wins; the env only fills the
former default slot; and an unset or unrecognised value returns undefined so
the code falls through to `balanced` — a typo can never silently select a
profile nobody asked for. Validated against the mode enum in each package.

Co-Authored-By: claude-flow <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01MUrJdDHhQ91hwpUBQhV4fC

* fix(sona): resolve sonaMode per-instance in LearningBridge, not at module load

learning-bridge.ts captured sonaModeFromEnv() into a module-scope
DEFAULT_CONFIG constant, evaluated once on first import — so any
RUFLO_INTELLIGENCE_MODE set later in the same process (including
test setup) was permanently missed. sona-adapter.ts's equivalent
(mergeConfig()) already re-reads the env var on every call; this
brings LearningBridge's constructor in line with that behavior,
preserving the same precedence (explicit config.sonaMode > env > default).

Adds regression tests for both packages (sona-adapter.ts had none
previously) and registers RUFLO_INTELLIGENCE_MODE in
KNOWN_ESCAPE_HATCHES per the audit script's existing requirement for
operator-knob env vars outside its SCAN_ROOTS.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01SjxUvZnyBdwtx4Y1jKAqt6
2026-09-16 02:22:13 +00:00
Dragan SpiridonovandRuflo & AQE 6776bd2d7a fix(federation): read the untrusted-relay envelope the gateway actually sends (#3304)
* fix(federation): read the untrusted-relay envelope the gateway actually sends

#3300 started wrapping relay-sourced results in a nonce-fenced provenance
envelope. The server shipped; the client kept calling JSON.parse on the whole
string, so it died on the first word of the gateway's own prose:

  Unexpected token 'T', "The block "... is not valid JSON

That killed `ruflo federation sync`, `roster` and `claims`, and the
x_federation_* MCP tools behind them — 3 of 4 federation reads, on 3.41.2.
`registry` kept working because that response is not fenced, which made the
outage read as intermittent rather than total.

The suite stayed green throughout because every mock returned bare JSON — a
contract the server had stopped honouring. The new fixtures are built with the
gateway's own fenceUntrusted(), so the next envelope change fails here instead
of in production.

Two things this deliberately does NOT do:

- It does not unwrap to `.data`. The whole point of #3300 is that a caller can
  tell whose words these are; quietly returning the payload would restore valid
  JSON by discarding the labelling that made it safe to read. The full envelope
  (untrusted/provenance/relay/retrievedAt/data) is returned.
- It does not match the fence loosely. The token backreference is what stops a
  publisher forging an END marker to make later text read as gateway narration,
  so a mismatched token does not close the region. An unterminated envelope
  throws rather than silently dropping relay content.

Verified against live x.ruv.io: federation_sync, ruv://swarm/roster and
ruv://claims/board are all fenced and all failed the old parser with the exact
error above; the unfenced registry resource is unaffected. Mutating the parser
back to plain JSON.parse turns 6 of the new tests red with that same string.

Full @claude-flow/cli suite: 90 failed files / 112 failed tests both before and
after (pre-existing), passing 2426 -> 2433. tsc: 463 errors before and after.

Co-Authored-By: Ruflo & AQE
Claude-Session: https://claude.ai/code/session_01NpXyuvm9QACWhD8egqw8zU

* fix(federation): Seraphina had the same bug, and three review findings

An independent adversarial review of the first commit found one blocker and
three should-fixes. All four are addressed here.

BLOCKER — seraphina-tools.ts had the identical defect, unfixed.
`askSeraphina` runs its own gateway client and reads three fenced endpoints
(roster, claims board, federation_sync), so `seraphina_guidance` — registered at
mcp-client.ts:186 — was dead on 3.41.2 with the same error. The first commit's
claim of "3 of 4 federation reads" was 3 of 4 tools in ONE file.

Its test file carried the same trap the first commit diagnosed: bare-JSON mocks
for endpoints the server had started fencing. Those fixtures now use the
gateway's own fenceUntrusted(), which turns the existing context assertion into
a real regression guard.

The obvious fix there would have corrupted silently. seraphina-tools.ts reads
`recent.messages` and `Object.keys(roster)` directly, so returning the envelope
(right at the MCP boundary) would have given Seraphina an empty message list and
a roster miscounted as 5 — no error, and she assigns work on it. Added
`relayPayload()` for internal consumers, and said plainly in the comment why the
two shapes exist.

S2 — the two "adversarial" tests did not test what they claimed. Both passed
with the backreference deleted, with the newline anchors deleted, and with the
quantifier made greedy. The real neutraliser today is that the body is
JSON.stringify'd onto a single line, so publisher text cannot contain a raw
newline. The backreference is the defence that survives a switch to pretty
printing, so it is now pinned by a test built on a hand-made envelope; deleting
\1 turns exactly that test red. The code comment named the wrong mechanism as
load-bearing and has been corrected.

S3 — exec() is non-global and first match wins. fenceUntrusted splices its
`note` verbatim BEFORE the fence, so a caller interpolating relay-derived text
into a note could smuggle in an earlier complete envelope and have it returned
with untrusted:false. Now refuses a response carrying more than one envelope.

The first attempt at that guard counted raw marker occurrences and introduced a
denial of service: a publisher typing the literal marker into a message made
every read throw. Caught by the existing hostile-payload test. The count is
newline-anchored, matching the fence itself.

S4 — `parsed` was computed before `r.isError` was consulted, so an SDK
createToolError (raw text, not JSON) surfaced as "Unexpected token 'p'" instead
of its message. isError is checked first, falling back to the raw text.

Reviewer confirmed and I verified: no fenced response can carry a top-level
error, and x-federation-channels.ts / x-federation-join.ts speak Nostr directly
rather than /mcp, so they were correctly out of scope.

Every new guard has a mutant that reddens its own test: backreference removed,
seraphina reverted to bare parse, seraphina returning the envelope, and isError
checked after parsing. Live against x.ruv.io the internal path reads 25 messages
where the envelope bug reads 0, and an empty roster where it reads 5.

Full @claude-flow/cli suite: 90 failed files / 112 failed tests before and after
(pre-existing); passing 2426 -> 2439. tsc: 463 before and after.

Co-Authored-By: Ruflo & AQE
Claude-Session: https://claude.ai/code/session_01NpXyuvm9QACWhD8egqw8zU
2026-09-16 02:21:20 +00:00
Lukas BuckandrUv be9b4d28ec fix(integration): token savings need the baseline the caller has (#3317)
`getCompactContext` reported `tokensSaved` as the query string's length
minus the retrieved prompt's. The query is a search instruction, not the
context the compact prompt replaces, so the subtraction had no valid
baseline: a short query against a longer retrieved prompt reported 0 no
matter how much context the caller then dropped, and a long query against
a short prompt reported a saving with no replaced context behind it.
`getStats` turned the accumulated value into `estimatedMonthlySavings`,
in a module whose header states that no fabricated metrics are reported.

The baseline is the caller's to supply, because this method never sees
it. `options.baselineTokens` names the size of the context being
replaced; savings are measured against that and floored at 0. Without
it the call is reported as unmeasured -- `tokensSaved: null`, nothing
added to the total -- rather than as a saving of 0, so a caller summing
these cannot fold "no saving" and "no measurement" into one number.
`contextsMeasured` says how many calls the total was actually built
from, and the report renders it next to the total.

Co-authored-by: rUv <ruv@ruv.net>
2026-09-16 02:21:17 +00:00
Lukas BuckandrUv 955510695f fix(memory): replace the drive colon when deriving the auto memory key (#3305)
resolveAutoMemoryDir mirrors Claude Code's project key, which replaces
`/`, `_` and `:` with dashes. The colon was missing, so a Windows git
root of D:\projects\elearning\v3_26 produced the key
D:-projects-elearning-v3-26 instead of D--projects-elearning-v3-26.

A colon is not legal inside a Windows path segment, so ensureMemoryDir()
failed with ENOENT and doSync() swallowed it as "Sync failed
(non-critical)": the auto memory sync had never run on Windows, and
reported success while doing nothing. It also wrote to a different key
than Claude Code reads, so even a successful write would have been
invisible.

POSIX paths carry no colon, so nothing changes there.

Co-authored-by: rUv <ruv@ruv.net>
2026-09-16 02:21:15 +00:00
rUv 977b7cc058 Merge branch 'main' into docs/readme-zh-cn 2026-09-15 15:04:25 +00:00
ruv 2602b642d9 chore(release): 3.42.0 — dream-cycle backlog batch (14 PRs)
Merges the full dream-cycle evaluated-backlog batch: weighted swarm
consensus, HNSW product-quantization dispatch, ADR-377 caller-identity
verification, EWC confidence-gate fix, weighted-RRF memory fusion,
symmetric topology rebalancing, dead-code + stale-claim cleanup,
opt-in MCP governance policy enforcement, sliding-window rate limiting,
reward-aware learning consolidation, embedding near-duplicate detection,
lazy MMR tokenization, hive-mind Sybil-vote + join/leave authentication,
and a confidence/similarity conflation fix in pattern retrieval.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01RYP825phHMjPRmmjkcAWpq
v3.42.0
2026-09-14 20:55:06 -04:00
rUvandClaude 2abc9292da dream(intelligence): #3301 gate findSimilar()'s confidence on reliability, not query-similarity (evaluated, ACCEPT) (#3302)
* dream(intelligence): #3301 findSimilar() confidence/similarity conflation

LocalReasoningBank.findSimilar() overwrote every returned pattern's
confidence (learned reliability) with the per-query cosine similarity
score, instead of returning the score under the already-declared
PatternMatch.similarity field. This silently broke distillLearning()'s
"only distill from high-confidence matches" gate (it tested
query-similarity, not reliability) and forced findSimilarPatterns()'s
public API into an unsafe type-cast fallback that made confidence and
similarity numerically identical for every caller.

Fix: findSimilar() now preserves the real stored confidence and returns
the cosine score as a distinct similarity field; findSimilarPatterns()
reads the real field instead of casting; memory-bridge.ts's search-
ranking consumer (which wants query-relevance, not reliability) is
migrated to prefer similarity, falling back to confidence.

Evaluated: baseline-fails/candidate-passes via git-stash isolation (4
new discriminating tests), full @claude-flow/cli suite identical
90-vs-91-failed-file sets (only delta is the new test file; all other
failures are pre-existing unbuilt-sibling-package issues), tsc
--noEmit byte-identical. Independent adversarial critique: CONFIRMED,
no blocking caveats.

Darwin: skipped (binary correctness fix, no fitness gradient).
Security: not sensitive, in-process bookkeeping only.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_013LQSLa9h1uLdYsQBP5r36z

* dream(intelligence): #3301 update ledger with issue #3301 / PR #3302

Records tonight's finding, verified GitHub fates for the trailing 7
nights (including a newly-discovered merge conflict on #3232), and the
evaluation verdict.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_013LQSLa9h1uLdYsQBP5r36z

* dream(intelligence): #3301 make findSimilarPatterns() test CI-deterministic

CI's "Test Suite (ubuntu-latest)" job (root-level ci-test-ratchet.mjs)
flagged this new test file as an unexpected failure: the "confidence
and similarity differ for a partial match" case called the real
findSimilarPatterns(), which tries a live ONNX embedding (falling back
to a hash) before it can compare fields. In the CI runner that path
silently returned [] (no cached model / restricted network),
so `hit` was undefined.

Mock both embedding sources (memory-bridge.js's bridgeGenerateEmbedding,
memory-initializer.js's generateEmbedding) to a fixed deterministic
vector. This matches the evaluation's own stated claim ("fully
deterministic, $0 evaluation cost") that this one test wasn't actually
honoring. Reproduced the exact CI invocation locally (root-level
vitest, not the cli package's own scoped config) — all 4 tests now
pass; local package-scoped suite unaffected (7/7 across this file and
the adjacent hooks-intelligence-learning.test.ts).

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_013LQSLa9h1uLdYsQBP5r36z

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-15 00:34:22 +00:00
rUvandClaude ee412dfd15 dream(security): #3290 fix hive-mind_consensus Sybil-vote authentication gap (evaluated, ACCEPT-scoped) (#3291)
* dream(security): #3290 fix hive-mind_consensus Sybil-vote authentication gap

hive-mind_consensus's vote action recorded proposal.votes[voterId] for
any caller-supplied voterId string, with no check against state.workers
(the roster hive-mind_join populates). Since calculateRequiredVotes()
derives the quorum threshold from state.workers.length, a single caller
could cross any strategy's threshold (raft/bft/quorum) by voting under
fabricated identities -- a Sybil attack on consensus, not merely a
double-vote. The existing double-vote guard and Byzantine-flip detector
only catch one identity contradicting its own prior vote, not many
distinct forged identities each voting once.

Fixed with a fail-closed roster-membership check before a vote is
recorded. Stash-isolated: 2/3 new tests fail against real baseline
(forged votes silently accepted; a BFT proposal reaches "approved" from
3 forged identities against 3 real workers), 3/3 pass against candidate.
Full @claude-flow/cli suite: 2863/3036 passing, 46 pre-existing/unrelated
failures (workspace-resolution gaps), zero "hive" failures. Independent
adversarial critique: CONFIRMED-WITH-CAVEATS -- hive-mind_join/leave
remain fully unauthenticated, so this closes forged-vote Sybil but not
forged-join Sybil (disclosed follow-up).

Closes #3290 (full research: 5-role parallel fan-out, ledger check,
intelligence/swarm scan findings, competitor comparison, adversarial
critique).

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01DXHWKVWLjLv6wHkx6bBDF1

* dream(security): update ledger for #3290/#3291 (2026-09-11)

Records tonight's hive-mind_consensus Sybil-vote fix, verified GitHub
fates for the trailing nights (#3139/#3152/#3160 still open/draft;
unmerged performance night (#3265/#3266).

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01DXHWKVWLjLv6wHkx6bBDF1

* dream(security): capability-bind hive-mind join/leave/vote, fix CI cold-install

Addresses ruvnet's review REJECT on PR #3291 at b275fdd0:

1. hive-mind_join/hive-mind_leave were themselves unauthenticated, so the
   roster-membership check alone (the original fix) only closed forged-vote
   Sybil, not forged-join Sybil -- an attacker could just legitimately join
   under fake names. hive-mind_init now mints a 32-byte hiveToken; join,
   leave, and vote all require it (constant-time comparison), fail-closed:
   a denied call makes zero state change (no roster write, no vote write),
   verified by reloading state.json fresh off disk after each denial
   (standing in for a restart/reopen). The CLI's own hive-mind subcommands
   are unaffected -- a new getHiveTokenForCli() reads the token directly
   off the same-machine state file (never exposed via hive-mind_status,
   which is MCP-reachable) and the CLI wires it through automatically.

2. The required "Test Suite" CI workflow failed twice on the exact head:
   @claude-flow/security (a root npm-workspace member) has no
   prepare/postinstall script, only prepublishOnly (which npm ci never
   runs), so a fresh checkout's dist/ never gets built, causing
   ERR_MODULE_NOT_FOUND in doctor.js -> policy-runtime.ts. Root-caused via
   a real root `npm ci` (confirmed dist/index.js is missing without a
   prepare script, present with one) and cross-checked against PR #3266's
   identical first-run failure. Added "prepare": "npm run build" --
   standard npm lifecycle, fixes every future checkout, not just this PR.

Full @claude-flow/cli suite re-run after both fixes: 28 failed / 2884
passed (was 46/2863) -- the ~18-test improvement is exactly the
@claude-flow/security-dependent tests the prepare script now fixes; the
remainder are pre-existing, unrelated @claude-flow/neural/@claude-flow/mcp
workspace-resolution gaps. Zero "hive" failures. 6/6 new/updated tests
pass against the candidate, 6/6 fail appropriately against a
stash-isolated baseline. tsc --noEmit clean on every touched file.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01DXHWKVWLjLv6wHkx6bBDF1

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-15 00:01:15 +00:00
rUvandClaude f13b8567de dream(performance): #3265 stop re-tokenizing MMR candidates that PR #3169 mostly stopped needing (evaluated, ACCEPT) (#3266)
* dream(performance): #3265 stop re-tokenizing MMR candidates that PR #3169 mostly stopped needing

mmrRerank() eagerly re-tokenized every remaining candidate's content on
every outer-loop pass (O(N x limit) tokenize() calls), a pattern that
predates and survived PR #3169 unchanged. #3169 made embedding-cosine
the preferred, now-common pairSimilarity path, so most of that
tokenization was computed and then discarded. Tokens are now computed
lazily and cached per-candidate, only when the Jaccard fallback is
actually needed.

Evaluated: tokenize() calls 400 -> 0 on a 30-candidate/limit-20
all-embedded corpus (stash-isolated: fails against real baseline,
passes against candidate); vitest bench shows the candidate 5.88x
faster (independently reproduced at 5.96x by an adversarial critic).
Selection output is byte-for-byte identical to baseline across
all-embedded/no-embedding/mixed scenarios. 473/474 full package suite
both ways (1 pre-existing, unrelated environmental failure), tsc clean.

Evaluated, ACCEPT. Full research (5-role parallel fan-out), evaluation
receipt, adversarial critique, Darwin/Flywheel scoping, reward-hack
check, and security/hive-mind scan findings in the linked issue and
gist.

Closes #3265

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01P5UJ62RVAbq8DLEEXPrwvU

* dream(performance): append 2026-09-10 ledger row (#3265, #3266)

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01P5UJ62RVAbq8DLEEXPrwvU

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-14 23:43:16 +00:00