🧠 Zero-Configuration AI Database with Triple Intelligence™ https://soulcraft.com
Find a file
David Snelling 5f3a2ca7d5 fix: internal subtype consistency + brain.audit() diagnostic + improved enforcement errors
Brainy 7.30 shipped opt-in subtype enforcement; SDK 3.20.0 then registered
SDK_CORE_VOCABULARY on every consumer's brain (Event, Collection, Message,
Contract, Media, Document NounTypes). On 2026-06-08 Venue's /book flow went 500
because their brain.add({ type: NounType.Event, ... }) call sites lacked
subtype. An audit of Brainy's OWN source revealed 14 HIGH-risk internal write
paths that also omit subtype — any consumer running the same vocabulary would
have hit Brainy's infrastructure paths next. 7.30.1 closes both gaps before
8.0 makes strict mode the default.

Additive across the board. Zero behavior change for consumers not using strict
mode. Every change is JS-side — Cortex needs no work for 7.30.1.

NEW — brain.audit() diagnostic
- Read-only method walking storage.getNouns() / getVerbs() pagination
- Returns { entitiesWithoutSubtype: { type: count }, relationshipsWithoutSubtype,
  total, scanned, recommendation }
- VFS infrastructure entities excluded by default (they bypass enforcement via
  isVFSEntity marker); pass { includeVFS: true } to surface them
- The companion to migrateField (7.x) and fillSubtypes (8.0): tells consumers
  exactly what would break under strict enforcement, deterministically

NEW — Improved enforcement error messages
- Caller's source location extracted from Error().stack so users see their own
  call site, not a Brainy internal frame
- Specific guidance branches: registered vocabulary → "Pass one of: a, b, c";
  brain-wide strict mode → mentions the except clause; otherwise → registration
  recipe via brain.requireSubtype()
- Documentation link to the canonical migration recipe
- Same shape for noun and verb enforcement

NEW — CLI --subtype flag
- brainy add and brainy relate gain -s/--subtype <value>
- Defaults to 'cli-add' / 'cli-relate' so the CLI works against strict-mode
  brains without the user needing to know the vocabulary in advance

INTERNAL — every Brainy write path now sets subtype
- VFS Contains edges (5 sites at lines 503/905/1694/1772/1886) → 'vfs-contains'
- VFS symlink entity → 'vfs-symlink' (NEW — distinct from 'vfs-file')
- VFS copy-file → preserves source subtype, falls back to 'vfs-file'
- VFS symlink also adopts the isVFSEntity infrastructure marker so it bypasses
  enforcement in strict mode
- Aggregation materializer (Measurement entities) → 'materialized-aggregate'
- ImportCoordinator (3 sites): document → 'import-source'; entities →
  options.defaultSubtype ?? 'imported'; placeholder → 'import-placeholder'
- SmartImportOrchestrator (4 entity sites + 2 batch relate sites): same
  precedence (extractor → options.defaultSubtype → 'imported')
- EntityDeduplicator → candidate.subtype ?? 'imported'
- UniversalImportAPI → extractor → 'extracted' for both entities and relations
- NeuralImport → adds defaultSubtype to NeuralImportOptions; precedence same
- GoogleSheetsIntegration → request body 'subtype' ?? 'imported-from-sheets'
- ODataIntegration → request body 'Subtype' ?? 'imported-from-odata'
- MCP client message storage → 'mcp-message' (also fixes pre-existing missing
  data field and missing type by aliasing from the prior text field)

Side-effect fix: storage.getNouns() paginated now surfaces subtype to top-level
- Single-noun getNoun() already did this in 7.30; the paginated path was missed
- Without this fix brain.audit() saw missing subtype on entities that actually
  had one (caught by the strict-mode self-test before release)

NEW — tests/integration/strict-mode-self-test.test.ts (13 tests)
- Creates a brain under the exact SDK_CORE_VOCABULARY shape Venue hit + brain-
  wide strict mode
- Exercises every internal Brainy path: VFS root + mkdir + writeFile + cp + mv
  + ln + symlink; aggregation engine; audit diagnostic with includeVFS toggle
- Validates error message UX: caller location, vocabulary guidance, brain-wide
  strict mode guidance, off-vocabulary value reporting

