feat(field-memory): add governed packed attractor routing - #202
Draft
ruvnet wants to merge 1 commit into
Draft
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds the experimental
@metaharness/field-memoryworkspace package: a governed,packed-multihead attractor field for cost-aware agent routing. Verified aggregate
outcomes change future route probabilities without putting predecessor prompts,
solutions, proofs, or tool traces into the context window.
This is deliberately called field memory, not morphic memory. The package
implements experimentally grounded mechanisms—associative attractors, decay,
drift windows, bounded history dependence, and support-gated collective updates—
without making a metaphysical claim.
Why this layout
The discovery swarm reproduced a structural failure in the expanded layout:
when one identical centroid vector is stored per configuration and
retrievalK < configurationCount, ANN selection censors valid reward headsbefore scoring. In eight deterministic synthetic seeds, increasing K from 3 to
4 restored 25.00 percentage points of configuration coverage and added 11.13
success points.
Packing four reward heads behind one centroid:
retrieval unit.
These are mechanism results, not production task-quality claims. Promotion
remains gated on held-out signed trajectory replay.
Public API
createFieldMemory({ storage, verifier, identityHashKey, config, clock? })exposes:
update(outcome)— verifies and atomically admits a bounded aggregate update;choose(query)— retrieves packed centroids and returns a cost-aware route;compact({ now })— deterministic, explicit maintenance;exportState()/exportStateJson()— bounded authenticated snapshots;importState(state, { mode: 'replace' })— privileged atomic restore.The package exposes no episode list, prompt retrieval, solution reconstruction,
or proof-recovery API.
Implementation details
Packed field and temporal adaptation
heads behind it.
buckets.
expired high-similarity row cannot censor an active row.
accumulate over time.
Routing policy
cost penalty.
hysteresisMargindefaults to zero.configured margin and the old/new query embeddings clear the semantic
continuity threshold.
await,preventing verifier/compaction TOCTOU mutation.
Governance and privacy boundary
principal/domain identities used for accounting.
idempotency identifiers with a required 32+ byte deployment key.
aggregate budgets bound every accepted contribution.
uses the authenticated observation time.
minimumSupportremain outside the searchable centroid and cannotmove an already eligible centroid.
The support gate is routing quarantine, not a confidentiality guarantee.
An authorized state export contains aggregates, and a singleton aggregate can
equal the original observation. Principal/domain caps are per centroid and do
not provide fleet-global Sybil resistance; verifier-side admission, global rate
limits, and centroid-creation policy remain required.
State safety
metaharness.field-memory/v1.fingerprint; wrong-key restore fails closed.
bucket IDs, bounded cardinalities, aggregate/cap consistency, and derived
centroid verification.
its own importer cannot restore.
reversible only through an adapter with atomic replacement.
importState()is admin-only. Deployments must use a unique key per logicalfield and enforce an external monotonic snapshot version/epoch to prevent
cross-field substitution under key reuse or rollback to an older valid HMAC.
Storage and concurrency contract
FieldStorageAdapter.atomicMutate()is a globally serialized read/modify/writeprimitive. This makes idempotency, influence budgets, aggregate budgets, and
cardinality limits survive two
FieldMemoryinstances sharing one adapter.Adapters fail construction if required mutation methods or writer scope are
missing.
writerScope: 'process'is explicitly single-process; multi-processdeployments require a distributed transaction/lock.
The dependency-free in-memory adapter is the deterministic reference oracle.
The RuVector seam is duck-typed and adds no mandatory native dependency.
RuVector dependency and compatibility
The v0.1 adapter intentionally supports only the canonical cosine-distance
contract (
similarity = 1 - distance). It rejects Euclidean, dot-product, andcaller-defined score semantics.
The adapter requires the corrected contract from
RuVector PR #831 (or a later
coordinated release):
getIndexInfo().configurationVerified === true, backed by the nativeeffective-options getter rather than requested wrapper options;
indexType === 'flat';mutationMode === 'in-place';cosinemetric, and normalized absolute storageidentity.
Searchable replacements use explicit-ID in-place upsert. Search requires native
metadata schema/revision to match the authoritative registry revision, turning
a partial native/registry mutation into safe unavailability instead of pairing
a new vector with old aggregates. Revision tags are a consistency check, not a
MAC; storage-writer compromise remains a trusted-boundary failure.
Published
ruvector@0.2.41is rejected because it cannot prove the effectiveconfiguration through
getIndexInfo(). This is intentional. Repeated mutableHNSW replacement was observed to become unsearchable even while
len() === 1,and versioned IDs only delayed the failure. A direct flat-core test remained
searchable through 100 replacements, but final wrapper integration must be run
in CI against the new native effective-options build—not the transitional
sidecar wrapper or published core 0.1.32.
Draft release gate: do not enable the RuVector adapter in production until
the coordinated platform binaries and
@ruvector/corerelease containing thenative
getOptions()getter pass an actual-native, non-proxy integration smoke.Production RuVector use also requires a durable
RuVectorRecordRegistrywith aglobal
withLock()and exact O(1)count(). The exported in-memory registry isprocess-local and ephemeral. State import remains disabled unless the deployment
supplies an atomic index+registry replacement transaction.
Performance implications
reduction).
pruning/rebuilding is O(H * B * D) in the active centroid.
O(C * H * B * D) maintenance before ANN, then O(K * H * B * D) scoring.
head-buckets and performs up to 15,872 * D component aggregations, plus ANN
and the maintenance pass.
scalars.
routing state rather than adding predecessor tokens to each prompt.
The O(C * H * B * D) pre-search maintenance and global transaction are
correctness-first v0.1 choices and do not substantiate a
10,000-agent/100,000-centroid fleet-scale claim. Benchmark and/or replace them
with expiry-aware indexing and a durable transactional registry before that
scale.
Tests
Package tests: 41/41 passed. Publish-order tests: 6/6 passed. Combined
focused run: 47/47 passed twice, with byte-identical deterministic export.
Coverage includes:
accounting, and principal-scoped idempotency;
principal activation, choice, export/import, zero/oversized aggregate import
rejection, and opposing-direction cancellation quarantine;
round-trip, malformed/duplicate/over-cap hostile states;
insertion orders;
native/registry revision mismatch, insert rollback, and ambiguous-delete
rollback;
Commands run:
Published compatibility smoke:
The root ordered build and npm pack should remain CI/reviewer gates because the
execution sandbox rejected npm subprocess spawning. The package itself was
compiled directly, the scripts pass
node --check, the exact settled upstreamduck type compiles, and the curated publish-order unit test passes.
Security assessment
Assessment scope:
packages/field-memory, public API inputs, verifier boundary,snapshot parser/authentication, storage transactions, native RuVector boundary,
and release dependencies.
@claude-flow/cli@3.25.6.99c45988f9d5b500e81445e46dc5ec4814711494143d5f1ce1599e3b0a64f670.2026-08-16T00:18:52Z.threat model is documented in
packages/field-memory/SECURITY.md.npm audit --omit=dev --json: 0 total (0 critical/high/moderate/low).npm audit: 1 critical, 4 high, 3 moderate, all outside theproduction tree. Signals are the existing workspace test/tool chain
(
vitest/vite/vite-node/esbuild/nanoid/postcss) plus unrelatedjs-yaml; the new package has no runtime dependencies.both
packages/field-memoryand unchangedpackages/routerwith the exactsame package list. This confirms they are workspace dev-dependency signals,
not new reachable field-memory or router code findings.
No scanner finding is being suppressed as a runtime issue. The dev-tool
advisories remain repository-level dependency maintenance and should be handled
separately rather than expanding this feature PR to a Vitest major upgrade.
Documentation and release wiring
Rollout and acceptance
Keep the package experimental until all of the following pass on held-out,
signed MetaHarness trajectories at equal inference/token budgets:
Files changed (19 paths)
New package (13 source/docs/config files, 3,876 lines before generated
dist):packages/field-memory/{package.json,tsconfig.json,README.md,SECURITY.md,LICENSE}packages/field-memory/src/{index,types,policy,util,storage,field-memory,ruvector-storage}.tspackages/field-memory/__tests__/field-memory.test.tsRepository wiring:
CHANGELOG.mdREADME.mdpackage-lock.jsonscripts/build-ordered.mjsscripts/publish-workspace.mjs__tests__/publish-workspace.test.ts