* 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 af185fcccd.
* fix(hooks): ADR-112 guidance clause on hooks_model-verify description
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ci): retune #1921 fix-invariant to the >=2.8.0 OTel override floor
The PR deliberately raised the @opentelemetry/core override from the exact
1.25.1 pin to a >=2.8.0 floor (OTel 2.x audit fix), but the #1921 invariant
in audit-fix-invariants.mjs still asserted the old pin substring, failing
the 'Hook-command install safety (#1921)' job. Per the audit's own guidance,
the invariant is updated to point at the new location of the fix — the
override entry itself — preserving the regression guard (arborist Invalid
Version placeholder) rather than deleting it.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3
* fix(ci): register RUFLO_METAHARNESS_CACHE_BASE as env-var escape hatch
The metaharness _invoke.mjs consolidation introduced cacheBaseDir(), whose
RUFLO_METAHARNESS_CACHE_BASE read is a CI/test seam for relocating the
~/.ruflo pinned-cache root in smoke tests — there is no CLI-flag surface in
plugin scripts to take precedence. Register it in KNOWN_ESCAPE_HATCHES per
ADR-125/ADR-130 remediation Option B, unblocking the 'Plugin package
install-safety (#1902/#1903/#1904)' job.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3
* fix(ci): linear-time dash trim in A2A slugify — resolves js/polynomial-redos
CodeQL flagged /^-+|-+$/g in slugify() (agent-card.ts:281) as polynomial
ReDoS: the anchored quantifier backtracks O(n^2) on adversarial all-dash
card names, and card names are remote library input. Replace the trim regex
with an index-scan (charCodeAt) that is strictly linear. Behavior verified
equivalent against the old implementation over edge cases plus 5000-input
fuzz; package typechecks and all 600 tests pass.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3
* fix(ci): no-metaharness drill uses the _invoke.mjs test seams
The pinned-cache resolution defeats the drill's registry-blackhole absence
simulation (metaharness resolves locally / from the warm ~/.ruflo cache).
RUFLO_METAHARNESS_SKIP_LOCAL=1 + an empty RUFLO_METAHARNESS_CACHE_BASE make
'absent' mean absent again. Reproduced locally: exit 0 + degraded:true.
Co-Authored-By: RuFlo <ruv@ruv.net>
@claude-flow/memory
High-performance memory for Claude Flow V3 — one canonical
MemoryServiceAPI on top of a real hybrid backend (sql.js + AgentDB), persistent HNSW vector search that survives restart, a memory-bound consolidator, graceful keyword (FTS5) fallback when the embedder isn't available, plus the AutoMemoryBridge, self-learning, and knowledge-graph layers that build on top.
What's new in 3.0.0-alpha.18 (ADR-125)
This release closes out ADR-125 — Memory Consolidation. If you're upgrading from 3.0.0-alpha.17 or earlier, this is the headline:
- One canonical entry point.
MemoryServicereplaces the oldUnifiedMemoryServicename (both still exported — the old one is@deprecatedand will be removed at3.0.0-rc). See Migration below. - A real hybrid default.
createHybridService(...)finally returns a service whose backend is an actualHybridBackend(sql.js + AgentDB). Earlier releases silently downgraded this to AgentDB-only — ADR-009's promise wasn't delivered until now. - Persistent HNSW. Closing a service snapshots its HNSW index to a sidecar (
<dbPath>.hnsw+<dbPath>.meta.json). Reopening on the same path restores in milliseconds rather than rebuilding from scratch — search-ready cold start. MemoryConsolidator. A background service that evicts expired entries from indexes and HNSW, deduplicates by content hash, and rebuilds the HNSW index when it gets fragmented. Auto-runs on a configurable timer (default 6 hours) so memory stays bounded.- Graceful retrieval.
service.search('query')no longer throws when@claude-flow/embeddingsis unavailable — it degrades to FTS5 keyword search and emitshealth.embedder = 'degraded'. The full hybrid path also adds real Reciprocal Rank Fusion + MMR diversity rerank. - Reproducible benchmarks.
npm run benchnow actually runs. The HNSW search baseline (single-threaded, 1k × 128-dim cosine vectors on Apple Silicon, Node 22): 0.53 ms / search · 1,889 ops/s · 533 ms to build 1k. Seebenchmarks/results/baseline-20260519T212453Z.md. - Node 26 install support (#1867) —
better-sqlite3is fully optional; installs succeed on Node 24/26 and the package falls back to sql.js when the native build isn't available.
Features
- Canonical
MemoryServiceAPI — one entry point for store / retrieve / search / hybrid query - Real hybrid backend —
HybridBackend(sql.js + AgentDB) for structured + vector queries (ADR-009 / ADR-125 Phase 2) - Persistent HNSW — index survives
close()and restart; auto-snapshots every Nth write (ADR-125 Phase 3) MemoryConsolidator—sweepExpired()+dedup()+compactHnsw()+ auto-run timer (ADR-125 Phase 4)- Graceful retrieval — automatic FTS5 keyword fallback when embedder is unreachable; RRF + MMR for hybrid (ADR-125 Phase 5)
- HNSW vector search — measured 0.53 ms / search at 1k × 128 dim on Apple Silicon; see baseline above
- Auto Memory Bridge — Bidirectional sync between Claude Code auto memory and AgentDB (ADR-048)
- Self-Learning — LearningBridge connects insights to SONA/ReasoningBank neural pipeline (ADR-049)
- Knowledge Graph — PageRank + label propagation community detection over memory entries (ADR-049)
- Agent-Scoped Memory — 3-scope agent memory (project/local/user) with cross-agent knowledge transfer (ADR-049)
- Vector Quantization — Binary, scalar, and product quantization for 4–32x memory reduction
- Multiple Distance Metrics — Cosine, Euclidean, dot product, and Manhattan
- Query Builder — Fluent API for building complex memory queries
- Cache Manager — LRU caching with configurable size and TTL
- Migration Tools —
MemoryMigratorfor moving from V2 memory systems - Cross-platform — Works on Linux, macOS, and Windows; Node 18+ (including Node 24/26)
Installation
npm install @claude-flow/memory
Standalone use (without the Ruflo CLI)
This package works on its own — you don't need @claude-flow/cli or the
full Ruflo install. Use it any time you want HNSW vector search, an
AgentDB façade, or the v3 controller registry from your own app.
Two recipes that exercise the most-installed surface:
Recipe 1 — HNSW index with built-in quantization (no other deps)
// recipe.mjs
import { HNSWIndex } from '@claude-flow/memory';
const index = new HNSWIndex({
dimensions: 8,
M: 16,
efConstruction: 200,
metric: 'cosine',
});
// Add a few vectors
await index.addPoint('doc-a', new Float32Array([1, 0, 0, 0, 0, 0, 0, 0]));
await index.addPoint('doc-b', new Float32Array([0.9, 0.1, 0, 0, 0, 0, 0, 0]));
await index.addPoint('doc-c', new Float32Array([0, 1, 0, 0, 0, 0, 0, 0]));
// Search — top 2 nearest to "doc-a"-shaped query
const hits = await index.search(new Float32Array([1, 0, 0, 0, 0, 0, 0, 0]), 2);
console.log(hits); // [{ id: 'doc-a', distance: 0 }, { id: 'doc-b', distance: ~0.005 }]
Recipe 2 — Drive the controller registry against your own AgentDB
The registry coordinates 15+ memory controllers (learning bridge, memory
graph, tiered cache, vector backend, etc.) on top of an AgentDB instance
you own. Useful when you already have an AgentDB lifecycle and just
want the v3 governance layer (issue #2019 added the agentdb injection
field that makes this clean).
import { ControllerRegistry } from '@claude-flow/memory';
import { AgentDB } from 'agentdb';
const agentdb = new AgentDB({ dbPath: ':memory:' });
await agentdb.initialize();
const registry = new ControllerRegistry();
await registry.initialize({ agentdb });
// Now everything backed by AgentDB is reachable through the registry
const reflexion = registry.get('reflexion'); // ReflexionMemory
const vectorBackend = registry.get('vectorBackend'); // live vector backend
const enabled = registry.isEnabled('skills'); // true
const health = await registry.healthCheck();
console.log(`${health.activeControllers}/${health.controllers.length} controllers active`);
await registry.shutdown();
Quick Start
The fastest way to get a full-featured memory service — hybrid backend, HNSW vector index, FTS5 keyword fallback, persistent snapshots, consolidation timer — is createHybridService:
import { createHybridService } from '@claude-flow/memory';
async function embedder(text: string): Promise<Float32Array> {
// Use any embedding provider — OpenAI, @claude-flow/embeddings, your own model.
// If the embedder ever fails, MemoryService falls back to FTS5 keyword search
// automatically (emitting `health.embedder = 'degraded'`).
return new Float32Array(/* ... */);
}
const memory = await createHybridService('./data/memory.db', embedder, 1536);
await memory.initialize();
// Store an entry — content is embedded and added to both SQLite and HNSW
await memory.store({
key: 'auth-patterns',
content: 'OAuth 2.0 implementation patterns for secure authentication',
tags: ['auth', 'security', 'patterns'],
});
// Semantic search via HNSW
const similar = await memory.semanticSearch('user authentication best practices', 5);
// Keyword search via FTS5 (also used as the automatic fallback)
const exact = await memory.searchKeyword('OAuth 2.0', { limit: 10 });
// Hybrid search — RRF-fused dense + sparse, MMR-diversified
const blended = await memory.search('authentication patterns', { limit: 10 });
// Clean shutdown — flushes the consolidator timer and snapshots HNSW to disk
await memory.close();
// Reopen the same path — entries AND HNSW index are restored from sidecar
const reopened = await createHybridService('./data/memory.db', embedder, 1536);
await reopened.initialize();
// memory.search() is immediately fast — no rebuild
You can also use the lower-level primitives directly. HNSWIndex is exported and works without any of the service layer if you just want a vector index:
import { HNSWIndex } from '@claude-flow/memory';
const index = new HNSWIndex({
dimensions: 1536, // OpenAI embedding size
M: 16, // Max connections per node
efConstruction: 200,
metric: 'cosine',
});
await index.addPoint('memory-1', new Float32Array(embedding));
await index.addPoint('memory-2', new Float32Array(embedding2));
const results = await index.search(queryVector, 10);
// [{ id: 'memory-1', distance: 0.05 }, { id: 'memory-2', distance: 0.12 }]
// New in 3.0.0-alpha.18: persist the index to a buffer for restore later
const snapshot: Buffer = index.serialize();
const restored = HNSWIndex.deserialize(snapshot);
Migrating from 3.0.0-alpha.17 or earlier
If you're already using this package:
// Before
import { UnifiedMemoryService } from '@claude-flow/memory';
const memory = new UnifiedMemoryService({ /* ... */ });
// After (recommended) — both names resolve to the same class
import { MemoryService } from '@claude-flow/memory';
const memory = new MemoryService({ /* ... */ });
// `UnifiedMemoryService` continues to work through 3.0.0-rc as a `@deprecated` alias.
Two other things changed in 3.0.0-alpha.18:
createHybridServicenow does what its name says. If you were relying on the old AgentDB-only downgrade, you'll get a realHybridBackendnow — semantic search and structured queries both work without extra wiring.semanticSearchno longer throws when the embedder is absent. Code that relied on a thrown error to detect a misconfigured embedder should listen forhealth.embedder = 'degraded'events instead. See Graceful retrieval below.
The HnswLite and RvfBackend classes are no longer top-level exports (they were internal implementation details). If your code imported them, switch to HNSWIndex (more capable, persistent) — they're verified to have zero external importers.
Persistence
In 3.0.0-alpha.18 the HNSW index survives close() and restart. Snapshots happen automatically:
- On
service.close(), the index is serialized to<dbPath>.hnswand the in-memory entry/namespace/key/tag maps go to<dbPath>.meta.json. - During the lifetime of the service, the index also auto-snapshots every Nth
store()call (defaultN=1000, configurable viaMemoryServiceConfig.snapshotInterval). - On initialize, if both sidecars exist, they're restored. The service emits one of three
health.persistenceevents:'restored'(success),'fresh'(no sidecar found — first run), or'corrupt'(deserialize failed — automatic fallback to fresh state).
import { MemoryService, HNSWIndex } from '@claude-flow/memory';
const memory = new MemoryService({
persistenceEnabled: true,
persistencePath: './data/memory.db',
snapshotInterval: 500, // snapshot every 500 stores
embeddingGenerator,
});
memory.on('health.persistence', (status) => {
// 'restored' | 'fresh' | 'corrupt'
console.log('Persistence state:', status);
});
await memory.initialize();
// ...store, query...
await memory.close(); // flushes a final snapshot
Manual snapshot/restore on a raw HNSWIndex:
const buf: Buffer = index.serialize();
// write buf to disk, transfer between processes, etc.
const restored = HNSWIndex.deserialize(buf);
// search works immediately — no rebuild
The serialized format is versioned with a magic header (HNSW\x01) — a corrupted or stale snapshot is detected and rejected loudly rather than silently producing wrong neighbors.
Memory consolidation
MemoryConsolidator keeps the index bounded. Three operations:
import { MemoryConsolidator } from '@claude-flow/memory';
const consolidator = new MemoryConsolidator(memory, {
dedupStrategy: 'merge-tags', // 'keep-newest' | 'keep-oldest' | 'merge-tags'
intervalMs: 6 * 60 * 60 * 1000, // auto-run every 6h
});
// Evict expired entries from all indexes (including HNSW)
const swept = await consolidator.sweepExpired();
// { removed: 142, remaining: 8503 }
// Deduplicate by SHA-256 content hash
const dedup = await consolidator.dedup('keep-newest');
// { merged: 23 }
// Rebuild HNSW to reclaim space after large churn
const compaction = await consolidator.compactHnsw();
// { before: 8503, after: 8503, durationMs: 198 }
// Or run all three in sequence
const result = await consolidator.runAll();
You don't have to construct it manually — MemoryService will wire it up if you opt in:
const memory = new MemoryService({
consolidator: {
autoRun: true, // start a setInterval that runs runAll()
intervalMs: 6 * 60 * 60 * 1000, // every 6h (default)
},
});
memory.on('consolidation.complete', (result) => {
console.log(`Swept ${result.swept.removed}, deduped ${result.dedup.merged}`);
});
The nightlyLearner controller in the AgentDB controller registry now delegates to MemoryConsolidator.runAll() instead of the old AgentDB pass-through, so the consolidator is invoked from every layer that expects the "nightly memory hygiene" hook.
Graceful retrieval (FTS5 fallback)
MemoryService.search() and semanticSearch() no longer hard-fail when @claude-flow/embeddings (or whatever embedder you injected) is unavailable. They:
- Try the embedder.
- If it throws or is missing, emit
health.embedder = 'degraded'. - Run the same query through FTS5 keyword search (porter + unicode61 tokenizer) and return those results.
const memory = new MemoryService({
// No embeddingGenerator — semantic queries will fall back to FTS5
});
await memory.initialize();
memory.on('health.embedder', (state) => {
// 'available' | 'degraded'
console.warn(`Embedder is ${state}`);
});
await memory.store({ key: 'note-1', content: 'OAuth pattern review' });
const results = await memory.search('OAuth', { limit: 5 });
// Returns FTS-ranked matches; no throw
When both dense (HNSW) and sparse (FTS5) paths are available, service.search(query) runs both, fuses the rankings with Reciprocal Rank Fusion (k=60), and reranks with MMR (λ=0.7) for diversity. This is what the AgentDB hybridSearch controller exposes too — it used to be a stub that returned null; in 3.0.0-alpha.18 it's a real implementation.
API Reference
HNSW Index
import { HNSWIndex } from '@claude-flow/memory';
const index = new HNSWIndex({
dimensions: 1536,
M: 16, // Max connections per layer
efConstruction: 200, // Construction-time search depth
maxElements: 1000000, // Max vectors
metric: 'cosine', // 'cosine' | 'euclidean' | 'dot' | 'manhattan'
quantization: { // Optional quantization
type: 'scalar', // 'binary' | 'scalar' | 'product'
bits: 8
}
});
// Add vectors
await index.addPoint(id: string, vector: Float32Array);
// Search
const results = await index.search(
query: Float32Array,
k: number,
ef?: number // Search-time depth (higher = more accurate)
);
// Search with filters
const filtered = await index.searchWithFilters(
query,
k,
(id) => id.startsWith('session-')
);
// Remove vectors
await index.removePoint(id);
// Get statistics
const stats = index.getStats();
// { vectorCount, memoryUsage, avgSearchTime, compressionRatio }
AgentDB Adapter
import { AgentDBAdapter } from '@claude-flow/memory';
const adapter = new AgentDBAdapter({
dimension: 1536,
indexType: 'hnsw',
metric: 'cosine',
hnswM: 16,
hnswEfConstruction: 200,
enableCache: true,
cacheSizeMb: 256
});
await adapter.initialize();
// Store memory
await adapter.store({
id: 'mem-123',
content: 'User prefers dark mode',
embedding: vector,
metadata: { type: 'preference', agentId: 'agent-1' }
});
// Semantic search
const memories = await adapter.search(queryVector, {
limit: 10,
threshold: 0.7,
filter: { type: 'preference' }
});
// Cross-agent memory sharing
await adapter.enableCrossAgentSharing({
shareTypes: ['patterns', 'preferences'],
excludeTypes: ['secrets']
});
Cache Manager
import { CacheManager } from '@claude-flow/memory';
const cache = new CacheManager({
maxSize: 1000,
ttlMs: 3600000, // 1 hour
strategy: 'lru'
});
// Cache operations
cache.set('key', value);
const value = cache.get('key');
const exists = cache.has('key');
cache.delete('key');
cache.clear();
// Statistics
const stats = cache.getStats();
// { size, hits, misses, hitRate }
Query Builder
import { QueryBuilder } from '@claude-flow/memory';
const results = await new QueryBuilder()
.semantic(queryVector)
.where('agentId', '=', 'agent-1')
.where('type', 'in', ['pattern', 'strategy'])
.where('createdAt', '>', Date.now() - 86400000)
.orderBy('relevance', 'desc')
.limit(20)
.execute();
Migration
import { MemoryMigrator, createMigrator } from '@claude-flow/memory';
const migrator = createMigrator({
source: './data/v2-memory.db',
destination: './data/v3-memory.db',
});
// Inspect what will be migrated
const preview = await migrator.preview();
console.log(`Will migrate ${preview.recordCount} records`);
// Execute migration
await migrator.execute({
batchSize: 1000,
onProgress: (progress) => console.log(`${progress.percent}%`),
});
Quantization Options
// Binary quantization (32x compression)
const binaryIndex = new HNSWIndex({
dimensions: 1536,
quantization: { type: 'binary' }
});
// Scalar quantization (4x compression)
const scalarIndex = new HNSWIndex({
dimensions: 1536,
quantization: { type: 'scalar', bits: 8 }
});
// Product quantization (8x compression)
const productIndex = new HNSWIndex({
dimensions: 1536,
quantization: { type: 'product', subquantizers: 8 }
});
Auto Memory Bridge (ADR-048)
Bidirectional sync between Claude Code's auto memory files and AgentDB. Auto memory is a persistent directory (~/.claude/projects/<project>/memory/) where Claude writes learnings as markdown. MEMORY.md (first 200 lines) is loaded into the system prompt; topic files are read on demand.
Quick Start
import { AutoMemoryBridge } from '@claude-flow/memory';
const bridge = new AutoMemoryBridge(memoryBackend, {
workingDir: '/workspaces/my-project',
syncMode: 'on-session-end', // 'on-write' | 'on-session-end' | 'periodic'
pruneStrategy: 'confidence-weighted', // 'confidence-weighted' | 'fifo' | 'lru'
});
// Record an insight (stores in AgentDB + optionally writes to files)
await bridge.recordInsight({
category: 'debugging',
summary: 'HNSW index requires initialization before search',
source: 'agent:tester',
confidence: 0.95,
});
// Sync buffered insights to auto memory files
const syncResult = await bridge.syncToAutoMemory();
// Import existing auto memory files into AgentDB (on session start)
const importResult = await bridge.importFromAutoMemory();
// Curate MEMORY.md index (stays under 200-line limit)
await bridge.curateIndex();
// Check status
const status = bridge.getStatus();
Sync Modes
| Mode | Behavior |
|---|---|
on-write |
Writes to files immediately on recordInsight() |
on-session-end |
Buffers insights, flushes on syncToAutoMemory() |
periodic |
Auto-syncs on a configurable interval |
Insight Categories
| Category | Topic File | Description |
|---|---|---|
project-patterns |
patterns.md |
Code patterns and conventions |
debugging |
debugging.md |
Bug fixes and debugging insights |
architecture |
architecture.md |
Design decisions and module relationships |
performance |
performance.md |
Benchmarks and optimization results |
security |
security.md |
Security findings and CVE notes |
preferences |
preferences.md |
User and project preferences |
swarm-results |
swarm-results.md |
Multi-agent swarm outcomes |
Key Optimizations
- Batch import -
bulkInsert()instead of individualstore()calls - Pre-fetched hashes - Single query for content-hash dedup during import
- Async I/O -
node:fs/promisesfor non-blocking writes - Exact dedup -
hasSummaryLine()uses bullet-prefix matching, not substring - O(1) sync tracking -
syncedInsightKeysSet prevents double-write race - Prune-before-build - Avoids O(n^2) index rebuild loop
Utility Functions
import {
resolveAutoMemoryDir, // Derive auto memory path from working dir
findGitRoot, // Walk up to find .git root
parseMarkdownEntries, // Parse ## headings into structured entries
extractSummaries, // Extract bullet summaries, strip metadata
formatInsightLine, // Format insight as markdown bullet
hashContent, // SHA-256 truncated to 16 hex chars
pruneTopicFile, // Keep topic files under line limit
hasSummaryLine, // Exact bullet-prefix dedup check
} from '@claude-flow/memory';
Types
import type {
AutoMemoryBridgeConfig,
MemoryInsight,
InsightCategory,
SyncDirection,
SyncMode,
PruneStrategy,
SyncResult,
ImportResult,
} from '@claude-flow/memory';
Self-Learning Bridge (ADR-049)
Connects insights to the @claude-flow/neural learning pipeline. When neural is unavailable, all operations degrade to no-ops.
Quick Start
import { AutoMemoryBridge, LearningBridge } from '@claude-flow/memory';
const bridge = new AutoMemoryBridge(backend, {
workingDir: '/workspaces/my-project',
learning: {
sonaMode: 'balanced',
confidenceDecayRate: 0.005, // Per-hour decay
accessBoostAmount: 0.03, // Boost per access
consolidationThreshold: 10, // Min insights before consolidation
},
});
// Insights now trigger learning trajectories automatically
await bridge.recordInsight({
category: 'debugging',
summary: 'Connection pool exhaustion on high load',
source: 'agent:tester',
confidence: 0.9,
});
// Consolidation runs JUDGE/DISTILL/CONSOLIDATE pipeline
await bridge.syncToAutoMemory(); // Calls consolidate() first
Standalone Usage
import { LearningBridge } from '@claude-flow/memory';
const lb = new LearningBridge(backend, {
// Optional: inject neural loader for custom setups
neuralLoader: async () => {
const { NeuralLearningSystem } = await import('@claude-flow/neural');
return new NeuralLearningSystem();
},
});
// Boost confidence when insight is accessed
await lb.onInsightAccessed('entry-123'); // +0.03 confidence
// Apply time-based decay
const decayed = await lb.decayConfidences('default'); // -0.005/hour
// Find similar patterns via ReasoningBank
const patterns = await lb.findSimilarPatterns('connection pooling');
// Get learning statistics
const stats = lb.getStats();
// { totalTrajectories, activeTrajectories, completedTrajectories,
// totalConsolidations, accessBoosts, ... }
Confidence Lifecycle
| Event | Effect | Range |
|---|---|---|
| Insight recorded | Initial confidence from source | 0.1 - 1.0 |
| Insight accessed | +0.03 per access | Capped at 1.0 |
| Time decay | -0.005 per hour since last access | Floored at 0.1 |
| Consolidation | Neural pipeline may adjust | 0.1 - 1.0 |
Knowledge Graph (ADR-049)
Pure TypeScript knowledge graph with PageRank and community detection. No external graph libraries required.
Quick Start
import { AutoMemoryBridge, MemoryGraph } from '@claude-flow/memory';
const bridge = new AutoMemoryBridge(backend, {
workingDir: '/workspaces/my-project',
graph: {
similarityThreshold: 0.8,
pageRankDamping: 0.85,
maxNodes: 5000,
},
});
// Graph builds automatically on import
await bridge.importFromAutoMemory();
// Curation uses PageRank to prioritize influential insights
await bridge.curateIndex();
Standalone Usage
import { MemoryGraph } from '@claude-flow/memory';
const graph = new MemoryGraph({
pageRankDamping: 0.85,
pageRankIterations: 50,
pageRankConvergence: 1e-6,
maxNodes: 5000,
});
// Build from backend entries
await graph.buildFromBackend(backend, 'my-namespace');
// Or build manually
graph.addNode(entry);
graph.addEdge('entry-1', 'entry-2', 'reference', 1.0);
graph.addEdge('entry-1', 'entry-3', 'similar', 0.9);
// Compute PageRank (power iteration)
const ranks = graph.computePageRank();
// Detect communities (label propagation)
const communities = graph.detectCommunities();
// Graph-aware ranking: blend vector score + PageRank
const ranked = graph.rankWithGraph(searchResults, 0.7);
// alpha=0.7 means 70% vector score + 30% PageRank
// Get most influential insights for MEMORY.md
const topNodes = graph.getTopNodes(20);
// BFS traversal for related insights
const neighbors = graph.getNeighbors('entry-1', 2); // depth=2
Edge Types
| Type | Source | Description |
|---|---|---|
reference |
MemoryEntry.references |
Explicit cross-references between entries |
similar |
HNSW search | Auto-created when similarity > threshold |
temporal |
Timestamps | Entries created in same time window |
co-accessed |
Access patterns | Entries frequently accessed together |
causal |
Learning pipeline | Cause-effect relationships |
Performance
| Operation | Result | Target |
|---|---|---|
| Graph build (1k nodes) | 2.78 ms | <200 ms |
| PageRank (1k nodes) | 12.21 ms | <100 ms |
| Community detection (1k) | 19.62 ms | — |
rankWithGraph(10) |
0.006 ms | — |
getTopNodes(20) |
0.308 ms | — |
getNeighbors(d=2) |
0.005 ms | — |
Agent-Scoped Memory (ADR-049)
Maps Claude Code's 3-scope agent memory directories for per-agent knowledge isolation and cross-agent transfer.
Quick Start
import { createAgentBridge, transferKnowledge } from '@claude-flow/memory';
// Create a bridge for a specific agent scope
const agentBridge = createAgentBridge(backend, {
agentName: 'my-coder',
scope: 'project', // 'project' | 'local' | 'user'
workingDir: '/workspaces/my-project',
});
// Record insights scoped to this agent
await agentBridge.recordInsight({
category: 'debugging',
summary: 'Use connection pooling for DB calls',
source: 'agent:my-coder',
confidence: 0.95,
});
// Transfer high-confidence insights between agents
const result = await transferKnowledge(sourceBackend, targetBridge, {
sourceNamespace: 'learnings',
minConfidence: 0.8, // Only transfer confident insights
maxEntries: 20,
categories: ['debugging', 'architecture'],
});
// { transferred: 15, skipped: 5 }
Scope Paths
| Scope | Directory | Use Case |
|---|---|---|
project |
<gitRoot>/.claude/agent-memory/<agent>/ |
Project-specific learnings |
local |
<gitRoot>/.claude/agent-memory-local/<agent>/ |
Machine-local data |
user |
~/.claude/agent-memory/<agent>/ |
Cross-project user knowledge |
Utilities
import {
resolveAgentMemoryDir, // Get scope directory path
createAgentBridge, // Create scoped AutoMemoryBridge
transferKnowledge, // Cross-agent knowledge sharing
listAgentScopes, // Discover existing agent scopes
} from '@claude-flow/memory';
// Resolve path for an agent scope
const dir = resolveAgentMemoryDir('my-agent', 'project');
// → /workspaces/my-project/.claude/agent-memory/my-agent/
// List all agent scopes in a directory
const scopes = await listAgentScopes('/workspaces/my-project');
// [{ agentName: 'coder', scope: 'project', path: '...' }, ...]
Performance Benchmarks
Reproducible benchmarks ship in benchmarks/*.bench.ts. Run them yourself:
cd v3/@claude-flow/memory
npm run build
npm run bench # runs benchmarks/*.bench.ts under vitest
HNSW search baseline (baseline-20260519T212453Z.md)
Measured on Apple Silicon (M-series), Node 22.22.1, vitest 4.0.16. Scenario: 1,000 random 128-dim cosine-normalized vectors loaded into a single HNSWIndex, then 200 query iterations after warmup.
| Metric | Value | Notes |
|---|---|---|
build_time_ms |
533.42 ms | Sequential addPoint() × 1,000 |
search_k10_avg_ms |
0.5294 ms | Post-warmup, average of 200 iterations |
search_k50_avg_ms |
0.5235 ms | k=50 ≈ k=10 — heap-based selection dominates |
add_avg_ms |
0.8656 ms | Incremental insert after the initial 1k |
search_k10_ops_per_sec |
1,888.9 ops/s | Derived |
search_k50_ops_per_sec |
1,910.1 ops/s | Derived |
These numbers are device-specific; CI baselines will replace this file once the GitHub Actions bench job lands. ADR-125 Phase 3 (persistent HNSW) means cold-start restoration should be a small fraction of build_time_ms once the snapshot benchmark is added.
ADR-049 Benchmarks
| Operation | Actual | Target | Headroom |
|---|---|---|---|
| Graph build (1k nodes) | 2.78 ms | <200 ms | 71.9x |
| PageRank (1k nodes) | 12.21 ms | <100 ms | 8.2x |
| Insight recording | 0.12 ms/each | <5 ms/each | 41.0x |
| Consolidation | 0.26 ms | <500 ms | 1,955x |
| Confidence decay (1k) | 0.23 ms | <50 ms | 215x |
| Knowledge transfer | 1.25 ms | <100 ms | 80.0x |
TypeScript Types
import type {
// Core
HNSWConfig, HNSWStats, SearchResult, MemoryEntry,
QuantizationConfig, DistanceMetric,
// Auto Memory Bridge (ADR-048)
AutoMemoryBridgeConfig, MemoryInsight, InsightCategory,
SyncDirection, SyncMode, PruneStrategy,
SyncResult, ImportResult,
// Learning Bridge (ADR-049)
LearningBridgeConfig, LearningStats,
ConsolidateResult, PatternMatch,
// Knowledge Graph (ADR-049)
MemoryGraphConfig, GraphNode, GraphEdge,
GraphStats, RankedResult, EdgeType,
// Agent Scope (ADR-049)
AgentMemoryScope, AgentScopedConfig,
TransferOptions, TransferResult,
} from '@claude-flow/memory';
Dependencies
agentdb^3.0.0-alpha.14— Vector database enginesql.js— SQLite driver via WASM (always available; no native build required)better-sqlite3— Optional native SQLite driver for higher throughput. The package works without it (sql.js fallback), so installs succeed on Node 24/26 even when the native build can't compile (#1867)@claude-flow/embeddings— Optional for semantic search. When absent or failing,search()automatically falls back to FTS5 keyword (see Graceful retrieval)@claude-flow/neural— Optional peer dependency for self-learning (graceful fallback when unavailable)
Related Packages
- @claude-flow/neural - Neural learning integration (SONA, ReasoningBank, EWC++)
- @claude-flow/shared - Shared types and utilities
- @claude-flow/hooks - Session lifecycle hooks for auto memory sync
License
MIT