Docs
- New "Strict mode in practice" section in docs/guides/subtypes-and-facets.md
  covering the SDK_CORE_VOCABULARY pattern, 4-step migration recipe
  (audit → migrateField → hand-fix → re-audit), the Brainy-internal label
  reference table, and an 8.0 forward-look on fillSubtypes()
- docs/api/README.md: new audit() entry, strict-mode tips on add() and relate()
- RELEASES.md: full 7.30.1 entry

Cortex parity (forward-looking, not blocking 7.30.1)
- 6th open question added to .strategy/BRAINY-8.0-SUBTYPE-CONTRACT.md: native
  fast path for audit() and fillSubtypes() via column-store null-subtype
  bitmap for billion-scale brains
- Cortex should add a parity test mirroring strict-mode-self-test.test.ts
  against their native paths to catch any latent bug where native writes
  bypass JS validation
- Brainy-internal subtype labels become a documented part of the 8.0 contract
  (useful for Cortex telemetry surfacing Brainy-managed infrastructure %)

Verification
- npx tsc --noEmit: clean
- npm test: 1468/1468 unit
- 7.29 noun integration suite: 26/26 (no regression)
- 7.30 verb subtype + enforcement integration suite: 30/30 (no regression)
- New strict-mode-self-test integration suite: 13/13
- npm run build: clean
- Closed-source product reference audit: clean

