Commit graph

617 commits

Author SHA1 Message Date
ac7a1f772c chore(release): 7.12.0 2026-02-01 08:25:50 -08:00
490a14af5f refactor: remove deprecated Cortex class (replaced by brain.augmentations API) 2026-02-01 08:22:11 -08:00
7f9d2a70a5 feat: update plugin references from @soulcraft/brainy-cortex to @soulcraft/cortex 2026-02-01 08:22:07 -08:00
b0439fbc26 chore(release): 7.11.0 2026-01-31 12:43:40 -08:00
0f3a88429d feat: add SQ8 vector quantization, lazy loading, and two-phase rerank to HNSW
- SQ8 scalar quantization (8-bit) for 4x vector storage reduction
- Lazy vector loading: evict float32 vectors after graph construction,
  load on-demand from storage via UnifiedCache
- Two-phase search: over-retrieve with SQ8 approximate distances,
  rerank top candidates with exact float32 distances
- Configuration surface: hnsw.quantization and hnsw.vectorStorage in BrainyConfig
- All features disabled by default (zero behavior change for existing users)
- 27 new tests covering quantization accuracy, lazy loading, reranking
- Remove GitHub Actions CI (build locally, cortex CI handles native builds)
2026-01-31 12:41:53 -08:00
e384afcdac chore(release): 7.10.0 2026-01-31 12:02:59 -08:00
1513e297ef feat: wire plugin system with provider resolution, storage factories, and browser deprecation
- Wire PluginRegistry into Brainy init() with provider resolution for distance,
  metadataIndex, graphIndex, embeddings, roaring, msgpack, and storage adapters
- Add setupStorage() factory that resolves storage:* providers from plugins before
  falling back to built-in createStorage()
- Export internals API (setGlobalCache, UnifiedCache, EntityIdMapper, etc.) for
  cortex plugin consumption
- Add plugin.test.ts verifying registration, activation, and provider resolution
- Deprecate browser support (OPFS, Web Workers, WASM embeddings) with warnings
  in preparation for v8.0 server-only release
- FileSystemStorage: fix setupStorage resolution for mmap-filesystem provider
2026-01-31 12:02:13 -08:00
25912b5728 chore: sync package-lock.json after dependency install 2026-01-31 09:30:43 -08:00
cc50ac3776 feat: add plugin system for cortex and storage adapters
Simple plugin architecture with two use cases:
1. Native acceleration (@soulcraft/brainy-cortex) — auto-detected
2. Custom storage adapters (e.g., Redis, DynamoDB)

Plugins implement BrainyPlugin interface with activate/deactivate lifecycle.
Auto-detection tries dynamic import of known packages during init().
Manual registration via brain.use(plugin) before init().

Provider keys: metadataIndex, graphIndex, entityIdMapper, cache, hnsw,
roaring, embeddings, distance, msgpack, storage:<name>
2026-01-31 09:22:32 -08:00
35cb674157 perf: optimize init() and rebuild performance
- Remove detectAndRepairCorruption from init() hot path — was loading all
  metadata chunks sequentially on startup. Now available via checkHealth()
  and repairIndex() methods.
- Short-circuit warmCache on empty workspace — skip 4-6 wasted storage reads.
- Parallelize MetadataIndex.init() and getGraphIndex() via Promise.all().
- Defer metadata writes during rebuild to batch boundaries (every 5000
  entities) instead of flushing per-entity.
- Skip pre-reads for new entities in transactions — saves 2 storage
  round-trips per add() on cloud storage.
