mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-12-04 06:21:59 +09:00
722232566ad1fc4e73ba4fefc46d77d380ce61ba
167
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
722232566a |
fix(memory): RvfBackend search through hnsw-index.ts (recall@10 0.09 → 0.89) (#4836)
* fix(memory): RvfBackend search through hnsw-index.ts (recall@10 0.09 -> 0.89) RvfBackend's inlined HnswLite seeded every search from the first efConstruction vectors in insertion order and BFS'd a flat neighbour graph, and each insert was an O(n) brute-force scan. Measured against exact search on 5,000 random unit vectors (cosine, 200 queries, seed 42): index 384-dim recall@10 1536-dim clustered 384 HnswLite (before) 0.091 0.079 0.999 @ruvector/diskann 0.1.3 0.896 0.739 1.000 hnsw-index.ts, ef=200 0.888 0.744 0.990 DiskANN matched HNSWIndex on recall but a vector inserted after build() is not searchable until a full rebuild (3.6-4.3 s at 1k vectors), which breaks store()-then-search(). HNSWIndex is incremental and is the single HNSW implementation ADR-125 asks for, so RvfBackend now uses it through a private RvfVectorIndex (not exported; the prepublishOnly surface check still passes). - indexes of <= 1000 vectors and dimension-mismatched queries use an exact scan - distances map back to the old similarity scale; threshold filter unchanged - re-storing an entry without an embedding removes its old vector - update() re-indexes when an untyped caller passes an embedding New rvf-backend-recall.test.ts drives the real RvfBackend.search: recall@10 >= 0.9 on 2000 random 64-dim vectors (HnswLite scored 0.294 there), exact results at 300 vectors, delete/re-store correctness, recall after reopen. @claude-flow/memory 3.2.2 -> 3.2.3. Co-Authored-By: claude-flow <ruv@ruv.net> * chore(memory): leave the version at 3.2.2 in this PR audit-leaf-package-publish requires the CLI pin to cover the workspace version, and audit-leaf-versions-published requires that pin to exist on the registry. The 3.2.3 bump, its publish and the CLI pin move together in the release that follows. Co-Authored-By: claude-flow <ruv@ruv.net> * release(memory): @claude-flow/memory 3.2.3, CLI pins it The RvfBackend change has to reach users through a standalone publish: memory is not bundled into the release tarballs (Publishing Rules). @claude-flow/memory@3.2.3 is published from this branch's tree; the CLI pin (dependencies + optionalDependencies) moves to it so audit-leaf-package-publish and audit-leaf-versions-published both hold. The lockfile also gains the @ruvector/sona 0.1.10 package entries pnpm reported missing. Co-Authored-By: claude-flow <ruv@ruv.net> --------- Co-authored-by: r <r@x> |
||
|
|
47406b0a96 |
fix(memory,neural): AgentDB SQL fallback persistence, cache size reuse, MoE mean P_i (#4639)
* fix(memory,neural): persist AgentDB SQL fallback, reuse cached sizes, average MoE P_i - memory (#4410): AgentDBBackend's SQL fallback gated on db.run/db.get, which agentdb's prepare/exec handle never has, so no table was created and every write was a silent no-op. Use prepare().run/get with spread params (safe on better-sqlite3 and agentdb's sql.js shim) and quote the "references" column. - memory (#4481): CacheManager stores each entry's size on its LRU node and refunds that number on overwrite/delete/eviction instead of re-serializing. - neural (#4381): computeLoadBalanceLoss() uses the mean gate probability over the same route() history as f_i, persisted and reset with the routing stats. - Bump @claude-flow/memory 3.2.2, @claude-flow/neural 3.0.2. Co-Authored-By: RuFlo <ruv@ruv.net> * chore(cli): pin @claude-flow/memory 3.2.2 and @claude-flow/neural 3.0.2 (both published) Co-Authored-By: RuFlo <ruv@ruv.net> --------- Co-authored-by: r <r@x> |
||
|
|
56fe4dc604 |
feat: ecosystem convergence — agentdb 3.0.0, agentic-flow 3.0.0, AIMDS packs; release 3.67.0 (#4628)
* fix(aidefence): restore the ADR-118 wider-detection pass to source (3.0.4) @claude-flow/aidefence 3.0.3 (npm latest) was published from an uncommitted tree carrying the ADR-118 / #2004 patterns, so main never had them, and main's #3177 ReDoS bounds never reached npm. 3.0.4 is a true superset: the verb-noun override window, behave-as role hijack and god/root/admin/sudo mode jailbreak markers, on top of main's bounded PII/marker regexes. Parity against the published 3.0.3 dist: 24-input corpus, 0 regressions. Drops publishConfig.tag=alpha. Refs #4625. Co-Authored-By: RuFlo <ruv@ruv.net> * feat(aidefence): merge AIMDS pattern packs into ThreatDetectionService (3.1.0) Vendors the AIMDS pack engine (normalize, decoders, pattern-loader, engine) and its six pattern packs (53 patterns) from midstream AIMDS at abe78d6 into src/domain/services/packs/. Packs are embedded as TS modules, so they load from the published ESM dist with no fs path lookup; the files allowlist is unchanged. ThreatDetectionService.detect() runs the packs in a second pass over the raw input and merges findings into the existing result shape (one threat per type, as before). Built-in patterns, including the ADR-118 extras, stay and their confidences are unchanged. Packs are on by default; disable or select them with createThreatDetectionService({ packs }) or createAIDefence({ packs }). The legacy pattern-array argument still works. - ThreatType gains tool_invocation, data_exfiltration, markup_forgery; Threat gains an optional ruleId (e.g. EX-001) for pack findings. - Packs are validated, compiled and regex-warmed once per process, so isSafe()/checkThreats() no longer pay a compile per call and the first detect() is not charged ~17 ms of lazy regex compilation. - Fixes a quadratic regex in the vendored normaliser (undoLeet): 100 KB of hex digits took 1.8 s; now 6 ms. Decoders cap each blob before decoding. Corpus (55 attacks / 30 legit): built-ins only 8/55, packs on 55/55; false positives F13 and F27 in both modes (built-in encoding_attack), pinned. Co-Authored-By: RuFlo <ruv@ruv.net> * fix(memory): build AgentDB controllers with an embedder and the shared vector backend LearningSystem, NightlyLearner, ExplainableRecall and the graph transformer's CausalMemoryGraph take (db, embedder, ...). The registry passed only the database, so the first predict/discover/recall threw on this.embedder (the #3327 Finding A class, fixed for ReasoningBank only). Real-agentdb test fails on the old source (learningSystem.embedder undefined). memory suite 659/659. Adds ADR-513 (stable versions, convergence) and ADR-516 (aidefence recovery). Co-Authored-By: RuFlo <ruv@ruv.net> * feat(cli): move to agentic-flow ^2.2.0 (main line); stable-only tag policy - agentic-flow ^3.0.0-alpha.1 resolved to the March 3.0.0-alpha.2, which pulled @xenova/transformers -> onnx-proto -> protobufjs 6 (critical). 2.2.0 is agentic-flow's main line (ADR-515). The update validator and the init doc table follow. - neural-tools: computeEmbedding returns a Float32Array, which JSON.stringify writes as {"0":...}; convert to an array before the neural store. - CLAUDE.md: no more alpha/v3alpha/next dist-tags (ADR-513); overrides do not reach users; examples use ruflo@latest. Co-Authored-By: RuFlo <ruv@ruv.net> * chore(cli): pin @claude-flow/aidefence 3.1.0 (AIMDS pattern packs) Co-Authored-By: RuFlo <ruv@ruv.net> * chore(cli): target agentic-flow ^3.0.0 (first stable 3.x, ADR-515) agentic-flow's security defaults change in a breaking way (agents no longer bypass permissions by default, proxies need a token), so the main line ships as 3.0.0 rather than 2.2.0. That also gives the 3.x alpha line a stable head: existing ^3.0.0-alpha.1 installs resolve to it and drop the March alpha's protobufjs 6 (critical). Co-Authored-By: RuFlo <ruv@ruv.net> * fix(memory): capture AgentDB's backend failure reason from stderr too agentdb 3.0.0 moves library diagnostics off stdout (they corrupted stdio MCP JSON-RPC), so the #4622 lock-reason capture patches console.error as well. Co-Authored-By: RuFlo <ruv@ruv.net> * docs(adr): ADR-514 agentdb 3.0.0, ADR-515 agentic-flow 3.0.0, ADR-517 AIMDS pattern packs Co-Authored-By: RuFlo <ruv@ruv.net> * chore(memory): 3.2.1 (embedder wiring, stderr reason capture) Co-Authored-By: RuFlo <ruv@ruv.net> * chore(release): 3.67.0 — agentdb 3.0.0, agentic-flow 3.0.0, aidefence 3.1.0, memory 3.2.1 - CLI and the claude-flow umbrella declare agentic-flow ^3.0.0 (root lock and v3 pnpm lock resolve 3.0.0 / agentdb 3.0.0). - CHANGELOG 3.67.0. Co-Authored-By: RuFlo <ruv@ruv.net> * test/docs: dated ADRs 513-517; scope the bracket/DAN timing test to built-ins - ADRs 513-517 gain Date lines (the console ADR parser expects >97% dated) and ADR-513/516 name the versions that shipped (agentic-flow 3.0.0, aidefence 3.1.0). - threat-detection 'bounds the bracket and DAN patterns' measures the built-in regexes it was written for ({ packs: false }); the AIMDS packs have their own 100 KB adversarial timing test. Full detector on that input: 86 ms locally, 301 ms on the CI runner (linear, budget was 200 ms). Co-Authored-By: RuFlo <ruv@ruv.net> * fix(deps): stop pinning ruvector 0.2.27 under agentdb 3.0.0; CLI agentdb ^3.0.0 The root (and ruflo wrapper) overrides pinned ruvector ^0.2.27 from the BEIR work (3.10.29). npm applies overrides inside this repo's tree, so CI ran agentdb 3.0.0 on ruvector 0.2.27, below agentdb's own ^0.2.40: a pairing no user ever installs (published overrides are ignored), and the one where #2226 pattern recall failed on CI. Raised to ^0.2.41. The CLI's agentdb range moves to ^3.0.0 (stable; no alpha ranges, ADR-513), so the v3 pnpm lock resolves 3.0.0 and the v3 test job exercises what users get instead of 3.0.0-alpha.20. 115 agentdb/memory-related CLI test files: 868/868 on 3.0.0. Co-Authored-By: RuFlo <ruv@ruv.net> --------- Co-authored-by: r <r@x> |
||
|
|
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> |
||
|
|
7387295568 |
dream(memory): #4549 wire ControllerRegistry.set() — MutationGuard/AttestationLog activation was permanently dead (evaluated, ACCEPT-scoped) (#4550)
* dream(memory): wire ControllerRegistry.set() so MutationGuard/AttestationLog activation stops being dead code
memory-bridge.ts's post-init controller-activation wiring (reasoningBank,
learningSystem, skills, semanticRouter, gnnService, rvfOptimizer,
mutationGuard, attestationLog, guardedVectorBackend) has always gated
registration on `typeof reg.set === 'function'`, falling back to an
unread `reg._controllers` property otherwise. ControllerRegistry never
implemented a public set() method, so every external activation silently
took the dead fallback: registry.get('mutationGuard')/get('attestationLog')
always returned null, permanently disabling write-mutation validation
(fail-open "no guard installed = allow") and audit logging (silent no-op)
on the real store/delete/purge paths. Same bug shape as the already-fixed
#3327 Finding A (reasoningBank.store never existed, so its own
typeof-guard was dead too).
Adds ControllerRegistry.set<T>(name, instance) mirroring the shape
initController() already produces internally. Zero changes needed at any
of the 9 memory-bridge.ts call sites.
5 new discriminating tests reproduce memory-bridge.ts's exact activation
pattern; stash-isolated baseline fails all 5 (TypeError: registry.set is
not a function), candidate passes all 5. Full @claude-flow/memory suite:
650/651 both ways (1 pre-existing environmental failure, byte-identical,
unrelated chmod/root-bypass test). tsc --noEmit: 0 errors.
Evaluated, pending independent adversarial critique.
* dream(memory): close prior instance on ControllerRegistry.set() (post-critique)
Independent adversarial critique of
|
||
|
|
6e213d5bb3 |
fix(memory): distinguish recent dead locks from live writers (#4389)
* fix(memory): distinguish recent dead locks from live writers inspectAgentdbLock() labeled a dead holder as 'live' when the lock was younger than the 10s stale threshold. The same state then produced 'another process is writing this database' guidance, so callers could wait for a writer that did not exist or leave a recoverable lock in place indefinitely (#3979 item 5).\n\nAdd a distinct 'recent' LockState for dead-PID locks still inside the stale window, clamp clock-skewed ages to zero, and give withAgentdbLockRecovery a precise retry message. The guard still refuses to clear the lock until it is old enough; only the diagnosis changes. * chore(memory): bump @claude-flow/memory to 3.0.9 The leaf-package-publish audit correctly requires a version bump whenever publishable @claude-flow/memory source changes. Bump the leaf and both CLI dependency pins, and update the pnpm importer specifier, matching the #4279/#4152 release pattern. |
||
|
|
462c573cb7 |
fix(memory): wire real AgentDB HNSWIndex with safe fallback (#4249) (#4322)
* fix(memory): adapt real AgentDB HNSWIndex with safe fallback Verify actual native search, mutation lifecycle, concurrency and exact fallback. Include source-bound regression and bounded benchmark evidence for #4249. No persistence or package-release claim. * fix(memory): preserve expiry and vector ownership across native search Keep TTL-bearing semantic queries exact and detach stored/returned vectors. Snapshot query vectors before awaits. Add three real-native regressions and refresh the verification receipt: 645 tests pass; disclose transient timing miss. * fix(memory): bump @claude-flow/memory to 3.0.8 for the real HNSW adapter #4249's leaf-package-publish audit correctly flagged that agentdb-backend.ts/agentdb-hnsw-adapter.ts changed source but the package version was still 3.0.7. Bumps the leaf, the CLI's exact pin, and the pnpm-lock.yaml specifier together so the fix actually ships. Co-Authored-By: RuFlo <ruv@ruv.net> --------- Co-authored-by: r <r@x> |
||
|
|
9cf2ad57ba |
dream(memory): #4137 wire delete-sync into AutoMemoryBridge.importFromAutoMemory() (evaluated, ACCEPT) (#4138)
* dream(memory): #4137 AutoMemoryBridge was additive-only, never delete-synced removed/vanished source content
importFromAutoMemory() diffed new content against AgentDB by content-hash
to insert/skip, but never detected or deleted an entry whose source
heading (or whole source file) was removed — deleted memory content
stayed retrievable via semantic search indefinitely. Adds a per-source-
file key diff (reusing the existing single bulk query, zero schema
change) plus a second pass for files removed entirely from disk, each
with a false-full-wipe guard. Evaluated: 7 new discriminating tests,
baseline-fails/candidate-passes via stash isolation; full suite and tsc
clean modulo pre-existing/unrelated flakes. Adversarial critique found
and this session fixed forward the whole-file-removed gap and a vacuous
test assertion before this commit.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01UkpQrJUNdFzDJVnY2FzXh8
* dream(memory): #4137 append 2026-10-13 ledger row
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01UkpQrJUNdFzDJVnY2FzXh8
* fix(memory): #4137 bump @claude-flow/memory to 3.0.5 for the delete-sync change
CI's leaf-package-publish audit caught this: @claude-flow/memory is a
non-bundled leaf that resolves from the registry for the release train,
so a publishable source change (auto-memory-bridge.ts) must bump the
leaf's own version or the fix silently never reaches a release. Bumps
the leaf's package.json, the CLI's exact pin (dependencies +
optionalDependencies), and the matching pnpm-lock.yaml specifier.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01UkpQrJUNdFzDJVnY2FzXh8
* fix(memory): #4137 scope delete-sync to the writing memoryDir, avoid version collision with #4183
Review finding: the backend can be shared across multiple memory dirs
(e.g. the SessionStart hook's main dir vs. a worktree dir from
worktreeMemoryDir()). Without recording which memoryDir wrote an entry,
importing one dir could see another dir's same-named file/heading as
"gone" and delete it. Entries now carry metadata.memoryDir, and both
delete-sync passes (per-heading diff and whole-file-removed) only
consider entries whose memoryDir matches the importing bridge's own —
legacy entries written before this field existed (no memoryDir at all)
are therefore never delete-sync eligible. Two new discriminating tests
cover cross-dir isolation and the legacy-entry case; all 9 existing
delete-sync fixtures updated to carry memoryDir so they still exercise
the intended "same dir" path rather than being silently excluded.
Also bumps @claude-flow/memory to 3.0.6 (CLI pins + lockfile specifier)
since #4183 independently claimed 3.0.5 for the same leaf — whichever
of the two PRs lands second needs a version past the other's.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01UkpQrJUNdFzDJVnY2FzXh8
* fix(memory): #4137 revert stray codex/security/shared lockfile drift
An earlier `pnpm install` run in this session (unrelated to this PR's
own change) left pnpm-lock.yaml recording codex/security/shared at
specifier 3.0.6 while v3/@claude-flow/cli/package.json still pins them
at 3.0.5 — a mismatch that got swept into a prior commit by staging the
whole lockfile file. `pnpm install --frozen-lockfile` (what CI runs)
fails on that drift regardless of this PR's actual content. Reverted
those three specifiers back to 3.0.5 to match package.json; the memory
specifier bump to 3.0.6 (this PR's real change) is untouched. Verified
locally: `pnpm install --frozen-lockfile` now succeeds.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01UkpQrJUNdFzDJVnY2FzXh8
* chore(memory): untrack test-generated agentdb.rvf.idmap.json
Swept into the previous merge commit by running the test suite to
verify the merge; it's a fresh-run artifact (empty idToLabel/labelToId
maps), not source. Added to .gitignore alongside the other *.rvf
test-pollution exclusions in this package.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(memory): bump @claude-flow/memory to 3.0.7 for the delete-sync fix
AutoMemoryBridge.importFromAutoMemory()'s delete-sync fix in this PR
changed v3/@claude-flow/memory/src/auto-memory-bridge.ts without
bumping the package version. @claude-flow/memory is not bundled into
the release tarballs — it resolves from the registry — so publishing
the three train packages without this bump would ship the old 3.0.6
copy and the fix would reach nobody (ruvnet/ruflo#3335, #3390).
Will publish @claude-flow/memory@3.0.7 standalone once this merges.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(memory): #4137 bump CLI pins + lockfile specifier to match memory@3.0.7
|
||
|
|
d529a38a7c |
release: 3.58.0 (#4306)
* chore(release): 3.58.0 version bumps and changelog
Minor release: new memory peek command, Codex activity viewer, configurable
MCP rate limits, plus the #4303 install-breaking fix and a round of
correctness fixes merged since 3.57.2. Also bumps ruflo-console 0.44.4 ->
0.44.5 for the #4305 TUI fix, which shipped to main without a plugin version
bump (the same gap already documented as a past mistake in the console's own
changelog for 0.44.3/0.44.4).
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ruflo-console): update smoke.sh's hardcoded version check to 0.44.5
The plugin.json version bump to 0.44.5 (for the #4305 TUI fix) broke the
smoke contract's own hardcoded expectation of 0.44.4 in step 1. Update the
step name and grep pattern to match.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ci): sync the smoke-workflow regression test to the real 15-minute timeout
#3950 bumped .github/workflows/all-plugins-smoke.yml's smoke-all job from
timeout-minutes 10 to 15 (the job now also checks out and smokes the first
external git-subdir marketplace entry, agentic-qe-fleet) but never updated
this test's hardcoded expectation of 10, breaking the Test Suite job on
every PR since.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(memory): resolve sql.js's wasm dist path directly, not via package.json
fts5.test.ts located sql-wasm.wasm via require.resolve('sql.js/package.json')
then string-replaced the suffix. sql.js 1.14 tightened its exports map to
"." and "./dist/*" only, so that package.json subpath resolve throws
ERR_PACKAGE_PATH_NOT_EXPORTED even though the wasm file is present on disk —
caught by the existing try/catch and misreported as "sql.js isn't installed",
failing all 4 SqlJsBackend FTS5 tests with "sql.js/dist/sql-wasm.wasm not
found". Resolve 'sql.js/dist/sql-wasm.wasm' directly instead, which the
"./dist/*" export already permits.
Verified: 6/6 passing locally (was 4 failed before the fix).
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ci): move pod-tick.test.mjs to the node:test exclusion list
Same fix as #4308: this file imports test() from node:test (not vitest)
and documents itself as "Run with: node --test" in its own header, but
was miscategorized into ci-test-baseline.txt. Running it under vitest's
shared worker process correlates strongly with the ERR_IPC_CHANNEL_CLOSED
crash hit 4/6 times on this PR's own CI (#4307). Applying here directly so
this release doesn't wait on #4308 to merge first.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ci): cap the ratchet's vitest worker count to 2
#4307: Test Suite (ubuntu-latest) intermittently crashes with tinypool's
ERR_IPC_CHANNEL_CLOSED at three different, unrelated points across 7 runs
on this PR, after ruling out any specific file as the cause (one
candidate, pod-tick.test.mjs, was fixed separately for an unrelated
reason and the crash still recurred at a different file). The pattern
(crash location varies, happens ~60-90s into a ~9500-test run) is more
consistent with cumulative memory pressure across the default fork
pool (one fork per CPU, ~4 on a standard runner) than a single bad
test. Capping workers at 2 trades some wall-clock time for headroom
while the real cause is still open in #4307.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(graph-intelligence): build the optional cli import specifier from parts
#4307 investigation, round 8: once the worker-cap fix (
|
||
|
|
78817c3e5f |
fix(memory): remove RvfBackend's dead @ruvector/rvf native branch (#4279)
tryNativeInit() called an instance open() that the @ruvector/rvf SDK
doesn't have (it only has the static RvfDatabase.create/open), so init
always threw, the catch swallowed it, and every install ran pure-TS.
Correcting only that call would turn a silent fallback into silent data
loss: initialize() skipped loadFromDisk() on the native path, while store,
search and persist still went through the in-memory map, so the next
persistToDisk() would overwrite databasePath with only the new entries.
The SDK is a vector index (u64 ids, {id, distance} results, no payloads),
so it can't be the store for MemoryEntry records. Remove the branch and
keep the pure-TS backend that already runs everywhere. healthCheck() no
longer recommends installing @ruvector/rvf.
Adds rvf-backend.test.ts: reopen reloads and keeps the snapshot even when
an @ruvector/rvf whose factories succeed is importable. It fails against
main and against the open()-only fix.
Fixes #4279
Co-Authored-By: RuFlo <ruv@ruv.net>
|
||
|
|
85537ab4d8 |
fix(memory): TieredMemoryStore recalls multi-word and natural-language queries (#4152)
Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
a46e49cbc5 |
test(memory): apply each agentdb mock change before queueing the next
vitest applies queued doMock/doUnmock entries for one path in resolve order, so an afterEach doUnmock could win over the next test's doMock and the stale-lock retry test saw the real agentdb (CI: 0 fake instances). |
||
|
|
c536e77fda |
fix(memory): reroute the stale-lock retry AgentDB too; memory 3.0.4
Rebased onto main, where ControllerRegistry and AgentDBBackend build AgentDB inside withAgentdbLockRecovery(); useHostSqliteDriver() now runs inside that closure right after each `new AgentDB`, so the instance a stale-lock retry creates also opens its handle with getHostSqliteDriver(). Tests drive the retry path for both sites. @claude-flow/memory 3.0.3 was published by 3.56.3 without the driver, so this ships as 3.0.4 and the CLI pins 3.0.4. The #3693 memory-owner test now reports a skip when no native addon is available instead of passing. |
||
|
|
d4458abdff |
fix(memory,cli): keep the CLI's better-sqlite3 handles on AgentDB's copy
Follow-up to the AgentDB driver change. shared-sqlite.ts (#3693/#3883) resolved better-sqlite3 from agentdb's location so CLI handles share AgentDB's native copy. With AgentDB now opened through @claude-flow/memory's better-sqlite3, that put graph-edge-writer, the memory-initializer repair paths, backup restore, distillation, tuning and the attestation log back on agentdb's nested 11.x: `hooks post-task` still loaded both addons (and aborted on Node 24), and mixing copies on one file can delete the -wal/-shm sidecars under AgentDB's live handle. - @claude-flow/memory exports getHostSqliteDriver(), the one source of the constructor; useHostSqliteDriver() opens AgentDB with it and reports whether it replaced the loader. - shared-sqlite resolves better-sqlite3 from @claude-flow/memory when the installed memory carries agentdb-native-driver.js, else from agentdb as before, so either memory version keeps one copy per process. - @claude-flow/memory 3.0.3, CLI pin 3.0.3 (leaf-publish gate). Tests: identity between AgentDB's handle constructor and loadBetterSqlite3(); #3693 owner model for the memory holder and the pre-3.0.3 fallback; both AgentDB construction sites; routing against a real nested copy; a drift guard on agentdb's initializeDatabase contract. |
||
|
|
b1645c6f47 |
fix(memory): open AgentDB with our better-sqlite3 so Node 24 does not abort
On Node 24.19+, `memory search`, `memory_store` and the AgentDB MCP tools abort intermittently with `Assertion failed: (env) != nullptr` in node::RemoveEnvironmentCleanupHook, from Statement::~Statement() in agentdb/node_modules/better-sqlite3 (exit 134 / "Connection closed"). agentdb 3.0.0-alpha.x pins better-sqlite3 ^11.8.1. 11.x has no Node 24 prebuild, so npm compiles it against the local Node headers, and 24.19+ headers carry a partial ObjectWrap cleanup-hook backport (nodejs/node#65446) that aborts when a Statement is collected outside an Environment. Our own better-sqlite3 12.x ships a Node 24 prebuild built before that header change. The `better-sqlite3` override in the published package.json files does not reach agentdb: npm ignores overrides in a dependency, and `npm i -g ruflo` still installs the nested 11.10.0. ControllerRegistry and AgentDBBackend now replace the AgentDB instance's initializeDatabase() so its handle is opened with this package's better-sqlite3; AgentDB's own loader stays as the fallback and forceWasm is untouched. |
||
|
|
dd8fd3cda8 |
fix(memory): settle hybrid shutdown, real-path sql.js lock test for AgentDBBackend
Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
01fa240e7c |
wip(memory): agentdb alpha.20 floor + sql.js lock/concurrency guard
Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
74b8e7bf1c | Merge branch 'pr-3687' into feat/release-3.56.0-batch | ||
|
|
20f91b0e8b | Merge branch 'pr-3679' into feat/release-3.56.0-batch | ||
|
|
681f0b488b |
fix(memory): preserve frozen non-stateful invalidation patterns
Signed-off-by: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com> |
||
|
|
e0fb4ebd74 |
fix(memory): match each cache key independently during invalidation
Signed-off-by: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com> |
||
|
|
e36ec17c78 |
fix(memory): account for replacement sizes before cache admission
Signed-off-by: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com> |
||
|
|
02bfa26622 |
dream(memory): #3516 cache mmrRerank() cosine max-similarity across rounds
O(candidates x selected^2) -> O(candidates x selected): a running per- candidate max-similarity-to-selected cache replaces the full re-walk of the selected set on every outer MMR loop pass. Byte-identical selection order (max is associative; zero-floor semantics preserved exactly), >2x measured wall-clock at N=200/limit=100, 20/20 MMR tests green, stash-isolated baseline-vs-candidate proof included. Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_01NQn4ZDMLEVvSwbgKEfVgwg |
||
|
|
e9f8ba7bac | test(memory): preserve significant index indentation | ||
|
|
5350afae99 | fix(memory): preserve user index content when generated views grow | ||
|
|
7f6fd2d76a | fix(memory): preserve distinct namespace and key tuples in upserts | ||
|
|
34e4bb400a |
dream(memory): #3351 fix AgentDBAdapter.store() same-key upsert orphaning (evaluated, ACCEPT-scoped) (#3352)
* dream(memory): #3351 fix AgentDBAdapter.store() same-key upsert orphaning AgentDBAdapter.store() never checked for an existing entry under the same (namespace, key) before writing. Since entry.id is always a fresh random id (generateMemoryId()), a second store() for the same logical key left the prior occupant as a permanent orphan: unreachable via getByKey(), but still live in entries/namespaceIndex/tagIndex and, for embedded entries, still a point in the HNSW index -- so search()/semanticSearch() returned stale duplicates forever. Fixed by evicting the prior (namespace,key) occupant via the adapter's own existing, already-tested delete() path before storing the new entry. Independent adversarial critique: CONFIRMED-WITH-CAVEATS. Disclosed gap: the fix covers sequential re-stores; concurrent store() calls for the same key can still race (no mutex) -- flagged as a follow-up, not fixed tonight. 4 new regression tests (agentdb-adapter-upsert.test.ts): 2/4 fail against baseline for the predicted reason, 4/4 pass against the candidate. Full @claude-flow/memory suite: 517->521 passed, 1 pre-existing unrelated failure unchanged. tsc --noEmit clean both ways. Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_01QYZ8XEAXBWp8HVni2enLcY * dream(memory): #3351 record PR #3352 in ledger Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_01QYZ8XEAXBWp8HVni2enLcY * dream(memory): #3351 post-review hardening — bulkInsert() + failure atomicity Addresses ruvnet's review on PR #3352 (2 blocking findings): 1. AgentDBAdapter.bulkInsert() bypassed store()'s same-key dedup entirely -- UnifiedMemoryService.bulkInsert() forwards to it, so a batch containing duplicate (namespace,key) values, or replacing an already-stored key, left old ids reachable via get()/query() while only keyIndex pointed at the newest id. Fixed: bulkInsert() now computes superseded ids (both pre-existing occupants and intra-batch duplicate-key losers, last entry per key wins) from a pre-mutation snapshot, and evicts them via the same evictEntry() primitive store() uses, after the batch's embeddings are safely indexed. 2. store() deleted the prior (namespace,key) occupant BEFORE validating the replacement's embedding via HNSWIndex.addPoint() (which can throw on a dimension mismatch or a full index). A rejected write therefore lost the prior value outright instead of merely failing. Fixed: addPoint() now runs first; the prior occupant is only evicted once the replacement is confirmed indexable. delete() is refactored into a shared evictEntry(id, {touchKeyIndex}) private primitive, used by delete() (touchKeyIndex: true) and by both same-key upsert paths (touchKeyIndex: false, since those callers are about to repoint keyIndex themselves). 5 new tests per the review's request: failed-replacement-preserves-prior- value, bulkInsert duplicate-key-within-batch, bulkInsert pre-existing-vs- batch replacement, a same-key replacement surviving a persisted save/ reload, and a disclosed-not-fixed concurrent-store race (documents the still-open gap rather than silently omitting it -- see PR discussion for why a per-key lock is a follow-up, not part of tonight's patch). Full @claude-flow/memory suite: 521->526 passed (+5 new), 1 pre-existing unrelated failure unchanged. tsc --noEmit clean. Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_01QYZ8XEAXBWp8HVni2enLcY * dream(memory): #3351 post-review addendum in gist/ledger, recompute witness Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_01QYZ8XEAXBWp8HVni2enLcY --------- Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
11ce88327b |
fix(memory): activate reasoningBank — wire the real embedder + correct the bridge contract (#3327 Finding A) (#3390)
Activates reasoningBank end-to-end (#3327 Finding A). - memory/controller-registry.ts: hand agentdb's ReasoningBank an embedder that satisfies its asymmetric embedQuery/embedPassage contract; adapt agentdb's mock embedder rather than passing it through; flag the zero-vector stub. - cli/memory-bridge.ts: call the real storePattern(), map agentdb's ReasoningPattern shape (approach/similarity) instead of content/score, and record the swallowed error so health can name the cause. Verified: 77/77 controller-registry tests pass; negative control (new tests vs main's source) fails 8/9, confirming the tests are load-bearing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> |
||
|
|
79529c6cf6 | fix(memory): preserve retrieval relevance in smart search results | ||
|
|
a65bdf683a |
fix(memory): pass a bare mode string to NeuralLearningSystem, not an object (#3336)
learning-bridge.ts's loadNeural() called
`new NeuralLearningSystem({ mode, ewcLambda })`, but the real constructor
signature is `constructor(mode: SONAMode = 'balanced')` — a bare string
(see @claude-flow/neural/src/index.ts and the CLI's own reference-correct
call site in memory/neural-package-bridge.ts). This never threw: SONAManager
resolves `MODE_CONFIGS[mode]`, which for an object argument coerces to the
key "[object Object]", finds nothing, and `{...undefined}` silently produces
an empty config instead of the intended mode's settings — so every
LearningBridge-driven neural session has been running with an unset,
default-less SONA config regardless of `sonaMode`/`RUFLO_INTELLIGENCE_MODE`.
`ewcLambda` was never a real constructor parameter either — each mode
carries its own fixed lambda via MODE_CONFIGS, with no override mechanism —
so it's dropped from the call rather than papered over.
Added a regression test that mocks the real `@claude-flow/neural` import
path (the existing 67 tests all inject a `neuralLoader`, which bypasses this
code path entirely — that's why this went uncaught). Confirmed the new test
fails against the pre-fix constructor call and passes with the fix.
Claude-Session: https://claude.ai/code/session_01SjxUvZnyBdwtx4Y1jKAqt6
|
||
|
|
90889f4772 |
feat(sona): default the learning mode from RUFLO_INTELLIGENCE_MODE (#3334)
* feat(sona): default the learning mode from RUFLO_INTELLIGENCE_MODE The SONA learning mode was only settable per call (`config.mode`), defaulting to `balanced` otherwise. A deployment that wants every session to learn in a specific profile — a managed desktop fleet running `research` for +55% quality, or `edge` on constrained hosts — had no way to set that default short of threading `mode` through every call site or patching a generated helper. This reads `RUFLO_INTELLIGENCE_MODE` as the fleet-wide default in both the SONA config merge (`@claude-flow/integration` sona-adapter) and the memory learning bridge (`@claude-flow/memory`). Precedence is unchanged where a caller is explicit: `config.mode` (or `sonaMode`) still wins; the env only fills the former default slot; and an unset or unrecognised value returns undefined so the code falls through to `balanced` — a typo can never silently select a profile nobody asked for. Validated against the mode enum in each package. Co-Authored-By: claude-flow <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_01MUrJdDHhQ91hwpUBQhV4fC * fix(sona): resolve sonaMode per-instance in LearningBridge, not at module load learning-bridge.ts captured sonaModeFromEnv() into a module-scope DEFAULT_CONFIG constant, evaluated once on first import — so any RUFLO_INTELLIGENCE_MODE set later in the same process (including test setup) was permanently missed. sona-adapter.ts's equivalent (mergeConfig()) already re-reads the env var on every call; this brings LearningBridge's constructor in line with that behavior, preserving the same precedence (explicit config.sonaMode > env > default). Adds regression tests for both packages (sona-adapter.ts had none previously) and registers RUFLO_INTELLIGENCE_MODE in KNOWN_ESCAPE_HATCHES per the audit script's existing requirement for operator-knob env vars outside its SCAN_ROOTS. Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_01SjxUvZnyBdwtx4Y1jKAqt6 |
||
|
|
955510695f |
fix(memory): replace the drive colon when deriving the auto memory key (#3305)
resolveAutoMemoryDir mirrors Claude Code's project key, which replaces `/`, `_` and `:` with dashes. The colon was missing, so a Windows git root of D:\projects\elearning\v3_26 produced the key D:-projects-elearning-v3-26 instead of D--projects-elearning-v3-26. A colon is not legal inside a Windows path segment, so ensureMemoryDir() failed with ENOENT and doSync() swallowed it as "Sync failed (non-critical)": the auto memory sync had never run on Windows, and reported success while doing nothing. It also wrote to a different key than Claude Code reads, so even a successful write would have been invisible. POSIX paths carry no colon, so nothing changes there. Co-authored-by: rUv <ruv@ruv.net> |
||
|
|
f13b8567de |
dream(performance): #3265 stop re-tokenizing MMR candidates that PR #3169 mostly stopped needing (evaluated, ACCEPT) (#3266)
* dream(performance): #3265 stop re-tokenizing MMR candidates that PR #3169 mostly stopped needing mmrRerank() eagerly re-tokenized every remaining candidate's content on every outer-loop pass (O(N x limit) tokenize() calls), a pattern that predates and survived PR #3169 unchanged. #3169 made embedding-cosine the preferred, now-common pairSimilarity path, so most of that tokenization was computed and then discarded. Tokens are now computed lazily and cached per-candidate, only when the Jaccard fallback is actually needed. Evaluated: tokenize() calls 400 -> 0 on a 30-candidate/limit-20 all-embedded corpus (stash-isolated: fails against real baseline, passes against candidate); vitest bench shows the candidate 5.88x faster (independently reproduced at 5.96x by an adversarial critic). Selection output is byte-for-byte identical to baseline across all-embedded/no-embedding/mixed scenarios. 473/474 full package suite both ways (1 pre-existing, unrelated environmental failure), tsc clean. Evaluated, ACCEPT. Full research (5-role parallel fan-out), evaluation receipt, adversarial critique, Darwin/Flywheel scoping, reward-hack check, and security/hive-mind scan findings in the linked issue and gist. Closes #3265 Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_01P5UJ62RVAbq8DLEEXPrwvU * dream(performance): append 2026-09-10 ledger row (#3265, #3266) Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_01P5UJ62RVAbq8DLEEXPrwvU --------- Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
e036e35dd7 |
dream(memory): #3231 wire embedding near-dup detection into MemoryConsolidator.dedup() (evaluated, ACCEPT) (#3232)
* dream(memory): wire embedding near-duplicate detection into MemoryConsolidator.dedup()
MemoryConsolidator.dedup() only ever deduplicated entries via byte-exact
SHA-256 content hashing, even though every entry already carries a
computed .embedding and the adapter's HNSWIndex (already held in scope
for removal bookkeeping) is incrementally kept in sync. Paraphrases and
reformattings of the same memory were never caught.
Adds a second pass: for hash-pass survivors with an embedding, query the
already-populated HNSWIndex for cosine-similarity neighbors above a
configurable similarityThreshold (default 0.95, matching the unwired
domain-layer consolidator's own constant), and merge using the same
keeper-selection strategies (now factored into shared selectKeeper/
mergeGroup helpers). Guarded to cosine-metric indexes only; disabled via
similarityThreshold >= 1.
Evaluation: 471/472 passing in @claude-flow/memory (1 pre-existing,
unrelated, environmental failure); baseline (git-stash-isolated source)
fails exactly the 2 new discriminating tests and passes the rest,
confirming the fix is additive and non-regressive. tsc --noEmit clean.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01H4kfasS4XkYaSGYXFLSSEG
* dream(memory): fix-forward — converge near-dup pass to a fixed point in one dedup() call
Independent adversarial critique (STEP 10) reproduced a real, bounded gap
in the prior commit: a near-duplicate cluster larger than
NEAR_DUP_SEARCH_K (8) split into multiple leftover sub-group survivors
within a single dedup() call, because each round's `consumed` bookkeeping
permanently excluded a group's keeper from further matching even though
it was still fully present in the index. 15 pairwise-identical-embedding
entries collapsed to 2 survivors (merged: 13) instead of 1 (merged: 14).
It self-healed across repeated runAll() calls (background timer /
nightlyLearner), so this was never a permanent-data-loss bug, but a
single manual dedup() call under-converged relative to its documented
"collapse duplicates" contract.
Fix: loop pass 2 to a fixed point (re-scan until a full round produces
zero merges) instead of a single scan. Always terminates — entries
strictly decrease each round that merges anything. `groups` now counts
merge operations across all rounds, which can exceed the number of
underlying duplicate clusters when one needed more than one round;
documented in the method's doc comment.
Added a discriminating regression test reproducing the critic's exact
15-entry scenario; confirmed it fails against the pre-fix single-round
code (merged: 13) and passes against this fix (merged: 14, single
survivor). Full package suite: 472/473 passing (1 pre-existing,
unrelated, environmental failure, unchanged from before this commit).
tsc --noEmit clean.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01H4kfasS4XkYaSGYXFLSSEG
* dream(memory): 2026-09-08 research gist — embedding near-dup consolidation
Full SOTA report: 5-role parallel research fan-out, ledger check with
GitHub-verified fates for the last 14 rows (3 merged since 09-03, one PR
now crossing the 14-day stale threshold for the first time this cycle),
competitor comparison (CrewAI/Mem0/Zep/LangMem/Qdrant/SemDedup), plugins
and automation scan findings, adversarial critique with a real bug found
and fixed, and witness stamp.
No gist-creation MCP tool available in this session (GitHub MCP tools
cover issues/PRs/repos, not gists) — committing to docs/dream-cycle/
instead, matching every dream-cycle night since 2026-08-14.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01H4kfasS4XkYaSGYXFLSSEG
* dream(memory): #3231 update LEDGER.md for 2026-09-08
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01H4kfasS4XkYaSGYXFLSSEG
* dream(memory): #3231 empirical receipts for dedup() near-dup pass (response to review)
Response to PR #3232's INCONCLUSIVE review, which asked for a threshold
contract rather than a smoke fixture: a contamination-checked embedding
corpus with pinned model, precision/recall including hard negatives and
cross-namespace cases, baseline vs. candidate latency/memory at realistic
cardinality, and deterministic replay + unchanged exact-dedup behavior.
Real pinned-model corpus: attempted directly against both ONNX backends
this monorepo ships. Both fail for reasons unrelated to this candidate,
reproduced on an unmodified checkout before writing anything:
- @huggingface/transformers@4.2.0: transformers.node.mjs does
`import { Tensor } from "onnxruntime-common"` against a CJS module — a
real ESM/CJS interop break under this sandbox's Node version.
- @xenova/transformers@2.17.0: pulls in sharp@0.32.6, whose native
binding (sharp-linux-x64.node) isn't present for this platform — the
same failure independently reproduced moments later by this package's
own nightlyLearner test, which falls back to mock embeddings.
Neither is fixable within this PR's scope without touching unrelated,
pre-existing native/module-resolution infrastructure. Documented in
detail at the top of the new test file rather than silently worked
around or omitted.
What's delivered instead, in
v3/@claude-flow/memory/src/consolidator-embedding-benchmark.test.ts:
- A deterministic synthetic corpus where pairwise cosine similarity is
constructed EXACTLY via vectorAtSimilarity() (Gram-Schmidt against a
random orthogonal vector), not measured after the fact — a rigorous
instrument for threshold mechanics specifically, disclosed as not
validating real-world semantic accuracy.
- Precision/recall/false-merge-rate across a 5-point threshold sweep,
every point at a deliberate margin from every corpus similarity value
after an exact-boundary collision (sweep value == corpus value) proved
float32-jitter-sensitive while writing this — documented as a finding,
not silently patched around.
- Namespace isolation: proved cross-namespace near-dup merging matches
cross-namespace hash-exact merging exactly (both pre-existing,
unscoped-by-namespace behavior — this candidate doesn't change it).
- Determinism: 3 independent runs, compared by deterministic entry KEY
(not raw id, which is randomly generated per store() and was a second
bug this file's own first draft had to fix).
- Latency/memory at N=5000 (matching this repo's own HNSW-benchmark
convention): initially measured 9.8s for the candidate pass, which
traced to an unset `ef` search parameter defaulting to efConstruction
(200) — every dedup() search traversed a 200-candidate list for a
duplicate-detection task that only needs very-close neighbors. Fixed
by passing an explicit NEAR_DUP_SEARCH_EF=32 in consolidator.ts,
re-measured at 3.7s (~2.7x), precision/recall unchanged (still exact).
Real numbers logged in the test output either way, not asserted away.
Full package suite: 478/479 passing (472 pre-existing + 7 new; same 1
pre-existing unrelated environmental failure as every prior commit on
this branch). tsc --noEmit clean.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01H4kfasS4XkYaSGYXFLSSEG
* dream(memory): #3231 add new benchmark file to CI test-ratchet baseline
CI on a2e99cf failed with "1 unexpected failing file(s): +
v3/@claude-flow/memory/src/consolidator-embedding-benchmark.test.ts".
Root-caused via the vitest JSON report artifact (test-results-ubuntu-latest,
downloaded and parsed directly, not guessed): a suite-level collection
failure, "Cannot find package '@claude-flow/security' imported from
'.../v3/@claude-flow/memory/src/agentdb-retrieval-guard.ts'" — the same
unbuilt-sibling-package gap already accepted in scripts/ci-test-baseline.txt
for 9 other @claude-flow/memory test files, including consolidator.test.ts
itself (line 95). Every file in this package fails identically in this CI
checkout state; my new file just wasn't in the baseline yet because it's
new. Not a regression this PR introduced — confirmed by the failure being
a pre-import-time module-resolution error, not a test assertion in the
new file's own logic (which passes locally in a checkout with @claude-flow/
memory's dependencies actually built: see the 6/6 local run in the prior
commit's message).
Fix: add the new file to the baseline, alongside its 9 memory-package
siblings already there, matching this repo's own established convention
for this exact gap rather than working around it some other way.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01H4kfasS4XkYaSGYXFLSSEG
* dream(memory): #3231 baseline 2 more federation/gateway plugin test files
CI on
|
||
|
|
755b6720c5 |
dream(intelligence): #3159 LearningBridge.consolidate() reward-blind fix (evaluated, ACCEPT) (#3160)
LearningBridge.consolidate() reported every completed trajectory's reward as a hardcoded 1.0, regardless of the underlying insight's actual quality. Now resolves the real confidence via backend.getByKey(namespace, key) — the entryId flowing through this bridge is the caller's key, not the backend's internal id, a distinction the round-1 fix got wrong and an adversarial critic caught before this PR. Baseline 56/56 -> candidate 62/62 tests; full package 464/465 (1 pre-existing environmental failure, unrelated). Also recovers 9 nights (2026-08-24..2026-09-01) of missing ledger rows — pipeline ran to completion each night but the ledger-append step silently failed, same pattern as the 08-14..08-19 gap recovered on 08-19. Claude-Session: https://claude.ai/code/session_014pTYiv93Ft6xAN8FAaWH5s Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
fde5b3b88b |
dream(memory): #3118 wire HybridBackend's dead weights field into weighted-RRF fusion (evaluated, ACCEPT) (#3119)
* dream(memory): #3118 wire HybridBackend's dead weights field into real weighted-RRF fusion HybridQuery.weights was computed and then discarded by queryHybrid's 'union' strategy (combineUnion did a plain set-union, no score math, and no caller ever set weights either). Adds combineWeighted: per-arm-weighted reciprocal-rank fusion matching the pattern documented for Qdrant/ Weaviate/Azure AI Search. Evaluated via deterministic Vitest, baseline isolated via git stash: the weight-sensitivity test fails on baseline, passes on candidate. 461/462 full memory-package suite green (1 pre-existing, unrelated environmental failure, confirmed identical on baseline). tsc --noEmit clean. Also backfills docs/dream-cycle/LEDGER.md rows for 2026-08-20..23 (genuine no-run gap) and 2026-08-24..27 (ran to completion but stuck on unmerged draft PRs, not a repeated ledger-append failure — see issue #3118 §11). Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_01AjuAxfhZi6eZXnLbLC14Ay * fix(memory): validate weights + deterministic tie-break; port #3104 lockfile fix Per ruvnet's review on #3119: - weighted RRF fusion previously had undefined ranking semantics for malformed weights (NaN poisons the sort comparator, negative/Infinity invert or swamp the intended ordering). Each weight component now validates independently (finite, >= 0) and falls back to its own documented default otherwise, same degradation as an omitted weights field already had. - rrf ties now break deterministically by entry.id (explicit secondary sort key) instead of relying on Array.sort's stability plus Map insertion order as an undocumented side effect. - 4 new tests: 3 malformed-weight fallback cases + 1 genuine-tie (weights: {semantic:0, structured:0}) deterministic-order case. Also ports PR #3104's fix verbatim (v3/pnpm-lock.yaml: @claude-flow/mcp specifier ^3.0.0-alpha.9 -> 3.0.0-alpha.10, matching the CLI manifest's exact pin) to unblock the install-dependent CI gates this PR needs to actually execute (issue #3101, also flagged in the review). Root-level npm ETARGET (issue #3095, package-lock.json) is a separate, still-open, maintainer-flagged issue with no proposed fix yet -- not addressed here. Validated: `corepack pnpm install --frozen-lockfile --lockfile-only` and `--ignore-scripts` both succeed from v3/; full @claude-flow/memory suite 465/466 (same 1 pre-existing unrelated env failure); tsc --noEmit clean. Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_01AjuAxfhZi6eZXnLbLC14Ay * fix(test): stop hybrid-backend's rrf tie-break test from flaking on id/key mismatch The tie-break test asserted a hardcoded key-alphabetical expected order, but combineWeighted's tie-break is entry.id.localeCompare(), not key. generateMemoryId() produces `mem_<ms-timestamp>_<random>` — the two fixture entries are frequently created in the same millisecond, so which id sorts first is decided by the random suffix, with no fixed relationship to which key sorts first. Confirmed empirically: 1/5 runs failed before this fix, 10/10 pass after. Fix: capture each entry's actual generated id in beforeEach, and compute the test's expected order from those ids (matching the code's actual documented contract) instead of assuming id-order equals key-order. Full @claude-flow/memory suite still 475/475, tsc clean. Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_01RYP825phHMjPRmmjkcAWpq --------- Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
2d6227005e |
dream(performance): #3093 wire productQuantizeDistance() into HNSW search path (evaluated, ACCEPT) (#3094)
* dream(performance): #3093 wire productQuantizeDistance() into HNSW search path Quantizer.productQuantize()/productQuantizeDistance() correctly implement codebook-aware PQ encoding and distance, but HNSWIndex.distance()/ distanceOptimized() never called productQuantizeDistance() - generic cosine/euclidean/dot/manhattan distance was computed directly on raw PQ centroid-index arrays, which is numerically meaningless. Zero callers of productQuantizeDistance() existed anywhere in v3/ before this change. Wires the dispatch in, guarded by a new isValidPQEncoding() check to avoid crashing/corrupting on vectors added before PQ codebook training completes (a separate, disclosed, pre-existing limitation not fully solved here - see hnsw-index.ts comments and docs/dream-cycle/dream-gist-2026-08-25.md). Measured on a deterministic synthetic corpus: recall@10 recovers from 0.097 (pre-fix) to 0.270 (post-fix), independently reproduced by an adversarial critic across 3 additional corpus shapes. Full evaluation receipt, hypothesis, and adversarial critique in the linked gist and issue #3093. Also backfills the 2026-08-24 ledger row (branch/issue/PR existed but the row was never appended - recovery per this pipeline's STEP 1 convention). Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_01Aor8qaXa8T3ZCGgRmjc4VG * dream(performance): append 2026-08-25 ledger row (#3093/#3094) Follow-up to a8b527105 now that the issue and PR numbers exist. Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_01Aor8qaXa8T3ZCGgRmjc4VG --------- Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
13880e3aa4 |
fix(memory,daemon): stop destroying a user index, honour autoStart:false, and finish the sibling disclosure (#3282)
Three from the current issue backlog, all confirmed in source before touching anything, and all with a test that fails without the fix. #3224 — curateIndex() rebuilt MEMORY.md from the bridge's own topic files and overwrote whatever was there. The #1556 guard only skips the write when NOTHING matched, but the bridge writes the first topic file itself, so after the first insight the guard stops applying and the rebuild replaces a hand-maintained index with a stub: 75 curated lines and 49 links down to 6 in the reported case. The bridge only knows its own topic files, so everything else looks like nothing to it. A curate may now grow or reorder the index and never shrink it; when the generated view is smaller it is written beside the file as MEMORY.generated.md and the bridge emits index:preserved rather than going quiet. #3278 — the autostart disable check read claude-flow.config.json with the key daemon.autostart, while init generates .claude/settings.json with claudeFlow.daemon.autoStart. A different file AND a different capital S, so the one setting a fresh project actually ships was never consulted. It is written false under the comment "Opt-in only — prevents unintended token consumption (#1427, #1330)", which the runtime then ignored. Both files and both spellings are now read: someone who wrote autostart false anywhere sensible meant it. #3228 (half) — 3.41.1 disclosed the sibling AgentDB store from `memory list` only. retrieve, search and an empty list kept returning a clean negative while the rows sat in the file this interface does not read; the reported Windows install has 31,673 rows in that other store answering found:false. A confident negative is worse than an error, because nothing prompts anyone to look further. That was a gap in my own fix, not a new defect. Verified the tests are worth having by reverting each fix and re-running: #3224 fails 1/2, #3278 fails 2/4, and all six pass again restored. Claude-Session: https://claude.ai/code/session_013u4pmL9ZUAXb6usVQgNo67 |
||
|
|
277c7bc03a |
dream(memory): #3168 wire embedding-cosine into SmartRetrieval's MMR step (evaluated, ACCEPT) (#3169)
* dream(memory): wire embedding-cosine into SmartRetrieval's MMR step (evaluated, ACCEPT) smart-retrieval.ts's MMR diversity re-ranking used token-Jaccard text overlap as its "similarity to already-selected" term, even though memory-initializer.ts's searchEntries() already computes real ONNX-embedding cosine similarity for the primary relevance score and discards it before returning. 2025-2026 production practice (LangChain's reference maximal_marginal_relevance, Qdrant's native Mmr query shipped Sept 2025, Weaviate's MMR reranker shipped in 1.37) universally uses embedding-cosine for this term; token overlap misses low-token-overlap paraphrases embeddings correctly flag as near-duplicates. Threads the embedding through: searchEntries()'s two live compute sites (RaBitQ rerank, brute-force SQL) now return it instead of discarding it; the two CLI/MCP bridge mappers (memory-tools.ts, commands/memory.ts) pass it through; SearchCandidate gains an optional `embedding` field; mmrRerank uses cosine when both candidates have one, falling back to token-Jaccard otherwise (existing callers/tests without embeddings are unaffected). controller-registry.ts's separate toCands()/applyMMR path had the same gap for a different reason (embedding available on r.entry.embedding but never copied) — fixed the same way. Evaluated via deterministic Vitest, zero LLM calls, $0 cost. New discriminating test: a low-token-overlap paraphrase (near-1.0 cosine to the seed) vs. a genuinely different topic (near-0 cosine). Baseline (git stash-isolated): picks the paraphrase second (Jaccard can't tell "low overlap because paraphrase" from "low overlap because unrelated"). Candidate: correctly picks the different topic second. Full @claude-flow/memory suite: 460/461 passing identically with/without the candidate (1 pre-existing chmod-based environmental failure, same class documented since 2026-08-15). tsc --noEmit: zero new errors (verified @claude-flow/cli's 455 pre-existing errors, from unbuilt workspace packages, are identical with and without this diff). Darwin: skipped, scope mismatch (correctness/similarity-metric fix with a discriminating unit test, not a continuous parameter with a gold-labeled corpus). Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_01Qho5K4p5ACBt4yzCWjkBGe * dream(memory): address review remediation — split CI, real benchmark, hardening Response to ruvnet's REJECT review on #3169: 1. Split — dream-cycle-backlog-guard.yml moved out to #3205; this branch now carries only the MMR fix, rebased onto main (which already includes the merged #3203 CI fix). 2. Real benchmark (new src/mmr-benchmark.test.ts): 18-doc/6-topic labeled corpus (1 canonical + 2 low-token-overlap paraphrases per topic), run through the actual smartSearch/mmrRerank code, swept across mmrLambda in {0.3, 0.5, 0.7, 0.9} rather than one favorable value. Honest finding: at diversity-heavy lambda, candidate's recall/nDCG drop sharply vs. baseline, because cosine correctly suppresses same-topic near-duplicates that Jaccard fails to detect at all (and so "accidentally" keeps full recall). At smart-retrieval.ts's own default (lambda=0.7), recall@6/nDCG@6 are identical to baseline (1.000/0.777 both) while topic-diversity improves 0.472->0.667 and ground-truth duplicate-rate drops 0.289->0.200. Reports latency (sub-ms both paths at this corpus size) and a memory-overhead estimate. 3. Malformed/dimension-mismatch: found and fixed a real bug while writing these cases. A NaN/Infinity-poisoned embedding component reached cosineSimilarity unguarded; the poisoned NaN score meant `mmr > bestMmr` was never true (NaN comparisons are always false in JS), which could silently break MMR's selection loop and under-fill results below the requested limit. Added isWellFormedEmbedding() so malformed/empty embeddings fall back to token-Jaccard, same as absent/mismatched ones. 3 new cases (NaN/Infinity, empty array, explicit dimension-mismatch) plus a test mirroring the two real CLI/MCP output whitelists (memory-tools.ts:559-569, commands/memory.ts:633-639) to assert `embedding` cannot appear in either shape. 4. Determinism: new test runs the same input through smartSearch 5 times concurrently, asserts byte-identical result ordering every time, including a genuine same-embedding tie. Full @claude-flow/memory suite: 465/466 (1 pre-existing, unrelated environmental failure). tsc --noEmit: zero errors. Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_01Qho5K4p5ACBt4yzCWjkBGe --------- Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
8a85001942 |
fix: Windows CI build, dead agentdb controller exports, memory driver doctor check
- #2992: pin windows-latest -> windows-2022 for the Build V3 matrix job. windows-latest moved to VS2026, which node-gyp can't detect, breaking native builds for hnswlib-node and better-sqlite3. - #2977: remove dead agentdb import attempts in controller-registry.ts for 8 exports no installable agentdb range provides. Promote the working tieredMemoryFallback/createConsolidationStub implementations to first-class for hierarchicalMemory/memoryConsolidation; the other 6 controllers (semanticRouter, mutationGuard, attestationLog, gnnService, rvfOptimizer, guardedVectorBackend) have no fallback and now return null directly instead of attempting an import that never resolves. The consolidation stub now reports source:'stub' and an explicit note so agentdb_consolidate reads as "did not run" rather than "nothing to do". - #2968: add a read-only doctor check (checkMemoryPersistenceDriver) that reports whether the active SQLite driver is native better-sqlite3 (durable, WAL-capable) or the sql.js fallback (silently drops wal_checkpoint writes), using the table-count signal from the issue (~47 native vs ~10 fallback). Warns, never fails; does not touch install behavior. #2990 (MCP HTTP transport protocolVersion/tools-list/IPv6 bind) required no code change — all three fixes are already present on main; the bug in published ruflo/@claude-flow/cli only persists because no release has been cut since they landed. #3002 (ruvocal hidden-tab stream freeze) also required no code change — already fixed on main. Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_018ZkgSrVRWNMcXmaFiMZ7Z8 |
||
|
|
41efca8be3 |
dream(memory): #3056 hybridSearch reachable via explicit opt-in (evaluated, ACCEPT-scoped) (#3057)
* dream(memory): #3056 hybridSearch reachable via explicit opt-in without memoryService The ADR-125 Phase 5 three-arm (dense+sparse+entity) RRF/MMR fusion controller was fully built and tested but unreachable from any production call site: its explicit-enable config override worked at the isControllerEnabled() gate but the createController() factory still unconditionally required a hand-built UnifiedMemoryService, silently returning null otherwise. Falls back to the existing this.backend when it type-guards as AgentDBAdapter-compatible, reachable only via explicit controllers: { hybridSearch: true } -- default auto-enable behavior is unchanged. New deterministic $0 benchmark quantifies the feature's actual retrieval-quality effect for the first time (previously only functional/unit tests existed): +0.267 aggregate recall@10, with a disclosed, statistically significant regression on pure-paraphrase queries where fusion noise dilutes an already-perfect dense signal. Independent adversarial critic (fresh subagent): CONFIRMED-SAFE, reproduced bit-for-bit. 75/75 tests passing in touched files, 458/459 in the full package (1 pre-existing environmental failure, unrelated). Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_016T1JRz8NBeGGmxQJVPReWa * dream(memory): #3056 update ledger with 2026-08-14..18 nights + PR #3057 Reconstructs the v2 live-entries table from PR/issue history since each night's own LEDGER.md edit lives only on its unmerged branch and never reaches main (0% merge rate). Adds tonight's row (memory, hybridSearch reachability fix, ACCEPT scoped, witness b28714fb...). Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_016T1JRz8NBeGGmxQJVPReWa --------- Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
1d365d4a65 |
fix: silent memory-write loss + daemon lock cwd bypass (#2887, #2878, #2877) (#2966)
Three independent data-integrity/correctness bugs in the memory and daemon subsystems: #2887 — agentdb_hierarchical-store reported success:true for writes that were never persisted. Root cause: agentdb dropped its HierarchicalMemory export at 3.0.0-alpha.17, so every call was silently landing on an in-process-only TieredMemoryStore fallback. The fallback now writes through to a `tiered_memory` SQLite table when given a db handle, and the bridge refuses to report success for a write that isn't durable — it names the fallback controller and reason instead. agentdb_health now reports the real persisted row count so a claimed write vs. an empty table is visible. #2878 — concurrent sql.js writers lost updates while reporting success (measured 10/12 lost in a 12-way concurrent repro), because storeEntry, getEntry, deleteEntry, applyTemporalDecay, and ensureSchemaColumns did unlocked whole-image read-modify-write against memory.db. All five now run under the existing withMemoryDbLock primitive (previously only used by purgeNamespace). Made the lock reentrant via AsyncLocalStorage, since every mutator calls ensureSchemaColumns internally and a plain O_EXCL lock isn't reentrant. Also fixed a path-normalization bug where different callers spelled the same db path differently and so serialized against nothing. #2877 — the daemon lock/PID file was keyed to raw process.cwd(), so `daemon start` from a project subdirectory span its own lock/PID pair instead of contending with one from the project root, bypassing the #2407/#2484 dedup. Added resolveDaemonProjectRoot(), which walks up from cwd to the nearest directory carrying a real Ruflo marker (not just any package.json, so independently-initialized nested sub-projects in a monorepo keep their own daemon), stopping at a .git boundary so the walk can't escape into an unrelated ancestor project. Wired into every daemon command that previously used process.cwd() directly. Tests: 123 passing across affected suites (controller-registry.test.ts, tiered-memory.test.ts, hierarchical-store-durability-2887.test.ts, memory-concurrent-write-loss-2878.test.ts, daemon-autostart.test.ts). Both packages typecheck clean. Pre-existing failures in unrelated suites (ruvector wasm bindings, agenticow, memory-search-recall-2558) reproduce identically with these changes reverted — confirmed not regressions. Fixes #2887, #2878, #2877 |
||
|
|
f074987ea0 |
feat(security): implement ADR-377 — AgentDB Retrieval Security Layer (#2874)
Implements all 3 phases of ADR-377 (ruvnet/ruflo#2516, tracked in #2873): AgentDB's retrieval and write paths had zero certified defenses against memory poisoning — SMSR (arXiv:2606.12703) shows 93-100% undefended attack success. All three phases are off by default; enabling each is opt-in via env flag until independently benchmarked, per the ADR's own gate criteria. Phase 1 — AgentDbRetrievalGuard (@claude-flow/memory) - New `agentdb-retrieval-guard.ts`, wired into `AgentDBBackend.search()` (covers `query()`'s semantic path too, since it calls `search()` internally). Reuses `@claude-flow/security`'s `ToolOutputGuardrail` (ADR-131) for the actual OWASP LLM01/LLM08 pattern scan rather than duplicating it — `@claude-flow/memory` now depends on `@claude-flow/security` (no cycle: security has zero workspace deps). - Size gate + guardrail scan per retrieved chunk. Flag-only by default; `CLAUDE_FLOW_RETRIEVAL_GUARD_STRICT=true` drops unsafe/oversized chunks instead of just annotating them. Both flags off by default (`CLAUDE_FLOW_RETRIEVAL_GUARD=true` to enable scanning at all). Phase 2 — MemoryPoisonForensics (@claude-flow/hooks) - New `workers/memory-poison-forensics.ts`: rolling-window z-score anomaly detection on write-interval and content-length features per (agentId, namespace), reproducing the Forensic Trajectory Signatures (arXiv:2606.30566) shape (behavioral features on write *sequences*, not content). Opt-in `HookEvent.PostToolUse` handler for memory-write tools; `CLAUDE_FLOW_POISON_FORENSICS=0` disables recording. - NOT wired into any of this repo's three separate "worker" dispatch systems (hooks' own workers/index.ts codebase-analyzers, @claude-flow/swarm's worker-dispatch.ts 12-trigger table, or the CLI's scheduled daemon) — @claude-flow/swarm is a deliberately zero-workspace-dependency package and adding hooks there would break that property; picking the wrong one of three ambiguous dispatch tables seemed worse than leaving that integration as an explicit follow-up. See the file header for detail. Phase 3 — McpCallerIdentity (@claude-flow/security) - New `mcp-caller-identity.ts`: per-invocation Ed25519-signed capability tokens (callerId + toolName + nonce + 30s TTL by default), native node:crypto sign/verify following the same pattern already used by `@claude-flow/browser`'s witness-signer.ts (reimplemented rather than cross-imported — a security-primitives module depending on the browser package would be a backwards layering dependency). - Standalone issue/verify API; deliberately NOT wired into `AgentAuthorizationPropagator.checkToolCall` (ADR-144) or any tool dispatcher — this repo has at least 3 distinct `ToolRegistry` implementations and guessing which is authoritative risked silently wiring the wrong path. `CLAUDE_FLOW_MCP_CALLER_AUTH` defaults to disabled, matching the ADR's own text: key distribution needs a follow-on ADR before this ships enabled. Deviations from the ADR's guessed file paths/class names (documented inline where relevant): the ADR was written against aspirational paths (`agentdb/retrieval-guard.ts`, a `BackgroundWorker` interface, `SafeExecutor`) that don't match the real repo layout — implementation targets the actual `AgentDBBackend`, the actual worker systems, and the actual `AgentAuthorizationPropagator`/tool-registries respectively. Tests: 31 new tests across the three packages (9 + 11 + 11), all passing; full existing suites re-run clean (memory 451, hooks 145, security 570 — zero regressions). |
||
|
|
d012042800 |
feat: review-driven upgrades — perf, security, SOTA capabilities (6-agent concurrent implementation) (#2547)
* chore(arch): untrack the prepublish plugin mirror — build artifact, not source
v3/@claude-flow/cli/plugins/ is regenerated by prepublishOnly from
plugins/ruflo-metaharness/ at publish time. Keeping it committed caused
silent drift between publishes (4 files diverged this week alone) and
every source edit required a manual mirror sync. npm pack still bundles
it — the files array + prepublish copy are unaffected by gitignore.
Co-Authored-By: RuFlo <ruv@ruv.net>
* feat(gaia): submission integrity checklist — fail-closed pre-submit audit (Berkeley RDI hardening)
Adds a 4-part integrity section to the gaia-validate pre-submit gate,
motivated by UC Berkeley RDI's 'Agents' Last Exam' (April 2026), which
gamed all 8 major agent benchmarks to near-100% without solving tasks.
- scripts/gaia-integrity.mjs: (A) answer-key-shaped path reads outside
the sanctioned dataset dir — FAIL-CLOSED exit 2; (B) eval()/new
Function()/exec-of-non-literal strings in gaia-bench runner code
paths — FAIL-CLOSED exit 2; (C) judge-prompt-injection markers in
produced answers/trajectories — WARN; (D) provenance stamp (results
+ git SHA + dataset content hash) written for gaia-submit to embed.
- --allow-integrity-override suppresses the exit code but records
'overridden: true' in the stamp — never silent.
- --self-test plants a fake answer-key read, an eval-of-task runner,
and injection markers in temp fixtures and proves fail-closed/pass/warn.
- gaia-validate.md: new check 7 documenting the checklist + flags.
- gaia-submit.md: package now embeds integrity.json under the Ed25519
witness manifest (tamper-evident attestation); stale/failed stamps block
packaging.
- smoke-gaia.sh: 3 new steps (script wired, self-test green, repo scan
clean); plugin bumped to 0.5.0.
Co-Authored-By: RuFlo <ruv@ruv.net>
* perf(cli): lazy ONNX embedder init + local-first ruvector resolution
Fix 1 — lazy ONNX init (measured, biggest win):
neural-tools.ts had a module-level try/catch with TOP-LEVEL AWAIT that ran
`await import('ruvector')` + `initOnnxEmbedder()` + a probe embed at import
time. Because mcp-client statically imports neural-tools, this added the
full ONNX startup to every CLI command. The block is now a memoized
`ensureEmbeddings()` (module-level promise guard) invoked from
generateEmbedding() and from the three handlers that report the provider
without embedding (neural_compress / neural_status / neural_optimize), so
degraded/fallback semantics and provider reporting are byte-identical.
The probe embed moved inside ensureEmbeddings() — it still guards the
ADR-086 type-load-success-but-runtime-fails trap, but only on first use.
Measured (warm, darwin-arm64):
node bin/cli.js --help 0.50s -> 0.09s
node bin/cli.js status 0.64s -> 0.24s
import(mcp-client.js) 438ms -> 30ms
"Loading ONNX model" no longer appears on non-embedding commands;
appears exactly once on first embed (neural_predict / memory search).
Fix 2 — ruvector pin + local-first resolution:
browser-session-tools.ts pinned `npx -y ruvector@0.2.25` while 0.2.27 is
what the package installs, forcing cold npx downloads of a second version
(4 per browser session). The pin is now 0.2.27 and a memoized
resolveLocalRuvectorCli() (createRequire + package.json bin walk) spawns
`node <local-cli>` directly, falling back to the npx pin only when no
local install exists.
While verifying the 0.2.27 subcommand surface (required before bumping),
found the trajectory-* flags passed here were never valid on 0.2.25 OR
0.2.27 (`--session-id/--task/--args/--verdict` vs the real
`--context/--agent`, `--action/--result`, `--success/--quality`) — every
trajectory call exited with commander "unknown option", same bug class as
the #2015 `rvf create --kind` fix documented in this file. Flags are now
mapped correctly; browser_session_record and browser_session_end verified
end-to-end (rvf create + trajectory-begin/step/end + rvf compact all pass).
Fix 3 — lazy heavy MCP tool groups: profiled and NOT converted.
Per-module timed dynamic imports of all 36 tool modules show neural-tools
was 469.6ms and every other group is 0.3-5.5ms (hooks-tools 3.5ms,
agentdb-tools 2.5ms, embeddings 0.9ms, wasm-agent 0.6ms). After fix 1 the
whole registry builds in ~30ms; converting handler dispatch to lazy
import() would add risk for <6ms of residual win, so mcp-client.ts is
intentionally untouched.
Validation:
- tsc build clean
- plugins/ruflo-metaharness/scripts/test-mcp-tools.mjs: 171/171 passed
- memory search / neural predict still work; ONNX loads lazily then
Co-Authored-By: RuFlo <ruv@ruv.net>
* security(deps): lift OTel floor-became-ceiling pins — core >=2.8.0, otlp family >=0.220.0
The exact pins @opentelemetry/{core,resources,sdk-trace-base}@1.25.1 and
the otlp exporter/transformer family@0.52.1 (root + ruflo wrapper
overrides) were added in #1997/#2112 as a 'fewer-knobs-for-arborist'
defense against the npm arborist Invalid Version crash (empty-version
placeholder from optionalDependencies/peerDependencies overlap). They
were never API-compat pins — but they became a ceiling that forces the
tree onto @opentelemetry/core <2.8.0, which npm audit flags for
GHSA-8988-4f7v-96qf (unbounded memory allocation in W3C Baggage
parsing), and they blocked every upstream fix.
Convert to floors while keeping the lockstep families coherent:
- stable line: core / resources / sdk-trace-base -> >=2.8.0
- otlp line: sdk-node, exporter-prometheus, the three
exporter-trace-otlp-* packages, otlp-exporter-base,
otlp-grpc-exporter-base, otlp-transformer -> >=0.220.0
(sdk-node@0.220.0 declares exactly core@2.9.0 + otlp@0.220.0, so the
floors resolve to one mutually consistent set; verified in both the
root lockfile and a fresh ruflo/ resolution: core 2.9.0 everywhere,
otlp 0.220.0 everywhere.)
The arborist defense is preserved — every package in both families is
still forced to a single resolution via overrides; the override set is
now broader (whole otlp family at root too), which gives arborist fewer
ambiguous nodes than before, not more.
Also adds the exporter family overrides to the root manifest so root
and the published ruflo wrapper stay aligned (#2112 lesson: root
overrides do not propagate to the published wrapper).
Validation:
- root: npm audit --omit=dev 30 moderate -> 0 vulnerabilities
- ruflo: npm install --package-lock-only succeeds, 0 vulnerabilities
- runtime probe: new NodeSDK({}) via @opentelemetry/sdk-node@0.220.0
with core@2.9.0 loads and exposes start(); OTLPTraceExporter loads
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3
* security(deps): npm audit fix on v3 workspace lock — grpc-js, hono/node-server, brace-expansion
Plain `npm audit fix --omit=dev --package-lock-only` (no --force) on the
v3 npm workspace lockfile. Clears the three targeted advisories:
- @grpc/grpc-js 1.14.3 -> 1.14.4 GHSA-5375-pq7m-f5r2 (+GHSA-99f4-grh7-6pcq)
- @hono/node-server 1.19.9 -> 1.19.14 GHSA-wc8c-qw6v-h7f6 (+GHSA-92pp-h63x-v22m)
- @isaacs/brace-expansion 5.0.0 removed/deduped GHSA-7h2j-956f-4vf2
Audit summary: 82 vulnerabilities (2 low, 56 moderate, 24 high)
-> 55 vulnerabilities (50 moderate, 5 high).
The remainder needs --force / dependency swaps and is out of scope for
this pass.
Note: the reify was run with the two pnpm-style `workspace:*` devDep
specs (plugin-agent-federation, plugin-iot-cognitum) temporarily
substituted with the registry pins the lockfile already records
(@claude-flow/shared@3.0.0-alpha.8, @claude-flow/security@3.0.0-alpha.10),
because npm's arborist does not support the workspace: protocol; the
manifests themselves are unchanged. The v3 workspace is otherwise
pnpm-driven (`pnpm -r build`).
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3
* security(deps): align agentdb floor in @claude-flow/memory — ^3.0.0-alpha.17
Root overrides force agentdb >=3.0.0-alpha.17, but @claude-flow/memory
declared ^3.0.0-alpha.16, so its nested/published tree could still
resolve alpha.16 (the #2112 lesson: overrides do not propagate to
nested or published trees). The v3 pnpm lock indeed had memory pinned
to agentdb 3.0.0-alpha.16 — bumping the package's own floor makes both
branches resolve the same version regardless of the consumer's
override set.
pnpm-lock.yaml is regenerated by `pnpm install`; besides the
agentdb 3.0.0-alpha.16 -> 3.0.0-alpha.17 move under memory, it also
reconciles previously committed manifest bumps (metaharness family)
that had drifted from the stale lock.
Verified: `npm ls agentdb` from root shows a single deduped
agentdb@3.0.0-alpha.17 across direct, @claude-flow/memory,
@claude-flow/neural, and agentic-flow branches.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3
* security(deps): correct FEDERATION_BIND_HOST doc default — 127.0.0.1 (ADR-166 Phase 3d)
The bin.ts header JSDoc still advertised `default: 0.0.0.0`, but the
code (makeContext) has defaulted to 127.0.0.1 since the ADR-166
Phase 3d loopback-by-default hardening. Doc-only change.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3
* fix(memory): drop vitest-4 style vi.fn generic that breaks tsc build
The hoisted vitest 1.x types Mock as Mock<Args extends any[], Returns>,
so the single-generic vi.fn<SearchFn> form fails the package build
(pre-existing baseline failure). Annotate the variable instead — the
inferred mock signature is identical.
Co-Authored-By: RuFlo <ruv@ruv.net>
* perf(memory): batch embeddings in the migration import path
MemoryMigrator.processBatch batched entries (batchSize=100) but then
awaited this.embeddingGenerator(content) ONE ENTRY AT A TIME inside the
loop — N sequential ONNX inferences per batch on the
memory_import_claude hot path.
Now:
- New BatchEmbeddingGenerator type ((contents: string[]) =>
Promise<Float32Array[]>) accepted as an optional 4th constructor /
factory param — one true batch call per migration batch when the
embedder supports it (e.g. bge-embedder's single padded forward pass).
- Fallback: bounded concurrency over the single-text generator
(MigrationConfig.embeddingConcurrency, default 8 — never unbounded;
set 1 to restore sequential behavior).
- If the batch call fails, falls back to per-entry embedding so one
backend hiccup doesn't strand the batch.
Per-entry error semantics preserved: validation failures skip, store
failures fail, embedding failures warn and store the entry without a
vector — one bad entry never fails the batch.
Measured (200 synthetic entries, 5ms simulated single-embed latency):
sequential 1220ms -> concurrency-8 156ms (7.8x) -> true batch 115ms
(10.6x).
Co-Authored-By: RuFlo <ruv@ruv.net>
* feat(memory): temporal validity on hierarchical memory (Zep/Graphiti-style)
Facts in hierarchical memory can now carry validity windows and are
INVALIDATED on conflict instead of overwritten:
- New TieredMemoryStore module (@claude-flow/memory) promotes the inline
controller-registry stub to a first-class, tested store with optional
validFrom / validUntil (ISO) + supersededBy fields.
- store accepts supersedes=<entryId|key>: the old entry is stamped
validUntil=now + supersededBy=<newId> and archived — never deleted.
- recall filters temporally-invalid entries (expired, superseded, or
not-yet-valid) by default; includeExpired=true is the audit escape
hatch.
- Backward compatible: entries without the fields behave exactly as
before (always valid); legacy store(key,value,tier) / recall(query,
topK) call shapes unchanged; same-key stores still overwrite; the
bridge's real-vs-stub detection signal (getStats+promote) is
preserved.
- CLI bridge passes the new optional fields through
bridgeHierarchicalStore/-Recall. On the native agentdb
HierarchicalMemory backend, validFrom/validUntil ride in metadata and
are filtered at recall; supersedes is reported as unsupported there
(no public update API) rather than silently dropped.
- MCP inputSchemas for agentdb_hierarchical-store (validFrom,
validUntil, supersedes) and agentdb_hierarchical-recall
(includeExpired) expose the fields to agents, with ISO-8601
validation.
Tests: supersede flow (including same-key supersede preserving
history), expired + not-yet-valid filtering, includeExpired escape
hatch, legacy entries untouched, unparseable timestamps fail open.
Co-Authored-By: RuFlo <ruv@ruv.net>
* feat(routing): confidence-gated tier escalation — hooks_model-verify ($0 post-generation verifier)
ADR-026/143 classify BEFORE generation only. This adds the 2026-SOTA
post-generation gate: attempt the cheap tier, verify the output with
CHEAP structural signals (no LLM call), escalate only on failure.
- src/ruvector/output-verifier.ts — pure verifier: empty/truncated
output, refusal patterns, degenerate repetition, unbalanced
delimiters, and a real syntax parse for code/JSON tasks (TypeScript
transpileModule diagnostics / JSON.parse, graceful degradation when
typescript is absent). Returns {confident, reasons[], suggestedTier,
suggestedModel, escalate}; ladder haiku→sonnet→opus, tier 2→3.
- hooks_model-verify MCP tool (hooks-tools.ts, surgical) — wraps the
verifier and feeds the verdict into the SAME learning stream as
hooks_model-outcome (ModelRouter.recordOutcome: success when
confident, escalated when not) so the Thompson priors learn which
task shapes the cheap tier fails on. A dedicated tool (not a verify
mode on hooks_model-outcome) because verify is a mid-loop decision
point returning a verdict the agent acts on, while outcome is a
terminal write — the sequence is route → generate → verify →
(escalate) → outcome.
- __tests__/output-verifier.test.ts — refusal/truncation/parse/
escalation-ladder coverage + MCP handler tests (18 tests).
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3
* feat(federation): A2A Agent Cards — spec-1.0 discovery adapter over the bespoke federation schema
Implements the Agent2Agent (A2A, Linux Foundation) Agent Card layer as an
ADAPTER over the existing federation registration/discovery shapes. Cards
only — A2A Tasks/messaging are deliberately out of scope this iteration.
Spec: A2A Protocol 1.0.0 (a2a-protocol.org; schema source of truth
specification/a2a.proto in a2aproject/A2A). Required AgentCard fields per
spec 4.4.1: name, description, supportedInterfaces, version, capabilities,
defaultInputModes, defaultOutputModes, skills. Well-known discovery path
per 8.2 + IANA registration: /.well-known/agent-card.json.
- src/a2a/agent-card.ts: toAgentCard() maps FederationManifest -> spec-
compliant card (agent types -> AgentSkills; federation endpoint -> open-
form RUFLO-FEDERATION AgentInterface; bespoke identity rides in a spec
4.6 extension urn:ruflo:federation:manifest:v1 for lossless round-trip);
validateAgentCard() enforces the 1.0 required-field shape;
fromAgentCard() maps a remote card into a FederationNode — ALWAYS
TrustLevel.UNTRUSTED (cards are self-asserted metadata; trust is earned
via the normal handshake + TrustEvaluator path).
- src/a2a/well-known.ts: minimal node:http endpoint serving GET/HEAD on
the exact well-known path with spec 8.6 Cache-Control + ETag/304.
Binds 127.0.0.1 by default and REFUSES non-loopback binds without an
explicit allowNonLoopback opt-in (ADR-166 posture preserved — no
loosening of federation bind or auth).
- src/a2a/consume.ts: fetchAgentCard (injectable fetch, timeout, size cap,
structural validation) + consumeAgentCard registering the peer into
DiscoveryService so A2A peers appear in federation discovery.
- DiscoveryService: new 'a2a-card' discovery mechanism +
registerExternalPeer() (refresh-not-replace preserves trust state).
- plugin.ts: opt-in wiring via config.a2aCard/a2aCardPort/a2aCardHost;
bind failure degrades gracefully; server closed on shutdown.
- 40 new unit tests incl. golden-file card fixture
(__tests__/fixtures/a2a-agent-card.golden.json), foreign-card mapping,
round-trip, loopback guard, and a live serve->consume e2e over HTTP.
- plugin.test.ts: fixed pre-existing stale assertion (10 -> 11 CLI
commands; 'federation trust elevate' was added without updating the
count) — baseline suite failed before this change.
Build clean; 600/600 tests green.
Co-Authored-By: RuFlo <ruv@ruv.net>
* feat(intelligence): execution-state-tree retrieval prototype (MAGE-style positional recall)
Research basis: MAGE (arXiv 2606.06090) — semantic-similarity retrieval
fragments decision trajectories on long-horizon tasks; retrieving by
POSITION in a hierarchical execution-state tree (root→current path)
preserves coherence.
- src/ruvector/trajectory-tree.ts — TrajectoryTree prototype:
trajectory-start opens a node under the session root (nesting under
the deepest open trajectory), steps append children, end closes and
pops the current position. recallPath({sessionId, depth}) returns
the exact root→current path + recent siblings — no embedding search.
Best-effort JSON snapshot at .claude-flow/intelligence/
trajectory-tree.json, ALONGSIDE existing trajectory storage (no
migration). Limitations documented in the module header.
- hooks-tools.ts (surgical): non-fatal tree mirrors in
hooks_intelligence_trajectory-start/step/end (+ optional sessionId
param on start), and an opt-in strategy:"state-tree" on
hooks_intelligence_pattern-search (+ sessionId/depth params).
Default strategy stays "semantic" — zero behavior change unless
opted in.
- __tests__/trajectory-tree.test.ts — synthetic 3-level trajectory
path assertions, nesting/pop, sibling window, persistence
round-trip, and default-strategy-untouched checks (12 tests).
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3
* fix(metaharness): kill third-party @latest, extract shared _invoke.mjs, derive smoke counts
Three of the four converged security/perf/arch review fixes:
1. SECURITY (HIGH) + PERF — _harness.mjs no longer shells to
`npx -y metaharness@latest` (a compromised upstream publish would have
executed arbitrary code on user machines, and @latest forced a registry
check per call). Resolution is now: (a) locally installed metaharness
satisfying the PINNED range ~0.3.0 (walk-up node_modules), then (b) a
one-time `npm install --prefix ~/.ruflo/metaharness-cache-0.3.0`, then
plain `node <abs-path-to-cli>` spawns — zero network per call. Both bins
(metaharness + harness) are read from the resolved package.json bin map.
The {stdout, stderr, exitCode, json, degraded, reason, durationMs}
contract and ADR-150 graceful degradation are preserved; timeouts now
report 'metaharness-timeout' (matching _darwin/_redblue) instead of being
conflated with 'metaharness-not-available'.
Measured: `score.mjs --path .` completes in ~0.35s via the cache.
2. ARCH — new scripts/_invoke.mjs consolidates the copy-pasted plumbing:
DEGRADED_RX (superset incl. `npm ERR`), classifyDegraded (keeps the
-timeout vs -not-available distinction), injectJson, parseTrailingJson
(the LAST-{...}-block variant from _darwin — the old _harness first-block
parse was a live bug), ensureCachedInstall (generalizes gepa/_redblue,
cache-dir naming kept compatible so existing caches keep serving),
importOptionalLibrary, findLocalPackageDir, makeDegradedEmitter.
_harness/_darwin/_redblue/gepa are now thin adapters with IDENTICAL
exported signatures; their genuinely-different parts stay (redblue's
node-direct isMain workaround, darwin's async streaming for evolve,
harness's dual binaries). test-graceful-degradation.mjs gains
RUFLO_METAHARNESS_CACHE_BASE / RUFLO_METAHARNESS_SKIP_LOCAL seams so the
ADR-150 drill still exercises the degraded path on warm-cache machines.
3. ARCH — smoke.sh derives EXPECTED_TOOLS / EXPECTED_SUBS once from
metaharness-tools.ts / metaharness.ts and replaces the 7 independently
hardcoded literals (15 at :750/:829/:2046, 13 at :725/:851, 16 footnote,
15 success-pattern). Cross-surface value preserved: independent surfaces
(CLAUDE.md catalog, test-mcp-tools' own `tools.length === 15` literal,
footnote appends, runScript refs) are compared against the derived count,
never a surface against itself; a >=15/>=13 floor step catches
extraction-regex rot.
Validation: smoke.sh 122/122, test-graceful-degradation 16/16,
test-mcp-tools 171/171.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(metaharness): add --diagnose GEPA failure diagnosis to evolve
GEPA's key trick — natural-language failure diagnosis from execution traces
feeding the next mutation, not just scalar fitness — scoped modestly into
the evolve wrapper as an opt-in flag.
`evolve.mjs --diagnose` now appends a `diagnosis` section to the emitted
JSON after the run completes: losing/failed variants' transcripts are run
through darwin's gepa `analyzeTranscript` + `classifyFailure` ops (via the
shared importGepa resolver, moved to _darwin.mjs because gepa.mjs runs
main() on import) and aggregated into failure classes + counts + dominant
class per variant.
Upstream shape findings (verified against @metaharness/darwin@0.8.0 with a
tiny mock-sandbox evolve):
- `metaharness-darwin evolve --json` emits a TEXT leaderboard — stdout
carries no JSON and no transcripts (r.json has always been null here).
- Per-variant run records live at <repo>/.metaharness/runs/<id>.json as
sandbox exec traces ({taskId, exitCode, stdout, stderr}) — NOT gepa
{actionRaw, obs} transcripts.
Diagnosis therefore layers: gepa-shaped transcripts when a run record
embeds them (agent sandbox / future upstream) → champion-transcript
fallback → `diagnosis: {available: false, reason, traceSummary}` with a
mechanical per-variant tally. Never fails the run — internal errors
degrade to {available: false, reason: 'diagnosis-failed: ...'}.
Both paths exercised end-to-end: mock evolve yields the traceSummary
fallback; a seeded gepa-shaped run record yields
{available: true, scope: 'losing-variants', failureClasses:
{exploration-loop: 1, edit-mechanics: 1}, dominantClass: 'exploration-loop'}.
Documented in skills/harness-evolve/SKILL.md.
Co-Authored-By: RuFlo <ruv@ruv.net>
* Revert "feat(gaia): submission integrity checklist — fail-closed pre-submit audit (Berkeley RDI hardening)"
This reverts commit
|
||
|
|
d112d4fc8b |
fix(memory): #2432 #2431 + release 3.13.1 — close prior controllers, WAL-safe graph-edge writes
PATCH per semver — pure bug fixes, no API changes. Fixes: #2432 — Unbounded sql.js MEMFS leak (~36 GB observed in production) Root cause: ControllerRegistry.initController() called controllers.set(name, ...) without closing the prior instance. SqlJsRvfBackend wrappers held an Emscripten MEMFS file (~11 MB each = sizeof memory.db) that only releases on explicit .close() — JS GC of the wrapper does NOT reclaim MEMFS because the sql.js module is a process singleton. Fix: added closePriorIfAny(name) helper, called before every controllers.set() site in v3/@claude-flow/memory/src/controller-registry.ts. Best-effort close (catches errors so replacement always proceeds). #2431 — graph-edge-writer.ts dual-write corrupts memory.db (ADR-130 regression) Root cause: sql.js opened memory.db, did in-memory writes, then called fs.writeFileSync(dbPath, db.export()) after every edge insert. This whole-file flush overwrote memory.db while the better-sqlite3 bridge was writing through its WAL — exactly the dual-write race that ADR-068 (#1257) removed. Symptom: PRAGMA integrity_check reports "database disk image is malformed (11)" after a single memory_store + causal-edge sequence. Fix: ported v3/@claude-flow/cli/src/memory/graph-edge-writer.ts from sql.js to better-sqlite3 + WAL mode. Same native engine as the bridge, no whole-file fsync, no race. Public API unchanged. Smoke-tested: 50 concurrent insertGraphEdge() calls + PRAGMA integrity_check → ok. Note: this is the minimum-safe fix. The architecturally cleaner fix (route edge writes through the bridge's controller layer per ADR-068) is deferred to a future ADR. The current fix removes the race by ensuring both writers share the same WAL-coordinated SQLite engine. Version bumps: - @claude-flow/memory 3.0.0-alpha.20 → 3.0.0-alpha.21 - @claude-flow/cli 3.13.0 → 3.13.1 (pins memory ^3.0.0-alpha.21) - claude-flow umbrella 3.13.0 → 3.13.1 - ruflo wrapper 3.13.0 → 3.13.1 Published to npm with all three dist-tags (latest, alpha, v3alpha) for each of the four packages. Verified post-publish: every package × every tag = 3.13.1 (memory at alpha.21). Co-Authored-By: RuFlo <ruv@ruv.net> |
||
|
|
b099b705f8 |
feat(memory): ADR-147 entity arm + signal provenance in hybridSearch (#2327)
Adds entity matching as a third RRF arm alongside dense + sparse, plus per-result signal provenance (#2317). What this lands: - `entity-tagger.ts` — regex extractor for emails, URLs, file paths, quoted phrases, proper-noun 2-grams (12 unit tests) - `hybridSearch` controller — entity arm wired into the existing RRF+MMR fusion at `controller-registry.ts` - `signals: ('vector' | 'bm25' | 'entity')[]` on every fused result End-to-end capability smoke against built dist (not just TS source): - Corpus: 30 generic "authentication" entries + 1 "Alice Smith" needle - Query: `"Alice Smith authentication"` - Result: **Alice ranks #1** with `signals=["vector","bm25","entity"]`; runners-up only have `["vector","bm25"]` - RRF score gap: 0.0477 vs 0.0323 = **47% boost** from the entity signal 16/16 tests in touched modules. Full memory suite 416/420 (4 pre-existing Windows-env failures in unrelated files). Closes part of #2317. The ADR's stated P1 ("wire FTS5 + RRF") was already shipped before this PR; this lands the actual P2 (entity arm + provenance) that the dream-cycle author missed when surveying the tree. |
||
|
|
facec4ccc4 |
fix(memory): auto-memory cluster — frontmatter parse, _ paths, plugin lookup, embed default (#2291)
Fixes 5 related bugs reported in #2281–#2285, all in the SessionStart
auto-memory pipeline.
- #2281 (embeddings.ts): `ruflo embeddings init` defaulted to the full
HF model name `Xenova/all-MiniLM-L6-v2`, but the embedder's
MODEL_REGISTRY keys are short names (`all-MiniLM-L6-v2`). The `/`
also failed VALID_MODEL_ID_PATTERN. Switched default + example to
the registry-style short form.
- #2282 (auto-memory-bridge.ts): `resolveAutoMemoryDir` only replaced
`/` with `-`, but Claude Code normalizes `_` to `-` too. Any project
path with an underscore (e.g. `RX_ERP`) produced a mismatched
project key and the bridge looked at a non-existent directory.
- #2283 (auto-memory-bridge.ts): `parseMarkdownEntries` only split on
`## ` headings. Claude Code's auto-memory format is YAML frontmatter
+ free-text body with no sub-headings, so every real memory file
parsed to zero entries. Now: strip frontmatter → split on `## ` →
fall back to single untitled entry per file. Frontmatter `name`,
`description`, `type`, `originSessionId` flow into entry metadata.
- #2284 (auto-memory-hook.mjs): the hook hardcoded
`workingDir: PROJECT_ROOT` in both doImport and doSync, where
PROJECT_ROOT is the plugin clone path. The bridge then computed
its memory directory from the plugin path, not the user's project.
Now uses `process.env.CLAUDE_FLOW_CWD || process.cwd()`.
- #2285 (auto-memory-hook.mjs): the plugin marketplace ships
`v3/@claude-flow/*` source-only (no `dist/`), so the existing
4-strategy lookup never found the bundled `@claude-flow/memory`
package when `ruflo` is installed via `npm i -g`. Added a new
`resolveBundledFile()` helper with a global-npm-prefix fallback
that checks the `ruflo`, `claude-flow`, and `@claude-flow/cli`
wrappers in both Unix and Windows global layouts. Applied to all
4 PROJECT_ROOT-anchored package lookups (memory pkg, memory-
initializer, intelligence module).
Tests: 77/78 pass in @claude-flow/memory. The one failure is a
pre-existing Windows-only `path.join` assertion from commit
|
||
|
|
8773fcffdf |
feat(memory): #2061 ADR-125 Phase 5 — graceful retrieval degradation + FTS5 keyword fallback
Closes the last gap from ADR-125's hardening pass: when the embedder is
unavailable the memory subsystem returns FTS-ranked keyword results
instead of throwing, and the previously-stubbed `hybridSearch` controller
finally returns real fused results.
- `AgentDBAdapter.semanticSearch` — wraps the embedder call in try/catch.
On no-generator OR generator-throws: emits
`health:embedder { status: 'degraded' }` then delegates to
`searchKeyword(query, opts)` (Acceptance Criterion #5).
- `AgentDBAdapter.searchKeyword` — new in-memory token-overlap ranking
with a dependency-free `tokenize` helper. Used both as the embedder
fallback and as the sparse arm of `hybridSearch`.
- `SQLiteBackend` + `SqlJsBackend` — both gain a FTS5 virtual table
(`memory_fts USING fts5(id UNINDEXED, content, tokenize='porter
unicode61')`), mirror writes on `store()`, prune on `delete()`, and a
`searchKeyword(query, limit)` method that queries `memory_fts MATCH`
ranked by FTS5's BM25 and joins back to `memory_entries`. Both fall
back to `LIKE` when FTS5 isn't available on the build.
- `controller-registry.ts` `hybridSearch` controller — replaces the
`return null` placeholder with a real RRF + MMR pipeline:
1. Run `semanticSearch` (which itself degrades) AND `searchKeyword`
independently with fanOutK = limit * 3.
2. Fuse via Reciprocal Rank Fusion (k=60) using the new public
`applyRRF` helper exported from `smart-retrieval.ts`.
3. Diversify via MMR (lambda=0.7) using the new public `applyMMR`
helper (re-export of the existing `mmrRerank`).
Auto-enables when a `MemoryService` is registered.
Tests:
- `src/graceful-retrieval.test.ts` — 3 cases covering Acceptance
Criterion #5 (no embedder → keyword + degraded event), embedder-throws
fallback, and the `hybridSearch` controller's fused output shape.
- `src/fts5.test.ts` — 6 cases covering sqljs FTS5 insert/match/delete/
update and gated sqlite FTS5 tests (skip when `better-sqlite3` isn't
installable in the env).
403/15 tests pass (was 394/13).
Refs: #2061, ADR-125 §Phase 5, Acceptance Criterion #5.
Co-Authored-By: RuFlo <ruv@ruv.net>
|
||
|
|
850450f385 |
feat(memory): #2061 ADR-125 Phase 4 — MemoryConsolidator (sweep + dedup + compactHnsw)
Promotes the Phase 3 consolidator placeholder to a real maintenance pass:
- `MemoryConsolidator.sweepExpired()` — drops entries past `expiresAt`
from `entries`/`namespaceIndex`/`keyIndex`/`tagIndex` AND from the HNSW
index (`HNSWIndex.removePoint`). Cleans up emptied namespace/tag sets.
- `MemoryConsolidator.dedup(strategy)` — SHA-256 content hash, then one
of `keep-newest | keep-oldest | merge-tags`. `merge-tags` unions tag
sets across duplicates and updates `tagIndex` for newly-added tags.
- `MemoryConsolidator.compactHnsw()` — rebuilds a fresh `HNSWIndex` from
the current `entries` and swaps pointers atomically. Uses the new
`HNSWIndex.getConfig()` accessor instead of reaching into private state.
- `MemoryConsolidator.runAll()` — sweep → dedup → compact, returning the
full `ConsolidationResult` breakdown.
Wiring:
- `UnifiedMemoryService` lazy-loads + memoizes the consolidator via
`getConsolidator()`. With `consolidator.autoRun: true` a `setInterval`
fires `runAll()` every 6h (configurable, unref'd to allow process
exit). `close()` clears the timer before snapshotting.
- `controller-registry.ts` `nightlyLearner` controller now returns a
thin wrapper bound to `consolidator.runAll()` when a `memoryService`
is registered (`RuntimeConfig.memoryService`). Falls back to the
upstream AgentDB `NightlyLearner` when only `agentdb` is registered.
`isControllerEnabled('nightlyLearner')` updated to enable on either
signal.
Tests: `src/consolidator.test.ts` covers Acceptance Criterion #4 (1000
expired → 0 remaining + HNSW emptied), all three dedup strategies,
compact-after-sweep size invariant, auto-run timer firing, close()
timer cleanup, and the nightlyLearner controller delegation.
394/13 tests pass (was 385/12).
Refs: #2061, ADR-125 §Phase 4, Acceptance Criterion #4.
Co-Authored-By: RuFlo <ruv@ruv.net>
|
||
|
|
81a2b23eb9 |
feat(memory): #2061 ADR-125 Phase 3 — persistent HNSW snapshot + restore
Adds the first end-to-end durability path for `@claude-flow/memory`: - `HNSWIndex.serialize() / static deserialize()` — length-prefixed binary format with magic header `HNSW\x01`. Round-trips graph topology + node vectors + normalized cache + per-level neighbor sets. Asserts header on read and throws on truncated payloads. - `AgentDBAdapter.loadFromDisk / saveToDisk / saveSnapshot` — replaces the placeholder stubs (around `agentdb-adapter.ts:1025-1034`). Sidecars are `<persistencePath>.hnsw` (binary HNSW) and `<persistencePath>.meta.json` (stable JSON for entries + namespace/key/tag indices). Atomic write via temp-and-rename. Emits `persistence:loaded` with `status: restored | fresh | corrupt` so callers can observe state. - `UnifiedMemoryService` — adds `snapshotInterval` config (default 1000, configurable, 0/Infinity disables). Triggers `saveSnapshot()` every Nth `store()` / per-entry in `bulkInsert`, and on `close() / shutdown()`. `close()` is added as a lifecycle alias. - `HnswLite` deletion — `src/hnsw-lite.ts` is removed; its brute-force-degrading implementation is inlined into `rvf-backend.ts` as a private helper (RvfBackend is the only user). The `cosineSimilarity` re-export from the package surface is removed; users who want it should pull from `@claude-flow/embeddings`. Tests: `src/hnsw-persistence.test.ts` covers serialize round-trip, truncation/magic checks, full restart-restore (Acceptance Criterion #3), sidecar corruption fallback, and snapshot-every-N triggering. A `MemoryConsolidator` stub lands in `src/consolidator.ts` so the index compiles; the real implementation arrives with Phase 4. 385/12 tests pass (was 378/11). Refs: #2061, ADR-125 §Phase 3, Acceptance Criterion #3. Co-Authored-By: RuFlo <ruv@ruv.net> |