Addresses VE-SUBTYPE-MIGRATION (Venue's reported request) and ships internal
labels Venue did NOT ask for but that would have broken them next under their
own vocabulary registration.
2026-06-08 11:31:47 -07:00
.claude/skills feat: add aggregation engine with incremental SUM/COUNT/AVG/MIN/MAX, GROUP BY, and time windows 2026-02-16 16:57:53 -08:00
assets/models/all-MiniLM-L6-v2 feat: migrate embeddings to Candle WASM + remove semantic type inference 2026-01-06 12:52:34 -08:00
bin feat: remove legacy ImportManager, standardize getStats() API 2025-10-09 11:40:31 -07:00
docs fix: internal subtype consistency + brain.audit() diagnostic + improved enforcement errors 2026-06-08 11:31:47 -07:00
examples refactor: remove augmentation system and semantic type matching 2026-02-01 10:48:56 -08:00
integrations feat: Integration Hub for external tool connectivity 2026-01-20 16:21:11 -08:00
models-cache/Xenova/all-MiniLM-L6-v2 🧠 Brainy 2.0.0 - Zero-Configuration AI Database with Triple Intelligence™ 2025-08-26 12:32:21 -07:00
scripts chore(release): create annotated tag so --follow-tags pushes it 2026-05-26 11:44:14 -07:00
src fix: internal subtype consistency + brain.audit() diagnostic + improved enforcement errors 2026-06-08 11:31:47 -07:00
tests fix: internal subtype consistency + brain.audit() diagnostic + improved enforcement errors 2026-06-08 11:31:47 -07:00
.aiignore feat: add distributed scaling and enterprise features for v3 2025-09-08 14:26:09 -07:00
.dockerignore feat: Brainy 3.0 - Production-ready Triple Intelligence database 2025-09-11 16:23:32 -07:00
.gitignore chore: gitignore Claude Code harness scheduled-tasks lockfile 2026-05-15 11:26:11 -07:00
.npmignore chore: Add .npmignore to exclude models from npm package 2025-08-26 13:37:44 -07:00
.nvmrc feat: update Node.js requirements to 22 LTS for ONNX compatibility 2025-08-28 16:05:14 -07:00
.versionrc.json feat: implement simpler, more reliable release workflow 2025-10-01 13:26:04 -07:00
brainy.png 🧠 Brainy 2.0.0 - Zero-Configuration AI Database with Triple Intelligence™ 2025-08-26 12:32:21 -07:00
bun.lock feat: migrate embeddings to Candle WASM + remove semantic type inference 2026-01-06 12:52:34 -08:00
CHANGELOG.md chore(release): 7.30.0 2026-06-05 11:16:15 -07:00
CLAUDE.md docs: add RELEASES.md + cross-project coordination section to CLAUDE.md 2026-02-28 10:07:34 -08:00
CONTRIBUTING.md feat: migrate embeddings to Candle WASM + remove semantic type inference 2026-01-06 12:52:34 -08:00
docker-compose.yml feat: Brainy 3.0 - Production-ready Triple Intelligence database 2025-09-11 16:23:32 -07:00
Dockerfile feat: Brainy 3.0 - Production-ready Triple Intelligence database 2025-09-11 16:23:32 -07:00
eslint.config.js chore: enforce consistent coding style and semicolon removal 2025-09-29 09:50:59 -07:00
LICENSE 🧠 Brainy 2.0.0 - Zero-Configuration AI Database with Triple Intelligence™ 2025-08-26 12:32:21 -07:00
package-lock.json chore(release): 7.30.0 2026-06-05 11:16:15 -07:00
package.json chore(release): 7.30.0 2026-06-05 11:16:15 -07:00
README.md feat: verb subtype + updateRelation + requireSubtype enforcement 2026-06-05 11:15:52 -07:00
RELEASES.md fix: internal subtype consistency + brain.audit() diagnostic + improved enforcement errors 2026-06-08 11:31:47 -07:00
tsconfig.cli.json feat: complete CLI with VFS, data management, and Triple Intelligence search 2025-09-29 16:57:14 -07:00
tsconfig.json build: add CLI compilation config 2025-09-29 16:02:54 -07:00
vitest.config.memory.ts 🧠 Brainy 2.0.0 - Zero-Configuration AI Database with Triple Intelligence™ 2025-08-26 12:32:21 -07:00
vitest.config.ts 🧠 Brainy 2.0.0 - Zero-Configuration AI Database with Triple Intelligence™ 2025-08-26 12:32:21 -07:00

Brainy

Brainy Logo

npm version npm downloads Documentation MIT License TypeScript

Three database paradigms. One API. Zero configuration.

Built because we were tired of stitching together Pinecone + Neo4j + MongoDB and spending weeks on configuration before writing a single line of business logic. Brainy unifies vector search, graph traversal, and metadata filtering so you don't have to choose.

New here?What is Brainy? — plain-language overview, no jargon


Install

npm install @soulcraft/brainy

Quick Start

import { Brainy, NounType, VerbType } from '@soulcraft/brainy'

const brain = new Brainy()
await brain.init()

// Add knowledge — text auto-embeds, metadata auto-indexes
const reactId = await brain.add({
  data: 'React is a JavaScript library for building user interfaces',
  type: NounType.Concept,
  metadata: { category: 'frontend', year: 2013 }
})

const nextId = await brain.add({
  data: 'Next.js framework for React with server-side rendering',
  type: NounType.Concept,
  metadata: { category: 'framework', year: 2016 }
})

// Create a relationship
await brain.relate({ from: nextId, to: reactId, type: VerbType.BuiltOn })

// Query all three paradigms at once
const results = await brain.find({
  query: 'modern frontend frameworks',            // Vector similarity
  where: { year: { greaterThan: 2015 } },         // Metadata filtering
  connected: { to: reactId, depth: 2 }            // Graph traversal
})

Full API Reference | soulcraft.com/docs


Three Indexes, One Query

Every piece of knowledge lives in three indexes simultaneously:

  • dataVector index — Content for semantic search. Strings auto-embed into 384-dim vectors. Queried with find({ query: '...' }).
  • metadataMetadata index — Structured fields for filtering. O(1) lookups. Queried with find({ where: { ... } }).
  • relate()Graph index — Typed, directed relationships between entities. Traversed with find({ connected: { ... } }).
// Data → vector index (semantic search)
const articleId = await brain.add({
  data: 'A deep dive into transformer architectures',
  type: NounType.Document,
  metadata: { author: 'Dr. Chen', year: 2024, tags: ['AI'] }  // → metadata index
})

// Relationships → graph index
await brain.relate({ from: authorId, to: articleId, type: VerbType.Authored })

// Query all three at once
brain.find({
  query: 'attention mechanisms',                  // Vector similarity
  where: { year: { greaterThan: 2023 } },         // Metadata filter
  connected: { from: authorId, depth: 1 }         // Graph traversal
})

Data Model Reference | Query Operators


Features

Triple Intelligence

Vector search + graph traversal + metadata filtering in every query. No stitching services together — one find() call combines all three.

const results = await brain.find({
  query: 'machine learning',
  where: { department: 'engineering', level: 'senior' },
  connected: { from: teamLeadId, via: VerbType.WorksWith, depth: 2 }
})

Automatically combines keyword (text) and semantic (vector) search. No configuration needed.

await brain.find({ query: 'David Smith' })             // Auto: text + semantic
await brain.find({ query: 'AI concepts', searchMode: 'semantic' })  // Semantic only
await brain.find({ query: 'exact id', searchMode: 'text' })         // Text only

Query Operators

Filter metadata with equality, comparison, array, existence, pattern, and logical operators:

await brain.find({
  where: {
    status: 'active',                          // Exact match
    score: { greaterThan: 90 },                // Comparison
    tags: { contains: 'ai' },                  // Array
    anyOf: [{ role: 'admin' }, { role: 'owner' }]  // Logical OR
  }
})

Query Operators Reference — all operators with indexed/in-memory matrix

Graph Relationships

Typed, directed edges between entities. Traverse connections at any depth.

await brain.relate({ from: personId, to: projectId, type: VerbType.WorksOn })

const results = await brain.find({
  connected: { from: personId, via: VerbType.WorksOn, depth: 3 }
})

Git-Style Branching

Fork your entire database in <100ms. Snowflake-style copy-on-write.

const experiment = await brain.fork('test-migration')
await experiment.add({ data: 'test data', type: NounType.Concept })
await experiment.commit({ message: 'Add test data', author: 'dev@co.com' })
await brain.checkout('test-migration')

// Time-travel: query at any past commit
const snapshot = await brain.asOf(commitId)
const pastResults = await snapshot.find({ query: 'historical data' })
await snapshot.close()

Branching Documentation

Entity Versioning

Save, restore, and compare entity snapshots.

const userId = await brain.add({ data: 'Alice', type: NounType.Person })
await brain.versions.save(userId, { tag: 'v1.0' })

await brain.update(userId, { data: 'Alice Smith' })
await brain.versions.save(userId, { tag: 'v2.0' })

const diff = await brain.versions.compare(userId, 1, 2)
await brain.versions.restore(userId, 1)

Virtual Filesystem

File operations with semantic search built in.

const vfs = brain.vfs

await vfs.writeFile('/docs/readme.md', 'Project documentation')
const content = await vfs.readFile('/docs/readme.md')
const tree = await vfs.getTreeStructure('/docs', { maxDepth: 3 })

// Semantic file search
const matches = await vfs.search('React components with hooks')

VFS Quick Start | Common Patterns

Import Anything

CSV, Excel, PDF, URLs — auto-detected format, auto-classified entities.

await brain.import('customers.csv')
await brain.import('sales-data.xlsx', { excelSheets: ['Q1', 'Q2'] })
await brain.import('research-paper.pdf', { pdfExtractTables: true })
await brain.import('https://api.example.com/data.json')

Import Guide

Entity Extraction

AI-powered named entity recognition with 4-signal ensemble scoring.

const entities = await brain.extractEntities('John Smith founded Acme Corp in New York')
// [
//   { text: 'John Smith', type: NounType.Person, confidence: 0.95 },
//   { text: 'Acme Corp', type: NounType.Organization, confidence: 0.92 },
//   { text: 'New York', type: NounType.Location, confidence: 0.88 }
// ]

Neural Extraction Guide

Plugin System

Optional native acceleration via @soulcraft/cortex — SIMD distance calculations, CRoaring bitmaps, Candle ML embeddings.

const brain = new Brainy({ plugins: ['@soulcraft/cortex'] })
await brain.init()

Plugins are opt-in. Brainy never auto-imports packages unless listed in plugins.

Plugin Documentation


Type System

42 noun types and 127 verb types form a universal knowledge protocol:

42 Nouns × 127 Verbs = 5,334 base relationship combinations

Model any domain — healthcare (Patient → diagnoses → Condition), finance (Account → transfers → Transaction), education (Student → completes → Course), or your own.

Subtypes — sub-classification within a NounType or VerbType

Both noun types and verb types are intentionally coarse. Use the top-level subtype field to sub-classify entities AND relationships within a type — flat string, no hierarchy, your choice of vocabulary:

// Nouns: sub-classify entities
await brain.add({
  data: 'Avery Brooks — runs the AI lab',
  type: NounType.Person,
  subtype: 'employee'                 // 'customer', 'vendor', 'contractor', …
})

// Verbs: sub-classify relationships
await brain.relate({
  from: ceoId,
  to: vpId,
  type: VerbType.ReportsTo,
  subtype: 'direct'                   // 'dotted-line', 'matrix', …
})

// Filter on the fast path — column-store hit, not metadata fallback:
const employees = await brain.find({ type: NounType.Person, subtype: 'employee' })
const directReports = await brain.getRelations({ from: ceoId, subtype: 'direct' })

// O(1) counts via the persisted rollups:
brain.counts.bySubtype(NounType.Person)
// → { employee: 12, customer: 847, vendor: 34 }

brain.counts.byRelationshipSubtype(VerbType.ReportsTo)
// → { direct: 12, 'dotted-line': 3 }

Enforce the pairing. Register a vocabulary per type or turn on brain-wide strict mode to ensure every entity AND relationship has both type AND subtype:

// Per-type rule with vocabulary
brain.requireSubtype(NounType.Person, { values: ['employee', 'customer'], required: true })

// Or brain-wide strict mode
const brain = new Brainy({ requireSubtype: true })

For other facets you want counted (status, source, role), register them with brain.trackField(name). Renaming an existing convention to subtype? Use brain.migrateField({from, to, entityKind: 'both'}) to walk nouns AND verbs in one pass. Full guide: Subtypes & Facets.

Noun-Verb Taxonomy | Stage 3 Canonical Reference


Storage: Memory to Cloud

The same API at every scale. Change one config line to go from prototype to production.

Development — Zero Config

const brain = new Brainy()

Production — Filesystem with Compression

const brain = new Brainy({
  storage: { type: 'filesystem', path: './data', compression: true }
})

Cloud — S3, GCS, Azure, Cloudflare R2

const brain = new Brainy({
  storage: {
    type: 's3',
    s3Storage: { bucketName: 'my-knowledge-base', region: 'us-east-1' }
  }
})

Performance benchmarks and capacity planning in docs/PERFORMANCE.md.

Cloud Deployment Guide | Capacity Planning


Use Cases

  • AI agents — Persistent memory with semantic recall and relationship tracking
  • Knowledge bases — Auto-linking, semantic search, relationship-aware navigation
  • Semantic search — Find by meaning across codebases, documents, or media
  • Enterprise knowledge — CRM, product catalogs, institutional memory
  • Interactive experiences — Game worlds, NPCs, and characters that remember
  • Content platforms — Similarity-based discovery, intelligent tagging

Documentation

Start Here

Core

Architecture

Virtual Filesystem

Guides

Operations


Requirements

Bun 1.0+ (recommended) or Node.js 22 LTS

bun install @soulcraft/brainy    # Bun — best performance
npm install @soulcraft/brainy    # Node.js — fully supported

Deprecation Notice: Browser support (OPFS, Web Workers, WASM embeddings) is deprecated in v7.10.0 and will be removed in v8.0.0. Brainy v8+ will be server-only.

Single-Writer Model

Brainy is single-writer, many-reader on filesystem storage. One writer holds an exclusive lock on the data directory; any number of readers can inspect it concurrently. Opening a second writer throws with the PID of the existing one.

// Live application — writer mode is the default
const brain = new Brainy({ storage: { type: 'filesystem', rootDirectory: '/data/brain' } })
await brain.init()

// Out-of-band diagnostics from a separate process — safe to run while the
// writer is live
const reader = await Brainy.openReadOnly({
  storage: { type: 'filesystem', rootDirectory: '/data/brain' }
})
await reader.requestFlush({ timeoutMs: 5000 })
const stats = await reader.stats()

For incident debugging, use the brainy inspect CLI:

brainy inspect stats   /data/brain
brainy inspect find    /data/brain --where '{"entityType":"booking"}'
brainy inspect explain /data/brain --where '{"entityType":"booking"}'
brainy inspect health  /data/brain

See the multi-process model and the inspection guide for the full story, including stale-lock detection, the cross-process flush RPC, and what's not yet enforced on cloud storage backends.

Contributing

We welcome contributions! See CONTRIBUTING.md for guidelines.

License

MIT © Brainy Contributors