Commit graph

746 commits

Author SHA1 Message Date
7493d8e33f fix: code-point string collation in LSM SSTable, COW trees/refs, sorted queries
Replaces localeCompare / raw relational operators with compareCodePoints (UTF-8
byte order) in the remaining persisted or native-facing comparison sites:
- SSTable sourceId sort + zone-map range check + binary search (graph LSM)
- COW TreeObject + RefManager name sorts (reproducible content hashes and ref
  listings across environments)
- getSortedIdsForFilter (numeric-aware; code-point for strings) so the JS sort
  fallback matches the native column store exactly

Deterministic across OS/Node/ICU and byte-identical to the native engine. No
migration: COW serialize/deserialize preserve stored order, so existing trees
keep their hashes; only new writes adopt code-point order.
2026-05-27 11:53:26 -07:00
298b572671 feat(storage): add raw binary-blob primitive to every storage adapter
Introduce a first-class binary-blob storage primitive on the StorageAdapter
contract and implement it across all storage backends. This stores opaque byte
payloads verbatim instead of base64-in-JSON, eliminating the ~33% inflation and
full-materialization cost of the JSON envelope. It unblocks zero-copy,
mmap-able column-store segments and batch vector I/O at billion scale.

New methods (declared abstract on BaseStorageAdapter, the class that implements
StorageAdapter, and added to the StorageAdapter interface):

  saveBinaryBlob(key, data)    raw write, atomic on real filesystems
  loadBinaryBlob(key)          exact bytes, or null if absent
  deleteBinaryBlob(key)        idempotent (missing is ignored)
  getBinaryBlobPath(key)       real local fs path where one exists, else null

Shared key -> location convention across every adapter: the key's
"/"-separated segments nest under a `_blobs/` prefix and are suffixed with
`.bin`, e.g. "graph-lsm/source/sstable-123" ->
"<root>/_blobs/graph-lsm/source/sstable-123.bin". Blobs are not branch-scoped
(COW): they are immutable producer-managed segments.

Per-adapter behavior:
- FileSystemStorage: writes under <rootDir>/_blobs via tmp+rename; returns the
  real on-disk path so native code can mmap it directly. Path convention matches
  the existing MmapFileSystemStorage subclass byte-for-byte.
- S3CompatibleStorage / R2Storage / GcsStorage / AzureBlobStorage: put/get/delete
  raw octet-stream objects; getBinaryBlobPath returns null (remote stores have no
  local path).
- MemoryStorage: defensive-copied Map<string, Buffer>; null path; cleared on
  clear().
- OPFSStorage: stores raw bytes in the OPFS tree; null path.
- HistoricalStorageAdapter: read-only — save/delete throw; load resolves the
  blob from the historical commit tree; null path.

Tests: tests/unit/storage/binaryBlob.test.ts exercises save/load round-trip
(byte-identical, incl. non-UTF8 bytes), overwrite, delete-then-load, load-missing,
and getBinaryBlobPath behavior for all eight adapters. Cloud adapters run against
in-memory client fakes that drive the real adapter code; OPFS runs against an
in-memory FileSystem Access API mock; the historical adapter commits a blob into
a real COW tree. 59 new tests; full unit suite (1398 tests) green.
2026-05-27 11:50:04 -07:00
547721ae14 fix: deterministic code-point string collation for column store + aggregation
Replace localeCompare (default-locale, non-deterministic across environments —
unsafe for a persisted sorted index) with UTF-8 byte / code-point order via a
shared compareCodePoints() helper. String ordering is now deterministic and
byte-identical to the native column store / aggregation sort, so results are the
same with or without the native accelerator. Covers the aggregate orderBy sort
and all 5 column-store comparison sites (tail buffer, merge sort, binary search).
Adds compareCodePoints unit tests.
2026-05-26 17:35:18 -07:00
fe4f5df8c9 feat: exact percentile and distinctCount aggregation ops
Add 'percentile' (with a 'p' fraction in [0,1]) and 'distinctCount' to the
aggregation engine. Both are exact, computed from a per-metric value multiset
(MetricState.valueCounts) maintained incrementally and delete-safe; percentile
uses numpy-linear interpolation. The multiset is JSON-serializable so results
survive persistence. 35 aggregation unit tests pass.
2026-05-26 16:18:47 -07:00
bca3736f4c chore(release): 7.24.0 2026-05-26 14:21:04 -07:00
c2e21b7b3c feat: array-unnest groupBy for aggregates + batch-embed entity extraction
- groupBy now supports { field, unnest: true }: an entity contributes once per
  distinct element of an array field (tag frequency / faceted counts). Duplicate
  elements on one entity count once; an empty/missing array joins no group. The
  incremental add/update/delete paths fan out across the unnested groups.
