brainy/tests/unit/plugin.test.ts
David Snelling 780fb6444b feat(8.0)!: flip requireSubtype default to true (BRAINY-8.0-SUBTYPE-CONTRACT § C-1)
Brainy 8.0 makes subtype required by default on every public write path
(`add`, `addMany`, `update`, `relate`, `relateMany`, `updateRelation`,
import). Per the locked C-1 contract, every entity and relation gets a
non-empty subtype string by the time the storage layer sees it.

OPT-OUT REMAINS FULLY SUPPORTED

The runtime flag is still consumer-controlled. Three opt-out paths
cover migration / legacy fixtures / typed escape:

- `new Brainy({ requireSubtype: false })` — last-resort: turn off the
  contract entirely. Recommended only for migration windows or test
  fixtures that legitimately can't supply a subtype.
- `new Brainy({ requireSubtype: { except: [NounType.Thing, ...] } })` —
  per-type allowlist: strict everywhere except the listed types.
- `brain.requireSubtype(type, options)` — per-type registration with
  optional vocabulary. Composes with the brain-wide flag.

Default is now `true`. Opt-out is explicit and documented; nothing
silently degrades.

TEST SWEEP

Bulk-applied `requireSubtype: false` to every `new Brainy({...})` call
site across 120 test files. Three sed patterns covered the shapes:
  - `new Brainy({` → `new Brainy({ requireSubtype: false,`
  - `new Brainy<T>({` → `new Brainy<T>({ requireSubtype: false,`
  - `new Brainy()` → `new Brainy({ requireSubtype: false })`

tests/helpers/test-factory.ts → createTestConfig() defaults
`requireSubtype: false` so test files using the helper inherit the
opt-out without per-site edits.

The test sites that DO exercise subtype semantics (the
subtype-and-facets suite, the strict-mode-self-test suite, the verb-
subtype-and-enforcement suite, etc.) already pass real subtypes — they
were the 7.30.x acceptance tests for this contract. Those tests
continue to pass unchanged.

CHANGES

src/brainy.ts
- normalizeConfig() — `requireSubtype` default `false` → `true`.
  Comment refreshed to document the three opt-out paths.

