Commit Graph
222 Commits
Author SHA1 Message Date
e0ad134ce5 fix(memory): persist HNSW metadata atomically and report failures (#5001)
Co-authored-by: wasabihu <973168+wasabihu@users.noreply.github.com>
Co-authored-by: rUv <ruv@ruv.net>
2026-11-17 11:19:50 -05:00
rUvandr 8971ebad35 fix(memory): apply configured embedding model and dimension to AgentDB (#4984) (#4985)
* fix(memory): apply configured embedding model and dimension to AgentDB (#4984)

The registry created AgentDB with only { dbPath }, so memory_store and
memory_search kept using AgentDB's hardcoded MiniLM/384 embedder whatever
.claude-flow/embeddings.json said.

- registry: forward config.dimension as vectorDimension; install a supplied
  embeddingGenerator in place on agentdb.embedder (awaited in init) and reject
  vectors whose length differs from config.dimension
- cli bridge: pass a local-chain generator (real ONNX only, no bridge
  re-entry) when the effective model is not the default
- cli bridge: label rows by the embedder that produced the vector instead of
  inferring the model from vector length

Needs a standalone @claude-flow/memory publish to reach users.

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

* chore(memory): release @claude-flow/memory 3.3.3 and pin it in the CLI (#4984)

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

---------

Co-authored-by: r <r@x>
2026-11-13 15:34:37 -05:00
randRuFlo ac36136d02 feat(router): opt-in nearest-centroid agent router (ADR-527)
CLAUDE_FLOW_ROUTER_CENTROID=1 routes hooks_route tasks to the nearest MiniLM
centroid of the ADR-391 corpus dev split. Held-out test: 63.7% vs 25.7% for
the current default, falling back on 1.8% of prompts. Off by default: p95
latency fails the ADR-391 gate.

- Centroids are versioned with the embedder (embedder, model, dim); a query
  embedded any other way is refused and the current router decides.
- Near-ties (top-two margin < 0.005) keep the current router's pick.
- Every flagged response carries centroid.baselineAgent for pilot comparison.
- The local embedder now records which model produced a vector (modelId).
- ruv-fann routing deferred: training never beat the centroid on dev CV.

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-11-10 14:56:24 -05:00
rUv a3a38378af Merge pull request #4853 from NotZhu/fix/4734-readonly-getentry
fix(memory): make getEntry a read-only path, drop whole-image write (#4734)
2026-11-10 00:16:01 -05:00
rUv 8976d98ad7 Merge pull request #4928 from ruvnet/fix/2633-project-root-anchor
fix(cli,cli-core): anchor durable state to the project root, not raw cwd (#2633)
2026-11-09 18:59:21 -05:00
randRuFlo c9b87db61d fix(cli,cli-core): anchor durable state to the project root, not raw cwd (#2633)
Under an agent the Bash tool cwd is sticky, and MCP servers and hooks inherit
it, so process.cwd() is often a subdirectory of the project. Memory, autopilot,
neural and metrics state keyed to it was written under the subdirectory and
never read again: loadState() returned defaults and the learning state
silently started over.

- Extract the #2877 daemon marker walk (nearest Ruflo marker, `.git` hard
  stop, start dir when nothing matches, read-only) into
  cli/src/services/project-root.ts; resolveDaemonProjectRoot and
  isRufloProject delegate to it unchanged.
- getProjectRoot()/anchorToProjectRoot() add the home/filesystem-root guard
  cli-core already applies, so a ~/.claude/settings.json claudeFlow key never
  makes $HOME the project.
- getMemoryRoot(), `memory backup` and `memory distill` resolve memory
  against the project root.
- autopilot-state resolves its state, log, swarm-tasks and checklist paths
  against the project root per call (exported constants stay relative).
- neural checkpoints/patterns, `.claude-flow/memory` patterns, LoRA weights,
  EWC fisher and swarm-activity metrics use the project root.
- cli-core: export isRufloProject/resolveProjectRoot from mcp-tools/types;
  getProjectCwd() keeps CLAUDE_FLOW_CWD precedence, else walks up from
  process.cwd(), falling back to process.cwd() when no marker is found or
  the walk lands on home / a filesystem root. Bump cli-core to 3.7.7.

The CLI pins cli-core 3.7.6, which lacks these exports, so the CLI carries a
copy of the walk; a parity test pins both copies together.

Fixes #2633

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-11-09 18:01:12 -05:00
r 7e9e263ea6 Merge main (incl. #4926) into the memory 3.3.0 branch
Co-Authored-By: RuFlo <ruv@ruv.net>

# Conflicts:
#	v3/@claude-flow/cli/package.json
#	v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.ts
#	v3/@claude-flow/cli/src/memory/memory-bridge.ts
2026-11-09 17:45:58 -05:00
rUv 65db110751 Merge pull request #4926 from ruvnet/feat/4707-agentdb-inventory-tools
feat(cli): read-only AgentDB pattern/skill inventory MCP tools (#4707)
2026-11-09 17:44:41 -05:00
rUv 6f44e533bd Merge pull request #4919 from ruvnet/fix/2305-embedding-config
fix(cli): memory path honours .claude-flow/embeddings.json (#2305)
2026-11-09 17:44:33 -05:00
randRuFlo 7047eedb1b Merge main into the memory 3.3.0 branch
Co-Authored-By: RuFlo <ruv@ruv.net>
2026-11-09 16:42:18 -05:00
randRuFlo 4f4920b6d4 feat(cli): read-only AgentDB pattern/skill inventory MCP tools (#4707)
Adds agentdb_pattern-list (ReasoningBank.listPatterns), agentdb_skill-list
(SkillLibrary.listSkills), agentdb_skill-get (SkillLibrary.getSkill) and the
count-only agentdb_hierarchical-stats (TieredMemoryStore.getTierStats +
countPersisted). They read through the existing memory-bridge registry under
the bridge operation lease. A missing controller or method returns
success:false, code:'unsupported' naming the method, never an empty list;
native errors (page validation, graph-adapter refusal) keep their own code.

Fixes #4707

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-11-09 15:17:48 -05:00
rUv 8d7866a9bb Merge pull request #4916 from ruvnet/fix/4714-pattern-search-zero-match
fix(cli): report a healthy pattern-search zero-match as a no-match, not degraded (#4714)
2026-11-09 14:38:19 -05:00
randRuFlo 105033d1f2 feat(memory,cli): persisted inventory + exact-ID reads for TieredMemoryStore (#4712)
TieredMemoryStore exposed store/recall/remove/count but no way to enumerate
what is persisted or read an entry back by id. recall() scores the hydrated
maps, which cap each tier and the archive at 5,000 rows and collapse same-key
rows, so the in-memory view cannot establish the persisted population.

@claude-flow/memory 3.3.0:
- TieredMemoryStore.listEntries({ tier, status = 'active', limit = 100, cursor })
  reads the tiered_memory table with keyset pagination on ts DESC, id DESC.
  status is active | expired | superseded | archived | all, derived by one
  function with fixed precedence (superseded > archived > expired > active;
  not-yet-valid rows count as expired, matching recall's includeExpired).
  limit is clamped to 1..1000. The cursor is base64url JSON bound to the
  tier/status filter; altered, malformed or foreign cursors throw
  TieredMemoryCursorError. totalEstimate is an exact COUNT for all /
  superseded / archived and omitted for the temporal filters.
- TieredMemoryStore.getEntry(id, { includeInactive = false }) is an exact
  stable-id read returning the entry plus its status, or null.
- Both throw TieredMemoryUnsupportedError ("unsupported: volatile store") on a
  store without a SQLite handle, never write, and let SQL errors propagate.
- Logic lives in tiered-memory-inventory.ts with injected decode/isValid, so
  there is no runtime import cycle.

CLI: read-only MCP tools agentdb_hierarchical-list and agentdb_hierarchical-get,
appended at the end of agentdbTools from a new module. Bridge helpers are
appended to memory-bridge.ts and run inside one bridge operation; they refuse
with a reason on a native agentdb controller, an older @claude-flow/memory
without the API, a volatile store, or a read failure.

Fixes #4712

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-11-09 12:44:17 -05:00
randRuFlo 02e5341fe7 fix(cli): memory path honours .claude-flow/embeddings.json (#2305)
`embeddings init` writes { model, dimension } to .claude-flow/embeddings.json,
but memory init, the AgentDB bridge and the router task embedder all
hardcoded Xenova/all-MiniLM-L6-v2 / 384.

Add src/memory/embedding-config.ts: resolveEmbeddingConfig(root) reads that
file (same schema commands/embeddings.ts writes; bare model names get the
Xenova/ namespace), falls back to MiniLM/384, and warns once on malformed
JSON. resolveEffectiveEmbeddingConfig() additionally checks memory.db and
agentdb-memory.db: if either already holds real vectors of another
dimension, that recorded dimension is kept with one warning; nothing is
mixed or rebuilt. Resolutions are cached per root.

Used by loadLocalEmbeddingChain, fresh vector_indexes seeds, the bridge's
registry init / embedding labels / dimension stub check, and task-embedder.

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-11-09 12:11:08 -05:00
randRuFlo 1664b0c887 fix(cli): report a healthy pattern-search zero-match as a no-match, not degraded (#4714)
agentdb_pattern-search only treated a ReasoningBank result as success when
it had hits. A healthy empty result fell through to the legacy
pattern-namespace fallback and came back degraded:true with
reason "reasoningBank-empty:reasoningBank", so callers that honour
`degraded` stopped although every read completed.

- bridgeSearchPatterns now reports read failures in-band (`error`):
  a throwing controller, a non-array controller result, and a failing
  reasoning_patterns substring scan. These used to become [] or null.
- The handler returns {results: [], noMatch: true, degraded: false,
  controller: 'reasoningBank', searched: [...]} only when ReasoningBank ran
  without error AND the legacy semantic, list and hydrate reads all
  succeeded with nothing found. scanLimited is set when the namespace
  holds more than the 200 entries the substring scan reads.
- A ReasoningBank error stays degraded with reason reasoningBank-error:<msg>.
  Legacy list/hydrate failures are now surfaced as listError.
- Legacy hits after an empty ReasoningBank keep the existing labelling;
  ReasoningBank hits are returned unchanged.

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-11-09 12:05:35 -05:00
randRuFlo c05262236b fix(cli): report failed pattern persistence instead of claiming success (#4880)
LocalReasoningBank.flushToDisk() caught write errors such as ENOSPC, logged
them and left the bank dirty, but returned void, so recordTrajectory() still
returned true for patterns that only existed in memory.

- flushToDisk() now returns a boolean: true when persisted or nothing to
  write, false when the write failed (state stays dirty). It still never
  throws, so the debounce timer path is unchanged. The lock/merge/temp-file
  + rename algorithm is untouched.
- The last flush error and attempt time are recorded and exposed read-only
  through getFlushState() and getPersistenceStatus() (dirty, lastFlushError,
  lastFlushAt). A successful flush clears the error.
- recordTrajectory() and flushPatterns() return the flush result.

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-11-09 10:32:54 -05:00
ruvanddskarasev 238ce5b32a fix(memory): migrate CLI-created memory_entries in SQLiteBackend; memory_store metadata (#1426)
Re-applies dskarasev's #1426 on current main.

SQLiteBackend: a memory.db created by the CLI's memory-initializer DDL has no
access_level, version or "references" column. CREATE TABLE IF NOT EXISTS left
that table alone, so every store() failed with "table memory_entries has no
column named access_level". initialize() now adds the missing columns (and
access_count / last_accessed_at for older DDLs) with createDefaultEntry()
defaults.

memory_store: accepts an optional `metadata` object and persists it on both
write paths (AgentDB bridge and sql.js fallback), which both hard-coded '{}'.
Arrays, null and scalars are rejected at the MCP boundary.

Tests: sqlite-backend-legacy-schema.test.ts (fails on main with the
no-such-column error) and memory-store-metadata-1426.test.ts (sql.js path,
bridge path, input check; 6 of 7 fail on main).

Co-Authored-By: dskarasev <dskarasev@users.noreply.github.com>
Co-Authored-By: claude-flow <ruv@ruv.net>
2026-11-08 20:21:18 -05:00
NotZhu 151ee0b4d6 fix(memory): make getEntry a read-only path, drop whole-image write (#4734)
The sql.js fallback getEntry bumped access_count and then exported/rewrote the
whole database image on every read. That turned each get into a full-image write
held under the exclusive memory.db lock, so concurrent readers contended with
real writers and could fail to acquire the lock. A get now just reads the
snapshot (matching listEntries/searchEntries), and accessCount is reported as
stored+1 for display only. The native WAL-sidecar guard is kept.
2026-11-06 20:05:16 +08:00
r ff187f8402 Merge PR #4819 2026-11-05 09:54:32 -05:00
马建彤 2436139903 fix(intelligence): merge patterns.json under the writer lock
LocalReasoningBank.flushToDisk() wrote its whole in-memory list. A long-lived daemon/MCP process therefore erased patterns added by hooks or another process, and a corrupt patterns.json was silently replaced with an empty bank on the next flush (#4735).\n\nRe-read patterns.json under withStatsFileLock, merge only locally dirty IDs, carry deleted IDs as tombstones (and clear() as a full reset), then write temp+rename. Corrupt files are renamed aside and preserved before any replacement. Pattern store/update/eviction/delete/clear track dirty/tombstone state.\n\nThree regressions cover cross-process additions, no resurrection of a local delete, and corrupt-file preservation; all fail on baseline and pass on candidate. Existing confidence/dedup/flush tests pass; tsc reports no errors in the changed source. The #4217 stats barrier timeout reproduces identically on baseline (local Windows spawn issue).
2026-11-05 14:18:42 +08:00
ZYZ666-RGBandyuzhou 130bb1f269 fix(embeddings): honour normalize:false in embeddings_generate
embeddings_generate accepted normalize and then ignored it, so every
vector came back L2-normalized. Pass the flag through to the local
embedding chain: false returns the pre-L2 vector, and the default stays
unit length.

Addresses #4724

Co-authored-by: yuzhou <1991039819@qq.com>
2026-11-05 02:03:24 +00:00
ordinary being ad7e9e5416 fix(memory): page list row identities before loading payloads (#4687)
bridgeListEntries() and the sql.js listEntries() fallback selected full content and embedding columns before ORDER BY updated_at DESC LIMIT/OFFSET, so metadata-only pages sorted large payloads that were then discarded (#4686).\n\nUse a rowid subquery to order/limit row identities first, then fetch the page's payload columns. The original full-row query remains as a fallback for legacy WITHOUT ROWID tables. Filters (status/TTL/namespace/provenance/tags), total count, embedding cap, page membership, order and returned fields are unchanged.\n\nAdds a sql.js fixture test for descending offset pages, full content, total and limit 0. Existing sql.js list/provenance/tag and ADR-472 embedding tests pass 12/12 locally; tsc reports only the pre-existing missing workspace packages.
2026-11-04 09:05:02 -06:00
rUvandr bbd057eb17 fix(memory): find stored patterns when agentdb serves mock embeddings (#4643) (#4681)
agentdb_pattern-store writes through ReasoningBank.storePattern(), but when
agentdb's Transformers.js model fails to load (offline, failed sharp install,
or a loaded CI runner) it serves hash-based mock embeddings. A passage and a
query then embed to unrelated vectors, so searchPatterns() returned [] for a
pattern that was just stored. This is the full-suite #2226 failure that has
kept the CI ratchet red since the move to agentdb 3.2.

- bridgeSearchPatterns: when the agentdb vector search returns nothing, scan
  the same reasoning_patterns table for the query text, matching what the
  LocalReasoningBank branch already does over getAll().
- rescueAgentdbEmbedder: agentdb 3.x's ReasoningBank calls embedQuery() /
  embedPassage(), which bypass embed(). Patch the role methods too and clear
  the cached mock vectors, so a host with ONNX actually gets real vectors.
- Regression test forces AGENTDB_DISABLE_TRANSFORMERS=1 and requires the
  round-trip to hit; it fails without the fix.

Co-authored-by: r <r@x>
2026-11-04 01:57:56 -06:00
ordinary being 762fbf74c2 fix(memory): expose AgentDB init failures in health (#4667)
agentdb_health could return available:true with controllers while AgentDB itself had failed to open (for example because the daemon or another MCP server owned the RuVector store). The only trace was the separate isBridgeAvailable() check; the health payload had no init error or lock hint (#4654).\n\nbridgeHealthCheck now reads the registry's getAgentDBInitError(), reports available:false, includes agentdbInitError and the recorded bridgeFailureReason, and adds an actionable hint when the cause is an already-open/locked native store. Older registries without the record are unchanged.\n\nRegression extends the #4622 fake registry with listControllers and covers failed and healthy health payloads. Baseline returns available:true and no error for the failure case; candidate 5/5 with the Windows bridge opt-in, existing 3 tests unchanged.
2026-11-04 01:01:20 -06:00
rUv 3c30ee3fa3 feat(agentdb): episode CRUD over agentdb 3.3 (ADR-520) + release 3.69.0 (#4642)
* feat(agentdb): episode get/list/update/delete over agentdb 3.3 (ADR-520)

agentdb_episode-get, -list, -update and -delete reach agentdb 3.3's
ReflexionMemory through one new bridge helper (withReflexionController),
so a verified session can be marked success with a critique in place,
keeping its id, and recall re-ranks it. Strict integer ids; pre-3.3
builds get a clear error (delete is gated so the old parseInt-ing
deleteEpisode is never used).

agentdb ^3.3.0 in root and CLI, ruflo override >=3.3.0, both lockfiles;
marketplace agentdb plugin -> plugin-v3.3.0.

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

* fix(agentdb): ADR-112 use-when guidance on episode CRUD tool descriptions

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

* chore(release): 3.69.0

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-11-01 12:52:22 -05:00
rUvandr 73b20daf6e fix(cli): session-end consolidation, session snapshot IDs, Fisher decay env (#4638)
* fix(cli): session-end consolidation, snapshot IDs, Fisher decay env, read-path regression test

- #3908: bridgeSessionEnd probed only `nightlyLearner.consolidate`, which
  neither the MemoryConsolidator wrapper nor AgentDB's NightlyLearner has.
  Feature-detect consolidate -> run -> runAll, bounded (10s) and non-fatal.
- #4404: session_save keyed snapshot rows by a bare `namespace::key`, so
  tuples containing `::` collided (one dropped on save, a distinct sibling
  row skipped as a mirror). Percent-escape `%` and `:` per component;
  ordinary IDs are unchanged and restore reads the explicit fields.
- #3475: CLAUDE_FLOW_FISHER_DECAY overrides the default Fisher EMA decay;
  only a finite number in (0, 1] is honoured, constructor config still wins.
- #4570: the sql.js read paths no longer rewrite memory.db on main (fixed by
  #3918's ensureSchemaColumns change); add a regression test asserting
  inode/mtime/ctime/size are unchanged across searchEntries, listEntries,
  memory_search, memory_list and memory_search_unified.

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

* test(cli): drop #4570 regression test (issue closed separately as fixed by #3918)

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

---------

Co-authored-by: r <r@x>
2026-11-01 12:17:55 -05:00
rUvandr 2b1a392747 feat(memory): session episodes through agentdb 3.2 hybrid retrieval; release 3.68.0 (ADR-519) (#4632)
- Session end stores the summary as a ReflexionMemory episode (neutral reward,
  unverified). The bridge called startEpisode/endEpisode, which ReflexionMemory
  never had, so no session episode was ever written.
- New agentdb_episode-recall MCP tool: retrieveRelevant with agentdb 3.2's
  keyword + vector fusion by default, opt-in cross-encoder rerank.
- agentdb_session-start takes recall/k/hybrid/rerank and returns episodes.
- A failing secondary write no longer discards a stored or recalled episode.
- agentdb ^3.2.0 in cli and claude-flow, >=3.2.0 in the ruflo override.
- scripts/smoke-episode-recall.mjs runs the round trip on real agentdb.

Co-authored-by: r <r@x>
2026-11-01 00:33:07 -04:00
rUvandr 49adc540a0 fix(memory): report the original AgentDB open failure; memory_list reports failed queries (#4622); release 3.66.1 (#4623)
- ControllerRegistry keeps the first backend failure AgentDB logs (e.g. a
  native vector store locked by another process) instead of only the last
  fallback's format rejection, exposed as getAgentDBInitError(), with the
  single-owner HTTP remedy. @claude-flow/memory 3.2.0.
- The CLI bridge records that reason, so the sql.js fallback's refusal names
  it, and isBridgeAvailable() is false when AgentDB did not open.
- memory_list returns success:false with the error on a failed query instead
  of an empty inventory.
- Release 3.66.1 with plugin-agent-federation 1.0.4 (#4619 trust thresholds).

Co-authored-by: r <r@x>
2026-10-31 11:17:37 -04:00
rUvandr 243bc57f0b feat(learning): lessons say where the fix goes; reworded tasks learn together (ADR-511) (#4603)
* feat(learning): lessons say where the fix goes; reworded tasks learn together (ADR-511)

The §7 evaluation (#4581) showed three limits on what the verified-outcome
loop can learn:

- a lesson named an agent, nothing the model can act on;
- tasks naming different files merged into one lesson;
- the same task worded differently never learned (15 reworded verified
  successes left 15 patterns at one success each, zero lessons).

Changes:
- mods: a verified turn records its screened edited source files; a lesson
  names the three its passing fixes edited most and leads with them; pick()
  weighs rare keywords (IDF) and drops matches far below the best.
  ruflo-mods 0.13.0.
- cli: files are counted per pattern (successes only) into learned-lessons.json;
  SONA takes them as pattern anchors (never keywords), so reworded tasks that
  fixed the same file reinforce one pattern; tasks naming disjoint paths never
  merge. Lesson building moves to verified-lessons.ts.
- eval: the harness gains --ablate, --test-index, --concurrency, --lessons,
  --save-lessons, --eval-sample, --calibrate and --max-turns;
  scripts/eval-learning-loop-corpus.mjs writes a validated 15+30-task corpus.

Proved offline (tests): 15 reworded prompts form 5 lessons, up from 0; the
first run's prompts form 5 lessons, up from 1; the right lesson ranks first
for 30 of 30 eval prompts, with 1.07 lessons shown per prompt.

Paid pilots (haiku, about $6.80) are directional and did not reach the gate:
- 8-turn cap: off 2/10, on 4/10, lessons without files 1/10;
- uncapped: 6/6 vs 6/6, cost within 1%.
ADR-511 §5 has the details.

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

* docs(adr): ADR-511 cites PR #4603

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

---------

Co-authored-by: r <r@x>
2026-10-30 12:12:42 -04:00
rUvandr 38112e0042 feat(mods): learning-loop gaming defences — taints, re-verify, anomaly gate (ADR-503) (#4590)
* feat(learning-loop): gaming defences for verified outcomes (ADR-503)

The verified-outcome loop (ADR-502) trusts a verifier's exit status, but the
model chooses what that verifier checks. Four downgrade-only layers:

- mod: a verified-success record carries taints when the turn edited a test
  file (edited-tests), a verifier config (edited-verifier-config), or decided
  on a weakened/narrowed command (narrowed-verifier); a per-process session
  token is written on every record. The outcome word never changes.
- CLI: a success with a taint not listed in .claude-flow/config.json
  learningLoop.allowTaint is counted under `tainted` and never reaches SONA.
- CLI: opt-in re-verify (learningLoop.reverify, off by default) re-runs a
  rotating allowlisted manifest check in a temp detached git worktree at HEAD
  with a timeout; failure, timeout or error downgrades to unknown. Only an
  explicit verified-ingest re-verifies; hot callers defer.
- CLI: anomaly gate holds would-be lessons that are perfect-and-tainted,
  only-narrowed, or from one session, listed as `held: <id> (<reason>)`.

Adds scripts/eval-learning-loop.mjs (manual, plan-only unless --run).

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

* docs(adr): ADR-503 status names PR #4590

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

* fix(learning-loop): shell edits of tests taint; test the real re-verify runner (ADR-503)

- A Bash command that writes, moves or deletes a test file or verifier
  config (rm, mv, cp, tee, truncate, sed -i/perl -i, output redirection,
  git rm/checkout/restore/...) now sets edited-tests /
  edited-verifier-config like an Edit of that file. Before this change,
  Edit src/a.ts + `sed -i 's/it(/it.skip(/' src/a.test.ts` + `npm test`
  produced an untainted verified-success. Downgrade-only: reads and test
  runs earn nothing.
- gitWorktreeRunner is now tested against a throwaway git repo: pass,
  fail, missing script, timeout (hung script's process verified dead),
  non-repo error. After each run only the main worktree remains and no
  ruflo-reverify-* dir is left. A negative control (kill only the direct
  child) makes the timeout test fail.
- ADR-503 implementation notes record both, plus the interpreter-write gap.

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

* test(learning-loop): give the hung-check re-verify test an 8s budget for cold CI runners

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

* chore(ruflo-mods): 0.9.0 for ADR-503

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

---------

Co-authored-by: r <r@x>
2026-10-29 18:57:12 -04:00
rUvandr 375e846c66 feat(mods): verified-outcome learning loop, on by default (learningLoop, #4581, ADR-502) (#4583)
* feat(mods): verified-outcome learning loop (learningLoop, #4581, ADR-502)

ruflo-mods 0.8.0 adds the learningLoop option (default off). Each main-loop
turn becomes a trajectory whose outcome is verified-success/verified-failure
only when a recognised test/build/typecheck/lint command ran after the
turn's last edit and the shell's exit status said so; otherwise unknown.
A masked status (|| true, pipes, ;, background, substitution) verifies
nothing, and the model's own words are never read.

The CLI ingests the records (ruflo hooks verified-ingest, the
hooks_intelligence_verified-ingest MCP tool, and automatically from
hooks_route and hooks_session-end): only verified records train SONA,
unknown ones are counted; each id once; PII-redacted. It writes
learned-lessons.json, and the mod adds at most three cited lessons at or
above the 0.6 gate to a matching prompt. doctor --component learning-loop
reports whether outcomes reach SONA.

Stages 5-7 of #4581 (pane, autonomous /loop-run, GEPA self-tuning) are
deferred; the on-by-default evaluation has not been run.

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

* fix(mods): learning loop needs an edit to verify; redact e-mails before writing (#4581)

A turn that edited nothing is unknown (a verifier verifies a change).
The mod replaces e-mail addresses in the stored task; ADR-502 states the
privacy limit (broader PII redaction runs at CLI ingest).

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

* feat(mods): learningLoop on by default (#4581)

Maintainer decision: ship the learning loop on by default. Set the
learningLoop option to false to turn it off. ADR-502 records that the
issue's 30-task evaluation has not been run yet.

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

* fix(cli): ADR-112 guidance on hooks_intelligence_verified-ingest (#4581)

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

---------

Co-authored-by: r <r@x>
2026-10-29 16:38:56 -04:00
rUvandr cbd1986979 fix(cli): store patterns in LocalReasoningBank when it is the registered bank (#4567)
@claude-flow/memory 3.1.0 (#4550) made ControllerRegistry.set() real, so the
bridge now registers the intelligence module's LocalReasoningBank whenever
agentdb's ReasoningBank is unavailable. It has store()/findSimilar() but no
storePattern(), so bridgeStorePattern wrote to the SQL pattern namespace while
bridgeSearchPatterns read the bank: a stored pattern was never found when the
bank already held other patterns (the #2226 test failed on CI for #4566).

- bridgeStorePattern writes to the bank's store() with an embedding from the
  same generateEmbedding() the search uses, and flushes it to disk.
- bridgeSearchPatterns falls through to the SQL namespace when the bank has
  no match, so patterns written by the fallback path stay findable.

Co-authored-by: r <r@x>
2026-10-28 14:16:31 -04:00
ordinary being aca151dfe1 fix(memory): rescue each store's embedder, not just the first (#4421)
rescueAgentdbEmbedder() used a process-wide boolean to avoid re-patching. AgentDB registries are keyed by dbPath and each owns a distinct embedder, so after the first store was rescued every later store kept its mock embedder and wrote/searchable vectors from AgentDB's random fallback (#4410 memory scan).\n\nThe per-embedder __ruvectorRescued sentinel already makes the patch idempotent. Remove the global flag, keep the sentinel check, and export the helper for a focused two-store regression. Baseline (export-only, no behavior change) rescues the first embedder and leaves the second false; candidate rescues both.
2026-10-23 08:33:50 -04:00
rUvandr 17da11320a fix(memory): restore 10000-row bridge search window, configurable (#4397 part 1) (#4405)
The #2982 ORDER BY fix kept LIMIT 1000, so rows outside the newest 1000
were unfindable (3.38.3 and the sql.js path use 10000). Default is now
10000; CLAUDE_FLOW_SEARCH_WINDOW overrides (clamped 100..100000).

Co-authored-by: r <r@x>
2026-10-22 22:16:10 -04:00
ordinary being 947204c082 fix(memory): scrub deleted payload from tombstones (#4351)
memory delete is a soft delete so the UNIQUE(namespace,key) slot stays occupied and a later upsert can resurrect the row. Both write paths kept the payload on disk: the native bridge left content, embedding, tags and metadata intact, and the sql.js fallback only nulled embedding. A deleted value therefore remained readable by anyone opening memory.db/agentdb-memory.db directly (#3785 residual).\n\nScrub content, embedding, embedding_model, embedding_dimensions, tags and metadata in both the bridge SQL and the sql.js image path. content is NOT NULL in the schema, so use the empty string rather than SQL NULL; identity, namespace, status, provenance and timestamps remain for resurrection and audit. Enable PRAGMA secure_delete=ON before both soft-delete paths and namespace purges so SQLite overwrites the old cells instead of leaving the payload in free pages.\n\nAdd sql.js delete/purge regression tests that also scan the raw image, plus a native better-sqlite3 case that checks the columns and the image after a WAL truncate checkpoint. Baseline local cases fail on the raw markers; the fix passes, and related delete/purge/upsert/concurrency tests pass 25/26 (native case skipped locally).
2026-10-21 09:14:47 -04:00
Gss d7f2286835 fix(memory): build the RaBitQ index on demand and use it on the vector path (#4318)
* fix(memory): build the RaBitQ index on demand and use it on the vector path (#4203)

shouldRebuildRabitq() had no callers and the index was only ever populated by the explicit embeddings_rabitq_build tool, so searchRabitq() always returned null and the sql.js pre-filter was dead.

ensureRabitqIndex() drives the existing thresholds from the search entry points (60s throttle, 10-vector floor, 20% drift, disabled after a missing-WASM failure, bound to the source dbPath and dimensions).

The bridge cosine path now scans RaBitQ candidates and reranks them with the same exact cosine, falling back to the unchanged exhaustive scan on any error.

* test(memory): cover RaBitQ auto-build, exact rerank and top-k recall (#4203)

Six tests against a real sqlite store: build on demand, bridge uses the index and reranks with exact cosine, no rebuild per search, below-floor negative control, exhaustive-vs-indexed parity when the corpus fits the candidate window, and recall plus exact-rerank on a 60-row corpus larger than the window (>=80% top-5 recall).
2026-10-20 06:00:14 -04:00
Mathew BeaneandRuFlo f67d3b201f feat(memory,ollama): tag filter for memory list, export v1.1, local Ollama default model (#3526) (#3526)
Rebased onto main 3.56.9.

- memory_list / `memory list --tags`: exact AND tag filter via json_each,
  ANDed with namespace and provenance on the sql.js and bridge paths;
  coexists with ADR-472 embeddings and #4056 includeExpired.
- memory_export v1.1 carries tags; memory_import restores them and reports
  withTags alongside main's vectors/failed accounting.
- Ollama: tier aliases and claude-* ids resolve to OLLAMA_DEFAULT_MODEL or
  the persisted `providers configure` model; only the real ollama.com
  endpoint falls back to gpt-oss:120b-cloud, a local endpoint without a
  default fails loudly instead of egressing to Ollama Cloud.

Provider precedence is dropped from this change: main's #3493 (explicit
provider fails closed) supersedes the earlier narrowing.

Co-authored-by: RuFlo <ruv@ruv.net>
2026-10-20 05:36:37 -04:00
6afffb777c fix(embeddings): writable model cache dir + retryable degraded state (#3692) (#3831)
A system-prefix global install's default ONNX model cache lives under its
own package directory, which is root-owned — an ordinary runtime user hits
EACCES the first time any of three independent call sites load the local
transformers.js pipeline. The resulting failure also got memoized as
permanent mock-embedding state for a worker's entire process lifetime, so
fixing cache permissions mid-run never helped an already-running worker.

- Resolve a writable cache dir (TRANSFORMERS_CACHE/HF_HOME, else
  ~/.cache/ruflo/models) and set it before pipeline() init at all three
  call sites: transformers-loader.ts, memory-initializer.ts, task-embedder.ts.
- Distinguish a permanently-missing backend from a retryable environmental
  failure (EACCES, ENOSPC, transient network) in memory-initializer.ts and
  task-embedder.ts, so a retryable degraded state re-attempts real
  initialization after a bounded interval instead of requiring a restart.
- Keep ADR-390's truthful backend:'onnx'|'mock' reporting unchanged.

See ADR-454 for the full decision record.

Co-authored-by: Nicholas Ruest <nicholasruest@Nicholass-MacBook-Pro.local>
Co-authored-by: RuFlo <ruv@ruv.net>
2026-10-19 22:56:02 -04:00
rUvandClaude e86134e45b feat(memory): add read-only memory peek command (#3508) (#3620)
Reports which memory.db/agentdb-memory.db files this cwd resolves to,
their active row counts, last write, and why the route was chosen —
without calling ensureInitialized(), the MCP tool layer, or writing
anything. Addresses the gap left after #3463/#3448: memory_stats and
friends still initialize the default store when called with no path,
answer for one file per call, and never report both stores or the
sharedKeys intersection (so a naive consumer double-counts mirrored
rows).

- src/memory/memory-peek.ts: new, self-contained read-only probe.
  sql.js store is read as a one-shot in-memory byte buffer (never
  written back); the native agentdb-memory.db sibling is opened
  readonly/fileMustExist, same as sibling-store.ts. Neither file is
  ever opened unless existsSync() first confirms it exists.
- src/commands/memory.ts: wires `memory peek [--path] [--format json]`
  into the existing subcommand list/help text.
- __tests__/memory-peek-3508.test.ts: asserts a fresh project ends up
  with zero files after a peek, plus correctness coverage for row
  counts (excluding soft-deleted rows), last-write timestamps, the
  sharedKeys intersection (not sum), route-source labeling, and the
  encrypted-at-rest case.

Scoped to the CLI subcommand only; the MCP `memory_peek` tool and
doctor integration from the issue's "smallest API" are left for a
follow-up to keep this change minimal.


Claude-Session: https://claude.ai/code/session_019gH7pnqfexcs77Ca1UCqHr

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-19 21:49:41 -04:00
rUv 2b15ef2715 Merge pull request #4191 from 555aaditya/fix/3113-3114-reasoningbank-embedder
fix(memory): use the ReasoningBank embedder instead of the hash fallback
2026-10-19 17:21:52 -04:00
rUv 0bec340c54 Merge pull request #4298 from ruvnet/fix/4291-graph-query-db-path
fix(memory): resolve graph reads through explicit CLAUDE_FLOW_DB_PATH binding (#4291)
2026-10-19 17:02:21 -04:00
randRuFlo 14f659089f fix(memory): resolve graph reads through explicit CLAUDE_FLOW_DB_PATH binding (#4291)
getBridgeDb() and isBridgeDbEncryptedAtRest() in graph-edge-writer.ts
resolved the memory.db path as `customDbPath ?? path.join(getMemoryRoot(),
'memory.db')`, bypassing resolveDbPath() (memory-initializer.ts) — the
function that actually implements the documented path-priority rule
(explicit CLAUDE_FLOW_DB_PATH wins over the plain default). A caller that
explicitly selected a store via that env var silently got graph-query
results read from a different, unselected memory.db instead — a
source-bound read leaking data from a store it never chose.

Both functions now resolve the file through resolveDbPath(customDbPath),
so a custom argument, then CLAUDE_FLOW_DB_PATH, then the memory-root
default are tried in that order, and encryption sniffing (isRfe1EncryptedAtRest)
and the native open always agree on the same resolved file. A missing or
encrypted-at-rest explicit source still refuses (returns null) rather than
falling back to any other store — unchanged behavior, just now applied to
the correct path.

Adds __tests__/graph-query-explicit-db-path-4291.test.ts, reproducing the
issue's exact synthetic fixture (two sqlite stores under a fixture .swarm
dir, CLAUDE_FLOW_MEMORY_PATH + CLAUDE_FLOW_DB_PATH env bindings, a k-hop
agentdb_graph-query call) plus: unchanged default behavior with no env
binding, refusal when the explicit path is missing, and refusal when the
explicit source is encrypted at rest. Does not touch the independent
agentdb-memory.db controller default (#3155/#3156) or the ControllerRegistry
identity fix (#3143).

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-10-19 15:00:25 -04:00
rUv 227a9176c4 Merge branch 'main' into fix/3113-3114-reasoningbank-embedder 2026-10-19 19:49:28 +01:00
kevin9327 ed98c2341e fix(intelligence): write learned patterns before a one-shot command exits (#4283)
recordTrajectory() saved stats.json synchronously but left the
ReasoningBank save to its 100 ms debounce timer. The one-shot bins call
process.exit(0) as soon as the command resolves, so the timer never
fired: patternsLearned went up while patterns.json was never written.
Flush the bank next to savePersistedStats() so the counter is never
persisted for a pattern that wasn't.
2026-10-19 09:14:27 +09:00
xjh bd92ac5b4c fix(intelligence): forward trajectories using the ruvllm contract (#4222)
Map outcomes and steps to the fields consumed by ruvllm pattern extraction. Add coverage for success, failure, and partial trajectories.

Refs #4199 (part A).
2026-10-17 16:35:22 +01:00
Rudy Mizrahi Celekli f429ccac53 fix: serialize learning stats read-merge-write transactions (#4240) 2026-10-17 14:59:04 +01:00
555aaditya 1ec4cddcfa fix(memory): use the ReasoningBank embedder instead of the hash fallback
When agentic-flow/reasoningbank was the first available local embedder,
every memory store and search still produced hash-fallback vectors:

- #3113: the loader registered the model as { embed: computeEmbedding },
  but generateLocalEmbedding() only calls the model when it is a
  function, so the object never ran. It also advertised 768 dimensions
  for agentic-flow's 384-dim all-MiniLM-L6-v2 model.
- #3114: computeEmbedding() resolves to a Float32Array, which has no
  .data and fails Array.isArray(), so its output was discarded even
  when called.

Register a function wrapper with 384 dimensions, as the ruvector branch
already does, and accept typed-array output. DataView is excluded: it is
an ArrayBuffer view without an iterator, so Array.from() would return []
and be reported as a real zero-length vector. The transformers
(output.data) and ruvector (plain array) paths are unchanged.

vitest externalizes agentic-flow*, so the regression runs the source in
a child process under the existing agentic-flow-root-probe loader hooks,
which gain a PROBE_REASONINGBANK=float32|dataview mode.

Fixes #3113
Fixes #3114
2026-10-14 23:10:16 +05:30
randRuFlo 0aaff49bcb fix(cli): neural data dir resolves through getProjectCwd (env-var precedence audit)
Co-Authored-By: RuFlo <ruv@ruv.net>
2026-10-14 10:25:25 -04:00
randRuFlo fca96f9fc0 Merge main into perf/mcp-memory-on-core
Co-Authored-By: RuFlo <ruv@ruv.net>
2026-10-14 10:24:16 -04:00
rUv d4f7af9983 Merge pull request #4185 from ruvnet/fix/sona-neighbour-reinforcement-4134
fix(sona): reinforce the nearest existing pattern for near-identical tasks (#4134)
2026-10-14 06:10:39 -07:00