- extractEntities/extractConcepts batch-embed the unique candidate spans in one
  embedBatch call instead of one embed() per candidate (N sequential model calls);
  falls back to per-candidate embedding if the batch fails. No behavior change.
2026-05-26 14:20:40 -07:00
2591001bd0 chore(release): 7.23.0 2026-05-26 13:56:09 -07:00
1a98e4276a feat: queryAggregate() + HAVING, plus aggregate backfill, traversal depth/via, extraction typing (BR-ADV-FEATURES-BUN)
New report APIs:
- brain.queryAggregate(name, params) returns the clean AggregateResult[] shape
  ({ groupKey, metrics, count }) directly, instead of the search-Result wrapper that
  find({ aggregate }) returns.
- HAVING: find({ aggregate, having }) and queryAggregate filter groups by computed
  metric values (e.g. revenue > 1000), complementing where (which filters group keys).
  Evaluated per group: O(groups), independent of entity count.

Fixes (all reproducible on Node; surfaced under Cortex+Bun by Memory):
- Aggregate backfill-on-define: defining an aggregate over a store that already holds
  matching entities returned []. It now backfills from existing entities on first query
  (storage-agnostic via getNouns), so it works under durable backends that reopen
  pre-populated. groupBy:['noun'] resolves to the entity type; find({ aggregate }) rows
  expose groupKey/metrics/count at the top level.
- Multi-hop find({ connected: { depth, via } }) honors depth and via at every hop
  (was 1-hop only, with verb filtering applied to hop 1 only); BFS bounded by limit.
- extractEntities no longer bleeds a neighbour's type indicator across candidates; each
  candidate is typed by its own span. Also fixes the "Dr." title pattern.

Adds real-embedding regression tests; full unit suite green.
2026-05-26 13:55:43 -07:00
513186d951 chore(release): create annotated tag so --follow-tags pushes it
A lightweight tag is skipped by 'git push --follow-tags', so v$VERSION stayed
local-only and 'gh release create' failed at the end of the release. Use an
annotated tag (-a) so it pushes with the release commit.
2026-05-26 11:44:14 -07:00
16f39f2b73 chore(release): 7.22.1 2026-05-26 11:33:34 -07:00
0a9d1d9a17 fix: extraction, multi-hop traversal, and aggregate result shape (BR-ADV-FEATURES-BUN)
Three advanced-API correctness fixes, all reproducible on Node (not Bun-specific):

- Entity/concept extraction returned []. SmartExtractor combined agreeing signals
  with a weighted sum compared against an absolute 0.60 gate, so a confident
  low-weight signal lost selection to a mediocre high-weight one that then failed
  the gate, dropping the whole result. Select and gate on a normalized weighted
  average instead. The public `confidence` option now controls the threshold (was
  a dead hardcoded 0.60), and the embedding-signal timeout is raised 100ms -> 2000ms
  so the neural signal is not silently dropped on slower runtimes.

- Multi-hop find({ connected }) returned only the 1-hop neighbour. executeGraphSearch
  ignored depth/via; it now delegates to the depth-aware neighbors() BFS.

- find({ aggregate }) hid groupKey/metrics/count under .metadata, so callers
  expecting AggregateResult saw empty rows. Expose those fields at the top level.