2026-01-31 09:14:51 -08:00
cd875294ad fix: eliminate flaky test timeouts and add storage adapters guide
- Switch vitest pool from threads to forks for process isolation
- Disable v8 coverage by default (causes vitest worker RPC timeout)
- Increase hookTimeout 30s to 60s for MetadataIndexManager init under load
- Reduce O(1) space test entity count, replace brittle timing assertions
- Add docs/guides/storage-adapters.md with verified batch config values
2026-01-31 09:11:20 -08:00
92d9420a5c fix: eliminate cloud storage write amplification and rate limiting
brain.add() was generating 26-40 immediate cloud writes per call, causing
HTTP 429 rate limit errors and high latency on GCS/S3/R2/Azure. Three-layer
fix: (1) deferred metadata writes with dirty-marking, (2) MetadataWriteBuffer
for write coalescing, (3) retry/backoff on all cloud storage adapters.
2026-01-31 09:09:36 -08:00
23e1c56ae0 fix: distribute metadata index keys across sub-prefixes to avoid cloud rate limits
All metadata index files were stored under a single _system/ prefix, causing
per-prefix rate limiting on GCS/S3/R2/Azure during cold starts and bulk imports.
Distributes high-volume system keys across 256 sub-prefixes using FNV-1a hash.
Backward-compatible with legacy path fallback.
2026-01-31 09:09:23 -08:00
66d7aa736c fix: invalidate VFS caches recursively on rmdir to prevent orphaned reads
When rmdir({ recursive: true }) deleted a directory tree, child file paths
remained in contentCache and statCache, causing readFile() to return stale
data for deleted files. Adds recursive flag to invalidateCaches() that
evicts all descendant keys by prefix.
2026-01-31 09:09:12 -08:00
88d0c89143 chore(release): 7.9.3 2026-01-28 08:52:52 -08:00
df7d467a4b perf: optimize addMany() with batch embedding for 5-10x speedup
Uses embedBatch() to pre-compute all vectors in a single WASM forward
pass instead of N individual embed() calls. Items that already have
vectors are skipped.

Before: 100 entities = 100 separate WASM calls
After:  100 entities = 1 batched WASM call (micro-batched internally)
2026-01-28 08:50:24 -08:00
f8dd93c93c fix: cancel abandoned highlight() semantic work and harden WASM engine recovery
highlight() used Promise.race with a 10s timeout, but the losing
semantic phase promise continued running 25 WASM micro-batches,
saturating the event loop and degrading all subsequent operations
(find() going from ~200ms to ~10,000ms).

Add AbortController to highlight() so the semantic phase stops
immediately on timeout or error. Pass abort signal through
embedBatch() → EmbeddingManager → micro-batch loop.

Also add defensive hardening:
- CandleEmbeddingEngine: try/catch around WASM calls resets engine
  state on failure so next call triggers re-initialization
- WASMEmbeddingEngine: initialize() now checks underlying Candle
  engine state, not just its own flag, completing the recovery chain
2026-01-27 18:26:37 -08:00
279fccebfe chore(release): 7.9.2 2026-01-27 16:51:48 -08:00
bf71317d21 fix: prevent WASM embedding from blocking event loop during highlight()
embedBatch() with large inputs (e.g. 500 chunks from highlight()) runs
a single synchronous WASM forward pass that blocks the event loop for
200-500ms. Split large batches into micro-batches of 20 with setTimeout(0)
yields between each, keeping max blocking per batch to ~10-30ms.

Also change Cargo.toml opt-level from "z" (size) to 3 (speed) for
~15-20% faster WASM inference. Requires WASM rebuild to take effect.
2026-01-27 16:49:26 -08:00
1ffdfa70ae chore(release): 7.9.1 2026-01-27 15:40:46 -08:00
364360d447 fix: exclude __words__ keyword index from corruption detection and getStats()
The __words__ keyword index stores 50-5000 entries per entity (one per
word), which inflated avg entries/entity well above the corruption
threshold of 100. This caused:

1. validateConsistency() to falsely detect corruption on every startup,
   triggering unnecessary clearAllIndexData() + rebuild() cycles
2. getStats() to log false "Metadata index may be corrupted" warnings
   and report inflated totalEntries/totalIds stats

Both methods now skip __words__ when counting, so stats and health
checks reflect metadata fields only (noun, type, createdAt, etc.).
Keyword search is unaffected since the __words__ field index itself
is not modified.
2026-01-27 15:38:21 -08:00
32dbdcec61 chore(release): 7.9.0 2026-01-27 13:48:43 -08:00
3911fa75fd chore: rebuild type embeddings for updated ContentCategory type 2026-01-27 13:48:26 -08:00
ff80b87a0a feat: expand ContentCategory to universal 6-category set for highlight()
Replace document-centric categories (prose/heading/code/label) with a
universal set that works across documents, code, and UI:

- title: headings, identifiers, labels, JSON keys
- annotation: comments, docstrings, captions, alt text
- content: paragraphs, list items, flowing text
- value: string literals, numbers, form values
- code: unparsed code blocks
- structural: keywords, operators, punctuation

Built-in extractors now produce title/content/code. All 6 categories
are available for custom parsers (e.g. tree-sitter).

Also adds inline code detection in Markdown: backtick spans within
prose lines are split into separate code/content segments.
2026-01-27 13:44:58 -08:00
6c27f9f7fd chore(release): 7.8.0 2026-01-27 10:30:38 -08:00
cca1cd8ce2 feat: add structured content extraction and batch embedding optimization to highlight()
Fix highlight() hanging on structured text input by addressing 3 root causes:

1. embedBatch() now uses native WASM batch API (single forward pass instead
   of N individual embed() calls via Promise.all)

2. highlight() auto-detects content type (plain text, rich-text JSON, HTML,
   Markdown) and extracts meaningful text segments. Supports TipTap, Slate.js,
   Lexical, Draft.js, and Quill Delta formats. New contentType hint and
   contentExtractor callback for custom parsers.

3. Semantic matching phase has 10s timeout - falls back to text-only matches
   instead of hanging indefinitely.

Also fixes extractTextContent() array check: uses type-based detection
(typeof data[0] === 'number') instead of length-based (data.length > 10)
so arrays of objects are properly indexed for text search.

New types: ContentType, ContentCategory, ExtractedSegment
New fields: HighlightParams.contentType, HighlightParams.contentExtractor,
            Highlight.contentCategory
2026-01-27 10:27:22 -08:00
2b901974ed chore(release): 7.7.0 2026-01-26 17:25:15 -08:00
a78f3bb0d2 docs: update architecture docs and README for hybrid search 2026-01-26 17:16:49 -08:00
4adba1b254 feat: add match visibility and semantic highlighting to hybrid search
- Add textMatches, textScore, semanticScore, matchSource to search results
- Add highlight() method for zero-config text + semantic highlighting
- Increase word indexing limit to 5000 (handles articles/chapters)
- Optimize findMatchingWords() with O(1) fast path for semantic-only results
- Add production safety limits (500 chunks for highlight)
- Add comprehensive tests for new features (35 tests)
- Update docs with match visibility and highlight() API
2026-01-26 17:16:18 -08:00
b0ea2f3810 chore(release): 7.6.1 2026-01-26 14:22:44 -08:00
f8ef0a0536 docs: add link to hosted API documentation 2026-01-26 14:22:18 -08:00
2ee6a049a6 chore(release): 7.6.0 2026-01-26 13:16:08 -08:00
f0f7acccc5 chore(release): 7.5.4 2026-01-26 13:08:44 -08:00
7883bb1545 chore(release): 7.5.3 2026-01-26 13:02:15 -08:00
1208c6597e chore(release): 7.5.2 2026-01-26 12:52:33 -08:00
20a3a59def chore(release): 7.5.1 2026-01-26 12:49:11 -08:00
58d85b9c91 chore(release): 7.5.0 2026-01-26 12:16:09 -08:00
a94219e720 fix: update() field asymmetry causing index corruption
CRITICAL: Fixed metadata index corruption on update() operations where
removalMetadata only contained custom metadata + type, while entityForIndexing
contained ALL indexed fields. This caused 7 fields to accumulate on every
update, eventually making queries return 0 results.

- Fix removalMetadata to include all indexed fields (src/brainy.ts)
- Add validateIndexConsistency() and getIndexStats() public APIs
- Add auto-corruption detection and repair on startup
- Add getOrAssignSync() for EntityIdMapper persistence
- Add comprehensive regression tests
2026-01-26 12:12:11 -08:00
478c6e6342 chore(release): 7.4.1 2026-01-20 17:38:29 -08:00
2bd4031f9c fix: VFS readdir() no longer returns duplicate entries
- PathResolver.getChildren() now deduplicates by entity ID (v7.4.1)
  This handles duplicate relationship records that can occur when multiple
  Brainy instances create relationships concurrently for the same storage path.

