feat(8.0): version-coupling guard — a mismatched/failed native plugin fails loud, never silent JS fallback

A wrong or missing accelerator (@soulcraft/cor) used to silently degrade to the
default JS engine — the #1 source of invisible cross-repo drift. Brainy does no
plugin auto-detection (a registered plugin is always explicitly requested via
config.plugins or brain.use()), so any mismatch/failure is now fatal:

- BrainyPlugin gains optional `brainyRange` (semver range of brainy it supports);
  init() throws if the running brainy is outside it. New dep-free, prerelease-safe
  matcher pluginRangeSatisfies() (8.0.0-rc1 satisfies >=8.0.0).
- activateAll(): a plugin that THROWS during activate now re-throws (was swallowed
  to a JS fallback); a graceful decline (activate()→false) stays non-fatal but logs
  a loud warning.
- loadPlugins(): an explicitly-listed package that can't load — or isn't a valid
  plugin — throws (was a silent skip).
- Provider-key cliff: a pre-8.0 plugin that registers a legacy vector key
  ('hnsw'/'diskann') but not the 8.0 'vector' key throws (brainy 8.x reads only
  'vector', so it would otherwise run JS vectors invisibly).

Tests: tests/unit/plugin-version-coupling.test.ts (range matcher incl. rc1; range
mismatch / activate-throw / cliff / missing-package all throw; decline non-fatal).
Updated two plugin.test.ts cases that asserted the old silent-swallow behavior.
Build green; 1464 unit green. cor declares its brainyRange per handoff LV.1 #2.
This commit is contained in:
David Snelling 2026-06-19 10:13:04 -07:00
parent b198281ce1
commit 1264fec534
4 changed files with 271 additions and 32 deletions

View file