Adds real-embedding regression tests in tests/integration/advanced-apis-regression.test.ts.
2026-05-26 11:32:46 -07:00
07754d135a docs: storage-adapter inheritance contract + correct the hasStorageMethod story
Per the Cortex team's audit, the BR-CX-INTERFACE-GAP boot crash was a
build/install artifact (stale node_modules, lockfile drift, Docker cache,
bundler quirks), not a plugin-bundles-brainy version-skew issue. Cortex's
MmapFileSystemStorage extends FileSystemStorage and inherits all 6
multi-process helpers via the prototype chain at runtime; the dynamic
ESM import to @soulcraft/brainy is preserved in cortex's dist.

  - Rewrote the hasStorageMethod() doc comment to credit the real cause.
  - Updated the init-time warning to point operators at the actual fix:
    clean install or container rebuild to refresh node_modules.
  - New docs/concepts/storage-adapters.md documenting the inheritance
    contract: extend FileSystemStorage to inherit the multi-process
    helpers, override supportsMultiProcessLocking() -> true to activate.
    Includes a minimum checklist for adapter authors.
  - New docs/architecture/multiprocess-storage-mixin.md as a future-
    direction note: extracting the 7 methods into a
    MultiProcessSafeStorage interface/mixin is the architecturally clean
    next step, deferred to v8 or until a second multi-process capability
    lands.

No behavior changes. Ships with the next release.
2026-05-15 13:20:18 -07:00
505651d70f chore(release): 7.22.0 2026-05-15 12:31:46 -07:00
70263113ad fix: find()/stats() correctness + Cortex compat (BR-FIND-WHERE-ZERO, BR-DEFENSIVE-INTERFACE)
Two production correctness defects fixed together so consumers can land
one upgrade.

BR-FIND-WHERE-ZERO — find() returned [] and stats() reported 0 entities
for any workspace whose data was written after the 7.20.0 column-store
refactor. Root cause: getStats() and the getIds() fallback still read
from the deleted sparse-index path. Separately, BaseStorage.getNounType()
was hardcoded to return 'thing', poisoning type-statistics.json with
every noun attributed to that bucket.

  - MetadataIndex.getStats() reads from ColumnStore + idMapper.
  - MetadataIndex.getIdsFromChunks() throws BrainyError(FIELD_NOT_INDEXED)
    when neither store has the field. getIdsForFilter() catches per
    clause, logs once, returns [].
  - BaseStorage.nounTypeByIdCache populated in saveNounMetadata_internal
    and consumed in saveNoun_internal. flushCounts() now persists the
    Uint32Array counters too, so readers see fresh per-type counts.
  - Self-heal at init: loadTypeStatistics() auto-rebuilds when the
    poisoned signature is detected. rebuildTypeCounts() is now public for
    use from `brainy inspect repair`.
  - Dead state removed: dirtyChunks, dirtySparseIndices,
    flushDirtyMetadata().

BR-DEFENSIVE-INTERFACE — 7.21.0 called supportsMultiProcessLocking()
unconditionally, crashing on older Cortex storage adapters that predate
the method. New hasStorageMethod(name) helper gates every new-method
call site. Older adapter triggers a one-line warning at init pointing
at the recommended plugin version.

Tests:
  - new tests/integration/find-where-zero.test.ts (7 cases)
  - new tests/integration/cortex-compat.test.ts (5 cases)
  - multi-process-safety.test.ts updated to enforce correct counts
  - 1329/1329 unit + 24/24 new integration tests passing
2026-05-15 12:31:28 -07:00
79f58cb87b chore(release): 7.21.0 2026-05-15 11:26:30 -07:00
a8fcc3dfbc chore: gitignore Claude Code harness scheduled-tasks lockfile 2026-05-15 11:26:11 -07:00
4fcdc0fef3 feat: multi-process safety + read-only inspector mode
Filesystem storage now enforces single-writer, many-reader semantics.
A second writer on the same data directory throws at init time with the
holder's PID, hostname, and heartbeat — replacing the previous silent
stale-reads failure mode.

- New: `Brainy.openReadOnly()` — coexists with a live writer, every
  mutation throws clearly.