- brain.clear() now invalidates GraphAdjacencyIndex (v7.4.1)
  Prevents stale in-memory index data after clearing storage, which could
  cause relate()'s duplicate check to fail.

Fixes: Workshop bug where readdir('/') returned same directory 13+ times
2026-01-20 17:37:27 -08:00
311f165533 chore(release): 7.4.0 2026-01-20 16:22:12 -08:00
b5bc9000cf feat: Integration Hub for external tool connectivity
- Add native config option: `new Brainy({ integrations: true })`
- OData integration for Excel Power Query and Power BI
- Google Sheets integration with Apps Script
- Server-Sent Events (SSE) for real-time streaming
- Webhooks for push notifications
- Zero-config with sensible defaults
- Full tree-shaking when disabled
2026-01-20 16:21:11 -08:00
24039e8a1a chore(release): 7.3.1 2026-01-16 17:05:10 -08:00
79ae349b60 fix: clear() now properly resets VFS and COW state
Bug: After brain.clear(), VFS operations failed with
"Source entity 00000000-0000-0000-0000-000000000000 not found"

Root causes fixed:
- VFS instance remained in memory pointing to deleted root entity
- FileSystemStorage.clear() set blobStorage=undefined but didn't reinit
- Write-through cache returned stale entity data after clear()

Changes:
- Re-initialize COW (BlobStorage) after storage.clear() in brainy.ts
- Reset and reinitialize VFS following checkout() pattern
- Add clearWriteCache() to BaseStorage, call in Memory/FileSystem adapters
- Add 7 integration tests for VFS clear functionality

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-16 17:04:09 -08:00
1a813c7b86 chore(release): 7.3.0 2026-01-07 12:52:12 -08:00
d938a6bd4f feat: progressive init and readiness API for cloud storage
- Add `initMode` option to all cloud storage adapters (GCS, S3, Azure)
  - 'auto' (default): progressive in cloud, strict locally
  - 'progressive': <200ms cold starts, lazy bucket validation
  - 'strict': blocking validation (current behavior)

- Add cloud environment auto-detection for:
  - Cloud Run (K_SERVICE, K_REVISION)
  - AWS Lambda (AWS_LAMBDA_FUNCTION_NAME)
  - Cloud Functions (FUNCTIONS_TARGET)
  - Azure Functions (AZURE_FUNCTIONS_ENVIRONMENT)

- Add readiness API to Brainy class:
  - `brain.ready`: Promise that resolves when init() completes
  - `brain.isFullyInitialized()`: checks if background tasks done
  - `brain.awaitBackgroundInit()`: waits for background tasks

- Lazy bucket validation on first write (not during init)
- Background count synchronization
- Update AWS/GCP deployment docs with readiness patterns

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 12:51:05 -08:00
19c5e67035 chore(release): 7.2.2 2026-01-07 10:46:59 -08:00
9fbefd4220 test: increase timing threshold for flaky updateMany test 2026-01-07 10:44:59 -08:00
5885de7aac perf: 10-50x faster vector search with batch operations
Performance optimizations for billion-scale deployments:

- Vector search N+1 fixed: batchGet() instead of individual get() calls
  GCS: 10 results now 1×50ms vs 10×50ms = 10x faster

- Static imports: validation functions imported at module load
  Saves 1-5ms per add/update/relate/find operation

- VFS race condition: added _vfsInitialized flag with warning
  Prevents undefined behavior during concurrent init/access

- HNSW rebuild fix: property mismatch (nounType→type)
  Eliminates N+1 metadata fetch during index rebuild

- Removed debug console.log in relate() hot path

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 10:42:17 -08:00
cf06d82520 chore(release): 7.2.1 2026-01-06 18:01:38 -08:00