#1825 guards against a `workspace:` protocol leak in cli's optionalDependencies
by citing the literal `"@claude-flow/memory": "^3.0.0-alpha.` in
v3/@claude-flow/cli/package.json. #3392 pins that dependency exactly, so the
caret is gone and the marker drifted (witness marker drift smoke, #2021). The
marker is now `"@claude-flow/memory": "3.0.0-alpha.`, which still catches the
`workspace:` leak (that string would not match).
All three manifests were regenerated OS-aware (os field = linux/macos/windows)
with a pristine, unbuilt checkout of the release-bump commit:
- entries whose cited file exists were re-hashed and re-verified (18);
- the 99 entries citing build outputs (dist/) are carried forward unchanged,
not re-attested, because a source checkout does not contain them: that is
exactly the set the CI smoke reports as "file-missing (skipped, #1880)".
The regeneration tool as shipped would mark those 99 unverified, which would
turn 117 verified into 18 for a reason unrelated to this change.
Both witness smokes pass locally: marker-drift (18 pass, 0 drifted) and
verify-precondition.
Co-Authored-By: RuFlo <ruv@ruv.net>
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>
`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>
The test spawned the real `init` with only cwd isolated, so a local run
appended the Ruflo block to the developer's ~/.claude/CLAUDE.md, registered
[mcp_servers.ruflo] in ~/.codex/config.toml, and started a
`codex plugin marketplace add` clone that outlived init's 20 s timeout as an
orphan.
Each spawn now gets a throwaway HOME/USERPROFILE/CODEX_HOME and a fail-fast
`codex` stub first on PATH, which init treats as a non-fatal skip.
Verified with a decoy home: before, both files' checksums change; after, both
are byte-identical and no clone process is left behind.
Co-Authored-By: RuFlo <ruv@ruv.net>
Minor: new opt-in router embedder (CLAUDE_FLOW_ROUTER_EMBEDDER=minilm),
router.js becomes a signed critical helper.
- ADR-389: router.js refreshed on upgrade (installs get the #3401 word-boundary fix)
- ADR-390: opt-in MiniLM embedder for hooks_route; default stays hash
- ADR-391: blind 197-prompt corpus + benchmark; first run promotes nothing
- typesafe-router test (e) fixed (was red on main since #3402)
Helpers manifest re-signed @ 3.44.0 — now 5 helpers (router.js added).
No non-bundled leaf changed.
Co-Authored-By: RuFlo <ruv@ruv.net>
* 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>
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>
* 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>
* 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>
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.
* 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>
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
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.
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.
@ruvector/router 0.1.30 builds its HNSW graph keeping only the nearest
candidates per node, so on clustered data no edges cross between clusters
and search returns mostly the most-recently-inserted region. 0.1.31
(ruvnet/RuVector#1005) switches to the diversity heuristic.
Measured in this repo's own install, 3,000 clustered 64-d vectors,
100 queries, recall@10 vs exact cosine:
0.1.30 -> 0.071
0.1.31 -> 1.000
Consumers: hooks_route's native semantic router (hooks-tools.ts
getSemanticRouter) and agentdb/agentic-flow, which dedupe to the root copy.
Their own ranges (^0.1.15 / ^0.1.25) already admit 0.1.31, so this raises
the floor and moves the lockfile; v3/pnpm-lock.yaml is left alone because
a transitive-only update there re-resolves unrelated packages.
scripts/verify-helpers.mjs pins the signed manifest to the package version, so
the 3.42.4 -> 3.42.5 bump invalidated it:
[verify-helpers] manifest version 3.42.4 != package.json 3.42.5
Re-signed the 4 critical helpers (auto-memory-hook.mjs, hook-handler.cjs,
intelligence.cjs, statusline.cjs) with ruflo-helpers-signing-key from GCP
Secret Manager (ruv-dev). Verify now reports:
[verify-helpers] ok — 4 helpers match signed manifest @ 3.42.5
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The v3.42.5 release (run 35641592705) failed at "Install root release-audit
dependencies", 9 steps before any publish. `npm ci --omit=dev --omit=optional`
triggers v3/@claude-flow/security's "prepare": "npm run build" (it is both a
root workspace and a root dependency). That package does not declare
@types/node, relying on a hoist from the root dev tree, so --omit=dev leaves
tsc with no Node types and --omit=optional removes @napi-rs/keyring:
TS2591: Cannot find name 'crypto' / 'Buffer' / 'process'
TS2307: Cannot find module '@napi-rs/keyring'
The step only needs `semver` for audit-umbrella-version-lockstep.mjs, so it
should not link or build workspaces. Verified locally against the tagged tree:
the current command reproduces the CI failure exactly; adding --workspaces=false
installs 175 packages and the lockstep audit passes.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Ships #3390 (#3327 Finding A). The fix spans two packages and only one of
them rides the release train, so memory is bumped and published alongside:
- cli/src/memory/memory-bridge.ts -> @claude-flow/cli 3.42.5 (train)
- memory/src/controller-registry.ts -> @claude-flow/memory 3.0.0-alpha.25
Without the memory publish the embedder half of the fix never reaches users
and reasoningBank stays inert, since @claude-flow/memory is NOT in
INTERNAL_RUNTIME_PACKAGES and resolves from the registry via ^3.0.0-alpha.23.
CLAUDE.md: correct the Publishing Rules claim that internal @claude-flow/*
components are all bundled. Only four are (security, codex, mcp,
plugin-agent-federation); cli-core, neural, shared and memory resolve from
the registry and need a standalone publish when their source changes. Adds a
semver-aware pre-tag drift check that fails loudly if it inspects zero leaves.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
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>
Proposed. Root cause: `ruflo swarm start` (commands/swarm.ts:588-672) never
executes the objective — it prints a plan, calls MCP swarm_init, writes
state.json, prints "execution happens via claude -p / hive-mind spawn --claude"
and returns. Nothing invokes those, so the console's Swarms deploy sets up
coordination then finishes with no work, no artifacts, nothing to find/use/deploy
(agents are registry rows with no process).
Decision: swarm start becomes a streaming, steerable, long-horizon agentic
orchestrator that WIRES existing ruflo primitives (the nested-* / research-agent
recursive-fan-out pattern, claude -p, MCP tools, AgentDB memory, self-learning
hooks, hive-mind raft consensus, agentbbs federation, horizon-tracker) instead of
deferring. Streams NDJSON per-agent (works over the console SSE /run today); a
file-inbox session channel carries real-time guidance; a structured final
overview names artifacts + where to find/run/deploy them.
Hard dependencies stated: agents can't run without the ADR-069 per-tenant LLM
key (prerequisite for the console path); real-time steering needs a bidirectional
channel (file-inbox now, WebSocket later). Increments I1-I4 + an acceptance test.
Ships PR #3340 (fix(memory): preserve retrieval relevance in smart search
results): memory_search({smart:true}) was returning the RRF fusion score in
the `similarity` field instead of the underlying retrieval relevance;
`similarity` now carries the raw retrieval score, and the fused SmartRetrieval
ranking score is exposed separately as `rankingScore`.
Note: 3.42.1-3.42.3 were published to npm without matching version-bump
commits on main (no `chore(release)` commit, gitHead unset in npm metadata).
Verified via `v3.42.0`/`v3.42.1`/`v3.42.3` git tags: all are ancestors of this
commit, so 3.42.4 is a strict superset of what was previously published.
Co-Authored-By: RuFlo <ruv@ruv.net>
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.
Same EINVAL bug as #3346 (stage-internal-runtime-bundles.mjs's runBuild),
one file over: prepare-root-publish.mjs's own npm.cmd spawnSync for
building v3/@claude-flow/swarm and cli lacked shell:true, blocking the
root claude-flow package's Windows publish the same way. Found
immediately after #3346 while publishing 3.42.3 end to end.
Single-string shell:true form, matching #3346's fix, to avoid Node's
DEP0190 warning. Still constant literals, no injection surface.
* fix(release): spawn npm.cmd with shell:true on Windows
spawnSync('npm.cmd', ['run','build'], {stdio:'inherit'}) threw EINVAL on
Windows, blocking every @claude-flow/cli publish on this platform since
CreateProcess can't launch a .cmd directly and Node has refused to shell
out implicitly since CVE-2024-27980.
Found live while publishing 3.42.3: prepublishOnly -> prepare-publish.mjs
-> stageInternalRuntimeBundles() rebuilds the four internal runtime
packages (security/codex/mcp/plugin-agent-federation) and hit this on
the very first Windows publish attempt after upgrading past the Node
version where the implicit shell fallback still worked.
command/args here are constant literals ('npm.cmd', ['run','build']),
never hook-derived or user-controlled, so shell:true carries no
injection risk.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(release): avoid DEP0190 warning in the npm.cmd shell:true fix
Single-string command form instead of args array — same shell:true
safety (still constant literals, nothing interpolated), no warning.
Co-Authored-By: RuFlo <ruv@ruv.net>
override.split(' ') broke process.execPath into 'C:\Program' plus stray
tokens on a standard Windows Node install (C:\Program Files\nodejs\node.exe),
since the override string wasn't quote-aware. Found while verifying #3332's
Windows argv fix on a real Windows machine: 3 of 32 plugin-hooks-smoke cases
failed only on a stock Windows dev box, not on windows-latest CI (whose
hostedtoolcache Node path has no space).
RUFLO_HOOK_CLI_OVERRIDE is a test-only escape hatch, never set in
production, so this has no user-facing impact — it only unblocks the
test harness on the common case of a Program-Files Node install.
Adds splitCliOverride(), a minimal double-quote-aware tokenizer, and
quotes the two override strings test-hooks.mjs builds from
process.execPath.
`beforeEach` built each test's "unique" audit-log/policy file path from
`Date.now()` alone (millisecond resolution). Two tests whose beforeEach
hooks fire within the same millisecond — easily happens in a fast
suite — get the identical filename, so one test's audit-log writes leak
into another's line-count assertions.
This is the root cause of an intermittent CI failure: "deny -> expiry ->
allow through the real stdio dispatcher" expects exactly 3 audit-log
lines but sometimes sees 5 — the extra 2 lines come from the preceding
"budget=1" test's two dispatch calls, when both tests' beforeEach hooks
land on the same Date.now() value. Confirmed the mechanism directly:
Date.now() collides trivially in a tight loop (2M iterations, first
try), while crypto.randomUUID() never collides across 200k calls.
Swapped both the audit-log and policy-file paths in this describe block
to use randomUUID() instead. Ran the file 9 times back-to-back post-fix:
31/31 passing every time.
Claude-Session: https://claude.ai/code/session_01SjxUvZnyBdwtx4Y1jKAqt6
#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.
learning-bridge.ts's loadNeural() called
`new NeuralLearningSystem({ mode, ewcLambda })`, but the real constructor
signature is `constructor(mode: SONAMode = 'balanced')` — a bare string
(see @claude-flow/neural/src/index.ts and the CLI's own reference-correct
call site in memory/neural-package-bridge.ts). This never threw: SONAManager
resolves `MODE_CONFIGS[mode]`, which for an object argument coerces to the
key "[object Object]", finds nothing, and `{...undefined}` silently produces
an empty config instead of the intended mode's settings — so every
LearningBridge-driven neural session has been running with an unset,
default-less SONA config regardless of `sonaMode`/`RUFLO_INTELLIGENCE_MODE`.
`ewcLambda` was never a real constructor parameter either — each mode
carries its own fixed lambda via MODE_CONFIGS, with no override mechanism —
so it's dropped from the call rather than papered over.
Added a regression test that mocks the real `@claude-flow/neural` import
path (the existing 67 tests all inject a `neuralLoader`, which bypasses this
code path entirely — that's why this went uncaught). Confirmed the new test
fails against the pre-fix constructor call and passes with the fix.
Claude-Session: https://claude.ai/code/session_01SjxUvZnyBdwtx4Y1jKAqt6
* chore(deps): bump agent-browser in /v3/@claude-flow/browser
Bumps [agent-browser](https://github.com/vercel-labs/agent-browser) from 0.27.0 to 0.37.1.
- [Release notes](https://github.com/vercel-labs/agent-browser/releases)
- [Changelog](https://github.com/vercel-labs/agent-browser/blob/main/CHANGELOG.md)
- [Commits](https://github.com/vercel-labs/agent-browser/compare/v0.27.0...v0.37.1)
---
updated-dependencies:
- dependency-name: agent-browser
dependency-version: 0.37.1
dependency-type: direct:production
update-type: version-update:semver-minor
...
Signed-off-by: dependabot[bot] <support@github.com>
* chore(deps): regenerate the v3 pnpm lockfile for agent-browser 0.37.1
Dependabot bumped v3/@claude-flow/browser/package.json and its npm
package-lock, but v3 is a pnpm workspace with its own lockfile. Every
frozen-lockfile job failed with ERR_PNPM_OUTDATED_LOCKFILE, which is what the
28 red checks on this PR were — not an agent-browser API break.
Co-Authored-By: RuFlo <ruv@ruv.net>
---------
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: ruv <ruv@ruv.net>
`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`
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.
`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>
`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>
loadEd25519() threw an error telling callers to set WITNESS_ED25519_ROOT
when @noble/ed25519 couldn't be found, but the function never read
process.env — the env var had no effect. Prepend it to the probe list
so the advertised escape hatch actually works.
Fixes#3200
Co-authored-by: rUv <ruv@ruv.net>
`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>
`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.
* feat(sona): default the learning mode from RUFLO_INTELLIGENCE_MODE
The SONA learning mode was only settable per call (`config.mode`), defaulting
to `balanced` otherwise. A deployment that wants every session to learn in a
specific profile — a managed desktop fleet running `research` for +55% quality,
or `edge` on constrained hosts — had no way to set that default short of
threading `mode` through every call site or patching a generated helper.
This reads `RUFLO_INTELLIGENCE_MODE` as the fleet-wide default in both the SONA
config merge (`@claude-flow/integration` sona-adapter) and the memory learning
bridge (`@claude-flow/memory`). Precedence is unchanged where a caller is
explicit: `config.mode` (or `sonaMode`) still wins; the env only fills the
former default slot; and an unset or unrecognised value returns undefined so
the code falls through to `balanced` — a typo can never silently select a
profile nobody asked for. Validated against the mode enum in each package.
Co-Authored-By: claude-flow <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01MUrJdDHhQ91hwpUBQhV4fC
* fix(sona): resolve sonaMode per-instance in LearningBridge, not at module load
learning-bridge.ts captured sonaModeFromEnv() into a module-scope
DEFAULT_CONFIG constant, evaluated once on first import — so any
RUFLO_INTELLIGENCE_MODE set later in the same process (including
test setup) was permanently missed. sona-adapter.ts's equivalent
(mergeConfig()) already re-reads the env var on every call; this
brings LearningBridge's constructor in line with that behavior,
preserving the same precedence (explicit config.sonaMode > env > default).
Adds regression tests for both packages (sona-adapter.ts had none
previously) and registers RUFLO_INTELLIGENCE_MODE in
KNOWN_ESCAPE_HATCHES per the audit script's existing requirement for
operator-knob env vars outside its SCAN_ROOTS.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01SjxUvZnyBdwtx4Y1jKAqt6
* 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
`getCompactContext` reported `tokensSaved` as the query string's length
minus the retrieved prompt's. The query is a search instruction, not the
context the compact prompt replaces, so the subtraction had no valid
baseline: a short query against a longer retrieved prompt reported 0 no
matter how much context the caller then dropped, and a long query against
a short prompt reported a saving with no replaced context behind it.
`getStats` turned the accumulated value into `estimatedMonthlySavings`,
in a module whose header states that no fabricated metrics are reported.
The baseline is the caller's to supply, because this method never sees
it. `options.baselineTokens` names the size of the context being
replaced; savings are measured against that and floored at 0. Without
it the call is reported as unmeasured -- `tokensSaved: null`, nothing
added to the total -- rather than as a saving of 0, so a caller summing
these cannot fold "no saving" and "no measurement" into one number.
`contextsMeasured` says how many calls the total was actually built
from, and the report renders it next to the total.
Co-authored-by: rUv <ruv@ruv.net>
resolveAutoMemoryDir mirrors Claude Code's project key, which replaces
`/`, `_` and `:` with dashes. The colon was missing, so a Windows git
root of D:\projects\elearning\v3_26 produced the key
D:-projects-elearning-v3-26 instead of D--projects-elearning-v3-26.
A colon is not legal inside a Windows path segment, so ensureMemoryDir()
failed with ENOENT and doSync() swallowed it as "Sync failed
(non-critical)": the auto memory sync had never run on Windows, and
reported success while doing nothing. It also wrote to a different key
than Claude Code reads, so even a successful write would have been
invisible.
POSIX paths carry no colon, so nothing changes there.
Co-authored-by: rUv <ruv@ruv.net>
* 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>
* 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>