The npx fallback in execBrowserCommand set shell: process.platform === 'win32'
so cmd.exe could resolve npx.cmd. Its safety comment assumed hard-coded
arguments, but fill values, eval scripts and selectors now flow through it, so
on Windows hosts without a global agent-browser those values were shell syntax.
Resolve the npm shims to the process behind them (native .exe or node <entry>,
and node <npm>/bin/npx-cli.js for the fallback) and spawn with an argv array.
.cmd and .bat targets are refused, bin paths that escape the package are
rejected, and an unresolvable launcher reports the install hint instead of
falling back to a shell. POSIX behaviour is unchanged.
Tests fail on the previous implementation; a static guard fails if a shell
option is reintroduced.
Co-Authored-By: RuFlo <ruv@ruv.net>
* dream(intelligence): #3394 fix inverted EMA direction in EWCConsolidator.updateFisherFromConfidences()
EWCConsolidator.updateFisherFromConfidences() (v3/@claude-flow/cli/src/memory/ewc-consolidation.ts),
the Fisher-matrix EMA update wired into production at intelligence.ts:413 after every SONA
distillLearning() pass, used globalFisher[i] = alpha*old + (1-alpha)*new with alpha=fisherDecayRate
(0.01) -- giving the new batch 99% weight and the accumulated Fisher signal only 1%, discarding
~99% of accumulated importance on every call. Inverted vs. the two sibling globalFisher-updating
methods in the same class (computeFisherMatrix(), recordGradient()), which correctly do
(1-decay)*old + decay*new. Confirmed against the standard online-EWC/EWC++ convention (Chaudhry
et al., ECCV 2018, arXiv:1801.10112).
Fixed to match the sibling sites. Added a discriminating regression test
(__tests__/ewc-fisher-ema-direction.test.ts): baseline-fails/candidate-passes verified via git
stash isolation, independently reproduced by an adversarial critic. Full @claude-flow/cli suite
byte-identical failure set both ways (96 pre-existing, unbuilt-dist class); 155/155 in EWC-adjacent
tests; tsc --noEmit identical (463 pre-existing errors, none in changed files).
Darwin skipped (binary correctness fix, no fitness gradient to search). No Flywheel state exists
in this repo; evidence retained as tests + issue + gist + stash-isolated proof, per every accepted
night since 2026-08-18.
See issue #3394 for the full evaluation receipt, adversarial critique, and witness stamp.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_0183FfWhMHJ2EjZb2MjxZfpJ
* dream(intelligence): #3394 update ledger with 2026-09-22 row + 09-15..09-21 backlog note
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_0183FfWhMHJ2EjZb2MjxZfpJ
* dream(intelligence): #3394 harden updateFisherFromConfidences() per review
Addresses ruvnet's REJECT review on #3395 (evidence-gate review at 1cc7231):
the EMA-direction fix itself was confirmed correct (retention 1.01e-8% ->
95.099% after 5 low-signal updates), but the function had no defenses
against malformed input or a corrupted persisted state file.
- updateFisherFromConfidences(): drop a sample whose embedding or
oldConf/newConf is non-finite (NaN/Infinity) instead of letting it poison
the shared globalFisher accumulator for every other pattern in the batch;
a batch where no sample contributes (all filtered out, or every delta was
zero) now leaves globalFisher and persisted state untouched instead of
decaying accumulated importance toward an empty no-op batch and writing
that no-op to disk.
- loadFromDisk(): validate the loaded globalFisher (exact dimensions, every
entry a finite non-negative number -- Fisher values are sums of squares
and can never legitimately be negative) and quarantine (reset to zero)
the whole array if invalid, rather than silently resuming with corrupted
entries (e.g. a non-finite value that round-tripped through JSON as
`null`).
- 3 new regression tests: non-finite input dropped without poisoning state,
no-op update doesn't persist, corrupted persisted state is quarantined
on load. All 3 independently confirmed to fail against the pre-hardening
code via git stash isolation.
158/158 EWC-adjacent tests passing (153 pre-existing + 5 EMA-direction +
3 new hardening); tsc --noEmit identical (463 pre-existing errors, none in
changed files).
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_0183FfWhMHJ2EjZb2MjxZfpJ
* dream(intelligence): #3394 rebind witness to the hardened candidate commit
Addresses the last item of ruvnet's REJECT review on #3395: the original
witness bound "session commit" to the pre-session base commit
(9c61c86, computed at STEP 0 before any diff existed), which didn't
actually bind the receipt to the candidate that was reviewed. Rebound to
290959f (the hardened candidate commit from the previous push) and
recomputed the gist SHA-256 + witness stamp against it.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_0183FfWhMHJ2EjZb2MjxZfpJ
* dream(intelligence): #3394 update ledger with post-review hardening outcome
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_0183FfWhMHJ2EjZb2MjxZfpJ
---------
Co-authored-by: Claude <noreply@anthropic.com>
* dream(intelligence): #3349 wire CLAUDE_FLOW_PRIOR_DECAY env override for ModelRouter's dormant decay primitive
ModelRouter's discounted-Thompson-sampling priorDecay (built/tested/
benchmarked in #3049) shipped permanently inert: DEFAULT_CONFIG.priorDecay
was hardcoded to 1 (disabled) with no env/config knob, unlike its sibling
maxUncertainty (envMaxUncertainty()). Adds envPriorDecay() mirroring that
exact pattern; default behavior is unchanged when the env var is unset.
Evaluation: stash-isolated discriminating test (1/3 new tests fails against
reverted source, 16/16 pass restored); full @claude-flow/cli suite and
tsc --noEmit both byte-identical baseline vs candidate outside the 3 new
tests; benchmark re-run reproduces the 2026-08-17 receipt exactly. Real
non-stationary recovery win in the 'low' bucket; a small but statistically
real stationary-accuracy cost in the 'med' bucket, accepted only under the
pre-existing ±1pp tolerance band from the original receipt — disclosed in
the issue/gist rather than oversold. Independent adversarial critic verdict:
CONFIRMED-WITH-CAVEATS.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_011tXcJWNao4vh57f4uFXutg
* docs(dream-cycle): append 2026-09-17 ledger row + backfill 09-13..09-16 gap/run verification
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_011tXcJWNao4vh57f4uFXutg
* fix(audit): register CLAUDE_FLOW_PRIOR_DECAY as a documented env-var escape hatch
scripts/audit-env-var-precedence.mjs (ADR-125/ADR-130) flagged the new
CLAUDE_FLOW_PRIOR_DECAY read in model-router.ts as undocumented CLI-flag
precedence. It's the same operator-knob shape as the adjacent, already-
registered CLAUDE_FLOW_MAX_UNCERTAINTY (envMaxUncertainty() is the pattern
envPriorDecay() mirrors) — no CLI invocation owns the router's persisted
lifetime, so there's no flag to wire precedence against. Registered
alongside it with the same justification.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_011tXcJWNao4vh57f4uFXutg
---------
Co-authored-by: Claude <noreply@anthropic.com>
* dream(security): #3384 add PATH/search-path family to validateEnv() denylist (evaluated, ACCEPT-scoped)
validateEnv()'s loader-hijack denylist blocked LD_PRELOAD/NODE_OPTIONS-class
vars but not PATH itself or the equivalent interpreter/VCS search-path
family (CWE-427) -- flagged grade-A by last night's security scan.
Adds PATH, PYTHONPATH, PERL5LIB, RUBYLIB, GIT_EXTERNAL_DIFF,
GIT_SSH_COMMAND, BASH_ENV, IFS to the denylist, closing the only
MCP-reachable exposure (terminal_create/terminal_execute). An independent
adversarial critic found the lookup was case-sensitive (path/Path bypass
it on case-insensitive Windows); fixed same session via .toUpperCase()
case-folding, which also hardens the original 9 names.
13 new discriminating tests (32/32 total), baseline-fails/candidate-passes
verified via git-stash isolation and independently reproduced twice by
the critic. Full suite failed-file set byte-identical to baseline (36
pre-existing environmental failures) -- zero new failures.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01Sq3BMM7SqC5dzEaQiogNyp
* docs(dream-cycle): update LEDGER.md with 2026-09-21 security row
Records tonight's PATH/search-path denylist fix, the new 2026-09-13/14
no-run gap (confirmed via git ls-remote), the 09-15..09-20 backlog
(confirmed real, not transcribed per established convention), and a
correction that search_pull_requests's merged field is stale/unreliable
(pull_request_read is authoritative).
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01Sq3BMM7SqC5dzEaQiogNyp
* fix(ci): build+overlay local @claude-flow/cli-core before running the test ratchet
PR #3385's own new tests (validate-input-env.test.ts) passed locally but
failed in CI's Test Suite job: package-lock.json resolves
@claude-flow/cli-core from the published npm registry tarball, not an
npm workspace link (unlike @claude-flow/security, which the previous
step in this same job already handles for the same reason). Since
scripts/ci-test-ratchet.mjs runs vitest from repo root,
v3/@claude-flow/cli's tests resolve @claude-flow/cli-core by walking up
to root node_modules -- the stale published dist/, never the local
source. Building the local package and overlaying its dist/ onto the
installed one (same version, so not a version bump) makes CI test the
actual PR diff instead of a stale registry snapshot, without touching
package-lock.json.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01Sq3BMM7SqC5dzEaQiogNyp
* dream(security): #3384 re-validate persisted session.env at execute time
Post-review fix on PR #3385: terminal_execute() trusted session.env from
the on-disk store unconditionally after terminal_create's one-time
validateEnv() call. A session persisted before a denylist update (or a
store.json edited/restored out of band) could carry a now-denylisted
env var (PATH, etc.) forever, silently bypassing tonight's fix -- and
the original 9-name denylist -- for every execute on that pre-existing
session.
terminal_execute now re-validates session.env via validateEnv() and
drops it to {} on failure rather than merging it unchecked, so a stale/
tampered session degrades to a clean environment instead of blocking.
2 new tests (stash-isolated: fails on the pre-fix handler, passes on
the fix); full package suite unaffected (same 36 pre-existing
environmental failures as before this commit).
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01Sq3BMM7SqC5dzEaQiogNyp
---------
Co-authored-by: Claude <noreply@anthropic.com>
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>
* 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>
* 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.
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
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
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.
`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