Commit Graph
1355 Commits
Author SHA1 Message Date
Rudy Celekli 6096bcaebf fix(doctor): check native AgentDB store integrity 2026-09-25 14:18:50 -04:00
ruv a35901de80 fix(cli): make the memory version verdict a warning and the test layout-independent (#3392)
CI's root `npm ci` hoists @claude-flow/memory alpha.21 (a transitive of the
bundled workspace packages), so the loaded copy legitimately differs from the
pin there. A `fail` would make doctor's exit code depend on which copy a
package manager happened to hoist, and it broke the real-resolution test. The
issue asked for a loud warning, not a gate, so the verdict is now `warn`, and
the real-resolution test asserts only the verdict's shape; the version
comparison itself is covered by the pure-function tests.

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-09-24 18:22:06 -04:00
ruv 6ff6fded33 fix(cli): pin @claude-flow/memory exactly and warn in doctor on a stale copy (#3392)
`npx @claude-flow/cli@latest` reuses one npx cache directory across CLI
versions, and npm keeps an already-installed dependency that still satisfies
its range. With memory declared as `^3.0.0-alpha.23`, a cached alpha.24 was
never replaced by alpha.25, so a fix that shipped in both packages (#3390)
only half-applied, with no error and `agentdb_health` still reporting healthy.

- Pin `@claude-flow/memory` to `3.0.0-alpha.25` in both `dependencies` and
  `optionalDependencies` (npm resolves the optional entry; they must agree).
  A stale copy can no longer satisfy the spec, so npm has to replace it.
- `doctor` gains a `@claude-flow/memory version` check that compares the copy
  the CLI actually loads (its own module context, not cwd) against its declared
  range and fails with a cache-clear remediation when they diverge. It runs in
  the default suite, `--component memory` and `--component memory-package`.
- v3/pnpm-lock.yaml: minimal hand edit (importer specifier/version plus one
  new registry snapshot); proven with `pnpm@8 install --frozen-lockfile`
  passing on the new lock and failing on the old one.

Verified by reproduction: with memory alpha.24 already installed, adding the
registry cli@3.44.0 (caret) leaves alpha.24; adding a tarball of this branch
upgrades it to alpha.25.

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-09-24 18:07:54 -04:00
rUv 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>
2026-09-23 18:39:18 +00:00
ruv c73d127cfe fix(guidance): classify seraphina_* and x_federation_* tools in the capability brain
The stable-release gate `guidance-brain.test.ts › classifies every live
registered MCP tool without duplicates` has been failing on main since the
x.ruv.io federation and Seraphina tools landed: 15 tools
(seraphina_guidance + 14 x_federation_*) only reached a domain through the
runtime-services fallback, which the gate treats as a coverage gap.

- seraphina_ -> guidance domain (it is capability guidance), owner @claude-flow/cli / ruflo-core
- x_federation_ -> AgentBBS & federation domain alongside federation_bbs_, owner @claude-flow/cli / ruflo-x-gateway

guidance-brain + mcp-client-guardrail: 12/12; x-federation + seraphina tool tests 25/25; tsc clean.

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-09-23 11:00:22 -04:00
rUv 7d801171d5 feat(hooks): opt-in @ruvector/typesafe task router (CLAUDE_FLOW_ROUTER_TYPESAFE=1) (#3406)
* feat(hooks): opt-in @ruvector/typesafe task router (CLAUDE_FLOW_ROUTER_TYPESAFE=1)

hooks_route can now ask @ruvector/typesafe (local typed decisions over
sentence embeddings) to pick the agent. Off by default; optional peer;
removable (dynamic import, any load/decide error falls back silently).

- src/ruvector/typesafe-router.ts: adapter. Builds choice options from
  TASK_PATTERNS with not_for hints (tester/reviewer/researcher). Gates:
  abstain <= 0.30, lift (top-1 x options) >= 1.2, top-1 margin >= 0.005,
  all env-tunable. Surfaces routedBy, confidence, abstain, calibrated,
  lift; keeps the built-in pick under fallbackRoute; never copies
  uncalibrated confidence into successProbability.
- hooks-tools.ts: hooks_route handler wrapped; body untouched. With the
  flag unset the legacy result object is returned as-is.
- doctor --component typesafe: install + gate status.
- package.json: @ruvector/typesafe ^0.1.0 as an optional peer.
- USERGUIDE: routing section documents flag, gates, limitations.

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

* chore(lock): record optional peer @ruvector/typesafe in v3 pnpm lockfile

v3 sets autoInstallPeers, so the new optional peer must be recorded in
the cli importer or `pnpm install --frozen-lockfile` fails with
ERR_PNPM_OUTDATED_LOCKFILE (verified: fails without this change, passes
with it).

Minimal: only the @ruvector/typesafe importer + package entries (9 lines).
A full `pnpm install --lockfile-only` would also flip @claude-flow/memory
from the registry build to link:../memory; that changes what CI tests the
CLI against and is left out of this PR deliberately.

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

* fix(doctor): keep 'metaharness)' at the end of the --component help list (smoke 17h anchor)

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-09-23 14:57:45 +00:00
rUv 72e17533ca fix(memory): release graph-edge-writer's native WAL handle so sql.js memory_store isn't refused (#3397) (#3405)
* fix(memory): release graph-edge-writer's native WAL handle so sql.js memory_store isn't refused (#3397)

graph-edge-writer cached its better-sqlite3 WAL handle in a module
singleton for the whole MCP server lifetime; nothing but the test-only
_resetBridgeDb ever closed it. Its -wal/-shm sidecars therefore stayed on
disk forever, and the #2735 sidecar guard (correctly) refused every later
sql.js whole-image write. On Windows, where the native AgentDB bridge is
off by default (#3024), that turned one hooks_post-task into a permanent
memory_store outage for the server.

- getBridgeDb() arms an unref'd idle timer (1s, CLAUDE_FLOW_GRAPH_EDGE_IDLE_MS)
  that checkpoints (TRUNCATE) and closes the handle; re-armed on every use.
- New releaseBridgeDb(dbPath?) is called by memory-initializer right before
  each #2735 guard, so a store immediately after an edge write works and the
  edge is checkpointed into the image sql.js rewrites.
- process 'exit' hook releases the handle so a clean shutdown does not leave
  stale sidecars for the next process. No signal handlers (would change
  Node's default termination).
- The guard itself is unchanged: an open WAL connection makes a whole-image
  write unsafe even in-process until its WAL is checkpointed.

Fixes #3397

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

* chore(audit): register CLAUDE_FLOW_GRAPH_EDGE_IDLE_MS as an env-only tuning knob (ADR-125)

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-09-23 14:57:35 +00:00
rUv 9e71cf66d2 fix(hooks): post-task reports observed learning counts, not placeholders (#3353) (#3403)
hooks_post-task synthesized learningUpdates from the success flag:
patternsUpdated = feedbackResult?.updated || (success ? 2 : 1),
newPatterns = success ? 1 : 0, trajectoryId = traj-${Date.now()}.
With the feedback controller unavailable it still claimed "2 updated,
1 new", and the || turned an observed updated:0 into 2. The direct
recordTrajectory() result was awaited and discarded.

Now patternsUpdated is the controller's observed count (0 when feedback
was not recorded), newPatterns is null (no path reports creation),
trajectoryId is null (no real id exists), and learningUpdates gains
available + reason. A new top-level trajectory.recorded exposes the
recordTrajectory() result. All existing keys are kept. The CLI prints a
'Learning degraded' warning and shows unknown instead of invented values.
2026-09-23 14:57:24 +00:00
rUv 44883dbd1f fix(memory): make the embedder rescue reachable and stop silent NULL embeddings (#3375, #3325) (#3407)
* fix(memory): make the embedder rescue reachable and stop silent NULL embeddings (#3375, #3325)

#3375: generateLocalEmbedding() is documented as bridge-free but loaded its
model through loadEmbeddingModel(), which is bridge-first. With the bridge up,
the local state was recorded as { loaded: true, model: null }, so every call
returned the hash fallback (backend 'mock') and rescueAgentdbEmbedder()'s
backend === 'onnx' probe could never pass. Split out loadLocalEmbeddingChain()
and cache the bridge result separately; generateLocalEmbedding() now loads
only the local chain and never touches agentdb's embedder.

#3325: bridgeStoreEntry embedded only via agentdb's embedder and a bare catch
stored embedding=NULL when it was absent or threw, reporting nothing. Add
embedForBridge(): agentdb first, then the local chain (generateLocalEmbedding,
never the bridge-first generateEmbedding -- #2312), accepting only a real ONNX
vector. Used for both the write and the bridgeSearchEntries query. When no
vector can be produced the result carries embeddingError, and
bridgeStorePattern reports hasEmbedding/embeddingError. Also fix
bridgeGetEntry reporting hasEmbedding:false on every TieredCache hit.

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

* fix(memory): treat a mock-tagged agentdb embedder as no embedder; surface embeddingError in memory_store (#3325)

embedForBridge now honours the same isMock / backend==='mock' signal that
bridgeGenerateEmbedding already uses, so vectors from an embedder the
rescue could not replace are not stored as if they carried meaning; the
local chain is tried instead, and embeddingError is reported if it has no
real model either. storeEntry's type and memory_store's response carry
embeddingError through.

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-09-23 14:52:21 +00:00
rUv 5f3f4df408 fix(policy): retry transient rename failures in writeJsonAtomic, never orphan the temp file (#3398) (#3404)
On Windows, renameSync over .claude-flow/policy/state.json fails with
EPERM/EBUSY/EACCES while another process briefly holds the destination open.
writeJsonAtomic made a single attempt with no cleanup, so the whole MCP call
failed and state.json.<pid>.<uuid>.tmp was left behind.

- Retry transient rename errors with a bounded async backoff (~1.3s total,
  inside the 5s state.lock wait; async so the MCP event loop is not blocked).
- try/finally removes the temp file on any final failure.
- A final failure still fails the call: the state carries the hash-chained
  receipt ledger and consumed approval uses; dropping the write would return
  a phantom receipt and let a one-shot approval be reused.

Fixes #3398
2026-09-23 14:26:50 +00:00
rUv 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.
2026-09-23 14:26:46 +00:00
rUv 7b4e97a316 fix(memory): reject a missing required query/key at the memory tool boundary (#3374) (#3400)
memory_search declares required: ['query'] but nothing enforced it, and
validateMemoryInput() is truthiness-guarded, so an omitted query passed
validation and reached generateHashEmbedding's text.toLowerCase(), coming
back as "Cannot read properties of undefined (reading 'toLowerCase')".

Add a presence check (non-empty string) at the top of memory_search and
memory_search_unified (query) and memory_store / memory_retrieve /
memory_delete (key). A violation returns the handler's normal error shape
plus code MISSING_REQUIRED_PARAM and an error naming the parameter, and the
memory layer is never called.
2026-09-23 14:24:24 +00:00
rUvandClaude Opus 5 11ce88327b fix(memory): activate reasoningBank — wire the real embedder + correct the bridge contract (#3327 Finding A) (#3390)
Activates reasoningBank end-to-end (#3327 Finding A).

- memory/controller-registry.ts: hand agentdb's ReasoningBank an embedder that
  satisfies its asymmetric embedQuery/embedPassage contract; adapt agentdb's
  mock embedder rather than passing it through; flag the zero-vector stub.
- cli/memory-bridge.ts: call the real storePattern(), map agentdb's
  ReasoningPattern shape (approach/similarity) instead of content/score, and
  record the swallowed error so health can name the cause.

Verified: 77/77 controller-registry tests pass; negative control (new tests vs
main's source) fails 8/9, confirming the tests are load-bearing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 18:50:56 +00: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
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
takagibit18 79529c6cf6 fix(memory): preserve retrieval relevance in smart search results 2026-09-16 14:54:34 +08: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 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
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
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 82595ec557 dream(security): #3151 sliding-window reset for maxToolCallsPerTurn (evaluated, ACCEPT) (#3152)
* dream(security): #3151 sliding-window reset for maxToolCallsPerTurn (evaluated, ACCEPT)

Follow-up to PR #3139 (2026-08-31, unmerged): the opt-in MCP policy
enforcer's maxToolCallsPerTurn was a permanent session-lifetime cumulative
counter that never reset, explicitly disclosed as unsafe to enable by
default. Tonight's research (5 parallel roles) converged on a wall-clock
sliding window as the correct fix, corroborated by the MCP spec's own
silence on rate-limit mechanism, SEP-2567's removal of the session
concept, Cloudflare's production sliding-window-counter data, and how
FastMCP/PolicyLayer solve the same problem in the MCP ecosystem.

- checkAndRecordCall/evaluateToolCall now take an injectable `now`
  (defaults to Date.now(), zero production behavior change at the one
  real call site in mcp-server.ts).
- New McpPolicy.turnWindowMs field (default 60000ms); shipped in
  .harness/mcp-policy.json alongside the existing maxToolCallsPerTurn.
- 30/30 tests passing (24 pre-existing unmodified + 6 new). Broader
  MCP-suite sweep: 52/56 (4 failures are pre-existing unbuilt-sibling-
  package environmental gaps, unrelated to this diff).
- Independent adversarial critique: CONFIRMED-WITH-CAVEATS. Two minor
  findings (untested exact window boundary; audit-log timestamp cosmetic
  desync from the injected clock) fixed before this commit.

Full report: docs/dream-cycle/dream-gist-2026-09-01.md

* dream(security): #3151 update LEDGER.md for 2026-09-01

Ledger row for tonight's dream-cycle: sliding-window reset for
maxToolCallsPerTurn (PR #3152, stacked on #3139).

* dream(security): #3151 address ruvnet's PR #3152 review (round 1)

Retargeted PR #3152's base to main: dream/2026-08-31-security is not
main/develop, so every required CI workflow (ci.yml, integration-tests.yml,
cve-audit.yml, v3-ci.yml, verification-pipeline.yml) is configured to
trigger only on PRs targeting main/develop and structurally never ran on
either #3139 or this stacked PR's head, regardless of what was pushed.
This is a repo-wide trigger-configuration fact, not fixable by a commit.

Also addresses the review's other concrete asks:
- Built the two sibling packages disclosed as unbuilt (@claude-flow/cli-core,
  @claude-flow/neural) via tsc. Broader MCP-suite sweep improves from 52/56
  to 201/204 -- remaining 3 failures confirmed (independently, by testing a
  raw ::1 bind outside any test) to be EAFNOSUPPORT: IPv6 loopback binding
  unsupported at the container/OS level in this sandbox, unrelated to this
  diff and not fixable by any code change here.
- Added an integration test exercising the real stdio dispatcher
  (MCPServerManager.handleMCPMessage) through a full deny -> expiry -> allow
  cycle with fake timers, proving the fix holds without bypassing audit
  logging or the opt-in flag -- the review's specific ask, previously only
  covered at the direct evaluateToolCall() call level.
- Strengthened documentation (McpPolicy.maxToolCallsPerTurn JSDoc and
  .harness/mcp-policy.json's own field comment): explicit that despite the
  field name this is wall-clock rate limiting, not a literal
  per-conversational-turn counter -- MCP has no protocol-level turn concept.

31/31 policy-enforcer tests passing (was 30/30; +1 dispatcher-level test).

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-14 22:20:33 +00:00
rUvandClaude e7fb8edc19 dream(security): #3138 opt-in MCP governance policy enforcement (evaluated, ACCEPT) (#3139)
* dream(security): #3138 opt-in MCP governance policy enforcement (evaluated, ACCEPT)

.harness/mcp-policy.json declared auditLog/maxToolCallsPerTurn/dangerousPatterns
but was only ever read by the offline metaharness mcp-scan linter -- the actual
running claude-flow MCP server (mcp-server.ts) never consulted it, so any
connected client could call every tool with no audit trail and no call budget.

Adds an opt-in PolicyEnforcer (RUFLO_MCP_ENFORCE_POLICY=1, default off) wiring
auditLog + maxToolCallsPerTurn into the real tools/call dispatch path. Default
behavior is unconditionally unchanged. 16/16 new tests, 39/43 broader MCP
regression sweep (4 failures traced to pre-existing unbuilt sibling packages,
unrelated to this change). Independent adversarial critique found one real,
disclosed limitation (maxToolCallsPerTurn is session-lifetime cumulative, not
true per-turn) -- documented in the module, gist, and issue; not a blocker for
landing opt-in/default-off.

Full research, hypothesis, evaluation receipt, and witness: issue #3138 and
docs/dream-cycle/dream-gist-2026-08-31.md.

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

* dream(security): fail-closed on policy load/audit-log failure (review round 1)

Addresses ruvnet's PR review on #3139: an enforcement feature that
silently falls back to unrestricted execution when its own config is
missing/malformed, or when a mandatory audit-log write fails, isn't
real enforcement.

- loadMcpPolicy() returning null (missing/malformed .harness/mcp-policy.json)
  now denies the call instead of falling through unconstrained.
- A failed appendAuditLog() write, when policy.auditLog is true, now denies
  the call instead of silently proceeding unaudited.
- New evaluateToolCall() is the single enforcement entry point combining
  fail-closed policy loading + budget + fail-closed audit logging;
  mcp-server.ts's tools/call wiring simplified to call it directly.
- 8 new tests: fail-closed on null policy, fail-closed on malformed JSON
  on disk (server-integration level), fail-closed on unwritable audit log
  (server-integration level + unit level), concurrent-call budget
  accounting. 24/24 passing.

Two of the review's five findings remain open by design, not silently
dropped: the maxToolCallsPerTurn session-lifetime-vs-per-turn semantic gap
(needs a real TTL/reset design) and the stdio-only enforcement scope (HTTP/
WS transport lives in a separate @claude-flow/mcp package) — both already
documented in this module's own doc comment and flagged as follow-up in
the PR/issue, not attempted here to keep this round's diff reviewable.
Getting the repo's other currently-broken workflows (CI/CD Pipeline, CVE
Audit Gate, Cross-Agent Integration Tests, V3 CI, Verification Pipeline)
green is out of scope for this PR — confirmed pre-existing and base-branch-
wide (see PR comment), unrelated to this diff.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-14 22:07:29 +00:00
rUvandClaude 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>
2026-09-14 21:55:21 +00:00
rUvandClaude 1bd734e272 dream(security): #3102 bind ADR-377 caller-identity verification into live authorizeMcpTool chokepoint (evaluated, ACCEPT-with-caveats) (#3103)
* dream(security): #TBD bind ADR-377 caller-identity verification into live authorizeMcpTool chokepoint (evaluated, ACCEPT-with-caveats)

authorizeMcpTool() trusted the plain, unsigned CLAUDE_FLOW_PRINCIPAL_ID env
var as caller identity with zero verification (OWASP ASI07-class gap).
ADR-377 Phase 3 already implemented Ed25519 issueInvocationToken/
verifyInvocationToken but never wired it into a live dispatch path.

Binds the two: DualModeOrchestrator mints a per-worker signed
InvocationToken at spawn (worker-lifetime TTL, wildcard tool scope --
disclosed reduction from the primitive's original per-call design);
authorizeMcpTool verifies it before trusting identity, failing closed on
missing/forged/expired tokens. Off by default (CLAUDE_FLOW_MCP_CALLER_AUTH).

6 new deterministic Vitest scenarios plus an independent adversarial
critique (fresh session, verdict CONFIRMED-SAFE-WITH-CAVEATS) are recorded
in docs/dream-cycle/dream-gist-2026-08-26.md. Darwin skipped (scope
mismatch -- binary crypto gate, no tunable parameter space).

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

* fix(ci): register ADR-377 Phase 3 caller-identity env vars as known escape hatches

CLAUDE_FLOW_MCP_CALLER_PUBKEY and CLAUDE_FLOW_MCP_INVOCATION_TOKEN
(DualModeOrchestrator's per-worker Ed25519 credential pair, read by
resolveMcpCallerIdentity()) weren't registered in
audit-env-var-precedence.mjs's KNOWN_ESCAPE_HATCHES, so the audit flagged
CLAUDE_FLOW_MCP_CALLER_PUBKEY as a real violation (exit 1). Same no-CLI-flag
reasoning as the existing CLAUDE_FLOW_PRINCIPAL_ID entry: these are
credentials minted into a spawned worker's own environment, not a value
any caller should be able to select via a flag.

Verified: audit-env-var-precedence.mjs now exits 0. policy-runtime.test.ts
still 18/18.

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

* fix(ci): regenerate root package-lock.json for codex's new @claude-flow/security dep

The CI Test Suite job runs plain `npm ci` at repo root (no v3 pnpm
install step), so it resolves workspace deps strictly from
package-lock.json — not from v3/pnpm-lock.yaml, which this PR had
already updated. codex/package.json's new @claude-flow/security
dependency was missing from package-lock.json's codex entry, so CI's
npm ci never linked it and every dual-mode test importing
orchestrator.ts failed with "Cannot find package '@claude-flow/security'".

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

* fix(ci): build @claude-flow/security before Test Suite runs it

Complements d492ea835 (codex's package-lock.json entry) rather than
duplicating it: that commit fixed `npm ci` not *linking*
@claude-flow/security for codex at all ("Cannot find package"); this
fixes the fact that even where it IS linked (codex now, @claude-flow/cli
already), nothing builds its dist/ before tests run, so importers hit
ERR_MODULE_NOT_FOUND on dist/index.js instead.

This was already a known, pre-existing gap for @claude-flow/cli:
v3/@claude-flow/cli/__tests__/policy-runtime.test.ts has carried a
scripts/ci-test-baseline.txt entry for exactly this reason since before
this PR existed. dual-mode.test.ts and dual-mode-stdin-2947.test.ts
(added by the caller-identity candidate on this branch) newly trip the
same gap in @claude-flow/codex, confirmed by diffing main's own Test
Suite ratchet failures (3, pre-existing, unrelated oauth/publisher
plugin tests) against this branch's (5: the same 3 plus these 2). Adding
new files to ci-test-baseline.txt to paper over this is explicitly
forbidden by that file's own header ("Never add entries to make a
regression green"), and gutting the tests to avoid the import would
remove real coverage of the orchestrator/security integration point.

Real fix: build @claude-flow/security before "Run all tests", using its
own existing `npm run build` (tsc && verify-oauth-exports.mjs). Verified
locally end-to-end by removing both dist/ and the stale
tsconfig.tsbuildinfo (simulating a fresh CI checkout, since both are
gitignored) -- the build step produces a full dist/, both new codex test
files pass, and (bonus, explicitly allowed by the baseline file's own
"remove entries when fixed" rule) the pre-existing policy-runtime.test.ts
baseline entry is now consistently green too, so it's removed here.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-14 21:05:45 +00:00
rUvandClaude 9a9ff88671 dream(intelligence): #3109 wire computeConfidencePenalty/updateFisherFromConfidences into distillLearning's EWC gate (evaluated, ACCEPT-scoped, corrected post-review) (#3110)
* dream(intelligence): wire computeConfidencePenalty/updateFisherFromConfidences into distillLearning's EWC gate (evaluated, ACCEPT-with-caveats)

Dream Cycle 2026-08-27. distillLearning() called EWCConsolidator.getPenalty
with 1-element confidence arrays, which its own length guard collapses to
reading globalFisher[0] only (1 of 384 dims) for every pattern regardless of
embedding. computeConfidencePenalty/updateFisherFromConfidences already
existed for exactly this scalar-confidence case (docstring: "used by SONA
after distillLearning") but were dead code. Wires them in.

Full research, evaluation receipt, adversarial critique, and witness in the
linked issue/gist.

* docs(dream-cycle): update ledger for 2026-08-27 + backfill 08-20..26

Backfills 08-24 (swarm/weightedConsensus), 08-25 (performance/PQ
dispatch), 08-26 (security/caller-identity) rows verified via GitHub MCP,
and records the confirmed 08-20..23 no-run gap. Appends tonight's
2026-08-27 intelligence row.

* dream(intelligence): #3109 correct per-pattern overclaim per ruvnet review

ruvnet's review of PR #3110 correctly rejected the frozen hypothesis:
computeConfidencePenalty(oldConfidence, newConfidence) takes no
per-pattern embedding, so it cannot discriminate between patterns under
a fixed consolidator state -- it only reads avg(globalFisher), a value
shared by every pattern at a point in time. The original tests showed
sensitivity to *changing* the global Fisher state between two cases,
not to per-pattern discrimination within one state.

The underlying wiring defect is unchanged and still fixed: distillLearning()
was calling getPenalty([oldConf],[newConf]), which collapses to reading
globalFisher[0] alone. This commit narrows the claim to what's actually
true (shared full-Fisher-average signal vs. one arbitrary dimension) and
adds the acceptance test ruvnet's review specified: fixed state, equal
confidence deltas, different embeddings -> identical penalty, proving no
per-pattern discrimination exists.

Updates hypothesis/evaluation sections in the gist, the ledger row, and
inline comments to match. 153/153 tests passing (+1 acceptance test).

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-14 20:46:20 +00:00
rUv 0acd106420 fix(agentdb): pattern-store returns a readable id, pattern-search surfaces why tier=substring fired (#3326)
Fixes #3324 and #3325, both found while triaging #3288.

#3324: bridgeStorePattern's bridge-fallback branch (registry present,
reasoningBank unusable — the common real-world state) returned
bridgeStoreEntry's own internally generated row id (result.id,
generateId('entry')) as the caller's patternId, instead of the actual key
the row was stored under (generateId('pattern')). getEntry/memory_retrieve
look up by key, so the returned handle could never be read back.

#3325: agentdb_pattern-search's Tier-1 semantic step had two silencers —
a bare `catch {}` discarding a thrown error, and `semantic?.results ?? []`
treating `{success: false, error}` (which searchEntries returns WITHOUT
throwing) as an honest zero-match. Both made a hard failure and "nothing
found" indistinguishable. Capture whichever fires as `semanticError` and
return it alongside `tier` when tier === 'substring'.

Regression tests:
- #3324: new agentdb-pattern-bridge-fallback-3324.test.ts uses the
  documented __setMemoryBridgeRegistryForTests() seam (same pattern as
  memory-store-persist-warning-2968.test.ts) to force the bridge-fallback
  branch deterministically and round-trip the returned id through
  bridgeGetEntry plus a direct SQL check. Confirmed it fails on the
  unfixed code (patternId comes back entry_-prefixed) and passes on the
  fix (pattern_-prefixed) via git stash.
- #3325: extends bug-cluster-2219-2226.test.ts — asserts semanticError is
  a non-empty string whenever tier === 'substring' and the field is
  present; tolerant of tier === 'semantic' or an honest empty substring
  result, matching the file's existing skip-gracefully convention.

Not addressed: the deeper reason Tier-1 semantic search itself returns 0
where memory_search finds the same entry — #3325 explicitly flags this as
an unconfirmed hypothesis (possible distinct module instance / uninitialised
index between agentdb-tools.ts's direct import and memory-tools.ts's
getMemoryFunctions()), not something this fix diagnoses or resolves.


Claude-Session: https://claude.ai/code/session_01RYP825phHMjPRmmjkcAWpq
2026-09-14 19:54:29 +00:00
rUv dfd6596551 fix(agentdb): surface degraded:true on the pattern-search/store fallback path (#3323)
* fix(agentdb): surface degraded:true on the pattern-search/store fallback path

Fixes #3288. agentdb_pattern-search and agentdb_pattern-store both return
{success: true} (or a results array with no error field) when they've
silently fallen back to the memory-store-fallback / substring-match path
because the ReasoningBank controller is unavailable — the only signal was
a free-text `note` string, which a caller has no structural reason to
check on an apparently-successful response.

Add degraded:true to both fallback return paths, matching the existing
{degraded: true, reason} convention already used by agentbbs-tools.ts.
The healthy ReasoningBank path is unaffected (no degraded field).

Regression tests added to bug-cluster-2219-2226.test.ts, alongside the
existing #2226 test for the same two handlers: assert degraded:true when
controller === 'memory-store-fallback', and degraded === undefined
otherwise. Both skip gracefully when the backend can't initialize in
isolation, matching the file's existing convention.

Does not address the underlying reason vectorBackend/reasoningBank are
disabled in a given deployment (tracked separately in #1228/#2296) — this
fix is scoped to making that state observable from the tool response
shape, per the report's suggested fix direction.

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

* fix(agentdb): flag degraded at the controller boundary, not per fallback block

Review caught a real gap in the first commit: bridgeStorePattern and
bridgeSearchPatterns (memory-bridge.ts) return non-null with
controller: 'bridge-fallback' when the registry exists but reasoningBank
itself is unusable — this is the degraded state #3288 actually reported.
That result flows through `if (result) return result;` / the
results.length>0 early-return in agentdb-tools.ts, both of which sit
BEFORE the memory-store-fallback blocks the previous commit patched, so
agentdb_pattern-store never got flagged at all, and agentdb_pattern-search
only got flagged when bridge-fallback happened to return zero results.

Fix: check `result.controller === 'reasoningBank'` at both return
boundaries instead of patching specific fallback-label blocks. Any other
label — bridge-fallback, memory-store-fallback, or one added later — is
degraded by definition, so this can't silently reopen the gap the way
per-block matching just did. Also adds a `reason` field (stable,
machine-checkable) alongside the existing `note` (human-readable),
matching agentbbs-tools.ts's {degraded, reason} shape exactly rather than
degraded-only.

Tests inverted to match: assert degraded:true for every controller value
EXCEPT 'reasoningBank', instead of asserting undefined for everything
except the one label the previous commit patched — the old assertion
would have made bridge-fallback's un-flagged state an enforced invariant,
failing CI on a later correct fix.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01RYP825phHMjPRmmjkcAWpq
2026-09-14 18:41:07 +00:00
rUv 8008bc3562 fix(federation): verified event identity must win over publisher-controlled content (#3322)
* fix(federation): verified event identity must win over publisher-controlled content

fetchRecent/fetchManyOn/fetchChannel spread the parsed message content
after the signature-verified id/pubkey/created_at, so a publisher could
put those keys in their own content and overwrite their verified
identity downstream (reduceClaims trusts .pubkey for claim
release/handoff authorization). Reorder so verified fields always win.

Also in x-federation-channels.ts: reqEvents() never called verifyEvent()
at all, so channel-read/grant-accept events were trusted unsigned; add
the check. Same content-override reorder in x_federation_channel_read.

fix(hooks): escape argv for the Windows shell:true npm-shim path

ruflo-hook.cjs's invokeHook() passes hook-derived values (command text,
file paths) through cmd.exe via shell:true to resolve npm's .cmd/.ps1
shims. Node does no escaping in that mode, so a value containing a
cmd.exe metacharacter could be reinterpreted as a separate command or
redirection instead of reaching the CLI as data. Add escapeCmdArg()
(qntm.org/cmd algorithm, same one cross-spawn uses) and apply it to
every argv element on that path.

No native Windows/cmd.exe available to execute this end-to-end in this
environment — verified at the string-transform level only (8 unit
tests). Real Windows execution remains a required follow-up gate.

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

* fix(ci): register new hook test env var and test file with CI guards

Follow-up to the previous commit's escape-cmd-arg.test.cjs:
- Register RUFLO_HOOK_UNIT_TEST in audit-env-var-precedence.mjs's
  KNOWN_ESCAPE_HATCHES, matching the existing RUFLO_HOOK_CLI_OVERRIDE/
  RUFLO_HOOK_DEBUG_STDOUT entries for the same file.
- Register plugins/ruflo-core/scripts/escape-cmd-arg.test.cjs in
  ci-test-baseline.txt, matching the sibling mcp-launch.test.cjs entry —
  both are node:test-based .cjs files that vitest's own JSON reporter
  marks "failed" (it doesn't recognize the node:test API) even though
  every test inside genuinely passes under `node --test`.

Verified locally: node scripts/audit-env-var-precedence.mjs now passes
(exit 0). A scoped `vitest run` + `ci-test-ratchet.mjs --report` against
just these two files confirms escape-cmd-arg.test.cjs is no longer an
unexpected failure (the one remaining flagged file is a stale local
worktree artifact under .claude/worktrees/, not part of a clean CI
checkout).

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01RYP825phHMjPRmmjkcAWpq
2026-09-14 17:12:05 +00:00
rUv 13880e3aa4 fix(memory,daemon): stop destroying a user index, honour autoStart:false, and finish the sibling disclosure (#3282)
Three from the current issue backlog, all confirmed in source before touching
anything, and all with a test that fails without the fix.

#3224 — curateIndex() rebuilt MEMORY.md from the bridge's own topic files and
overwrote whatever was there. The #1556 guard only skips the write when NOTHING
matched, but the bridge writes the first topic file itself, so after the first
insight the guard stops applying and the rebuild replaces a hand-maintained index
with a stub: 75 curated lines and 49 links down to 6 in the reported case. The
bridge only knows its own topic files, so everything else looks like nothing to
it. A curate may now grow or reorder the index and never shrink it; when the
generated view is smaller it is written beside the file as MEMORY.generated.md
and the bridge emits index:preserved rather than going quiet.

#3278 — the autostart disable check read claude-flow.config.json with the key
daemon.autostart, while init generates .claude/settings.json with
claudeFlow.daemon.autoStart. A different file AND a different capital S, so the
one setting a fresh project actually ships was never consulted. It is written
false under the comment "Opt-in only — prevents unintended token consumption
(#1427, #1330)", which the runtime then ignored. Both files and both spellings
are now read: someone who wrote autostart false anywhere sensible meant it.

#3228 (half) — 3.41.1 disclosed the sibling AgentDB store from `memory list`
only. retrieve, search and an empty list kept returning a clean negative while
the rows sat in the file this interface does not read; the reported Windows
install has 31,673 rows in that other store answering found:false. A confident
negative is worse than an error, because nothing prompts anyone to look further.
That was a gap in my own fix, not a new defect.

Verified the tests are worth having by reverting each fix and re-running: #3224
fails 1/2, #3278 fails 2/4, and all six pass again restored.


Claude-Session: https://claude.ai/code/session_013u4pmL9ZUAXb6usVQgNo67
2026-09-10 19:16:14 +00:00
rUv e6f116b5c0 fix(memory): honour an explicit database path, and stop counting one store as if it were all of them (#3196) (#3271)
* fix(memory): honour an explicit database path, and stop counting one store as if it were all of them (#3196)

Two writes, both reporting success, landing in two files neither interface could
see whole. Reproduced on 3.41.0 in a clean directory:

  .swarm/memory.db            CLI-written key 1, MCP-written key 0
  .swarm/agentdb-memory.db    CLI-written key 0, MCP-written key 1

The cause is a cache, not a path calculation. getRegistry() kept one global
instance, so the first caller to touch the bridge decided the file for the whole
process; every later caller's dbPath was accepted and then silently ignored,
because the function returned the existing instance without ever comparing
paths. `--path` and CLAUDE_FLOW_DB_PATH have always advertised that they select
a database. Now they do: the cache is keyed by resolved path, so two paths in one
process are two registries, and a relative path and its absolute form are one.

The second half is worse than the split and is fixed separately. `memory list`
printed "Showing 1 of 1 entries" — not a warning, not a partial result, a
confident total describing one file as though it described the memory. A
downstream integrator measured 51 rows in one store and 16,671 in its sibling,
with 50 keys existing only in the smaller one. Silence would have been
recoverable; a wrong total is not, because nothing prompts anyone to look
further. The CLI now names the store it did not read, and how to read it.

Deliberately NOT done: merging the two files. #2786 gave AgentDB its own
plaintext file so native better-sqlite3 does not open an encrypted memory.db,
where it fails with "file is not a database" and silently disables the learning
system. Unifying the path would re-break encryption at rest. Both corpora stay,
and both stay readable.

The sibling count is read-only, opens nothing it cannot open read-only, and
returns null when the file is missing or unreadable — an unreadable store is not
evidence of an empty one, so the CLI stays silent rather than claim zero.

Verified against the original reproduction: the MCP-written rows are now
disclosed by name and count after the total. Three regression tests cover
sibling identity, path resolution, and silence on an unreadable store.

Reported-by: pacphi (pacphi/agentic-kit#213)
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_013u4pmL9ZUAXb6usVQgNo67

* fix(memory): make the bridge test seam override every path, not two guessed keys

Keying the registry cache by path broke #2968's fixture. That test installs a
fake registry through __setMemoryBridgeRegistryForTests and then calls
bridgeStoreEntry with its own temp dbPath, so an override installed under the
two keys the seam could guess was never consulted: the call resolved a third
path, missed the cache, and tried a real init instead of the fake.

A test seam means 'use this registry', not 'use it if the caller passes the path
I assumed'. It is now a separate override that getRegistry() returns first, kept
deliberately outside the path cache so the two concerns cannot collide again.

Verified: #2968 and the #3196 identity tests pass together, and the bridge dbPath,
durability, purge and row-visibility suites are unchanged.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_013u4pmL9ZUAXb6usVQgNo67
2026-09-10 14:14:53 +00:00
rUv 90bff10f15 feat(x-gateway): public and private swarm channels (ADR-386) (#3261)
Coordination on x.ruv.io was one flat topic: every member read every message,
and there was no way to keep a stream separate — or confidential — without
standing up another relay tenant.

Channels are one tag on the existing events, in two visibilities:

  public   c=pub:<name>      plaintext, any relay member reads it
  private  c=prv:<16 hex>    NIP-44 v2 ciphertext, k=enc hides the message type

The private channel key is generated client-side and cached at
~/.ruflo/channels.json (0600). Access is granted by sealing that key to a
member's pubkey over ECDH and publishing it as a ChannelGrant only they can
open. The gateway holds no channel keys and cannot decrypt — a hosted gateway
that encrypted on your behalf would be a custodian of every private channel on
the service, which is the thing worth not building.

Not hidden, and said so in the ADR: the relay sees that a channel exists, its
opaque id, who published and when. There is no revocation either; removing
someone means rotating the channel.

The channel tag is 'c', not the obvious 'h'. buzz-relay already implements
NIP-29-style server-side group membership on : an h-tagged event publishes
fine and the matching REQ comes back CLOSED "restricted: not a channel member",
so the author cannot read back their own message. Measured every other
single-letter tag against the live relay — c/d/g/l/m/r/x/y/z are all indexed and
unrestricted.

Surfaces: gateway channel_list / channel_sync / channel_publish (public only,
admin-gated) + ruv://swarm/channels; client x_federation_channel_{create,grant,
accept,publish,read,list} and 'ruflo federation channel --action ...'.

Verified: gateway 12/12, CLI 11/11, and a live two-key E2E on wss://relay.ruv.io
— grantee reads the plaintext, an outsider key cannot decrypt, the ciphertext
does not contain the secret, and the gateway's own channel_sync returns
encrypted:true. Deployed as ruflo-x-gateway-00008-s6n.


Claude-Session: https://claude.ai/code/session_013u4pmL9ZUAXb6usVQgNo67
2026-09-10 03:53:36 +00:00
rUv 6f29819fe6 fix(metaharness): bump the darwin pin to 0.10.2 so pin-drift and clean-install go green on main (#3262)
main is red on two required gates: @metaharness/darwin is declared ~0.9.0 while
npm latest is 0.10.2, so check-metaharness-pins reports STALE. The drift predates
#3256 — it merged with these gates already failing — but it is on main now.

Checked the bump rather than assuming it: unpacked both tarballs and compared.
0.9.0 and 0.10.2 ship the same bin (metaharness-darwin), the same exports (. and
./gepa), and the same gepa symbols this repo imports (loadCand6Genome,
CAND6_GENOME_PATH). Nothing we call was removed.

MH_DARWIN_PIN moves with it, since the mechanical oracle shells out to
npx @metaharness/darwin@<pin> and an out-of-range pin is its own drift failure.
pnpm lockfile regenerated in the same commit — v3 is a separate pnpm workspace
and a stale lockfile takes the frozen-lockfile jobs down.

Verified: check-metaharness-pins exits 0 with every pin reported current.


Claude-Session: https://claude.ai/code/session_013u4pmL9ZUAXb6usVQgNo67
2026-09-10 03:53:20 +00:00
rUv dbf450a927 feat(federation): ruflo CLI + MCP integration for x.ruv.io, and Seraphina (swarm queen) (#3256)
* feat(federation): ruflo CLI + MCP integration for x.ruv.io, and Seraphina (swarm queen)

Integrate the open swarm federation into ruflo itself, and add Seraphina —
a primary-coordinator / swarm-queen guidance tool in the style of the ruOS
assistant terminal (invoked from a terminal or any MCP client).

MCP tools (src/mcp-tools/x-federation-tools.ts), registered in the barrel and
the in-process registry so `callMCPTool` and the MCP server both see them:
  x_federation_sync / roster / claims / registry   (open reads)
  x_federation_publish / invite_mint / admit       (gateway-identity writes,
    require RUFLO_X_ADMIN_TOKEN; fail closed with no network call)
Each description follows ADR-112 ("Use when … wrong because …").

Seraphina (src/mcp-tools/seraphina-tools.ts): `seraphina_guidance { goal }`
gathers the live roster, claims board and recent messages from the x.ruv.io
gateway, compacts them (dedupe by from|type, cap 15 — a cheap tier drowns in
repeated PeerHellos), and asks the cognitum meta-llm gateway
(https://api.cognitum.one/v1/messages, model cognitum-auto by default with a
tier override) using a queen system prompt that treats message content as
data, respects one-owner-per-resource claims, and returns
{ guidance, proposals[], risks[] }. Proposals are advisory. JSON is extracted
by slicing the outermost object so fenced/prose-wrapped answers still parse.
Key from SERAPHINA_METALLM_KEY (GCP secret seraphina-metallm-api-key).

CLI: `ruflo federation sync|roster|claims|registry|invite|admit|publish`
(src/commands/federation.ts), thin over the same tools.

Skill: .agents/skills/open-federation/SKILL.md documents CLI, tools,
Seraphina, the claims rules, the canonical NIP-42 relay-tag gotcha, and
onboarding.

Tests: 11 (x-federation: RPC shaping, SSE parse, resource mapping, fail-closed
admin gating, isError surfacing; seraphina: registration, fail-closed key,
context gathering + queen prompt + x-api-key, tier override, fenced-JSON
extraction). Project typechecks at 0 errors.

Verified live: Seraphina against the real 3-node federation returned 3
structured proposals + 4 risks via cognitum-auto (routed to a cheap tier).

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

* fix(federation): ADR-125 env-var precedence — URL config takes a flag/arg, credentials registered env-only

The env-var-precedence audit correctly flagged the new process.env reads.
Config URLs now have a precedence path: `ruflo federation --gateway` feeds a
`gatewayUrl` tool arg (and Seraphina takes `metaLlmUrl`/`gatewayUrl`) that
wins over RUFLO_X_GATEWAY_URL / SERAPHINA_METALLM_URL, documented per ADR-125.
Credentials (RUFLO_X_ADMIN_TOKEN, SERAPHINA_METALLM_KEY) are registered as
env-only escape hatches with rationale: a secret must never be a CLI flag.
+1 test (arg precedence, arg not forwarded upstream). Audit passes locally.

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

* feat(federation): `ruflo federation join --code` — self-service invite access with your own key

The user-facing path into the open swarm. Decentralized by design: the user
generates/holds THEIR OWN Nostr key (~/.ruflo/nostr.key, 0600), redeems an
invite code with a NIP-98-signed claim directly against the relay (no admin in
the loop), proves membership via NIP-42, and can then publish as themselves.
The gateway never signs for a user.

- src/mcp-tools/x-federation-join.ts: x_federation_join { code, relayHttp?,
  relayWs?, keyFile? } — validates the code shape before any network call,
  loads/creates the key, NIP-98 claim, NIP-42 verify, returns pubkey + role.
  ADR-125: args take precedence over RUFLO_X_RELAY_HTTP / RUFLO_X_RELAY_WS /
  RUFLO_NOSTR_KEY_FILE.
- CLI: `ruflo federation join --code v2.…`
- nostr-tools added as an optionalDependency (secp256k1/Schnorr is not in
  node:crypto); the tool degrades with an install hint when absent. pnpm
  lockfile regenerated in this PR (frozen-lockfile CI).
- 4 tests: 0600 key create/reuse, valid NIP-98 header (kind 27235, verifies,
  bound to url+method+payload hash), malformed code rejected pre-network,
  ADR-112 description. Suite: 16/16; tsc 0; env-var audit passes.

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

* fix(federation): default relay -> wss://relay.ruv.io; join test tolerates missing nostr-tools

- x-federation-join defaults now point at the canonical relay.ruv.io host (Cloud Run
  domain mapping for buzz-relay); the raw run.app host stays routable for old clients.
- Validate the invite-code shape before the optional-dependency check so a bad code
  fails fast whether or not nostr-tools is installed.
- The root Test Suite runs the CLI tests via root npm ci, which never installs the
  CLI's optionalDependencies: the crypto cases are it.skipIf(!nostr-tools) so the
  file no longer trips the CI test ratchet.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_013u4pmL9ZUAXb6usVQgNo67
2026-09-10 02:51:40 +00:00
rUv e111bfbd7f fix(memory,tests): restore memory search recall and green the CLI suite (69 → 0) (#3252)
* fix(memory,tests): restore `memory search` recall and green the CLI suite (69 → 0)

The CLI suite had 69 failing tests across 50 files. Root-causing each rather
than adjusting expectations turned up one real product regression, two real
bugs, and a set of tests asserting things about the machine instead of the code.

PRODUCT REGRESSION — `memory search` recalled nothing (re-break of #2558)

`memory search` returned zero results for content that matched word for word,
while store/list/retrieve worked. Bisected to the threshold default:

  * 2026-07-04 #2558 restored recall, designed around a 0.3 threshold. Its
    fusion scores a full-coverage keyword hit as
    0.6*max(0,semantic) + 0.4*lexical, so with a non-positive cosine — routine
    for a one-word query — a PERFECT keyword match tops out at exactly 0.40.
  * 2026-07-26 #2790 set the CLI default to 0.7. Above 0.4, keyword recall is
    mathematically unreachable, so #2558 silently regressed.

Instrumented the live path to confirm before changing anything:
  key=note/alpha terms=["connectivity"] cov=1 bm25=0.029 sem=-0.883
  lex=1.000 score=0.400 thr=0.7      → dropped
Default restored to 0.3 at both sites, with the ceiling documented so it is not
raised past 0.4 again. Verified end to end: a shared keyword recalls all three
entries, a unique keyword recalls only its own. This was broken on main too.

REAL BUG — anchor containment rejected any project under a symlink

containedPath() compared a realpath'd root against a NON-realpath'd candidate,
so on macOS (/tmp → /private/tmp) every project looked like an escape. Now
compares like with like. Both guarantees re-verified by probe: ../ traversal,
deep traversal, absolute-outside and symlink-escape all still rejected;
symlinked-root spelling now accepted.

REAL BUG — a test that could not fail

funnel.test.ts asserted `elapsed < 100ms` as a proxy for "no network call" —
its own comment conceded a future fetch() would still pass. It also failed
intermittently (118ms) under full-suite CPU contention. Replaced with an
actual assertion on fetch/http.request/https.request, patched via the CJS
copies (ESM namespaces are non-writable). Negative-controlled: the technique
observes a real call and restores cleanly.

TESTS THAT MEASURED THE MACHINE, NOT THE CODE

  * 51 wasm tests asserted `available === true` for optional packages that were
    simply not installed, gated only on `process.env.CI`. Now also gated on real
    availability. The 7 tests in those files that need no WASM were lifted into
    their own blocks so they keep running rather than being skipped along with
    the rest — no coverage traded away for a green tick.
  * 4 agenticow tests lacked the `skipIf(!havePkg)` guard their 4 siblings had;
    in degraded mode the verb is inert and returns before validation.
  * policy-runtime hashed the raw tmpdir path while the source hashes the
    CANONICAL one, so it looked for a trust anchor that is never written there —
    and its cleanup was deleting a nonexistent path, leaking real anchors into
    ~/.config on every run.
  * sona's provider allowlist predated the ruvector / wasm-embedder /
    @claude-flow/embeddings backends.
  * ruvector/index asserted vi.mock satisfies a *dynamic* import() of a bare
    specifier. It does not under vitest 4 — the specifier is rewritten to
    '/@id/@ruvector/core' and fails with ERR_MODULE_NOT_FOUND. Now pins the
    contract the try/catch actually provides: unloadable → false, never throws.

TIMEOUTS — the "flakiness" was a fixed 5s budget

Six memory/intelligence files failed with "Test timed out in 5000ms", never an
assertion. They initialise a real ONNX embedder and SQLite; alone they are
fast, but the full suite saturates every core (~440% CPU). Because it depended
on scheduling, a different file failed each run. Raised testTimeout/hookTimeout
to 30s. (Process-level isolation was tried first and ruled out — forks changed
nothing, which is what identified the cause as time, not shared state.)

Verified: 3 consecutive full runs at 0 failed / 3572 passed on the feature
base, and 0 failed / 3537 passed on this branch's base.

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

* fix(tests): make ruvector availability assertion environment-independent

CI caught what my first pass missed. The rewritten test asserted
`isRuvectorAvailable()` resolves to `false`, but whether the dynamic
`import('@ruvector/core')` resolves is environment-dependent:

  - under vitest's module runner a bare-specifier dynamic import is
    rewritten to '/@id/@ruvector/core' and fails (ERR_MODULE_NOT_FOUND)
    → false → my `toBe(false)` passed locally
  - a normal install where the package resolves → true → `toBe(false)`
    fails, which is exactly what the CI test-ratchet flagged

The prior `toBe(true)` had the same defect in the other direction. Pin
the invariant that holds in BOTH environments instead — the only thing
the try/catch actually promises: it resolves to a boolean and never
throws. No specific resolution outcome is asserted.

Verified 33/33 locally; the sibling "should return boolean" test already
covers the type, so this now documents the no-throw contract distinctly.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_013u4pmL9ZUAXb6usVQgNo67
2026-09-09 23:07:32 +00:00
rUv 72df96c297 feat(agentbbs): cross-host federation — signed envelopes, pinned peers, union merge (#3251)
* feat(agentbbs): cross-host federation — signed envelopes, pinned peers, union merge

Phase 1 gave every host a local append-only room log and derived roomId
deterministically from the room label, so two hosts that register #sales
already compute the same roomId without talking. This adds the layer that
actually moves envelopes between them.

Design. A room log is an append-only set of immutable envelopes, so reconciling
two hosts is a set union — there is no conflicting write to arbitrate and
nothing for a consensus round to decide. Union is commutative, associative and
idempotent, so sync is order independent and safe to retry. That is a
grow-only set keyed on envelopeId, and it is cheaper and less failure-prone
than the Byzantine agreement the plugin README gestures at.

What union does not give you is authenticity: if any peer can inject, the merge
faithfully replicates forgeries. So each host now holds a persistent Ed25519
identity (Phase 1's key was ephemeral per process, which no peer can pin),
every published envelope is signed, and a receiver verifies against the key it
pinned at peer-add time rather than one carried in the envelope — otherwise an
attacker signs with their own key and claims any origin.

Transport is pull-based HTTP: peers poll GET /agentbbs/v1/rooms/:roomId/
envelopes?since=N. Pull needs no inbound connectivity, tolerates a node being
offline, and leaves ingest volume under the receiver's control; push would make
every node an unauthenticated write target. The server binds 127.0.0.1 unless
a bindHost is passed explicitly, and exposes no route that mutates state.

Bounds are enforced receive-side where a sender cannot negotiate them away:
envelopes per sync, bytes per envelope, bytes per response, peer count, and a
hop limit that is incremented on merge so a cycle terminates. hops is excluded
from the signed material, since it is mutated in transit by design.

Five tools: identity, peer_add, peers, serve, sync.

Tested: 35 new tests, most of them the trust boundary — forged payload,
forged origin, key substitution, unpinned signer, cross-room injection, replay,
oversize, hop exhaustion, traversal at the HTTP boundary, and private key never
served. Convergence and idempotence are asserted against two real nodes over a
real socket, not mocks. Verified end to end with three independent nodes:
all three converge on the same envelope set, a second round merges nothing,
and an unpinned node's injection is rejected.

The Phase 1 structural test pinned the surface at exactly 4 tools; it now pins
9 and names both groups, so adding a tool stays a deliberate contract change.
Full package suite: 68 failures against 70 on main, +35 passing — no
regressions.

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

* ci(agentbbs): stop rule 2 firing on the federation wire namespace

ADR-164 rule 2 exists to stop `agentbbs` becoming a mandatory dependency: a
static `import ... from 'agentbbs'` is forbidden, and any other mention has to
sit behind loadAgentbbs / a dynamic import. Its catch-all is a substring test
for "agentbbs" anywhere in the file.

agentbbs-federation.ts trips that catch-all without importing anything. Its
only remaining mentions after comment-stripping are string literals that never
reach a module resolver: the '/agentbbs/v1/...' HTTP route prefix and the
'agentbbs:<kind>:' hash domain-separators.

Adds those two shapes to the existing benign-pattern strip list. The
static-import check is untouched and remains the real gate.

Verified this narrows the check rather than loosening it, by running the
workflow's own rule-2 body verbatim against fixtures:
  - the real federation module            -> passes (false positive gone)
  - `import { x } from 'agentbbs'`        -> still caught
  - unguarded runtime reference           -> still caught
  - guarded `await import('agentbbs')`    -> passes

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

* ci(agentbbs): feed rule 2 via a quoted heredoc so bash stops mangling it

The rule 2 fix in fda44cd1f passed locally but still failed in CI. Cause:
the check runs as `node -e "..."` — a bash double-quoted string — so bash
rewrites the script before node ever parses it:

  - `\\?` collapsed to `\?`, turning the intended optional-backslash
    lookahead into a lookahead for a literal '?'. It could never match
    `agentbbs/v1`, so the strip was a no-op and rule 2 kept firing.
  - backticks in the explanatory comments were command substitution, so
    bash actually executed `export { agentbbsTools } from ...` etc. and
    spliced their (empty) output back into the script. Pre-existing since
    #2503 — visible as `import: command not found` noise in every run.

Fix the boundary rather than re-escaping: feed the script through a
QUOTED heredoc (`node - <<'RULE2'`), which bash passes through verbatim.
Regex backslashes and comment backticks now reach node as written. Also
drops backslashes from the new lookaheads so the pattern is robust even
if the step is ever converted back to an inline string.

Verified by executing the step's actual `run:` block through `bash -c`
(parsed out of the YAML), not a hand-retyped copy — that gap is what hid
the bug. Negative controls, all through that same path:

  static import of agentbbs ............................. CAUGHT
  unguarded runtime ref (deps['agentbbs']) .............. CAUGHT
  wire route + real unguarded ref (bypass test) ......... CAUGHT
  guarded dynamic import ................................ pass
  wire route only ('/agentbbs/v1/...') .................. pass
  hash domain only ('agentbbs:node:') ................... pass
  escaped-slash route (/agentbbs\/v1\/rooms/) ........... pass
  real tree ............................................. pass

The static-import check is untouched and remains the real gate.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_013u4pmL9ZUAXb6usVQgNo67
2026-09-09 21:54:14 +00:00
rUv 07f1cf3a3f fix(agentbbs-tools): detect the real CLI-only agentbbs package instead of a nonexistent JS import (#3250)
* fix(agentbbs-tools): detect the real CLI-only agentbbs package instead of a nonexistent JS import

The published `agentbbs` package (0.2.1) is a CLI-only launcher — a `bin`
script with no importable JS entry point — that downloads/builds a Rust
binary and shells out to it. loadAgentbbs()'s `await import('agentbbs')`
could therefore never resolve, even with the CLI correctly installed and
on PATH, so all 4 federation_bbs_* tools reported degraded:true
unconditionally regardless of install state.

Replace the dynamic import with a subprocess presence probe
(agentbbsCliAvailable(), `agentbbs --version`), matching how the rest of
the codebase treats optional CLI tools. shell:true is required for the
probe to find npm's Windows .cmd shim (child_process does not consult
PATHEXT otherwise).

Making the probe actually succeed surfaced two further pre-existing bugs
in code that was previously always skipped:
- vitest.config.ts externalized @noble/ed25519 alongside genuinely-optional
  deps (agentic-flow, agentdb, ...), but it is an always-installed hard
  dependency; externalizing it broke dynamic-import resolution under Vite's
  SSR transform.
- federation_bbs_human_join dynamically imported @noble/ed25519 a second
  time (getSigningKey() already does), which is now deduplicated behind one
  memoized loadEd25519() loader.

All 12 tests in agentbbs-tools.test.ts now pass, including the 4
happy-path tests that were previously always skipped.

* fix(agentbbs-tools): gate the probe shell to win32 instead of always on

`shell: true` was unconditional, and the probed binary comes from
`process.env.AGENTBBS_BIN`. Under a shell that argument is command-interpreted,
so `AGENTBBS_BIN='agentbbs --version; touch /tmp/PWNED'` executes the trailing
command. Verified locally: the file is created with `shell: true` and the spawn
fails with ENOENT once the shell is gated off.

This is the case browser-tools.ts already warns about in the comment beside the
same pattern -- "if user-controlled args are ever added, escape them before
spawn" -- and `shell: process.platform === 'win32'` is the convention already
used at browser-tools.ts:49, commands/init.ts:856 and :1194, and
init/helpers-generator.ts:1459. Unconditional `shell: true` appeared nowhere
else in the package.

The Windows behaviour the original was reaching for is unchanged: cmd.exe still
resolves the `agentbbs.cmd` shim via PATHEXT. POSIX simply stops interpreting
the override. Added windowsHide to match the sibling call sites.

Verified the fix still does what it set out to do: with the CLI resolvable the
suite is 12/12 and the four previously-always-skipped happy-path tests execute,
with the shell disabled on POSIX.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_013u4pmL9ZUAXb6usVQgNo67
2026-09-09 20:14:19 +00:00
rUv d55b1bfeac fix(memory): stop reporting a gated native bridge as the active backend (#3228) + fast-uri CVE (#3245)
* fix(memory): stop reporting a gated native bridge as the active backend (#3228)

On Windows the #3024 kill-switch makes getRegistry() return null, so every
memory read/write silently falls back to the sql.js store (memory.db) instead
of the AgentDB corpus (agentdb-memory.db) the bridge would have opened. The
reporter measured the consequence: a canary store/retrieve round-trip SUCCEEDS
because both halves use the same unintended file, while an existing live-store
key returns found:false against 31,673 real rows.

The status surface hid the substitution. getHNSWStatus() gated its bridge
branch on whether the bridge MODULE was loaded -- which it is, even when the
registry is gated off -- so describeBackend() printed "sqlite (bridge,
brute-force cosine)" for a store the bridge never touched.

Gate on whether the bridge is permitted to be the active path rather than on
whether the module resolved. shouldDisableNativeBridge() is sync and a pure
function of platform + env, so it is a faithful discriminator and needs no
warm registry. describeBackend() now names the gate and its reason, so an
upgrade that changes which file receives writes says so.

This does not fix the opt-in allocation abort (#2948) or reroute the fallback
to the AgentDB corpus; both need Windows validation. It makes the silent case
loud, which is what the report asks for first.

Also bumps fast-uri 3.1.5 -> ^3.1.6 (resolves 3.1.7), clearing
GHSA-5jgf-p345-68v8 (high, host confusion via skipped IDN canonicalization)
and the ajv high that inherited it. Same change as #3222 by @aeonframework,
applied here because CI was never authorized to run on that PR.

Refs #3228, #3222, #2948, #3024

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

* chore(release): 3.39.0 -> 3.39.1

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01JJnDvpYYk2rTvjkudQUoCk
2026-09-09 12:55:02 +00:00
rUv ea2df4726c fix(flywheel): encode candidatePolicy fractions as decimal strings (#3229) (#3235)
`ruflo metaharness flywheel run` wrote receipts whose candidatePolicy
carried binary floats — {"alpha": 0.3, "mmrLambda": 0.5} — contradicting
the contract each receipt claims to satisfy:

  witness-receipt-contract.md rule 2  "Fractional values are decimal
                                       strings, never binary floats"
  conformance-checklist A3            "Every fractional value is a
                                       canonical decimal string"
  ADR-322C L22                        "Signed policy fractions use
                                       schema-quantized decimal strings"

The spec's own example strings it: {"hnswEf": 128, "hybridWeight": "0.65"}.
Confirmed in the PUBLISHED 3.38.23 artifact, not just source:
dist/src/services/harness-flywheel.js:219 `candidatePolicy: candidate`.
Two releases shipped after the 3.38.21 report without fixing it.

Root cause was two-part, and the second half is what let it survive:

1. Producer: `candidate as unknown as Record<string, unknown>` — a DOUBLE
   cast (a single one will not compile) that erased RetrievalConfig's
   `number` fields and laundered floats into the receipt.
2. Verifier: `assertJsonValue` accepted any finite non--0 number. That was
   its entire number rule, so ruflo verified its own non-conforming
   receipts while autogenous's stricter verifier correctly rejected them
   (ruvnet/autogenous#15). The JSON Schema pins `decimalString` on ten
   named fields and cannot express it inside `candidatePolicy`, which is
   opaque by design — so the rule lived only in prose.

Fix:
- `encodePolicyFractions` encodes non-integers to scale-12 decimal strings
  and leaves integers as JSON numbers, matching the contract's example.
  Recurses through nested objects and arrays.
- `policyCandidateId` encodes at the hashing boundary, so the content ID is
  always over the canonical form. Encoding is idempotent, so
  policyCandidateId(raw) === policyCandidateId(encoded) and `verify` can
  still recompute the ID from the payload.
- `assertReceiptNumberDomain` enforces the rule at the RECEIPT boundary, on
  produce (before signing) and on verify. This is the half that closes the
  class: without it the next writer drifts again invisibly.
- The producer's type-erasing double cast is gone.
- policySchemaVersion v1 -> v2, because fixing the encoding changes the
  candidate content ID. Pre-fix receipts now refuse promotion with an
  ACCURATE 'policy schema changed' instead of a confusing 'stale baseline'
  hash mismatch. Signed receipts are deliberately NOT migrated: re-encoding
  changes the content, hence the ID, hence invalidates the signature — a
  migration would mean minting new receipts claiming to be old ones. They
  stay valid as history and unpromotable; the champion is re-established
  through the existing confirm-and-reason reset path.

Scope note worth keeping: a first attempt put the rule inside
`canonicalizeJcs` and broke the proposer envelope and the promotion ledger,
which share that canonicalizer and which the contract does not govern. The
full suite caught it; a test now pins that the shared canonicalizer stays
permissive.

Mutation-verified: disabling the encoder fails 16 tests, disabling the
enforcement fails 1, and dropping the boundary encoding in
policyCandidateId fails 13.

Measured A/B on one installed+built tree — strictly better, nothing broken:
  baseline  40 files / 83 tests failed, 2801 passed
  with fix  39 files / 82 tests failed, 2811 passed
The remaining failures are @ruvector/*-wasm optional native deps absent on
this host, present identically on origin/main.


Claude-Session: https://claude.ai/code/session_01J2s8oQsAZjJtJ6inoYRFPj
2026-09-08 16:46:28 +00:00
rUv 6acc689150 dream(intelligence): #3220 gate EnhancedModelRouter's forwarded modelId on tier match (evaluated, ACCEPT-scoped) (#3221)
Merged after independent re-verification: 109/109 CI green, the earlier '168 failures' finding traced to an unbuilt-sibling-package local artifact (unrelated to changed files), and a subsequent CI flake confirmed unrelated via clean re-run. Overriding the PR's self-merge gate on explicit user (ruvnet) authorization.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_013XaRQntabVwGT9SvnW8cKK
2026-09-07 10:57:05 -04:00
rUvandClaude 277c7bc03a dream(memory): #3168 wire embedding-cosine into SmartRetrieval's MMR step (evaluated, ACCEPT) (#3169)
* dream(memory): wire embedding-cosine into SmartRetrieval's MMR step (evaluated, ACCEPT)

smart-retrieval.ts's MMR diversity re-ranking used token-Jaccard text
overlap as its "similarity to already-selected" term, even though
memory-initializer.ts's searchEntries() already computes real
ONNX-embedding cosine similarity for the primary relevance score and
discards it before returning. 2025-2026 production practice (LangChain's
reference maximal_marginal_relevance, Qdrant's native Mmr query shipped
Sept 2025, Weaviate's MMR reranker shipped in 1.37) universally uses
embedding-cosine for this term; token overlap misses low-token-overlap
paraphrases embeddings correctly flag as near-duplicates.

Threads the embedding through: searchEntries()'s two live compute sites
(RaBitQ rerank, brute-force SQL) now return it instead of discarding it;
the two CLI/MCP bridge mappers (memory-tools.ts, commands/memory.ts) pass
it through; SearchCandidate gains an optional `embedding` field;
mmrRerank uses cosine when both candidates have one, falling back to
token-Jaccard otherwise (existing callers/tests without embeddings are
unaffected). controller-registry.ts's separate toCands()/applyMMR path
had the same gap for a different reason (embedding available on
r.entry.embedding but never copied) — fixed the same way.

Evaluated via deterministic Vitest, zero LLM calls, $0 cost. New
discriminating test: a low-token-overlap paraphrase (near-1.0 cosine to
the seed) vs. a genuinely different topic (near-0 cosine). Baseline
(git stash-isolated): picks the paraphrase second (Jaccard can't tell
"low overlap because paraphrase" from "low overlap because unrelated").
Candidate: correctly picks the different topic second. Full
@claude-flow/memory suite: 460/461 passing identically with/without the
candidate (1 pre-existing chmod-based environmental failure, same class
documented since 2026-08-15). tsc --noEmit: zero new errors (verified
@claude-flow/cli's 455 pre-existing errors, from unbuilt workspace
packages, are identical with and without this diff).

Darwin: skipped, scope mismatch (correctness/similarity-metric fix with
a discriminating unit test, not a continuous parameter with a
gold-labeled corpus).

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

* dream(memory): address review remediation — split CI, real benchmark, hardening

Response to ruvnet's REJECT review on #3169:

1. Split — dream-cycle-backlog-guard.yml moved out to #3205; this branch
   now carries only the MMR fix, rebased onto main (which already
   includes the merged #3203 CI fix).

2. Real benchmark (new src/mmr-benchmark.test.ts): 18-doc/6-topic labeled
   corpus (1 canonical + 2 low-token-overlap paraphrases per topic), run
   through the actual smartSearch/mmrRerank code, swept across mmrLambda
   in {0.3, 0.5, 0.7, 0.9} rather than one favorable value. Honest
   finding: at diversity-heavy lambda, candidate's recall/nDCG drop
   sharply vs. baseline, because cosine correctly suppresses same-topic
   near-duplicates that Jaccard fails to detect at all (and so
   "accidentally" keeps full recall). At smart-retrieval.ts's own default
   (lambda=0.7), recall@6/nDCG@6 are identical to baseline (1.000/0.777
   both) while topic-diversity improves 0.472->0.667 and ground-truth
   duplicate-rate drops 0.289->0.200. Reports latency (sub-ms both paths
   at this corpus size) and a memory-overhead estimate.

3. Malformed/dimension-mismatch: found and fixed a real bug while writing
   these cases. A NaN/Infinity-poisoned embedding component reached
   cosineSimilarity unguarded; the poisoned NaN score meant `mmr > bestMmr`
   was never true (NaN comparisons are always false in JS), which could
   silently break MMR's selection loop and under-fill results below the
   requested limit. Added isWellFormedEmbedding() so malformed/empty
   embeddings fall back to token-Jaccard, same as absent/mismatched ones.
   3 new cases (NaN/Infinity, empty array, explicit dimension-mismatch)
   plus a test mirroring the two real CLI/MCP output whitelists
   (memory-tools.ts:559-569, commands/memory.ts:633-639) to assert
   `embedding` cannot appear in either shape.

4. Determinism: new test runs the same input through smartSearch 5 times
   concurrently, asserts byte-identical result ordering every time,
   including a genuine same-embedding tie.

Full @claude-flow/memory suite: 465/466 (1 pre-existing, unrelated
environmental failure). tsc --noEmit: zero errors.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-05 11:57:23 -04:00
ruv d413297dde fix(memory): stop seeding the bridge's ControllerRegistry with the sql.js dbPath
Fixes #3155. `initializeMemoryDatabase()` passed its just-resolved
sql.js-facing `memory.db` path straight through to
`activateControllerRegistry()` -> `bridge.getControllerRegistry(dbPath)`.
That seeded the process-wide ControllerRegistry singleton with `memory.db`
as AgentDB's own native better-sqlite3 database, instead of the dedicated
`agentdb-memory.db` sibling `getAgentDbPath()` exists specifically to
provide (#2786).

Because this activation only runs on a database's first-ever init (an
already-initialized `.swarm/` skips it via the #1791.6 idempotent no-op
branch), a bridge started against a brand-new directory would activate
against `memory.db` and work fine for that process's lifetime. A
restarted bridge process, whose `.swarm/memory.db` already exists, would
skip that call entirely, and its first real bridge operation would
activate the registry against `agentdb-memory.db` instead (via the
`dbPath || getAgentDbPath()` fallback in memory-bridge.ts). That file
never received the earlier writes, so every read after a restart came
back `found:false` / an empty list, silently, with no error anywhere.

`activateControllerRegistry()` no longer forwards the sql.js dbPath to
the bridge at all — it calls `bridge.getControllerRegistry()` with no
argument, so both the init-time warm-up and every later bridge call
(bridgeStoreEntry, bridgeGetEntry, ...) resolve the same file via
`getAgentDbPath()`, regardless of whether this is a fresh directory or a
restart against an already-initialized one.

Co-Authored-By: claude-flow <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01MND33UDrtWPRH851k9w8M3
2026-09-01 21:40:17 -04:00
Dragan Spiridonov 36740e4304 fix(proxy): verify effective daemon on install 2026-08-30 15:27:37 +02:00
ruv 8a85001942 fix: Windows CI build, dead agentdb controller exports, memory driver doctor check
- #2992: pin windows-latest -> windows-2022 for the Build V3 matrix job.
  windows-latest moved to VS2026, which node-gyp can't detect, breaking
  native builds for hnswlib-node and better-sqlite3.
- #2977: remove dead agentdb import attempts in controller-registry.ts for
  8 exports no installable agentdb range provides. Promote the working
  tieredMemoryFallback/createConsolidationStub implementations to
  first-class for hierarchicalMemory/memoryConsolidation; the other 6
  controllers (semanticRouter, mutationGuard, attestationLog, gnnService,
  rvfOptimizer, guardedVectorBackend) have no fallback and now return null
  directly instead of attempting an import that never resolves. The
  consolidation stub now reports source:'stub' and an explicit note so
  agentdb_consolidate reads as "did not run" rather than "nothing to do".
- #2968: add a read-only doctor check (checkMemoryPersistenceDriver) that
  reports whether the active SQLite driver is native better-sqlite3
  (durable, WAL-capable) or the sql.js fallback (silently drops
  wal_checkpoint writes), using the table-count signal from the issue
  (~47 native vs ~10 fallback). Warns, never fails; does not touch install
  behavior.

#2990 (MCP HTTP transport protocolVersion/tools-list/IPv6 bind) required
no code change — all three fixes are already present on main; the bug in
published ruflo/@claude-flow/cli only persists because no release has been
cut since they landed.

#3002 (ruvocal hidden-tab stream freeze) also required no code change —
already fixed on main.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_018ZkgSrVRWNMcXmaFiMZ7Z8
2026-08-22 12:14:24 -04:00
rUvandClaude b291ac4049 dream(intelligence): #3048 discounted Thompson sampling for model-router bandit (evaluated, ACCEPT-scoped) (#3049)
* dream(intelligence): discounted Thompson sampling for model-router bandit

Adds an opt-in `priorDecay` config field (default 1 = disabled, fully
backward compatible) to ModelRouter's Beta-Bernoulli bandit. When enabled,
every bucket/model's alpha/beta decays geometrically once per
recordOutcome() call before that round's reward is added (arXiv
2305.10718 discounted Thompson sampling), so accumulated routing history
from a long-running persisted state file no longer permanently dominates
the posterior after a real-world model-quality shift.

Benchmark (n=30 paired trials, seeded PRNG, identical stream baseline vs
candidate): non-stationary regime-shift recovery 26.5 -> 21.9 rounds
(-17.6%, t=7.24); post-shift correct-routing rate +1.3pp (t=6.10);
stationary-workload invariant held (delta +0.02pp, not a regression).
Receipt: v3/@claude-flow/cli/benchmarks/results/prior-decay-receipt.json.

Mirrors the epsilon-decay pattern q-learning-router.ts already applies to
its own exploration rate -- an internal-consistency fix, not an imported
pattern. Evaluation and adversarial critique in progress; this commit is
the checkpointed, test-passing candidate + its baseline/candidate receipt.

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

* dream(intelligence): #3048 fix adversarial-critique findings, add gist + ledger

Independent adversarial critique found and this commit fixes: a paired-t
statistics bug (population vs sample stddev inflated every t-value by
n/(n-1)), an unguarded priorDecay input (NaN/negative could silently poison
persisted .swarm/model-router-state.json forever, bypassing sampleBeta's
own defensive fallback), and a single-bucket benchmark blind spot (now
covers low + med complexity buckets -- the med bucket shows no significant
effect, disclosed rather than hidden).

Also adds the research gist and backfills 3 missing ledger rows for
2026-08-14/15/16 (real PRs/issues existed for those nights but the ledger
table wasn't updated) plus tonight's own row.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-08-21 11:21:27 -04:00