integrate: dream-cycle memory/neural fixes (#4660, #4973, #4081, #3650, #4983, #5034, #5012) (#5041)

* dream(memory): #3649 restore quantizer config/codebooks across HNSWIndex serialize/deserialize

HNSWIndex.serialize()/deserialize() never persisted config.quantization or
trained PQ codebooks, so this.quantizer came back null after any
save/reload cycle — silently re-breaking the product-quantization distance
dispatch fixed 2026-08-25 (#3093/#3094) every time AgentDBAdapter.saveToDisk()/
loadFromDisk() round-trips an index. Added a versioned magic header (v1/v2)
so serialize() now writes quantization config + trained codebooks, and
deserialize() restores them, while old-format snapshots still read
correctly with no quantizer (unchanged pre-existing behavior).

Evaluated: pre-serialize recall@10 0.270 -> post-deserialize 0.010 on
baseline (bug reproduced) -> ~0.270 on candidate. 557/558 full suite both
ways (1 pre-existing unrelated failure), tsc clean. Independent adversarial
critic CONFIRMED, including a stronger real pre-fix v1-buffer repro.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01TfsQojjDGj9ZEgPo6qZvPc

* docs(dream-cycle): fill candidate commit sha in 2026-10-03 gist witness table

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01TfsQojjDGj9ZEgPo6qZvPc

* fix(memory): validate importCodebooks() input, reject malformed shape

Addresses ruvnet's review on #3650: deserialize() fed JSON.parse() output
straight into this.codebooks with no validation, so a corrupted v2
snapshot could either throw (invalid JSON) or silently adopt a
wrong-shaped/non-finite codebooks array, poisoning every subsequent
distance computed against it with garbage or NaN.

importCodebooks() now validates shape (numSubquantizers sub-arrays, each
numCentroids centroids of the expected per-subvector length) and that
every value is a finite number, returning false and leaving the quantizer
untrained on any mismatch -- same as the existing pre-training bootstrap
state, not a new failure mode. deserialize() now guards the JSON.parse()
call itself so corrupt JSON degrades to "untrained" instead of throwing.

2 new discriminating tests, both verified to fail against the pre-fix
code via git-stash isolation (one throws on corrupt JSON, one silently
accepted a wrong-shaped array). Full suite 559/560 (1 pre-existing
unrelated failure), tsc --noEmit clean.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01TfsQojjDGj9ZEgPo6qZvPc

* docs(dream-cycle): record post-review hardening in 2026-10-03 gist

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01TfsQojjDGj9ZEgPo6qZvPc

* dream(intelligence): #4080 wire SONA learning-state persistence into LearningBridge (evaluated, ACCEPT)

LearningBridge is the only production path that exercises SONAManager
(via auto-memory-hook.mjs's SessionStart/SessionEnd hooks), and every
short-lived hook invocation constructed a fresh, empty neural learning
state. SONAManager.serialize()/deserialize() already existed but were
never called. Wires that round-trip into LearningBridge.loadNeural()
(restore) and destroy() (persist, synchronous since destroy() is called
unawaited right before process exit), mirroring MoERouter's existing
.swarm/moe-weights.json persistence pattern.

This supersedes the handed-in candidate for tonight (fixing SONAManager's
EWC key-mismatch), which an architecture review proved would be
behaviorally inert: SONAManager.loraWeights.A/B are never updated by
gradient descent anywhere, so aligning EWC's keys would only change
internal telemetry, not real behavior. The persistence gap fixed here is
the actual root cause making SONA's learning trigger (EWC included)
practically unreachable in the first place.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01K7m7AnVWdCQRydcfxzK6ke

* docs(dream-cycle): append 2026-10-12 intelligence ledger row

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01K7m7AnVWdCQRydcfxzK6ke

* chore(release): bump neural/memory leaves for #4081's source change

v3/@claude-flow/neural and v3/@claude-flow/memory are non-bundled leaf
packages resolved from the registry, not shipped with the release train
(CLAUDE.md "Publishing Rules") — a source change without a version bump
would ship nobody the fix (ruvnet/ruflo#3335, #3390). Minor-bumps both
(3.0.0->3.1.0, 3.0.4->3.1.0: backward-compatible additions, no breaking
API change) and updates v3/@claude-flow/cli's exact pins + v3/pnpm-lock.yaml
to match.

Root claude-flow's own @claude-flow/neural dependency resolves from the
real npm registry (not a workspace link, confirmed via package-lock.json's
resolved tarball URL) — widened to "^3.0.0" rather than bumped to "3.1.0",
since 3.1.0 isn't published yet and pinning to it would break `npm ci`.
@claude-flow/memory isn't a direct dependency of the root package, so it
needed no equivalent change there.

Verified: audit-leaf-package-publish.mjs, audit-wrapper-dep-ranges.mjs,
audit-plugin-packages.mjs, audit-package-dep-overlap.mjs, and
audit-umbrella-version-lockstep.mjs all pass locally; `npm ci` and
`pnpm install --frozen-lockfile` (in v3/) both succeed cleanly.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01K7m7AnVWdCQRydcfxzK6ke

* fix(cli): widen neural/memory pins to ranges, not an unpublished exact version

The previous commit exact-pinned @claude-flow/cli's neural/memory deps to
3.1.0 to match the leaf version bump — but the CLI package is consumed via
real npm resolution when packed/installed (npx, or a real `npm install` of
the published tarball), not via the pnpm workspace link that made the pin
look fine locally. 3.1.0 isn't published, so smoke-cli-npx-install.mjs's
real `npm install` of the packed CLI tarball failed: `ETARGET No matching
version found for @claude-flow/neural@3.1.0`.

Same fix as the prior commit's root package.json change: widen to "^3.0.0"
rather than bump to the unpublished version. This still satisfies
audit-leaf-package-publish.mjs's range-coverage check (^3.0.0 covers the
workspace's 3.1.0) without requiring a real registry publish, and resolves
correctly to whatever's actually published (3.0.0) when installed for
real. CLAUDE.md documents this exact failure mode happening before
(memory@3.0.0-alpha.27, 2026-09-28) — exact-pinning to vaporware breaks
installs outright.

Verified: ran scripts/smoke-cli-npx-install.mjs locally end-to-end (packs
the real tarball, npm installs it, runs `cli --version`) — passes. All
other audit scripts + both packages' test suites unchanged/green.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01K7m7AnVWdCQRydcfxzK6ke

* fix(cli): restore exact memory pin to satisfy witness-marker guard (#2021/#1825)

The previous commit widened @claude-flow/cli's "@claude-flow/memory" dep
(both dependencies and optionalDependencies) to "^3.0.0" to avoid the same
ETARGET problem neural hit. That broke a different, deliberate guard:
`witness marker drift smoke (#2021)` flags any change to a line previously
witnessed as a historical fix. #1825's fix (PR #1827) specifically pins
this field to an exact "3.x" version after a `workspace:` protocol leak
crashed npm's resolver entirely for ALL users — the marker
`"@claude-flow/memory": "3.` guards against regressing that.

memory doesn't need the same treatment neural got: it's listed in BOTH
`dependencies` and `optionalDependencies` (pre-existing, not introduced
here), and pnpm/npm treat a dependency declared in both as optional
overall — confirmed empirically by running scripts/smoke-cli-npx-install.mjs
locally with memory exact-pinned to the unpublished 3.1.0: npm installs
the tarball cleanly, because an unresolvable optional dependency doesn't
fail the install (unlike neural, which is required and must stay on a
range that resolves to what's actually published).

Restored the exact "3.1.0" pin (matching the new leaf version, satisfying
both the witness marker's "3." substring and
audit-leaf-package-publish.mjs's range-coverage) in both package.json
fields and the pnpm-lock.yaml specifier; left neural's "^3.0.0" from the
prior commit untouched.

Verified: smoke-witness-marker-drift.mjs (0 drifted, was 1),
smoke-cli-npx-install.mjs, audit-leaf-package-publish.mjs,
audit-wrapper-dep-ranges.mjs, audit-plugin-packages.mjs,
audit-package-dep-overlap.mjs, audit-umbrella-version-lockstep.mjs all
pass; pnpm install --frozen-lockfile (v3/) succeeds; both affected
packages' test suites unchanged.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01K7m7AnVWdCQRydcfxzK6ke

* fix(memory,neural): harden SONA state persistence found in #4081 review

- LearningBridge never follows a symlink at statePath (read or write) and never
  writes into a symlinked directory: the file lives in the project directory, so
  it is untrusted input (reproduced: a planted symlink was overwritten).
- Atomic write (private 0600 temp file + rename); no torn files.
- Persist only when something was learned: no stray .swarm/ in every cwd.
- A file from another schema version is preserved, never overwritten.
- A rejected restore is rolled back to the pre-restore snapshot; reads are size-capped.
- SONAManager.deserialize validates the whole snapshot before assigning any field
  (reproduced: {"schemaVersion":1} left the manager half-applied and permanently
  unable to learn or self-heal).
Known limitation, documented: concurrent processes are last-writer-wins
(8 parallel processes kept 4 of 8 trajectories).

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

* dream(intelligence): #LOCAL wire ResearchMode.getConsolidationSnapshot() into SONA EWC++ (evaluated, ACCEPT-scoped)

Continues 2026-10-27 (#4531/#4532) and 2026-11-01 (#4633 SCAN)'s own
disclosed gap: BalancedMode was the only SONA learning mode wired into
SONAManager's EWC++ consolidation path. ResearchMode already maintains
real per-key gradient-shaped state (adamM/adamV, already read back by its
own dormant computeEWCLoss()) so it can be wired honestly using the exact
reviewed Balanced-mode delta-since-snapshot pattern, with zero
sona-manager.ts changes needed (the hook is mode-agnostic).

EdgeMode and RealTimeMode are explicitly NOT wired (no real gradient-shaped
state exists to snapshot without fabricating it); BatchMode is also not
wired (its accumulatedGradients map is zeroed on an independent 4-step
flush cadence, making a direct port semantically ambiguous).

5 new tests (3 discriminating, 2 controls), stash-isolated baseline fails
3/5 exactly as predicted, candidate 5/5 pass. Full @claude-flow/neural
suite 153/153 both ways except the 3 discriminating failures, 0
regressions. tsc --noEmit 0 errors both ways. Independent adversarial
critique: CONFIRMED-WITH-CAVEATS (one test-strength nit, fixed forward
same session).

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01ReiDH7BxmEedHJQP2wdfCq

* docs(dream-cycle): fill in witness stamp for 2026-11-02 gist

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01ReiDH7BxmEedHJQP2wdfCq

* docs(dream-cycle): append 2026-11-02 ledger row (#4659/#4660)

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01ReiDH7BxmEedHJQP2wdfCq

* fix(ci): bump @claude-flow/neural to 3.0.3 for the leaf-package-publish audit

CI's audit-leaf-package-publish.mjs correctly flagged this PR: @claude-flow/
neural is a non-bundled leaf (resolves from the registry, not shipped inside
the release train tarballs), and this PR changed its publishable source
(src/modes/research.ts) without bumping its package.json version — a release
now would ship the old copy and the ResearchMode EWC fix would reach nobody.

Bumps v3/@claude-flow/neural to 3.0.3 and the CLI's exact pin + lockfile
specifier to match (the CLI pins an exact version, not a range, so both must
move together). Verified locally: audit-leaf-package-publish.mjs now passes
clean against the PR base; @claude-flow/neural suite still 153/153, tsc
--noEmit still 0 errors.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01ReiDH7BxmEedHJQP2wdfCq

* fix(ci): bump root claude-flow umbrella's @claude-flow/neural pin to 3.0.3

audit-wrapper-dep-ranges.mjs flagged a second, independent pin: the root
claude-flow umbrella's own dependencies block also pins @claude-flow/neural
exactly, separately from the CLI's pin fixed in 0e5b4a9. Bumped to 3.0.3 to
match the workspace source version. package-lock.json's resolved tarball
entry intentionally stays at the last-published 3.0.2 until neural is
actually published alongside a future release -- that's expected pre-publish
drift, not something this PR fixes, per CLAUDE.md's publishing rules.

Verified locally: audit-wrapper-dep-ranges.mjs, audit-leaf-package-publish.mjs,
and audit-umbrella-version-lockstep.mjs all pass clean.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01ReiDH7BxmEedHJQP2wdfCq

* Revert "fix(ci): bump root claude-flow umbrella's @claude-flow/neural pin to 3.0.3"

This reverts commit 9c060b680e.

* Revert "fix(ci): bump @claude-flow/neural to 3.0.3 for the leaf-package-publish audit"

This reverts commit 0e5b4a9852.

* dream(intelligence): #4972 SONAManager.triggerLearning() backlog-replay fix (post-critique scoped)

triggerLearning() re-filtered the entire trajectories map every call with
no "already learned from" marker, so trajectories surviving pruning got
re-fed into gradient accumulation / EWC Fisher updates on every subsequent
cycle, purely from replay. Disclosed-but-not-fixed 2026-10-27 (#4531/#4532);
fixed here via a new Trajectory.learnedFrom gate.

An independent adversarial critique found the fix is real but narrower
than first claimed: it stops replay of stalled trajectories, but
BalancedMode's gradientAccumulator/ewcState.means are never reset at all,
so the same unbounded growth persists under ordinary continuous operation.
Disclosed in both test docstrings and the gist, carried forward as the
next priority candidate rather than shipped as fully fixed.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01ReiDH6sq7KJoxGzn3ZSEAm

* dream(intelligence): #4972 record PR #4973 in ledger

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01ReiDH6sq7KJoxGzn3ZSEAm

* dream(intelligence): #4972 bump @claude-flow/neural to 3.0.4

Patch bump for the triggerLearning() backlog-replay fix — neural is a
non-bundled leaf resolved from the registry, so the CLI's pin must be
raised and the leaf republished at actual release time for this fix to
reach users (CLAUDE.md "Publishing Rules"; CI's
audit-leaf-package-publish.mjs caught the unbumped version).

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01ReiDH6sq7KJoxGzn3ZSEAm

* dream(memory): wire causalRecall into ControllerRegistry.initialize()

ControllerRegistry declares `causalRecall` as an AgentDBControllerName
with a real createController() case (dynamic agentdb import, built with
the ADR-514-adapted embedder, same shape as its already-wired siblings
causalGraph/learningSystem/explainableRecall) and includes it in the
isControllerEnabled() "AgentDB-internal controllers" branch. But it was
absent from every level of INIT_LEVELS, so initialize() never called
createController() for it, and the public get() accessor's fallback path
(agentdb[name] / agentdb.getController(name)) never runs this wrapper's
own construction logic either. Net effect: registry.get('causalRecall')
always returned null, silently.

Disclosed-but-deferred by a 2026-10-28 session ("needs a human call on
init-level ordering"). agentdb and its .database/.embedder/.vectorBackend
are already populated before the INIT_LEVELS loop runs, so level
placement doesn't affect correctness; grouped with construction-sibling
causalGraph in level 4.

Two discriminating tests added: a structural assertion that causalRecall
appears in INIT_LEVELS, and an extension of the existing ADR-514
real-agentdb embedder-wiring integration test to cover causalRecall
alongside its siblings. Both fail against the baseline exactly as
predicted (toContain assertion; get() returns null) and pass against the
candidate. Full package suite 717/718 with the fix (1 pre-existing,
unrelated, environmental chmod-as-root failure in
auto-memory-bridge.test.ts, confirmed byte-identical on the stashed
baseline). tsc --noEmit clean both ways.

Zero production call sites currently request causalRecall, so today's
blast radius is zero — this makes a correctly-built, research-aligned
capability (causal-provenance-conditioned memory recall) reachable for
the first time rather than fixing a live breakage.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01ReiDH5vDhjQF9zXr1xHT2a

* fixup(memory): correct causalGraph construction claim in causalRecall comments

Independent adversarial critique (Dream Cycle 2026-11-13) found the prior
commit's comments overstated that causalRecall is "same shape as
causalGraph" — causalGraph is actually built via agentdb's own
getController() switch, not the dynamic-import-and-construct pattern
causalRecall shares with learningSystem/explainableRecall. Cosmetic only;
does not change behavior. Re-ran the targeted suite (94/94) and
tsc --noEmit (clean) after this change.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01ReiDH5vDhjQF9zXr1xHT2a

* docs(dream-cycle): add 2026-11-13 memory SOTA gist

Gist publishing blocked by the environment's proxy policy ("Gist writes
are not permitted through this proxy", HTTP 403 on api.github.com/gists)
-- a different root cause than prior nights' broken GH_TOKEN, same
FALLBACK-for-remote-gist-publication outcome. Committed locally per
established convention; full report embedded in the issue as well.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01ReiDH5vDhjQF9zXr1xHT2a

* docs(dream-cycle): append 2026-11-13 ledger row

Issue #4982, PR #4983 (causalRecall wired into ControllerRegistry.initialize()).

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01ReiDH5vDhjQF9zXr1xHT2a

* chore(memory): bump @claude-flow/memory to 3.3.3 for the causalRecall fix

CI's audit-leaf-package-publish.mjs (added 2026-11-02, ruvnet/ruflo#3335/
#3390/#3327 Finding A) flags any non-bundled @claude-flow/* leaf whose
publishable source changed without a version bump -- @claude-flow/memory
is resolved from the registry by @claude-flow/cli, not bundled into the
release tarball, so an unbumped source change here would silently never
reach a fresh install. PATCH bump (bug fix, no API/schema change) per
CLAUDE.md's semver policy.

This does not, by itself, turn the check fully green: the CLI's exact pin
(v3/@claude-flow/cli/package.json, still "3.3.2") now fails the sibling
range-coverage check, since 3.3.3 is not yet published and the pin cannot
honestly point at an unpublished version. Same unresolved shape as PR
#4973 (2026-11-12), which hit the identical gap bumping
@claude-flow/neural and left it to a human publish -- full resolution
needs `npm publish @claude-flow/memory@3.3.3` plus a CLI-pin bump in a
follow-up, which is outside this session's authority (see CLAUDE.md
"Publishing to npm").

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01ReiDH5vDhjQF9zXr1xHT2a

* dream(intelligence): ReasoningBank.distill() discards failed trajectories, losing all pitfall-avoidance memory

ReasoningBank.distill() judged every trajectory but only distilled
successes into the retrievable memory pool; failures were judged then
unconditionally discarded. An accepted ICLR 2026 paper (ReasoningBank,
arXiv 2509.25140) measures that failure-aware distillation beats
success-only memory on web/SWE benchmarks, and Ruflo already has a
disconnected dual-track distiller (reasoningbank-adapter.ts) showing the
team built this pattern once and never wired it in.

- distill() now distills unsuccessful trajectories into a distinct
  memoryType: 'pitfall' memory (strategy framed as "AVOID: ...") instead
  of returning null, for any trajectory with at least one recorded step.
- completeTask()'s call into PatternLearner.extractPattern() is now
  gated on memoryType === 'success', so a pitfall can never be promoted
  into a positive-exemplar Pattern (independently confirmed by adversarial
  critique to be load-bearing: PatternLearner's own qualityThreshold
  (0.5) and ReasoningBank's distillationThreshold (0.6) already diverge,
  so a ~0.55-quality trajectory could reach extractPattern with no prior
  memoryType field to stop it).
- deduplicateMemories() is fixed forward: it would otherwise delete a
  pitfall memory that happens to share a near-identical embedding with a
  higher-quality success memory, treating opposite outcomes as
  duplicates -- a direct consequence of merging both types into one
  pool. Dedup now skips any pair whose memoryType differs.

Evaluated: stash-isolated baseline fails exactly the new/changed tests
(38/42 unaffected pass); candidate 43/43; full package 152/152, 0
regressions; related @claude-flow/memory learning-bridge suite 78/78;
tsc --noEmit clean. Independently reproduced by an adversarial critic
(verdict: CONFIRMED-WITH-CAVEATS -> forward-fixed -> re-verified).

Human review required. Do not self-merge.

* dream(intelligence): #5011 publish research gist (local, no gh gist access)

docs/dream-cycle/dream-gist-2026-11-17.md -- full SOTA report, competitor
comparison, hypothesis, evaluation receipt, and witness for issue #5011.

* dream(intelligence): #5011 append ledger row (PR #5012)

* dream(intelligence): #5011 bump @claude-flow/neural to 3.0.4 (CI: leaf-package-publish)

The "Plugin package install-safety" CI gate (audit-leaf-package-publish.mjs)
correctly flagged that this PR changes @claude-flow/neural's publishable
source (index.ts, reasoning-bank.ts, types.ts) without a version bump --
it's a non-bundled leaf per CLAUDE.md's Publishing Rules, so an unbumped
version means the fix would ship to nobody at release time. Bump to 3.0.4
(patch: bug fix, no breaking API removal) and keep @claude-flow/cli's
exact pin in lockstep to avoid introducing new cli-pin/workspace drift.

* dream(intelligence): #5011 sync v3/pnpm-lock.yaml for @claude-flow/neural@3.0.4

CI's "Smoke (no better-sqlite3)" and "Static regression guards" jobs both
failed with ERR_PNPM_OUTDATED_LOCKFILE after the prior commit bumped
@claude-flow/cli's @claude-flow/neural specifier without regenerating the
lockfile in the same commit. @claude-flow/neural resolves via
link:../neural regardless of specifier value (it's a local workspace
link, not a registry/integrity entry), so this is a minimal, surgical
specifier-only edit rather than a full `pnpm install --lockfile-only`
regen -- the latter pulled in unrelated pre-existing drift (@claude-flow/codex
and @claude-flow/memory switching to workspace links, a ruvector bump)
that has nothing to do with this PR. Verified locally with pnpm@8.15.0
(matching CI's pinned version, not this environment's default pnpm@10.28,
which produces a differently-shaped lockfile): `pnpm install
--frozen-lockfile --lockfile-only` now passes clean.

* dream(intelligence): #5011 bump root package.json's @claude-flow/neural range too

audit-wrapper-dep-ranges.mjs caught a third pin location I'd missed:
the root `claude-flow` umbrella package.json declares its own
"@claude-flow/neural": "3.0.3" dependency range, separate from
@claude-flow/cli's pin. Bumped to 3.0.4 to match. Did NOT touch
package-lock.json: its @claude-flow/neural entry carries a real
resolved/integrity hash from the npm registry for 3.0.3, and
@claude-flow/neural@3.0.4 is not yet published there -- regenerating it
would require either a real `npm install` (which fails ETARGET, same as
the CLI npx-install smoke failure already reported on this PR) or
fabricating a resolved URL/integrity for a tarball that doesn't exist,
which would be unsafe. Any CI job that runs `npm ci` at the repo root
will stay red for the same reason already documented on this PR: this
needs an actual npm publish of @claude-flow/neural@3.0.4, which is a
separate, human-authorized release action outside this session's scope.

* Revert "dream(intelligence): #5011 bump root package.json's @claude-flow/neural range too"

This reverts commit 96f0a32e56.

* dream(memory): #5033 CacheManager frequency-aware eviction (HTM-EAR-grounded)

Adds an opt-in, Darwin-tuned frequencyWeight/evictionScanWindow blend to
CacheManager's eviction policy. Default (unset/0) is byte-identical to the
existing pure-LRU tail eviction via an early return - zero behavior change
for every current caller (AgentDBAdapter, TieredCacheManager,
ControllerRegistry's tieredCache).

Motivated by HTM-EAR (arXiv:2603.10032, Feb 2026), which shows pure-LRU
eviction permanently drops high-access-frequency entries under skewed
access even though CachedEntry.accessCount already tracks exactly the
signal needed.

Evaluation: baseline 718/719 (1 pre-existing environmental failure) ->
candidate 722/723, tsc clean both ways, stash-isolated discriminating
tests fail on baseline exactly as predicted. Independently reproduced by a
fresh-context adversarial critic (verdict: CONFIRMED). Bounded 3-gen x
4-candidate Darwin sweep over a new synthetic skewed-workload benchmark
finds an interior optimum (frequencyWeight=0.85) that beats both the
baseline and a naive frequencyWeight=1.0 - full lineage persisted.

Full receipt in docs/dream-cycle/dream-gist-2026-11-18.md and issue #5033.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01ReiDH4YtmHBfXwGDoLNB76

* dream(memory): #5033 witness finalization

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01ReiDH4YtmHBfXwGDoLNB76

* dream(memory): #5033 ledger update

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01ReiDH4YtmHBfXwGDoLNB76

* dream(memory): #5033 bump @claude-flow/memory 3.3.3 -> 3.4.0 + CLI pin

audit-leaf-package-publish flagged that this PR changes publishable
source in @claude-flow/memory (a non-bundled leaf that resolves from the
registry, not the release tarball) without a version bump - per
CLAUDE.md's Publishing Rules, that would ship nobody the fix.

Minor bump (backward-compatible: two new optional CacheConfig fields,
default-off). CLI's exact pin raised to match, mirroring PR #5021's
documented precedent for @claude-flow/cli-core: the leaf needs an actual
npm publish before a real release, which is a separately-authorized
human action out of scope for this PR. v3/pnpm-lock.yaml is deliberately
left unchanged (still resolving 3.3.3) until that publish happens - its
integrity entries can't be computed for an unpublished tarball, same
reasoning as #5021's "fill in the integrity after the publish".

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01ReiDH4YtmHBfXwGDoLNB76

* dream(memory): #5033 sync pnpm-lock.yaml specifier for the memory bump

pnpm install --frozen-lockfile was failing (ERR_PNPM_OUTDATED_LOCKFILE)
across ~14 CI jobs (Smoke, Type Check V3, Test V3 Packages, Plugin hooks
smoke, Windows hooks smoke, MCP paired-tool smoke, guard, etc.) because
v3/pnpm-lock.yaml still specified @claude-flow/memory@3.3.3 for the cli
importer after 7423f32 bumped package.json to 3.4.0.

Minimal hand-edit (2 lines), not a full `pnpm install --no-frozen-lockfile`
regeneration - that pulls in unrelated registry drift (ruvector/router
version bumps, dropped platform-optional entries) with no connection to
this change, which PR #5021 explicitly avoided for the same reason
("lockfiles are hand-edited to the minimum"). The cli importer's entry now
resolves via workspace link (`link:../memory`), matching how every other
importer in this lockfile already references @claude-flow/memory. Verified
locally: `pnpm install --frozen-lockfile` passes.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01ReiDH4YtmHBfXwGDoLNB76

* fix(neural): keep distill()'s success-path threshold from #5012

#5012 dropped the distillationThreshold check for every trajectory. judge()
already applies it to success verdicts, but a verdict set without judge()
would now distill below threshold. Restore the check for successes only;
pitfalls are unaffected.

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

* chore(release): bump @claude-flow/neural 3.1.0 and @claude-flow/memory 3.4.0

One bump per touched leaf for the integrated dream-cycle fixes (both add
public surface: NeuralLearningSystem.serialize/deserialize,
DistilledMemory.memoryType, Trajectory.learnedFrom; LearningBridge statePath,
CacheConfig.frequencyWeight/evictionScanWindow). CLI and root umbrella pins
follow. pnpm-lock edited by hand (specifiers only, plus memory now linking
to the workspace since 3.4.0 is not yet on npm). The root package-lock.json
still records neural 3.0.3 and needs a refresh after the leaves publish
(same as 68c8d74b23 -> 3ce46cfa57).

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

* fix(neural): treat memories without memoryType as successes when deduplicating

ReasoningBank snapshots saved before #5012 have no memoryType, so the new
success/pitfall dedup guard never matched them against fresh success
memories. They only ever held successes; default the field accordingly.

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

* chore(deps): root lockfile resolves published @claude-flow/neural 3.1.0

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: r <r@x>
This commit is contained in:
authored and GitHub committed 2026-11-19 01:44:33 -05:00
1 parent 5cdb56feb7
commit 89a00242b3
38 files changed
+2745 -54

No files matched your search

@@ -0,0 +1,17 @@
{
"corpus_path": ".harness/bench-memory-eviction-2026-11-18.json",
"created_by_date": "2026-11-18",
"created_by_hypothesis": "CacheManager frequency-aware eviction (HTM-EAR arXiv:2603.10032) -- frequencyWeight/evictionScanWindow tuning",
"task_count": 6,
"task_categories": ["mild-skew", "moderate-skew", "severe-skew"],
"gold_data_source": "synthetically generated by scripts/bench-cache-eviction.mjs from the seeds below; 'golden' keys = the true top-decile most-accessed keys in each generated access trace, computed independently of any cache eviction policy before the trace is replayed",
"notes": "Each task replays a deterministic Zipfian-skewed key-access trace (seeded PRNG, no external data) through a real CacheManager instance (not a simulation/reimplementation) with maxSize well below numKeys, forcing eviction. Metric: fraction of golden (truly highest-frequency) keys still resident at the end of the trace, plus ops/sec throughput. This benchmark was authored tonight specifically to evaluate tonight's own candidate -- see the periodic corpus-fairness caveat in the issue/PR (STEP 10): it has not yet been run against an unrelated weak candidate to prove it has teeth, which is disclosed as a limitation, not resolved.",
"tasks": [
{ "id": "mild-1", "seed": 1001, "numKeys": 40, "maxSize": 12, "numOps": 2000, "skewExponent": 0.6, "goldenTopFraction": 0.1 },
{ "id": "mild-2", "seed": 1002, "numKeys": 60, "maxSize": 15, "numOps": 3000, "skewExponent": 0.6, "goldenTopFraction": 0.1 },
{ "id": "moderate-1", "seed": 2001, "numKeys": 40, "maxSize": 12, "numOps": 2000, "skewExponent": 1.1, "goldenTopFraction": 0.1 },
{ "id": "moderate-2", "seed": 2002, "numKeys": 60, "maxSize": 15, "numOps": 3000, "skewExponent": 1.1, "goldenTopFraction": 0.1 },
{ "id": "severe-1", "seed": 3001, "numKeys": 40, "maxSize": 12, "numOps": 2000, "skewExponent": 1.8, "goldenTopFraction": 0.1 },
{ "id": "severe-2", "seed": 3002, "numKeys": 60, "maxSize": 15, "numOps": 3000, "skewExponent": 1.8, "goldenTopFraction": 0.1 }
]
}
+227
View File
@@ -0,0 +1,227 @@
{
"baselineEval": {
"candidate": {
"frequencyWeight": 0,
"evictionScanWindow": 32
},
"quality": 0.5,
"successRate": 1,
"latency": 1,
"costEfficiency": 1,
"reproducibility": 1,
"safety": 1,
"fitness": 0.825,
"meanRetentionDelta": 0,
"meanOpsRatio": 1.0189885574485578
},
"lineage": [
{
"candidate": {
"frequencyWeight": 0.25,
"evictionScanWindow": 32
},
"quality": 0.5,
"successRate": 1,
"latency": 0.8459947209361269,
"costEfficiency": 1,
"reproducibility": 1,
"safety": 1,
"fitness": 0.8018992081404189,
"meanRetentionDelta": 0,
"meanOpsRatio": 0.8459947209361269,
"generation": 1
},
{
"candidate": {
"frequencyWeight": 0.5,
"evictionScanWindow": 32
},
"quality": 0.5138888888888888,
"successRate": 1,
"latency": 0.9679645154304543,
"costEfficiency": 1,
"reproducibility": 1,
"safety": 1,
"fitness": 0.8250557884256792,
"meanRetentionDelta": 0.027777777777777773,
"meanOpsRatio": 0.9679645154304543,
"generation": 1
},
{
"candidate": {
"frequencyWeight": 0.75,
"evictionScanWindow": 32
},
"quality": 0.5625,
"successRate": 1,
"latency": 0.99520369062745,
"costEfficiency": 1,
"reproducibility": 1,
"safety": 1,
"fitness": 0.8461555535941174,
"meanRetentionDelta": 0.125,
"meanOpsRatio": 0.99520369062745,
"generation": 1
},
{
"candidate": {
"frequencyWeight": 1,
"evictionScanWindow": 32
},
"quality": 0.5625,
"successRate": 0.8333333333333334,
"latency": 0.9839787268849135,
"costEfficiency": 1,
"reproducibility": 1,
"safety": 0.8333333333333334,
"fitness": 0.7944718090327371,
"meanRetentionDelta": 0.12499999999999999,
"meanOpsRatio": 0.9839787268849135,
"generation": 1
},
{
"candidate": {
"frequencyWeight": 0.75,
"evictionScanWindow": 8
},
"quality": 0.5763888888888888,
"successRate": 1,
"latency": 0.9542000513428158,
"costEfficiency": 1,
"reproducibility": 1,
"safety": 1,
"fitness": 0.8448661188125334,
"meanRetentionDelta": 0.15277777777777776,
"meanOpsRatio": 0.9542000513428158,
"generation": 2
},
{
"candidate": {
"frequencyWeight": 0.75,
"evictionScanWindow": 16
},
"quality": 0.5625,
"successRate": 1,
"latency": 0.9660947630936612,
"costEfficiency": 1,
"reproducibility": 1,
"safety": 1,
"fitness": 0.8417892144640491,
"meanRetentionDelta": 0.125,
"meanOpsRatio": 0.9660947630936612,
"generation": 2
},
{
"candidate": {
"frequencyWeight": 0.75,
"evictionScanWindow": 32
},
"quality": 0.5625,
"successRate": 1,
"latency": 0.9692733165184113,
"costEfficiency": 1,
"reproducibility": 1,
"safety": 1,
"fitness": 0.8422659974777617,
"meanRetentionDelta": 0.125,
"meanOpsRatio": 0.9692733165184113,
"generation": 2
},
{
"candidate": {
"frequencyWeight": 0.75,
"evictionScanWindow": 64
},
"quality": 0.5625,
"successRate": 1,
"latency": 0.994950328239898,
"costEfficiency": 1,
"reproducibility": 1,
"safety": 1,
"fitness": 0.8461175492359846,
"meanRetentionDelta": 0.125,
"meanOpsRatio": 0.994950328239898,
"generation": 2
},
{
"candidate": {
"frequencyWeight": 0.55,
"evictionScanWindow": 32
},
"quality": 0.5138888888888888,
"successRate": 1,
"latency": 0.9281190352575156,
"costEfficiency": 1,
"reproducibility": 1,
"safety": 1,
"fitness": 0.8190789663997383,
"meanRetentionDelta": 0.027777777777777773,
"meanOpsRatio": 0.9281190352575156,
"generation": 3
},
{
"candidate": {
"frequencyWeight": 0.65,
"evictionScanWindow": 32
},
"quality": 0.5347222222222222,
"successRate": 1,
"latency": 0.9476806019421461,
"costEfficiency": 1,
"reproducibility": 1,
"safety": 1,
"fitness": 0.8293048680690996,
"meanRetentionDelta": 0.06944444444444443,
"meanOpsRatio": 0.9476806019421461,
"generation": 3
},
{
"candidate": {
"frequencyWeight": 0.85,
"evictionScanWindow": 32
},
"quality": 0.5972222222222222,
"successRate": 1,
"latency": 0.9480068455034522,
"costEfficiency": 1,
"reproducibility": 1,
"safety": 1,
"fitness": 0.8512288046032955,
"meanRetentionDelta": 0.19444444444444442,
"meanOpsRatio": 0.9480068455034522,
"generation": 3
},
{
"candidate": {
"frequencyWeight": 0.95,
"evictionScanWindow": 32
},
"quality": 0.5625,
"successRate": 0.8333333333333334,
"latency": 0.9584037476969183,
"costEfficiency": 1,
"reproducibility": 1,
"safety": 0.8333333333333334,
"fitness": 0.7906355621545377,
"meanRetentionDelta": 0.12499999999999999,
"meanOpsRatio": 0.9584037476969183,
"generation": 3
}
],
"finalWinner": {
"candidate": {
"frequencyWeight": 0.85,
"evictionScanWindow": 32
},
"quality": 0.5972222222222222,
"successRate": 1,
"latency": 0.9480068455034522,
"costEfficiency": 1,
"reproducibility": 1,
"safety": 1,
"fitness": 0.8512288046032955,
"meanRetentionDelta": 0.19444444444444442,
"meanOpsRatio": 0.9480068455034522,
"generation": 3
}
}
+13
View File
@@ -267,6 +267,19 @@ as a first-class, high-priority candidate, not a background note.
| 2026-11-13 | memory | `ControllerRegistry.initialize()`'s `INIT_LEVELS` never listed `causalRecall`, so `get('causalRecall')` always returned `null` despite a correct, already-written `createController()` case (same declared-but-unreachable-config shape as 10-28's `.set()` fix). Added `causalRecall` to Level 4 | #4982 | #4983 | yes | ACCEPT (evaluated) | 2 new discriminating tests, stash-isolated baseline fails as predicted → 94/94 candidate; full `@claude-flow/memory` suite 717/718 (1 pre-existing unrelated environmental failure, byte-identical); `tsc --noEmit` clean both ways; independent adversarial critique CONFIRMED-WITH-CAVEATS (1 non-blocking comment-accuracy nit, fixed forward) | 6d7d059d... | gist local-only (`dream-gist-2026-11-13.md`), `gh gist create` blocked by proxy policy (HTTP 403, not a GH-auth failure); not yet merged, 3 days old, not stale |
| 2026-11-14 | swarm | `ByzantineConsensus`/`GossipConsensus` never called `setMaxListeners(0)` despite the identical per-proposal listener-growth pattern `RaftConsensus` already guards against (`raft.ts:60-64`) — real `MaxListenersExceededWarning` under >10 concurrent proposals. Mirrored Raft's existing guard in both constructors | #4988 | #4989 | yes | ACCEPT | 2 new discriminating tests, stash-isolated baseline captures the real warning → 6/6 candidate; full `@claude-flow/swarm` suite 382/382 (380+2), 0 regressions, `tsc --noEmit` clean; independent adversarial critique confirmed no evaluator gaming, re-ran baseline from scratch, 50-concurrent-proposal stress test clean | 0e31d2b1... | gist local-only (`dream-gist-2026-11-14.md`), `gh gist create` blocked by proxy policy (HTTP 403); not yet merged, 2 days old, not stale |
| 2026-11-11 | security | `v3/@claude-flow/cli/src/init/settings-risk-scanner.ts`'s `scanAllowRuleForRisk()` (the heuristic `ruflo init --upgrade` runs against a target project's existing `.claude/settings.json`) flagged `permissions.allow` rules pre-approving `bash/sh/python/ruby/perl/curl/wget`+dangerous-words with no per-call confirmation, but had no entry for `node`/`deno`/`bun`/`php` — GTFOBins-documented shell-breakout interpreters in the same tier as the four already covered. This repo's own committed `.claude/settings.json` (lines 14/29) carries a live, unscoped `Bash(node:*)` allow-rule this exact scanner silently passed as clean before tonight; confirmed not a documented design tradeoff (`ruflo init`'s own `generateSettings()` never emits a node-related allow rule by default, so the gap wasn't forced by avoiding a false positive on Ruflo's own output). Fixed via a new `INTERPRETER_WORDS` list feeding only `RISKY_PREAPPROVE_WORDS`, deliberately kept out of `SHELL_EXEC_WORDS` so the separate `scanCommandStringForRisk` (hook command strings, where `node <script>` is legitimate) stays untouched. Also corrected a stale 2026-10-30 deferred finding: `http_fetch`'s DNS-rebind SSRF gap is already closed (`http-fetch-pinned.ts`'s `pinnedLookup`, ADR-164 §5.1.8) — no action needed, REJECT-with-evidence on reopening it. SCAN: intelligence (10-27/11-01's EWC++ per-mode gap confirmed still open tonight, mitigated since every mode-construction site defaults to `'balanced'` — narrower blast radius than previously framed; third disclosure without action), swarm (11-01's `TaskOrchestrator.failTask()` agent-stranding finding confirmed **already fixed** via direct code read of `releaseWorker()` — not reused) | #4960 | #4961 | yes | ACCEPT | 10 new/extended tests (`settings-risk-scanner.test.ts` + a CJS/TS parity case), stash-isolated baseline fails 5/54 exactly as predicted → candidate 54/54 pass, 75/75 across all three affected test files after the critic's own fix + this session's follow-up regression test; benchmark-corpus recall 0.75→1.0, precision 1.0 both ways (0 false positives); `tsc --noEmit` 512 pre-existing unrelated errors (unbuilt siblings) byte-identical per the critic's own line-for-line diff, 0 in changed files; full-package suite timed out at 170s (environmental); independent adversarial critique (fresh context, re-ran stash-isolation + `tsc` diff itself, independently verified the live `Bash(node:*)` rule rather than trusting the write-up) CONFIRMED + PASS, and on its own initiative found and fixed forward a real cross-file parity gap (this session's TS-only change would have left the `hook-handler.cjs` CJS mirror used by the `session-restore` boot hook out of sync on these exact cases) plus extended the parity test; one remaining caveat (untested prefix-collision safety for `nodemon`/`phpunit`/`bunx`/`denoland`, verified correct by hand) closed same session with a dedicated test | 6bfe9cf4... | 10-26/10-27/10-28 MERGED (per 2026-11-01's confirmed state, not re-verified tonight); 10-31 #4619 MERGED; 11-01 #4634 status not re-checked tonight (budget — see pre-row note above); 11-02 #4660 open/draft as of 11-10's note, 9 days old, not stale; 11-08 #4910 CLOSED not merged; 11-09 #4908/#4927 MERGED; `dream/2026-11-10-hive-mind` (#4937/#4938, disclosed SCAN override, `RaftConsensus` legacy `requestVote()` fix) **MERGED**. Prior-night gist score: not scored (see note above) |
| 2026-11-12 | intelligence | `v3/@claude-flow/neural/src/sona-manager.ts`'s `triggerLearning()` re-filtered the ENTIRE `this.trajectories` map on every call with no "already learned from" marker — any trajectory surviving `pruneTrajectories()`'s quality-based eviction got re-fed into `BalancedMode.learn()`'s gradient accumulation / EWC Fisher update on every subsequent cycle, purely from replay. Disclosed-but-not-fixed 2026-10-27 (#4531/#4532's own docstring, named "a priority future-night candidate"); picked up directly tonight. Fixed via new `Trajectory.learnedFrom` marker gating the filter. **Independent adversarial critique then found the fix is real but narrower than first claimed**: it stops replay of stalled (no-new-completions) trajectories, but `BalancedMode`'s `gradientAccumulator`/`ewcState.means` are never reset at all (only on `initialize()`/`cleanup()`), so under ordinary continuous operation (one genuinely-new, similar-content trajectory per cycle) the SAME 6.59x/2.03x growth curve originally attributed to the pre-fix baseline still occurs on the fixed candidate — independently reproduced twice more this session, byte-identical numbers. This deeper bug is disclosed, not fixed, and carried forward as tonight's top candidate. Rejected the already-3x-disclosed EWC-per-mode wiring gap (10-27/11-01/11-11) per STEP 1.1 — this is a different bug in the same subsystem. SCAN: capabilities (`claims.ts checkCommand` fails open on config error — new, deferred, score 3.5/5), memory (`memory compress --quantize` CLI/MCP schema mismatch, always prints "Quantization: No"/"Duration: NaNs" — new, deferred, score 3/5) | #4972 | #4973 | yes | ACCEPT-scoped (post-critique) | 4 new discriminating tests, stash-isolated baseline fails 3/4 exactly as predicted → candidate 4/4; full `@claude-flow/neural` suite 152/152 (148+4 new), 0 regressions, `tsc --noEmit` clean both ways; standalone growth probe confirms baseline/pre-fix-equivalent-scenario growth 0.000065→0.013917→0.091778→0.189414→0.384688 (cycles 1/30/150/300/600, linear, not plateauing) persists on the candidate under continuous-new-trajectory input, while the narrower zero-new-trajectories scenario the hypothesis actually covers is correctly flat; independent adversarial critique CONFIRMED-WITH-CAVEATS — found and this session verified a real overclaim in the original docstring/gist draft ("flat 1.000x" was only true for the narrower sub-case), corrected before publication rather than shipped as written | 4cfe2017... | 11-11 #4961 MERGED (confirmed tonight); 10-26 through 11-10 MERGED where a decision exists (per prior nights' notes, not re-verified tonight — budget); 11-08 #4910 CLOSED-not-merged; 11-02 #4660 status not re-checked tonight. Prior gist (11-11, security) scored 9/10 (2+2+2+2+0(2065 words, over cap)+1) |
| 2026-11-10 | hive-mind (SCAN override of performance DEEP, see issue #4937 §3 for the override rationale) | `RaftConsensus`'s no-transport "legacy in-process" `requestVote()` path (`v3/@claude-flow/swarm/src/consensus/raft.ts`) granted votes on a bare `currentTerm > peer.currentTerm` comparison — no vote-once-per-term check, no log-up-to-date check — unlike the transport RPC path and `handleInboundRaftMessage()` a few lines above it, both of which correctly implement Raft §5.2/§5.4. Confirmed production-reachable (no call site in `v3/` ever wires a `ConsensusTransport`; `UnifiedSwarmCoordinator` calls `consensusEngine.addNode()` for every real spawned agent onto this exact path). A candidate whose term was inflated by retries alone (not log progress) could out-vote a more log-advanced peer (unsafe over-grant, a real Leader Completeness violation); the same strict `>` check also wrongly denied a legitimate same-term, equally-fresh-log candidate (spurious under-grant). Fixed by mirroring the file's own two already-correct implementations. DEEP=performance's own deferred lead (`CacheManager.estimateSize()`, scored 4.85 on 10-20) was investigated first and REJECTED with evidence: regression test #4481 requires exact size accounting even without `maxMemory`, so "skip when unset" does not survive scrutiny — not re-proposed as-is. SCAN: security (http-fetch/path-containment/claims-tools reviewed, no new finding), hive-mind (Byzantine/Gossip sanity-checked for an analogous gap — none found, architected differently) | #4937 | #4938 | yes | ACCEPT | 4 new tests (2 discriminating, 2 controls), stash-isolated baseline 378/380 (2 predicted failures) → candidate 380/380, independently reproduced byte-identical by a separate fresh-context adversarial-critic subagent from its own stash/pop cycle, which also independently re-verified the production-reachability claim from scratch; full `@claude-flow/swarm` suite 380/380 (376+4 new), 0 regressions, `tsc --noEmit` clean both ways; `metaharness mcp-scan` MEDIUM(3)/0-high, byte-identical to baseline; independent critique CONFIRMED, no blocking issues (3 non-blocking caveats disclosed: `appendEntries()`'s analogous gap left unfixed, a possible pre-existing zero-peer self-election edge case, private-field test casts matching existing convention) | 5af6b216... | 10-26 through 11-01 all MERGED where a decision exists; 11-02 open/draft not stale; 11-08 #4910 CLOSED-not-merged; 11-09 #4908/#4927 MERGED; 11-03..11-07 confirmed no-run gap (5 nights). Prior gist (11-09, swarm) scored 10/10 on the same rubric per its own issue §2 |
**Note (2026-11-02):** trailing-6-night fates verified via GitHub MCP tools (`gh` CLI's `GH_TOKEN` invalid, MCP tools work fine — not FALLBACK) before tonight's own row: #4532 (10-27, intelligence) **MERGED**; #4550 (10-28, memory) **MERGED**; #4573 (10-29, swarm) closed-not-merged but superseded and shipped via #4640 (merged) per its own comment thread — effectively merged; #4598 (10-30, performance) **MERGED**; #4619 (10-31, security) **MERGED**; #4634 (11-01, security) **MERGED**. 6/6 of the trailing window shipped in some form, no stale (>14d) items. Prior gist (11-01, security) scored 9/10 (2+2+2+2+1(1380 words)+0 — continuation of 10-31's own disclosed finding, not genuinely novel).
| 2026-11-02 | intelligence | `SONAManager`'s EWC++ consolidation hook (`getConsolidationSnapshot()`, wired 10-27 for `BalancedMode` only, re-disclosed as a 4-mode gap 11-01) investigated directly for all 4 remaining modes rather than assumed uniform: `ResearchMode` already runs a real, never-cleared-except-init/cleanup Adam optimizer (`adamM`/`adamV`, already read back by its own dormant `computeEWCLoss()`) — structurally identical to Balanced's `gradientAccumulator`, wired honestly tonight using the exact reviewed delta-since-snapshot pattern, zero `sona-manager.ts` changes needed. `EdgeMode`/`RealTimeMode` confirmed to track no gradient-shaped state at all (Edge: quantized int8 weights only; RealTime: `learn()`'s own comment says "we skip full backprop") — NOT wired, would require fabricating state. `BatchMode`'s `accumulatedGradients` is real but zeroed every 4 cycles by `applyAccumulatedGradients()`, making snapshot timing ambiguous — deferred for a dedicated design pass, not ported. SCAN: capabilities (`.harness/mcp-policy.json`'s false shell/network-surface claim, 3rd consecutive disclosure since 10-26 without action — flagged for a deliberate decision), memory (`CacheManager.clear()`'s `previousSize` always 0, 2nd consecutive disclosure since 10-27, still live) | #4659 | #4660 | yes | ACCEPT-scoped | 5 new tests (3 discriminating, 2 controls), stash-isolated baseline fails 3/5 exactly as predicted → candidate 5/5 pass, independently reproduced from scratch by a fresh-context adversarial critic; full `@claude-flow/neural` suite 148/148→153/153 (0 regressions); `tsc --noEmit` 0 errors both ways; independent adversarial critique CONFIRMED-WITH-CAVEATS — 1 non-blocking test-strength nit (weak `>0` assertion vs. Balanced's `>valueAfter1*0.9`) found and fixed forward same session after the critic empirically confirmed a ~7.5x ratio clears the stronger bound | c972c16f... | 10-27/10-28/10-30/10-31/11-01 MERGED; 10-29 closed-not-merged but superseded+shipped via #4640; none stale. Prior gist (11-01) scored 9/10 |
| 2026-10-12 | intelligence | Handed-in candidate (fix `SONAManager`'s dead EWC key-mismatch, per open #3622/#3879) independently REJECTED by an architecture-review subagent: `loraWeights.A/B` (what EWC would regularize) are never updated by gradient descent anywhere — fixing the key mismatch alone would be behaviorally inert. Pivoted to the root cause the same investigation surfaced: `LearningBridge` (the only production path exercising `SONAManager`, via `auto-memory-hook.mjs`'s SessionStart/SessionEnd hooks) never persisted SONA's learning state across its own short-lived process invocations — `SONAManager.serialize()`/`deserialize()` already existed (`#1773 Phase 1.6`) but nothing called them. Wired the round-trip into `LearningBridge.loadNeural()`/`destroy()`, mirroring `MoERouter`'s existing `.swarm/moe-weights.json` pattern | #4080 | #4081 | yes | ACCEPT | 10 new discriminating tests, stash-isolated 3/10 fail baseline (write-on-destroy/restore-on-load/cross-instance-accumulation) → 10/10 pass candidate, independently reproduced by an adversarial critic's own stash/pop cycle; real unmocked `SONAManager` smoke test via built `dist/` (0→1 completed trajectories across a fresh instance after restore, JSON-round-trip-stable); full `@claude-flow/memory` suite 615/616 both ways (3 known-flaky/pre-existing failures, 0 attributable, independently reproduced); full `@claude-flow/neural` suite 139/139 unchanged; independent adversarial critique CONFIRMED-WITH-CAVEATS (non-blocking: disclosed-not-fixed `deepDecode` `__proto__` hardening, corrected full-suite failure count from 1 to 3) | 2f6fe1d0... | 10-09 #3929, 10-10 #3977, 10-11 #4053 all MERGED; 10-06 #3835, 10-07 #3879, 10-08 #3909 open/draft, none stale (<14d). Prior gist (10-11, security) scored 10/10 (2+2+2+2(witness in linked PR #4053, verified present/valid)+1(1173 words)+1) |
**Note (2026-10-03):** verified via `mcp__github` tools before tonight's own row (no `gh` CLI this session — invalid token, used MCP tools throughout): trailing nights 09-22 (#3394/#3395) **CLOSED, not merged** (2026-09-26); 09-24 (#3411/#3412, test/parity-gate PR, off the "[Dream Cycle]" title convention) **MERGED** 2026-09-26 — the only merge in this window; 09-27 (#3475/#3476), 09-28 (#3516/#3517), 09-29 (#3538/#3539), 09-30 (#3562/#3563), 10-01 (#3598/#3599), 10-02 (#3621/#3622) all still **OPEN/draft**. **2026-09-23, 09-25, 09-26 confirmed genuine no-run gaps** (no branch/issue/PR for any of the three — same class as 08-20..23/09-13-14), independently reconfirmed by tonight's own `automation` scan (nightly trigger has no in-repo cron/workflow, root cause remains outside this repo's visibility). `plugins` scan: the 2026-09-22 gist's open plugin-install-verification gap is now **resolved** (#3557, 2026-09-30 — trust-policy.ts + checksum enforcement + `--ignore-scripts`), closing out of the backlog.
| 2026-10-03 | memory | `HNSWIndex.serialize()`/`deserialize()` dropped `config.quantization` and trained PQ codebooks entirely — silently re-broke the product-quantization distance dispatch fixed 2026-08-25 (#3093/#3094) on every save/reload cycle; `AgentDBAdapter.saveToDisk()`/`loadFromDisk()` call this exact pair in production. Versioned magic header (v1/v2) persists+restores quantizer config/codebooks, backward-compatible with old snapshots | #3649 | #3650 | yes | ACCEPT | pre-serialize recall@10 0.270 → post-deserialize 0.010 (bug, baseline) → ~0.270 (candidate, within 0.05 of pre-serialize); 557/558 full-suite both ways (1 pre-existing unrelated failure, confirmed byte-identical via stash isolation); `tsc --noEmit` clean; independent adversarial critic CONFIRMED (reproduced with a stronger real pre-fix v1-buffer test, not just the hand-built one in the test file) | 98d206b0... | 09-22 CLOSED-not-merged; 09-24 MERGED (only merge this window); 09-27..10-02 (6 nights) all open/draft, none stale; 09-23/25/26 no-run gaps |
**Note (2026-11-13):** 11-12 (intelligence, #4972/#4973, `SONAManager.triggerLearning()` backlog-replay gating) ran — real branch `dream/2026-11-12-intelligence` confirmed via `git ls-remote`; its own PR is OPEN/draft, 1 day old, not stale. It scored 11-11's gist 9/10 (2+2+2+2+0(2065 words, over cap)+1), matching this session's own independent scoring of that same gist before reading 11-12's row. 11-12's own adversarial critique found its fix narrower than first claimed (stops replay of *stalled* trajectories only; `BalancedMode`'s lifetime-cumulative `gradientAccumulator`/EWC `means` anchor remains unbounded under normal continuous operation) — flagged as a strong carried-forward candidate for a future `intelligence` night, not picked up tonight (different DEEP surface). Trailing-decided-PR fates (direct verification): 10-26/10-27/10-28/10-31/11-01/11-09/11-10/11-11 all MERGED; 11-02 #4660 OPEN/draft, now 11 days old, `mergeable_state: dirty` (flagged, not this session's PR to fix); 11-08 #4910 CLOSED-not-merged.
| 2026-11-13 | memory | `ControllerRegistry` declared `causalRecall` as an `AgentDBControllerName` with a real `createController()` case (dynamic `agentdb` import + the ADR-514-adapted embedder, same construction pattern as `learningSystem`/`explainableRecall`) but it was absent from every level of `INIT_LEVELS`, so `initialize()` never constructed it and `registry.get('causalRecall')` always returned `null` — disclosed-but-deferred 2026-10-28 ("needs a human call on init-level ordering"); acted on tonight, added to level 4 alongside construction-sibling `causalGraph` (agentdb/vectorBackend already populated before the level loop runs, so placement doesn't affect correctness). Third instance in six weeks of the same "declared-but-dead" shape in this package family (10-28 `ControllerRegistry.set()`, 10-31/11-01 `plugin-agent-federation` `SecurityPolicy` thresholds). Zero current production callers — forward-looking fix, not a live-breakage fix. SOTA research (2 fresh 2026 arXiv papers + a survey) confirms causal-provenance-conditioned memory recall is a genuine unexplored 2026 frontier; 0/11 reviewed competitors ship an activated version. SCAN: plugins (`v3/plugins/code-intelligence`'s 7 declared config knobs never read by any of its 4 MCP tool handlers, new finding, deferred, 4/5), automation (`hooks worker dispatch --priority` accepted/persisted/documented but never read by `drainDispatchQueue()` — plain FIFO regardless, new finding, deferred, 4/5; confirmed no in-repo cron drives Dream Cycle; confirmed the previously-disclosed `noHardcodedSecrets` audit-fabrication bug is already fixed) | #4982 | #4983 | yes | ACCEPT | baseline: 2 new discriminating tests fail exactly as predicted (`toContain('causalRecall')`; `get('causalRecall')` returns `null`); candidate: 94/94 across the 4 relevant test files; full `@claude-flow/memory` suite 717/718 both ways outside the 2 new tests (1 pre-existing unrelated chmod-as-root environmental failure, confirmed byte-identical on the stashed baseline); `tsc --noEmit` clean both ways; independent adversarial critique CONFIRMED-WITH-CAVEATS (one inaccurate in-source comment — "same shape as `causalGraph`," which is actually built differently — fixed forward same session in a separate commit, re-verified clean) | 6d7d059d... | 10-26/10-27/10-28/10-31/11-01/11-09/11-10/11-11 MERGED; 11-02 #4660 open/draft, 11 days, `mergeable_state: dirty` (flagged, not actioned); 11-08 #4910 CLOSED-not-merged; 11-12 #4972/#4973 open/draft, 1 day, not stale. Prior gist (11-11, security) scored 9/10 by 11-12's own session, independently matching this session's own scoring |
**Note (2026-11-18):** rows for 2026-11-12/13/14/16/17 are missing from this table even though real branches/issues/PRs exist for all five nights (#4973/#4972, #4983/#4982, #4989/#4988, #5004/#5003, #5012/#5011 — all open drafts as of tonight) — confirmed via `git ls-remote --heads origin` + GitHub MCP `list_pull_requests`, a STEP 25 backfill gap (the pipeline ran every night; the append just didn't land on `main`), not a pipeline failure. #5004's own issue (#5003) already disclosed this gap for 11-12/13/14; tonight additionally confirms 11-16/11-17 are in the same state. Left for a future lower-stakes backfill pass rather than reconstructed here from PR bodies, since the real evidence (branches+PRs) already makes each night's work independently verifiable without a ledger row.
| 2026-11-18 | memory | `CacheManager`'s pure-LRU `evictLRU()` (`v3/@claude-flow/memory/src/cache-manager.ts`) had no frequency/importance signal despite `CachedEntry.accessCount` already being tracked on every entry — HTM-EAR (arXiv:2603.10032, Feb 2026) documents this exact policy permanently dropping high-value entries under skewed access. Added an opt-in, continuous `frequencyWeight`/`evictionScanWindow` blend to `selectEvictionVictim()`; `frequencyWeight` falsy (default/unset) is an early `return this.tail!`, structurally byte-identical to the original pure-LRU path for every current caller (`AgentDBAdapter`, `TieredCacheManager`, `ControllerRegistry`'s `tieredCache`). Repository-local bounded Darwin sweep (3 gens × 4 candidates, new synthetic skewed-workload corpus `.harness/bench-memory-eviction-2026-11-18.json`) found an interior optimum `frequencyWeight=0.85` (fitness 0.851 vs baseline 0.825, +19.4pp mean essential-key retention, 0/6 tasks regressed) that beats the naive `frequencyWeight=1.0` (0.794, regresses 1/6) — not shipped as the default, disclosed as tuning evidence only. SCAN: plugins (`PluginStoreConfig`/`code-intelligence` dead-config findings confirmed still open; `SecurityPolicy.minTrustLevelForSpawn` confirmed fixed 10-31; new finding: `@claude-flow/plugins`' public `ResourceLimits` SDK export only enforces `maxMemoryMB` of 5 declared fields, zero in-repo callers but live-but-broken for external plugin authors), automation (the "worker fabricates unperformed audit/scan work" 3-instance pattern from 10-13/10-28 confirmed fully fixed with regression tests; `hooks worker dispatch --priority` confirmed still a dead flag since 11-13) | #5033 | #5034 | yes | ACCEPT | 4 new discriminating tests, stash-isolated baseline fails the 1 test requiring non-LRU behavior exactly as predicted (3/4 pass vacuously); candidate 722/723 full `@claude-flow/memory` suite (718 pre-existing + 4 new, same 1 pre-existing environmental chmod-as-root failure), `tsc --noEmit` clean both ways; independently reproduced byte-identical by a fresh-context adversarial critic, which also hand-verified the `frequencyWeight=0` early-return is structurally (not just empirically) byte-identical — verdict CONFIRMED, one minor disclosed-not-fixed caveat (unvalidated `frequencyWeight` range, no real caller can reach it today); `metaharness mcp-scan`/`threat-model` MEDIUM(3)/0-high, byte-identical to baseline | 8e6a4d8e... | 11-12/13/14/16/17 all open/draft, none stale (see note above, a backfill gap not a merge-rate signal); last confirmed-merged dream PR remains 11-01 #4634 (per 11-10's own note) and 11-10 #4937/#4938 (MERGED). Prior gist (11-17, intelligence) not independently re-scored tonight (out of scope, left as a note in issue #5033 §3 rather than fabricated) |
| 2026-11-17 | intelligence | `ReasoningBank.distill()` (`v3/@claude-flow/neural/src/reasoning-bank.ts`) judged every trajectory but only distilled successes into the retrievable memory pool, discarding all judged-failure information -- an accepted ICLR 2026 paper (ReasoningBank, arXiv 2509.25140) measures failure-aware distillation beats success-only memory; fixed to distill a distinct `memoryType: 'pitfall'` memory, gated `PatternLearner.extractPattern()` on `memoryType === 'success'` (critic-confirmed load-bearing, not redundant, due to a pre-existing quality-threshold divergence), and fixed forward a cross-type `deduplicateMemories()` bug the change would otherwise have introduced | #5011 | #5012 | yes | ACCEPT (post-critique) | baseline fails exactly the 4 predicted tests, 38/42 unaffected pass; candidate 43/43; full `@claude-flow/neural` 152/152, 0 regressions; related `@claude-flow/memory` suite 78/78; `tsc --noEmit` clean; independently reproduced byte-for-byte by an adversarial critic (verdict CONFIRMED-WITH-CAVEATS -> forward-fixed -> re-verified) | 2261d4ec... | 2026-11-16 (intelligence, #5003/#5004) OPEN draft, not stale; 2026-11-12/13/14 OPEN drafts, not stale; 2026-11-15 no `dream/*` branch (genuine skipped night); 2026-11-10/11 MERGED |
| 2026-11-16 | intelligence (SCAN override to capabilities, see issue #5003 §2 for the override rationale) | `buildCapabilityBrain()`'s `coverage.coveragePercent` (`v3/@claude-flow/cli/src/mcp-tools/capability-brain.ts`) was hardcoded to `100` and `classifiedToolCount` unconditionally equaled the raw unique-tool count, ignoring `fallbackClassifiedTools` entirely — a declared-but-dead metric reachable through the live `guidance_brain` MCP tool, violating ADR-329's own coverage-gate invariant. DEEP=intelligence's own top candidate (decay the never-decaying EWC `gradientAccumulator` in `balanced.ts`, mirroring Ruflo's own upstream `@ruvector/sona@0.1.11` dependency's already-shipped EMA decay) scored lower once an architecture review found its output is currently discarded by `learn()` — disclosed as a strong candidate for a near-future night, not fixed tonight. Also: DEEP=security was rejected before research began (3rd occurrence of the `.harness/mcp-policy.json` false shell/network-surface claim, disclosed 2026-10-26/2026-10-27 — STEP 1.1 duplicate-direction rule). SCAN: memory (`CacheManager.clear()`'s `previousSize` always-0 bug, disclosed 2026-10-27, confirmed still live, not yet fixed) | #5003 | #5004 | yes | ACCEPT (post-critique) | 3 new tests (2 discriminating, 1 control; one discriminating test added post-critique), stash-isolated baseline fails the original discriminating test exactly as predicted → 11/11 pass; `tui-command.test.ts` 13/13 (+3 skips), 0 regressions; `tsc --noEmit` 0 errors in changed files; independent adversarial critique found and this session fixed forward a real edge case (duplicate tool name + fallback classification drove the metric negative), re-verified 11/11 after the fix, verdict CONFIRMED | 634d0afc... | Backfilled 3 missing ledger rows tonight (2026-11-12/13/14 each had a real evaluated draft PR that never got a ledger row — a genuine STEP 25 gap found during tonight's STEP 1 check, see rows above). 11-12 #4973/11-13 #4983/11-14 #4989 all open/draft, 2-4 days old, not stale. 11-11 #4961 status not re-checked tonight. Prior gist (11-11, security) scored 9/10 (2+2+2+2+0(2065 words)+1) — this is the last gist actually available to read; 11-12/13/14's own gists are local-only on their unmerged branches, not fetched tonight (budget) |
| 2026-11-10 | hive-mind (SCAN override of performance DEEP, see issue #4937 §3 for the override rationale) | `RaftConsensus`'s no-transport "legacy in-process" `requestVote()` path (`v3/@claude-flow/swarm/src/consensus/raft.ts`) granted votes on a bare `currentTerm > peer.currentTerm` comparison — no vote-once-per-term check, no log-up-to-date check — unlike the transport RPC path and `handleInboundRaftMessage()` a few lines above it, both of which correctly implement Raft §5.2/§5.4. Confirmed production-reachable (no call site in `v3/` ever wires a `ConsensusTransport`; `UnifiedSwarmCoordinator` calls `consensusEngine.addNode()` for every real spawned agent onto this exact path). A candidate whose term was inflated by retries alone (not log progress) could out-vote a more log-advanced peer (unsafe over-grant, a real Leader Completeness violation); the same strict `>` check also wrongly denied a legitimate same-term, equally-fresh-log candidate (spurious under-grant). Fixed by mirroring the file's own two already-correct implementations. DEEP=performance's own deferred lead (`CacheManager.estimateSize()`, scored 4.85 on 10-20) was investigated first and REJECTED with evidence: regression test #4481 requires exact size accounting even without `maxMemory`, so "skip when unset" does not survive scrutiny — not re-proposed as-is. SCAN: security (http-fetch/path-containment/claims-tools reviewed, no new finding), hive-mind (Byzantine/Gossip sanity-checked for an analogous gap — none found, architected differently) | #4937 | #4938 | yes | ACCEPT | 4 new tests (2 discriminating, 2 controls), stash-isolated baseline 378/380 (2 predicted failures) → candidate 380/380, independently reproduced byte-identical by a separate fresh-context adversarial-critic subagent from its own stash/pop cycle, which also independently re-verified the production-reachability claim from scratch; full `@claude-flow/swarm` suite 380/380 (376+4 new), 0 regressions, `tsc --noEmit` clean both ways; `metaharness mcp-scan` MEDIUM(3)/0-high, byte-identical to baseline; independent critique CONFIRMED, no blocking issues (3 non-blocking caveats disclosed: `appendEntries()`'s analogous gap left unfixed, a possible pre-existing zero-peer self-election edge case, private-field test casts matching existing convention) | 5af6b216... | 10-26 through 11-01 all MERGED where a decision exists; 11-02 open/draft not stale; 11-08 #4910 CLOSED-not-merged; 11-09 #4908/#4927 MERGED; 11-03..11-07 confirmed no-run gap (5 nights). Prior gist (11-09, swarm) scored 10/10 on the same rubric per its own issue §2 |
**Recovery note (2026-11-14):** 2026-11-12's row and 2026-11-13's row were never appended live despite both nights running to completion (real `dream/2026-11-12-intelligence`/`dream/2026-11-13-memory` branches, issues #4972/#4982, draft PRs #4973/#4983 — all confirmed via `git ls-remote --heads origin "dream/*"` and GitHub MCP tools before tonight's own row, not inferred). Backfilled below from each night's own issue body (title-derived, full body not re-verified tonight).
+83
View File
@@ -0,0 +1,83 @@
# Memory SOTA Report — 2026-10-03
TL;DR: In 2026, every production vector database handles distance computation over *quantized* vectors specially — Hamming+popcount for binary codes, dequantize-then-rescale for scalar/int8, or a mandatory rescore against full-precision vectors. Ruflo's `HNSWIndex` (`v3/@claude-flow/memory/src/hnsw-index.ts`) does this correctly for product quantization (fixed 2026-08-25, #3093/#3094) — but tonight's research found that fix doesn't survive a save/reload cycle: `serialize()`/`deserialize()` never persisted the quantization config or trained PQ codebooks at all, so `AgentDBAdapter.saveToDisk()`/`loadFromDisk()` silently dropped the quantizer on every reload, re-breaking the already-fixed dispatch. Candidate fix: persist quantization config + trained codebooks across the wire format, with a versioned magic header for backward compatibility. Evaluated tonight: real bug, reproduced, fixed, tested.
## What's New in 2026
| Finding | Source | Confidence |
|---|---|---|
| RaBitQ's 1-bit-per-dim quantization uses a provably unbiased asymmetric distance estimator (random rotation + bi-valued codebook + scalar correction), not a naive metric on packed bits | Gao & Long, SIGMOD 2024, arXiv:2405.12497 | A |
| Qdrant binary quantization: bitwise Hamming-style scoring for candidate generation, **mandatory rescore/oversampling** against full f32 vectors for correctness | Qdrant quantization docs + binary-quantization-openai article | B |
| Weaviate BQ: dedicated bitwise comparison kernel + conditional overfetch/rescore (`rescoreLimit`) against uncompressed vectors | Weaviate BQ compression docs + BQ blog | B |
| Milvus: dedicated binary vector dtype with native Hamming-distance index types (`BIN_FLAT`/`BIN_IVF_FLAT`), explicitly selected at index-creation time, not inferred from a generic metric | Zilliz index-types blog + BQ learn article | B |
| Vespa: binarized tensors declare an explicit `hamming` distance metric (XOR+popcount) for ANN retrieval, then a float rerank phase | Vespa binarizing-vectors docs + billion-scale kNN blog | B |
No competitor runs a plain float distance formula directly on packed-bit or rescaled-int arrays without either a dedicated kernel or an explicit dequantize/rescore step — a consistent pattern across 4 independent vendors plus a peer-reviewed theoretical basis (RaBitQ).
## Ruflo Current Capability
`HNSWIndex` supports three quantization modes (`product`, `binary`, `scalar`) via an internal `Quantizer` class. Product quantization's distance dispatch was fixed 2026-08-25 (`isProductQuantized()` guard routes to `productQuantizeDistance()`). Tonight's research re-verified that fix directly, and in doing so found it doesn't survive persistence: `serialize()` wrote index topology (nodes, vectors, connections) but never `config.quantization` or the trained `codebooks`; `deserialize()` always reconstructed via `new HNSWIndex({dimensions, M, efConstruction, metric})` — no quantization field — so `this.quantizer` was `null` after every reload, collapsing `isProductQuantized()` back to `false` and reintroducing the exact pre-#3093 bug for any index that persists and reloads. `AgentDBAdapter.saveToDisk()`/`loadFromDisk()` (`agentdb-adapter.ts:1267,1316`) call this pair in production.
Separately (re-confirmed, not re-fixed tonight): `binary`/`scalar` quantization have no distance-dispatch guard at all (same bug class, unfixed), but are currently **dead code** — no call site anywhere in the repo constructs `HNSWIndex` with `quantization:{type:'binary'|'scalar'}`. Flagged for a future night rather than bundled into tonight's patch (keeps the patch to one conceptual change).
## Competitor Comparison
| System | Approach to quantized distance | Source | Grade |
|---|---|---|---|
| Qdrant | Hamming-style bit-space scoring + mandatory rescore | Qdrant docs/blog | B |
| Weaviate | Bitwise kernel + overfetch/rescore | Weaviate docs/blog | B |
| Milvus | Native Hamming-distance index type for binary vectors | Zilliz blog (x2) | B |
| Vespa | Explicit `hamming` metric + float rerank phase | Vespa docs/blog | B |
| RaBitQ (theory) | Provably unbiased asymmetric estimator | SIGMOD 2024 paper | A |
LangGraph/AutoGen/CrewAI/OpenAI agent tooling delegate vector quantization entirely to an external vector DB — none implement it themselves, confirming this is a vector-DB-layer concern, not an agent-framework one.
## Hypothesis
Given an `HNSWIndex` configured with quantization (binary, scalar, or trained product) that is serialized and reconstructed via `deserialize()` — the exact round trip `AgentDBAdapter.saveToDisk()`/`loadFromDisk()` perform — when `serialize()`/`deserialize()` are extended to persist and restore `config.quantization` and (for trained product quantization) the PQ `codebooks`, then post-deserialize distance dispatch should match pre-serialize behavior (recall@10 within noise of the pre-serialize value) rather than collapsing to chance level, subject to: (1) non-quantized indexes' round-trip behavior is unchanged; (2) old-format ("v1") snapshots still deserialize without crashing; (3) existing serialization/quantization tests stay green; (4) deterministic, $0 evaluation.
## Benchmarks
New deterministic test (`hnsw-serialization-quantization.test.ts`): a trained product-quantized index (1500 synthetic clustered 64-dim vectors, 8 clusters, pqTrainingThreshold=256) measures recall@10 against brute-force ground truth before serialization and again after `deserialize(serialize())`, plus a hand-verified v1-format backward-compatibility buffer and a non-quantized-index regression check.
## Evaluation
**evaluated: accepted.** Real evaluator: Vitest 4.1.8, deterministic, $0, zero LLM calls. Baseline-fails/candidate-passes via `git stash` isolation on `hnsw-index.ts` alone: pre-serialize recall@10 = 0.270 (matches 2026-08-25's measured PQ floor); post-deserialize recall@10 collapses to **0.010** on baseline, recovers to ~0.270 on the candidate (within 0.05 of pre-serialize, asserted). Full `@claude-flow/memory` suite: 557/558 both ways (1 pre-existing unrelated failure — a root-user/read-only-file permission test in `auto-memory-bridge.test.ts`, confirmed byte-identical via stash isolation). `tsc --noEmit`: clean, no errors.
## Post-Review Hardening (ruvnet, 2026-10-09)
Rebased onto main (`5f709e367`); dropped the PR's `package.json`/`pnpm-lock.yaml`/CLI-pin version-bump commit per review — version bumps for unbundled leaves belong to the release integrator, not this PR (main's `@claude-flow/memory` had independently moved to `3.0.2` by review time; this fix ships with "the next standalone `@claude-flow/memory` publish after 3.0.2, plus the CLI pin bump," per the reviewer). Three further findings addressed in the same pass:
1. **Input validation**: `Quantizer.importCodebooks()` took `JSON.parse()` output straight into `this.codebooks` with no shape/finiteness check. Now validates `numSubquantizers × numCentroids × expectedSubvectorLength` of finite numbers before accepting; rejects (leaving the quantizer untrained, not NaN-poisoned) otherwise. `deserialize()` also guards the `JSON.parse()` call itself so corrupt JSON degrades the same way instead of throwing. 2 new discriminating tests, both stash-verified to fail pre-fix.
2. **Disclosed limitation (no code change)**: a v2-format snapshot cannot be read by older `@claude-flow/memory` versions (the magic-byte check throws on downgrade) — a one-way format bump, consistent with how the v1→v2 transition was designed (old buffers stay readable going forward, not the reverse). Separately, any *existing* v1 snapshot that came from a quantized index was never saveable with its quantizer config in the first place (the bug this PR fixes) — such snapshots stay un-quantized after upgrading too and need a rebuild to actually gain this fix's benefit; upgrading alone doesn't retroactively recover them.
3. **Release note**: per the reviewer, `@claude-flow/memory` being an unbundled leaf means this PR's merge alone does not ship the fix to consumers — it needs a standalone `@claude-flow/memory` publish plus a CLI pin bump in a subsequent release, handled by the integrator.
Full suite re-verified post-hardening: 559/560 (1 pre-existing unrelated failure, unchanged), `tsc --noEmit` clean.
## Darwin Results
Skipped: this is a correctness/persistence fix (quantizer state either round-trips or it doesn't) — not a continuous parameter with a fitness gradient. Same skip class as prior binary-correctness-fix nights (#3110, #3160, #3184, #3221, #3243, #3266, #3302, #3330, #3378, #3385, #3395).
## SOTA Proof & Witness
**Reward hack check** (manual checklist — `ruvector` CLI became unreachable via npx mid-session, same disclosed-fallback pattern as 2026-09-22): no test weakening (diff is purely additive — new magic version, new wire-format section, new methods); no gold-data tampering (ground truth is brute-force L2 on raw unquantized vectors, untouched); no cherry-picking (test corpus/seed shared with the existing 2026-08-25 PQ test for consistency, not hand-picked for this fix); no evaluator exploitation; no cost hiding ($0 deterministic). Independently re-verified by an adversarial critic who reproduced the stash-isolated fail/pass proof itself.
**Security review**: no new attack surface — the serialization format gains one versioned section read from a trusted local buffer (same trust boundary as the rest of `deserialize()`, which already parses attacker-uncontrolled local files); backward-compatible with pre-fix snapshots.
**Promotion gate** (advisory only — never self-promoted): evaluation_complete ✓, effect_positive ✓ (0.010→0.270 post-fix), significance_sufficient ✓ (27x), no_material_regression ✓ (557/558 both ways, byte-identical failure), tests_green ✓, reward_hack_clear ✓, critic_clear (pending independent critic report — see PR), witness_valid ✓ (below), receipt_reproducible ✓ (stash-isolated). **VERDICT: ACCEPT** — recommended for human review, not self-promoted.
| Field | Value |
|---|---|
| Session commit | `52d7a9d247c210a725e25bac9af2559ecc79a697` |
| Candidate commit | `21adc01ad1c136c6e34abd5fe0a0ad8c0f382c4a` (post-rebase + ruvnet-review fixes; original pre-rebase commit was `7eb7ceba8c9327023d448d01fefac2f2eca7f247`) |
| Gist SHA-256 | `b9969030fa3927b5e979aee6201eb4b9a251bc6e44a9d88dcc5f996eeb8c368a` |
| Witness stamp | `98d206b036e3d7d4e8e27c469288792085f3e1b402a24811a040fe45767d3507` |
Verifier: fetch this gist, replace "Candidate commit"'s value with "PENDING — filled on `dream/2026-10-03-memory` before push", SHA-256 the file, concatenate with the session commit above, SHA-256 again — must equal the witness stamp.
## Recommended Next Steps
1. **This fix**: human review and merge of the linked draft PR — one file (`hnsw-index.ts`) + one new test file, one conceptual change (serialization completeness for quantizer state).
2. **Binary/scalar quantized-distance dispatch** (same file, `distance()` ~line 1018): still has no Hamming/dequantize kernel, same bug class as the already-fixed PQ case — but currently dead code (no production call site), so lower urgency; good candidate the day a caller wires binary/scalar quantization in.
3. **Plugin install trust/checksum enforcement** — previously flagged (2026-09-22 gist) as an open gap; tonight's scan confirms it was **already fixed** by PR #3557 (2026-09-30, trust-policy.ts + `--ignore-scripts` for untrusted installs). No action needed; closing this out of the backlog.
4. **Dream Cycle automation trigger**: tonight's `automation` scan reconfirms the nightly trigger lives entirely outside the repo (no in-repo cron/workflow references it) — root cause of the recurring no-run gaps (08-20..23, 09-13/14, 09-23/25/26) remains undiagnosed and out of this repo's visibility. Standing recommendation unchanged: a dedicated future `automation`/`meta` night scoped explicitly to diagnosing the external trigger.
+179
View File
@@ -0,0 +1,179 @@
# Intelligence SOTA Report — 2026-10-12
TL;DR: Tonight's `intelligence` deep-dive started from a handed-in candidate —
fix `SONAManager`'s dead EWC key-mismatch (the subject of still-open PRs
#3622 and #3879) — and **rejected it** after an independent architecture
review proved it would be behaviorally inert even if fixed (the LoRA
weights EWC would protect are never updated by gradient descent anywhere in
the codebase). Research pivoted to a more foundational finding from the same
investigation: `LearningBridge`, the only production path that exercises
`@claude-flow/neural`'s `SONAManager` (wired to Claude Code's
SessionStart/SessionEnd hooks via `auto-memory-hook.mjs`), constructs a
**fresh, empty neural learning state on every single short-lived hook
invocation** — `SONAManager.serialize()`/`deserialize()` already exist
(built for exactly this) but nothing ever called them. Tonight wires that
round-trip in, evaluated with 10 new discriminating tests plus a real,
unmocked `SONAManager` smoke test. 2026 external research confirms no
mainstream agent framework attempts anything EWC-analogous (pure-retrieval
memory has nothing for Fisher regularization to protect) but a Sept-2026
arXiv paper shows EWC/LwF genuinely working for LLM-agent skill-retriever
forgetting — informing, not blocking, tonight's scope.
## What's New in 2026
| Finding | Source | Confidence |
|---|---|---|
| EWC-LoRA: EWC over low-rank adapters, reconstructing full-dim Fisher from a low-rank representation | arXiv:2602.17559 (Feb 2026, **ICLR 2026**, public code) | A |
| EWC/LwF/embedding-anchor/L2-init all independently shown to preserve OOD retrieval while improving in-distribution retrieval 13.98% for a 34k-skill LLM-agent retriever | arXiv:2609.10750 (Sept 2026) | A (single preprint, not yet independently reproduced) |
| FOREVER: replay-cadence scheduling by optimizer-update magnitude, not fixed step intervals | arXiv:2601.03938, **ACL 2026 long paper** | A |
| ReasoningBank: agent memory via distillation/retrieval over trajectories, explicitly *not* parameter-level | arXiv:2509.25140 (Google Research, v2 Mar 2026) | A |
| No mainstream agent framework (LangGraph/AutoGen/CrewAI/OpenAI Agents SDK) implements any EWC-analogous mechanism — all use pure retrieval/curation, which has no object for a Fisher-information penalty to protect | Official docs, direct fetch | A (LangGraph, CrewAI docs); B/C (AutoGen, OpenAI — no first-party memory docs found at all) |
## Ruflo Current Capability
`@claude-flow/neural`'s `package.json` advertises "EWC++ for continual
learning." In reality there are **4-5 independently reimplemented
EWC-shaped structures** in this repo (`EWCConsolidator` in
`ewc-consolidation.ts` — actively maintained, real fixes in the last 3
weeks; `SONAManager`'s own dead `ewcState`; `TestSonaBridge`; `LearningLoop`;
a decoupled `EwcRecord` struct), no shared abstraction. `SONAManager`'s copy
is reachable from production (`auto-memory-hook.mjs` → `AutoMemoryBridge` →
`LearningBridge` → `NeuralLearningSystem.completeTask()` →
`SONAManager.completeTrajectory()` → `checkLearningTrigger()` →
`triggerLearning()` → the 3 modes' dead EWC code) but gated behind an
80%-of-`trajectoryCapacity` threshold (2400 for default `balanced` mode)
that could never practically be crossed anyway — **no process-to-process
persistence existed for any of SONA's learning state**, EWC or otherwise.
## Competitor Comparison
| # | Framework/Product | EWC-analog? | Why |
|---|---|---|---|
| 1 | LangGraph | None | Pure KV/vector `Store`, no trainable weights to protect (A) |
| 2 | AutoGen | None | Stateless by default; third-party memory (Mem0/Zep) bolted on, still no parameter-level mechanism (B) |
| 3 | CrewAI | None — opposite instinct | LLM-judged keep/update/delete/insert_new on records; actively *deletes* superseded memory rather than protecting it (A, official docs) |
| 4 | OpenAI Agents SDK | None | No first-party long-term memory at all; defers to Mem0/Hindsight/Cognee (A for the absence, by direct doc search) |
| 5 | Qdrant/Weaviate/Milvus/LanceDB/Vespa | None (one adjacent feature) | Qdrant ≥1.18 supports zero-downtime embedding-model migration (named-vector coexistence) — schema tooling, not forgetting-mitigation (B) |
| 6 | arXiv:2609.10750 (LLM-agent skill retriever) | **Yes** | EWC/LwF/embedding-anchor/L2-init tested and shown to work for exactly this agent-adjacent setting (A) |
Synthesis: every agent-framework "None" is architectural — RAG-based
memory has no shared weight space for EWC to protect. The real EWC-adjacent
work lives one layer down, in fine-tuned retrievers/LoRA adapters (also:
CURLoRA, SLoRA, ReCoLoRA — grade B/C). No competitive cover for Ruflo's
half-wired SONA-level EWC, but no pressure to fix it tonight either — it
only matters once SONA's weights actually update via gradient descent,
which they don't (see H1, rejected, below).
## Hypothesis
> Given `LearningBridge`'s production usage (repeated short-lived
> `auto-memory-hook.mjs` processes recording insights via SessionStart/
> SessionEnd hooks), when `SONAManager`'s existing `serialize()`/
> `deserialize()` round-trip is wired into `LearningBridge.loadNeural()`
> (restore from `.swarm/sona-learning-state.json` if present) and
> `LearningBridge.destroy()` (persist synchronously before the unawaited,
> short-lived process exits), then completed-trajectory counts and other
> learning-state counters should accumulate monotonically ACROSS separate
> process invocations instead of resetting to zero every time, subject to:
> zero behavior change when no real `@claude-flow/neural` resolves or a
> mock `neuralLoader` lacks `serialize`/`deserialize`; corrupt/missing/
> schema-incompatible state degrades to a fresh start rather than throwing;
> all existing tests remain green.
Frozen before evaluation; not modified after.
## Candidates Considered (STEP 3.2, scored)
score = 0.25·fit + 0.20·testability + 0.20·measurability + 0.15·production + 0.10·novelty + 0.10·reviewability
| # | Candidate | Fit | Test | Measure | Prod | Novel | Review | Score |
|---|---|---|---|---|---|---|---|---|
| H1 | Fix SONAManager EWC key-mismatch (handed-in candidate) | 3 | 5 | 3 | 2 | 2 | 3 | **3.15** |
| H2 | Wire SONAManager serialize/deserialize into LearningBridge | 5 | 4 | 5 | 5 | 4 | 3 | **4.50** ← selected |
| H3 | Replace LearningBridge's hash pseudo-embedding with real ONNX embedding | 4 | 5 | 4 | 4 | 3 | 4 | 4.10 |
| H4 | Consolidate 4-5 duplicated EWC-shaped implementations | 3 | 2 | 2 | 2 | 3 | 2 | 2.35 |
| H5 | Wire seedable RNG into MoE/SONA weight-init (reproducibility) | 4 | 5 | 5 | 3 | 4 | 5 | 4.35 |
**H1 rejected despite handed-in status**: an independent architecture
review traced `SONAManager.loraWeights.A/B` (the actual parameters EWC
would regularize) and found exactly one `.set()` call anywhere in the
package — at init. No mode's `learn()` ever writes back into it. Fixing
EWC's key mismatch alone would make the penalty computation internally
consistent (non-zero) but have **zero effect on real agent behavior** —
reachable, but behaviorally inert. H2 scored highest on the frozen rubric
*and* is independently the most foundational finding (it's the reason EWC's
trigger threshold was practically unreachable in the first place, and it
affects every SONA learning mode, not just EWC) — no override needed.
## Benchmarks / Evaluation
Real evaluator: Vitest 4.1.8, deterministic, $0, zero LLM calls, against a
freshly `pnpm install`-ed `v3/` workspace (this sandbox had no
`node_modules` at session start for either package).
- **`learning-bridge.test.ts`**: 10 new tests, own mock extension +
`mkdtempSync`-isolated temp dirs (67 pre-existing tests/shared mock
untouched). Stash-isolated: exactly 3 of 10 fail against baseline
(write-on-destroy, restore-on-load, cross-instance accumulation — the
real discriminating assertions); the other 7 (degradation/guard tests)
pass unchanged both ways, as they should. Candidate: 77/77 pass.
- **Full `@claude-flow/memory` suite**: 3 known-flaky/pre-existing
full-suite failures, 0 attributable (independently re-verified): a
`chmod`-readonly test that can't trigger since this sandbox runs as
`root`; 2 CPU-contention-sensitive timing tests that pass in isolation on
both baseline and candidate, flaking only under full parallel load.
- **Full `@claude-flow/neural` suite**: 139/139 unchanged.
- **Real, unmocked smoke test**: built the package (tolerating 117
pre-existing `@types/node`-missing errors — no `pnpm install` had run
this sandbox before tonight) and ran a standalone Node script against
`dist/index.js` (same `modes/balanced.ts` vitest load-order workaround
PR #3879 used). Instance A completes 1 trajectory, serializes; fresh
instance B: 0 completed before restore, 1 after `deserialize()`; a
JSON-round-tripped copy matches exactly. **PASS.**
- `tsc --noEmit`: same `@types/node`-missing-from-sandbox error class both
ways (117 neural; 664→666 memory, +2 from 2 new import lines) — disclosed,
not a regression.
## Darwin Results
Skipped — this is a binary wiring/correctness fix (call the already-built
serialize/deserialize at the right two lifecycle points), not a continuous
parameter with a fitness gradient for Darwin's real interface (`ruvector
harness darwin <config> --execute`, confirmed available) to search over.
Same skip class as nearly every accepted fix in the ledger since 2026-08-18.
## SOTA Proof & Witness
```
Session commit: aac16fbdb3af21c0ddb989aaff4513a9ec1aaca5
Gist SHA-256 (pre-witness content): 4eb310ad52ca30b5f87846db58c18d5b3564576d06dc255d7c4df6c135e2c030
Witness stamp: 2f6fe1d0a8e5eb322c2631d36d9858726772f3cee3c8349fcb2c793eef03d12a
```
Verifier: fetch this file from this branch, strip the three values above
back to `PENDING`, SHA-256 the file, concatenate with the session commit,
SHA-256 again — must equal the witness stamp.
## Recommended Next Steps
1. **H3** (replace `LearningBridge`'s hash-based pseudo-embedding, flagged
in its own comment as a "lightweight stand-in," with the real
`@claude-flow/embeddings` ONNX backend) scored second (4.10) and fires
on a more frequent path (every insight record, not gated behind a
trajectory threshold). Needs a 768→384-dim reconciliation plan first.
2. **H4** (consolidate the 4-5 duplicated EWC-shaped implementations) is
real design debt, correctly judged too large for one night (4
packages/plugins) — a dedicated scoping night, not a bundled fix.
3. **H5** (wire `utils/rng.ts`'s seedable PRNG into `moe-router.ts`'s
`xavierInit()`/`addNoise()` and `research.ts`'s k-means init — currently
zero imports from the RNG module built for this) is trivial, zero-risk,
and directly serves CLAUDE.md's own "measured, not inherited" discipline
— good pick for a tight-budget night.
4. Capabilities scan (ADR-451 `capabilityProbe`): the live validation
script only loads one plugin, so `plugin.register` can structurally
never fire — a test-harness gap, not an engine bug. One-line fix + a
second live run (~$0.05-0.15) closes the doc's own open disclosure.
5. Memory scan (`AutoMemoryBridge.importFromAutoMemory()`): additive-only —
never deletes entries whose heading was removed from source, so
retracted notes resurface forever. Qdrant's sync docs (grade A) describe
the standard fix. Distinct from the already-fixed #3351/#3352 bug.
+77
View File
@@ -0,0 +1,77 @@
# Intelligence SOTA Report — 2026-11-02
**TL;DR**: 2026 continual-learning research converges on a specific warning for self-learning agents: diagonal-Fisher EWC (exactly what Ruflo's SONA implements) is a known-imperfect approximation, and "capability erosion" from self-adaptation is now a named failure mode in the agent literature, not just a classic ML concern. Tonight directly continues 2026-10-27's (#4531/#4532) and 2026-11-01's (#4633 SCAN) own disclosed gap: `BalancedMode` was the only one of SONA's 5 learning modes wired into `SONAManager`'s EWC++ consolidation path. Investigating the other 4 modes found they are **not structurally equivalent** — `ResearchMode` already maintains real per-key gradient-shaped state (an Adam optimizer's `adamM`/`adamV`, already read back by its own dormant `computeEWCLoss()`), so it can be wired honestly using the exact reviewed Balanced-mode pattern. `EdgeMode` and `RealTimeMode` cannot be, without fabricating state from nothing. `BatchMode`'s gradient map is real but is zeroed on its own independent flush cadence, making a direct port semantically ambiguous rather than a clean port. Tonight wires `ResearchMode` only and discloses the other three with evidence, rather than stubbing all four uniformly.
## What's New in 2026
| Finding | Source | Confidence |
|---|---|---|
| Diagonal-Fisher EWC misses cross-parameter correlations; at low SNR per-sample gradients align and the empirical Fisher is closer to rank-1 — a rank-1 EWC+replay variant nearly eliminates forgetting on class-incremental benchmarks | arXiv:2509.23593 (ICLR 2026 poster), revised 2026-01 | A |
| "EWC Done Right": standard EWC's Fisher-matrix reliance can cause vanishing gradients and inaccurate importance estimates in some regimes; proposes EWC-DR | arXiv:2603.18596 (CVPR 2026 submission) | B |
| "Capability erosion" named explicitly as a multi-channel agent failure mode (workflow/skill/model/memory adaptation each degrade prior ability); preservation strategies reduce it across all four channels | arXiv:2605.09315 | B |
| Synthetic-data fine-tuning for agent skill retrieval causes real forgetting: OOD recall fell 0.850→0.650 in the most aggressive setup studied (34,396-skill corpus) | arXiv:2609.10750 | B |
| "How Fast Do Agents Rot?": geometric decay fits 28/36 model-task cells for long-horizon agent reliability; projects 0.42 (GAIA-length) → 0.24 (100-step production horizons) | arXiv:2609.01660 | C (single study) |
## Ruflo Current Capability
`SONAManager` (`v3/@claude-flow/neural/src/sona-manager.ts`) runs 5 pluggable learning modes (`real-time`/`balanced`/`research`/`edge`/`batch`) behind one `ModeImplementation` interface. `triggerLearning()` calls `modeImpl.learn()` then a mode-agnostic `updateEWCConsolidation()` hook that folds an optional `getConsolidationSnapshot()` into `ewcState.fisher`/`.means` via online-EWC decay+accumulate. 2026-10-27 implemented that optional hook for `BalancedMode` only (scoped deliberately); 2026-11-01's SCAN re-disclosed the other 4 modes as still contributing nothing. Direct inspection tonight of all 4 (`edge.ts`, `real-time.ts`, `research.ts`, `batch.ts`) found they are not one uniform gap: `ResearchMode` already runs a full Adam optimizer (`adamM`/`adamV`, persistent across calls, already consumed by its own long-dormant `computeEWCLoss()`) — structurally identical to Balanced's `gradientAccumulator`. `EdgeMode` stores only quantized `Int8Array` weights and compressed patterns (no per-key `Float32Array` gradient map exists to snapshot). `RealTimeMode`'s `learn()` contains the literal comment "we skip full backprop" and tracks no gradient state at all. `BatchMode` has a real `accumulatedGradients: Map<string, Float32Array>`, but `applyAccumulatedGradients()` deliberately `.fill(0)`s it every 4 learning cycles — a delta-since-last-EWC-snapshot measured at an arbitrary point relative to that independent flush would not mean "this cycle's movement" the way it does for Balanced/Research.
## Competitor Comparison
| Competitor | Mechanism | Weight-level continual-learning / forgetting mitigation? | Grade |
|---|---|---|---|
| LangGraph | Graph-state persistence across turns; human-in-the-loop checkpoints | No — state/memory management, not weight consolidation | C |
| AutoGen → Microsoft Agent Framework (1.0, 2026-04) | Custom memory stores per agent | No — externalized memory, not weight-level EWC/regularization | C |
| CrewAI | Built-in memory management, "flows" mode (2026) | No — same external-memory shape | C |
| OpenAI Agents SDK | Tight integration to Assistants/function-calling; no documented weight-adaptation layer | No — stateless-weights-by-design; forgetting is out of scope | C |
| **Ruflo (SONA)** | Per-mode LoRA adaptation + EWC++ Fisher/means consolidation (now 2/5 modes wired) | Partial — the only reviewed source with an actual weight-regularization mechanism, still incomplete | — |
The uniform "None" here is explained, not just reported: all four frameworks manage conversation/task **state**, not model **weights** — none of them fine-tune or adapt parameters in production the way SONA's LoRA+EWC pipeline does, so "catastrophic forgetting" in the classical sense is architecturally out of scope for them. This is a genuine differentiator, not an oversight on their part — and it means Ruflo owns both the capability and the risk the 2026 capability-erosion literature describes.
## Hypothesis
> Given SONA's `'research'` learning mode processing completed trajectories through `SONAManager.triggerLearning()` using its existing Adam-optimizer first-moment state (`adamM`), when a real diagonal-Fisher snapshot (squared delta of `adamM` since the last consolidation) is computed from that existing optimizer state and folded into `ewcState.fisher`/`.means` via the already-existing, mode-agnostic `updateEWCConsolidation()` path (zero `sona-manager.ts` changes required), then `ewcState.fisher`/`.means` should become non-empty and `ResearchMode`'s own existing, previously-inert `computeEWCLoss()` should return a strictly positive value after a second learning cycle — subject to: zero change to `ResearchMode`'s existing Adam-update math, zero regression to the `@claude-flow/neural` suite, deterministic $0 Vitest evaluation, and explicit non-claims that EdgeMode/RealTimeMode (no real gradient-shaped state to snapshot honestly) and BatchMode (gradient map reset on an independent flush cadence) remain unwired. Frozen before evaluation; not modified after.
## Benchmarks / Evaluation
Real evaluator: Vitest 4.1.8, `@claude-flow/neural`. 5 new tests (3 discriminating, 2 controls) in `__tests__/sona-ewc-consolidation-research.test.ts`, mirroring the reviewed Balanced-mode test file's structure. Stash-isolated baseline (`research.ts` reverted): 3/5 fail exactly as predicted (`ewcState.fisher/means` stay empty for research mode). Candidate: 5/5 pass — independently reproduced from scratch by a fresh-context adversarial critic, who also independently ran the full suite and `tsc`. Full `@claude-flow/neural` suite: **153/153** both ways except the 3 discriminating failures (8 files, 0 regressions). `tsc --noEmit`: 0 errors both ways.
## Adversarial Critique
**CONFIRMED-WITH-CAVEATS** (independent fresh-context critic). Verified: zero `sona-manager.ts` changes needed (hook is genuinely mode-agnostic); `adamM`'s never-cleared-except-init/cleanup lifecycle is structurally sound for the delta-since-snapshot approach (not the raw-cumulative-squaring bug Balanced's own fix corrected); non-finite guards hold under length mismatch; Fisher/means key sets agree with what `computeEWCLoss()` reads back. Re-ran the full suite, `tsc`, and their own independent stash-isolation — all matched. Confirmed by direct read that Edge/RealTime/Batch's "not wired" claims are accurate, not just asserted. On reward-hacking: using `adamM` (an EMA, not a raw gradient) as the Fisher-estimation input was judged **not** metric substitution — it's the same empirical-Fisher-via-smoothed-gradient approximation already reviewed and merged for Balanced mode, applied consistently. **One nit, fixed forward same session**: the "decays before folding in fresh evidence" test only asserted `> 0` instead of the stronger `> valueAfter1 * 0.9` Balanced's own test uses; tightened after the critic empirically confirmed a ~7.5x ratio comfortably clears that bound.
## Darwin Results
Skipped — binary wiring/correctness fix (a mode either implements `getConsolidationSnapshot()` or it doesn't), no continuous/categorical parameter for Darwin's bounded-evolution interface to search over. Same skip class as nearly every EWC-wiring ACCEPT in this repo's dream-cycle history (2026-10-27, and most binary-fix nights generally).
## Flywheel Evidence
No `.claude-flow/flywheel/` state exists in this checkout (confirmed by direct inspection, same as every prior night). Evidence retained as: the 5 new tests, both stash-isolated comparisons (session + independent critic), the issue, this gist, and the witness below.
## Reward Hack Check
Clean. Diff is additive-only (new method + 2 lines in `initialize()`/`cleanup()` + a new test file); no existing test, threshold, or gold data touched; $0, fully deterministic; independently re-verified by the adversarial critic, who specifically scrutinized the Adam-moment-as-Fisher-input choice (see above) and found it consistent with the already-reviewed Balanced-mode precedent, not a loosening.
## Scan Findings
**capabilities**: `.harness/mcp-policy.json` still falsely claims `allowShell:false`/`allowNetwork:false` at the MCP layer while `terminal_execute` and `http_fetch` MCP tools both exist in `@claude-flow/cli/src/mcp-tools/`, directly contradicting it. This is now the **3rd consecutive** disclosure (2026-10-26, 2026-10-27, tonight) without action — each night correctly treated it as "a design question, not a unilateral patch" rather than acting unilaterally, but per STEP 1.1 this now needs a deliberate human decision on a future night rather than a 4th deferral.
**memory**: `CacheManager.clear()` (`v3/@claude-flow/memory/src/cache-manager.ts:218-224`) still reads `this.cache.size` **after** calling `this.cache.clear()`, so the emitted `cache:cleared` event's `previousSize` is always `0`. Confirmed still live (2nd consecutive disclosure since 2026-10-27). Small, mechanical, one-line fix — a strong future-night pick.
## SOTA Proof & Witness
```
Session commit: 5f3dacc54b7279e39b172d6027d7989791448e2e
Candidate commit: 47dafc5b5d9da16adccbe716155e03e3dd7a32ca
Gist SHA-256 (pre-witness, this block held to the literal text PENDING): 48e2d7c45cf21b1a6e713c2f5abc24714b6eb5c2f8960f4dfee15ec317c9dfec
Witness stamp: c972c16f3884ca869e0df970127e3da7bb161fe0509d2465ab15fb41406ec380
```
Verifier: fetch this gist, replace this block's three dynamic values with the literal text `PENDING` (as they were before this computation), SHA-256 the result, concatenate with the Session commit above, SHA-256 again — must equal the Witness stamp.
Evaluation receipt identity: 5 new tests in `sona-ewc-consolidation-research.test.ts`, stash-isolated 3/5-fail-baseline → 5/5-pass-candidate, independently reproduced by a fresh-context adversarial critic who also ran the full suite and `tsc` themselves. Flywheel evidence identity: none (`.claude-flow/flywheel/` doesn't exist in this repo, confirmed). Darwin lineage identity: none (skipped, see above).
## Recommended Next Steps
1. **Fix `CacheManager.clear()`'s `previousSize:0` bug** (memory SCAN) — one-line, mechanical, high-confidence next-night pick, now twice disclosed.
2. **Force a deliberate decision on `.harness/mcp-policy.json`'s false shell/network claim** (capabilities SCAN) — 3rd consecutive disclosure without action; either tighten the policy's `$comment` framing to acknowledge native-tool-layer reach, or treat it as a real policy gap, but stop re-deferring it silently.
3. **Give `BatchMode`'s EWC wiring its own dedicated design pass**, not a port of tonight's pattern — specifically, decide what "this cycle's movement" should mean when `accumulatedGradients` is reset on an independent 4-step flush cadence, before attempting it.
+71
View File
@@ -0,0 +1,71 @@
# Intelligence SOTA Report — 2026-11-12
**TL;DR**: In 2026, continual-learning-for-agents has split into two camps — weight-space regularization (EWC-family, what Ruflo claims) versus non-parametric/replay approaches, with recent practitioner and research voices (Letta/MemGPT's "Continual Learning in Token Space" essay, SuRe arXiv:2511.22367, MSSR arXiv:2603.09892) arguing replay is the stronger, more consistently effective baseline. Tonight's review found Ruflo's own EWC++ implementation has a bug that makes this debate concrete: `SONAManager.triggerLearning()` re-fed every STILL-RESIDENT, already-learned trajectory into gradient accumulation on every cycle with no "already learned from" marker — fixed tonight (disclosed-but-not-fixed 2026-10-27, #4531/#4532). An independent adversarial critic then found, and this session independently re-confirmed, that the fix is real but narrower than first claimed: it stops replay of *stalled* trajectories, but `BalancedMode`'s underlying gradient accumulator is never reset at all, so EWC's `means` anchor still grows linearly and unboundedly under ordinary, correct, continuous operation (one genuinely-new trajectory per cycle) — a distinct, deeper bug carried forward, not fixed tonight. Also surfaced: a live fail-open authorization bug in `ruflo claims check`, a `memory compress` CLI/MCP schema mismatch, and a stale, inconsistent performance claim in CLAUDE.local.md.
## What's New in 2026
| Finding | Source | Confidence |
|---|---|---|
| Replay-based continual learning consistently outperforms EWC-style regularization for continual LLM/agent fine-tuning | SuRe arXiv:2511.22367; MSSR arXiv:2603.09892 | B |
| Letta/MemGPT: weight-space consolidation (EWC) is the wrong layer to fight forgetting at for agents; non-parametric context/memory paging sidesteps it entirely | Letta "Continual Learning in Token Space" essay (Dec 2025) | B/C |
| Vespa's HNSW is a genuinely mutable graph (real-time CRUD, no rebuild) — a published answer to "continual index updates" Ruflo's docs don't address | Vespa ANN docs + design blog | A/B |
| RouteLLM reports ~95% of top-model quality at ~14% of top-model queries via learned routing (cost/quality benchmark) — but a May-2026 study argues routing-headroom claims across this category are broadly inflated | RouteLLM arXiv (A); headroom-inflation critique (C, single source) |
| Adaptive/entropy-conditioned top-K expert selection is an active 2026 MoE research direction; Ruflo's `moe-router.ts` computes routing entropy but never consults it for K | SoftMoE/ProbMoE/AdaMoE summaries | B/C |
| A 72-model controlled 2025 study finds pure linear/flash attention degrades recall; recommends 3:1–6:1 linear:full-attention ratios | arXiv:2507.06457 | A |
| No 2025/2026 benchmark exists for flash/linear attention at small-batch, agent-coordination scale — a genuine open gap, honestly reported as absence-of-evidence | — | N/A |
**Why this isn't "None across the board"**: no competitor bundles routing + continual-learning + attention-management the way Ruflo's CLAUDE.md claims to; the field instead answers each piece separately and usually better-documented (Vespa on index mutability, RouteLLM on routing cost curves) — Ruflo's gap is in benchmarking/engaging these existing answers, not a universally unsolved problem.
## Ruflo Current Capability
`v3/@claude-flow/neural/src/sona-manager.ts`'s 4-stage pipeline (RETRIEVE→JUDGE→DISTILL→CONSOLIDATE) is real and reachable from production (`QueenCoordinator.completeTask()`→`NeuralLearningSystem`→`SONAManager.completeTrajectory()`→`triggerLearning()`). `moe-router.ts`'s 8-expert gate is correctly hardened (load-balance loss, persistence) per 2026-09-15's review. HNSW (`@claude-flow/memory`) measures ~1.9x–4.7x vs. brute force (CLAUDE.md, corrected from a fabricated 150x-12,500x figure found earlier this year) — but **CLAUDE.local.md still carries the uncorrected 150x-12,500x figure**, a live internal-consistency gap (flagged by tonight's competitor-analyst, not independently scored as a candidate — a one-line doc fix for a future night).
## Competitor Comparison
| Competitor | Mechanism | vs. Ruflo | Grade |
|---|---|---|---|
| Vespa | Mutable HNSW graph, no-rebuild CRUD | Published, load-bearing design Ruflo's HNSW docs don't address at all | A/B |
| Qdrant | Tunable ef/efConstruct, segment-based inserts | User-exposed tuning docs; Ruflo doesn't expose efSearch as independently tunable (tonight's #1 deferred candidate) | B |
| Weaviate | Dynamic flat→HNSW conversion by size threshold | Matches Ruflo's own "HNSW loses below crossover" finding — an industry-acknowledged tradeoff | B |
| Milvus | Static per-collection index-type choice (HNSW/IVF/DiskANN/ScaNN) | Closest public analog to "pick index by workload shape," but static, not learned like Ruflo's MoE claim | B |
| RouteLLM / vLLM Semantic Router | Learned whole-model routing, published cost/quality curve | Ruflo's MoE gate has only an internal confidence-convergence metric, no external cost/quality benchmark, and conflates true MoE with cross-model routing | A/C |
| Letta/MemGPT | Non-parametric context paging, explicit rejection of weight-space consolidation | Direct, named challenge to Ruflo's EWC++ premise that CLAUDE.md doesn't engage | B/C |
| LangGraph/AutoGen/CrewAI | No built-in routing/continual-learning/attention primitives | Deliberate, stated design choice (stay unopinionated) — genuine N/A, not a gap | B |
## Hypothesis
> Given `SONAManager.triggerLearning()`, which re-filters the entire `this.trajectories` map on every call with no marker for prior processing, when trajectories are gated on a new `learnedFrom` flag set after a successful `modeImpl.learn()` call, then a `triggerLearning()` cycle with no newly-completed trajectories should produce zero additional gradient-accumulator/EWC-means movement and should not increment `learnIterations`, relative to today's baseline which reprocesses the full surviving backlog and produces nonzero movement from pure replay — while a cycle with a genuinely new completed trajectory still learns from it normally, subject to: zero change to `pruneTrajectories()`'s capacity-bounding behavior, zero change to below-threshold trajectory exclusion, deterministic $0 Vitest evaluation. Frozen before evaluation; not modified after. **Confirmed exactly as stated, no more and no less** — see Evaluation below for what this hypothesis does and does not cover.
## Benchmarks / Evaluation
Real evaluator: Vitest 4.1.8, `@claude-flow/neural` (package required `pnpm install` — no prior build). Stash-isolated baseline (`sona-manager.ts`/`types.ts` reverted): **3/4 new tests fail exactly as predicted** (`learnIterations` 1→2 on a no-op second cycle; `learnedFrom` always `undefined`, field doesn't exist); 1 non-discriminating control passes both ways. Candidate: **4/4 pass**; full package suite **152/152** (148 pre-existing + 4 new), 0 regressions; `tsc --noEmit` 0 errors both ways.
**Post-critique correction** (this is the important part — an earlier version of this evaluation overclaimed): a first growth probe (one trajectory completed once, then `triggerLearning()` called 150x with nothing new) showed baseline growing 6.59x (cycle30→150) and candidate flat — but that scenario is the ONE case the hypothesis actually covers (zero new completions), so "flat" there doesn't mean the underlying growth problem is solved. An independent adversarial critic re-ran the *actual* 2026-10-27 "stationary periodic input" scenario (one brand-new, content-identical trajectory completed every cycle — the realistic "agent keeps succeeding at a similar task" case) against the candidate and found the SAME 6.59x/2.03x growth curve the original baseline showed. This session independently reproduced that exact result twice more (own re-check + confirming the critic's numbers byte-for-byte): `ewcState.means[0]` = 0.000065/0.013917/0.091778/0.189414/0.384688 at cycles 1/30/150/300/600 — linear, not plateauing, under the fixed candidate. Root cause (traced in `modes/balanced.ts`): `accumulateGradient()`'s `gradientAccumulator` is a lifetime-cumulative sum reset only by `initialize()`/`cleanup()`; `getConsolidationSnapshot()` sets `ewcState.means` to that raw accumulator. Tonight's fix removes the O(backlog-size) *multiplier* on this growth (real, verified) but leaves the underlying O(cycle-count) unbounded accumulator itself untouched. **Verdict: ACCEPT-scoped (post-critique)** — ships the narrower, correctly-tested fix; the deeper accumulator-reset bug is disclosed, not fixed, and carried forward as tonight's top recommended next step.
## Darwin Results
Skipped — binary "already learned from" gate, not a continuous/categorical tunable parameter. Same skip class as most prior ACCEPTs of this shape.
## SOTA Proof & Witness
See PR for full witness block (session commit, candidate commit, gist SHA-256, witness stamp) — computed after this file is finalized.
## Recommended Next Steps
1. **`BalancedMode`'s never-reset gradient accumulator** (new, found by tonight's own adversarial critique — highest priority): `means`/`gradientAccumulator` grow linearly without bound under ordinary continuous operation, not just under the now-fixed backlog-replay bug. Needs a deliberate design decision (periodic reset/decay of the accumulator itself, not just gating which trajectories feed it) before `computeEWCPenalty()` is ever wired into a real gradient update.
2. **HNSW efSearch/efConstruction decoupling** (score 4.55/5, deep-researcher): decouple query-time `ef` from `efConstruction` in `hnsw-index.ts:334`; reuses `scripts/benchmark-intelligence.mjs` directly.
3. **`claims.ts` `checkCommand` fail-open on config error** (score 4.05/5, scan-capabilities): silently grants any non-`admin:`-prefixed claim on config read/parse failure; zero test coverage; a real, narrowly-scoped security candidate for a future security/capabilities night.
4. **`memory compress --quantize` CLI/MCP schema mismatch** (score 3.65/5, scan-memory): always prints "Quantization: No"/"Duration: NaNs" regardless of flags; pure glue-code bug, no data-integrity risk.
5. Sync CLAUDE.local.md's stale "150x-12,500x" HNSW figure with CLAUDE.md's corrected ~1.9x-4.7x number (doc-only, not scored as a candidate).
## Witness
```
Session commit: dc25dd9b522bf1f3761f0d061a0bd0deb1900ba1
Evaluation receipt identity: v3/@claude-flow/neural __tests__/sona-trigger-learning-idempotency.test.ts (4 tests) + sona-ewc-consolidation.test.ts (5 tests, docstring corrected)
Flywheel evidence identity: none (.claude-flow/flywheel/ does not exist in this checkout)
Darwin lineage identity: none (skipped — binary gate, not a tunable parameter)
Report SHA-256 (pre-witness): fa2e43352ad5de3487b3ca2b8cbcfdd6411340da1da395aacace03ea07098c9e
Witness stamp: 4cfe201778b06a9918196637183d4270c38da7123b2ee29119498c525d83db15
```
Verifier: fetch this file, replace "Report SHA-256 (pre-witness)" and "Witness stamp" values with the literal text PENDING, SHA-256 the result, concatenate with the Session commit, SHA-256 again — must equal the Witness stamp above.
+71
View File
@@ -0,0 +1,71 @@
# Memory SOTA Report — 2026-11-13
**TL;DR**: In 2026, "causal recall" — retrieval conditioned on a causal/provenance graph, not pure embedding similarity — is a genuine, actively-forming research frontier: two fresh 2026 papers (ActMem, AMA-Agent) build causal-dependency graphs over agent memory, and a 2026 survey names causal-graph-traversal-plus-similarity hybrids as "largely unexplored." No production memory system (Mem0, Letta/MemGPT, Zep/Graphiti, Qdrant, Weaviate, Milvus, LanceDB, Vespa) ships an activated version — Mem0 actually *removed* its graph variant in its 2026 v3 rewrite. Ruflo's own `@claude-flow/memory` already has a correctly-built `CausalRecall` controller — it imports the real `CausalRecall` class from `agentdb` and wraps it with the registry's own ADR-514 embedder adapter — but it was dead code: absent from every level of `ControllerRegistry`'s `INIT_LEVELS`, so `initialize()` never constructed it and `registry.get('causalRecall')` always returned `null`. Disclosed-but-deferred by a 2026-10-28 session ("needs a human call on init-level ordering"). Tonight: verified independently by two fresh subagents (one rebuilt the package from scratch, 93/93 baseline green; one adversarial critic re-derived and re-ran everything), fixed with a one-line `INIT_LEVELS` addition plus two discriminating tests.
## What's New in 2026
| Finding | Source | Confidence |
|---|---|---|
| ActMem: causal memory KG refined by counterfactual reasoning + PMI filtering; "utility for action," not recall capacity | [arXiv:2603.00026](https://arxiv.org/html/2603.00026) | B |
| AMA-Agent: explicit "Causality Graph" over interaction history, +11pt claim vs best baseline (ICML 2026) | [arXiv:2602.22769](https://arxiv.org/html/2602.22769v1) | C (author-reported, not cross-checked) |
| Mem0 removed its graph-memory variant (Mem0g) entirely in the April-2026 v3 rewrite — found the graph edge was thin even where it won | [Mem0 2026 blog](https://mem0.ai/blog/state-of-ai-agent-memory-2026); origin paper [arXiv:2504.19413](https://arxiv.org/html/2504.19413v1) | B |
| Zep/Graphiti: the one production system with an explicit bitemporal model (valid/invalid real-world time vs created/expired system time) — closest production analog to disciplined memory lifecycle, but still relationship/time-based, not causal-provenance-based | [arXiv:2501.13956](https://arxiv.org/abs/2501.13956); [Graphiti docs](https://mintlify.com/getzep/graphiti/concepts/temporal-model) | A |
| 2026 survey names "hybrid retrievers combining causal graph traversal with similarity search" as largely unexplored; proposes cheap causal-parent write-time annotation as an approximation | arXiv:2603.07670 | B |
| Qdrant/Weaviate explicitly decouple build-time `ef_construct`/`efConstruction` from query-time `hnsw_ef`/`ef`; official guidance: tune query-time first, touch build-time only if recall plateaus | [Qdrant course](https://qdrant.tech/course/essentials/day-2/what-is-hnsw/); [Weaviate ANN benchmarks](https://weaviate.io/developers/weaviate/benchmarks/ann) | A |
**Why this isn't "None across the board"**: the gap is real but it's a frontier, not abandonment — two 2026 papers and a survey are actively forming the idea, and Mem0's removal of graph memory this year reads as considered scope-narrowing (compute/design overhead vs. its token-cost pitch), not ignorance. Letta/MemGPT's flat pgvector archive looks like a genuine gap, not deliberate avoidance. Qdrant is the clearest "not our layer" case: its own blog frames provenance/causal modeling as the application's job, not the index's.
## Ruflo Current Capability
`v3/@claude-flow/memory/src/controller-registry.ts`'s `ControllerRegistry` declares `'causalRecall'` as a first-class `AgentDBControllerName`, with a correct `createController()` case (dynamic `import('agentdb')`, pulls the real `CausalRecall` export, constructs `new CR(this.agentdb.database, this.agentdbEmbedder(), this.agentdb.vectorBackend ?? undefined)` — the same `agentdbEmbedder()` ADR-514 adapter used by its already-wired siblings `learningSystem`/`explainableRecall`/`nightlyLearner`). It's also included in `isControllerEnabled()`'s "AgentDB-internal controllers" branch, so it reads as enabled whenever `agentdb !== null`. But `initialize()` only calls `createController()` for names it finds while iterating the `INIT_LEVELS` array (7 levels, 0-6), and `causalRecall` was absent from every one of them — so that construction code could never execute. The public `get<T>(name)` accessor's fallback path, for a name with no registry entry, only tries `this.agentdb[name]` (direct property) or `this.agentdb.getController(name)` (the *upstream* `agentdb` package's own method) — neither runs this wrapper's own embedder-adaptation logic. Net effect, confirmed by direct testing: `registry.get('causalRecall')` always returned `null`, silently, with no error.
Third instance in six weeks of the same "declared-but-dead" shape in this package family: `ControllerRegistry.set()` didn't exist, so 9 controllers' post-init activation silently no-op'd (fixed 10-28); `SecurityPolicy.minTrustLevelForWrite/Memory/Spawn` were declared but never read in sibling package `plugin-agent-federation` (fixed 10-31/11-01). Tonight's SCAN found two *more* fresh instances elsewhere (see Next Steps) — recurring enough to warrant a structural fix, not one-off patches.
Zero production call sites in `v3/` currently request `.get('causalRecall')` — unlike the 10-28/10-31 precedents, nobody is live-broken today. Tonight's fix is forward-looking: it makes a correctly-built, research-aligned capability (causal-provenance-conditioned recall — the exact frontier the 2026 literature above calls unexplored) reachable for the first time, removing a trap for the first future caller.
## Competitor Comparison
| Competitor | Mechanism | Causal/provenance-aware? | Lifecycle "declared-but-dead" guard? | Grade |
|---|---|---|---|---|
| LangGraph | Cross-thread `Store` + checkpointing | No — value+namespace, not origin | No plugin system | B |
| AutoGen / MS Agent Framework | Durable memory via 3rd-party (Neo4j, Hindsight) | None in-framework | Unverified | C |
| CrewAI | Unified `Memory` + per-record source tag | Partial — source tag, no causal edges | Unverified | B |
| OpenAI Agents SDK | `Sessions` = history only | None native | N/A | C |
| Mem0 | Mem0g: vector + entity-relation graph (removed 2026) | No — relations, not causality | N/A | B |
| Letta/MemGPT | Flat pgvector archival store | No — no edge typing | Unverified | B |
| Qdrant | Filterable HNSW, shared-attribute edges | No — explicitly app's job | N/A | B |
| Weaviate | `ENABLE_MODULES` module system | No | **Yes** — docs disclose >1 vectorizer disables `Explore` | A |
| Milvus | Vector + BM25 hybrid | None native (3rd-party bolt-ons) | 3rd-party lifecycle hooks only | B |
| LanceDB | Per-mutation versioning, manifest lineage | Lineage yes, causal reasoning no | N/A | B |
| Vespa | Rank profiles + match-features | No — feature-level, not causal | N/A | B |
Weaviate's documented module-interaction guard is the only real external precedent for "declared capability needs an activation guard" — Ruflo's gap was silent, Weaviate's is disclosed.
## Hypothesis
> Given `ControllerRegistry.initialize()`'s level-based controller activation (`INIT_LEVELS`), when `'causalRecall'` is added to Level 4's controller list (alongside its construction-sibling `causalGraph`), then `ControllerRegistry.get('causalRecall')` should return a real, non-null `CausalRecall` instance (built via the existing `createController()` case, with the registry's own ADR-514-adapted embedder) once `initialize()` completes and AgentDB is available — relative to today's baseline where `get('causalRecall')` always returns `null` because `causalRecall` is absent from every `INIT_LEVELS` entry and the public `get()` accessor's fallback path never invokes `createController()` — subject to: zero change to any other controller's level/order, zero regression to the existing `@claude-flow/memory` suite, the returned instance uses the wrapper's adapted embedder (not a mismatched contract), deterministic $0 Vitest evaluation. Frozen before evaluation; not modified after.
## Benchmarks / Evaluation
Real evaluator: Vitest 4.1.8 against `@claude-flow/memory`, built from source in-session. No `.harness/bench.json` corpus exists for this package; the package's own suite is the established "real evaluator" convention here (matches 10-18/10-28). Stash-isolated baseline: the 2 new tests fail exactly as predicted (`toContain('causalRecall')`; `expect(c, 'causalRecall').not.toBeNull()`). Candidate: 94/94 pass across the 4 relevant test files; `tsc --noEmit` clean both ways. Full package suite with candidate applied: 717/718 (1 pre-existing, unrelated, chmod-as-root environmental failure, byte-identical on the stashed baseline). **Independent adversarial critique: CONFIRMED-WITH-CAVEATS** — a fresh-context critic re-derived the bug from source, re-ran stash-isolation and the full suite itself, checked init-order safety (Level 4 runs after `vectorBackend`'s Level 2), grepped for other call sites (zero), and checked for a deliberate-omission reason (none; `agentdb`'s `CausalRecall` export is real). One caveat: the comment overstated `causalRecall` as "same shape as `causalGraph`" — `causalGraph` is actually built via `agentdb`'s own `getController()` switch, a different mechanism. Fixed forward same session; re-verified clean.
## Darwin Results
Skipped — binary level-membership fix (a controller name either sits in an `INIT_LEVELS` array or it doesn't), not a continuous/categorical tunable parameter. Same skip class as nearly every prior ACCEPT of this shape in this repo's history.
## SOTA Proof & Witness
Reward-hack check: clean — diff is additive-only (one array entry, two new tests, one comment correction), no existing test/threshold/gold data touched, independently re-confirmed by the adversarial critic. Security review: not security-sensitive — pure in-process controller-lifecycle wiring, no new I/O/network/filesystem/MCP surface, no credential handling. Flywheel: `.claude-flow/flywheel/` does not exist in this checkout, consistent with every prior night — evidence instead lives in the two discriminating tests, this gist, the issue, and the witness below.
```
Session commit: 002d8c1ac031871fc14220e964f4dbb35b60428f
Candidate commit: 51944eb30cff8226af302119608d61bd6f25de90
Witness stamp: 6d7d059d30431f825c65e67f2bd77b1f8231765dbc859758c2c7c6d0084e266f
```
Verifier: fetch this gist at the candidate commit, replace the three dynamic values above with the literal text `PENDING`, SHA-256 the result, concatenate with the Session commit, SHA-256 again — must equal the Witness stamp.
## Recommended Next Steps
1. **Act on tonight's own pattern elsewhere** — two fresh SCAN instances of the same "declared-but-dead" shape: `v3/plugins/code-intelligence`'s 7 declared config knobs (`defaultTopK`, `similarityThreshold`, `maxGraphDepth`, etc.) are merged by `updateConfig()` but never read by any of its 4 MCP tool handlers (4/5, future `plugins` night); `hooks worker dispatch --priority` is accepted/persisted/documented as priority-jumping but `drainDispatchQueue()` never reads it — plain FIFO regardless (4/5, future `automation` night).
2. Consider one test asserting every `AgentDBControllerName` appears in `INIT_LEVELS.flatMap(controllers)`, to catch this bug class at test time instead of one controller at a time.
3. Now that `causalRecall` is reachable, a future `memory` or `intelligence` night could prototype wiring it into a real retrieval call site — tonight's own SOTA research suggests shipping genuine causal-provenance-conditioned recall would be ahead of every reviewed competitor (none has shipped one).
+67
View File
@@ -0,0 +1,67 @@
# Intelligence SOTA Report — 2026-11-17
TL;DR: In 2026, an accepted ICLR paper ("ReasoningBank", arXiv 2509.25140) measured that distilling *both* successful and failed agent trajectories into memory beats distilling successes only. Ruflo's own `ReasoningBank.distill()` — the class actually wired into the live `completeTask()` → `LearningBridge.consolidate()` path — was doing exactly the inferior success-only thing, discarding every judged failure. Fixed tonight, plus a latent cross-type dedup bug the fix would otherwise have introduced.
## What's New in 2026
| Finding | Source | Confidence |
|---|---|---|
| Failure-aware trajectory distillation (+MaTTS test-time scaling) beats success-only memory on web/SWE benchmarks | Google Research, ICLR 2026 poster, arXiv 2509.25140 | A |
| Fisher-Guided Gradient Masking selects *which* params to update via Fisher info, beats MIGU without old-task data | arXiv 2601.18261 (Jan 2026) | B (single preprint) |
| EWC's task-boundary assumption is a poor fit for continuous LLM/agent learning (no discrete task demarcation) | arXiv 2502.04390 | B |
| Online-EWC canonical decayed-Fisher form confirmed across independent implementations | capymoa.org, AiDotNet docs | B |
| Combining regularization+replay+routing (not any one alone) sustains long-horizon agent memory | arXiv 2609.06986 (2026) | C (single paper) |
## Ruflo Current Capability
`ReasoningBank.distill()` (`v3/@claude-flow/neural/src/reasoning-bank.ts:456`) judged every trajectory (`getFailedTrajectories()` existed and was tracked in stats) but **only distilled successes** into the retrievable `this.memories` pool — failures were judged, then thrown away. A dual-track success/failure distiller already exists in a sibling file, `reasoningbank-adapter.ts` (697 lines, its own `Success|Failure|Partial` verdict type), but is never imported by `@claude-flow/neural/src/index.ts` — built once, never wired up, the same "implemented but disconnected" pattern this repo's own audit has flagged elsewhere.
Separately (not tonight's candidate, but surfaced by research): `BalancedMode.computeEWCPenalty()`'s output is computed but never reaches a real weight update in `learn()` — confirmed again tonight, still discarded, still disqualified for low production value (same conclusion as 2026-11-16's research).
## Competitor Comparison
| Framework | Continual/online learning | Forgetting mitigation | Self-optimizing routing/memory | Grade |
|---|---|---|---|---|
| LangGraph | None — app-defined store/checkpoint eviction, not weight learning | None | None | C |
| AutoGen | "Teachable" agents (vector-DB facts); newer task-centric-memory marked experimental | N/A (non-parametric) | None | B |
| CrewAI | 2026 unified `Memory` API (LanceDB-backed) | None native | None | B/C |
| OpenAI Agents SDK | `Sessions` = history persistence only, no cross-session semantic memory | N/A | None native | B |
| Letta (MemGPT) | Self-editing memory via tool calls; explicit "token space, not weight space" design philosophy | Avoided by design (no weight updates) | Agent-directed, not learned | B |
| Mem0 | ADD/UPDATE/DELETE/NOOP consolidation pipeline | Policy-driven selective forgetting, not automatic | None | B |
| Zep (Graphiti) | Bi-temporal knowledge graph, validity-interval fact invalidation | Strongest native decay mechanism in this set | None | A (own benchmark: DMR 94.8% vs MemGPT 93.4%) |
Every "None" in the self-optimizing-routing column is the same industry-wide, deliberate scope boundary: these are orchestration frameworks that keep the base model frozen and push "learning" into context/store engineering instead of weight space — a March 2026 position paper (arXiv 2603.01761) argues nobody ships the in-weight+in-context combination in production, citing per-customer fine-tune cost, recertification burden, and imperfect-importance-estimate forgetting risk (the same Fisher-proxy problem this repo's own audit flags in its EWC++). Ruflo is the only system here attempting real in-process EWC-style weight consolidation at all — ahead on that narrow axis, behind Zep/Mem0 on memory-product maturity and public, reproducible benchmarks.
## Hypothesis
> Given Ruflo's live trajectory-learning path (`LearningBridge.consolidate()` → `NeuralLearningSystem.completeTask()` → `ReasoningBank.distill()`), when `distill()` is changed to also distill unsuccessful trajectories into a distinct `memoryType: 'pitfall'` memory instead of unconditionally discarding them, then `ReasoningBank.retrieve()` should surface pitfall memories for queries similar to a past failure — which it structurally cannot today — subject to: zero regression to existing success-path distillation/retrieval tests, `PatternLearner.extractPattern()`'s positive-exemplar consumer must never promote a pitfall memory into a success `Pattern`, deterministic $0 Vitest evaluation. Frozen before evaluation; not modified after.
## Benchmarks
No numeric benchmark corpus — this is a correctness/completeness fix, not a performance claim. Evaluation is deterministic Vitest discrimination (below), consistent with "a benchmark without reproducibility is not a successful Dream Cycle" — reproducibility here comes from stash-isolated baseline-vs-candidate test runs, independently reproduced by the critic.
## Evaluation
Vitest 4.1.8, `@claude-flow/neural` package (ran directly against `src/`, no build required). 5 new/changed tests in `__tests__/patterns.test.ts` (1 behavior-change update of a test whose prior assertion *was* the bug; 4 new). Stash-isolated baseline (`git stash push --keep-index` on the 3 source files, test file kept): baseline fails exactly the 4 predicted tests (null where a pitfall was expected, missing `memoryType`), 38/42 unaffected tests still pass. Candidate: **43/43 pass** (one more test added after the forward-fix below). Full package suite: **152/152 pass, 0 regressions**. Related suite (`@claude-flow/memory`'s `learning-bridge.test.ts`, the real caller chain, mocked neural import): **78/78 pass**. `tsc --noEmit -p .`: **clean, 0 errors**.
## Darwin Results
Skipped — this is a binary/structural guard fix (distill failures or don't; no continuous/categorical parameter introduced), not a tunable Darwin could search over. Same category as 2026-11-16's EWC/capability-brain findings.
## SOTA Proof & Witness
Independent adversarial critique (fresh-context `reviewer` subagent): traced real production reachability (`LearningBridge.consolidate()` is wired into the CLI via `enableLearningBridge`, default `true` in at least one runtime preset); confirmed the `extractPattern()` anti-promotion guard is **load-bearing, not redundant** (threshold divergence between `ReasoningBank`'s `distillationThreshold`=0.6 and `PatternLearner`'s own `qualityThreshold`=0.5 meant a pre-fix trajectory scoring ~0.55 could already have reached `extractPattern` with no `memoryType` field to stop it); independently reproduced the stash-isolation; ran the full suite and `tsc` itself. Verdict: **CONFIRMED-WITH-CAVEATS**. One caveat was a real bug, not cosmetic: `deduplicateMemories()` would now delete a pitfall memory that happened to share a near-identical embedding (≥0.95 cosine similarity) with a higher-quality success memory, treating opposite outcomes as duplicates — a direct consequence of merging both types into one pool. **Fixed forward same session**: dedup now skips any pair whose `memoryType` differs; added a discriminating regression test (`createTestTrajectory`'s embedding depends only on domain/steps, not quality, so a same-shape success/pitfall pair reaches cosine similarity 1.0 — proven to fail without the guard, pass with it). Second caveat, disclosed but **not** fixed tonight (out of scope, pre-existing): `detectContradictions()`'s `consolidated` flag is set but never read by `retrieve()`/`retrieveByContent()` — a dead toggle that predates this change and is unrelated to it.
```
Session commit: 8cb2fbc7a1e9e08f20fc5fc6a45e1046ad0369b9
Candidate commit: 08e2e32 (dream/2026-11-17-intelligence)
Gist SHA-256: 2e3839768122c32df740f83d5921b6b3625028f1ebfd5517feeb9f5fbb42a530
Witness stamp: 2261d4ec0aad5dedb3ee82c2766a4be15553bad262f44181d8cb909a161018e8
```
Verifier: fetch this file from the `dream/2026-11-17-intelligence` branch, replace the three dynamic values above with the literal text `PENDING`, SHA-256 the result, concatenate with the Session commit, SHA-256 again — must equal the Witness stamp.
## Recommended Next Steps
1. **Ship tonight's candidate** (ACCEPT, post-critique): `ReasoningBank.distill()` now distills pitfall memories; `extractPattern()` call site gated on `memoryType === 'success'`; `deduplicateMemories()` no longer cross-deletes success/pitfall pairs. Human review required before merge.
2. **Wire `consolidated` into `retrieve()`/`retrieveByContent()`** so contradiction-flagged entries are actually excluded (currently a dead toggle, pre-existing, orthogonal to tonight's fix) — small, safe, a good next-night pick on the memory SCAN surface.
3. **Reconnect `reasoningbank-adapter.ts`'s dual-track distiller** (already has `Success|Failure|Partial` + confidence-prior config, more sophisticated than tonight's minimal fix) to `@claude-flow/neural/src/index.ts`, or deliberately retire it — it is prior art the team already built and never wired up; leaving two parallel, inconsistent distillation designs in the package is a legibility risk even though neither currently breaks the other.
+85
View File
@@ -0,0 +1,85 @@
# Memory SOTA Report — 2026-11-18
TL;DR: a Feb-2026 paper (HTM-EAR, arXiv:2603.10032) shows pure-LRU eviction catastrophically drops high-value, high-frequency entries under skewed access. Ruflo's `@claude-flow/memory` `CacheManager` is pure LRU+TTL with no importance/frequency signal, even though `CachedEntry.accessCount` already tracks exactly the data needed. Tonight ships an opt-in, Darwin-tuned frequency-aware eviction blend (`frequencyWeight`, default 0 = byte-identical to today) with a real evaluation receipt and a 3-generation parameter sweep.
## What's New in 2026
| Finding | Source | Confidence |
|---|---|---|
| LongMemEval-V2 extends long-term memory eval to agentic/web tasks; best system 72.5% vs. 48.5% RAG baseline, oracle ceiling 86-90% | arXiv preprint + public leaderboard, May 2026 | B |
| Naive/frequent memory consolidation degrades utility *below* a no-memory baseline (GPT-5.4 failed 54% of ARC-AGI problems it solved without memory, after consolidating) | arXiv:2605.12978, May/Aug 2026 | B |
| **HTM-EAR**: importance+usage-weighted eviction vs. LRU — LRU permanently discarded 2,416 "essential" facts of 15K on a BGL log corpus; MRR 0.069 (LRU) vs 0.336 (HTM-EAR) | arXiv:2603.10032, Feb 2026 | B |
| MemX: hybrid dense+sparse fusion via RRF (not MMR); Hit@5 51.6%, temporal reasoning still weak | arXiv:2603.16171, ~Mar 2026 | B |
| Provenance/lineage becoming a required trust layer for memory writes/reads, not just an audit afterthought | arXiv:2606.04990 (survey) + MAP-Graph, Jun 2026 | B |
| FadeMem: per-layer exponential decay forgetting, claims 45% storage reduction | arXiv:2601.18642, Jan 2026 | **C** — baseline for the 45% figure unstated; not used to justify tonight's candidate |
No numeric claim above came from training-data recall; all are from the cited 2026 sources. Ruflo's own internal "150x-12,500x HNSW speedup" figure (CLAUDE.md) could not be found in any external 2026 source and should continue to be treated as unverified/internal-only, consistent with the repo's own audit doc.
## Ruflo Current Capability
`@claude-flow/memory`'s hot paths (hybrid-RRF+MMR fusion, controller lifecycle, LRU cache mechanics) are heavily hardened from many prior nightly passes — dense with changelog-style comments documenting NaN/negative-weight guards, deterministic tie-breaks, embedding-cosine MMR, etc. `CacheManager` specifically: pure LRU+TTL, zero importance/frequency signal in eviction despite `CachedEntry.accessCount`/`lastAccessedAt` already being tracked on every entry — exactly the gap HTM-EAR documents.
## Competitor Comparison
| Product | Hybrid fusion | Consolidation/distillation | Temporal/decay | Provenance/audit |
|---|---|---|---|---|
| Mem0 | unverified (no RRF doc found) | ADD/UPDATE/DELETE/NOOP ops (verified) | unverified (LRU/time-decay claimed by secondary source only) | None found |
| Zep | verified — cosine+BM25+graph BFS+rerank | None (entity/community summarization, not strategy distillation) | bi-temporal **invalidation**, not decay (deliberate design choice) | partial (bi-temporal ingestion timestamps) |
| Letta | None found | background consolidation (official) | None found | unofficial only (community-documented edit log) |
| ReasoningBank | N/A (not a retrieval system) | core strength — LLM-judge success/failure distillation (ICLR 2026) | None found | None found |
| Qdrant | verified — prefetch+RRF, version-gated weights | N/A (infra layer, by design) | unverified (payload-timestamp filtering only, no decay score) | None found |
| Ruflo (`@claude-flow/memory`) | **ahead of MemX** — RRF+MMR diversity together (`smart-retrieval.ts`) | dedup-only (embedding-cosine near-dup, ≥0.95) — no decay/gated consolidation | **gap** — pure LRU+TTL only (tonight's candidate) | `source:` tags for rerank provenance, not a trust/audit layer |
None of the scanned products publish a benchmark combining weighted hybrid fusion *and* MMR diversity *and* provenance together — a real, not solved-and-hidden, differentiation gap worth a future deep-research pass.
## Hypothesis
> Given a `CacheManager` under size/memory pressure with a skewed access pattern (an entry accessed many times historically but not most-recently, sitting near the LRU tail while rarely-touched entries occupy more recent positions), when eviction is extended with an opt-in, continuous `frequencyWeight` (0-1, default 0) blending recency-rank with normalized `accessCount` over a bounded scan window (`evictionScanWindow`, default 32) — falling back to the exact original tail-eviction when `frequencyWeight` is 0/unset — then a high-access-count entry should survive eviction under `frequencyWeight>0` where pure LRU would evict it, subject to: byte-identical default behavior, zero change to TTL/`maxMemory` accounting, deterministic $0 Vitest evaluation.
Frozen before evaluation; not modified after.
## Benchmarks
New corpus `.harness/bench-memory-eviction-2026-11-18.json` (6 synthetic Zipfian-skewed-access tasks, seeded/deterministic, 3 skew levels) + driver `scripts/bench-cache-eviction.mts`. Metric: fraction of the true top-decile most-accessed keys ("golden") still resident after a trace replay, plus ops/sec. **Corpus-fairness caveat (disclosed, not resolved tonight):** this corpus was authored tonight by the same session evaluating tonight's candidate, and has not yet been run against an unrelated weak candidate to prove it has teeth — flagged for a future night, not blocking since the unit-test-level evidence below is independent of this corpus.
## Evaluation
Real Vitest evaluator, stash-isolated. Baseline: 718/719 pass (1 pre-existing unrelated environmental chmod-as-root failure, consistent with every prior night). Candidate: 722/723 (718 + 4 new discriminating tests), same 1 pre-existing failure, `tsc --noEmit` clean both ways. Baseline fails exactly 1 of the 4 new tests as predicted (the one requiring non-LRU behavior); the other 3 pass vacuously on baseline since it ignores the new config. Independently reproduced by a fresh-context adversarial critic (separate stash/pop cycle), verdict **CONFIRMED**, no blocking issues.
## Darwin Results
Repository-local bounded sweep (native `metaharness evolve --bench` unavailable — unbuilt `@claude-flow/swarm` dist, pre-existing on main). 3 generations × 4 candidates, fitness = 0.35·quality + 0.20·success_rate + 0.15·latency + 0.10·cost_efficiency + 0.10·reproducibility + 0.10·safety (frozen before the sweep ran). Baseline fitness 0.825. Winner: **`frequencyWeight=0.85, evictionScanWindow=32`**, fitness 0.851, mean essential-key retention +19.4pp over baseline, 0/6 tasks regressed, ~5% throughput overhead. Notably `frequencyWeight=1.0` (full HTM-EAR-style, no recency at all) *underperforms* the baseline (fitness 0.794, regresses 1/6 tasks) — a genuine interior optimum, not a monotonic "more is better" result. This is evidence for operators who opt in; **the shipped default stays 0 (unchanged behavior)** — no autonomous promotion of a new default. Lineage persisted at `.harness/darwin-lineage-2026-11-18.json`.
## SOTA Proof & Witness
See issue and PR for the full receipt.
```
Session commit: edf7ddb3fefa15bca87986225b5a5ef7d4d059e5
Candidate commit: 7466cb8cc358bd91be56f10e7ff73c3f97d8a93a
Gist SHA-256 (pre-witness): b0776589b040ffd5d7ac8a5df306c1196fdf3b05690170a91257dccf94a979fb
Witness stamp: 8e6a4d8e961e20331a1540bb8c82cd354e3e7ca15d2805396b1de0e9774656ed
```
Verifier: fetch this file from the branch, replace the Witness block's three dynamic values (Candidate commit, Gist SHA-256, Witness stamp) with the literal text `PENDING`, SHA-256 the result, concatenate with the Session commit above, SHA-256 again — must equal the Witness stamp.
## Recommended Next Steps
1. If an operator wants frequency-aware eviction in production, set `frequencyWeight: 0.85` (or close to it) on the relevant `CacheManager`/`TieredCacheManager` config — validated by tonight's sweep, not yet a default.
2. A future DEEP=automation night should audit *every* worker type (`map`, `optimize`, `consolidate`, `testgaps`, `benchmark`) for the "claims work with no executor" anti-pattern — 3 confirmed+fixed instances across 2 prior nights (MCP dispatch tool, worker-detect, daemon audit worker) suggest a systemic class, not isolated bugs.
3. A future deep-research pass should explore whether Ruflo's RRF+MMR fusion can be paired with a provenance/audit layer (MAP-Graph-style lineage gating) — no scanned competitor ships that combination, a genuine open differentiation gap rather than a solved-and-hidden one.
## SCAN: plugins
- `PluginStoreConfig` security defaults (`requireSecurityAudit`, `minTrustLevel`, `trustedAuthors`, `blockedPlugins`, `allowedPermissions`, `requirePermissionPrompt`) still never read anywhere outside their declaration/default sites (confirmed unfixed since 2026-10-13).
- `SecurityPolicy.minTrustLevelForSpawn` — **fixed** 2026-10-31 via PR #4619 (merged); one disclosed caveat (`claim-event`/`agent-handoff` message types still unreachable under default `allowedMessageTypes`) remains open, not new.
- `code-intelligence` dead config knobs (`search.defaultTopK/similarityThreshold`, `architecture.maxGraphDepth/includeVendor`, `refactoring.defaultDepth`) — confirmed still unfixed.
- **New**: `@claude-flow/plugins` security SDK's `ResourceLimits` (`src/security/index.ts:497-550`) declares/defaults/accepts overrides for 5 fields, but `check()` only ever evaluates `maxMemoryMB` — `maxCPUPercent`, `maxFileSize`, `maxOpenFiles` are dead. Zero in-repo callers today, but it's a public SDK export (`Security` namespace) — live-but-broken for any external plugin author who adopts the documented contract. Deferred.
## SCAN: automation
- The "worker claims completed/scanned work it never performed" anti-pattern (3 instances across 2026-10-13 and 2026-10-28, two different components) is now **fully fixed** with regression tests (#4196, #4549×2) — confirmed by direct source inspection tonight.
- `hooks worker dispatch --priority` remains a confirmed **dead flag**: accepted end-to-end (CLI → MCP tool → queue JSON) but `drainDispatchQueue()` never reads it and iterates queue files in raw `readdirSync` order. Still unfixed since 2026-11-13. Deferred — same root cause class as the fixed findings above, recommended as a future candidate.
## Ledger note
`docs/dream-cycle/LEDGER.md` has no rows for 2026-11-12/13/14/16/17 even though real branches/issues/PRs exist for all five nights (#4973, #4983, #4989, #5004, #5012 — all open drafts, STEP 25 just wasn't reached or merged to main). This is a backfill gap, not a pipeline failure — direct evidence (branches + PRs) confirms the pipeline ran every one of those nights. Tonight's row is appended on top; backfilling the gap is left for a future, lower-stakes pass since it's cosmetic, not a trust issue.
+4 -4
View File
@@ -24,7 +24,7 @@
"@claude-flow/cli-core": "3.7.8",
"@claude-flow/codex": "3.0.8",
"@claude-flow/mcp": "3.1.6",
"@claude-flow/neural": "3.0.3",
"@claude-flow/neural": "3.1.0",
"@claude-flow/plugin-agent-federation": "1.0.7",
"@claude-flow/security": "3.0.7",
"@claude-flow/shared": "3.0.10",
@@ -238,9 +238,9 @@
}
},
"node_modules/@claude-flow/neural": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@claude-flow/neural/-/neural-3.0.3.tgz",
"integrity": "sha512-u9E4i1givJUo25Y/2hZLjzqI0IJv+Tov2H2vLDYrSFga/YLifQ6sM596+3vZeHksYMciSJ6U7Pqn5JBl5vbkiA==",
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/@claude-flow/neural/-/neural-3.1.0.tgz",
"integrity": "sha512-5Wpl4jP0sV3dlV7M8C5Y/YDIR6s+JVauxutKc8fqEnUCeg5x1TIi9thsUsyZ7BgaTdZEyYiRAzqnwS00O5IVUg==",
"license": "MIT",
"dependencies": {
"@claude-flow/memory": "^3.0.0",
+1 -1
View File
@@ -72,7 +72,7 @@
"@claude-flow/cli-core": "3.7.8",
"@claude-flow/codex": "3.0.8",
"@claude-flow/mcp": "3.1.6",
"@claude-flow/neural": "3.0.3",
"@claude-flow/neural": "3.1.0",
"@claude-flow/plugin-agent-federation": "1.0.7",
"@claude-flow/security": "3.0.7",
"@claude-flow/shared": "3.0.10",
+186
View File
@@ -0,0 +1,186 @@
#!/usr/bin/env -S npx tsx
/**
* Dream-cycle 2026-11-18 bounded Darwin-style parameter sweep for
* CacheManager's new frequency-aware eviction (frequencyWeight /
* evictionScanWindow). Repository-local implementation: the native
* `metaharness evolve --bench` CLI path requires a built CLI dist that is
* not reproducible in this checkout (unbuilt `@claude-flow/swarm` dist,
* pre-existing on main), so this script plays the same role -- bounded
* generations x candidates, a frozen fitness function, real evaluation
* against the real CacheManager class (not a reimplementation) -- without
* introducing a new dependency, per STEP 0.5's repository-local fallback.
*
* Bounds enforced (STEP 12 default budget): max 3 generations, max 4
* candidates/generation, promote exactly 1 lineage winner.
*/
import { readFileSync } from 'node:fs';
import { CacheManager } from '../v3/@claude-flow/memory/src/cache-manager.js';
interface Task {
id: string;
seed: number;
numKeys: number;
maxSize: number;
numOps: number;
skewExponent: number;
goldenTopFraction: number;
}
interface Corpus {
tasks: Task[];
}
interface Candidate {
frequencyWeight: number;
evictionScanWindow: number;
}
// Deterministic mulberry32 PRNG -- no external dependency, fully reproducible from seed.
function mulberry32(seed: number): () => number {
let a = seed;
return () => {
a |= 0;
a = (a + 0x6d2b79f5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function zipfianKeyIndex(rand: () => number, numKeys: number, exponent: number): number {
// Rejection-free approximation: rank by 1/(i+1)^exponent weights via inverse CDF sampling.
const weights: number[] = [];
let total = 0;
for (let i = 0; i < numKeys; i++) {
const w = 1 / Math.pow(i + 1, exponent);
weights.push(w);
total += w;
}
const r = rand() * total;
let cum = 0;
for (let i = 0; i < numKeys; i++) {
cum += weights[i];
if (r <= cum) return i;
}
return numKeys - 1;
}
function runTask(task: Task, candidate: Candidate): { retention: number; opsPerSec: number } {
const rand = mulberry32(task.seed);
const keys = Array.from({ length: task.numKeys }, (_, i) => `k${i}`);
const trueAccessCount = new Array(task.numKeys).fill(0);
const cache = new CacheManager<number>({
maxSize: task.maxSize,
frequencyWeight: candidate.frequencyWeight,
evictionScanWindow: candidate.evictionScanWindow,
});
const start = performance.now();
for (let op = 0; op < task.numOps; op++) {
const idx = zipfianKeyIndex(rand, task.numKeys, task.skewExponent);
trueAccessCount[idx]++;
const key = keys[idx];
if (cache.get(key) === null) {
cache.set(key, idx);
}
}
const elapsedMs = performance.now() - start;
const opsPerSec = task.numOps / (elapsedMs / 1000);
const rankedByTrueFreq = keys
.map((k, i) => ({ k, freq: trueAccessCount[i] }))
.sort((a, b) => b.freq - a.freq);
const goldenCount = Math.max(1, Math.floor(task.numKeys * task.goldenTopFraction));
const golden = rankedByTrueFreq.slice(0, goldenCount).map((x) => x.k);
const resident = new Set(cache.keys());
const retained = golden.filter((k) => resident.has(k)).length;
const retention = retained / golden.length;
return { retention, opsPerSec };
}
function evaluate(corpus: Corpus, candidate: Candidate, baseline: Candidate) {
const perTask = corpus.tasks.map((task) => {
const cand = runTask(task, candidate);
const base = runTask(task, baseline);
return { task: task.id, cand, base };
});
const qualityDeltas = perTask.map((t) => t.cand.retention - t.base.retention);
const quality = clamp01(0.5 + avg(qualityDeltas) / 2);
const successRate = avg(perTask.map((t) => (t.cand.retention >= t.base.retention - 1e-9 ? 1 : 0)));
const latencyRatios = perTask.map((t) => t.cand.opsPerSec / t.base.opsPerSec);
const latency = clamp01(avg(latencyRatios) / 1.0);
const costEfficiency = 1; // deterministic in-process code, $0
const reproducibility = 1; // seeded PRNG, fully deterministic
const safety = successRate; // no regression vs. baseline on any task
const fitness =
0.35 * quality + 0.2 * successRate + 0.15 * latency + 0.1 * costEfficiency + 0.1 * reproducibility + 0.1 * safety;
return {
candidate,
quality,
successRate,
latency,
costEfficiency,
reproducibility,
safety,
fitness,
meanRetentionDelta: avg(qualityDeltas),
meanOpsRatio: avg(latencyRatios),
};
}
function avg(xs: number[]): number {
return xs.reduce((a, b) => a + b, 0) / xs.length;
}
function clamp01(x: number): number {
return Math.max(0, Math.min(1, x));
}
function main() {
const corpus: Corpus = JSON.parse(readFileSync('.harness/bench-memory-eviction-2026-11-18.json', 'utf-8'));
const baseline: Candidate = { frequencyWeight: 0, evictionScanWindow: 32 };
const lineage: Array<ReturnType<typeof evaluate> & { generation: number }> = [];
// Generation 1: sweep frequencyWeight, fixed window=32 (4 candidates).
const gen1Weights = [0.25, 0.5, 0.75, 1.0];
let gen1Results = gen1Weights.map((w) =>
evaluate(corpus, { frequencyWeight: w, evictionScanWindow: 32 }, baseline)
);
gen1Results.forEach((r) => lineage.push({ ...r, generation: 1 }));
let winner = gen1Results.slice().sort((a, b) => b.fitness - a.fitness)[0];
// Generation 2: sweep evictionScanWindow around winner's weight (4 candidates).
const gen2Windows = [8, 16, 32, 64];
let gen2Results = gen2Windows.map((win) =>
evaluate(corpus, { frequencyWeight: winner.candidate.frequencyWeight, evictionScanWindow: win }, baseline)
);
gen2Results.forEach((r) => lineage.push({ ...r, generation: 2 }));
winner = [...gen1Results, ...gen2Results].sort((a, b) => b.fitness - a.fitness)[0];
// Generation 3: fine-tune weight around winner (4 candidates).
const base = winner.candidate.frequencyWeight;
const gen3Weights = [Math.max(0.05, base - 0.2), Math.max(0.05, base - 0.1), Math.min(1, base + 0.1), Math.min(1, base + 0.2)];
let gen3Results = gen3Weights.map((w) =>
evaluate(corpus, { frequencyWeight: w, evictionScanWindow: winner.candidate.evictionScanWindow }, baseline)
);
gen3Results.forEach((r) => lineage.push({ ...r, generation: 3 }));
const finalWinner = lineage.slice().sort((a, b) => b.fitness - a.fitness)[0];
const baselineEval = evaluate(corpus, baseline, baseline);
console.log(JSON.stringify({ baselineEval, lineage, finalWinner }, null, 2));
}
main();
// Each CacheManager instance starts an un-refed cleanup setInterval
// (see the 2026-11-18 architecture-review disclosure of cache-manager.ts's
// missing .unref() -- a separate, disclosed-not-fixed finding tonight).
// This script creates ~150 short-lived instances and never calls
// shutdown() on them, so force a clean exit rather than waiting on them.
process.exit(0);
+3 -3
View File
@@ -111,7 +111,7 @@
"@claude-flow/cli-core": "3.7.8",
"@claude-flow/codex": "3.0.8",
"@claude-flow/mcp": "3.1.6",
"@claude-flow/neural": "3.0.3",
"@claude-flow/neural": "3.1.0",
"@claude-flow/plugin-agent-federation": "1.0.7",
"@claude-flow/security": "3.0.7",
"@claude-flow/shared": "3.0.10",
@@ -137,12 +137,12 @@
"ws": "^8.21.0",
"yaml": "^2.8.0",
"zod": "^4.6.7",
"@claude-flow/memory": "3.3.3"
"@claude-flow/memory": "3.4.0"
},
"optionalDependencies": {
"@agntcy/slim-bindings": "2.1.1",
"@claude-flow/aidefence": "3.2.2",
"@claude-flow/memory": "3.3.3",
"@claude-flow/memory": "3.4.0",
"@metaharness/flywheel": "~0.1.10",
"@metaharness/radio": "~0.1.0",
"@metaharness/turn-credit": "~0.1.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@claude-flow/memory",
"version": "3.3.3",
"version": "3.4.0",
"type": "module",
"description": "Memory module - AgentDB unification, HNSW indexing, vector search, hybrid SQLite+AgentDB backend (ADR-009)",
"homepage": "https://ruv.io",
@@ -0,0 +1,78 @@
/**
* Discriminating tests for CacheManager's frequency-aware eviction
* (dream-cycle 2026-11-18, memory surface).
*
* HTM-EAR (arXiv:2603.10032, Feb 2026) documents that pure-LRU eviction
* drops high-access-frequency entries that happen to sit near the LRU tail
* (because nothing *else* touched them recently), even though they carry
* far more historical value than their low-frequency neighbors. These tests
* reproduce exactly that scenario against CacheManager's real eviction path.
*/
import { describe, it, expect } from 'vitest';
import { CacheManager } from './cache-manager.js';
function setupSkewedCache(frequencyWeight?: number): CacheManager<string> {
const cache = new CacheManager<string>({
maxSize: 4,
frequencyWeight,
evictionScanWindow: 4,
});
cache.set('A', 'high-frequency-entry');
cache.get('A');
cache.get('A');
cache.get('A');
cache.get('A');
cache.get('A'); // A.accessCount === 5
// B, C, D are each set and never re-accessed, which — because `set()`
// moves the new entry to the front — pushes A toward the tail purely
// through recency decay while its accessCount stays at 5.
cache.set('B', 'cold-1');
cache.set('C', 'cold-2');
cache.set('D', 'cold-3');
return cache;
}
describe('CacheManager frequency-aware eviction (discriminating)', () => {
it('pure LRU (frequencyWeight unset) evicts the high-frequency entry once capacity is exceeded', () => {
const cache = setupSkewedCache(undefined);
cache.set('E', 'cold-4'); // triggers eviction at maxSize=4
expect(cache.has('A')).toBe(false); // the valuable entry is gone
expect(cache.has('B')).toBe(true);
});
it('frequencyWeight=1 protects the high-frequency entry, evicting a cold one instead', () => {
const cache = setupSkewedCache(1);
cache.set('E', 'cold-4');
expect(cache.has('A')).toBe(true); // protected despite being LRU-oldest
expect(cache.has('B')).toBe(false); // a cold, never-reaccessed entry is evicted instead
});
it('frequencyWeight=0 explicitly behaves identically to unset (exact pure-LRU passthrough)', () => {
const cacheUnset = setupSkewedCache(undefined);
const cacheZero = setupSkewedCache(0);
cacheUnset.set('E', 'cold-4');
cacheZero.set('E', 'cold-4');
expect(cacheZero.has('A')).toBe(cacheUnset.has('A'));
expect(cacheZero.keys().sort()).toEqual(cacheUnset.keys().sort());
});
it('control: with no skew (all entries equally cold), frequencyWeight=1 still evicts the oldest on ties', () => {
const cache = new CacheManager<string>({ maxSize: 3, frequencyWeight: 1, evictionScanWindow: 3 });
cache.set('X', '1');
cache.set('Y', '2');
cache.set('Z', '3');
cache.set('W', '4'); // all accessCount === 0 -> tie -> first-scanned (oldest/tail) wins
expect(cache.has('X')).toBe(false);
expect(cache.has('Y')).toBe(true);
expect(cache.has('Z')).toBe(true);
expect(cache.has('W')).toBe(true);
});
});
+50 -3
View File
@@ -349,6 +349,8 @@ export class CacheManager<T = MemoryEntry> extends EventEmitter {
lruEnabled: config.lruEnabled !== false,
maxMemory: config.maxMemory,
writeThrough: config.writeThrough || false,
frequencyWeight: config.frequencyWeight,
evictionScanWindow: config.evictionScanWindow,
};
}
@@ -403,10 +405,11 @@ export class CacheManager<T = MemoryEntry> extends EventEmitter {
private evictLRU(): void {
if (!this.tail) return;
const evictedKey = this.tail.key;
const evictedSize = this.tail.size;
const victim = this.selectEvictionVictim();
const evictedKey = victim.key;
const evictedSize = victim.size;
this.removeNode(this.tail);
this.removeNode(victim);
this.cache.delete(evictedKey);
this.currentMemory -= evictedSize;
this.stats.evictions++;
@@ -414,6 +417,50 @@ export class CacheManager<T = MemoryEntry> extends EventEmitter {
this.emit('cache:eviction', { key: evictedKey });
}
/**
* Pick the node to evict. With the default `frequencyWeight` of 0 this is
* always the LRU tail (identical to the original pure-LRU behavior). With
* `frequencyWeight` > 0, a bounded window of the least-recently-used nodes
* is scored by blending recency rank with normalized `accessCount`, so a
* historically high-frequency entry sitting near the tail can survive an
* eviction that pure recency would otherwise apply to it (the failure mode
* HTM-EAR, arXiv:2603.10032, documents for plain LRU under skewed access).
*/
private selectEvictionVictim(): LRUNode<T> {
const weight = this.config.frequencyWeight;
if (!weight) {
return this.tail!;
}
const window = Math.max(1, this.config.evictionScanWindow ?? 32);
const candidates: Array<{ node: LRUNode<T>; distanceFromTail: number }> = [];
let maxAccessCount = 0;
let node: LRUNode<T> | null = this.tail;
let distanceFromTail = 0;
while (node && distanceFromTail < window) {
candidates.push({ node, distanceFromTail });
if (node.value.accessCount > maxAccessCount) {
maxAccessCount = node.value.accessCount;
}
node = node.prev;
distanceFromTail++;
}
const scaleFactor = candidates.length > 1 ? candidates.length - 1 : 1;
let victim = candidates[0].node;
let bestScore = Infinity;
for (const candidate of candidates) {
const normalizedFreq =
maxAccessCount > 0 ? candidate.node.value.accessCount / maxAccessCount : 0;
const score = (1 - weight) * candidate.distanceFromTail + weight * normalizedFreq * scaleFactor;
if (score < bestScore) {
bestScore = score;
victim = candidate.node;
}
}
return victim;
}
private startCleanupTimer(): void {
// Clean up expired entries every minute
this.cleanupInterval = setInterval(() => {
@@ -5,6 +5,12 @@
* database alone, so their first predict/discover/recall call threw a
* TypeError on `this.embedder.embed…`, or the controller came back null.
*
* causalRecall added to this list 2026-11-13 (Dream Cycle): it takes the
* same `(db, embedder, vectorBackend)` shape and already used the ADR-514
* `agentdbEmbedder()` helper in its createController() case, but was never
* reachable at all until tonight's INIT_LEVELS fix — this is the first test
* that actually constructs it via the real initialize() path.
*
* Runs against the real `agentdb` package in a temp directory.
*/
import { describe, it, expect, afterAll } from 'vitest';
@@ -16,7 +22,7 @@ import { ControllerRegistry } from './controller-registry.js';
const dir = mkdtempSync(join(tmpdir(), 'ruflo-adr514-'));
afterAll(() => rmSync(dir, { recursive: true, force: true }));
const NAMES = ['learningSystem', 'explainableRecall', 'nightlyLearner', 'graphTransformer'] as const;
const NAMES = ['learningSystem', 'explainableRecall', 'nightlyLearner', 'graphTransformer', 'causalRecall'] as const;
describe('ControllerRegistry hands AgentDB controllers an embedder (ADR-514)', () => {
it('builds each embedder-taking controller with a usable embedder', async () => {
@@ -235,6 +235,21 @@ describe('ControllerRegistry', () => {
expect(level4?.controllers).toContain('nightlyLearner');
});
it('should include causalRecall in a level so initialize() constructs it (Dream Cycle 2026-11-13)', () => {
// causalRecall has a real createController() case (dynamic agentdb import +
// adapted embedder, same construction pattern as learningSystem/
// explainableRecall — causalGraph itself is built differently, via agentdb's
// own getController() switch) but was absent from every INIT_LEVELS entry, so
// initialize() never calls initController() for it and get('causalRecall')
// always returned null. Deferred 2026-10-28 ("needs a human call on
// init-level ordering"); acted on tonight — level 4, grouped with causalGraph
// for topical reasons (agentdb/vectorBackend are both already populated
// before the INIT_LEVELS loop runs, so level choice doesn't affect
// correctness, only grouping).
const allNames = INIT_LEVELS.flatMap((l) => l.controllers);
expect(allNames).toContain('causalRecall');
});
it('should include advanced services in level 5', () => {
const level5 = INIT_LEVELS.find((l) => l.level === 5);
expect(level5?.controllers).toContain('graphTransformer');
@@ -207,7 +207,15 @@ export const INIT_LEVELS: InitLevel[] = [
// Level 3: Specialization
{ level: 3, controllers: ['skills', 'explainableRecall', 'reflexion', 'attestationLog', 'batchOperations', 'memoryConsolidation'] },
// Level 4: Causal & routing
{ level: 4, controllers: ['causalGraph', 'nightlyLearner', 'learningSystem', 'semanticRouter'] },
// causalRecall added 2026-11-13 (Dream Cycle): it has a real createController()
// case (dynamic agentdb import + the ADR-514-adapted embedder — same construction
// pattern as learningSystem/explainableRecall; causalGraph itself is built
// differently, via agentdb's own getController() switch) but was absent from
// every level, so initialize() never constructed it and get('causalRecall')
// always returned null. agentdb and its .database/.embedder/.vectorBackend are
// already populated before this loop runs, so level placement doesn't affect
// correctness — grouped here with causalGraph for topical (causal-family) reasons.
{ level: 4, controllers: ['causalGraph', 'causalRecall', 'nightlyLearner', 'learningSystem', 'semanticRouter'] },
// Level 5: Advanced services
{ level: 5, controllers: ['graphTransformer', 'sonaTrajectory', 'contextSynthesizer', 'rvfOptimizer', 'mmrDiversityRanker', 'guardedVectorBackend'] },
// Level 6: Session management
+138 -6
View File
@@ -547,7 +547,25 @@ export class HNSWIndex extends EventEmitter {
* Magic header for serialized HNSW snapshots.
* Format: "HNSW" + version byte (0x01).
*/
static readonly SERIALIZATION_MAGIC = Buffer.from([0x48, 0x4e, 0x53, 0x57, 0x01]);
static readonly SERIALIZATION_MAGIC = Buffer.from([0x48, 0x4e, 0x53, 0x57, 0x02]);
/**
* v1 format (no quantization section) — kept readable for backward
* compatibility. Dream Cycle 2026-10-03: v1 serialize()/deserialize()
* dropped `config.quantization` (and trained PQ codebooks) entirely, so
* every reload silently lost quantizer state. v1 buffers still
* deserialize exactly as before (no quantizer restored, same pre-existing
* behavior) rather than being rejected.
*/
private static readonly SERIALIZATION_MAGIC_V1 = Buffer.from([0x48, 0x4e, 0x53, 0x57, 0x01]);
private static bufMatchesMagic(buf: Buffer, magic: Buffer): boolean {
if (buf.length < magic.length) return false;
for (let i = 0; i < magic.length; i++) {
if (buf[i] !== magic[i]) return false;
}
return true;
}
/**
* Serialize the index to a binary buffer.
@@ -588,6 +606,31 @@ export class HNSWIndex extends EventEmitter {
chunks.push(this.encodeLengthPrefixedString(this.config.metric));
chunks.push(this.encodeLengthPrefixedString(this.entryPoint ?? ''));
// Quantization section (v2 — Dream Cycle 2026-10-03). Persists the
// quantization config and, for trained product quantization, the
// learned codebooks, so distance dispatch (isProductQuantized()) is
// restored correctly on reload instead of silently falling back to
// generic cosine/euclidean on raw PQ centroid indices.
if (this.config.quantization) {
chunks.push(Buffer.from([1]));
chunks.push(this.encodeLengthPrefixedString(this.config.quantization.type));
const qmeta = Buffer.alloc(12);
qmeta.writeUInt32BE(this.config.quantization.bits ?? 0, 0);
qmeta.writeUInt32BE(this.config.quantization.subquantizers ?? 0, 4);
qmeta.writeUInt32BE(this.config.quantization.codebookSize ?? 0, 8);
chunks.push(qmeta);
const codebooks = this.quantizer?.exportCodebooks() ?? null;
if (codebooks) {
chunks.push(Buffer.from([1]));
chunks.push(this.encodeLengthPrefixedString(JSON.stringify(codebooks)));
} else {
chunks.push(Buffer.from([0]));
}
} else {
chunks.push(Buffer.from([0]));
}
const nodeCountBuf = Buffer.alloc(4);
nodeCountBuf.writeUInt32BE(this.nodes.size, 0);
chunks.push(nodeCountBuf);
@@ -636,11 +679,15 @@ export class HNSWIndex extends EventEmitter {
if (buf.length < HNSWIndex.SERIALIZATION_MAGIC.length) {
throw new Error('HNSWIndex.deserialize: buffer too short for magic header');
}
for (let i = 0; i < HNSWIndex.SERIALIZATION_MAGIC.length; i++) {
if (buf[i] !== HNSWIndex.SERIALIZATION_MAGIC[i]) {
throw new Error(
`HNSWIndex.deserialize: magic header mismatch at byte ${i} (got 0x${buf[i].toString(16)}, expected 0x${HNSWIndex.SERIALIZATION_MAGIC[i].toString(16)})`
);
const isV2 = HNSWIndex.bufMatchesMagic(buf, HNSWIndex.SERIALIZATION_MAGIC);
const isV1 = !isV2 && HNSWIndex.bufMatchesMagic(buf, HNSWIndex.SERIALIZATION_MAGIC_V1);
if (!isV2 && !isV1) {
for (let i = 0; i < HNSWIndex.SERIALIZATION_MAGIC.length; i++) {
if (buf[i] !== HNSWIndex.SERIALIZATION_MAGIC[i]) {
throw new Error(
`HNSWIndex.deserialize: magic header mismatch at byte ${i} (got 0x${buf[i].toString(16)}, expected 0x${HNSWIndex.SERIALIZATION_MAGIC[i].toString(16)})`
);
}
}
}
@@ -659,6 +706,38 @@ export class HNSWIndex extends EventEmitter {
offset = entryRead.offset;
const entryPoint = entryRead.value === '' ? null : entryRead.value;
// Quantization section (v2 only — absent/skipped for v1 buffers, which
// restore with no quantizer, matching their pre-existing behavior).
let quantization: QuantizationConfig | undefined;
let restoredCodebooks: unknown = null;
if (isV2) {
const hasQuantization = buf[offset]; offset += 1;
if (hasQuantization) {
const typeRead = readLengthPrefixedString(buf, offset);
offset = typeRead.offset;
const bits = buf.readUInt32BE(offset); offset += 4;
const subquantizers = buf.readUInt32BE(offset); offset += 4;
const codebookSize = buf.readUInt32BE(offset); offset += 4;
quantization = {
type: typeRead.value as QuantizationConfig['type'],
...(bits ? { bits: bits as 4 | 8 | 16 } : {}),
...(subquantizers ? { subquantizers } : {}),
...(codebookSize ? { codebookSize } : {}),
};
const hasCodebooks = buf[offset]; offset += 1;
if (hasCodebooks) {
const cbRead = readLengthPrefixedString(buf, offset);
offset = cbRead.offset;
try {
restoredCodebooks = JSON.parse(cbRead.value);
} catch {
restoredCodebooks = null; // corrupt JSON -> leave quantizer untrained, don't throw
}
}
}
}
const nodeCount = buf.readUInt32BE(offset); offset += 4;
const index = new HNSWIndex({
@@ -666,9 +745,13 @@ export class HNSWIndex extends EventEmitter {
M,
efConstruction,
metric,
quantization,
});
index.maxLevel = maxLevel;
index.entryPoint = entryPoint;
if (restoredCodebooks && index.quantizer) {
index.quantizer.importCodebooks(restoredCodebooks);
}
for (let n = 0; n < nodeCount; n++) {
const idRead = readLengthPrefixedString(buf, offset);
@@ -1177,6 +1260,55 @@ class Quantizer {
this.dimensions = dimensions;
}
/**
* Export trained PQ codebooks for persistence (Dream Cycle 2026-10-03 —
* HNSWIndex.serialize()/deserialize() previously dropped quantization
* state entirely, silently re-breaking the product-quantization distance
* dispatch fixed in #3093/#3094 on every reload). Returns null when this
* isn't product quantization or training hasn't completed yet — matching
* the existing pre-training bootstrap fallback, not a new limitation.
*/
exportCodebooks(): number[][][] | null {
return this.pqTrained ? this.codebooks : null;
}
/**
* Restore previously-trained PQ codebooks after deserialization.
*
* `codebooks` comes from `JSON.parse()` on persisted (possibly corrupted)
* data, so it is untyped input, not a trusted `number[][][]`. Validates
* shape (`numSubquantizers` sub-arrays, each `numCentroids` centroids of
* the expected per-subvector length) and that every value is a finite
* number before accepting it. On any mismatch, leaves the quantizer
* untrained (same as the pre-training bootstrap state) rather than
* adopting data that could produce NaN/garbage distances. Returns
* whether the codebooks were accepted.
*/
importCodebooks(codebooks: unknown): boolean {
const numSubquantizers = this.config.subquantizers || 8;
const numCentroids = this.config.codebookSize || 256;
const subvectorSize = Math.ceil(this.dimensions / numSubquantizers);
if (!Array.isArray(codebooks) || codebooks.length !== numSubquantizers) return false;
for (let m = 0; m < numSubquantizers; m++) {
const start = m * subvectorSize;
const expectedLen = Math.min(subvectorSize, this.dimensions - start);
const sub = codebooks[m];
if (!Array.isArray(sub) || sub.length !== numCentroids) return false;
for (const centroid of sub) {
if (!Array.isArray(centroid) || centroid.length !== expectedLen) return false;
for (const value of centroid) {
if (typeof value !== 'number' || !Number.isFinite(value)) return false;
}
}
}
this.codebooks = codebooks as number[][][];
this.pqTrained = true;
return true;
}
/**
* Encode a vector using quantization
*/
@@ -0,0 +1,262 @@
/**
* Dream Cycle 2026-10-03 — HNSW serialize()/deserialize() dropped
* quantization state entirely.
*
* `HNSWIndex.serialize()` never wrote `config.quantization` (or, for
* trained product quantization, the learned PQ codebooks) to the wire
* format. `deserialize()` always reconstructed via
* `new HNSWIndex({ dimensions, M, efConstruction, metric })` — no
* `quantization` field — so `this.quantizer` came back `null` after *any*
* save/reload cycle, regardless of what the index was built with. For
* trained product quantization this silently re-broke the distance
* dispatch fixed in #3093/#3094 (2026-08-25): `isProductQuantized()`
* depends on `this.quantizer !== null`, so a deserialized PQ index fell
* back to generic cosine/euclidean on raw PQ centroid indices — the exact
* bug that fix closed, reintroduced on every reload. This matters because
* `AgentDBAdapter.saveToDisk()`/`loadFromDisk()` call this exact
* serialize/deserialize pair in production.
*
* This test builds a trained-PQ index, measures recall@10 against a brute
* force unquantized ground truth *before* serialization, then measures it
* again on the object returned by `HNSWIndex.deserialize(index.serialize())`
* using the identical corpus/queries. Pre-fix, post-deserialize recall
* collapses to the same ~0.10 chance-level the already-fixed #3093/#3094
* bug produced; post-fix it stays at the ~0.27 level the trained-PQ fix
* established (same ballpark as `hnsw-quantization.test.ts`'s own
* measured figures, since this is the same dispatch path exercised after a
* round trip instead of in-process).
*/
import { describe, it, expect } from 'vitest';
import { HNSWIndex } from './hnsw-index.js';
function xorshift32(seed: number): () => number {
let s = seed || 1;
return () => {
s ^= s << 13;
s ^= s >>> 17;
s ^= s << 5;
return (s >>> 0) / 4294967296;
};
}
function buildClusteredCorpus(n: number, dim: number, numClusters: number, seed: number): Float32Array[] {
const rand = xorshift32(seed);
const centers: Float32Array[] = [];
for (let c = 0; c < numClusters; c++) {
const center = new Float32Array(dim);
for (let d = 0; d < dim; d++) center[d] = (rand() - 0.5) * 20;
centers.push(center);
}
const vectors: Float32Array[] = [];
for (let i = 0; i < n; i++) {
const center = centers[i % numClusters];
const v = new Float32Array(dim);
for (let d = 0; d < dim; d++) v[d] = center[d] + (rand() - 0.5) * 1.5;
vectors.push(v);
}
return vectors;
}
function bruteForceTopK(query: Float32Array, corpus: Float32Array[], ids: string[], k: number): Set<string> {
const scored = corpus.map((v, i) => {
let sum = 0;
for (let d = 0; d < v.length; d++) {
const diff = v[d] - query[d];
sum += diff * diff;
}
return { id: ids[i], dist: sum };
});
scored.sort((a, b) => a.dist - b.dist);
return new Set(scored.slice(0, k).map((s) => s.id));
}
async function recallAtK(index: HNSWIndex, corpus: Float32Array[], ids: string[], seed: number, numQueries: number, k: number): Promise<number> {
const rand = xorshift32(seed);
let totalRecall = 0;
for (let q = 0; q < numQueries; q++) {
const queryIdx = Math.floor(rand() * corpus.length);
const query = corpus[queryIdx];
const groundTruth = bruteForceTopK(query, corpus, ids, k);
const results = await index.search(query, k, 200);
const returned = new Set(results.map((r) => r.id));
let hits = 0;
for (const id of returned) if (groundTruth.has(id)) hits++;
totalRecall += hits / k;
}
return totalRecall / numQueries;
}
describe('HNSWIndex serialize/deserialize — quantization round-trip (Dream Cycle 2026-10-03)', () => {
const DIM = 64;
const N = 1500; // well above pqTrainingThreshold=256
const NUM_CLUSTERS = 8;
const NUM_QUERIES = 30;
const K = 10;
it('product-quantized recall@10 survives a serialize()/deserialize() round trip', async () => {
const corpus = buildClusteredCorpus(N, DIM, NUM_CLUSTERS, 42);
const ids = corpus.map((_, i) => `v-${i}`);
const index = new HNSWIndex({
dimensions: DIM,
metric: 'euclidean',
M: 16,
efConstruction: 100,
quantization: { type: 'product', subquantizers: 8, codebookSize: 256 },
});
for (let i = 0; i < corpus.length; i++) await index.addPoint(ids[i], corpus[i]);
const preRecall = await recallAtK(index, corpus, ids, 1337, NUM_QUERIES, K);
// eslint-disable-next-line no-console
console.log(`[dream-cycle] pre-serialize recall@10 = ${preRecall.toFixed(3)}`);
expect(preRecall).toBeGreaterThanOrEqual(0.25); // sanity: matches hnsw-quantization.test.ts's measured floor
const restored = HNSWIndex.deserialize(index.serialize());
const postRecall = await recallAtK(restored, corpus, ids, 1337, NUM_QUERIES, K);
// eslint-disable-next-line no-console
console.log(`[dream-cycle] post-deserialize recall@10 = ${postRecall.toFixed(3)}`);
// Pre-fix: quantizer dropped on reload -> isProductQuantized() false ->
// generic distance on raw PQ centroid indices -> recall collapses to
// ~0.10 (chance level, same class as the pre-#3093/#3094 measurement).
// Post-fix: quantizer + trained codebooks restored -> dispatch matches
// pre-serialize behavior.
expect(postRecall).toBeGreaterThanOrEqual(0.25);
expect(Math.abs(postRecall - preRecall)).toBeLessThan(0.05);
});
it('restored index exposes the same quantization config and trained codebooks', async () => {
const corpus = buildClusteredCorpus(N, DIM, NUM_CLUSTERS, 7);
const index = new HNSWIndex({
dimensions: DIM,
metric: 'euclidean',
quantization: { type: 'product', subquantizers: 8, codebookSize: 256 },
});
for (let i = 0; i < corpus.length; i++) await index.addPoint(`v-${i}`, corpus[i]);
const restored = HNSWIndex.deserialize(index.serialize()) as unknown as {
quantizer: { getCompressionRatio(): number; isPQTrained: boolean } | null;
};
expect(restored.quantizer).not.toBeNull();
expect(restored.quantizer!.isPQTrained).toBe(true);
expect(restored.quantizer!.getCompressionRatio()).toBe(8);
});
it('non-quantized index round-trip is unaffected (no quantization section regression)', async () => {
const index = new HNSWIndex({ dimensions: 8, metric: 'cosine' });
await index.addPoint('a', new Float32Array([1, 0, 0, 0, 0, 0, 0, 0]));
await index.addPoint('b', new Float32Array([0, 1, 0, 0, 0, 0, 0, 0]));
const restored = HNSWIndex.deserialize(index.serialize()) as unknown as { quantizer: unknown };
expect(restored.quantizer).toBeNull();
const results = await (restored as unknown as HNSWIndex).search(new Float32Array([1, 0, 0, 0, 0, 0, 0, 0]), 2, 50);
expect(results.map((r) => r.id).sort()).toEqual(['a', 'b']);
});
it('importCodebooks() rejects malformed shape and leaves the quantizer untrained (ruvnet review, #3650)', () => {
const index = new HNSWIndex({
dimensions: DIM,
metric: 'euclidean',
quantization: { type: 'product', subquantizers: 8, codebookSize: 256 },
}) as unknown as {
quantizer: { importCodebooks(c: unknown): boolean; isPQTrained: boolean };
};
// Wrong subquantizer count (7 instead of 8).
expect(index.quantizer.importCodebooks(new Array(7).fill(null))).toBe(false);
expect(index.quantizer.isPQTrained).toBe(false);
// Right shape, but a non-finite value buried in one centroid — must not
// be silently accepted (would otherwise poison every distance computed
// against that centroid with NaN).
const subvectorSize = Math.ceil(DIM / 8);
const malformed = Array.from({ length: 8 }, () =>
Array.from({ length: 256 }, () => new Array(subvectorSize).fill(0))
);
malformed[3][5][2] = NaN;
expect(index.quantizer.importCodebooks(malformed)).toBe(false);
expect(index.quantizer.isPQTrained).toBe(false);
// Correctly-shaped, all-finite codebooks are accepted.
const valid = Array.from({ length: 8 }, () =>
Array.from({ length: 256 }, () => new Array(subvectorSize).fill(0.5))
);
expect(index.quantizer.importCodebooks(valid)).toBe(true);
expect(index.quantizer.isPQTrained).toBe(true);
});
it('a corrupted codebooks JSON section in a v2 buffer leaves the quantizer untrained, not NaN-poisoned', async () => {
const corpus = buildClusteredCorpus(300, DIM, NUM_CLUSTERS, 11);
const index = new HNSWIndex({
dimensions: DIM,
metric: 'euclidean',
quantization: { type: 'product', subquantizers: 8, codebookSize: 256 },
});
for (let i = 0; i < corpus.length; i++) await index.addPoint(`v-${i}`, corpus[i]);
const buf = index.serialize();
// Corrupt the JSON-encoded codebooks payload in place: flip one byte
// inside the string region so JSON.parse() throws.
const corrupted = Buffer.from(buf);
const needle = corrupted.indexOf(Buffer.from('[[[')); // start of the codebooks JSON array
expect(needle).toBeGreaterThan(0);
corrupted[needle] = '{'.charCodeAt(0); // "[[[" -> "{[[" breaks JSON.parse
const restored = HNSWIndex.deserialize(corrupted) as unknown as {
quantizer: { isPQTrained: boolean } | null;
};
expect(restored.quantizer).not.toBeNull();
expect(restored.quantizer!.isPQTrained).toBe(false); // corrupt payload rejected, not crashed, not NaN-poisoned
});
it('v1-format buffers (no quantization section) still deserialize, with no quantizer (backward compatibility)', async () => {
// Hand-build a v1-format buffer for a tiny 2-node, non-quantized,
// cosine-metric index — the exact wire format serialize() produced
// before this fix (magic byte 0x01, no quantization section).
const chunks: Buffer[] = [];
chunks.push(Buffer.from([0x48, 0x4e, 0x53, 0x57, 0x01])); // v1 magic
const header = Buffer.alloc(16);
header.writeUInt32BE(8, 0); // dimensions
header.writeUInt32BE(16, 4); // M
header.writeUInt32BE(200, 8); // efConstruction
header.writeUInt32BE(0, 12); // maxLevel
chunks.push(header);
const encodeStr = (s: string): Buffer => {
const strBuf = Buffer.from(s, 'utf-8');
const out = Buffer.alloc(4 + strBuf.length);
out.writeUInt32BE(strBuf.length, 0);
strBuf.copy(out, 4);
return out;
};
chunks.push(encodeStr('cosine')); // metric
chunks.push(encodeStr('a')); // entryPoint
const nodeCountBuf = Buffer.alloc(4);
nodeCountBuf.writeUInt32BE(1, 0);
chunks.push(nodeCountBuf);
// One node "a", level 0, vector [1,0,0,0,0,0,0,0], no normalizedVector, no connections.
chunks.push(encodeStr('a'));
const meta = Buffer.alloc(4);
meta.writeUInt32BE(0, 0); // level
chunks.push(meta);
const vec = new Float32Array([1, 0, 0, 0, 0, 0, 0, 0]);
const vecLenBuf = Buffer.alloc(4);
vecLenBuf.writeUInt32BE(vec.length, 0);
chunks.push(vecLenBuf, Buffer.from(vec.buffer));
chunks.push(Buffer.from([0])); // no normalizedVector
const lvlCountBuf = Buffer.alloc(4);
lvlCountBuf.writeUInt32BE(0, 0); // zero connection levels
chunks.push(lvlCountBuf);
const v1Buffer = Buffer.concat(chunks);
const restored = HNSWIndex.deserialize(v1Buffer) as unknown as { quantizer: unknown };
expect(restored.quantizer).toBeNull(); // no quantization section in v1 -> no quantizer, same as pre-fix behavior
const results = await (restored as unknown as HNSWIndex).search(new Float32Array([1, 0, 0, 0, 0, 0, 0, 0]), 1, 50);
expect(results[0]?.id).toBe('a');
});
});
@@ -6,6 +6,19 @@
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import {
existsSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
rmSync,
statSync,
symlinkSync,
writeFileSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { IMemoryBackend, MemoryEntry, MemoryEntryUpdate } from './types.js';
import type { MemoryInsight } from './auto-memory-bridge.js';
import { LearningBridge } from './learning-bridge.js';
@@ -1044,6 +1057,307 @@ describe('LearningBridge', () => {
});
});
// ===== State persistence across process invocations =====
//
// Without this, every short-lived auto-memory-hook.mjs invocation
// constructs a fresh NeuralLearningSystem and its learning state
// (trajectories, patterns, LoRA weights, EWC state) resets to empty every
// time — completed-trajectory counts (and everything gated behind them,
// e.g. EWC consolidation) can never accumulate past one process's
// lifetime. These tests use a mock neural system extended with
// serialize/deserialize, kept separate from the shared createMockNeuralSystem()
// fixture used by every other test in this file so that tests which don't
// care about persistence never touch the filesystem.
describe('state persistence', () => {
let stateDir: string;
let statePath: string;
beforeEach(() => {
stateDir = mkdtempSync(join(tmpdir(), 'learning-bridge-state-'));
statePath = join(stateDir, 'sona-learning-state.json');
});
afterEach(() => {
rmSync(stateDir, { recursive: true, force: true });
});
function createPersistableNeuralSystem(serializedState: unknown = { taskCount: 1 }) {
return {
...createMockNeuralSystem(),
serialize: vi.fn().mockReturnValue(serializedState),
deserialize: vi.fn(),
};
}
it('should write serialized state to statePath on destroy', async () => {
const persistable = createPersistableNeuralSystem({ taskCount: 7 });
const b = new LearningBridge(backend, {
neuralLoader: createNeuralLoader(persistable as any),
statePath,
});
await b.onInsightRecorded(createTestInsight(), 'entry-1'); // triggers neural init
b.destroy();
expect(persistable.serialize).toHaveBeenCalledTimes(1);
expect(existsSync(statePath)).toBe(true);
expect(JSON.parse(readFileSync(statePath, 'utf-8'))).toEqual({ taskCount: 7 });
});
it('should restore state from statePath on load', async () => {
writeFileSync(statePath, JSON.stringify({ taskCount: 42 }));
const persistable = createPersistableNeuralSystem();
const b = new LearningBridge(backend, {
neuralLoader: createNeuralLoader(persistable as any),
statePath,
});
await b.onInsightRecorded(createTestInsight(), 'entry-1');
expect(persistable.deserialize).toHaveBeenCalledTimes(1);
expect(persistable.deserialize).toHaveBeenCalledWith({ taskCount: 42 });
b.destroy();
});
it('should accumulate state across separate bridge instances (the actual bug)', async () => {
// First "process": records an insight, persists on destroy.
const first = createPersistableNeuralSystem({ taskCount: 1 });
const b1 = new LearningBridge(backend, {
neuralLoader: createNeuralLoader(first as any),
statePath,
});
await b1.onInsightRecorded(createTestInsight(), 'entry-1');
b1.destroy();
expect(existsSync(statePath)).toBe(true);
// Second "process": a brand-new bridge/neural instance must restore
// what the first one persisted, rather than starting from empty —
// this is the behavior that was entirely missing before this fix.
const second = createPersistableNeuralSystem({ taskCount: 1 });
const b2 = new LearningBridge(backend, {
neuralLoader: createNeuralLoader(second as any),
statePath,
});
await b2.onInsightRecorded(createTestInsight(), 'entry-2');
expect(second.deserialize).toHaveBeenCalledWith({ taskCount: 1 });
b2.destroy();
});
it('should not write a state file when neural.serialize is unavailable', async () => {
// The default createMockNeuralSystem() (used everywhere else in this
// file) has no serialize/deserialize — confirms old-mock callers are
// unaffected and no accidental file ever gets written for them.
const b = new LearningBridge(backend, {
neuralLoader: createNeuralLoader(neural),
statePath,
});
await b.onInsightRecorded(createTestInsight(), 'entry-1');
b.destroy();
expect(existsSync(statePath)).toBe(false);
});
it('should start fresh (not throw) when the state file is corrupt JSON', async () => {
writeFileSync(statePath, '{not valid json');
const persistable = createPersistableNeuralSystem();
const b = new LearningBridge(backend, {
neuralLoader: createNeuralLoader(persistable as any),
statePath,
});
await expect(b.onInsightRecorded(createTestInsight(), 'entry-1')).resolves.not.toThrow();
expect(persistable.deserialize).not.toHaveBeenCalled();
expect(b.getStats().neuralAvailable).toBe(true);
b.destroy();
});
it('should start fresh (not throw) when deserialize rejects the schema version', async () => {
writeFileSync(statePath, JSON.stringify({ schemaVersion: 999 }));
const persistable = createPersistableNeuralSystem();
persistable.deserialize = vi.fn().mockImplementation(() => {
throw new Error('SONAManager: unsupported schemaVersion 999 (expected 1)');
});
const b = new LearningBridge(backend, {
neuralLoader: createNeuralLoader(persistable as any),
statePath,
});
await expect(b.onInsightRecorded(createTestInsight(), 'entry-1')).resolves.not.toThrow();
expect(b.getStats().neuralAvailable).toBe(true);
b.destroy();
});
it('should not call deserialize when no state file exists yet', async () => {
const persistable = createPersistableNeuralSystem();
const b = new LearningBridge(backend, {
neuralLoader: createNeuralLoader(persistable as any),
statePath,
});
await b.onInsightRecorded(createTestInsight(), 'entry-1');
expect(persistable.deserialize).not.toHaveBeenCalled();
b.destroy();
});
it('should never throw from destroy even if serialize itself throws', () => {
const persistable = createPersistableNeuralSystem();
persistable.serialize = vi.fn().mockImplementation(() => {
throw new Error('boom');
});
const b = new LearningBridge(backend, {
neuralLoader: createNeuralLoader(persistable as any),
statePath,
});
expect(() => b.destroy()).not.toThrow();
});
// ---- hardening found in the #4081 review (symlink, litter, torn writes, poisoned restore) ----
it('never writes through a symlink at statePath (an opened repo can plant one)', async () => {
const victim = join(stateDir, 'victim.txt');
writeFileSync(victim, 'VICTIM-ORIGINAL');
symlinkSync(victim, statePath);
const persistable = createPersistableNeuralSystem({ taskCount: 9 });
const b = new LearningBridge(backend, {
neuralLoader: createNeuralLoader(persistable as any),
statePath,
});
await b.onInsightRecorded(createTestInsight(), 'entry-1');
b.destroy();
expect(readFileSync(victim, 'utf-8')).toBe('VICTIM-ORIGINAL');
expect(persistable.deserialize).not.toHaveBeenCalled();
});
it('does not read a symlinked state file either', async () => {
const real = join(stateDir, 'real.json');
writeFileSync(real, JSON.stringify({ taskCount: 5 }));
symlinkSync(real, statePath);
const persistable = createPersistableNeuralSystem();
const b = new LearningBridge(backend, {
neuralLoader: createNeuralLoader(persistable as any),
statePath,
});
await b.onInsightRecorded(createTestInsight(), 'entry-1');
expect(persistable.deserialize).not.toHaveBeenCalled();
b.destroy();
});
it('creates no state file or directory when nothing was learned this session', async () => {
const nested = join(stateDir, 'never', 'made', 'state.json');
const persistable = createPersistableNeuralSystem({ taskCount: 0 });
const b = new LearningBridge(backend, {
neuralLoader: createNeuralLoader(persistable as any),
statePath: nested,
});
// Neural gets loaded (e.g. by a read-only lookup) but no insight is recorded.
await b.findSimilarPatterns('anything');
b.destroy();
expect(existsSync(join(stateDir, 'never'))).toBe(false);
expect(persistable.serialize).not.toHaveBeenCalled();
});
it('writes atomically: no temp files left behind and the file is private (0600)', async () => {
const persistable = createPersistableNeuralSystem({ taskCount: 3 });
const b = new LearningBridge(backend, {
neuralLoader: createNeuralLoader(persistable as any),
statePath,
});
await b.onInsightRecorded(createTestInsight(), 'entry-1');
b.destroy();
expect(readdirSync(stateDir)).toEqual(['sona-learning-state.json']);
if (process.platform !== 'win32') {
expect(statSync(statePath).mode & 0o777).toBe(0o600);
}
});
it('rolls the neural instance back when a schema-valid but malformed state is rejected', async () => {
writeFileSync(statePath, JSON.stringify({ schemaVersion: 1 }));
const persistable = createPersistableNeuralSystem({ fresh: true });
// A restore that throws after partially mutating the instance.
persistable.deserialize = vi.fn().mockImplementationOnce(() => {
throw new Error('half-applied');
});
const b = new LearningBridge(backend, {
neuralLoader: createNeuralLoader(persistable as any),
statePath,
});
await b.onInsightRecorded(createTestInsight(), 'entry-1');
// First call is the rejected restore, second is the rollback to the pre-restore snapshot.
expect(persistable.deserialize).toHaveBeenCalledTimes(2);
expect(persistable.deserialize).toHaveBeenLastCalledWith({ fresh: true });
b.destroy();
});
it('preserves a state file written by a newer schema instead of overwriting it', async () => {
const newer = JSON.stringify({ schemaVersion: 2, keep: 'me' });
writeFileSync(statePath, newer);
const persistable = createPersistableNeuralSystem({ taskCount: 1 });
persistable.deserialize = vi.fn().mockImplementation(() => {
throw new Error('SONAManager: unsupported schemaVersion 2 (expected 1)');
});
const b = new LearningBridge(backend, {
neuralLoader: createNeuralLoader(persistable as any),
statePath,
});
await b.onInsightRecorded(createTestInsight(), 'entry-1');
b.destroy();
expect(readFileSync(statePath, 'utf-8')).toBe(newer);
});
it('heals a corrupt state file by replacing it with a valid one after learning', async () => {
writeFileSync(statePath, '{truncated');
const persistable = createPersistableNeuralSystem({ taskCount: 2 });
const b = new LearningBridge(backend, {
neuralLoader: createNeuralLoader(persistable as any),
statePath,
});
await b.onInsightRecorded(createTestInsight(), 'entry-1');
b.destroy();
expect(JSON.parse(readFileSync(statePath, 'utf-8'))).toEqual({ taskCount: 2 });
});
it('creates the parent directory only when it has something to write', async () => {
const nested = join(stateDir, 'a', 'b', 'state.json');
const persistable = createPersistableNeuralSystem({ taskCount: 4 });
const b = new LearningBridge(backend, {
neuralLoader: createNeuralLoader(persistable as any),
statePath: nested,
});
await b.onInsightRecorded(createTestInsight(), 'entry-1');
b.destroy();
expect(JSON.parse(readFileSync(nested, 'utf-8'))).toEqual({ taskCount: 4 });
mkdirSync(stateDir, { recursive: true });
});
it('should default statePath to .swarm/sona-learning-state.json', () => {
const b = new LearningBridge(backend);
// No direct getter for the resolved path; verified via the documented
// default in LearningBridgeConfig.statePath and DEFAULT_CONFIG.
expect(b.getStats()).toBeDefined();
b.destroy();
});
});
// ===== Neural init caching =====
describe('neural initialization', () => {
@@ -10,6 +10,8 @@
*/
import { EventEmitter } from 'node:events';
import { lstatSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
import { basename, dirname, join } from 'node:path';
import type { IMemoryBackend, MemoryEntry, SONAMode } from './types.js';
import type { MemoryInsight, InsightCategory } from './auto-memory-bridge.js';
@@ -54,6 +56,15 @@ export interface LearningBridgeConfig {
* Primarily used for testing.
*/
neuralLoader?: NeuralLoader;
/**
* Path to persist/restore NeuralLearningSystem's serialized learning state
* across process invocations (default: '.swarm/sona-learning-state.json',
* mirroring MoERouter's '.swarm/moe-weights.json' convention). Each
* auto-memory-hook.mjs run constructs a fresh neural instance; without
* this round-trip its learning state — trajectory counts, patterns, EWC
* state — resets to empty every invocation.
*/
statePath?: string;
}
/** Aggregated learning statistics */
@@ -119,10 +130,14 @@ const DEFAULT_CONFIG: ResolvedConfig = {
consolidationThreshold: 10,
enabled: true,
insightNamespace: 'learnings',
statePath: '.swarm/sona-learning-state.json',
};
const MS_PER_HOUR = 3_600_000;
/** Largest learning-state file restore will read (state is bounded by the neural system's own caps, ~1.5 MB at the trajectory cap). */
const MAX_STATE_BYTES = 16 * 1024 * 1024;
// ===== LearningBridge =====
/**
@@ -158,6 +173,8 @@ export class LearningBridge extends EventEmitter {
totalBoostAmount: 0,
};
private destroyed = false;
/** Set when the state file belongs to another schema version: it is left untouched instead of being overwritten. */
private keepExistingState = false;
private neuralInitPromise: Promise<void> | null = null;
constructor(backend: IMemoryBackend, config?: LearningBridgeConfig) {
@@ -431,6 +448,8 @@ export class LearningBridge extends EventEmitter {
this.activeTrajectories.clear();
this.consolidatedEntries.clear();
this.persistNeuralState();
if (this.neural && typeof this.neural.cleanup === 'function') {
try {
this.neural.cleanup();
@@ -467,6 +486,7 @@ export class LearningBridge extends EventEmitter {
if (this.config.neuralLoader) {
// Use injected loader (test / custom integrations)
this.neural = await this.config.neuralLoader();
this.restoreNeuralState();
return;
}
@@ -489,6 +509,7 @@ export class LearningBridge extends EventEmitter {
}
this.neural = instance;
this.restoreNeuralState();
} catch {
// @claude-flow/neural not installed or failed to initialize.
// This is expected in many environments; degrade silently.
@@ -529,6 +550,104 @@ export class LearningBridge extends EventEmitter {
}
}
/**
* Best-effort restore of previously persisted learning state into the freshly
* constructed neural instance. Without this, every short-lived
* auto-memory-hook.mjs invocation starts SONAManager from a blank slate, so
* completed-trajectory counts (and everything gated behind them, incl. EWC
* consolidation) can never accumulate past one process's lifetime.
*
* The state file lives in the project directory, so it is treated as
* untrusted input: a symlink or non-regular file is never followed, the read
* is size-capped, and a rejected restore is rolled back to the pre-restore
* snapshot so a schema-valid but malformed file cannot leave the neural
* instance half-applied. A file written by another schema version is kept
* as is (never overwritten by this process).
*/
private restoreNeuralState(): void {
if (!this.neural || typeof this.neural.deserialize !== 'function') return;
const path = this.config.statePath;
let parsed: unknown;
try {
const st = lstatSync(path);
if (!st.isFile() || st.size > MAX_STATE_BYTES) return;
parsed = JSON.parse(readFileSync(path, 'utf-8'));
} catch {
return; // missing, unreadable or corrupt: start fresh (a later persist replaces it)
}
let snapshot: unknown;
let haveSnapshot = false;
if (typeof this.neural.serialize === 'function') {
try {
snapshot = this.neural.serialize();
haveSnapshot = true;
} catch {
// no rollback point available
}
}
try {
this.neural.deserialize(parsed);
} catch {
if (haveSnapshot) {
try {
this.neural.deserialize(snapshot);
} catch {
// best effort
}
}
const fileVersion = (parsed as { schemaVersion?: unknown } | null)?.schemaVersion;
const ownVersion = (snapshot as { schemaVersion?: unknown } | null)?.schemaVersion;
if (typeof fileVersion === 'number' && fileVersion !== ownVersion) {
this.keepExistingState = true;
}
}
}
/**
* Best-effort persistence of the current learning state. Called from
* destroy(), which auto-memory-hook.mjs invokes synchronously and unawaited
* right before the short-lived process exits, so the write is synchronous.
*
* Nothing is written when nothing was learned this session (no stray
* `.swarm/` directories in every working directory), when the existing file
* belongs to another schema version, or when the target (or its directory) is
* a symlink or not a regular file. The write is atomic (private temp file,
* mode 0600, then rename) so a killed process cannot leave a torn file.
* Concurrent processes are last-writer-wins: this is a known limitation.
*/
private persistNeuralState(): void {
if (this.keepExistingState) return;
if (this.stats.totalTrajectories === 0 && this.stats.completedTrajectories === 0) return;
if (!this.neural || typeof this.neural.serialize !== 'function') return;
const path = this.config.statePath;
const dir = dirname(path);
const tmp = join(dir, `.${basename(path)}.${process.pid}.${Date.now()}.tmp`);
try {
const body = JSON.stringify(this.neural.serialize());
try {
if (lstatSync(dir).isSymbolicLink()) return;
} catch {
mkdirSync(dir, { recursive: true });
}
try {
if (!lstatSync(path).isFile()) return;
} catch {
// no existing file: fine
}
writeFileSync(tmp, body, { flag: 'wx', mode: 0o600 });
renameSync(tmp, path);
} catch {
// Best-effort; never block teardown on a persistence failure.
try {
unlinkSync(tmp);
} catch {
// nothing to clean up
}
}
}
/**
* Resolve the reward to report to the neural system when a trajectory
* completes. Uses the insight's current confidence (as tracked in
+12
View File
@@ -437,6 +437,18 @@ export interface CacheConfig {
/** Enable write-through caching */
writeThrough: boolean;
/**
* Blend factor (0-1) for frequency-aware eviction. 0 (default) preserves
* pure-LRU tail eviction exactly. Above 0, eviction scores a bounded
* window of least-recently-used entries by recency + normalized
* accessCount, so a high-frequency entry can survive an eviction pure
* recency would otherwise apply to it.
*/
frequencyWeight?: number;
/** Window size (entries scanned from the tail) for frequency-aware eviction. Default 32. Only consulted when frequencyWeight > 0. */
evictionScanWindow?: number;
}
/**
@@ -160,19 +160,50 @@ describe('ReasoningBank - Memory Distillation', () => {
expect(memory).toBeDefined();
expect(memory?.memoryId).toBeDefined();
expect(memory?.memoryType).toBe('success');
expect(memory?.strategy).toBeDefined();
expect(memory?.keyLearnings).toBeDefined();
expect(memory?.embedding).toBeInstanceOf(Float32Array);
expect(memory?.quality).toBeCloseTo(0.8);
});
it('should not distill low-quality trajectories', async () => {
it('should distill low-quality (failed) trajectories as pitfall memories, not discard them', async () => {
const trajectory = createTestTrajectory(0.3);
const memory = await bank.distill(trajectory);
expect(memory).not.toBeNull();
expect(memory?.memoryType).toBe('pitfall');
expect(memory?.strategy.startsWith('AVOID: ')).toBe(true);
expect(trajectory.verdict?.success).toBe(false);
});
it('should not distill a trajectory with no recorded steps', async () => {
const trajectory = createTestTrajectory(0.8, 'code', 0);
const memory = await bank.distill(trajectory);
expect(memory).toBeNull();
});
it('should never let a pitfall memory be promoted into a positive-success Pattern', async () => {
const failedTrajectory = createTestTrajectory(0.3);
const memory = await bank.distill(failedTrajectory);
expect(memory?.memoryType).toBe('pitfall');
// Mirrors the live guard in AdaptiveIntelligence.completeTask() —
// a pitfall memory must never reach memoryToPattern/extractPattern.
const patternCountBefore = bank.getPatterns().length;
expect(patternCountBefore).toBe(0);
});
it('should make a pitfall memory retrievable alongside success memories', async () => {
const failedTrajectory = createTestTrajectory(0.3, 'code', 8);
const failedMemory = await bank.distill(failedTrajectory);
expect(failedMemory).not.toBeNull();
const results = await bank.retrieve(failedMemory!.embedding, 5);
expect(results.some(r => r.memory.memoryId === failedMemory!.memoryId)).toBe(true);
});
it('should automatically judge before distillation', async () => {
const trajectory = createTestTrajectory(0.85);
expect(trajectory.verdict).toBeUndefined();
@@ -337,6 +368,25 @@ describe('ReasoningBank - Consolidation', () => {
expect(result.contradictionsDetected).toBeGreaterThanOrEqual(0);
});
it('should never deduplicate a success memory against a pitfall memory, even with an identical embedding', async () => {
// createTestTrajectory's embedding depends only on domain/steps, not
// quality, so these two produce a cosine similarity of 1.0 — the exact
// case dedup must NOT collapse now that pitfalls share the memory pool.
const successTraj = createTestTrajectory(0.95, 'code', 5);
const pitfallTraj = createTestTrajectory(0.2, 'code', 5);
const successMemory = await bank.distill(successTraj);
const pitfallMemory = await bank.distill(pitfallTraj);
expect(successMemory?.memoryType).toBe('success');
expect(pitfallMemory?.memoryType).toBe('pitfall');
expect(bank.getStats().memoryCount).toBe(2);
const result = await bank.consolidate();
expect(result.removedDuplicates).toBe(0);
expect(bank.getStats().memoryCount).toBe(2);
});
it('should merge similar patterns', async () => {
// Create some patterns first
for (let i = 0; i < 5; i++) {
@@ -27,6 +27,7 @@ import {
} from '../src/utils/serialize.js';
import { createReasoningBank } from '../src/reasoning-bank.js';
import { createPatternLearner } from '../src/pattern-learner.js';
import { assertValidSonaSnapshot } from '../src/utils/sona-state-validation.js';
// SONAManager is exercised separately — importing it here would pull in
// `modes/balanced.ts` which has a pre-existing load-order issue when
@@ -237,3 +238,54 @@ describe('Retrieval-path observability (#1773 item 2)', () => {
// deserialize() methods compile and behave correctly per the build, but
// instantiating SONAManager from a fresh vitest context surfaces a
// pre-existing class-inheritance bootstrap bug. Tracked for a follow-up.
describe('assertValidSonaSnapshot rejects malformed state before anything is assigned (#4081 review)', () => {
const validSnapshot = () => ({
schemaVersion: 1,
currentMode: 'balanced',
config: {},
optimizations: {},
trajectories: new Map(),
patterns: new Map(),
loraWeights: new Map(),
ewcState: null,
stats: {},
isInitialized: true,
operationCount: 0,
totalLatencyMs: 0,
learningCycles: 0,
lastStatsUpdate: 0,
});
it('accepts a complete, well-typed snapshot', () => {
expect(() => assertValidSonaSnapshot(validSnapshot())).not.toThrow();
});
it('keeps the unsupported-schema message', () => {
expect(() => assertValidSonaSnapshot({ ...validSnapshot(), schemaVersion: 2 })).toThrow(
/unsupported schemaVersion 2/,
);
});
const cases: Array<[string, unknown]> = [
['null', null],
['a number', 42],
['an array', []],
['only a schemaVersion', { schemaVersion: 1 }],
['an unknown mode', { ...validSnapshot(), currentMode: 'evil' }],
['a non-string mode', { ...validSnapshot(), currentMode: 7 }],
['config as a number', { ...validSnapshot(), config: 5 }],
['trajectories as a plain object', { ...validSnapshot(), trajectories: {} }],
['patterns as an array', { ...validSnapshot(), patterns: [] }],
['loraWeights as a number', { ...validSnapshot(), loraWeights: 5 }],
['ewcState as a string', { ...validSnapshot(), ewcState: 'x' }],
['isInitialized as a string', { ...validSnapshot(), isInitialized: 'yes' }],
['NaN counters', { ...validSnapshot(), operationCount: Number.NaN }],
['missing counters', { ...validSnapshot(), learningCycles: undefined }],
];
for (const [label, state] of cases) {
it(`rejects ${label}`, () => {
expect(() => assertValidSonaSnapshot(state)).toThrow();
});
}
});
@@ -0,0 +1,156 @@
/**
* Dream Cycle 2026-11-02 (DEEP=intelligence) — discriminating tests for
* ResearchMode's contribution to SONAManager's EWC++ consolidation path.
*
* Continues 2026-10-27's (#4531/#4532) own disclosed scope note, restated
* 2026-11-01 (#4633 SCAN): that fix wired `getConsolidationSnapshot()` for
* `BalancedMode` only — the other 4 modes still contributed nothing to
* `ewcState.fisher`/`.means`. Tonight's candidate wires `ResearchMode`,
* using its existing Adam-optimizer first-moment state (`adamM`, already
* read back by its own `computeEWCLoss()`) as the mode's "current
* parameter state", mirroring BalancedMode's own reviewed
* delta-since-last-snapshot pattern exactly.
*
* Scope disclosure (frozen before evaluation, not re-litigated after):
* EdgeMode and RealTimeMode are NOT wired by this candidate — neither
* tracks any per-key gradient-shaped state (Edge stores quantized int8
* weights; RealTime's `learn()` explicitly documents "we skip full
* backprop"), so a `getConsolidationSnapshot()` for either would have to
* fabricate Fisher/means from nothing rather than derive it from real
* learning state — exactly the "hidden preprocessing" / fabricated-metric
* shape the Dream Cycle's reward-hack check (STEP 11) exists to catch.
* BatchMode is also NOT wired tonight: its `accumulatedGradients` map is
* deliberately zeroed by `applyAccumulatedGradients()` on its own 4-step
* flush cadence (`gradientSteps >= 4`), so a delta-since-last-consolidation
* measured at an arbitrary point relative to that independent flush cycle
* would not carry the same "this cycle's movement" meaning it does for
* Balanced/Research — a dedicated design pass is needed there, not a
* direct port of this pattern. The last test below is a control proving
* Edge/RealTime are still exactly as inert as before this change (no
* fabricated state introduced for them).
*/
import { describe, it, expect } from 'vitest';
import { createSONAManager, type SONAManager } from '../src/sona-manager.js';
import { deepDecode } from '../src/utils/serialize.js';
import type { EWCState, Trajectory } from '../src/types.js';
function embedding(seed: number, len = 16): Float32Array {
const arr = new Float32Array(len);
for (let i = 0; i < len; i++) arr[i] = Math.sin(seed * 0.37 + i * 0.11);
return arr;
}
async function runLearningCycle(
manager: SONAManager,
domain: Trajectory['domain'],
seed: number,
quality: number
): Promise<void> {
const id = manager.beginTrajectory(`ctx-${seed}`, domain);
manager.recordStep(id, 'act-1', quality, embedding(seed));
manager.recordStep(id, 'act-2', quality, embedding(seed + 1));
manager.completeTrajectory(id, quality);
await manager.triggerLearning('test');
}
function decodeEwcState(manager: SONAManager): EWCState {
const decoded = deepDecode(manager.serialize()) as { ewcState: EWCState };
return decoded.ewcState;
}
describe('ResearchMode EWC++ consolidation', () => {
it('populates ewcState.fisher/means with real, non-zero values after a learning cycle (was permanently empty)', async () => {
const manager = createSONAManager('research');
await manager.initialize();
await runLearningCycle(manager, 'code', 1, 0.9);
const ewcState = decodeEwcState(manager);
expect(ewcState.fisher.size).toBeGreaterThan(0);
expect(ewcState.means.size).toBeGreaterThan(0);
let sawNonZero = false;
for (const fisher of ewcState.fisher.values()) {
for (const value of fisher) {
expect(Number.isFinite(value)).toBe(true);
expect(value).toBeGreaterThanOrEqual(0); // Fisher (squared delta) is never negative
if (value > 0) sawNonZero = true;
}
}
expect(sawNonZero).toBe(true);
expect(ewcState.taskCount).toBeGreaterThan(0);
expect(ewcState.lastConsolidation).toBeGreaterThan(0);
});
it('decays existing Fisher importance before folding in fresh evidence (online EWC), rather than overwriting it', async () => {
const manager = createSONAManager('research');
await manager.initialize();
await runLearningCycle(manager, 'code', 1, 0.9);
const after1 = decodeEwcState(manager);
const key = after1.fisher.keys().next().value as string;
const valueAfter1 = after1.fisher.get(key)![0];
expect(valueAfter1).toBeGreaterThan(0);
await runLearningCycle(manager, 'code', 2, 0.85);
const after2 = decodeEwcState(manager);
const valueAfter2 = after2.fisher.get(key)![0];
// Same reasoning as the reviewed BalancedMode test: the second cycle's
// fresh contribution is `decay(0.9) * valueAfter1 + freshFisher2`, and
// `freshFisher2` is itself strictly positive here (a different seed
// moves adamM further) — empirically ~7.5x valueAfter1 for this seed
// pair, well clear of the `* 0.9` decay-only floor. This test does not
// claim fisher stays bounded over many cycles.
expect(valueAfter2).toBeGreaterThan(valueAfter1 * 0.9);
expect(after2.taskCount).toBe(after1.taskCount + 1);
});
it('control: a trigger with no completed trajectories leaves ewcState untouched (no fabricated state)', async () => {
const manager = createSONAManager('research');
await manager.initialize();
await manager.triggerLearning('test'); // nothing completed yet -> learn() short-circuits
const ewcState = decodeEwcState(manager);
expect(ewcState.fisher.size).toBe(0);
expect(ewcState.means.size).toBe(0);
expect(ewcState.taskCount).toBe(0);
});
it('anchors means on adamM at consolidation, so computeEWCLoss() restarts at zero immediately after', async () => {
const manager = createSONAManager('research');
await manager.initialize();
await runLearningCycle(manager, 'code', 1, 0.9);
await runLearningCycle(manager, 'code', 2, 0.8);
const ewcState = decodeEwcState(manager);
const adamM = (manager as unknown as {
modeImpl: { adamM: Map<string, Float32Array> };
}).modeImpl.adamM;
expect(ewcState.means.size).toBeGreaterThan(0);
for (const [key, means] of ewcState.means) {
const current = adamM.get(key)!;
expect(current).toBeDefined();
for (let i = 0; i < means.length; i++) {
expect(means[i]).toBeCloseTo(current[i], 6);
}
}
});
it('control: EdgeMode and RealTimeMode remain exactly as inert as before this change (not wired, nothing fabricated)', async () => {
for (const mode of ['edge', 'real-time'] as const) {
const manager = createSONAManager(mode);
await manager.initialize();
await runLearningCycle(manager, 'code', 1, 0.9);
const ewcState = decodeEwcState(manager);
expect(ewcState.fisher.size).toBe(0);
expect(ewcState.means.size).toBe(0);
}
});
});
@@ -26,27 +26,58 @@
* delta), not the raw cumulative accumulator, specifically so Fisher/means
* don't trivially diverge from squaring an ever-growing lifetime-cumulative
* value; `means` is the accumulator at consolidation (the EWC anchor theta*,
* so the penalty restarts at zero). That bounds THIS fix's own contribution per cycle — but it does
* NOT make `ewcState.fisher` bounded over an arbitrarily long session,
* because of a separate, pre-existing, NOT-fixed-tonight behavior one
* layer up: `SONAManager.triggerLearning()` re-processes every completed
* trajectory still held in `this.trajectories` on every call (nothing
* marks a trajectory "already learned from"; only `pruneTrajectories()`'s
* 50%-of-capacity threshold ever removes one) — so `BalancedMode.learn()`'s
* `for (const good of goodTrajectories)` loop, and therefore
* `gradientAccumulator`'s movement per `triggerLearning()` call, grows with
* the total historical backlog, not just what's new since the last cycle.
* Verified directly (outside this test file, via a traced standalone
* script) that `ewcState.means[0]` grows roughly linearly over 150
* so the penalty restarts at zero). That bounds THIS fix's own contribution per cycle — but, as
* originally written, it did NOT make `ewcState.fisher` bounded over an
* arbitrarily long session, because of a separate, pre-existing behavior
* one layer up: `SONAManager.triggerLearning()` re-processed every
* completed trajectory still held in `this.trajectories` on every call
* (nothing marked a trajectory "already learned from"; only
* `pruneTrajectories()`'s 50%-of-capacity threshold ever removed one) — so
* `BalancedMode.learn()`'s `for (const good of goodTrajectories)` loop, and
* therefore `gradientAccumulator`'s movement per `triggerLearning()` call,
* grew with the total historical backlog, not just what was new since the
* last cycle. Verified directly (via a traced standalone script) that
* `ewcState.means[0]` grew roughly linearly (6.59x, cycle 30→150) over 150
* synthetic cycles with a stationary periodic input, well past the ~10-30
* cycles `BalancedMode`'s own `beta=0.9` momentum EMA would need to settle
* on a bounded periodic orbit if each cycle only processed its own new
* trajectory. Fixing that backlog-reprocessing behavior is a distinct,
* larger-blast-radius change (touches trajectory lifecycle, not EWC) and is
* carried forward as a priority future-night candidate — it should likely
* be fixed BEFORE `computeEWCPenalty()` is ever wired into a real gradient
* update (scope disclosure #1), or that wiring would inherit this
* divergence too.
* trajectory.
*
* **Partially fixed 2026-11-12** (carried forward as "a priority
* future-night candidate" above, picked up directly, then independently
* re-scoped by that same night's own adversarial critic — do not read this
* as fully resolved): `triggerLearning()` now gates on a new
* `Trajectory.learnedFrom` marker, excluding already-processed trajectories
* from subsequent cycles. See `sona-trigger-learning-idempotency.test.ts`
* for the discriminating tests. This closes exactly one driver of the
* growth above: a STALLED trajectory backlog (no new completions) no
* longer gets re-fed into `learn()` forever — verified flat (0.000065 at
* every checkpoint, 150 cycles) under that specific scenario.
*
* It does NOT bound `ewcState.means`/`gradientAccumulator` in general. Under
* continuous, realistic operation — a fresh, genuinely-new (never
* previously seen) trajectory completed every cycle, with similar-enough
* content that `BalancedMode`'s momentum EMA settles to a roughly steady
* nonzero value — `accumulateGradient()`'s `accumulator[i] += lr *
* momentum[i]` (this file's sibling `balanced.ts`, never reset except by
* `initialize()`/`cleanup()`) still sums a roughly constant increment every
* single cycle, forever. Re-ran the EXACT 2026-10-27 "stationary periodic
* input" scenario against the 2026-11-12 candidate (one brand-new
* trajectory per cycle, identical embedding/quality each time — distinct
* from, and a stricter test than, this file's own "zero new trajectories"
* probe) and got the SAME growth curve originally attributed to the
* pre-fix baseline: means[0] = 0.000065 / 0.013917 / 0.091778 at cycles
* 1/30/150 (6.59x, cycle30→150) and 0.189414/0.384688 at cycles 300/600
* (2.03x) — linear, not plateauing. Confirmed independently twice (the
* 2026-11-12 session's own re-check plus a separate adversarial-critic
* subagent, byte-identical numbers both times). This is a distinct,
* deeper, NOT-fixed-tonight bug (the never-reset accumulator itself, not
* which trajectories feed it) and is carried forward as the new priority
* future-night candidate, ahead of ever wiring `computeEWCPenalty()` into a
* real gradient update (scope disclosure #1 above, still open) — that
* wiring would otherwise inherit an EWC anchor (`means`) that drifts
* further from reality every single cycle even under correct, intended
* operation.
*/
import { describe, it, expect } from 'vitest';
@@ -0,0 +1,147 @@
/**
* Dream Cycle 2026-11-12 (DEEP=intelligence) — discriminating tests for
* SONAManager.triggerLearning()'s trajectory-reprocessing fix.
*
* Directly continues the priority follow-up `sona-ewc-consolidation.test.ts`
* disclosed (2026-10-27, PR #4531/#4532, "Scope disclosure #2"): before this
* fix, `triggerLearning()` re-filtered the ENTIRE `this.trajectories` map on
* every call with no marker for "already learned from" — so any trajectory
* that survived `pruneTrajectories()`'s quality-based eviction (the
* highest-quality ones, exactly the ones most worth keeping) got re-fed into
* `BalancedMode.learn()`'s gradient accumulation / EWC Fisher update on
* every subsequent cycle for as long as it stayed resident, purely from
* replaying old evidence rather than reflecting genuinely new data. The
* fix adds `Trajectory.learnedFrom` and excludes already-learned
* trajectories from the next cycle's filter.
*
* Every test below fails against the pre-fix baseline (verified via
* `git stash` isolation of `sona-manager.ts`/`types.ts`) and passes against
* the candidate.
*
* SCOPE DISCLOSURE (found by this same night's independent adversarial
* critic, confirmed by a second independent re-check): this fix only stops
* reprocessing of trajectories that are STILL RESIDENT with no new
* completions arriving (the scenario every test below exercises). It does
* NOT bound `BalancedMode`'s `gradientAccumulator`/`ewcState.means` under
* continuous normal operation — a steady stream of genuinely-new,
* similar-content trajectories (one per cycle, never reprocessed) still
* drives that accumulator to grow linearly without bound, because nothing
* resets it except `initialize()`/`cleanup()`. See
* `sona-ewc-consolidation.test.ts`'s updated docstring for the full
* reproduction and numbers; that deeper bug is carried forward as the next
* priority future-night candidate, not fixed here.
*/
import { describe, it, expect } from 'vitest';
import { createSONAManager, type SONAManager } from '../src/sona-manager.js';
function embedding(seed: number, len = 16): Float32Array {
const arr = new Float32Array(len);
for (let i = 0; i < len; i++) arr[i] = Math.sin(seed * 0.37 + i * 0.11);
return arr;
}
function gradientAccumulator(manager: SONAManager): Map<string, Float32Array> {
return (manager as unknown as {
modeImpl: { gradientAccumulator: Map<string, Float32Array> };
}).modeImpl.gradientAccumulator;
}
function learnIterations(manager: SONAManager): number {
return (manager as unknown as { modeImpl: { learnIterations: number } }).modeImpl
.learnIterations;
}
function snapshotAccumulator(manager: SONAManager): Map<string, Float32Array> {
const copy = new Map<string, Float32Array>();
for (const [key, value] of gradientAccumulator(manager)) {
copy.set(key, Float32Array.from(value));
}
return copy;
}
describe('SONAManager.triggerLearning() trajectory-reprocessing fix', () => {
it('a second triggerLearning() call with no new completed trajectories does not re-move the gradient accumulator', async () => {
const manager = createSONAManager('balanced');
await manager.initialize();
const id = manager.beginTrajectory('ctx-1', 'code');
manager.recordStep(id, 'act-1', 0.9, embedding(1));
manager.recordStep(id, 'act-2', 0.9, embedding(2));
manager.completeTrajectory(id, 0.9);
await manager.triggerLearning('test'); // cycle 1: learns from the one trajectory
const iterationsAfterCycle1 = learnIterations(manager);
const accumulatorAfterCycle1 = snapshotAccumulator(manager);
expect(accumulatorAfterCycle1.size).toBeGreaterThan(0);
await manager.triggerLearning('test'); // cycle 2: nothing new completed since cycle 1
expect(learnIterations(manager)).toBe(iterationsAfterCycle1);
const accumulatorAfterCycle2 = gradientAccumulator(manager);
for (const [key, before] of accumulatorAfterCycle1) {
const after = accumulatorAfterCycle2.get(key)!;
expect(after).toBeDefined();
for (let i = 0; i < before.length; i++) {
expect(after[i]).toBeCloseTo(before[i], 10);
}
}
});
it('marks every trajectory it learned from with learnedFrom=true', async () => {
const manager = createSONAManager('balanced');
await manager.initialize();
const id = manager.beginTrajectory('ctx-2', 'code');
manager.recordStep(id, 'act-1', 0.9, embedding(3));
manager.completeTrajectory(id, 0.9);
await manager.triggerLearning('test');
const trajectories = (manager as unknown as {
trajectories: Map<string, { learnedFrom?: boolean }>;
}).trajectories;
expect(trajectories.get(id)!.learnedFrom).toBe(true);
});
it('control: a genuinely new trajectory completed after cycle 1 IS processed in cycle 2 (the fix does not stop learning altogether)', async () => {
const manager = createSONAManager('balanced');
await manager.initialize();
const firstId = manager.beginTrajectory('ctx-3', 'code');
manager.recordStep(firstId, 'act-1', 0.9, embedding(4));
manager.completeTrajectory(firstId, 0.9);
await manager.triggerLearning('test');
const iterationsAfterCycle1 = learnIterations(manager);
const secondId = manager.beginTrajectory('ctx-4', 'code');
manager.recordStep(secondId, 'act-1', 0.9, embedding(5));
manager.completeTrajectory(secondId, 0.9);
await manager.triggerLearning('test');
expect(learnIterations(manager)).toBe(iterationsAfterCycle1 + 1);
const trajectories = (manager as unknown as {
trajectories: Map<string, { learnedFrom?: boolean }>;
}).trajectories;
expect(trajectories.get(firstId)!.learnedFrom).toBe(true);
expect(trajectories.get(secondId)!.learnedFrom).toBe(true);
});
it('control: a trajectory below qualityThreshold is never marked learnedFrom and never learned from', async () => {
const manager = createSONAManager('balanced');
await manager.initialize();
const id = manager.beginTrajectory('ctx-5', 'code');
manager.recordStep(id, 'act-1', 0.05, embedding(6));
manager.completeTrajectory(id, 0.05); // below default qualityThreshold
await manager.triggerLearning('test');
expect(learnIterations(manager)).toBe(0);
const trajectories = (manager as unknown as {
trajectories: Map<string, { learnedFrom?: boolean }>;
}).trajectories;
expect(trajectories.get(id)!.learnedFrom).toBeUndefined();
});
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@claude-flow/neural",
"version": "3.0.3",
"version": "3.1.0",
"type": "module",
"description": "Self-Optimizing Neural Architecture (SONA) for Claude Flow — adaptive learning, trajectory tracking, pattern reuse, 7 RL algorithms (PPO/A2C/DQN/Q-Learning/SARSA/Decision Transformer/Curiosity), Flash Attention, MoE routing, LoRA, EWC++ for continual learning. Reproducible via seedable PRNG; persistence via serialize/deserialize.",
"main": "dist/index.js",
+23 -2
View File
@@ -352,8 +352,10 @@ export class NeuralLearningSystem {
await this.reasoningBank.judge(trajectory);
const memory = await this.reasoningBank.distill(trajectory);
// Extract pattern if successful
if (memory) {
// Only promote a successful distillation into a reusable Pattern — a
// 'pitfall' memory (a failure to avoid) must never become a positive
// exemplar Pattern regardless of PatternLearner's own quality gate.
if (memory && memory.memoryType === 'success') {
this.patternLearner.extractPattern(trajectory, memory);
}
}
@@ -405,6 +407,25 @@ export class NeuralLearningSystem {
this.patternLearner.addEventListener(listener);
}
/**
* Serialize the full learning state (trajectories, patterns, LoRA weights,
* EWC state, stats) for persistence across process restarts. Delegates to
* SONAManager.serialize() — reasoningBank/patternLearner state is not
* included (callers that need it persist those separately).
*/
serialize(): unknown {
return this.sona.serialize();
}
/**
* Restore previously serialized learning state. Delegates to
* SONAManager.deserialize(), which throws on an unsupported schema
* version — callers should catch and discard rather than propagate.
*/
deserialize(state: unknown): void {
this.sona.deserialize(state);
}
/**
* Cleanup resources
*/
@@ -56,6 +56,7 @@ export class ResearchMode extends BaseModeImplementation {
this.adamM.clear();
this.adamV.clear();
this.adamStep = 0;
this.lastConsolidationSnapshot.clear();
}
async cleanup(): Promise<void> {
@@ -65,6 +66,7 @@ export class ResearchMode extends BaseModeImplementation {
this.checkpoints = [];
this.adamM.clear();
this.adamV.clear();
this.lastConsolidationSnapshot.clear();
await super.cleanup();
}
@@ -483,4 +485,69 @@ export class ResearchMode extends BaseModeImplementation {
return lambda * loss * 0.5;
}
// Snapshot of `adamM` as of the last call to getConsolidationSnapshot(),
// used to compute a bounded per-cycle delta instead of squaring the
// ever-growing EMA directly. Same rationale as BalancedMode's own
// `lastConsolidationSnapshot` (see modes/balanced.ts).
private lastConsolidationSnapshot: Map<string, Float32Array> = new Map();
/**
* Derive a Fisher-information/means snapshot from the CHANGE in `adamM`
* (the Adam first-moment EMA this mode already maintains across every
* `processBatch()` call, read back by `computeEWCLoss()`) since the last
* consolidation, for EWC consolidation.
*
* `adamM` is never cleared except in `initialize()`/`cleanup()`, so it
* plays the same role here as `gradientAccumulator` does in
* `BalancedMode.getConsolidationSnapshot()` — using the delta against the
* previous snapshot (rather than squaring the raw EMA value) bounds each
* cycle's Fisher contribution to that cycle's own first-moment movement,
* matching the already-reviewed Balanced-mode pattern. `means` is the
* `adamM` snapshot itself (the EWC anchor), so `computeEWCLoss()`'s
* penalty is zero immediately after consolidation.
*
* Scope: EdgeMode and RealTimeMode are not wired — neither tracks any
* per-key gradient-shaped state (Edge uses quantized weights; RealTime
* explicitly skips backprop), so a snapshot for either would have to be
* fabricated rather than derived. BatchMode is also not wired tonight:
* its `accumulatedGradients` map is deliberately zeroed by
* `applyAccumulatedGradients()` on its own 4-step flush cadence, so a
* delta-since-last-snapshot measured at an arbitrary point relative to
* that flush would not have the same "this cycle's movement" meaning it
* has here or in Balanced — a dedicated design pass, not a port of this
* same pattern, is needed there.
*/
getConsolidationSnapshot(): {
fisher: Map<string, Float32Array>;
means: Map<string, Float32Array>;
} {
const fisher = new Map<string, Float32Array>();
const means = new Map<string, Float32Array>();
for (const [key, current] of this.adamM) {
const previous = this.lastConsolidationSnapshot.get(key);
const delta = new Float32Array(current.length);
const snapshot = new Float32Array(current.length);
for (let i = 0; i < current.length; i++) {
const c = current[i];
const safe = Number.isFinite(c) ? c : 0;
const prevSafe = previous && Number.isFinite(previous[i]) ? previous[i] : 0;
delta[i] = safe - prevSafe;
snapshot[i] = safe;
}
const f = new Float32Array(delta.length);
for (let i = 0; i < delta.length; i++) {
f[i] = delta[i] * delta[i];
}
fisher.set(key, f);
means.set(key, Float32Array.from(snapshot));
this.lastConsolidationSnapshot.set(key, snapshot);
}
return { fisher, means };
}
}
+22 -4
View File
@@ -461,9 +461,18 @@ export class ReasoningBank {
await this.judge(trajectory);
}
// Only distill successful trajectories
if (!trajectory.verdict!.success ||
trajectory.qualityScore < this.config.distillationThreshold) {
// Distill both outcomes: successful trajectories become a reusable
// strategy to repeat, failed ones become a "pitfall" memory to avoid.
// A trajectory with no recorded steps carries nothing to distill either
// way, matching prior behavior for that one degenerate case.
if (trajectory.steps.length === 0) {
return null;
}
const memoryType: 'success' | 'pitfall' = trajectory.verdict!.success ? 'success' : 'pitfall';
// Keep the success path exactly as before: a success verdict supplied
// without judge() (which already applies this threshold) is still
// dropped below distillationThreshold.
if (memoryType === 'success' && trajectory.qualityScore < this.config.distillationThreshold) {
return null;
}
@@ -479,7 +488,8 @@ export class ReasoningBank {
const memory: DistilledMemory = {
memoryId: `mem_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`,
trajectoryId: trajectory.trajectoryId,
strategy,
memoryType,
strategy: memoryType === 'pitfall' ? `AVOID: ${strategy}` : strategy,
keyLearnings,
embedding,
quality: trajectory.qualityScore,
@@ -1177,6 +1187,14 @@ export class ReasoningBank {
for (let i = 0; i < entries.length; i++) {
for (let j = i + 1; j < entries.length; j++) {
// A success and a pitfall memory are never duplicates of each other
// regardless of embedding similarity — they encode opposite outcomes
// for a similar context, which is exactly the signal worth keeping.
// Snapshots written before memoryType existed only held successes.
if ((entries[i][1].memory.memoryType ?? 'success') !== (entries[j][1].memory.memoryType ?? 'success')) {
continue;
}
const sim = this.cosineSimilarity(
entries[i][1].memory.embedding,
entries[j][1].memory.embedding
+18 -5
View File
@@ -41,6 +41,7 @@ import { EdgeMode } from './modes/edge.js';
import { BatchMode } from './modes/batch.js';
import type { ModeImplementation } from './modes/index.js';
import { deepEncode, deepDecode } from './utils/serialize.js';
import { assertValidSonaSnapshot } from './utils/sona-state-validation.js';
/**
* Default mode configurations
@@ -431,8 +432,15 @@ export class SONAManager {
async triggerLearning(reason: string = 'manual'): Promise<void> {
const startTime = performance.now();
// Only feed trajectories that haven't already contributed to a prior
// learning cycle. Without this filter, every trajectory that survives
// pruneTrajectories()'s quality-based eviction (i.e. the highest-quality
// ones, exactly the ones most worth keeping) gets re-processed on every
// subsequent triggerLearning() call for as long as it stays resident,
// inflating gradient accumulation / EWC Fisher importance purely from
// replaying old evidence rather than reflecting genuinely new data.
const completedTrajectories = Array.from(this.trajectories.values())
.filter(t => t.isComplete && t.qualityScore >= this.config.qualityThreshold);
.filter(t => t.isComplete && t.qualityScore >= this.config.qualityThreshold && !t.learnedFrom);
if (completedTrajectories.length === 0) return;
@@ -449,6 +457,10 @@ export class SONAManager {
this.ewcState!
);
for (const trajectory of completedTrajectories) {
trajectory.learnedFrom = true;
}
this.updateEWCConsolidation();
this.learningCycles++;
@@ -683,13 +695,14 @@ export class SONAManager {
learningCycles: number;
lastStatsUpdate: number;
};
if (decoded.schemaVersion !== 1) {
throw new Error(`SONAManager: unsupported schemaVersion ${decoded.schemaVersion} (expected 1)`);
}
// Validate the whole snapshot BEFORE touching any field (see sona-state-validation.ts).
assertValidSonaSnapshot(decoded);
// Build the mode implementation first: if it throws, nothing has been assigned.
const modeImpl = this.createModeImplementation(decoded.currentMode);
this.currentMode = decoded.currentMode;
this.config = decoded.config;
this.optimizations = decoded.optimizations;
this.modeImpl = this.createModeImplementation(this.currentMode);
this.modeImpl = modeImpl;
this.trajectories = decoded.trajectories;
this.patterns = decoded.patterns;
this.loraWeights = decoded.loraWeights;
+16
View File
@@ -139,6 +139,15 @@ export interface Trajectory {
/** End timestamp (if complete) */
endTime?: number;
/**
* Set once this trajectory has been included in a `triggerLearning()`
* cycle (mode.learn() call). Prevents `SONAManager.triggerLearning()`
* from re-feeding the same already-processed trajectory into gradient
* accumulation / EWC Fisher updates on every subsequent cycle just
* because it survived `pruneTrajectories()`'s quality-based eviction.
*/
learnedFrom?: boolean;
/** Verdict from judgment */
verdict?: TrajectoryVerdict;
@@ -179,6 +188,13 @@ export interface DistilledMemory {
/** Source trajectory ID */
trajectoryId: string;
/**
* Whether this memory distills a successful trajectory to repeat, or a
* failed one to avoid. Consumers that assume a positive exemplar (e.g.
* "apply this strategy") must branch on this before acting on `strategy`.
*/
memoryType: 'success' | 'pitfall';
/** Extracted strategy pattern */
strategy: string;
@@ -0,0 +1,51 @@
/**
* Structural validation for a decoded SONAManager snapshot.
*
* SONAManager.deserialize() used to assign every field without checking it, so a
* schema-valid but malformed file (truncated, hand-edited, or planted in a
* repository's `.swarm/` directory) left the manager half-applied with
* undefined containers. This runs BEFORE any field is assigned.
*
* Kept free of imports from the mode implementations so it can be unit-tested
* without the mode/manager load-order cycle.
*/
const SONA_MODES: readonly string[] = ['real-time', 'balanced', 'research', 'edge', 'batch'];
const isRecord = (v: unknown): v is Record<string, unknown> =>
v !== null && typeof v === 'object' && !Array.isArray(v);
/** Throws a descriptive Error unless `decoded` is a complete, well-typed schemaVersion 1 snapshot. */
export function assertValidSonaSnapshot(decoded: unknown): void {
if (!isRecord(decoded)) {
throw new Error('SONAManager: state must be an object');
}
if (decoded.schemaVersion !== 1) {
throw new Error(`SONAManager: unsupported schemaVersion ${String(decoded.schemaVersion)} (expected 1)`);
}
if (typeof decoded.currentMode !== 'string' || !SONA_MODES.includes(decoded.currentMode)) {
throw new Error(`SONAManager: invalid currentMode ${String(decoded.currentMode)}`);
}
if (!isRecord(decoded.config) || !isRecord(decoded.optimizations) || !isRecord(decoded.stats)) {
throw new Error('SONAManager: invalid config, optimizations or stats');
}
if (
!(decoded.trajectories instanceof Map) ||
!(decoded.patterns instanceof Map) ||
!(decoded.loraWeights instanceof Map)
) {
throw new Error('SONAManager: trajectories, patterns and loraWeights must be maps');
}
if (decoded.ewcState !== null && !isRecord(decoded.ewcState)) {
throw new Error('SONAManager: invalid ewcState');
}
if (typeof decoded.isInitialized !== 'boolean') {
throw new Error('SONAManager: invalid isInitialized');
}
for (const key of ['operationCount', 'totalLatencyMs', 'learningCycles', 'lastStatsUpdate']) {
const v = decoded[key];
if (typeof v !== 'number' || !Number.isFinite(v)) {
throw new Error(`SONAManager: invalid ${key}`);
}
}
}
+3 -3
View File
@@ -127,7 +127,7 @@ importers:
specifier: 3.1.6
version: 3.1.6
'@claude-flow/neural':
specifier: 3.0.3
specifier: 3.1.0
version: link:../neural
'@claude-flow/plugin-agent-federation':
specifier: 1.0.7
@@ -224,8 +224,8 @@ importers:
specifier: 3.2.2
version: link:../aidefence
'@claude-flow/memory':
specifier: 3.3.3
version: 3.3.3(@types/node@20.19.27)(zod@4.6.7)
specifier: 3.4.0
version: link:../memory
'@metaharness/flywheel':
specifier: ~0.1.10
version: 0.1.13