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.
The guard's first real CI run passed but reported:
NOTE: diff check NOT EXERCISED — could not diff against 'origin/main' (shallow clone?)
So only the range check ran; check 2 — the half that replays #3335/#3390 by
catching a leaf source change with no version bump — sat out entirely. The
NOT EXERCISED note is what made that visible instead of reading as a pass,
which is precisely why a skipped check must never print like a clean one.
Two causes, both fixed:
- `git fetch --depth=1 origin $GITHUB_BASE_REF` fetches the base tip with no
shared history, so `base...HEAD` dies with "fatal: no merge base". Now
fetches --depth=50 with an explicit
+refs/heads/<base>:refs/remotes/origin/<base> refspec.
- The script only attempted three-dot. It now falls back to two-dot, which
needs no common ancestor, and reports which mode actually ran.
Verified against the exact failing condition — an orphan branch with no merge
base against origin/main, where `git diff origin/main...HEAD` returns
"fatal: no merge base": the guard now reports "diff check ran (two-dot ...)"
rather than skipping. NC1 re-confirmed: a leaf source change without a version
bump still fails, now accompanied by "diff check ran (three-dot ...)" proving
the check executed rather than being skipped into a pass.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Adds scripts/audit-leaf-package-publish.mjs, wired into v3-ci.yml's existing
audit job (semver is already installed there).
Only four @claude-flow/* components are bundled into the release tarballs —
INTERNAL_RUNTIME_PACKAGES in stage-internal-runtime-bundles.mjs: security,
codex, mcp, plugin-agent-federation. cli-core, neural, shared and memory
resolve from the REGISTRY at whatever v3/@claude-flow/cli/package.json pins, so
a merged source change in one of those does NOT ship with the three-package
train: the release silently carries the last published copy.
This has bitten twice. #3334 fixed RUFLO_INTELLIGENCE_MODE in
@claude-flow/memory; v3.42.1 shipped the train only and a fresh consumer
install had zero references to the fix (#3335). #3390's reasoningBank
activation spanned cli/src/memory/memory-bridge.ts AND
memory/src/controller-registry.ts — publishing only the train would have
shipped the bridge half and left the embedder half unreachable, leaving
reasoningBank exactly as inert as before. It was caught by hand and
memory@3.0.0-alpha.25 went out alongside v3.42.5.
What makes it easy to miss is that CI goes GREEN: the leaf's own package tests
run against workspace source, so the change looks verified while being
unshippable.
The audit asserts:
1. every non-bundled leaf's workspace version is covered by the CLI's
declared range (a miss means the release resolves to OLDER code than
this repo's source);
2. diff mode — if a leaf's publishable source changed vs the base ref but
its version did not, fail with remediation.
It imports INTERNAL_RUNTIME_PACKAGES rather than restating it, so the bundled
and non-bundled sets cannot drift apart; exits non-zero if it inspects zero
leaves, so a broken classifier can't report clean; and reports a skipped diff
check as NOT EXERCISED rather than as a pass.
@claude-flow/shared is entered as a time-boxed accepted finding (expires
2026-10-21): the CLI pins 3.0.0-alpha.7 while the workspace is at
3.0.0-alpha.8, which IS published — stale, not unshippable. Raising the pin
edits v3/@claude-flow/cli deps and so forces a pnpm-lock.yaml regen in the same
change (#2540 -> #2552), which wants its own PR. An EXPIRED entry fails the
guard rather than muting it.
Negative-controlled, all four paths:
- memory source changed, no bump -> FAIL (replays #3390)
- same change with a version bump -> pass
- test-only change in a leaf -> pass (not publishable)
- waiver expiry backdated -> FAIL, "no longer honoured"
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
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>
The ratchet runs vitest with `--reporter=json --outputFile=…`, so nothing
vitest prints reaches the job log and the only record of an unexpected
failure is the file name. Recovering the assertion means downloading the
`test-results-ubuntu-latest` artifact — and a rerun replaces it, so after a
rerun attempt 1's assertion is gone for good.
The failure messages are already in the report this process parsed. Printing
them costs nothing, needs no new artifact, and survives a rerun, because job
logs are per-attempt.
`formatUnexpectedFailures()` is exported and pure so it unit-tests alongside
`evaluateTestReport()`. Every field it reads is optional by design: a
file-level abort ("No test suite found in file") carries `message` and no
assertions, and a report from another reporter version may carry neither. In
both cases the filename still prints, exactly as before, and the PASS path is
untouched.
Verified against a real failing run rather than a fixture: replaying run
35521170139's `vitest.json` through this script turns
+ v3/@claude-flow/cli/__tests__/memory-search-scores-3327.test.ts
into that same line plus
✗ memory_search score contract (#3327 Finding B) preserves standard fallback on import failure
AssertionError: expected [ { key: 'a', …(5) } ] to deeply equal [ { key: 'a', …(4) } ]
which is the line that would have identified the failure in #3208 without a
second run.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KTedGmPKpEdArVBMMn3JaP
bridgeGetEntry() consults a per-process TieredCache before the database,
and each process only invalidated that cache on its own writes. Several
MCP servers routinely share one store (Claude Code, Codex and Grok each
run `mcp start` against the same .swarm/), so once server B had read a
key, an update or delete made by server A never reached B: B kept
returning the old value (found: true) until its cache entry expired
(5-minute TTL by default, not extended by reads).
Before a cached read, check SQLite's PRAGMA data_version (prepared once
per handle), which changes only when a different connection has
committed to the file, and clear the cache when it moved. Own writes
don't trip it, so hits stay cheap (~1 us added).
Native better-sqlite3 handles only: agentdb's sql.js fallback works on a
private image that never sees other processes' commits, so there is
nothing to detect and it is skipped (isWasm / no inTransaction) rather
than probed. A handle that can't prepare the check is not probed again. A check that
cannot validate the store on one read clears the cache for that read,
leaves the baseline alone and is retried — both when it throws (e.g.
SQLITE_BUSY) and when it answers without a usable number, since neither
is evidence the store is unchanged. The check is fail-open toward the
caller: it can never break the read it guards.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KTedGmPKpEdArVBMMn3JaP
`embeddings init` skipped the ONNX download whenever the optional
`@claude-flow/embeddings` package was absent — which is every plain
`npm i -g ruflo`, since that package is not declared in the CLI's
package.json at all. It then slept 500ms faking progress, printed a dimmed
"(Skipped — …)" note on the spinner's tail, and fell through to the success
path: "Embedding subsystem initialized", a settings table asserting the model
and 384 dimensions, a `.claude-flow/embeddings.json` recording a `modelPath`
that contains no model, and exit 0.
This is the command `memory/embedding-policy.ts` points users at in its
`[no-stub]` error, so the documented repair for broken embeddings reported
success and changed nothing.
- A download that was requested and did not happen now ends in
`spinner.fail` + `output.printWarning` + `{ success: false, exitCode: 1 }`,
per the CLI command contract in docs/MCP_CLIENT_GUIDE.md. `--no-download`
still exits 0: no download was asked for.
- `embeddings.json` gains additive optional `modelDownloaded` and
`modelSkipReason` keys. Every pre-existing key keeps its name and meaning,
so older readers are unaffected.
- Both `setTimeout(r, 500)` fake-progress delays are gone. The second, in
`embeddings models --download`, also reported `success: true` for a skip;
it now fails the same way.
Scope is items 1-3 of the issue. The missing `status`/`download` subcommands
(item 4) are deliberately left alone.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KTedGmPKpEdArVBMMn3JaP
On a stock ruflo 3.42.4 install every metaharness_* MCP tool reached for the
npm registry at tool-call time, although the packages it needs are already on
disk. Two causes, in the same six helper files, which is why they ship
together: the helper PINS rejected what ruflo installs, and three code paths
never looked for an installed copy at all. Fixing only the pins leaves darwin
and the memory tools on npx; fixing only the lookups leaves them resolving a
pin that nothing on disk satisfies.
1. Pins (metaharness, @metaharness/darwin)
The metaharness_* tools resolve MetaHarness through the plugin helpers' own
tilde pins, not through package.json. Those pins were never bumped:
_harness.mjs stayed at ~0.3.0 after the CLI declared metaharness ^0.4.1
(b8ec03f34), and _darwin.mjs stayed at ~0.8.0 while the CLI moved
@metaharness/darwin to ~0.9.0 (#2958) and ~0.10.2 (#3262). On a stock install
(metaharness 0.4.2, darwin 0.10.2) findLocalPackageDir() therefore rejected
the bundled metaharness, and every score / genome / mcp_scan / threat_model /
oia_audit / learn call ran
`npm install --prefix ~/.ruflo/metaharness-cache-0.3.0 metaharness@~0.3.0`
at tool-call time — a download of the older 0.3.2 (180 s install budget inside
a 120 s MCP subprocess budget), degraded offline. The darwin tools fetched
darwin 0.8.x through npx while gepa imported the bundled 0.10.2.
- _harness.mjs: METAHARNESS_PIN_VERSION ~0.3.0 -> ~0.4.1 (= CLI ^0.4.1)
- _darwin.mjs: DARWIN_PIN_VERSION ~0.8.0 -> ~0.10.2 (= CLI ~0.10.2)
- scripts/check-metaharness-pins.mjs: the watcher compared only the CLI's
declared ranges (and MH_DARWIN_PIN), so it reported "all current" while the
pins that decide what runs were two minors behind. It now reads each
helper's *_PIN_VERSION: the pin must be a `~X.Y.Z` range (the only form
_invoke.satisfiesTildeRange accepts), and must cover the declared range, or
admit npm latest when the CLI declares nothing (redblue). An unreadable
constant is fatal. `satisfies` now shares a `bounds()` helper with the new
`covers()`; the results for the existing rows are unchanged.
- metaharness-pin-drift.yml also triggers on the three helper files.
- The two current-pin comments in TypeScript (distill-oracle.ts MH_DARWIN_PIN,
metaharness-tools.ts ADR-153 header) named the old ~0.8.0 plugin pin; they
now name ~0.10.2. Comments only, no behaviour.
2. No npm/npx at tool-call time (darwin, redblue, memory)
- _darwin.mjs ran `npx -y -p @metaharness/darwin@<pin> metaharness-darwin` on
every evolve / bench / security_bench call: npm resolved the range each
time, it ignored the optionalDependency the CLI ships, and it could run a
different darwin than the gepa import in the same plugin. It now resolves
like _harness.mjs — installed copy satisfying the pin, then the one-time
versioned darwin-cache-<pin> that gepa already shares, then
`process.execPath <abs bin>` with shell:false.
- _redblue.mjs always npm-installed into redblue-cache-<pin> on first use,
never looking at the installed copy (ruflo 3.42.4 carries 0.1.4). It now
checks the installed copy first. The chosen CLI path is realpath'd, because
redblue only dispatches when import.meta.url === file://argv[1]; a
pnpm-symlinked package dir (or a cache base under /tmp on macOS) otherwise
makes it exit 0 having done nothing. Its spawn moves to process.execPath
with shell:false: the argv carries MCP-supplied --config/--out/--in, which
under the previous `shell: win32` went through cmd.exe unquoted.
- audit-list / audit-trend / oia-audit / similarity ran
`npx @claude-flow/cli@latest memory ...` — an npm-registry resolution per
call (the check _harness.mjs already removed for its own npx path), and
possibly a different CLI version than the server that spawned the tool
(#3306; cold-cache npx cost #3145/#3154). Without registry access oia_audit
reported persisted:false and audit_list silently showed 0 records. They now
call _invoke.runRufloCli(): process.execPath + bin/cli.js of the
@claude-flow/cli that ships the plugin (<cli>/plugins/ruflo-metaharness, or
v3/@claude-flow/cli in a checkout). A candidate needs dist/src/index.js next
to bin/cli.js (mcp-launch.cjs's unbuilt-checkout guard) plus a package.json
named @claude-flow/cli (a new check, so an unrelated parent directory can
never qualify). CLI_CORE=1 still opts into `npx @claude-flow/cli-core@alpha`,
and a layout with no usable local CLI still falls back to
`npx @claude-flow/cli@latest`.
- drift-from-history.mjs: drop its unused CLI_PKG constant.
The two new lookups end in a spawn of a package bin with MCP-supplied argv, so
they pass findLocalPackageDir(..., { fromCwd: false }) and search only the
ruflo install that owns the plugin — never the tool's cwd or its ancestors.
The pre-existing metaharness lookup keeps its cwd walk unchanged.
Tests (both hermetic, published layout, stub packages, npm/npx PATH trap):
- test-pin-alignment.mjs (+ smoke 17z74a): 3 passed / 9 failed on main,
12 / 0 here.
- test-no-tool-time-npx.mjs (+ smoke 17r2): 7 passed / 19 failed on main,
26 / 0 here. It covers both darwin success branches (installed copy and the
versioned cache), the memory round trip through the shipping CLI, the kept
contracts (CLI_CORE, npx fallback, a bin/cli.js that is not
@claude-flow/cli, darwin absent -> degraded exit 0), and the hardening
above: a darwin/redblue in the tool's own cwd node_modules is never
executed, a cache dir with package.json but no bin gets one reinstall
instead of degrading forever, and neither helper spawns the resolved bin
through a shell.
ADR-150 is unchanged: no static @metaharness import is added, no new
dependency, and every unresolvable path still returns the same
{degraded:true, reason} with exit 0.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KTedGmPKpEdArVBMMn3JaP
Review round 2 (@ruvnet on #3365). The first round kept a one-way "has served
stdio" flag so a second stop() could not delete another server's record. That
flag outlived the server it described: after start -> stop, an independent
status query still reported the manager running and checkHealth() still
reported it healthy. On upstream e558f0c0f the same replay reported
{"running":true,...} and {"healthy":false,"error":"No PID file found"} — the
status half is the pre-existing #2934 fallback, the health half was ours.
The flag is now the manager's live lifecycle ('idle' | 'running' | 'stopped'):
- while it is serving stdio the manager IS the server, so it reports itself
and never reads or clears the record it deliberately never wrote (the 30s
health monitor calls checkHealth());
- once stopped it reports running: false and healthy: false rather than
whatever PID the shared file happens to hold;
- 'idle' — a manager that never started, which is what `mcp status`,
`mcp health` and `mcp stop` build — keeps today's behaviour exactly,
including the #2934 stdio fallback.
stop() no longer needs a sticky flag: a stopped manager reports not running,
so a second stop() returns at its own guard.
The PID record now carries durable instance identity, the same model #3363
reached for the policy lock: host, platform, Linux PID namespace and kernel
boot id, and the owner's process start time (/proc/<pid>/stat field 22 on
Linux, `ps -o lstart=` elsewhere). A recorded PID is believed only while all
of it still matches, so a PID the OS has since handed to another process, or
one from another boot, host or namespace, is no longer treated as a live
server — it can no longer make an http start refuse, or be SIGKILLed by
`mcp start --force`. A server retracts its record only while the file still
holds, byte for byte, what it wrote.
Format compatibility: line 1 is still the bare PID, so an older ruflo's
parseInt and `head -1` both read it unchanged; line 2 is the identity. A
bare-integer record — an older ruflo's, or `start-mcp.sh --daemon`'s — parses
with no identity and behaves exactly as today. v3/scripts/start-mcp.sh now
reads the first line.
Not covered: PID reuse and boot detection need the identity line, so a record
written by an older ruflo keeps today's exposure; Windows has neither /proc
nor ps, so its records carry no start time and PID reuse stays unqualified
there, as isProcessRunning()'s process-name check already is.
Tests: 13 added (20 total in the file), covering start -> stop -> independent
status/health denial, concurrent ownership, PID reuse and non-owned processes,
and the Windows-shaped inputs. All 13 fail on 85c68888e except the two
labelled as pinning existing behaviour.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KTedGmPKpEdArVBMMn3JaP
`mcp start` on the stdio transport force-"restarted" whatever server was
recorded in the shared PID file — a single slot per os.tmpdir() (per user
on macOS/Windows; the machine-wide /tmp on Linux unless TMPDIR is set).
It sent SIGKILL to that PID, because a stdio server "can't be health-
checked". The victim was simply the last server started through the
command parser: another terminal's stdio server, or a live http/websocket
server that other clients were using. For the same reason, a terminal
stdio server made a later `mcp start -t http` refuse with "MCP Server
already running".
A stdio server is owned by the client that spawned it, over its own
pipes, and any number can run side by side. Only a port-bound transport
is single-instance. ADR-071 made this singleton safe against
self-detection and PID reuse; a stdio server has no business claiming or
killing the shared slot at all. So:
- commands/mcp.ts: a stdio start kills a recorded server only on an
explicit --force; http/websocket keep their guard unchanged.
- MCPServerManager: a stdio server no longer refuses to start over the
PID file, writes it, removes it on stop(), or health-checks it. While
it serves stdio, getStatus() and checkHealth() report the process
itself rather than whatever PID is recorded. A stale record is still
cleaned up by the pre-start status read, as before.
The documented piped-stdin `mcp start` (how MCP clients launch it) is
answered by bin/cli.js's inline fast path, which never touches the PID
file. A piped start whose argv does not begin with `mcp` (a leading
global flag) does reach the parser, and is covered too, because the fix
keys on the transport rather than on the TTY.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KTedGmPKpEdArVBMMn3JaP
acquireLock() records {pid, acquiredAt} in .claude-flow/policy/state.lock
but only ever reclaimed a lock by mtime age (LOCK_STALE_MS = 30 s). Every
MCP tool call, reads included, passes through authorizeMcpTool() ->
withPolicyTransaction() -> acquireLock(). When a server is killed inside a
transaction (SIGKILL, OOM, or a default-action SIGTERM: the bin/cli.js
stdio loop installs no handler), its finally block never releases the
lock, so each call on a fresh server waited LOCK_WAIT_MS and failed with
policy-state-lock-timeout until the orphan aged past 30 s: five 5 s
failures after every such crash.
Reclaim the lock at once when its owner is provably gone:
- The lock now also records host, platform and, on Linux, PID namespace
and kernel boot id. The pid is trusted only when every field matches
the reader's, because a sandboxed CLI (bwrap --unshare-pid), a
container, another kernel boot or another machine sees ESRCH for a live
owner. host alone is not an identity: two machines sharing a directory
can report the same hostname, and every Linux init PID namespace has
the same inode (PROC_PID_INIT_INO).
- Only ESRCH counts as dead (EPERM and any other error mean alive), and
the pid must be a number, an integer, and in 1..2^31-1 (process.kill
coerces a numeric string).
- The lock is read only if it is a small regular file (lstat, then
O_NOFOLLOW|O_NONBLOCK, fstat, at most 1 KiB), so a symlinked FIFO or
device cannot block the event loop.
- After the probe the lock is re-read and must be byte for byte the one
that was read, so a lock that changed hands during the probe is not
deleted. Comparing dev/ino/ctime instead is unsound on Linux: ext4
reuses a freed inode number at once, and before kernel 6.13 two files
created in one clock tick share a ctime. Replaying the handover on a
non-multigrain ext3 mount, the stat triple deleted the live new owner's
lock in 192 of 200 runs; the byte comparison in 0 of 200.
Every other lock, including one written by an older version, keeps the
30 s mtime rule. ADR-324's lock paragraph is updated to match.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KTedGmPKpEdArVBMMn3JaP
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.