tests/* (120 files)
- Bulk-edited brain construction sites. No functional test changes; the
  opt-out preserves the test author's original intent.

tests/helpers/test-factory.ts
- createTestConfig() base config gains `requireSubtype: false`.

NO-OP for consumers who were already passing subtype on every write.

For consumers who weren't, the upgrade path is one of the three opt-out
forms above. Migration recipe documented in 8.0 release notes (next
commit).

VERIFICATION

- npx tsc --noEmit: clean
- npm test: 1408 / 1409 (same pre-existing race-condition outstanding;
  no other regressions from the flip)
2026-06-09 14:58:25 -07:00

320 lines
9.1 KiB
TypeScript

/**
* Plugin System Integration Tests
*
* Tests the PluginRegistry lifecycle, provider resolution in init(),
* fallback behavior, and error handling.
*/
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { PluginRegistry } from '../../src/plugin.js'
import type { BrainyPlugin, BrainyPluginContext } from '../../src/plugin.js'
import { Brainy } from '../../src/brainy.js'
import { NounType } from '../../src/types/graphTypes.js'
import { MetadataIndexManager } from '../../src/utils/metadataIndex.js'
import { setGlobalCache, getGlobalCache, clearGlobalCache, UnifiedCache } from '../../src/utils/unifiedCache.js'
describe('PluginRegistry', () => {
let registry: PluginRegistry
beforeEach(() => {
registry = new PluginRegistry()
})
it('should register and retrieve a plugin', () => {
const plugin: BrainyPlugin = {
name: 'test-plugin',
activate: async () => true
}
registry.register(plugin)
expect(registry.getActivePlugins()).toEqual([])
})
it('should activate a plugin and expose providers', async () => {
const plugin: BrainyPlugin = {
name: 'test-plugin',
activate: async (ctx) => {
ctx.registerProvider('distance', () => 0.42)
return true
}
}
registry.register(plugin)
const context: BrainyPluginContext = {
registerProvider: (key, impl) => registry.registerProvider(key, impl),
version: '7.9.3'
}
const activated = await registry.activateAll(context)
expect(activated).toEqual(['test-plugin'])
expect(registry.getActivePlugins()).toEqual(['test-plugin'])
expect(registry.hasProvider('distance')).toBe(true)
const distFn = registry.getProvider<() => number>('distance')
expect(distFn!()).toBe(0.42)
})
it('should skip plugin that returns false', async () => {
const plugin: BrainyPlugin = {
name: 'unavailable-plugin',
activate: async () => false
}
registry.register(plugin)
const context: BrainyPluginContext = {
registerProvider: (key, impl) => registry.registerProvider(key, impl),
version: '7.9.3'
}
const activated = await registry.activateAll(context)
expect(activated).toEqual([])
expect(registry.getActivePlugins()).toEqual([])
})
it('should handle plugin that throws during activate', async () => {
const plugin: BrainyPlugin = {
name: 'broken-plugin',
activate: async () => {
throw new Error('activation failed')
}
}
registry.register(plugin)
const context: BrainyPluginContext = {
registerProvider: (key, impl) => registry.registerProvider(key, impl),
version: '7.9.3'
}
// Should not throw — graceful fallback
const activated = await registry.activateAll(context)
expect(activated).toEqual([])
expect(registry.getActivePlugins()).toEqual([])
})
it('should deactivate plugins', async () => {
const deactivateFn = vi.fn()
const plugin: BrainyPlugin = {
name: 'test-plugin',
activate: async () => true,
deactivate: deactivateFn
}
registry.register(plugin)
const context: BrainyPluginContext = {
registerProvider: (key, impl) => registry.registerProvider(key, impl),
version: '7.9.3'
}
await registry.activateAll(context)
expect(registry.getActivePlugins()).toEqual(['test-plugin'])
await registry.deactivateAll()
expect(registry.getActivePlugins()).toEqual([])
expect(deactivateFn).toHaveBeenCalledOnce()
})
it('should not activate same plugin twice', async () => {
let activateCount = 0
const plugin: BrainyPlugin = {
name: 'once-plugin',
activate: async () => {
activateCount++
return true
}
}
registry.register(plugin)
const context: BrainyPluginContext = {
registerProvider: (key, impl) => registry.registerProvider(key, impl),
version: '7.9.3'
}
await registry.activateAll(context)
await registry.activateAll(context)
expect(activateCount).toBe(1)
})
it('should register multiple providers from one plugin', async () => {
const plugin: BrainyPlugin = {
name: 'multi-provider',
activate: async (ctx) => {
ctx.registerProvider('distance', () => 0.5)
ctx.registerProvider('msgpack', { encode: () => null, decode: () => null })
ctx.registerProvider('roaring', class FakeRoaring {})
return true
}
}
registry.register(plugin)
const context: BrainyPluginContext = {
registerProvider: (key, impl) => registry.registerProvider(key, impl),
version: '7.9.3'
}
await registry.activateAll(context)
expect(registry.hasProvider('distance')).toBe(true)
expect(registry.hasProvider('msgpack')).toBe(true)
expect(registry.hasProvider('roaring')).toBe(true)
expect(registry.hasProvider('hnsw')).toBe(false)
})
it('should handle storage adapter factory registration', () => {
registry.registerProvider('storage:redis', {
name: 'redis',
create: () => ({} as any)
})
const factory = registry.getStorageFactory('redis')
expect(factory).toBeDefined()
expect(factory!.name).toBe('redis')
})
})
describe('setGlobalCache', () => {
beforeEach(() => {
clearGlobalCache()
})
it('should replace the global cache singleton', () => {
// Get default cache
const defaultCache = getGlobalCache()
expect(defaultCache).toBeInstanceOf(UnifiedCache)
// Replace with a new one
const customCache = new UnifiedCache({ maxSize: 1024 * 1024 })
setGlobalCache(customCache)
// Verify replacement
const retrieved = getGlobalCache()
expect(retrieved).toBe(customCache)
expect(retrieved).not.toBe(defaultCache)
// Clean up
clearGlobalCache()
})
})
describe('Brainy plugin integration', () => {
it('should use distance provider from plugin', async () => {
const mockPlugin: BrainyPlugin = {
name: 'test-distance',
activate: async (ctx) => {
ctx.registerProvider('distance', (a: number[], b: number[]) => {
// Simple euclidean for testing
let sum = 0
for (let i = 0; i < a.length; i++) {
sum += (a[i] - b[i]) ** 2
}
return Math.sqrt(sum)
})
return true
}
}
const brain = new Brainy({ requireSubtype: false,
storage: { type: 'memory' },
silent: true,
})
brain.use(mockPlugin)
await brain.init()
expect(brain.getActivePlugins()).toContain('test-distance')
await brain.close()
})
it('should verify metadataIndex factory provider is called', async () => {
let factoryCalled = false
const mockPlugin: BrainyPlugin = {
name: 'test-metadata-check',
activate: async (ctx) => {
// Register a factory — we only verify it gets called,
// not that the mock works as a full MetadataIndexManager replacement.
// The real NativeMetadataIndex in cortex implements the full interface.
ctx.registerProvider('metadataIndex', (storage: any) => {
factoryCalled = true
// Return a real MetadataIndexManager so init() works end-to-end
return new MetadataIndexManager(storage)
})
return true
}
}
const brain = new Brainy({ requireSubtype: false,
storage: { type: 'memory' },
silent: true,
})
brain.use(mockPlugin)
await brain.init()
expect(factoryCalled).toBe(true)
expect(brain.getActivePlugins()).toContain('test-metadata-check')
await brain.close()
})
it('should fall back to TS implementations when plugin returns false', async () => {
const mockPlugin: BrainyPlugin = {
name: 'unavailable-native',
activate: async () => false
}
const brain = new Brainy({ requireSubtype: false,
storage: { type: 'memory' },
silent: true,
})
brain.use(mockPlugin)
await brain.init()
// Should initialize normally with TS fallbacks
expect(brain.getActivePlugins()).toEqual([])
// Should still work with TS implementations
const id = await brain.add({
data: { name: 'test' },
type: NounType.Concept,
metadata: { tag: 'unit-test' }
})
expect(id).toBeTypeOf('string')
await brain.close()
})
it('should fall back gracefully when plugin throws', async () => {
const mockPlugin: BrainyPlugin = {
name: 'crashing-plugin',
activate: async () => {
throw new Error('native module not found')
}
}
const brain = new Brainy({ requireSubtype: false,
storage: { type: 'memory' },
silent: true,
})
brain.use(mockPlugin)
// Should not throw — graceful fallback to TS
await brain.init()
expect(brain.getActivePlugins()).toEqual([])
const id = await brain.add({
data: { name: 'test' },
type: NounType.Concept,
metadata: { tag: 'unit-test' }
})
expect(id).toBeTypeOf('string')
await brain.close()
})
it('should use() return this for chaining', () => {
const plugin: BrainyPlugin = {
name: 'chain-test',
activate: async () => true
}
const brain = new Brainy({ requireSubtype: false, storage: { type: 'memory' } })
const result = brain.use(plugin)
expect(result).toBe(brain)
})
})