@ -39,9 +39,26 @@ export interface BrainyPlugin {
/** Unique plugin name (typically the npm package name) */
name: string
/**
* Optional semver range of `@soulcraft/brainy` this plugin supports
* (e.g. `'>=8.0.0 <9.0.0'` or `'^8.0.0'`). When set and the running brainy is
* OUTSIDE the range, `init()` THROWS rather than silently falling back to the
* default JS engine. This is the version-coupling guard for the native
* accelerator (`@soulcraft/cor`): brainy 8.x and cor 3.x are a matched pair,
* and a mismatch must fail loud, not degrade invisibly. Supported range
* grammar: space-separated AND of `>=`, `>`, `<=`, `<`, `=` comparators, plus
* `^X.Y.Z` (same-major floor). Prerelease tags on the running version are
* tolerated (`8.0.0-rc1` satisfies `>=8.0.0`).
*/
brainyRange?: string
/**
* Called by brainy during init() to activate the plugin.
* Return true if activation succeeded, false to skip.
* Return `true` if activation succeeded. Returning `false` is a graceful
* decline (brainy logs a loud warning and uses the default engine for this
* plugin's providers). THROWING aborts init a registered plugin is always
* explicitly requested (via `config.plugins` or `brain.use()`; brainy does no
* auto-detection), so a hard failure is fatal, never a silent skip.
*/
activate(context: BrainyPluginContext): Promise<boolean>
@ -482,6 +499,65 @@ export interface StorageAdapterFactory {
/**
* Plugin registry manages plugin lifecycle and provider resolution.
*/
/** Parse `X.Y.Z[-prerelease][+build]` → `[major, minor, patch]`, prerelease/build stripped. */
function parseSemverCore(version: string): [number, number, number] | null {
const core = version.trim().split('+')[0].split('-')[0]
const parts = core.split('.')
if (parts.length < 1) return null
const nums = [0, 1, 2].map((i) => {
const n = parseInt(parts[i] ?? '0', 10)
return Number.isFinite(n) ? n : NaN
})
if (nums.some((n) => Number.isNaN(n))) return null
return nums as [number, number, number]
}
/** Compare two semver cores. <0 if a<b, 0 if equal, >0 if a>b. */
function compareSemverCore(a: [number, number, number], b: [number, number, number]): number {
for (let i = 0; i < 3; i++) {
if (a[i] !== b[i]) return a[i] - b[i]
}
return 0
}
/**
* Minimal, dependency-free semver-range check for pluginbrainy version coupling
* (see {@link BrainyPlugin.brainyRange}). Brainy is a public MIT library, so we
* avoid a full `semver` dependency; the coupling we enforce is major-version
* lockstep with the native accelerator. Supports a space-separated AND of
* `>=`, `>`, `<=`, `<`, `=` comparators plus `^X.Y.Z` (same-major, >= floor).
* Prerelease tags on the running `version` are tolerated (compared by core), so
* an RC build (`8.0.0-rc1`) satisfies `>=8.0.0`.
*
* @returns true if `version` satisfies `range`; on an unparseable range, returns
* true (fail-open on a malformed declaration rather than block a valid brain).
*/
export function pluginRangeSatisfies(version: string, range: string): boolean {
const v = parseSemverCore(version)
if (!v) return false
const comparators = range.trim().split(/\s+/).filter(Boolean)
if (comparators.length === 0) return true
for (const comp of comparators) {
const m = comp.match(/^(\^|>=|<=|>|<|=)?\s*(\d+(?:\.\d+){0,2}(?:[-+].*)?)$/)
if (!m) return true // unparseable comparator → fail-open
const op = m[1] || '='
const target = parseSemverCore(m[2])
if (!target) return true
const cmp = compareSemverCore(v, target)
let ok: boolean
switch (op) {
case '>=': ok = cmp >= 0; break
case '>': ok = cmp > 0; break
case '<=': ok = cmp <= 0; break
case '<': ok = cmp < 0; break
case '^': ok = v[0] === target[0] && cmp >= 0; break // same major, >= floor
default: ok = cmp === 0 // '='
}
if (!ok) return false
}
return true
}
export class PluginRegistry {
private plugins: Map<string, BrainyPlugin> = new Map()
private providers: Map<string, unknown> = new Map()
@ -504,14 +580,42 @@ export class PluginRegistry {
for (const [name, plugin] of this.plugins) {
if (this.activated.has(name)) continue
// Version-coupling guard. A registered plugin is ALWAYS explicitly
// requested (config.plugins or brain.use() — brainy does no
// auto-detection), so a version mismatch must FAIL LOUD, never silently
// degrade to the default JS engine. (This was the #1 cross-repo drift:
// an old @soulcraft/cor running invisibly against brainy 8.x.)
if (plugin.brainyRange && !pluginRangeSatisfies(context.version, plugin.brainyRange)) {
throw new Error(
`[brainy] Plugin "${name}" supports brainy ${plugin.brainyRange}, but this is brainy ` +
`${context.version}. The engines must be version-matched (brainy 8.x ↔ @soulcraft/cor 3.x); ` +
`install a compatible ${name} (or brainy). brainy will NOT silently run the default engine ` +
`in place of a mismatched accelerator.`
)
}
let success: boolean
try {
const success = await plugin.activate(context)
if (success) {
this.activated.add(name)
activated.push(name)
}
success = await plugin.activate(context)
} catch (error) {
console.warn(`[brainy] Plugin ${name} failed to activate:`, error)
// Hard activation failure on an explicitly-requested plugin is fatal,
// not a swallow-and-fall-back-to-JS.
throw new Error(
`[brainy] Plugin "${name}" failed to activate: ` +
`${error instanceof Error ? error.message : String(error)}`
)
}
if (success) {
this.activated.add(name)
activated.push(name)
} else {
// Documented graceful decline (activate() → false). Surface it loudly so
// a silent degrade to the default engine never goes unnoticed.
console.warn(
`[brainy] Plugin "${name}" declined activation (activate() returned false); ` +
`the default engine is in use for its providers.`
)
}
}