- New: writer lock at `<rootDir>/locks/_writer.lock` with 10s heartbeat
  and stale-detection (PID liveness + heartbeat freshness).
- New: cross-process flush-request RPC (filesystem-based, no signals)
  so inspectors can force fresh state on demand.
- New: `brain.stats()`, `brain.explain(findParams)`, `brain.health()`
  for operator-facing introspection.
- New: `brainy inspect` CLI with 13 subcommands (stats, find, get,
  relations, explain, health, sample, fields, dump, watch, backup,
  repair, diff), all read-only by default.
- Same-PID re-opens allowed with a warning (preserves test "simulate
  restart" patterns).
- Storage instances passed directly via `storage: new MemoryStorage()`
  are now honoured instead of silently falling through to the
  filesystem auto-detect path.

Brainy + Cortex compose under this model — the lock covers both because
they share `rootDir`, Cortex segments are immutable mmap files, and
MANIFEST updates use atomic-rename.
2026-05-15 11:25:05 -07:00
1bc6a430c7 chore(release): 7.20.0 2026-04-10 11:42:39 -07:00
11be039ae8 refactor: delete dead sparse index write path
Column store handles all writes and primary queries. Sparse index write
methods are unreachable:

Deleted: addToChunkedIndex (~103 lines), removeFromChunkedIndex (~37 lines),
splitChunkDeferred (~82 lines), getValueChunkFilename + makeSafeFilename
(~20 lines). Total: ~240 lines of dead write-path code.

Sparse index read methods kept as migration fallback for existing workspaces.
Will be deleted once lazy migration (buildFromStorage) ships.
2026-04-10 11:32:34 -07:00
46583f2d9b feat: unified column store for filtering + sorting at billion scale
Adds a per-field sorted column store (Lucene doc values + roaring bitmap
architecture) that replaces the MetadataIndex sparse index internals for
both filtering and sorting. One system for all field types with exact
precision — no bucketing, no per-entity storage reads.

Column store: binary .cidx segment format, in-memory tail buffers,
LSM-style compaction, k-way merge sort, multi-value support (__words__).
All queries (filter, range, sort, filtered sort) route through the column
store when data is available, falling back to sparse index otherwise.

Key unlocks:
- find({ orderBy: 'createdAt' }) works WITHOUT a filter (previously threw)
- find({ orderBy: 'metadata.price' }) works for custom numeric fields
- Exact timestamp precision (no 1-minute bucketing)
- O(K log S) sort independent of total entity count

New files: src/indexes/columnStore/ (types, format, tail buffer, cursor,
manifest, coordinator — ~700 lines). 101 new unit tests covering binary
format round-trips, CRC validation, sort, filter, range, deletion,
multi-segment merge, persistence, and multi-value (words) fields.

Deleted: metadataIndex-automatic-bucketing.test.ts (bucketing behavior
eliminated by exact-precision column store). Sparse index write path
removed from addToIndex/removeFromIndex. Sparse index legacy code still
present as dead code pending cleanup in next commit.
2026-04-10 11:22:19 -07:00
634ddfb2bb chore(release): 7.19.19 2026-04-09 16:43:57 -07:00
108e2bcab4 refactor: migrate aggregation + neural field reads to resolveEntityField
Preventive cleanup of sites that previously used dual-lookup patterns
(metadata[field] ?? entity[field]) or hardcoded timestamp if-chains
to read fields off HNSWNounWithMetadata. These worked today but were
fragile — the same failure mode that caused the orderBy sort bug
would have recurred the next time someone reordered or dropped a
lookup.

- AggregationIndex.computeGroupKey + getNumericField now route all
  dimension and metric field lookups through resolveEntityField.
- improvedNeuralAPI._getItemsByTimeWindow + _clusterItemsByField
  use resolveEntityField as the primary path, with item.data as a
  legacy producer fallback. The type/nounType legacy branch is
  preserved as-is since it handles storage format compatibility
  rather than shape contract drift.

No behavior change for correct inputs. All aggregation and orderby
regression tests pass unchanged.
2026-04-09 16:40:55 -07:00
9855f431f7 chore(release): 7.19.18 2026-04-09 16:29:29 -07:00
beefacbca9 feat: export resolveEntityField + STANDARD_ENTITY_FIELDS from internals
Cortex and other first-party plugins need a shared contract for reading
fields off HNSWNounWithMetadata. Exporting from /internals keeps a single
source of truth and prevents the shape contract from drifting between
packages.
2026-04-09 16:28:54 -07:00
75141ef400 chore(release): 7.19.17 2026-04-09 16:27:10 -07:00
be6c4dc182 fix: correct orderBy sort for timestamp fields via centralized field resolver
Muse reported that find({ orderBy: 'createdAt' }) silently returned the
wrong order: getFieldValueForEntity read noun.metadata[field] for
timestamp fields, but getNoun() destructures standard fields to the top
level, so the read always returned undefined and the sort collapsed to
insertion order.

The fix introduces a single source of truth for reading fields off an
entity. STANDARD_ENTITY_FIELDS + resolveEntityField() in coreTypes.ts
encode the "standard fields top-level, custom fields nested" contract
in one place. getFieldValueForEntity now uses the helper and routes
through a named BUCKETED_INDEX_FIELDS set instead of a hardcoded
timestamp if-chain — filtered sort on createdAt/updatedAt now works.

Unfiltered orderBy is explicitly rejected with a clear error pointing
callers at the right pattern. A scalable, unfiltered-sort-capable
time-ordered segment index is tracked as a separate follow-up.
2026-04-09 16:26:38 -07:00
086d90d01c chore(release): 7.19.16 2026-03-24 13:12:40 -07:00
9d035aceee fix: metadata index corruption after restart — 6-point integrity fix
Root cause: metadata index failed to reconstruct after deploy restart
because the field registry file (__metadata_field_registry__) was lost
during an interrupted flush. init() silently assumed the workspace was
empty even though 5000+ entities existed on disk.

Fix 1 (root cause): init() now probes storage for entities when field
registry is missing. If entities exist, triggers rebuild instead of
silently skipping. Never trusts a missing registry as "empty."

Fix 2 (safety net): after rebuildIndexesIfNeeded(), verifies metadata
index entry count matches storage entity count. Forces second rebuild
if mismatch detected.

Fix 3 (prevention): flush() now always saves field registry and
EntityIdMapper, even when no dirty fields exist. These tiny files are
the critical link that init() needs to discover persisted indices.

Fix 5 (safe rebuild): rebuild() no longer deletes the field registry
file before rewriting. If rebuild fails partway, the registry survives
for the next init() to discover and re-trigger rebuild.

Fix 6 (collision guard): EntityIdMapper init() warns when mapper file
is missing but entities exist on disk, preventing silent ID collisions
from nextId starting at 1.
2026-03-24 12:57:11 -07:00
e6c5eb6d8b chore(release): 7.19.15 2026-03-23 15:46:19 -07:00
b58ea02de1 fix: commit() now flushes and captures state by default
commit() previously defaulted captureState to false, creating commits
with NULL_HASH tree that could never be restored from. Now:

- flush() runs first to persist deferred HNSW nodes, count batches,
  and index state before snapshotting
- captureState defaults to true, creating real content-addressed trees
- captureState: false still available for lightweight metadata-only commits
2026-03-23 15:45:46 -07:00
74bc61a89c chore(release): 7.19.14 2026-03-22 16:53:26 -07:00
54865b3505 feat: add setMaxSize() for dynamic cache resizing
UnifiedCache.setMaxSize() allows runtime resizing of the cache maximum.
When the new limit is smaller than current usage, lowest-value items are
evicted until the cache fits. Used by Cortex's ResourceManager to
rebalance cache vs instance memory as brainy instances are created and
evicted in multi-tenant deployments.

Also adds getMaxSize() for observability.
2026-03-22 16:52:02 -07:00
3dd5ac0d8c chore(release): 7.19.13 2026-03-22 14:56:04 -07:00
60a0f1051f fix: suppress misleading 'Using Q8 WASM' log when Cortex native is active
EmbeddingManager constructor logged 'Using Q8 precision (WASM)' before
plugins had a chance to register a native embedder. Deferred logging to
init() so the startup message reflects the actual embedding engine.
2026-03-22 14:53:48 -07:00
973b6aaa39 perf: defer HNSW persistence during addMany() batch operations
addMany() now temporarily switches the HNSW index to deferred persist
mode during the batch loop. Previously, each add() triggered ~16-20
saveHNSWData calls for modified neighbors (each a read→gzip→atomic-write
cycle). For 450 items this was ~8,100 individual storage writes.

With deferred mode, dirty node IDs are collected in a Set during the
batch and flushed once at the end — deduplicating repeated neighbor
updates. A node modified by insert #3 and again by insert #47 is
written only once.

Also adds setPersistMode() to TypeAwareHNSWIndex, propagating mode
changes to all existing type-specific sub-indexes.
2026-03-22 14:53:11 -07:00
c054c41943 fix: add rootDirectory to BrainyConfig.storage type
The storage config type only exposed { type, options, branch } but plugin
storage factories (e.g. Cortex mmap) read rootDirectory from the top level
of the config object. This caused undefined storage paths when Cortex was
active. The underlying StorageOptions interface already declares
rootDirectory — this aligns BrainyConfig.storage to match.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 09:46:11 -07:00
a862b78585 docs: add RELEASES.md + cross-project coordination section to CLAUDE.md 2026-02-28 10:07:34 -08:00
1b04fa3755 chore(release): 7.19.10 2026-02-24 12:26:03 -08:00
239a4da835 fix: replace require('crypto') with ESM import in SSTable
SSTable.calculateChecksum() used require('crypto') which breaks in ESM
environments and Bun. Replace with top-level import { createHash } from
'node:crypto' — SSTable is Node-only (LSM-tree filesystem storage) so
a direct node:crypto import is appropriate.
2026-02-24 12:25:26 -08:00
027607688f chore(release): 7.19.9 2026-02-23 16:00:32 -08:00
6003e2b1a2 docs: replace ASCII box art with prose in Before/After section
Code blocks with Unicode box-drawing characters render poorly in web
doc viewers — font alignment breaks and the styled container creates
a visual box-in-a-box. Replaced with a bullet list (before) and a
bold statement (after) that render cleanly at any size and theme.
2026-02-23 15:59:59 -08:00
1a9cacd5fc chore(release): 7.19.8 2026-02-23 15:16:41 -08:00
3f16e1755b docs: redesign ELI5 comparison section and add What Can You Build?
Replace flat 15-row table with a Before/After ASCII diagram plus a
capability grid (Search/Graph/Filter/VFS/Branch/Import) with competitors
grouped by category. Add new What Can You Build? section with generic
use cases and Built with Brainy showcase. Tighten header copy.
2026-02-23 15:16:08 -08:00
c376fb9b61 chore(release): 7.19.7 2026-02-23 13:07:46 -08:00
a88962fae7 docs: add plain-language ELI5 overview and link from README
Adds docs/eli5.md — a jargon-free explanation of Brainy and Cortex
using everyday analogies (smart librarian, turbocharger). Targets
non-technical readers who want to understand the project before diving
into the API. Links added at the top of README and in the Documentation
section index.
2026-02-23 13:07:14 -08:00
7518c212ea chore(release): 7.19.6 2026-02-19 17:46:51 -08:00
791cacc6c0 docs: convert code examples to TypeScript
All code examples in installation.md and quick-start.md were tagged
as javascript — converted to typescript throughout.

quick-start.md also gets explicit type annotations:
- reactId/nextId declared as string (return type of brain.add)
- results declared as FindResult[]
- results[0].data and results[0].score shown in console.log example
2026-02-19 17:46:18 -08:00
fae88d0fdd chore(release): 7.19.5 2026-02-19 17:06:33 -08:00
b98bd532d2 chore(release): 7.19.4 2026-02-19 17:05:34 -08:00
33ea5e322a chore(release): 7.19.3 2026-02-19 17:04:37 -08:00