The 3.0 native engine ships as @soulcraft/cor (brainy 8.x <-> cor 3.x are a
version-matched pair); the old @soulcraft/cortex package stays on the 2.x/7.x
line. Public docs and .d.ts-visible comments now name the correct package.
Historical 2.x contract references (e.g. the 2.3.1 read-side fallback) keep
the old name deliberately.
The Phase-0 CI was red on all three runtimes: `src/embeddings/wasm/pkg/` (the
wasm-pack output the dynamic `import('./pkg/candle_embeddings.js')` resolves) was
gitignored + untracked, so tsc failed to resolve it on a fresh clone (TS2307), and
the Bun job ran test:bun without building dist first.
Fixes:
- Track the 3.1 MB prebuilt pkg (candle_embeddings.js/.d.ts + _bg.wasm/.d.ts). It
ships in the npm tarball anyway; versioning it lets consumers + CI build without
a Rust/wasm-pack toolchain and makes the shipped artifact reproducible (closes
the "publish ships whatever the maintainer last built" supply-chain gap). The
top-level .gitignore intended this (`!*.wasm` etc.) but excluded the whole dir,
so the re-includes were dead, and a nested wasm-pack `.gitignore *` also masked
it — force-added past both.
- CI Bun job: `npm run build` before `test:bun` (it imports the built dist/).
Verified against a tracked-files-only tree (fresh-clone sim): typecheck 0, build 0,
test:bun 8/8.
Pre-GA dead-code sweep. A deterministic import-reachability walk from the
package's real entry points (the exports map, the CLI bin, the conversation
surface) found 34 source modules that nothing reachable imports — they
compile and ship as dist output that no consumer or internal path can ever
reach. All were superseded duplicates, abandoned parallel implementations,
or built-but-never-wired features:
- superseded duplicates of live modules: an older "unified" entry, a
standalone neural-import variant, a static NLP processor + its matcher,
a parallel API-types module, a duplicate progress-types module
- an abandoned import path (orchestrator + entity deduplicator + barrels)
left behind when ingestion moved to the coordinator
- unwired feature modules (instance pool, import presets, cached
embeddings, relationship-confidence scorer) reachable only from tests
- dead leaf utilities (write buffer, deleted-items index, bounded
registry, two crypto shims, a cache manager, a structured logger, a
stale v5 type-migration helper, a browser-only FS type shim) and
several dead re-export barrels
- a CLI catalog command wired into no command
Also removed two tests that only exercised deleted modules, repointed two
VFS tests off a deleted barrel onto the implementation module, and deleted
one example that demoed removed features.
Verified: clean build (both tsc passes), unit 1505 + integration 607 green,
and a re-run of the reachability walk reports zero remaining orphans.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The integration suite loaded the real WASM model for every test, so a full run
took ~hours and reliably aborted (vitest reporter timeout) — which is why it was
never gated and silently rotted. Brainy already separates the embedder from all
other logic, so running integration with a deterministic embedder keeps every
code path real (HNSW build+search, graph traversal, metadata filtering,
transactions, storage/sharding, VFS, aggregation, import) while making the suite
complete in ~2 min on ANY machine — no GPU, no 16 GB requirement.
- Add isDeterministicEmbedMode() — a single source of truth for the test-embedder
switch (BRAINY_DETERMINISTIC_EMBEDDINGS, plus the legacy BRAINY_UNIT_TEST alias),
used by EmbeddingManager (init/embed/embedBatch) and brainy's eager-init guard.
- setup-integration.ts opts into it: Tier 1 = functional end-to-end. Real-model
semantic quality + the real embedding pipeline move to a Tier-2 suite.
Full integration now runs 482 passing / 583 in ~2 min (was un-completable). The
remaining failures are pre-existing test rot, fixed next. Unit 1414 green.
Brainy 8.0 is server-only. This commit takes the consequences seriously and
removes everything that was only there to keep browser/cloud/threading
surfaces alive.
Browser support drop (per the @deprecated notes in environment.ts):
- isBrowser, isWebWorker, areWebWorkersAvailable, navigator.deviceMemory
paths, window/document/self.onmessage code.
- browser console.log in unified.ts, the 'browser' branch in
autoConfiguration.ts (env enum + scaleUp cases), 'browser-cache' model
path, MCP service environment value.
- package.json browser field.
- src/worker.ts (Web Worker entrypoint) deleted.
Cloud SDK removal (the four adapters were dropped in Phase 7; the SDKs
were the lingering tax):
- @aws-sdk/client-s3, @azure/identity, @azure/storage-blob, and
@google-cloud/storage removed from package.json. Lockfile drops the
entire @aws/@azure/@google-cloud/@smithy transitive tree.
- EnhancedS3Clear class deleted from enhancedClearOperations.ts (the
only @aws-sdk/client-s3 consumer; the dynamic import sites went with
it). EnhancedFileSystemClear stays.
- src/utils/adaptiveSocketManager.ts deleted entirely (474 LOC of HTTPS
socket-pool management for the dropped cloud HTTP handler).
performanceMonitor.ts no longer reports a socketConfig; socket
utilization is fixed at 0.
Dead threading subsystem:
- executeInThread was imported by distance.ts and hnswIndex.ts but
never called. It was scaffolding for a future "off-main-thread
distance batch" optimization that never shipped.
- src/utils/workerUtils.ts deleted (Web Worker code path + an
unreachable Node Worker Threads code path).
- environment.ts loses isThreadingAvailable, isThreadingAvailableAsync,
areWorkerThreadsAvailable, areWorkerThreadsAvailableSync. All exports
purged from index.ts and unified.ts.
- autoConfiguration.ts drops AutoConfigResult.threadingAvailable.
Legacy plugin/augmentation pipeline:
- src/pipeline.ts deleted. The whole file was a no-op stub for
backwards compat — Pipeline class had no methods, no lifecycle hooks,
no before/after callbacks. AugmentationPipeline, augmentationPipeline,
createPipeline, createStreamingPipeline, StreamlinedPipelineOptions,
StreamlinedPipelineResult, StreamlinedExecutionMode were all aliases
for the same stub.
- src/mcp/mcpAugmentationToolset.ts deleted. executePipeline always
threw "deprecated", isValidAugmentationType always returned false,
getAvailableTools always returned []. Dead surface.
- BrainyMCPService no longer instantiates a toolset. TOOL_EXECUTION
requests now return the standard UNSUPPORTED_REQUEST_TYPE error.
'availableTools' system-info returns [] (was the same in practice).
Net: 22 files changed, ~6400 LOC deleted (including legacy code +
mechanical lockfile churn). Build clean, 1409/1409 tests pass.
PHASE A — every @deprecated marker resolved (~25 removed)
src/coreTypes.ts
- GraphVerb: dropped the "@deprecated Will be replaced by HNSWVerbWithMetadata"
note. GraphVerb IS the canonical contract — every public API path speaks
it. Removed the `source` and `target` legacy alias fields (renamed `from`
/ `to` callers years ago; no consumers remain).
- StorageAdapter: dropped the "@deprecated Use getNouns() with filter" notes
from `getNounsByNounType`, `getVerbsBySource`, `getVerbsByTarget`,
`getVerbsByType`. They were never deprecated in spirit — they're useful
non-paginated convenience wrappers over the paginated `getNouns()` /
`getVerbs()` surface. Refreshed JSDoc to explain the role.
src/types/graphTypes.ts
- Mirrored the GraphVerb cleanup: dropped `source` + `target` legacy aliases.
sourceId + targetId are the canonical fields.
src/import/ImportCoordinator.ts
- Deleted the entire DeprecatedImportOptions interface block (130 LOC). It
was a v3 → v4 migration tool using the `?: never` trick to force
compile errors on dropped options. Five major versions in, the
forced-error gate is no longer pulling its weight.
src/triple/TripleIntelligence.ts
- Deleted `TripleIntelligenceEngine = any` alias. No consumers; superseded
by `TripleIntelligenceSystem`.
src/storage/cow/binaryDataCodec.ts
- Deleted `wrapBinaryData()`. The COW dispatch layer in `baseStorage.ts`
routes by key-prefix convention; the old guess-by-JSON-parse codec was
fragile (compressed bytes can accidentally parse as JSON) and unused.
src/storage/baseStorage.ts
- Refreshed JSDoc on `convertHNSWVerbToGraphVerb()` — the method is alive
and used internally; the deprecation note was stale.
src/embeddings/wasm/AssetLoader.ts → DELETED
- File was @deprecated since model weights moved into the Candle WASM
bundle. No consumers. Removed from `embeddings/wasm/index.ts` exports.
src/embeddings/wasm/types.ts
- Dropped @deprecated tags on `TokenizerConfig` + `TokenizedInput` — still
used by `WordPieceTokenizer` (auxiliary tokenization). Deleted
`InferenceConfig` (truly dead). Updated `embeddings/wasm/index.ts`
exports.
src/utils/metadataIndex.ts
- Deleted `getIdsForCriteria()` — pure alias for `getIdsForFilter()`, no
consumers.
src/interfaces/IIndex.ts
- Removed RebuildOptions.lazy (deprecated and unused; lazy mode is auto-
selected by available-memory detection).
src/hnsw/hnswIndex.ts
- Removed `getNouns()` (returned a full Map; deprecated in favor of
pagination years ago and no consumers in src/ or tests/).
PHASE B — cacheManager dead StorageType branches
src/storage/cacheManager.ts
- Collapsed the `isRemoteStorage` flag and its 15 dead conditional branches
spanning calculateOptimalCacheSize() and calculateOptimalBatchSize().
After dropping cloud adapters in step 7, `coldStorageType` is never S3
or REMOTE_API; the branches were dead. Cache sizing and batch sizing now
honor the filesystem-only reality with simpler heuristics.
- Collapsed `detectWarmStorageType()` + `detectColdStorageType()` from
~40 LOC of environment-+-availability branching to 2-line returns of
`StorageType.FILESYSTEM`. Brainy 8.0 ships filesystem + memory only.
NOT YET — Phases C-G in follow-up commits
C: storageAutoConfig.ts + zeroConfig + extensibleConfig + sharedConfigManager
D: TODO/FIXME sweep across src/
E: skipped tests + the parallel-test race condition
F: docs deep clean (BATCHING, augmentations, READMEs)
G: browser support drop (the last 2 @deprecated)
VERIFICATION
- npx tsc --noEmit: clean
- npm test: 1408 / 1409 (same pre-existing race-condition outstanding)
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.
Add a write-time incremental aggregation engine that maintains running
totals on every add/update/delete for O(1) read performance. Integrates
into brain.find({ aggregate }) for a unified query API.
Core features:
- AggregationIndex with defineAggregate()/removeAggregate() API
- Five aggregation operations: SUM, COUNT, AVG, MIN, MAX
- GROUP BY with multiple dimensions including time windows
- Time window bucketing: hour, day, week, month, quarter, year, custom
- Materialization of results as NounType.Measurement entities
- Debounced persistence of definitions and state to storage
- Definition change detection via FNV-1a hashing with auto-rebuild
- Infinite loop prevention for materialized entities
- 'aggregation' plugin provider key for native acceleration
- Lazy initialization (created on first defineAggregate() call)
- 73 tests (unit + integration) covering all functionality
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- 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
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
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.
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.
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
In bun --compile binaries, import.meta.url resolves to virtual paths.
Added fallback strategies to find model assets:
1. Pre-resolved paths (Bun runtime)
2. ./node_modules/@soulcraft/brainy/assets/ (npm installed)
3. ./assets/ (local development)
For Docker/Cloud Run deployment:
- Copy assets folder alongside binary
- Or keep node_modules structure
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Cloud Run cold starts taking 139 seconds due to 90MB WASM file with
embedded 87MB model weights. WASM compilation scales with file size.
Solution: Split into 2.4MB WASM (code only) + external model files.
- WASM compile: 139,000ms → 6-8ms
- Model load: N/A → 30-115ms
- Total init: 139,000ms → 136-240ms
New modelLoader.ts handles all environments:
- Node.js: fs.readFile()
- Bun: Bun.file()
- Bun --compile: auto-embedded assets
- Browser: fetch()
Zero config - same API, npm package includes model files.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Remove @huggingface/transformers dependency (539MB native binaries)
- Add direct ONNX Runtime Web embedding engine
- Bundle all-MiniLM-L6-v2-q8 model (24MB, no runtime downloads)
- Works with Node.js, Bun, and bun build --compile
- Air-gap compatible: fully self-contained, no internet required
New WASM embedding components:
- WASMEmbeddingEngine: Main integration class
- WordPieceTokenizer: Pure TypeScript tokenizer
- EmbeddingPostProcessor: Mean pooling + L2 normalization
- ONNXInferenceEngine: Direct ONNX Runtime Web wrapper
- AssetLoader: Model file loading
Tests added:
- 11 WASM embedding integration tests
- 8 Bun compatibility tests
New npm scripts:
- test:wasm - Run WASM embedding tests
- test:bun - Run tests with Bun
- test:bun:compile - Build and run compiled binary
- Add importFile() method for single file imports
- Implement entity helper methods (linkEntities, findEntityOccurrences)
- Fix critical embedding tokenizer bug (char.charCodeAt error)
- Fix removeRelationship to actually remove using brain.unrelate()
- Add setMetadata/getMetadata methods
- Fix GitBridge to query real relationships and events
- Enable background Knowledge Layer processing
- Rewrite README to emphasize knowledge over files
- Add comprehensive VFS documentation (core, knowledge layer, examples)
- Add complete test suite covering all VFS methods
This completes the VFS implementation with full Knowledge Layer support,
enabling files as living knowledge that understand themselves, evolve
over time, and connect to everything related.
- Remove Node.js-specific imports from module level
- Use dynamic imports with isNode() environment checks
- Wrap all file system operations in conditional blocks
- Add fallback values for browser environments
- Ensure code works in both Node.js and browser contexts
This change enables Brainy to run in browser environments without
requiring Node.js polyfills, making it truly universal.
Co-Authored-By: dpsifr <noreply@dpsifr.com>
- Updated all fs, path, crypto, os, url, util, events, http, https, net, child_process, stream, and zlib imports
- Changed both static imports and dynamic imports to use node: protocol
- This makes Brainy more bundler-friendly by explicitly marking Node.js built-ins
- Prevents bundlers from attempting to polyfill or bundle these modules
- Reduces bundle size for web applications using Brainy
- Improves tree-shaking and dead code elimination
Benefits for external bundlers:
- Clear distinction between Node.js built-ins and external dependencies
- No ambiguity about what needs polyfilling
- Smaller bundles for browser builds
- Better compatibility with modern bundlers (Webpack 5, Vite, Rollup, esbuild)
🤖 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com>
- Unified embedding system with single EmbeddingManager
- Q8 model support with 75% smaller footprint (23MB vs 90MB)
- Intelligent precision auto-selection based on environment
- Clean cached embeddings with TTL and memory management
- Zero-config setup with smart defaults
- Complete storage structure documentation
- Removed legacy worker and hybrid managers
- Streamlined model configuration and precision management
- Changed confusing 'dtype' to 'precision' for model variant selection
- Fixed Q8 quantized model loading in transformers.js pipeline
- Added proper model file detection for q8 vs fp32 models
- Updated all references across codebase to use new parameter
- Maintains backward compatibility while providing clearer API
Changed default dtype from q8 to fp32 across all embedding implementations:
- embedding.ts: Default dtype changed to fp32
- worker-embedding.ts: Use fp32 for consistency
- universal-memory-manager.ts: Use fp32 for consistency
- lightweight-embedder.ts: Use fp32 for consistency
- hybridModelManager.ts: Use fp32 for all configurations
This ensures we use the exact same model (model.onnx) everywhere,
maintaining data compatibility and avoiding 404 errors for quantized models.
CRITICAL ARCHITECTURAL FIX:
- Change node-worker strategy to node-direct for ONNX compatibility
- Use single model instance on main thread instead of worker pool
- Prevents HandleScope V8 API locking errors in Node.js 22/24
- Reduces memory usage from 360MB+ to ~90MB (single model vs 4 workers)
- Maintains async operations using native transformers.js capabilities
Root Cause: ONNX runtime cannot properly handle V8 isolate context
switching between worker threads, causing fatal HandleScope errors.
Solution: Keep ONNX operations in main V8 isolate while preserving
all existing async functionality and performance.
Tested: Multiple concurrent addNoun operations work without errors.
- Implements automatic fallback chain: CDN → GitHub → Hugging Face
- Adds Soulcraft CDN as primary model source (models.soulcraft.com)
- GitHub release tar.gz extraction as reliable backup
- Zero configuration required - fully automatic
- Guarantees same model (all-MiniLM-L6-v2) across all sources
- 384-dimensional embeddings for data compatibility
- Local caching after first download
- Production-ready with multiple redundancy layers
BREAKING CHANGE: Removed tar-stream dependency, now uses native tar command