feat(8.0)!: delete fork/branch/commit/history/versions — superseded by the Db API
The COW version-control surface (fork, branches, checkout, commit,
getHistory/streamHistory, asOfCommit, brain.versions) is gone, along with
its subsystems: src/versioning/, the COW object store (CommitLog,
CommitObject, RefManager, TreeObject), HistoricalStorageAdapter, and the
TypeAwareHNSWIndex path it kept alive. The Db API (now/transact/asOf/
with/persist/restore) is the one versioning model in 8.0.
Survivors and replacements:
- BlobStorage survives (the VFS stores file content through it), relocated
to src/storage/blobStorage.ts with binaryDataCodec.ts; its adapter
interface is now BlobStoreAdapter, slimmed to the consumed surface
(write/read/has/delete/getMetadata + MIME-aware compression policy).
- brain.migrate() backup branches are replaced by persist-before-migrate:
MigrateOptions.backupTo persists a hard-link snapshot of the current
generation before any transform runs; MigrationResult.backupPath reports
it, and brain.restore(path) brings it back wholesale.
- CLI: cow.ts (fork/branch/checkout/history/migrate) is replaced by
snapshot.ts — snapshot <path>, restore <path>, history (tx-log),
generation.
- New public read API: brain.transactionLog({limit}) exposes the reified
tx-log (generation/timestamp/meta, newest first) that backs the CLI
history command; TxLogEntry is exported.
Tests: superseded suites deleted; fork/commit blocks excised from shared
suites; BlobStorage tests relocated + reworked against the slimmed store;
migration tests now prove the backupTo snapshot/restore round trip; new
transactionLog coverage in db-mvcc.
This commit is contained in:
parent
431cd64406
commit
8f93add705
64 changed files with 1444 additions and 16313 deletions
1089
src/brainy.ts
1089
src/brainy.ts
File diff suppressed because it is too large
Load diff
|
|
@ -1,465 +0,0 @@
|
|||
/**
|
||||
* COW CLI Commands - Copy-on-Write Operations
|
||||
*
|
||||
* Fork, branch, merge, and migration operations for instant cloning
|
||||
*/
|
||||
|
||||
import chalk from 'chalk'
|
||||
import ora from 'ora'
|
||||
import inquirer from 'inquirer'
|
||||
import { Brainy } from '../../brainy.js'
|
||||
import { readFileSync, writeFileSync, existsSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
|
||||
interface CoreOptions {
|
||||
verbose?: boolean
|
||||
json?: boolean
|
||||
pretty?: boolean
|
||||
}
|
||||
|
||||
interface ForkOptions extends CoreOptions {
|
||||
name?: string
|
||||
message?: string
|
||||
author?: string
|
||||
}
|
||||
|
||||
interface MergeOptions extends CoreOptions {
|
||||
force?: boolean
|
||||
strategy?: 'last-write-wins' | 'custom'
|
||||
}
|
||||
|
||||
interface MigrateOptions extends CoreOptions {
|
||||
from?: string
|
||||
to?: string
|
||||
backup?: boolean
|
||||
dryRun?: boolean
|
||||
}
|
||||
|
||||
let brainyInstance: Brainy | null = null
|
||||
|
||||
const getBrainy = (): Brainy => {
|
||||
if (!brainyInstance) {
|
||||
brainyInstance = new Brainy()
|
||||
}
|
||||
return brainyInstance
|
||||
}
|
||||
|
||||
const formatOutput = (data: any, options: CoreOptions): void => {
|
||||
if (options.json) {
|
||||
console.log(options.pretty ? JSON.stringify(data, null, 2) : JSON.stringify(data))
|
||||
}
|
||||
}
|
||||
|
||||
export const cowCommands = {
|
||||
/**
|
||||
* Fork the current brain (instant clone)
|
||||
*/
|
||||
async fork(name: string | undefined, options: ForkOptions) {
|
||||
let spinner: any = null
|
||||
try {
|
||||
const brain = getBrainy()
|
||||
await brain.init()
|
||||
|
||||
// Interactive mode if no name provided
|
||||
if (!name) {
|
||||
const answers = await inquirer.prompt([
|
||||
{
|
||||
type: 'input',
|
||||
name: 'branchName',
|
||||
message: 'Enter fork/branch name:',
|
||||
default: `fork-${Date.now()}`,
|
||||
validate: (input: string) =>
|
||||
input.trim().length > 0 || 'Branch name cannot be empty'
|
||||
},
|
||||
{
|
||||
type: 'input',
|
||||
name: 'message',
|
||||
message: 'Commit message (optional):',
|
||||
default: 'Fork from main'
|
||||
}
|
||||
])
|
||||
name = answers.branchName
|
||||
options.message = answers.message
|
||||
}
|
||||
|
||||
spinner = ora(`Forking brain to ${chalk.cyan(name)}...`).start()
|
||||
|
||||
const startTime = Date.now()
|
||||
const fork = await brain.fork(name)
|
||||
const elapsed = Date.now() - startTime
|
||||
|
||||
spinner.succeed(
|
||||
`Fork created: ${chalk.green(name)} ${chalk.dim(`(${elapsed}ms)`)}`
|
||||
)
|
||||
|
||||
// Show stats
|
||||
const stats = await fork.getStats()
|
||||
console.log(`
|
||||
${chalk.cyan('Fork Statistics:')}
|
||||
${chalk.dim('Entities:')} ${stats.entities.total || 0}
|
||||
${chalk.dim('Relationships:')} ${stats.relationships.totalRelationships || 0}
|
||||
${chalk.dim('Time:')} ${elapsed}ms
|
||||
${chalk.dim('Storage overhead:')} ~10-20%
|
||||
`.trim())
|
||||
|
||||
if (options.json) {
|
||||
formatOutput({
|
||||
branch: name,
|
||||
time: elapsed,
|
||||
stats
|
||||
}, options)
|
||||
}
|
||||
|
||||
} catch (error: any) {
|
||||
if (spinner) spinner.fail('Fork failed')
|
||||
console.error(chalk.red('Error:'), error.message)
|
||||
if (options.verbose) console.error(error)
|
||||
process.exit(1)
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* List all branches/forks
|
||||
*/
|
||||
async branchList(options: CoreOptions) {
|
||||
try {
|
||||
const brain = getBrainy()
|
||||
await brain.init()
|
||||
|
||||
const branches = await brain.listBranches()
|
||||
const currentBranch = await brain.getCurrentBranch()
|
||||
|
||||
console.log(chalk.cyan('\nBranches:'))
|
||||
|
||||
for (const branch of branches) {
|
||||
const isCurrent = branch === currentBranch
|
||||
const marker = isCurrent ? chalk.green('*') : ' '
|
||||
const name = isCurrent ? chalk.green(branch) : branch
|
||||
|
||||
// Branch-info enrichment (last-commit timestamp, etc.) requires a
|
||||
// refManager accessor that brainy hasn't surfaced on the public
|
||||
// storage adapter yet. CLI shows the bare branch name for now.
|
||||
console.log(` ${marker} ${name}`)
|
||||
}
|
||||
|
||||
console.log()
|
||||
|
||||
if (options.json) {
|
||||
formatOutput({
|
||||
branches,
|
||||
currentBranch
|
||||
}, options)
|
||||
}
|
||||
|
||||
} catch (error: any) {
|
||||
console.error(chalk.red('Error:'), error.message)
|
||||
if (options.verbose) console.error(error)
|
||||
process.exit(1)
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Switch to a different branch
|
||||
*/
|
||||
async checkout(branch: string | undefined, options: CoreOptions) {
|
||||
let spinner: any = null
|
||||
try {
|
||||
const brain = getBrainy()
|
||||
await brain.init()
|
||||
|
||||
// Interactive mode if no branch provided
|
||||
if (!branch) {
|
||||
const branches = await brain.listBranches()
|
||||
const currentBranch = await brain.getCurrentBranch()
|
||||
|
||||
const { selected } = await inquirer.prompt([
|
||||
{
|
||||
type: 'list',
|
||||
name: 'selected',
|
||||
message: 'Select branch:',
|
||||
choices: branches.map(b => ({
|
||||
name: b === currentBranch ? `${b} (current)` : b,
|
||||
value: b
|
||||
}))
|
||||
}
|
||||
])
|
||||
branch = selected
|
||||
}
|
||||
|
||||
const currentBranch = await brain.getCurrentBranch()
|
||||
|
||||
if (branch === currentBranch) {
|
||||
console.log(chalk.yellow(`Already on branch '${branch}'`))
|
||||
return
|
||||
}
|
||||
|
||||
spinner = ora(`Switching to ${chalk.cyan(branch)}...`).start()
|
||||
|
||||
await brain.checkout(branch!)
|
||||
|
||||
spinner.succeed(`Switched to branch ${chalk.green(branch)}`)
|
||||
|
||||
if (options.json) {
|
||||
formatOutput({ branch }, options)
|
||||
}
|
||||
|
||||
} catch (error: any) {
|
||||
if (spinner) spinner.fail('Checkout failed')
|
||||
console.error(chalk.red('Error:'), error.message)
|
||||
if (options.verbose) console.error(error)
|
||||
process.exit(1)
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Delete a branch/fork
|
||||
*/
|
||||
async branchDelete(branch: string | undefined, options: CoreOptions & { force?: boolean }) {
|
||||
try {
|
||||
const brain = getBrainy()
|
||||
await brain.init()
|
||||
|
||||
// Interactive mode if no branch provided
|
||||
if (!branch) {
|
||||
const branches = await brain.listBranches()
|
||||
const currentBranch = await brain.getCurrentBranch()
|
||||
|
||||
const { selected } = await inquirer.prompt([
|
||||
{
|
||||
type: 'list',
|
||||
name: 'selected',
|
||||
message: 'Select branch to delete:',
|
||||
choices: branches
|
||||
.filter(b => b !== currentBranch) // Can't delete current
|
||||
.map(b => ({ name: b, value: b }))
|
||||
}
|
||||
])
|
||||
branch = selected
|
||||
}
|
||||
|
||||
// Confirm deletion
|
||||
if (!options.force) {
|
||||
const { confirm } = await inquirer.prompt([
|
||||
{
|
||||
type: 'confirm',
|
||||
name: 'confirm',
|
||||
message: `Delete branch '${branch}'? This cannot be undone.`,
|
||||
default: false
|
||||
}
|
||||
])
|
||||
|
||||
if (!confirm) {
|
||||
console.log(chalk.yellow('Deletion cancelled'))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const spinner = ora(`Deleting branch ${chalk.red(branch)}...`).start()
|
||||
|
||||
await brain.deleteBranch(branch!)
|
||||
|
||||
spinner.succeed(`Deleted branch ${chalk.red(branch)}`)
|
||||
|
||||
if (options.json) {
|
||||
formatOutput({ deleted: branch }, options)
|
||||
}
|
||||
|
||||
} catch (error: any) {
|
||||
console.error(chalk.red('Error:'), error.message)
|
||||
if (options.verbose) console.error(error)
|
||||
process.exit(1)
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* View commit history
|
||||
*/
|
||||
async history(options: CoreOptions & { limit?: string }) {
|
||||
try {
|
||||
const brain = getBrainy()
|
||||
await brain.init()
|
||||
|
||||
const limit = options.limit ? parseInt(options.limit) : 10
|
||||
|
||||
const history = await brain.getHistory({ limit })
|
||||
|
||||
console.log(chalk.cyan(`\nCommit History (last ${limit}):\n`))
|
||||
|
||||
for (const commit of history) {
|
||||
const date = new Date(commit.timestamp)
|
||||
const age = formatAge(Date.now() - commit.timestamp)
|
||||
|
||||
console.log(
|
||||
`${chalk.yellow(commit.hash.substring(0, 8))} ` +
|
||||
`${chalk.dim(commit.message)} ` +
|
||||
`${chalk.dim(`by ${commit.author} (${age} ago)`)}`
|
||||
)
|
||||
}
|
||||
|
||||
console.log()
|
||||
|
||||
if (options.json) {
|
||||
formatOutput(history, options)
|
||||
}
|
||||
|
||||
} catch (error: any) {
|
||||
console.error(chalk.red('Error:'), error.message)
|
||||
if (options.verbose) console.error(error)
|
||||
process.exit(1)
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Migrate storage format (one-time)
|
||||
*/
|
||||
async migrate(options: MigrateOptions) {
|
||||
let spinner: any = null
|
||||
try {
|
||||
// Interactive mode if paths not provided
|
||||
let fromPath = options.from
|
||||
let toPath = options.to
|
||||
|
||||
if (!fromPath || !toPath) {
|
||||
const answers = await inquirer.prompt([
|
||||
{
|
||||
type: 'input',
|
||||
name: 'from',
|
||||
message: 'Old Brainy data path (v4.x):',
|
||||
default: './brainy-data',
|
||||
when: !fromPath
|
||||
},
|
||||
{
|
||||
type: 'input',
|
||||
name: 'to',
|
||||
message: 'New Brainy data path (v5.0.0):',
|
||||
default: './brainy-data-v5',
|
||||
when: !toPath
|
||||
},
|
||||
{
|
||||
type: 'confirm',
|
||||
name: 'backup',
|
||||
message: 'Create backup before migration?',
|
||||
default: true,
|
||||
when: options.backup === undefined
|
||||
}
|
||||
])
|
||||
|
||||
fromPath = fromPath || answers.from
|
||||
toPath = toPath || answers.to
|
||||
options.backup = options.backup ?? answers.backup
|
||||
}
|
||||
|
||||
// Verify old data exists
|
||||
if (!existsSync(resolve(fromPath!))) {
|
||||
throw new Error(`Old data path not found: ${fromPath}`)
|
||||
}
|
||||
|
||||
// Create backup if requested
|
||||
if (options.backup) {
|
||||
const backupPath = `${fromPath}.backup-${Date.now()}`
|
||||
spinner = ora(`Creating backup: ${backupPath}...`).start()
|
||||
const fs = await import('node:fs/promises')
|
||||
await fs.cp(fromPath, backupPath, { recursive: true, force: false })
|
||||
spinner.succeed(`Backup created: ${chalk.green(backupPath)}`)
|
||||
}
|
||||
|
||||
if (options.dryRun) {
|
||||
console.log(chalk.yellow('\n[DRY RUN] Migration plan:'))
|
||||
console.log(` From: ${fromPath}`)
|
||||
console.log(` To: ${toPath}`)
|
||||
console.log(` Backup: ${options.backup ? 'Yes' : 'No'}`)
|
||||
console.log()
|
||||
return
|
||||
}
|
||||
|
||||
spinner = ora('Migrating to v5.0.0 COW format...').start()
|
||||
|
||||
// Load old brain (v4.x)
|
||||
const oldBrain = new Brainy({
|
||||
storage: {
|
||||
type: 'filesystem',
|
||||
options: { path: fromPath }
|
||||
}
|
||||
})
|
||||
|
||||
await oldBrain.init()
|
||||
|
||||
// Create new brain
|
||||
const newBrain = new Brainy({
|
||||
storage: {
|
||||
type: 'filesystem',
|
||||
options: { path: toPath }
|
||||
}
|
||||
})
|
||||
|
||||
await newBrain.init()
|
||||
|
||||
// Migrate all entities
|
||||
const entities = await oldBrain.find({})
|
||||
let migrated = 0
|
||||
|
||||
spinner.text = `Migrating entities (0/${entities.length})...`
|
||||
|
||||
for (const result of entities) {
|
||||
// Add entity with proper params
|
||||
await newBrain.add({
|
||||
type: result.entity.type as any,
|
||||
data: result.entity.data
|
||||
})
|
||||
migrated++
|
||||
|
||||
if (migrated % 100 === 0) {
|
||||
spinner.text = `Migrating entities (${migrated}/${entities.length})...`
|
||||
}
|
||||
}
|
||||
|
||||
// Create initial commit (will be available after COW integration)
|
||||
// await newBrain.commit({
|
||||
// message: `Migrated from v4.x (${entities.length} entities)`,
|
||||
// author: 'migration-tool'
|
||||
// })
|
||||
|
||||
spinner.succeed(`Migration complete: ${chalk.green(migrated)} entities`)
|
||||
|
||||
console.log(`
|
||||
${chalk.cyan('Migration Summary:')}
|
||||
${chalk.dim('Old path:')} ${fromPath}
|
||||
${chalk.dim('New path:')} ${toPath}
|
||||
${chalk.dim('Entities:')} ${migrated}
|
||||
${chalk.dim('Format:')} v5.0.0 COW
|
||||
`.trim())
|
||||
|
||||
if (options.json) {
|
||||
formatOutput({
|
||||
from: fromPath,
|
||||
to: toPath,
|
||||
migrated
|
||||
}, options)
|
||||
}
|
||||
|
||||
await oldBrain.close()
|
||||
await newBrain.close()
|
||||
|
||||
} catch (error: any) {
|
||||
if (spinner) spinner.fail('Migration failed')
|
||||
console.error(chalk.red('Error:'), error.message)
|
||||
if (options.verbose) console.error(error)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format timestamp age
|
||||
*/
|
||||
function formatAge(ms: number): string {
|
||||
const seconds = Math.floor(ms / 1000)
|
||||
const minutes = Math.floor(seconds / 60)
|
||||
const hours = Math.floor(minutes / 60)
|
||||
const days = Math.floor(hours / 24)
|
||||
|
||||
if (days > 0) return `${days}d`
|
||||
if (hours > 0) return `${hours}h`
|
||||
if (minutes > 0) return `${minutes}m`
|
||||
return `${seconds}s`
|
||||
}
|
||||
227
src/cli/commands/snapshot.ts
Normal file
227
src/cli/commands/snapshot.ts
Normal file
|
|
@ -0,0 +1,227 @@
|
|||
/**
|
||||
* @module cli/commands/snapshot
|
||||
* @description Snapshot & time-travel CLI commands over the 8.0 Db API.
|
||||
*
|
||||
* - `snapshot <path>` — persist the current generation as a self-contained,
|
||||
* hard-link snapshot directory (`brain.now().persist(path)`).
|
||||
* - `restore <path>` — replace the store's ENTIRE state from a snapshot
|
||||
* (`brain.restore(path, { confirm: true })`, after an interactive confirm).
|
||||
* - `history` — the reified transaction log: one line per committed
|
||||
* `transact()` batch (generation, commit time, metadata).
|
||||
* - `generation` — the store's current generation watermark.
|
||||
*/
|
||||
|
||||
import chalk from 'chalk'
|
||||
import ora from 'ora'
|
||||
import inquirer from 'inquirer'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import { Brainy } from '../../brainy.js'
|
||||
|
||||
/**
|
||||
* @description Shared CLI flags every snapshot command accepts (`--verbose`,
|
||||
* `--json`, `--pretty`), mirroring the other command modules.
|
||||
*/
|
||||
interface SnapshotCliOptions {
|
||||
verbose?: boolean
|
||||
json?: boolean
|
||||
pretty?: boolean
|
||||
}
|
||||
|
||||
let brainyInstance: Brainy | null = null
|
||||
|
||||
const getBrainy = (): Brainy => {
|
||||
if (!brainyInstance) {
|
||||
brainyInstance = new Brainy()
|
||||
}
|
||||
return brainyInstance
|
||||
}
|
||||
|
||||
const formatOutput = (data: unknown, options: SnapshotCliOptions): void => {
|
||||
if (options.json) {
|
||||
console.log(options.pretty ? JSON.stringify(data, null, 2) : JSON.stringify(data))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description The `snapshot`/`restore`/`history`/`generation` command
|
||||
* handlers registered in `src/cli/index.ts`.
|
||||
*/
|
||||
export const snapshotCommands = {
|
||||
/**
|
||||
* @description Persist the current generation as a self-contained snapshot
|
||||
* directory. Instant on same-device targets (hard links); the result opens
|
||||
* with `Brainy.load(path)` or restores wholesale via `brainy restore`.
|
||||
* @param path - Target directory (created; must be empty or absent).
|
||||
* @param options - Shared CLI flags.
|
||||
*/
|
||||
async snapshot(path: string, options: SnapshotCliOptions) {
|
||||
let spinner: ReturnType<typeof ora> | null = null
|
||||
try {
|
||||
const brain = getBrainy()
|
||||
await brain.init()
|
||||
|
||||
const target = resolve(path)
|
||||
spinner = ora(`Persisting snapshot to ${chalk.cyan(target)}...`).start()
|
||||
|
||||
const startTime = Date.now()
|
||||
const db = brain.now()
|
||||
try {
|
||||
await db.persist(target)
|
||||
} finally {
|
||||
await db.release()
|
||||
}
|
||||
const elapsed = Date.now() - startTime
|
||||
|
||||
spinner.succeed(
|
||||
`Snapshot persisted: ${chalk.green(target)} ${chalk.dim(`(generation ${db.generation}, ${elapsed}ms)`)}`
|
||||
)
|
||||
console.log(`
|
||||
${chalk.cyan('Snapshot:')}
|
||||
${chalk.dim('Path:')} ${target}
|
||||
${chalk.dim('Generation:')} ${db.generation}
|
||||
${chalk.dim('Open with:')} Brainy.load('${target}')
|
||||
${chalk.dim('Restore with:')} brainy restore ${target}
|
||||
`.trim())
|
||||
|
||||
formatOutput({ path: target, generation: db.generation, time: elapsed }, options)
|
||||
} catch (error: any) {
|
||||
if (spinner) spinner.fail('Snapshot failed')
|
||||
console.error(chalk.red('Error:'), error.message)
|
||||
if (options.verbose) console.error(error)
|
||||
process.exit(1)
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* @description Replace the store's ENTIRE current state from a snapshot
|
||||
* directory. Destructive — asks for interactive confirmation first
|
||||
* (skipped with `--force`).
|
||||
* @param path - Snapshot directory produced by `brainy snapshot <path>`.
|
||||
* @param options - Shared CLI flags plus `--force`.
|
||||
*/
|
||||
async restore(path: string, options: SnapshotCliOptions & { force?: boolean }) {
|
||||
let spinner: ReturnType<typeof ora> | null = null
|
||||
try {
|
||||
const target = resolve(path)
|
||||
if (!existsSync(target)) {
|
||||
throw new Error(`Snapshot directory not found: ${target}`)
|
||||
}
|
||||
|
||||
if (!options.force) {
|
||||
const { confirm } = await inquirer.prompt([
|
||||
{
|
||||
type: 'confirm',
|
||||
name: 'confirm',
|
||||
message: `Replace the store's ENTIRE current state with the snapshot at '${target}'? This cannot be undone.`,
|
||||
default: false
|
||||
}
|
||||
])
|
||||
if (!confirm) {
|
||||
console.log(chalk.yellow('Restore cancelled'))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const brain = getBrainy()
|
||||
await brain.init()
|
||||
|
||||
spinner = ora(`Restoring from ${chalk.cyan(target)}...`).start()
|
||||
const startTime = Date.now()
|
||||
await brain.restore(target, { confirm: true })
|
||||
const elapsed = Date.now() - startTime
|
||||
|
||||
spinner.succeed(
|
||||
`Restored from ${chalk.green(target)} ${chalk.dim(`(now at generation ${brain.generation()}, ${elapsed}ms)`)}`
|
||||
)
|
||||
|
||||
formatOutput({ path: target, generation: brain.generation(), time: elapsed }, options)
|
||||
} catch (error: any) {
|
||||
if (spinner) spinner.fail('Restore failed')
|
||||
console.error(chalk.red('Error:'), error.message)
|
||||
if (options.verbose) console.error(error)
|
||||
process.exit(1)
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* @description Show the reified transaction log, newest first: one entry
|
||||
* per committed `transact()` batch with its generation, commit time, and
|
||||
* the `meta` the transaction was submitted with.
|
||||
* @param options - Shared CLI flags plus `--limit`.
|
||||
*/
|
||||
async history(options: SnapshotCliOptions & { limit?: string }) {
|
||||
try {
|
||||
const brain = getBrainy()
|
||||
await brain.init()
|
||||
|
||||
const limit = options.limit ? parseInt(options.limit, 10) : 10
|
||||
const entries = await brain.transactionLog({ limit })
|
||||
|
||||
if (entries.length === 0) {
|
||||
console.log(chalk.yellow('\nNo committed transactions yet (the log records transact() batches).\n'))
|
||||
formatOutput([], options)
|
||||
return
|
||||
}
|
||||
|
||||
console.log(chalk.cyan(`\nTransaction Log (last ${entries.length}):\n`))
|
||||
for (const entry of entries) {
|
||||
const age = formatAge(Date.now() - entry.timestamp)
|
||||
const meta = entry.meta ? ` ${chalk.dim(JSON.stringify(entry.meta))}` : ''
|
||||
console.log(
|
||||
`${chalk.yellow(`g${entry.generation}`)} ` +
|
||||
`${chalk.dim(new Date(entry.timestamp).toISOString())} ` +
|
||||
`${chalk.dim(`(${age} ago)`)}` +
|
||||
meta
|
||||
)
|
||||
}
|
||||
console.log()
|
||||
|
||||
formatOutput(entries, options)
|
||||
} catch (error: any) {
|
||||
console.error(chalk.red('Error:'), error.message)
|
||||
if (options.verbose) console.error(error)
|
||||
process.exit(1)
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* @description Print the store's current generation watermark (bumped once
|
||||
* per committed `transact()` batch and once per single-operation write
|
||||
* batch).
|
||||
* @param options - Shared CLI flags.
|
||||
*/
|
||||
async generation(options: SnapshotCliOptions) {
|
||||
try {
|
||||
const brain = getBrainy()
|
||||
await brain.init()
|
||||
|
||||
const generation = brain.generation()
|
||||
console.log(`${chalk.cyan('Generation:')} ${chalk.green(String(generation))}`)
|
||||
|
||||
formatOutput({ generation }, options)
|
||||
} catch (error: any) {
|
||||
console.error(chalk.red('Error:'), error.message)
|
||||
if (options.verbose) console.error(error)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Format a millisecond duration as a compact age string
|
||||
* (`3d` / `5h` / `12m` / `42s`).
|
||||
* @param ms - Elapsed milliseconds.
|
||||
* @returns The compact age string.
|
||||
*/
|
||||
function formatAge(ms: number): string {
|
||||
const seconds = Math.floor(ms / 1000)
|
||||
const minutes = Math.floor(seconds / 60)
|
||||
const hours = Math.floor(minutes / 60)
|
||||
const days = Math.floor(hours / 24)
|
||||
|
||||
if (days > 0) return `${days}d`
|
||||
if (hours > 0) return `${hours}h`
|
||||
if (minutes > 0) return `${minutes}m`
|
||||
return `${seconds}s`
|
||||
}
|
||||
|
|
@ -17,7 +17,7 @@ import { storageCommands } from './commands/storage.js'
|
|||
import { nlpCommands } from './commands/nlp.js'
|
||||
import { insightsCommands } from './commands/insights.js'
|
||||
import { importCommands } from './commands/import.js'
|
||||
import { cowCommands } from './commands/cow.js'
|
||||
import { snapshotCommands } from './commands/snapshot.js'
|
||||
import { inspectCommands } from './commands/inspect.js'
|
||||
import { readFileSync } from 'fs'
|
||||
import { fileURLToPath } from 'url'
|
||||
|
|
@ -760,58 +760,30 @@ program
|
|||
.option('--iterations <n>', 'Number of iterations', '100')
|
||||
.action(utilityCommands.benchmark)
|
||||
|
||||
// ===== COW Commands - Instant Fork & Branching =====
|
||||
// ===== Snapshot & Time-Travel Commands - Db API =====
|
||||
|
||||
program
|
||||
.command('fork [name]')
|
||||
.description('🚀 Fork the brain (instant clone in 1-2 seconds)')
|
||||
.option('--message <msg>', 'Commit message')
|
||||
.option('--author <name>', 'Author name')
|
||||
.action(cowCommands.fork)
|
||||
.command('snapshot <path>')
|
||||
.description('📸 Persist the current generation as a self-contained snapshot (instant hard links)')
|
||||
.action(snapshotCommands.snapshot)
|
||||
|
||||
program
|
||||
.command('branch')
|
||||
.description('🌿 Branch management')
|
||||
.addCommand(
|
||||
new Command('list')
|
||||
.alias('ls')
|
||||
.description('List all branches/forks')
|
||||
.action((options) => {
|
||||
cowCommands.branchList(options)
|
||||
})
|
||||
)
|
||||
.addCommand(
|
||||
new Command('delete')
|
||||
.alias('rm')
|
||||
.argument('[name]', 'Branch name to delete')
|
||||
.description('Delete a branch/fork')
|
||||
.option('-f, --force', 'Skip confirmation')
|
||||
.action((name, options) => {
|
||||
cowCommands.branchDelete(name, options)
|
||||
})
|
||||
)
|
||||
|
||||
program
|
||||
.command('checkout [branch]')
|
||||
.alias('co')
|
||||
.description('Switch to a different branch')
|
||||
.action(cowCommands.checkout)
|
||||
.command('restore <path>')
|
||||
.description('Replace the ENTIRE store state from a snapshot (asks for confirmation)')
|
||||
.option('-f, --force', 'Skip confirmation')
|
||||
.action(snapshotCommands.restore)
|
||||
|
||||
program
|
||||
.command('history')
|
||||
.alias('log')
|
||||
.description('Show commit history')
|
||||
.option('-l, --limit <number>', 'Number of commits to show', '10')
|
||||
.action(cowCommands.history)
|
||||
.description('Show the transaction log (one entry per committed transact() batch)')
|
||||
.option('-l, --limit <number>', 'Number of entries to show', '10')
|
||||
.action(snapshotCommands.history)
|
||||
|
||||
program
|
||||
.command('migrate')
|
||||
.description('🔄 Migrate from v4.x to v5.0.0 (one-time)')
|
||||
.option('--from <path>', 'Old Brainy data path (v4.x)')
|
||||
.option('--to <path>', 'New Brainy data path (v5.0.0)')
|
||||
.option('--backup', 'Create backup before migration')
|
||||
.option('--dry-run', 'Show migration plan without executing')
|
||||
.action(cowCommands.migrate)
|
||||
.command('generation')
|
||||
.description('Show the store\'s current generation watermark')
|
||||
.action(snapshotCommands.generation)
|
||||
|
||||
// ===== Interactive Mode =====
|
||||
|
||||
|
|
|
|||
|
|
@ -621,8 +621,27 @@ export class GenerationStore {
|
|||
async resolveTimestamp(
|
||||
timestampMs: number
|
||||
): Promise<{ generation: number; entry: TxLogEntry | null }> {
|
||||
const lines = await this.storage.readTxLogLines()
|
||||
let best: TxLogEntry | null = null
|
||||
for (const entry of await this.txLog()) {
|
||||
if (entry.timestamp <= timestampMs) {
|
||||
if (best === null || entry.generation > best.generation) best = entry
|
||||
}
|
||||
}
|
||||
return { generation: best?.generation ?? 0, entry: best }
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Read all committed tx-log entries, oldest first. Torn
|
||||
* trailing lines from a crashed append are tolerated and skipped, and
|
||||
* entries beyond the committed watermark are excluded — the tx-log is
|
||||
* advisory metadata; the manifest rename is the source of commit truth.
|
||||
* Compaction never rewrites the log, so entries may reference generations
|
||||
* whose record-sets were already reclaimed.
|
||||
* @returns Every committed {@link TxLogEntry}, in commit order.
|
||||
*/
|
||||
async txLog(): Promise<TxLogEntry[]> {
|
||||
const lines = await this.storage.readTxLogLines()
|
||||
const entries: TxLogEntry[] = []
|
||||
for (const line of lines) {
|
||||
let entry: TxLogEntry
|
||||
try {
|
||||
|
|
@ -630,11 +649,9 @@ export class GenerationStore {
|
|||
} catch {
|
||||
continue // tolerate a torn trailing line from a crashed append
|
||||
}
|
||||
if (entry.timestamp <= timestampMs && entry.generation <= this.committed) {
|
||||
if (best === null || entry.generation > best.generation) best = entry
|
||||
}
|
||||
if (entry.generation <= this.committed) entries.push(entry)
|
||||
}
|
||||
return { generation: best?.generation ?? 0, entry: best }
|
||||
return entries
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -59,10 +59,6 @@ export class JsHnswVectorIndex implements VectorIndexProvider {
|
|||
// save, so the migration converges under live traffic with no big-bang.
|
||||
private connectionsCodec: ConnectionsCodec | null = null
|
||||
|
||||
// COW (Copy-on-Write) support
|
||||
private cowEnabled: boolean = false
|
||||
private cowModifiedNodes: Set<string> = new Set()
|
||||
private cowParent: JsHnswVectorIndex | null = null
|
||||
|
||||
// Deferred HNSW persistence for cloud storage performance
|
||||
// In deferred mode, HNSW connections are only persisted on flush/close
|
||||
|
|
@ -301,99 +297,6 @@ export class JsHnswVectorIndex implements VectorIndexProvider {
|
|||
return this.persistMode
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable COW (Copy-on-Write) mode - Instant fork via shallow copy
|
||||
*
|
||||
* Snowflake-style instant fork: O(1) shallow copy of Maps, lazy deep copy on write.
|
||||
*
|
||||
* @param parent - Parent HNSW index to copy from
|
||||
*
|
||||
* Performance:
|
||||
* - Fork time: <10ms for 1M+ nodes (just copies Map references)
|
||||
* - Memory: Shared reads, only modified nodes duplicated (~10-20% overhead)
|
||||
* - Reads: Same speed as parent (shared data structures)
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const parent = new JsHnswVectorIndex(config)
|
||||
* // ... parent has 1M nodes ...
|
||||
*
|
||||
* const fork = new JsHnswVectorIndex(config)
|
||||
* fork.enableCOW(parent) // <10ms - instant!
|
||||
*
|
||||
* // Reads share data
|
||||
* await fork.search(query) // Fast, uses parent's data
|
||||
*
|
||||
* // Writes trigger COW
|
||||
* await fork.addItem(newItem) // Deep copies only modified nodes
|
||||
* ```
|
||||
*/
|
||||
public enableCOW(parent: JsHnswVectorIndex): void {
|
||||
this.cowEnabled = true
|
||||
this.cowParent = parent
|
||||
|
||||
// Shallow copy Maps - O(1) per Map, just copies references
|
||||
// All nodes/connections are shared until first write
|
||||
this.nouns = new Map(parent.nouns)
|
||||
this.highLevelNodes = new Map()
|
||||
for (const [level, nodeSet] of parent.highLevelNodes.entries()) {
|
||||
this.highLevelNodes.set(level, new Set(nodeSet))
|
||||
}
|
||||
|
||||
// Copy scalar values
|
||||
this.entryPointId = parent.entryPointId
|
||||
this.maxLevel = parent.maxLevel
|
||||
this.dimension = parent.dimension
|
||||
|
||||
// Share cache (COW at cache level)
|
||||
this.unifiedCache = parent.unifiedCache
|
||||
|
||||
// Share config and distance function
|
||||
this.config = parent.config
|
||||
this.distanceFunction = parent.distanceFunction
|
||||
this.useParallelization = parent.useParallelization
|
||||
|
||||
prodLog.info(`HNSW COW enabled: ${parent.nouns.size} nodes shallow copied`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure node is copied before modification (lazy COW)
|
||||
*
|
||||
* Deep copies a node only when first modified. Subsequent modifications
|
||||
* use the already-copied node.
|
||||
*
|
||||
* @param nodeId - Node ID to ensure is copied
|
||||
* @private
|
||||
*/
|
||||
private ensureCOW(nodeId: string): void {
|
||||
if (!this.cowEnabled) return
|
||||
if (this.cowModifiedNodes.has(nodeId)) return // Already copied
|
||||
|
||||
const original = this.nouns.get(nodeId)
|
||||
if (!original) return
|
||||
|
||||
// Deep copy connections Map (separate Map + Sets for each level)
|
||||
const connectionsCopy = new Map<number, Set<string>>()
|
||||
for (const [level, ids] of original.connections.entries()) {
|
||||
connectionsCopy.set(level, new Set(ids))
|
||||
}
|
||||
|
||||
// Deep copy node
|
||||
const nodeCopy: HNSWNoun = {
|
||||
id: original.id,
|
||||
vector: [...original.vector], // Deep copy vector array
|
||||
connections: connectionsCopy,
|
||||
level: original.level,
|
||||
// Copy SQ8 quantized data if present
|
||||
quantizedVector: original.quantizedVector ? new Uint8Array(original.quantizedVector) : undefined,
|
||||
codebookMin: original.codebookMin,
|
||||
codebookMax: original.codebookMax
|
||||
}
|
||||
|
||||
this.nouns.set(nodeId, nodeCopy)
|
||||
this.cowModifiedNodes.add(nodeId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate distances between a query vector and multiple vectors in parallel
|
||||
* This is used to optimize performance for search operations
|
||||
|
|
@ -602,8 +505,6 @@ export class JsHnswVectorIndex implements VectorIndexProvider {
|
|||
continue
|
||||
}
|
||||
|
||||
// COW: Ensure neighbor is copied before modification
|
||||
this.ensureCOW(neighborId)
|
||||
|
||||
noun.connections.get(level)!.add(neighborId)
|
||||
|
||||
|
|
@ -965,16 +866,12 @@ export class JsHnswVectorIndex implements VectorIndexProvider {
|
|||
return false
|
||||
}
|
||||
|
||||
// COW: Ensure node is copied before modification
|
||||
this.ensureCOW(id)
|
||||
|
||||
const noun = this.nouns.get(id)!
|
||||
|
||||
// Remove connections to this noun from all neighbors
|
||||
for (const [level, connections] of noun.connections.entries()) {
|
||||
for (const neighborId of connections) {
|
||||
// COW: Ensure neighbor is copied before modification
|
||||
this.ensureCOW(neighborId)
|
||||
|
||||
const neighbor = this.nouns.get(neighborId)
|
||||
if (!neighbor) {
|
||||
|
|
@ -994,8 +891,6 @@ export class JsHnswVectorIndex implements VectorIndexProvider {
|
|||
for (const [nounId, otherNoun] of this.nouns.entries()) {
|
||||
if (nounId === id) continue // Skip the noun being removed
|
||||
|
||||
// COW: Ensure noun is copied before modification
|
||||
this.ensureCOW(nounId)
|
||||
|
||||
for (const [level, connections] of otherNoun.connections.entries()) {
|
||||
if (connections.has(id)) {
|
||||
|
|
@ -1881,8 +1776,6 @@ export class JsHnswVectorIndex implements VectorIndexProvider {
|
|||
* Ensure a noun doesn't have too many connections at a given level
|
||||
*/
|
||||
private async pruneConnections(noun: HNSWNoun, level: number): Promise<void> {
|
||||
// COW: Ensure noun is copied before modification
|
||||
this.ensureCOW(noun.id)
|
||||
|
||||
const connections = noun.connections.get(level)!
|
||||
if (connections.size <= this.config.M) {
|
||||
|
|
|
|||
|
|
@ -1,763 +0,0 @@
|
|||
/**
|
||||
* Type-Aware HNSW Index - Phase 2 Billion-Scale Optimization
|
||||
*
|
||||
* Maintains separate HNSW graphs per entity type for massive memory savings:
|
||||
* - Memory @ 1B scale: PROJECTED 384GB → 50GB (-87% from architectural analysis, not yet benchmarked)
|
||||
* - Query speed: PROJECTED 10x faster for single-type queries (not yet benchmarked)
|
||||
* - Storage: Already type-first from Phase 1a
|
||||
*
|
||||
* Architecture:
|
||||
* - One JsHnswVectorIndex per NounType (42 total)
|
||||
* - Lazy initialization (indexes created on first use)
|
||||
* - Type routing for optimal performance
|
||||
* - Falls back to multi-type search when type unknown
|
||||
*/
|
||||
|
||||
import { JsHnswVectorIndex } from './hnswIndex.js'
|
||||
import {
|
||||
DistanceFunction,
|
||||
HNSWConfig,
|
||||
Vector,
|
||||
VectorDocument
|
||||
} from '../coreTypes.js'
|
||||
import { NounType, NOUN_TYPE_COUNT, TypeUtils } from '../types/graphTypes.js'
|
||||
import { euclideanDistance } from '../utils/index.js'
|
||||
import type { BaseStorage } from '../storage/baseStorage.js'
|
||||
import { prodLog } from '../utils/logger.js'
|
||||
|
||||
// Default HNSW parameters (same as JsHnswVectorIndex)
|
||||
const DEFAULT_CONFIG: HNSWConfig = {
|
||||
M: 16,
|
||||
efConstruction: 200,
|
||||
efSearch: 50,
|
||||
ml: 16
|
||||
}
|
||||
|
||||
/**
|
||||
* Type-aware HNSW statistics
|
||||
*/
|
||||
export interface TypeAwareHNSWStats {
|
||||
totalNodes: number
|
||||
totalMemoryMB: number
|
||||
typeCount: number
|
||||
typeStats: Map<NounType, {
|
||||
nodeCount: number
|
||||
memoryMB: number
|
||||
maxLevel: number
|
||||
entryPointId: string | null
|
||||
}>
|
||||
memoryReductionPercent: number
|
||||
estimatedMonolithicMemoryMB: number
|
||||
}
|
||||
|
||||
/**
|
||||
* TypeAwareHNSWIndex - Separate HNSW graphs per entity type
|
||||
*
|
||||
* Phase 2 of billion-scale optimization roadmap.
|
||||
* PROJECTED: Reduces HNSW memory by 87% @ billion scale (calculated from architecture, not yet benchmarked).
|
||||
*/
|
||||
export class TypeAwareHNSWIndex {
|
||||
// One HNSW index per noun type (lazy initialization)
|
||||
private indexes: Map<NounType, JsHnswVectorIndex> = new Map()
|
||||
|
||||
// Configuration
|
||||
private config: HNSWConfig
|
||||
private distanceFunction: DistanceFunction
|
||||
private storage: BaseStorage | null
|
||||
private useParallelization: boolean
|
||||
private persistMode: 'immediate' | 'deferred'
|
||||
|
||||
/**
|
||||
* Create a new TypeAwareHNSWIndex
|
||||
*
|
||||
* @param config HNSW configuration (M, efConstruction, efSearch, ml)
|
||||
* @param distanceFunction Distance function (default: euclidean)
|
||||
* @param options Additional options (storage, parallelization, persistMode)
|
||||
*/
|
||||
constructor(
|
||||
config: Partial<HNSWConfig> = {},
|
||||
distanceFunction: DistanceFunction = euclideanDistance,
|
||||
options: { useParallelization?: boolean; storage?: BaseStorage; persistMode?: 'immediate' | 'deferred' } = {}
|
||||
) {
|
||||
this.config = { ...DEFAULT_CONFIG, ...config }
|
||||
this.distanceFunction = distanceFunction
|
||||
this.storage = options.storage || null
|
||||
this.useParallelization =
|
||||
options.useParallelization !== undefined
|
||||
? options.useParallelization
|
||||
: true
|
||||
this.persistMode = options.persistMode || 'immediate'
|
||||
|
||||
prodLog.info('TypeAwareHNSWIndex initialized (Phase 2: Type-Aware HNSW)')
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable COW (Copy-on-Write) mode - Instant fork via shallow copy
|
||||
*
|
||||
* Propagates enableCOW() to all underlying type-specific HNSW indexes.
|
||||
* Each index performs O(1) shallow copy of its own data structures.
|
||||
*
|
||||
* @param parent - Parent TypeAwareHNSWIndex to copy from
|
||||
*/
|
||||
public enableCOW(parent: TypeAwareHNSWIndex): void {
|
||||
// Shallow copy indexes Map
|
||||
this.indexes = new Map(parent.indexes)
|
||||
|
||||
// Enable COW on each underlying type-specific index
|
||||
for (const [type, parentIndex] of parent.indexes.entries()) {
|
||||
const childIndex = new JsHnswVectorIndex(this.config, this.distanceFunction, {
|
||||
useParallelization: this.useParallelization,
|
||||
storage: this.storage || undefined,
|
||||
persistMode: this.persistMode
|
||||
})
|
||||
childIndex.enableCOW(parentIndex)
|
||||
this.indexes.set(type, childIndex)
|
||||
}
|
||||
|
||||
prodLog.info(`TypeAwareHNSWIndex COW enabled: ${parent.indexes.size} type-specific indexes shallow copied`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush dirty HNSW data to storage for all type-specific indexes
|
||||
*
|
||||
* In deferred persistence mode, HNSW connections are tracked as dirty but not
|
||||
* immediately persisted. Call flush() to persist all pending changes across
|
||||
* all type-specific indexes.
|
||||
*
|
||||
* @returns Total number of nodes flushed across all indexes
|
||||
*/
|
||||
public async flush(): Promise<number> {
|
||||
if (this.indexes.size === 0) {
|
||||
return 0
|
||||
}
|
||||
|
||||
const flushPromises = Array.from(this.indexes.values()).map(index =>
|
||||
index.flush()
|
||||
)
|
||||
|
||||
const results = await Promise.all(flushPromises)
|
||||
const totalFlushed = results.reduce((sum, count) => sum + count, 0)
|
||||
|
||||
if (totalFlushed > 0) {
|
||||
prodLog.info(`[TypeAwareHNSW] Flushed ${totalFlushed} dirty nodes across ${this.indexes.size} type indexes`)
|
||||
}
|
||||
|
||||
return totalFlushed
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the total number of dirty (unpersisted) nodes across all type-specific indexes
|
||||
*/
|
||||
public getDirtyNodeCount(): number {
|
||||
let total = 0
|
||||
for (const index of this.indexes.values()) {
|
||||
total += index.getDirtyNodeCount()
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current persist mode
|
||||
*/
|
||||
public getPersistMode(): 'immediate' | 'deferred' {
|
||||
return this.persistMode
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch persist mode at runtime. Propagates to all existing type-specific indexes.
|
||||
* Used by addMany() to defer persistence during batch operations.
|
||||
*/
|
||||
public setPersistMode(mode: 'immediate' | 'deferred'): void {
|
||||
this.persistMode = mode
|
||||
for (const index of this.indexes.values()) {
|
||||
if (typeof (index as any).setPersistMode === 'function') {
|
||||
(index as any).setPersistMode(mode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get or create HNSW index for a specific type (lazy initialization)
|
||||
*
|
||||
* Indexes are created on-demand to save memory.
|
||||
* Only types with entities get an index.
|
||||
*
|
||||
* @param type The noun type
|
||||
* @returns JsHnswVectorIndex for this type
|
||||
*/
|
||||
private getIndexForType(type: NounType): JsHnswVectorIndex {
|
||||
// Validate type is a valid NounType
|
||||
const typeIndex = TypeUtils.getNounIndex(type)
|
||||
if (typeIndex === undefined || typeIndex === null || typeIndex < 0) {
|
||||
throw new Error(
|
||||
`Invalid NounType: ${type}. Must be one of the 42 defined types.`
|
||||
)
|
||||
}
|
||||
|
||||
if (!this.indexes.has(type)) {
|
||||
prodLog.info(`Creating HNSW index for type: ${type}`)
|
||||
|
||||
const index = new JsHnswVectorIndex(this.config, this.distanceFunction, {
|
||||
useParallelization: this.useParallelization,
|
||||
storage: this.storage || undefined,
|
||||
persistMode: this.persistMode
|
||||
})
|
||||
|
||||
this.indexes.set(type, index)
|
||||
}
|
||||
|
||||
const index = this.indexes.get(type)
|
||||
if (!index) {
|
||||
throw new Error(
|
||||
`Unexpected: Index for type ${type} not found after creation`
|
||||
)
|
||||
}
|
||||
return index
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a vector to the type-aware index
|
||||
*
|
||||
* Routes to the correct type's HNSW graph.
|
||||
*
|
||||
* @param item Vector document to add
|
||||
* @param type The noun type (required for routing)
|
||||
* @returns The item ID
|
||||
*/
|
||||
public async addItem(item: VectorDocument, type: NounType): Promise<string> {
|
||||
if (!item || !item.vector) {
|
||||
throw new Error(
|
||||
'Invalid VectorDocument: item or vector is null/undefined'
|
||||
)
|
||||
}
|
||||
if (!type) {
|
||||
throw new Error('Type is required for type-aware indexing')
|
||||
}
|
||||
|
||||
const index = this.getIndexForType(type)
|
||||
return await index.addItem(item)
|
||||
}
|
||||
|
||||
/**
|
||||
* Search for nearest neighbors (type-aware)
|
||||
*
|
||||
* **Single-type search** (fast path):
|
||||
* ```typescript
|
||||
* await index.search(queryVector, 10, 'person')
|
||||
* // Searches only person graph (100M nodes instead of 1B)
|
||||
* ```
|
||||
*
|
||||
* **Multi-type search**:
|
||||
* ```typescript
|
||||
* await index.search(queryVector, 10, ['person', 'organization'])
|
||||
* // Searches person + organization, merges results
|
||||
* ```
|
||||
*
|
||||
* **All-types search** (fallback):
|
||||
* ```typescript
|
||||
* await index.search(queryVector, 10)
|
||||
* // Searches all 42 graphs (slower but comprehensive)
|
||||
* ```
|
||||
*
|
||||
* @param queryVector Query vector
|
||||
* @param k Number of results
|
||||
* @param type Type or types to search (undefined = all types)
|
||||
* @param filter Optional filter function
|
||||
* @returns Array of [id, distance] tuples sorted by distance
|
||||
*/
|
||||
public async search(
|
||||
queryVector: Vector,
|
||||
k: number = 10,
|
||||
type?: NounType | NounType[],
|
||||
filter?: (id: string) => Promise<boolean>,
|
||||
options?: { rerank?: { multiplier: number }; candidateIds?: string[] }
|
||||
): Promise<Array<[string, number]>> {
|
||||
// Single-type search (fast path)
|
||||
if (type && typeof type === 'string') {
|
||||
const index = this.getIndexForType(type)
|
||||
return await index.search(queryVector, k, filter, options)
|
||||
}
|
||||
|
||||
// Multi-type search (handle empty array edge case)
|
||||
if (type && Array.isArray(type) && type.length > 0) {
|
||||
return await this.searchMultipleTypes(queryVector, k, type, filter, options)
|
||||
}
|
||||
|
||||
// All-types search (slowest path + empty array fallback)
|
||||
return await this.searchAllTypes(queryVector, k, filter, options)
|
||||
}
|
||||
|
||||
/**
|
||||
* Search across multiple specific types
|
||||
*
|
||||
* @param queryVector Query vector
|
||||
* @param k Number of results
|
||||
* @param types Array of types to search
|
||||
* @param filter Optional filter function
|
||||
* @returns Merged and sorted results
|
||||
*/
|
||||
private async searchMultipleTypes(
|
||||
queryVector: Vector,
|
||||
k: number,
|
||||
types: NounType[],
|
||||
filter?: (id: string) => Promise<boolean>,
|
||||
options?: { rerank?: { multiplier: number }; candidateIds?: string[] }
|
||||
): Promise<Array<[string, number]>> {
|
||||
const allResults: Array<[string, number]> = []
|
||||
|
||||
// Search each specified type
|
||||
for (const type of types) {
|
||||
if (this.indexes.has(type)) {
|
||||
const index = this.indexes.get(type)!
|
||||
const results = await index.search(queryVector, k, filter, options)
|
||||
allResults.push(...results)
|
||||
}
|
||||
}
|
||||
|
||||
// Merge and sort by distance
|
||||
allResults.sort((a, b) => a[1] - b[1])
|
||||
|
||||
// Return top k
|
||||
return allResults.slice(0, k)
|
||||
}
|
||||
|
||||
/**
|
||||
* Search across all types (fallback for type-agnostic queries)
|
||||
*
|
||||
* This is the slowest path, but provides comprehensive results.
|
||||
* Used when type cannot be inferred from query.
|
||||
*
|
||||
* @param queryVector Query vector
|
||||
* @param k Number of results
|
||||
* @param filter Optional filter function
|
||||
* @returns Merged and sorted results from all types
|
||||
*/
|
||||
private async searchAllTypes(
|
||||
queryVector: Vector,
|
||||
k: number,
|
||||
filter?: (id: string) => Promise<boolean>,
|
||||
options?: { rerank?: { multiplier: number }; candidateIds?: string[] }
|
||||
): Promise<Array<[string, number]>> {
|
||||
const allResults: Array<[string, number]> = []
|
||||
|
||||
// Search each type's graph
|
||||
for (const [type, index] of this.indexes.entries()) {
|
||||
const results = await index.search(queryVector, k, filter, options)
|
||||
allResults.push(...results)
|
||||
}
|
||||
|
||||
// Merge and sort by distance
|
||||
allResults.sort((a, b) => a[1] - b[1])
|
||||
|
||||
// Return top k
|
||||
return allResults.slice(0, k)
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove an item from the index
|
||||
*
|
||||
* @param id Item ID to remove
|
||||
* @param type The noun type (required for routing)
|
||||
* @returns True if item was removed, false if not found
|
||||
*/
|
||||
public async removeItem(id: string, type: NounType): Promise<boolean> {
|
||||
const index = this.indexes.get(type)
|
||||
if (!index) {
|
||||
return false // Type has no index (no items ever added)
|
||||
}
|
||||
|
||||
return await index.removeItem(id)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get total number of items across all types
|
||||
*
|
||||
* @returns Total item count
|
||||
*/
|
||||
public size(): number {
|
||||
let total = 0
|
||||
for (const index of this.indexes.values()) {
|
||||
total += index.size()
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
/**
|
||||
* Get number of items for a specific type
|
||||
*
|
||||
* @param type The noun type
|
||||
* @returns Item count for this type
|
||||
*/
|
||||
public sizeForType(type: NounType): number {
|
||||
const index = this.indexes.get(type)
|
||||
return index ? index.size() : 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all indexes
|
||||
*/
|
||||
public clear(): void {
|
||||
for (const index of this.indexes.values()) {
|
||||
index.clear()
|
||||
}
|
||||
this.indexes.clear()
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear index for a specific type
|
||||
*
|
||||
* @param type The noun type to clear
|
||||
*/
|
||||
public clearType(type: NounType): void {
|
||||
const index = this.indexes.get(type)
|
||||
if (index) {
|
||||
index.clear()
|
||||
this.indexes.delete(type)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get configuration
|
||||
*
|
||||
* @returns HNSW configuration
|
||||
*/
|
||||
public getConfig(): HNSWConfig {
|
||||
return { ...this.config }
|
||||
}
|
||||
|
||||
/**
|
||||
* Get distance function
|
||||
*
|
||||
* @returns Distance function
|
||||
*/
|
||||
public getDistanceFunction(): DistanceFunction {
|
||||
return this.distanceFunction
|
||||
}
|
||||
|
||||
/**
|
||||
* Set parallelization (applies to all indexes)
|
||||
*
|
||||
* @param useParallelization Whether to use parallelization
|
||||
*/
|
||||
public setUseParallelization(useParallelization: boolean): void {
|
||||
this.useParallelization = useParallelization
|
||||
for (const index of this.indexes.values()) {
|
||||
index.setUseParallelization(useParallelization)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get parallelization setting
|
||||
*
|
||||
* @returns Whether parallelization is enabled
|
||||
*/
|
||||
public getUseParallelization(): boolean {
|
||||
return this.useParallelization
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuild HNSW indexes from storage (type-aware)
|
||||
*
|
||||
* CRITICAL: This implementation uses type-filtered pagination to avoid
|
||||
* loading ALL entities for each type (which would be 42 billion reads @ 1B scale).
|
||||
*
|
||||
* Can rebuild all types or specific types.
|
||||
* Much faster than rebuilding a monolithic index.
|
||||
*
|
||||
* @param options Rebuild options
|
||||
*/
|
||||
public async rebuild(
|
||||
options: {
|
||||
types?: NounType[] // Rebuild specific types (undefined = all types)
|
||||
batchSize?: number // Entities per batch
|
||||
onProgress?: (type: NounType, loaded: number, total: number) => void
|
||||
} = {}
|
||||
): Promise<void> {
|
||||
if (!this.storage) {
|
||||
prodLog.warn('TypeAwareHNSW rebuild skipped: no storage adapter')
|
||||
return
|
||||
}
|
||||
|
||||
const batchSize = options.batchSize || 1000
|
||||
|
||||
// Determine which types to rebuild
|
||||
const typesToRebuild = options.types || this.getAllNounTypes()
|
||||
|
||||
prodLog.info(
|
||||
`Rebuilding ${typesToRebuild.length} type-aware HNSW indexes from persisted data...`
|
||||
)
|
||||
|
||||
// Clear all indexes we're rebuilding
|
||||
for (const type of typesToRebuild) {
|
||||
const index = this.getIndexForType(type)
|
||||
;(index as any).nouns.clear()
|
||||
}
|
||||
|
||||
// Determine preloading strategy (adaptive caching) for entire dataset
|
||||
const stats = await this.storage.getStatistics()
|
||||
const entityCount = stats?.totalNodes || 0
|
||||
const vectorMemory = entityCount * 1536 // 384 dims × 4 bytes
|
||||
|
||||
// Use first index's cache (they all share the same UnifiedCache)
|
||||
const firstIndex = this.getIndexForType(typesToRebuild[0])
|
||||
const cacheStats = (firstIndex as any).unifiedCache.getStats()
|
||||
const availableCache = cacheStats.maxSize * 0.80
|
||||
const shouldPreload = vectorMemory < availableCache
|
||||
|
||||
if (shouldPreload) {
|
||||
prodLog.info(
|
||||
`HNSW: Preloading ${entityCount.toLocaleString()} vectors at init ` +
|
||||
`(${(vectorMemory / 1024 / 1024).toFixed(1)}MB < ${(availableCache / 1024 / 1024).toFixed(1)}MB cache)`
|
||||
)
|
||||
} else {
|
||||
prodLog.info(
|
||||
`HNSW: Adaptive caching for ${entityCount.toLocaleString()} vectors ` +
|
||||
`(${(vectorMemory / 1024 / 1024).toFixed(1)}MB > ${(availableCache / 1024 / 1024).toFixed(1)}MB cache) - loading on-demand`
|
||||
)
|
||||
}
|
||||
|
||||
// Load ALL nouns ONCE and route to correct type indexes
|
||||
// This is O(N) instead of O(42*N) from the previous parallel approach
|
||||
let offset = 0 // Use offset-based pagination instead of cursor (bug fix for infinite loop)
|
||||
let hasMore = true
|
||||
let totalLoaded = 0
|
||||
const loadedByType = new Map<NounType, number>()
|
||||
|
||||
while (hasMore) {
|
||||
const result: {
|
||||
items: Array<{ id: string; vector: number[]; type?: NounType }>
|
||||
hasMore: boolean
|
||||
nextCursor?: string
|
||||
totalCount?: number
|
||||
} = await (this.storage as any).getNounsWithPagination({
|
||||
limit: batchSize,
|
||||
offset // Pass offset for proper pagination (previously passed cursor which was ignored)
|
||||
})
|
||||
|
||||
// Route each noun to its type index
|
||||
for (const nounData of result.items) {
|
||||
try {
|
||||
// Use 'type' property from HNSWNounWithMetadata (not 'nounType')
|
||||
// Previously accessed wrong property, causing N+1 metadata fetches
|
||||
// getNounsWithPagination already includes type in response
|
||||
const nounType = nounData.type
|
||||
|
||||
// Skip if type not in rebuild list
|
||||
if (!nounType || !typesToRebuild.includes(nounType as NounType)) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Get the index for this type
|
||||
const index = this.getIndexForType(nounType as NounType)
|
||||
|
||||
// Load HNSW graph data
|
||||
const hnswData = await (this.storage as any).getVectorIndexData(nounData.id)
|
||||
if (!hnswData) {
|
||||
continue // No HNSW data
|
||||
}
|
||||
|
||||
// Create noun with restored connections
|
||||
const noun = {
|
||||
id: nounData.id,
|
||||
vector: shouldPreload ? nounData.vector : [],
|
||||
connections: new Map(),
|
||||
level: hnswData.level
|
||||
}
|
||||
|
||||
// Restore connections from storage
|
||||
for (const [levelStr, nounIds] of Object.entries(hnswData.connections)) {
|
||||
const level = parseInt(levelStr, 10)
|
||||
noun.connections.set(level, new Set<string>(nounIds as string[]))
|
||||
}
|
||||
|
||||
// Add to type-specific index
|
||||
;(index as any).nouns.set(nounData.id, noun)
|
||||
|
||||
// Track high-level nodes
|
||||
if (noun.level >= 2 && noun.level <= (index as any).MAX_TRACKED_LEVELS) {
|
||||
if (!(index as any).highLevelNodes.has(noun.level)) {
|
||||
;(index as any).highLevelNodes.set(noun.level, new Set())
|
||||
}
|
||||
;(index as any).highLevelNodes.get(noun.level).add(nounData.id)
|
||||
}
|
||||
|
||||
// Track progress
|
||||
loadedByType.set(nounType as NounType, (loadedByType.get(nounType as NounType) || 0) + 1)
|
||||
totalLoaded++
|
||||
|
||||
if (options.onProgress && totalLoaded % 100 === 0) {
|
||||
options.onProgress(nounType as NounType, loadedByType.get(nounType as NounType) || 0, totalLoaded)
|
||||
}
|
||||
} catch (error) {
|
||||
prodLog.error(`Failed to restore HNSW data for ${nounData.id}:`, error)
|
||||
}
|
||||
}
|
||||
|
||||
hasMore = result.hasMore
|
||||
offset += batchSize // Increment offset for next page
|
||||
|
||||
// Progress logging
|
||||
if (totalLoaded % 1000 === 0) {
|
||||
prodLog.info(`Progress: ${totalLoaded.toLocaleString()} entities loaded...`)
|
||||
}
|
||||
}
|
||||
|
||||
// Restore entry points for each type
|
||||
for (const type of typesToRebuild) {
|
||||
const index = this.getIndexForType(type)
|
||||
let maxLevel = 0
|
||||
let entryPointId: string | null = null
|
||||
|
||||
for (const [id, noun] of (index as any).nouns.entries()) {
|
||||
if (entryPointId === null || noun.level > maxLevel) {
|
||||
maxLevel = noun.level
|
||||
entryPointId = id
|
||||
}
|
||||
}
|
||||
|
||||
// Recovery: if still null after loop but nouns exist
|
||||
if ((index as any).nouns.size > 0 && !entryPointId) {
|
||||
const { id: recoveredId, level: recoveredLevel } = (index as any).recoverEntryPointO1()
|
||||
entryPointId = recoveredId
|
||||
maxLevel = recoveredLevel
|
||||
}
|
||||
|
||||
// Validation: if entry point doesn't exist in loaded nouns
|
||||
if (entryPointId && !(index as any).nouns.has(entryPointId)) {
|
||||
const { id: recoveredId, level: recoveredLevel } = (index as any).recoverEntryPointO1()
|
||||
entryPointId = recoveredId
|
||||
maxLevel = recoveredLevel
|
||||
}
|
||||
|
||||
;(index as any).entryPointId = entryPointId
|
||||
;(index as any).maxLevel = maxLevel
|
||||
|
||||
const loaded = loadedByType.get(type) || 0
|
||||
const cacheInfo = shouldPreload ? ' (vectors preloaded)' : ' (adaptive caching)'
|
||||
|
||||
prodLog.info(
|
||||
`✅ Rebuilt ${type} index: ${loaded.toLocaleString()} entities, ` +
|
||||
`${maxLevel + 1} levels, entry point: ${entryPointId || 'none'}${cacheInfo}`
|
||||
)
|
||||
}
|
||||
|
||||
prodLog.info(
|
||||
`✅ TypeAwareHNSW rebuild complete: ${this.size().toLocaleString()} total entities across ${this.indexes.size} types (loaded from persisted graph structure)`
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get comprehensive statistics
|
||||
*
|
||||
* Shows memory reduction compared to monolithic approach.
|
||||
*
|
||||
* @returns Type-aware HNSW statistics
|
||||
*/
|
||||
public getStats(): TypeAwareHNSWStats {
|
||||
const typeStats = new Map<
|
||||
NounType,
|
||||
{
|
||||
nodeCount: number
|
||||
memoryMB: number
|
||||
maxLevel: number
|
||||
entryPointId: string | null
|
||||
}
|
||||
>()
|
||||
|
||||
let totalNodes = 0
|
||||
let totalMemoryMB = 0
|
||||
|
||||
// Collect stats from each type's index
|
||||
for (const [type, index] of this.indexes.entries()) {
|
||||
const cacheStats = index.getCacheStats()
|
||||
const nodeCount = index.size()
|
||||
const memoryMB = cacheStats.hnswCache.estimatedMemoryMB
|
||||
|
||||
typeStats.set(type, {
|
||||
nodeCount,
|
||||
memoryMB,
|
||||
maxLevel: index.getMaxLevel(),
|
||||
entryPointId: index.getEntryPointId()
|
||||
})
|
||||
|
||||
totalNodes += nodeCount
|
||||
totalMemoryMB += memoryMB
|
||||
}
|
||||
|
||||
// Estimate monolithic memory (for comparison)
|
||||
// Monolithic would use ~384 bytes per entity @ 1B scale
|
||||
const estimatedMonolithicMemoryMB = (totalNodes * 384) / (1024 * 1024)
|
||||
|
||||
// Calculate memory reduction
|
||||
const memoryReductionPercent =
|
||||
estimatedMonolithicMemoryMB > 0
|
||||
? ((estimatedMonolithicMemoryMB - totalMemoryMB) /
|
||||
estimatedMonolithicMemoryMB) *
|
||||
100
|
||||
: 0
|
||||
|
||||
return {
|
||||
totalNodes,
|
||||
totalMemoryMB: parseFloat(totalMemoryMB.toFixed(2)),
|
||||
typeCount: this.indexes.size,
|
||||
typeStats,
|
||||
memoryReductionPercent: parseFloat(memoryReductionPercent.toFixed(2)),
|
||||
estimatedMonolithicMemoryMB: parseFloat(
|
||||
estimatedMonolithicMemoryMB.toFixed(2)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get statistics for a specific type
|
||||
*
|
||||
* @param type The noun type
|
||||
* @returns Statistics for this type's index (null if no index)
|
||||
*/
|
||||
public getStatsForType(
|
||||
type: NounType
|
||||
): {
|
||||
nodeCount: number
|
||||
memoryMB: number
|
||||
maxLevel: number
|
||||
entryPointId: string | null
|
||||
cacheStats: any
|
||||
} | null {
|
||||
const index = this.indexes.get(type)
|
||||
if (!index) {
|
||||
return null
|
||||
}
|
||||
|
||||
const cacheStats = index.getCacheStats()
|
||||
|
||||
return {
|
||||
nodeCount: index.size(),
|
||||
memoryMB: cacheStats.hnswCache.estimatedMemoryMB,
|
||||
maxLevel: index.getMaxLevel(),
|
||||
entryPointId: index.getEntryPointId(),
|
||||
cacheStats
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all noun types (for iteration)
|
||||
*
|
||||
* @returns Array of all noun types
|
||||
*/
|
||||
private getAllNounTypes(): NounType[] {
|
||||
const types: NounType[] = []
|
||||
for (let i = 0; i < NOUN_TYPE_COUNT; i++) {
|
||||
types.push(TypeUtils.getNounFromIndex(i))
|
||||
}
|
||||
return types
|
||||
}
|
||||
|
||||
/**
|
||||
* Get list of types that have indexes (have entities)
|
||||
*
|
||||
* @returns Array of types with indexes
|
||||
*/
|
||||
public getActiveTypes(): NounType[] {
|
||||
return Array.from(this.indexes.keys())
|
||||
}
|
||||
}
|
||||
18
src/index.ts
18
src/index.ts
|
|
@ -146,6 +146,7 @@ export type {
|
|||
TxUnrelateOperation,
|
||||
TransactOptions,
|
||||
TransactReceipt,
|
||||
TxLogEntry,
|
||||
CompactHistoryOptions,
|
||||
CompactHistoryResult,
|
||||
ChangedIds
|
||||
|
|
@ -221,23 +222,6 @@ export { MemoryStorage, createStorage }
|
|||
// FileSystemStorage is exported separately to avoid browser build issues.
|
||||
export { FileSystemStorage } from './storage/adapters/fileSystemStorage.js'
|
||||
|
||||
// Export COW (Copy-on-Write) infrastructure
|
||||
import { CommitLog } from './storage/cow/CommitLog.js'
|
||||
import { CommitObject, CommitBuilder } from './storage/cow/CommitObject.js'
|
||||
import { BlobStorage } from './storage/cow/BlobStorage.js'
|
||||
import { RefManager } from './storage/cow/RefManager.js'
|
||||
import { TreeObject } from './storage/cow/TreeObject.js'
|
||||
|
||||
export {
|
||||
// COW infrastructure
|
||||
CommitLog,
|
||||
CommitObject,
|
||||
CommitBuilder,
|
||||
BlobStorage,
|
||||
RefManager,
|
||||
TreeObject
|
||||
}
|
||||
|
||||
// Export types
|
||||
import type {
|
||||
Vector,
|
||||
|
|
|
|||
|
|
@ -2,9 +2,8 @@
|
|||
* @module columnStore/ColumnManifest
|
||||
* @description Per-field manifest tracking segment files and field metadata.
|
||||
*
|
||||
* Stored as JSON at `_column_index/{field}/MANIFEST.json` using workspace-global
|
||||
* storage paths (not branch-scoped, same as `_cow/` metadata). Rewritten
|
||||
* atomically on every flush and compaction.
|
||||
* Stored as JSON at `_column_index/{field}/MANIFEST.json` using storage-root-
|
||||
* relative paths. Rewritten atomically on every flush and compaction.
|
||||
*
|
||||
* The manifest is the single source of truth for which segments exist for a
|
||||
* field. On startup, the column store loads each field's manifest and
|
||||
|
|
|
|||
|
|
@ -192,7 +192,7 @@ export class MigrationRunner {
|
|||
* Entity-level errors are tracked (not thrown). If maxErrors is exceeded, migration
|
||||
* stops early and returns partial results with errors.
|
||||
*/
|
||||
async run(options?: Pick<MigrateOptions, 'onProgress' | 'maxErrors'>): Promise<Omit<MigrationResult, 'backupBranch'>> {
|
||||
async run(options?: Pick<MigrateOptions, 'onProgress' | 'maxErrors'>): Promise<Omit<MigrationResult, 'backupPath'>> {
|
||||
const state = await this.getState()
|
||||
const pending = this.getPendingMigrations(state)
|
||||
|
||||
|
|
@ -259,93 +259,6 @@ export class MigrationRunner {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run specific migrations without checking completion state.
|
||||
* Used for branch iterations where the state on main says "completed"
|
||||
* but branch-local entities still need transforming.
|
||||
*
|
||||
* Safe because transforms are idempotent (return null when already applied).
|
||||
* Does NOT save migration state — the authoritative state lives on main.
|
||||
*/
|
||||
async runMigrations(
|
||||
migrations: Migration[],
|
||||
options?: Pick<MigrateOptions, 'onProgress' | 'maxErrors'>
|
||||
): Promise<Omit<MigrationResult, 'backupBranch'>> {
|
||||
if (migrations.length === 0) {
|
||||
return { migrationsApplied: [], entitiesProcessed: 0, entitiesModified: 0, errors: [] }
|
||||
}
|
||||
|
||||
let totalProcessed = 0
|
||||
let totalModified = 0
|
||||
const appliedMigrations: string[] = []
|
||||
const errors: MigrationError[] = []
|
||||
const maxErrors = options?.maxErrors ?? DEFAULT_MAX_ERRORS
|
||||
const batchConfig = this.storage.getBatchConfig()
|
||||
const batchSize = batchConfig.maxBatchSize
|
||||
const batchDelay = batchConfig.batchDelayMs
|
||||
|
||||
for (const migration of migrations) {
|
||||
if (errors.length >= maxErrors) break
|
||||
|
||||
let processed = 0
|
||||
let modified = 0
|
||||
|
||||
if (migration.applies === 'nouns' || migration.applies === 'both') {
|
||||
const result = await this.migrateNouns(migration, 0, batchSize, batchDelay, errors, maxErrors, options?.onProgress)
|
||||
processed += result.processed
|
||||
modified += result.modified
|
||||
}
|
||||
|
||||
if (migration.applies === 'verbs' || migration.applies === 'both') {
|
||||
if (errors.length < maxErrors) {
|
||||
const result = await this.migrateVerbs(migration, 0, batchSize, batchDelay, errors, maxErrors, options?.onProgress)
|
||||
processed += result.processed
|
||||
modified += result.modified
|
||||
}
|
||||
}
|
||||
|
||||
totalProcessed += processed
|
||||
totalModified += modified
|
||||
if (modified > 0) {
|
||||
appliedMigrations.push(migration.id)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
migrationsApplied: appliedMigrations,
|
||||
entitiesProcessed: totalProcessed,
|
||||
entitiesModified: totalModified,
|
||||
errors
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up old system:backup branches created by previous migrations.
|
||||
* Identifies backups via ref metadata (not by name prefix).
|
||||
*/
|
||||
async cleanupOldBackups(): Promise<void> {
|
||||
const refManager = this.storage.refManager
|
||||
if (!refManager) return
|
||||
|
||||
const refs = await refManager.listRefs()
|
||||
const currentBranch = this.storage.currentBranch || 'main'
|
||||
|
||||
for (const ref of refs) {
|
||||
if (
|
||||
ref.metadata?.type === 'system:backup' &&
|
||||
ref.name.startsWith('refs/heads/') &&
|
||||
ref.name !== `refs/heads/${currentBranch}`
|
||||
) {
|
||||
const branchName = ref.name.replace('refs/heads/', '')
|
||||
try {
|
||||
await refManager.deleteRef(branchName)
|
||||
} catch {
|
||||
// Ignore — branch may be current or protected
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Private helpers ───────────────────────────────────────────────
|
||||
|
||||
private async migrateNouns(
|
||||
|
|
@ -524,12 +437,11 @@ export class MigrationRunner {
|
|||
|
||||
private async saveResumeState(migrationId: string, offset: number): Promise<void> {
|
||||
const state = await this.getState()
|
||||
const branch = this.storage.currentBranch || 'main'
|
||||
await this.saveState({
|
||||
completedVersion: state?.completedVersion || '',
|
||||
completedAt: state?.completedAt || 0,
|
||||
completedMigrations: state?.completedMigrations || [],
|
||||
resumeState: { migrationId, lastProcessedOffset: offset, branch }
|
||||
resumeState: { migrationId, lastProcessedOffset: offset }
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -29,7 +29,6 @@ export interface MigrationState {
|
|||
resumeState?: {
|
||||
migrationId: string
|
||||
lastProcessedOffset: number
|
||||
branch: string
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -56,8 +55,8 @@ export interface MigrationError {
|
|||
}
|
||||
|
||||
export interface MigrationResult {
|
||||
/** Backup branch name, or null if no changes were needed */
|
||||
backupBranch: string | null
|
||||
/** Path of the pre-migration snapshot, or null when no `backupTo` was supplied */
|
||||
backupPath: string | null
|
||||
/** IDs of migrations that were applied */
|
||||
migrationsApplied: string[]
|
||||
/** Total entities processed (scanned) */
|
||||
|
|
@ -71,6 +70,13 @@ export interface MigrationResult {
|
|||
export interface MigrateOptions {
|
||||
/** Preview what would change without writing */
|
||||
dryRun?: boolean
|
||||
/**
|
||||
* Directory to persist a pre-migration snapshot into (created; must be
|
||||
* empty or absent). The snapshot is cut via the Db API (hard-link
|
||||
* snapshot of the current generation) BEFORE any transform runs; restore
|
||||
* it wholesale with `brain.restore(path, { confirm: true })`.
|
||||
*/
|
||||
backupTo?: string
|
||||
/** Progress callback for long-running migrations */
|
||||
onProgress?: (progress: {
|
||||
migrationId: string
|
||||
|
|
|
|||
|
|
@ -152,9 +152,8 @@ export abstract class BaseStorageAdapter implements StorageAdapter {
|
|||
// "graph-lsm/source/sstable-123" "<root>/_blobs/graph-lsm/source/sstable-123.bin"
|
||||
//
|
||||
// i.e. the key's "/"-separated segments are nested under a `_blobs/` prefix and
|
||||
// suffixed with `.bin`. Blobs are deliberately NOT branch-scoped (COW): they
|
||||
// are immutable, content-addressed segments managed by their producer,
|
||||
// mirroring how COW metadata under `_cow/` is also kept global.
|
||||
// suffixed with `.bin`. Blobs are immutable, content-addressed segments
|
||||
// managed by their producer.
|
||||
|
||||
/**
|
||||
* Persist a raw binary blob under `key`, writing the bytes verbatim (no JSON
|
||||
|
|
|
|||
|
|
@ -912,7 +912,7 @@ export class FileSystemStorage extends BaseStorage {
|
|||
if (entry.isFile()) {
|
||||
// Handle multiple compression formats for broad compatibility
|
||||
// - .json.gz: Standard entity/metadata files (JSON compressed)
|
||||
// - .gz: COW files (refs, blobs, commits - raw compressed)
|
||||
// - .gz: Raw compressed payloads (e.g. blob-store binary values)
|
||||
// - .json: Uncompressed JSON files
|
||||
if (entry.name.endsWith('.json.gz')) {
|
||||
// Strip .gz extension and add the .json path
|
||||
|
|
@ -923,7 +923,7 @@ export class FileSystemStorage extends BaseStorage {
|
|||
seen.add(normalizedPath)
|
||||
}
|
||||
} else if (entry.name.endsWith('.gz')) {
|
||||
// COW files stored as .gz (not .json.gz)
|
||||
// Raw payloads stored as .gz (not .json.gz)
|
||||
// Strip .gz extension and return path
|
||||
const normalizedName = entry.name.slice(0, -3) // Remove .gz
|
||||
const normalizedPath = path.join(prefix, normalizedName)
|
||||
|
|
@ -1387,12 +1387,10 @@ export class FileSystemStorage extends BaseStorage {
|
|||
}
|
||||
}
|
||||
|
||||
// Clear the entire branches/ directory (branch-based storage)
|
||||
// Bug fix: Data is stored in branches/main/entities/, not just entities/
|
||||
// The branch-based structure was introduced for COW support
|
||||
const branchesDir = path.join(this.rootDir, 'branches')
|
||||
if (await this.directoryExists(branchesDir)) {
|
||||
await removeDirectoryContents(branchesDir)
|
||||
// Clear the canonical entity/verb data area
|
||||
const entitiesDir = path.join(this.rootDir, 'entities')
|
||||
if (await this.directoryExists(entitiesDir)) {
|
||||
await removeDirectoryContents(entitiesDir)
|
||||
}
|
||||
|
||||
// Remove all files in both system directories
|
||||
|
|
@ -1401,19 +1399,16 @@ export class FileSystemStorage extends BaseStorage {
|
|||
await removeDirectoryContents(this.indexDir)
|
||||
}
|
||||
|
||||
// Remove COW (copy-on-write) version control data
|
||||
// This directory stores all git-like versioning data (commits, trees, blobs, refs)
|
||||
// Must be deleted to fully clear all data including version history
|
||||
const cowDir = path.join(this.rootDir, '_cow')
|
||||
if (await this.directoryExists(cowDir)) {
|
||||
// Delete the entire _cow/ directory (not just contents)
|
||||
await fs.promises.rm(cowDir, { recursive: true, force: true })
|
||||
// Remove the content-addressed blob store (VFS file content)
|
||||
const casDir = path.join(this.rootDir, '_cas')
|
||||
if (await this.directoryExists(casDir)) {
|
||||
// Delete the entire _cas/ directory (not just contents)
|
||||
await fs.promises.rm(casDir, { recursive: true, force: true })
|
||||
|
||||
// Reset COW managers (but don't disable COW - it's always enabled)
|
||||
// COW will re-initialize automatically on next use
|
||||
this.refManager = undefined
|
||||
// Drop the BlobStorage instance — its LRU cache holds deleted blobs.
|
||||
// initializeBlobStorage() re-creates it (brain.clear() does this before
|
||||
// the VFS is rebuilt).
|
||||
this.blobStorage = undefined
|
||||
this.commitLog = undefined
|
||||
}
|
||||
|
||||
// Clear the statistics cache
|
||||
|
|
@ -1426,7 +1421,7 @@ export class FileSystemStorage extends BaseStorage {
|
|||
;(this as any).totalVerbCount = 0
|
||||
|
||||
// Clear write-through cache (inherited from BaseStorage)
|
||||
// Without this, readWithInheritance() would return stale cached data
|
||||
// Without this, readCanonicalObject() would return stale cached data
|
||||
// after clear(), causing "ghost" entities to appear
|
||||
this.clearWriteCache()
|
||||
}
|
||||
|
|
@ -1457,17 +1452,6 @@ export class FileSystemStorage extends BaseStorage {
|
|||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if COW has been explicitly disabled via clear()
|
||||
* Fixes bug where clear() doesn't persist across instance restarts
|
||||
* @returns true if marker file exists, false otherwise
|
||||
* @protected
|
||||
*/
|
||||
/**
|
||||
* Removed checkClearMarker() and createClearMarker() methods
|
||||
* COW is now always enabled - marker files are no longer used
|
||||
*/
|
||||
|
||||
/**
|
||||
* Get information about storage usage and capacity
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -1,571 +0,0 @@
|
|||
/**
|
||||
* Historical Storage Adapter
|
||||
*
|
||||
* Provides lazy-loading read-only access to a historical commit state.
|
||||
* Uses LRU cache to bound memory usage and prevent eager-loading of entire history.
|
||||
*
|
||||
* Architecture:
|
||||
* - Extends BaseStorage to inherit all storage infrastructure
|
||||
* - Wraps an underlying storage adapter to access commit state
|
||||
* - Implements lazy-loading with LRU cache (bounded memory)
|
||||
* - All writes throw read-only errors
|
||||
* - All reads load from historical commit state on-demand
|
||||
*
|
||||
* Usage:
|
||||
* const historical = new HistoricalStorageAdapter({
|
||||
* underlyingStorage: brain.storage as BaseStorage,
|
||||
* commitId: 'abc123...',
|
||||
* cacheSize: 10000 // LRU cache size
|
||||
* })
|
||||
* await historical.init()
|
||||
*
|
||||
* Performance:
|
||||
* - O(1) cache lookups for frequently accessed entities
|
||||
* - Bounded memory: max cacheSize entities in memory
|
||||
* - Lazy loading: only loads entities when accessed
|
||||
* - No eager-loading of entire commit state
|
||||
*
|
||||
* Production-ready, billion-scale historical queries
|
||||
*/
|
||||
|
||||
import { BaseStorage } from '../baseStorage.js'
|
||||
import { CommitLog } from '../cow/CommitLog.js'
|
||||
import { BlobStorage } from '../cow/BlobStorage.js'
|
||||
import {
|
||||
HNSWNoun,
|
||||
HNSWVerb,
|
||||
NounMetadata,
|
||||
VerbMetadata,
|
||||
StatisticsData
|
||||
} from '../../coreTypes.js'
|
||||
|
||||
/**
|
||||
* Simple LRU Cache implementation
|
||||
* Bounds memory usage by evicting least-recently-used items
|
||||
*/
|
||||
class LRUCache<T> {
|
||||
private cache = new Map<string, T>()
|
||||
private accessOrder: string[] = []
|
||||
private maxSize: number
|
||||
|
||||
constructor(maxSize: number = 10000) {
|
||||
this.maxSize = maxSize
|
||||
}
|
||||
|
||||
get(key: string): T | undefined {
|
||||
const value = this.cache.get(key)
|
||||
if (value !== undefined) {
|
||||
// Move to end (most recently used)
|
||||
this.accessOrder = this.accessOrder.filter(k => k !== key)
|
||||
this.accessOrder.push(key)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
set(key: string, value: T): void {
|
||||
// Remove if already exists
|
||||
if (this.cache.has(key)) {
|
||||
this.accessOrder = this.accessOrder.filter(k => k !== key)
|
||||
}
|
||||
|
||||
// Add to cache
|
||||
this.cache.set(key, value)
|
||||
this.accessOrder.push(key)
|
||||
|
||||
// Evict oldest if over capacity
|
||||
if (this.cache.size > this.maxSize) {
|
||||
const oldest = this.accessOrder.shift()
|
||||
if (oldest) {
|
||||
this.cache.delete(oldest)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
has(key: string): boolean {
|
||||
return this.cache.has(key)
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.cache.clear()
|
||||
this.accessOrder = []
|
||||
}
|
||||
|
||||
get size(): number {
|
||||
return this.cache.size
|
||||
}
|
||||
}
|
||||
|
||||
export interface HistoricalStorageAdapterOptions {
|
||||
/** Underlying storage to access commit state from */
|
||||
underlyingStorage: BaseStorage
|
||||
|
||||
/** Commit ID to load historical state from */
|
||||
commitId: string
|
||||
|
||||
/** Max number of entities to cache (default: 10000) */
|
||||
cacheSize?: number
|
||||
|
||||
/** Branch containing the commit (default: 'main') */
|
||||
branch?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Historical Storage Adapter
|
||||
*
|
||||
* Lazy-loading, read-only storage adapter for historical commit state.
|
||||
* Implements billion-scale time-travel queries with bounded memory.
|
||||
*/
|
||||
export class HistoricalStorageAdapter extends BaseStorage {
|
||||
private underlyingStorage: BaseStorage
|
||||
private commitId: string
|
||||
private branch: string
|
||||
private cacheSize: number
|
||||
|
||||
// LRU caches for lazy-loaded entities
|
||||
private cache: LRUCache<any>
|
||||
|
||||
// Historical commit state (loaded lazily) - must match BaseStorage visibility
|
||||
public commitLog?: CommitLog
|
||||
public blobStorage?: BlobStorage
|
||||
|
||||
constructor(options: HistoricalStorageAdapterOptions) {
|
||||
super()
|
||||
this.underlyingStorage = options.underlyingStorage
|
||||
this.commitId = options.commitId
|
||||
this.branch = options.branch || 'main'
|
||||
this.cacheSize = options.cacheSize || 10000
|
||||
|
||||
this.cache = new LRUCache(this.cacheSize)
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize historical storage adapter
|
||||
* Loads commit metadata but NOT entity data (lazy loading)
|
||||
*/
|
||||
public async init(): Promise<void> {
|
||||
// Get COW components from underlying storage
|
||||
// Fixed property names - use public properties without underscore prefix
|
||||
this.commitLog = this.underlyingStorage.commitLog
|
||||
this.blobStorage = this.underlyingStorage.blobStorage
|
||||
|
||||
if (!this.commitLog || !this.blobStorage) {
|
||||
throw new Error(
|
||||
'Historical storage requires underlying storage to have COW enabled. ' +
|
||||
'Call brain.init() first to initialize COW.'
|
||||
)
|
||||
}
|
||||
|
||||
// Verify commit exists
|
||||
const commit = await this.commitLog.getCommit(this.commitId)
|
||||
if (!commit) {
|
||||
throw new Error(`Commit not found: ${this.commitId}`)
|
||||
}
|
||||
|
||||
// Initialize GraphAdjacencyIndex and type statistics
|
||||
await super.init()
|
||||
}
|
||||
|
||||
// ============= Abstract Method Implementations =============
|
||||
|
||||
/**
|
||||
* Read object from historical commit state
|
||||
* Uses LRU cache to avoid repeated blob reads
|
||||
*/
|
||||
protected async readObjectFromPath(path: string): Promise<any | null> {
|
||||
// Check cache first
|
||||
if (this.cache.has(path)) {
|
||||
return this.cache.get(path) || null
|
||||
}
|
||||
|
||||
try {
|
||||
// Import COW classes
|
||||
const { CommitObject } = await import('../cow/CommitObject.js')
|
||||
const { TreeObject } = await import('../cow/TreeObject.js')
|
||||
const { isNullHash } = await import('../cow/constants.js')
|
||||
|
||||
// Read commit
|
||||
const commit = await CommitObject.read(this.blobStorage!, this.commitId)
|
||||
if (isNullHash(commit.tree)) {
|
||||
return null
|
||||
}
|
||||
|
||||
// Read tree
|
||||
const tree = await TreeObject.read(this.blobStorage!, commit.tree)
|
||||
|
||||
// Walk tree to find matching path
|
||||
for await (const entry of TreeObject.walk(this.blobStorage!, tree)) {
|
||||
if (entry.type === 'blob' && entry.name === path) {
|
||||
// Read blob data
|
||||
const blobData = await this.blobStorage!.read(entry.hash)
|
||||
const data = JSON.parse(blobData.toString())
|
||||
|
||||
// Cache the result
|
||||
this.cache.set(path, data)
|
||||
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
} catch (error) {
|
||||
// Path doesn't exist in historical state
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List objects under path in historical commit state
|
||||
*/
|
||||
protected async listObjectsUnderPath(prefix: string): Promise<string[]> {
|
||||
try {
|
||||
// Import COW classes
|
||||
const { CommitObject } = await import('../cow/CommitObject.js')
|
||||
const { TreeObject } = await import('../cow/TreeObject.js')
|
||||
const { isNullHash } = await import('../cow/constants.js')
|
||||
|
||||
// Read commit
|
||||
const commit = await CommitObject.read(this.blobStorage!, this.commitId)
|
||||
if (isNullHash(commit.tree)) {
|
||||
return []
|
||||
}
|
||||
|
||||
// Read tree
|
||||
const tree = await TreeObject.read(this.blobStorage!, commit.tree)
|
||||
|
||||
// Walk tree to find all paths matching prefix
|
||||
const paths: string[] = []
|
||||
for await (const entry of TreeObject.walk(this.blobStorage!, tree)) {
|
||||
if (entry.name.startsWith(prefix)) {
|
||||
paths.push(entry.name)
|
||||
}
|
||||
}
|
||||
|
||||
return paths
|
||||
} catch (error) {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* WRITE BLOCKED: Historical storage is read-only
|
||||
*/
|
||||
protected async writeObjectToPath(path: string, data: any): Promise<void> {
|
||||
throw new Error(
|
||||
`Historical storage is read-only. Cannot write to path: ${path}`
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* DELETE BLOCKED: Historical storage is read-only
|
||||
*/
|
||||
protected async deleteObjectFromPath(path: string): Promise<void> {
|
||||
throw new Error(
|
||||
`Historical storage is read-only. Cannot delete path: ${path}`
|
||||
)
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// Raw binary-blob primitive (read-only)
|
||||
// ===========================================================================
|
||||
|
||||
/**
|
||||
* WRITE BLOCKED: Historical storage is read-only.
|
||||
*
|
||||
* @param key - The blob key (unused; included for the error message).
|
||||
* @throws Always — historical state is immutable.
|
||||
*/
|
||||
public async saveBinaryBlob(key: string, _data: Buffer): Promise<void> {
|
||||
throw new Error(
|
||||
`Historical storage is read-only. Cannot save binary blob: ${key}`
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the raw bytes of a binary blob from the historical commit state by
|
||||
* walking the commit tree for the blob entry at `_blobs/<key>.bin` and reading
|
||||
* its content-addressed bytes verbatim (no JSON decode). Returns `null` if the
|
||||
* blob was not present in this commit.
|
||||
*
|
||||
* @param key - The blob key (same convention as the live adapters).
|
||||
* @returns The blob bytes as stored at this commit, or `null` if absent.
|
||||
*/
|
||||
public async loadBinaryBlob(key: string): Promise<Buffer | null> {
|
||||
try {
|
||||
const { CommitObject } = await import('../cow/CommitObject.js')
|
||||
const { TreeObject } = await import('../cow/TreeObject.js')
|
||||
const { isNullHash } = await import('../cow/constants.js')
|
||||
|
||||
const commit = await CommitObject.read(this.blobStorage!, this.commitId)
|
||||
if (isNullHash(commit.tree)) {
|
||||
return null
|
||||
}
|
||||
|
||||
const tree = await TreeObject.read(this.blobStorage!, commit.tree)
|
||||
const blobName = `_blobs/${key}.bin`
|
||||
|
||||
for await (const entry of TreeObject.walk(this.blobStorage!, tree)) {
|
||||
if (entry.type === 'blob' && entry.name === blobName) {
|
||||
return await this.blobStorage!.read(entry.hash)
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
} catch (error) {
|
||||
// Blob not present in historical state
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* DELETE BLOCKED: Historical storage is read-only.
|
||||
*
|
||||
* @param key - The blob key (unused; included for the error message).
|
||||
* @throws Always — historical state is immutable.
|
||||
*/
|
||||
public async deleteBinaryBlob(key: string): Promise<void> {
|
||||
throw new Error(
|
||||
`Historical storage is read-only. Cannot delete binary blob: ${key}`
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Historical state lives in the content-addressed commit store, not on the
|
||||
* local filesystem, so there is no mmap-able path. Always returns `null`.
|
||||
*
|
||||
* @param _key - The blob key (unused).
|
||||
* @returns Always `null`.
|
||||
*/
|
||||
public getBinaryBlobPath(_key: string): string | null {
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Get storage statistics from historical commit
|
||||
*/
|
||||
protected async getStatisticsData(): Promise<StatisticsData | null> {
|
||||
return await this.readObjectFromPath('_system/statistics.json')
|
||||
}
|
||||
|
||||
/**
|
||||
* WRITE BLOCKED: Cannot save statistics to historical storage
|
||||
*/
|
||||
protected async saveStatisticsData(data: StatisticsData): Promise<void> {
|
||||
throw new Error('Historical storage is read-only. Cannot save statistics.')
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear cache (does not affect historical data)
|
||||
*/
|
||||
public async clear(): Promise<void> {
|
||||
this.cache.clear()
|
||||
}
|
||||
|
||||
/**
|
||||
* Get storage status
|
||||
*/
|
||||
public async getStorageStatus(): Promise<{
|
||||
type: string
|
||||
used: number
|
||||
quota: number | null
|
||||
details?: Record<string, any>
|
||||
}> {
|
||||
return {
|
||||
type: 'historical',
|
||||
used: this.cache.size,
|
||||
quota: this.cacheSize,
|
||||
details: {
|
||||
commitId: this.commitId,
|
||||
branch: this.branch,
|
||||
cached: this.cache.size,
|
||||
maxCache: this.cacheSize,
|
||||
readOnly: true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if COW has been explicitly disabled via clear()
|
||||
* No-op for HistoricalStorageAdapter (read-only, doesn't manage COW)
|
||||
* @returns Always false (read-only adapter doesn't manage COW state)
|
||||
* @protected
|
||||
*/
|
||||
/**
|
||||
* Removed checkClearMarker() and createClearMarker() methods
|
||||
* COW is now always enabled - marker files are no longer used
|
||||
*/
|
||||
|
||||
// ============= Override Write Methods (Read-Only) =============
|
||||
|
||||
/**
|
||||
* WRITE BLOCKED: Historical storage is read-only
|
||||
*/
|
||||
public async saveNoun(noun: HNSWNoun): Promise<void> {
|
||||
throw new Error('Historical storage is read-only. Cannot save noun.')
|
||||
}
|
||||
|
||||
/**
|
||||
* WRITE BLOCKED: Historical storage is read-only
|
||||
*/
|
||||
public async saveNounMetadata(id: string, metadata: NounMetadata): Promise<void> {
|
||||
throw new Error('Historical storage is read-only. Cannot save noun metadata.')
|
||||
}
|
||||
|
||||
/**
|
||||
* WRITE BLOCKED: Historical storage is read-only
|
||||
*/
|
||||
public async deleteNoun(id: string): Promise<void> {
|
||||
throw new Error('Historical storage is read-only. Cannot delete noun.')
|
||||
}
|
||||
|
||||
/**
|
||||
* WRITE BLOCKED: Historical storage is read-only
|
||||
*/
|
||||
public async deleteNounMetadata(id: string): Promise<void> {
|
||||
throw new Error('Historical storage is read-only. Cannot delete noun metadata.')
|
||||
}
|
||||
|
||||
/**
|
||||
* WRITE BLOCKED: Historical storage is read-only
|
||||
*/
|
||||
public async saveVerb(verb: HNSWVerb): Promise<void> {
|
||||
throw new Error('Historical storage is read-only. Cannot save verb.')
|
||||
}
|
||||
|
||||
/**
|
||||
* WRITE BLOCKED: Historical storage is read-only
|
||||
*/
|
||||
public async saveVerbMetadata(id: string, metadata: VerbMetadata): Promise<void> {
|
||||
throw new Error('Historical storage is read-only. Cannot save verb metadata.')
|
||||
}
|
||||
|
||||
/**
|
||||
* WRITE BLOCKED: Historical storage is read-only
|
||||
*/
|
||||
public async deleteVerb(id: string): Promise<void> {
|
||||
throw new Error('Historical storage is read-only. Cannot delete verb.')
|
||||
}
|
||||
|
||||
/**
|
||||
* WRITE BLOCKED: Historical storage is read-only
|
||||
*/
|
||||
public async deleteVerbMetadata(id: string): Promise<void> {
|
||||
throw new Error('Historical storage is read-only. Cannot delete verb metadata.')
|
||||
}
|
||||
|
||||
/**
|
||||
* WRITE BLOCKED: Historical storage is read-only
|
||||
*/
|
||||
public async saveMetadata(id: string, metadata: any): Promise<void> {
|
||||
throw new Error('Historical storage is read-only. Cannot save metadata.')
|
||||
}
|
||||
|
||||
/**
|
||||
* WRITE BLOCKED: Historical storage is read-only
|
||||
*/
|
||||
public async saveVectorIndexData(nounId: string, hnswData: {
|
||||
level: number
|
||||
connections: Record<string, string[]>
|
||||
}): Promise<void> {
|
||||
throw new Error('Historical storage is read-only. Cannot save HNSW data.')
|
||||
}
|
||||
|
||||
/**
|
||||
* WRITE BLOCKED: Historical storage is read-only
|
||||
*/
|
||||
public async saveHNSWSystem(systemData: {
|
||||
entryPointId: string | null
|
||||
maxLevel: number
|
||||
}): Promise<void> {
|
||||
throw new Error('Historical storage is read-only. Cannot save HNSW system data.')
|
||||
}
|
||||
|
||||
// ============= Additional Abstract Methods =============
|
||||
|
||||
/**
|
||||
* Get noun vector from historical state
|
||||
*/
|
||||
public async getNounVector(id: string): Promise<number[] | null> {
|
||||
const noun = await this.getNoun(id)
|
||||
return noun?.vector || null
|
||||
}
|
||||
|
||||
/**
|
||||
* Get HNSW data from historical state
|
||||
*/
|
||||
public async getVectorIndexData(nounId: string): Promise<{
|
||||
level: number
|
||||
connections: Record<string, string[]>
|
||||
} | null> {
|
||||
const path = `_system/hnsw/nodes/${nounId}.json`
|
||||
return await this.readObjectFromPath(path)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get HNSW system data from historical state
|
||||
*/
|
||||
public async getHNSWSystem(): Promise<{
|
||||
entryPointId: string | null
|
||||
maxLevel: number
|
||||
} | null> {
|
||||
return await this.readObjectFromPath('_system/hnsw/system.json')
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize counts (no-op for historical storage)
|
||||
* Counts are loaded from historical state metadata
|
||||
*/
|
||||
protected async initializeCounts(): Promise<void> {
|
||||
// No-op: Historical storage doesn't need to initialize counts
|
||||
// They're read from commit state metadata
|
||||
}
|
||||
|
||||
/**
|
||||
* WRITE BLOCKED: Cannot persist counts to historical storage
|
||||
*/
|
||||
protected async persistCounts(): Promise<void> {
|
||||
// No-op: Historical storage is read-only
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// Generational record layer (8.0 MVCC) — not applicable to this adapter
|
||||
//
|
||||
// HistoricalStorageAdapter is the pre-8.0 commit-based time-travel view and
|
||||
// is read-only by construction. The generation store never registers its
|
||||
// write hooks on reader-mode instances, so these methods are unreachable in
|
||||
// normal operation; they throw explicitly rather than fake behavior.
|
||||
// ===========================================================================
|
||||
|
||||
/**
|
||||
* WRITE BLOCKED: the tx-log belongs to the live store, not a historical view.
|
||||
*/
|
||||
public async appendTxLogLine(_line: string): Promise<void> {
|
||||
throw new Error('Historical storage is read-only. Cannot append to the transaction log.')
|
||||
}
|
||||
|
||||
/**
|
||||
* Not supported: historical commit views predate the generational tx-log.
|
||||
*/
|
||||
public async readTxLogLines(): Promise<string[]> {
|
||||
throw new Error(
|
||||
'Transaction-log reads are not supported on a historical commit view. ' +
|
||||
'Use the live store (or a Db from brain.now()/brain.asOf()).'
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Not supported: snapshot a live store via db.persist(path) instead.
|
||||
*/
|
||||
public async snapshotToDirectory(_targetPath: string): Promise<void> {
|
||||
throw new Error(
|
||||
'snapshotToDirectory is not supported on a historical commit view. ' +
|
||||
'Call db.persist(path) on the live store instead.'
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* WRITE BLOCKED: cannot restore into a read-only historical view.
|
||||
*/
|
||||
public async restoreFromDirectory(_sourcePath: string): Promise<void> {
|
||||
throw new Error('Historical storage is read-only. Cannot restore from a snapshot.')
|
||||
}
|
||||
}
|
||||
|
|
@ -362,8 +362,13 @@ export class MemoryStorage extends BaseStorage {
|
|||
this.statisticsCache = null
|
||||
this.statisticsModified = false
|
||||
|
||||
// Drop the BlobStorage instance — its LRU cache holds deleted blobs.
|
||||
// initializeBlobStorage() re-creates it (brain.clear() does this before
|
||||
// the VFS is rebuilt).
|
||||
this.blobStorage = undefined
|
||||
|
||||
// Clear write-through cache (inherited from BaseStorage)
|
||||
// Without this, readWithInheritance() would return stale cached data
|
||||
// Without this, readCanonicalObject() would return stale cached data
|
||||
// after clear(), causing "ghost" entities to appear
|
||||
this.clearWriteCache()
|
||||
}
|
||||
|
|
@ -390,17 +395,6 @@ export class MemoryStorage extends BaseStorage {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if COW has been explicitly disabled via clear()
|
||||
* No-op for MemoryStorage (doesn't persist)
|
||||
* @returns Always false (marker doesn't persist in memory)
|
||||
* @protected
|
||||
*/
|
||||
/**
|
||||
* Removed checkClearMarker() and createClearMarker() methods
|
||||
* COW is now always enabled - marker files are no longer used
|
||||
*/
|
||||
|
||||
/**
|
||||
* Save statistics data to storage
|
||||
* @param statistics The statistics data to save
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
77
src/storage/binaryDataCodec.ts
Normal file
77
src/storage/binaryDataCodec.ts
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
/**
|
||||
* @module storage/binaryDataCodec
|
||||
* @description Single source of truth for wrapping/unwrapping binary payloads
|
||||
* stored in JSON-based object storage. Binary bytes (compressed blobs, raw
|
||||
* buffers) are persisted as `{ _binary: true, data: "<base64>" }` so they can
|
||||
* travel through adapters whose object primitive is JSON. `unwrapBinaryData`
|
||||
* reverses that wrapping — and MUST be used everywhere bytes come back out,
|
||||
* because content hashes are computed over the original bytes, not the
|
||||
* wrapper.
|
||||
*
|
||||
* Used by `BaseStorage`'s blob-store bridge and by `BlobStorage`'s
|
||||
* defense-in-depth verification path.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @description Wrapped binary data format used when storing binary data in
|
||||
* JSON-based storage.
|
||||
*/
|
||||
export interface WrappedBinaryData {
|
||||
_binary: true
|
||||
data: string // base64-encoded
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Type guard for the wrapped binary format.
|
||||
* @param data - Candidate value.
|
||||
* @returns True when `data` is a `{ _binary: true, data: string }` wrapper.
|
||||
*/
|
||||
export function isWrappedBinary(data: any): data is WrappedBinaryData {
|
||||
return (
|
||||
typeof data === 'object' &&
|
||||
data !== null &&
|
||||
data._binary === true &&
|
||||
typeof data.data === 'string'
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Unwrap binary data from its JSON wrapper.
|
||||
*
|
||||
* Handles:
|
||||
* - `Buffer` → `Buffer` (pass-through)
|
||||
* - `{ _binary: true, data: "<base64>" }` → `Buffer` (unwrap)
|
||||
* - Plain object → `Buffer` (JSON stringify — defensive)
|
||||
* - String → `Buffer`
|
||||
*
|
||||
* @param data - Data to unwrap (Buffer, wrapped object, plain object, or string).
|
||||
* @returns The unwrapped bytes.
|
||||
* @throws Error when the value cannot be interpreted as binary data.
|
||||
*/
|
||||
export function unwrapBinaryData(data: any): Buffer {
|
||||
// Case 1: Already a Buffer (no unwrapping needed)
|
||||
if (Buffer.isBuffer(data)) {
|
||||
return data
|
||||
}
|
||||
|
||||
// Case 2: Wrapped binary data {_binary: true, data: "base64..."}
|
||||
if (isWrappedBinary(data)) {
|
||||
return Buffer.from(data.data, 'base64')
|
||||
}
|
||||
|
||||
// Case 3: Plain object (shouldn't happen for binary blobs, but handle gracefully)
|
||||
if (typeof data === 'object' && data !== null) {
|
||||
return Buffer.from(JSON.stringify(data))
|
||||
}
|
||||
|
||||
// Case 4: String (convert to Buffer)
|
||||
if (typeof data === 'string') {
|
||||
return Buffer.from(data)
|
||||
}
|
||||
|
||||
// Case 5: Invalid type
|
||||
throw new Error(
|
||||
`Invalid data type for unwrap: ${typeof data}. ` +
|
||||
`Expected Buffer or {_binary: true, data: "base64..."}`
|
||||
)
|
||||
}
|
||||
498
src/storage/blobStorage.ts
Normal file
498
src/storage/blobStorage.ts
Normal file
|
|
@ -0,0 +1,498 @@
|
|||
/**
|
||||
* @module storage/blobStorage
|
||||
* @description Content-addressed blob store. Backs VFS file content with
|
||||
* SHA-256 addressing (automatic deduplication), reference counting, zstd
|
||||
* compression where it pays (MIME-aware: already-compressed media is stored
|
||||
* raw), and an LRU read cache.
|
||||
*
|
||||
* The store persists through a narrow key-value bridge
|
||||
* ({@link BlobStoreAdapter}) provided by `BaseStorage`, which roots all keys
|
||||
* under the `_cas/` storage area. Key naming is an explicit type contract:
|
||||
* `blob:<hash>` keys hold binary bytes, `blob-meta:<hash>` keys hold JSON
|
||||
* metadata — the key format decides how bytes are encoded, never content
|
||||
* sniffing.
|
||||
*/
|
||||
|
||||
import { createHash } from 'crypto'
|
||||
import { unwrapBinaryData } from './binaryDataCodec.js'
|
||||
|
||||
/**
|
||||
* @description Key-value bridge the blob store persists through. Implemented
|
||||
* by `BaseStorage.initializeBlobStorage()` over the adapter's raw object
|
||||
* primitives.
|
||||
*/
|
||||
export interface BlobStoreAdapter {
|
||||
/** Read the bytes stored under `key`, or `undefined` when absent. */
|
||||
get(key: string): Promise<Buffer | undefined>
|
||||
/** Persist `data` under `key` (overwrites). */
|
||||
put(key: string, data: Buffer): Promise<void>
|
||||
/** Delete the value under `key`. Missing keys are ignored. */
|
||||
delete(key: string): Promise<void>
|
||||
/** List all keys starting with `prefix`. */
|
||||
list(prefix: string): Promise<string[]>
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Metadata persisted alongside each blob (under
|
||||
* `blob-meta:<hash>`).
|
||||
*/
|
||||
export interface BlobMetadata {
|
||||
/** SHA-256 content hash (the blob's identity). */
|
||||
hash: string
|
||||
/** Original (uncompressed) size in bytes. */
|
||||
size: number
|
||||
/** Stored size in bytes (after compression, if any). */
|
||||
compressedSize: number
|
||||
/** Compression applied to the stored bytes. */
|
||||
compression: 'none' | 'zstd'
|
||||
/** Creation timestamp (epoch ms). */
|
||||
createdAt: number
|
||||
/** Number of logical references to this blob (deduplicated writes). */
|
||||
refCount: number
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Options for {@link BlobStorage.write}.
|
||||
*/
|
||||
export interface BlobWriteOptions {
|
||||
/**
|
||||
* Compression strategy. `'auto'` (default) compresses payloads above 1 KB
|
||||
* with zstd unless the MIME type says the bytes are already compressed.
|
||||
* Explicit `'none'`/`'zstd'` is honoured as asserted by the caller.
|
||||
*/
|
||||
compression?: 'none' | 'zstd' | 'auto'
|
||||
/**
|
||||
* Content type of the payload (e.g. `image/jpeg`, `video/mp4`).
|
||||
*
|
||||
* When set on an `auto`-compression write, the store skips zstd for MIME
|
||||
* types that are already heavily compressed (JPEG, PNG, WebP, MP4, WebM,
|
||||
* MP3, ZIP, PDF, etc.). zstd over these formats wastes CPU and rarely
|
||||
* shaves more than a single-digit percent — usually it actually grows the
|
||||
* payload because the entropy is already maximised by the format itself.
|
||||
*
|
||||
* Has no effect when `compression` is `'none'` or `'zstd'` explicitly —
|
||||
* the caller is asserting the choice and the store honours it.
|
||||
*/
|
||||
mimeType?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* MIME types whose payload is already heavily compressed. zstd over these is
|
||||
* almost always a CPU-only loss — the bytes are already near entropy-maximal,
|
||||
* so the output is the same size or slightly larger plus the cost of running
|
||||
* the compressor. Used by `BlobStorage.selectCompression()` in `auto` mode.
|
||||
*
|
||||
* Conservative denylist (well-known formats only). Anything not in this set
|
||||
* goes through the size heuristic. False negatives (compressing something we
|
||||
* should have skipped) waste CPU; false positives (skipping something we
|
||||
* could have compressed) waste a few percent of bytes. The denylist favours
|
||||
* CPU-cycle safety because the formats listed here are the ones where
|
||||
* gzip/zstd is reliably a net loss.
|
||||
*/
|
||||
const ALREADY_COMPRESSED_MIME_TYPES = new Set<string>([
|
||||
// Images
|
||||
'image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp',
|
||||
'image/avif', 'image/heic', 'image/heif', 'image/jp2',
|
||||
// Video
|
||||
'video/mp4', 'video/webm', 'video/x-matroska', 'video/quicktime',
|
||||
'video/x-msvideo', 'video/mpeg', 'video/3gpp', 'video/x-ms-wmv',
|
||||
// Audio
|
||||
'audio/mpeg', 'audio/mp4', 'audio/aac', 'audio/ogg', 'audio/webm',
|
||||
'audio/opus', 'audio/flac', 'audio/x-ms-wma',
|
||||
// Archives
|
||||
'application/zip', 'application/gzip', 'application/x-gzip',
|
||||
'application/x-bzip2', 'application/x-7z-compressed',
|
||||
'application/x-rar-compressed', 'application/x-xz', 'application/x-zstd',
|
||||
'application/x-compress', 'application/vnd.rar',
|
||||
// Documents with internal compression
|
||||
'application/pdf', 'application/epub+zip',
|
||||
// Office formats (zip-based)
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
'application/vnd.oasis.opendocument.text',
|
||||
'application/vnd.oasis.opendocument.spreadsheet',
|
||||
'application/vnd.oasis.opendocument.presentation'
|
||||
])
|
||||
|
||||
/**
|
||||
* @description True when the MIME type names a payload format known to be
|
||||
* already heavily compressed. Strips any `;charset=…` / `;boundary=…`
|
||||
* parameters and lowercases the bare type/subtype before lookup, so
|
||||
* `'IMAGE/JPEG; charset=binary'` and `'image/jpeg'` resolve identically.
|
||||
* @param mimeType - MIME type string, or `undefined`.
|
||||
* @returns Whether `auto` compression should skip zstd for this payload.
|
||||
*/
|
||||
export function isAlreadyCompressedMimeType(mimeType: string | undefined): boolean {
|
||||
if (!mimeType) return false
|
||||
const bare = mimeType.split(';', 1)[0].trim().toLowerCase()
|
||||
return ALREADY_COMPRESSED_MIME_TYPES.has(bare)
|
||||
}
|
||||
|
||||
/**
|
||||
* LRU cache entry.
|
||||
*/
|
||||
interface CacheEntry {
|
||||
data: Buffer
|
||||
metadata: BlobMetadata
|
||||
lastAccess: number
|
||||
size: number
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Content-addressed, deduplicating, reference-counted blob
|
||||
* store with MIME-aware zstd compression and an LRU read cache. See the
|
||||
* module doc for the persistence contract.
|
||||
*
|
||||
* @example
|
||||
* const hash = await blobStorage.write(buffer, { mimeType: 'image/png' })
|
||||
* const bytes = await blobStorage.read(hash) // verified against the hash
|
||||
* await blobStorage.delete(hash) // decrements refCount first
|
||||
*/
|
||||
export class BlobStorage {
|
||||
private adapter: BlobStoreAdapter
|
||||
private cache: Map<string, CacheEntry>
|
||||
private cacheMaxSize: number
|
||||
private currentCacheSize: number
|
||||
|
||||
// Compression (lazily loaded)
|
||||
private zstdCompress?: (data: Buffer) => Promise<Buffer>
|
||||
private zstdDecompress?: (data: Buffer) => Promise<Buffer>
|
||||
private compressionReady = false
|
||||
|
||||
// Configuration
|
||||
private readonly CACHE_MAX_SIZE = 100 * 1024 * 1024 // 100MB default
|
||||
private readonly COMPRESSION_THRESHOLD = 1024 // 1KB - don't compress smaller
|
||||
|
||||
/**
|
||||
* @param adapter - Key-value bridge to persist through.
|
||||
* @param options - `cacheMaxSize` bounds the LRU read cache (bytes,
|
||||
* default 100 MB).
|
||||
*/
|
||||
constructor(adapter: BlobStoreAdapter, options?: { cacheMaxSize?: number }) {
|
||||
this.adapter = adapter
|
||||
this.cache = new Map()
|
||||
this.cacheMaxSize = options?.cacheMaxSize ?? this.CACHE_MAX_SIZE
|
||||
this.currentCacheSize = 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Lazy-load the zstd compression module. Falls back to uncompressed
|
||||
* storage when the optional dependency is unavailable.
|
||||
*/
|
||||
private async ensureCompressionReady(): Promise<void> {
|
||||
if (this.compressionReady) return
|
||||
try {
|
||||
// Dynamic import to avoid loading if not needed
|
||||
// @ts-ignore - Optional dependency, gracefully handled if missing
|
||||
const zstd = await import('@mongodb-js/zstd')
|
||||
this.zstdCompress = async (data: Buffer) => {
|
||||
return Buffer.from(await zstd.compress(data, 3)) // Level 3 = fast
|
||||
}
|
||||
this.zstdDecompress = async (data: Buffer) => {
|
||||
return Buffer.from(await zstd.decompress(data))
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('zstd compression not available, falling back to uncompressed')
|
||||
this.zstdCompress = undefined
|
||||
this.zstdDecompress = undefined
|
||||
}
|
||||
this.compressionReady = true
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Compute the SHA-256 content hash of `data`.
|
||||
* @param data - Bytes to hash.
|
||||
* @returns Hex-encoded SHA-256 hash.
|
||||
*/
|
||||
static hash(data: Buffer): string {
|
||||
return createHash('sha256').update(data).digest('hex')
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Write a blob. Content-addressed: the SHA-256 hash of the
|
||||
* bytes is the storage key, so identical payloads deduplicate (the
|
||||
* existing blob's reference count is incremented instead of rewriting).
|
||||
*
|
||||
* @param data - Blob bytes.
|
||||
* @param options - Compression strategy and MIME hint (see
|
||||
* {@link BlobWriteOptions}).
|
||||
* @returns The blob's SHA-256 hash.
|
||||
*/
|
||||
async write(data: Buffer, options: BlobWriteOptions = {}): Promise<string> {
|
||||
const hash = BlobStorage.hash(data)
|
||||
|
||||
// Deduplication: identical content already stored — just add a reference.
|
||||
if (await this.has(hash)) {
|
||||
await this.incrementRefCount(hash)
|
||||
return hash
|
||||
}
|
||||
|
||||
await this.ensureCompressionReady()
|
||||
|
||||
// Determine compression strategy
|
||||
const compression = this.selectCompression(data, options)
|
||||
|
||||
// Compress if needed
|
||||
let finalData = data
|
||||
let compressedSize = data.length
|
||||
|
||||
if (compression === 'zstd' && this.zstdCompress) {
|
||||
finalData = await this.zstdCompress(data)
|
||||
compressedSize = finalData.length
|
||||
}
|
||||
|
||||
// Record the ACTUAL compression state, not the intended one — prevents
|
||||
// corruption if compression failed to initialize.
|
||||
const actualCompression = finalData === data ? 'none' : compression
|
||||
const metadata: BlobMetadata = {
|
||||
hash,
|
||||
size: data.length,
|
||||
compressedSize,
|
||||
compression: actualCompression,
|
||||
createdAt: Date.now(),
|
||||
refCount: 1
|
||||
}
|
||||
|
||||
await this.adapter.put(`blob:${hash}`, finalData)
|
||||
await this.adapter.put(`blob-meta:${hash}`, Buffer.from(JSON.stringify(metadata)))
|
||||
|
||||
// Write-through cache (caches the ORIGINAL bytes, not the compressed form)
|
||||
this.addToCache(hash, data, metadata)
|
||||
|
||||
return hash
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Read a blob: LRU cache first, then storage with
|
||||
* decompression and integrity verification (the bytes are re-hashed and
|
||||
* compared against the requested hash).
|
||||
*
|
||||
* @param hash - The blob's SHA-256 hash.
|
||||
* @returns The original (decompressed) blob bytes.
|
||||
* @throws Error when the blob is missing or fails integrity verification.
|
||||
*/
|
||||
async read(hash: string): Promise<Buffer> {
|
||||
// Check cache first
|
||||
const cached = this.getFromCache(hash)
|
||||
if (cached) {
|
||||
return cached.data
|
||||
}
|
||||
|
||||
const metadataBuffer = await this.adapter.get(`blob-meta:${hash}`)
|
||||
if (!metadataBuffer) {
|
||||
throw new Error(`Blob metadata not found: ${hash}`)
|
||||
}
|
||||
// Unwrap before parsing (defense-in-depth): metadata should come back as
|
||||
// JSON bytes, but an adapter might return the wrapped binary format.
|
||||
const metadata: BlobMetadata = JSON.parse(unwrapBinaryData(metadataBuffer).toString())
|
||||
|
||||
const data = await this.adapter.get(`blob:${hash}`)
|
||||
if (!data) {
|
||||
throw new Error(`Blob not found: ${hash}`)
|
||||
}
|
||||
|
||||
// Decompress if needed
|
||||
let finalData = data
|
||||
if (metadata.compression === 'zstd') {
|
||||
if (!this.zstdDecompress) {
|
||||
await this.ensureCompressionReady()
|
||||
}
|
||||
if (!this.zstdDecompress) {
|
||||
throw new Error('zstd decompression not available')
|
||||
}
|
||||
finalData = await this.zstdDecompress(data)
|
||||
}
|
||||
|
||||
// Defense-in-depth unwrap: even though the bridge unwraps, verify it
|
||||
// happened and re-unwrap if needed. Hash verification must run on the
|
||||
// original content bytes.
|
||||
const unwrappedData = unwrapBinaryData(finalData)
|
||||
|
||||
// Integrity verification (always on — a content-addressed store that
|
||||
// returns bytes not matching the address is corruption, not a result)
|
||||
if (BlobStorage.hash(unwrappedData) !== hash) {
|
||||
throw new Error(`Blob integrity check failed: ${hash}`)
|
||||
}
|
||||
|
||||
this.addToCache(hash, unwrappedData, metadata)
|
||||
|
||||
return unwrappedData
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Whether a blob with this hash exists (cache or storage).
|
||||
* @param hash - The blob's SHA-256 hash.
|
||||
* @returns True when the blob exists.
|
||||
*/
|
||||
async has(hash: string): Promise<boolean> {
|
||||
if (this.cache.has(hash)) {
|
||||
return true
|
||||
}
|
||||
const exists = await this.adapter.get(`blob:${hash}`)
|
||||
return exists !== undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Drop one reference to the blob. The stored bytes and
|
||||
* metadata are physically deleted only when the reference count reaches
|
||||
* zero — deduplicated content shared by other writers survives.
|
||||
*
|
||||
* @param hash - The blob's SHA-256 hash.
|
||||
*/
|
||||
async delete(hash: string): Promise<void> {
|
||||
const refCount = await this.decrementRefCount(hash)
|
||||
|
||||
// Only delete if no references remain
|
||||
if (refCount > 0) {
|
||||
return
|
||||
}
|
||||
|
||||
await this.adapter.delete(`blob:${hash}`)
|
||||
await this.adapter.delete(`blob-meta:${hash}`)
|
||||
this.removeFromCache(hash)
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Read a blob's metadata without reading its bytes.
|
||||
* @param hash - The blob's SHA-256 hash.
|
||||
* @returns The metadata, or `undefined` when the blob does not exist.
|
||||
*/
|
||||
async getMetadata(hash: string): Promise<BlobMetadata | undefined> {
|
||||
const data = await this.adapter.get(`blob-meta:${hash}`)
|
||||
if (data) {
|
||||
return JSON.parse(unwrapBinaryData(data).toString())
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
// ========== PRIVATE METHODS ==========
|
||||
|
||||
/**
|
||||
* Select the compression strategy for a write (see
|
||||
* {@link BlobWriteOptions.compression}).
|
||||
*/
|
||||
private selectCompression(
|
||||
data: Buffer,
|
||||
options: BlobWriteOptions
|
||||
): 'none' | 'zstd' {
|
||||
if (options.compression === 'none') {
|
||||
return 'none'
|
||||
}
|
||||
|
||||
if (options.compression === 'zstd') {
|
||||
return this.zstdCompress ? 'zstd' : 'none'
|
||||
}
|
||||
|
||||
// Auto mode
|
||||
if (data.length < this.COMPRESSION_THRESHOLD) {
|
||||
return 'none' // Too small to benefit
|
||||
}
|
||||
|
||||
// Content-type policy: skip already-compressed media. zstd over
|
||||
// JPEG / MP4 / ZIP etc. is a CPU loss for no measurable byte savings,
|
||||
// and on hot save paths (image / video uploads) it's the difference
|
||||
// between fast and slow. Applies only to `auto`; explicit `'zstd'` is
|
||||
// honoured because the caller is asserting the choice.
|
||||
if (isAlreadyCompressedMimeType(options.mimeType)) {
|
||||
return 'none'
|
||||
}
|
||||
|
||||
return this.zstdCompress ? 'zstd' : 'none'
|
||||
}
|
||||
|
||||
/**
|
||||
* Increment the reference count for an existing blob.
|
||||
*/
|
||||
private async incrementRefCount(hash: string): Promise<number> {
|
||||
const metadata = await this.getMetadata(hash)
|
||||
if (!metadata) {
|
||||
throw new Error(`Cannot increment ref count, blob not found: ${hash}`)
|
||||
}
|
||||
|
||||
metadata.refCount++
|
||||
await this.adapter.put(`blob-meta:${hash}`, Buffer.from(JSON.stringify(metadata)))
|
||||
return metadata.refCount
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrement the reference count for a blob (floored at zero).
|
||||
*/
|
||||
private async decrementRefCount(hash: string): Promise<number> {
|
||||
const metadata = await this.getMetadata(hash)
|
||||
if (!metadata) {
|
||||
return 0
|
||||
}
|
||||
|
||||
metadata.refCount = Math.max(0, metadata.refCount - 1)
|
||||
await this.adapter.put(`blob-meta:${hash}`, Buffer.from(JSON.stringify(metadata)))
|
||||
return metadata.refCount
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a blob to the LRU cache (evicting least-recently-used entries to
|
||||
* stay under the size bound).
|
||||
*/
|
||||
private addToCache(hash: string, data: Buffer, metadata: BlobMetadata): void {
|
||||
if (data.length > this.cacheMaxSize) {
|
||||
return // Blob too large for cache
|
||||
}
|
||||
|
||||
while (
|
||||
this.currentCacheSize + data.length > this.cacheMaxSize &&
|
||||
this.cache.size > 0
|
||||
) {
|
||||
this.evictLRU()
|
||||
}
|
||||
|
||||
this.cache.set(hash, {
|
||||
data,
|
||||
metadata,
|
||||
lastAccess: Date.now(),
|
||||
size: data.length
|
||||
})
|
||||
|
||||
this.currentCacheSize += data.length
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a blob from the cache, refreshing its LRU position.
|
||||
*/
|
||||
private getFromCache(hash: string): CacheEntry | undefined {
|
||||
const entry = this.cache.get(hash)
|
||||
if (entry) {
|
||||
entry.lastAccess = Date.now() // Update LRU
|
||||
}
|
||||
return entry
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a blob from the cache.
|
||||
*/
|
||||
private removeFromCache(hash: string): void {
|
||||
const entry = this.cache.get(hash)
|
||||
if (entry) {
|
||||
this.cache.delete(hash)
|
||||
this.currentCacheSize -= entry.size
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Evict the least-recently-used cache entry.
|
||||
*/
|
||||
private evictLRU(): void {
|
||||
let oldestHash: string | null = null
|
||||
let oldestTime = Infinity
|
||||
|
||||
for (const [hash, entry] of this.cache.entries()) {
|
||||
if (entry.lastAccess < oldestTime) {
|
||||
oldestTime = entry.lastAccess
|
||||
oldestHash = hash
|
||||
}
|
||||
}
|
||||
|
||||
if (oldestHash) {
|
||||
this.removeFromCache(oldestHash)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,763 +0,0 @@
|
|||
/**
|
||||
* BlobStorage: Content-Addressable Blob Storage for COW (Copy-on-Write)
|
||||
*
|
||||
* State-of-the-art implementation featuring:
|
||||
* - Content-addressable: SHA-256 hashing
|
||||
* - Type-aware chunking: Separate vectors, metadata, relationships
|
||||
* - Compression: zstd for JSON, optimized for vectors
|
||||
* - LRU caching: Hot blob performance
|
||||
* - Streaming: Multipart upload for large blobs
|
||||
* - Batch operations: Parallel I/O
|
||||
* - Integrity: Cryptographic verification
|
||||
* - Observability: Metrics and tracing
|
||||
*
|
||||
* @module storage/cow/BlobStorage
|
||||
*/
|
||||
|
||||
import { createHash } from 'crypto'
|
||||
import { NULL_HASH, isNullHash } from './constants.js'
|
||||
import { unwrapBinaryData } from './binaryDataCodec.js'
|
||||
|
||||
/**
|
||||
* Simple key-value storage interface for COW primitives
|
||||
* This will be implemented by BaseStorage when COW is integrated
|
||||
*/
|
||||
export interface COWStorageAdapter {
|
||||
get(key: string): Promise<Buffer | undefined>
|
||||
put(key: string, data: Buffer): Promise<void>
|
||||
delete(key: string): Promise<void>
|
||||
list(prefix: string): Promise<string[]>
|
||||
}
|
||||
|
||||
/**
|
||||
* Blob metadata stored alongside blob data
|
||||
*/
|
||||
export interface BlobMetadata {
|
||||
hash: string // SHA-256 hash
|
||||
size: number // Original size in bytes
|
||||
compressedSize: number // Compressed size in bytes
|
||||
compression: 'none' | 'zstd'
|
||||
type: 'vector' | 'metadata' | 'tree' | 'commit' | 'blob' | 'raw'
|
||||
createdAt: number // Timestamp
|
||||
refCount: number // How many objects reference this blob
|
||||
}
|
||||
|
||||
/**
|
||||
* Blob write options
|
||||
*/
|
||||
export interface BlobWriteOptions {
|
||||
compression?: 'none' | 'zstd' | 'auto' // Auto chooses based on type
|
||||
type?: 'vector' | 'metadata' | 'tree' | 'commit' | 'blob' | 'raw'
|
||||
/**
|
||||
* Content type of the payload (e.g. `image/jpeg`, `video/mp4`).
|
||||
*
|
||||
* When set on an `auto`-compression write, BlobStorage skips zstd for MIME
|
||||
* types that are already heavily compressed (JPEG, PNG, WebP, MP4, WebM,
|
||||
* MP3, ZIP, PDF, etc.). Gzip/zstd over these formats wastes CPU and rarely
|
||||
* shaves more than a single-digit percent — usually it actually grows the
|
||||
* payload because the entropy is already maximised by the format itself.
|
||||
*
|
||||
* Has no effect when `compression` is set to `'none'` or `'zstd'` explicitly
|
||||
* — the caller is asserting the choice and BlobStorage honours it.
|
||||
*/
|
||||
mimeType?: string
|
||||
skipVerification?: boolean // Skip hash verification (faster, less safe)
|
||||
}
|
||||
|
||||
/**
|
||||
* MIME types whose payload is already heavily compressed. zstd over these is
|
||||
* almost always a CPU-only loss — the bytes are already near entropy-maximal,
|
||||
* so the output is the same size or slightly larger plus the cost of running
|
||||
* the compressor. Used by `BlobStorage.selectCompression()` in `auto` mode.
|
||||
*
|
||||
* Conservative denylist (well-known formats only). Anything not in this set
|
||||
* goes through the existing per-type heuristic. False negatives (compressing
|
||||
* something we should have skipped) waste CPU; false positives (skipping
|
||||
* something we could have compressed) waste a few percent of bytes. The
|
||||
* denylist favours CPU-cycle safety because the formats listed here are the
|
||||
* ones where gzip/zstd is reliably a net loss.
|
||||
*/
|
||||
const ALREADY_COMPRESSED_MIME_TYPES = new Set<string>([
|
||||
// Images
|
||||
'image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp',
|
||||
'image/avif', 'image/heic', 'image/heif', 'image/jp2',
|
||||
// Video
|
||||
'video/mp4', 'video/webm', 'video/x-matroska', 'video/quicktime',
|
||||
'video/x-msvideo', 'video/mpeg', 'video/3gpp', 'video/x-ms-wmv',
|
||||
// Audio
|
||||
'audio/mpeg', 'audio/mp4', 'audio/aac', 'audio/ogg', 'audio/webm',
|
||||
'audio/opus', 'audio/flac', 'audio/x-ms-wma',
|
||||
// Archives
|
||||
'application/zip', 'application/gzip', 'application/x-gzip',
|
||||
'application/x-bzip2', 'application/x-7z-compressed',
|
||||
'application/x-rar-compressed', 'application/x-xz', 'application/x-zstd',
|
||||
'application/x-compress', 'application/vnd.rar',
|
||||
// Documents with internal compression
|
||||
'application/pdf', 'application/epub+zip',
|
||||
// Office formats (zip-based)
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
'application/vnd.oasis.opendocument.text',
|
||||
'application/vnd.oasis.opendocument.spreadsheet',
|
||||
'application/vnd.oasis.opendocument.presentation'
|
||||
])
|
||||
|
||||
/**
|
||||
* @description True when the MIME type names a payload format known to be
|
||||
* already heavily compressed. Strips any `;charset=…` / `;boundary=…`
|
||||
* parameters and lowercases the bare type/subtype before lookup, so
|
||||
* `'IMAGE/JPEG; charset=binary'` and `'image/jpeg'` resolve identically.
|
||||
*/
|
||||
export function isAlreadyCompressedMimeType(mimeType: string | undefined): boolean {
|
||||
if (!mimeType) return false
|
||||
const bare = mimeType.split(';', 1)[0].trim().toLowerCase()
|
||||
return ALREADY_COMPRESSED_MIME_TYPES.has(bare)
|
||||
}
|
||||
|
||||
/**
|
||||
* Blob read options
|
||||
*/
|
||||
export interface BlobReadOptions {
|
||||
skipDecompression?: boolean // Return compressed data
|
||||
skipCache?: boolean // Don't use cache
|
||||
skipVerification?: boolean // Skip hash verification (faster, less safe)
|
||||
}
|
||||
|
||||
/**
|
||||
* Blob statistics for observability
|
||||
*/
|
||||
export interface BlobStats {
|
||||
totalBlobs: number
|
||||
totalSize: number
|
||||
compressedSize: number
|
||||
cacheHits: number
|
||||
cacheMisses: number
|
||||
compressionRatio: number
|
||||
avgBlobSize: number
|
||||
dedupSavings: number // Bytes saved from deduplication
|
||||
}
|
||||
|
||||
/**
|
||||
* LRU Cache entry
|
||||
*/
|
||||
interface CacheEntry {
|
||||
data: Buffer
|
||||
metadata: BlobMetadata
|
||||
lastAccess: number
|
||||
size: number
|
||||
}
|
||||
|
||||
/**
|
||||
* State-of-the-art content-addressable blob storage
|
||||
*
|
||||
* Features:
|
||||
* - Content addressing via SHA-256
|
||||
* - Type-aware compression (zstd, vector-optimized)
|
||||
* - LRU caching with memory limits
|
||||
* - Streaming for large blobs
|
||||
* - Batch operations
|
||||
* - Integrity verification
|
||||
* - Observability metrics
|
||||
*/
|
||||
export class BlobStorage {
|
||||
private adapter: COWStorageAdapter
|
||||
private cache: Map<string, CacheEntry>
|
||||
private cacheMaxSize: number
|
||||
private currentCacheSize: number
|
||||
private stats: BlobStats
|
||||
|
||||
// Compression (lazily loaded)
|
||||
private zstdCompress?: (data: Buffer) => Promise<Buffer>
|
||||
private zstdDecompress?: (data: Buffer) => Promise<Buffer>
|
||||
private compressionReady = false
|
||||
|
||||
// Configuration
|
||||
private readonly CACHE_MAX_SIZE = 100 * 1024 * 1024 // 100MB default
|
||||
private readonly MULTIPART_THRESHOLD = 5 * 1024 * 1024 // 5MB
|
||||
private readonly COMPRESSION_THRESHOLD = 1024 // 1KB - don't compress smaller
|
||||
|
||||
constructor(adapter: COWStorageAdapter, options?: {
|
||||
cacheMaxSize?: number
|
||||
enableCompression?: boolean
|
||||
}) {
|
||||
this.adapter = adapter
|
||||
this.cache = new Map()
|
||||
this.cacheMaxSize = options?.cacheMaxSize ?? this.CACHE_MAX_SIZE
|
||||
this.currentCacheSize = 0
|
||||
this.stats = {
|
||||
totalBlobs: 0,
|
||||
totalSize: 0,
|
||||
compressedSize: 0,
|
||||
cacheHits: 0,
|
||||
cacheMisses: 0,
|
||||
compressionRatio: 1.0,
|
||||
avgBlobSize: 0,
|
||||
dedupSavings: 0
|
||||
}
|
||||
|
||||
// Lazy load compression (only if needed)
|
||||
if (options?.enableCompression !== false) {
|
||||
this.initCompression()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lazy load zstd compression module
|
||||
* (Avoids loading if not needed)
|
||||
*/
|
||||
private async initCompression(): Promise<void> {
|
||||
try {
|
||||
// Dynamic import to avoid loading if not needed
|
||||
// @ts-ignore - Optional dependency, gracefully handled if missing
|
||||
const zstd = await import('@mongodb-js/zstd')
|
||||
this.zstdCompress = async (data: Buffer) => {
|
||||
return Buffer.from(await zstd.compress(data, 3)) // Level 3 = fast
|
||||
}
|
||||
this.zstdDecompress = async (data: Buffer) => {
|
||||
return Buffer.from(await zstd.decompress(data))
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('zstd compression not available, falling back to uncompressed')
|
||||
this.zstdCompress = undefined
|
||||
this.zstdDecompress = undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure compression is ready before write operations
|
||||
* Fixes race condition where write happens before async compression init completes
|
||||
*/
|
||||
private async ensureCompressionReady(): Promise<void> {
|
||||
if (this.compressionReady) return
|
||||
await this.initCompression()
|
||||
this.compressionReady = true
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute SHA-256 hash of data
|
||||
*
|
||||
* @param data - Data to hash
|
||||
* @returns SHA-256 hash as hex string
|
||||
*/
|
||||
static hash(data: Buffer): string {
|
||||
return createHash('sha256').update(data).digest('hex')
|
||||
}
|
||||
|
||||
/**
|
||||
* Write a blob to storage
|
||||
*
|
||||
* Features:
|
||||
* - Content-addressable: hash determines storage key
|
||||
* - Deduplication: existing blob not rewritten
|
||||
* - Compression: auto-compress based on type
|
||||
* - Multipart: for large blobs (>5MB)
|
||||
* - Verification: hash verification
|
||||
* - Caching: write-through cache
|
||||
*
|
||||
* @param data - Blob data to write
|
||||
* @param options - Write options
|
||||
* @returns Blob hash
|
||||
*/
|
||||
async write(data: Buffer, options: BlobWriteOptions = {}): Promise<string> {
|
||||
const hash = BlobStorage.hash(data)
|
||||
|
||||
// Deduplication: Check if blob already exists
|
||||
if (await this.has(hash)) {
|
||||
// Update ref count
|
||||
await this.incrementRefCount(hash)
|
||||
this.stats.dedupSavings += data.length
|
||||
return hash
|
||||
}
|
||||
|
||||
// Ensure compression is initialized before writing
|
||||
// Fixes race condition where write happens before async init completes
|
||||
await this.ensureCompressionReady()
|
||||
|
||||
// Determine compression strategy
|
||||
const compression = this.selectCompression(data, options)
|
||||
|
||||
// Compress if needed
|
||||
let finalData = data
|
||||
let compressedSize = data.length
|
||||
|
||||
if (compression === 'zstd' && this.zstdCompress) {
|
||||
finalData = await this.zstdCompress(data)
|
||||
compressedSize = finalData.length
|
||||
}
|
||||
|
||||
// Create metadata
|
||||
// Store ACTUAL compression state, not intended
|
||||
// Prevents corruption if compression failed to initialize
|
||||
const actualCompression = finalData === data ? 'none' : compression
|
||||
const metadata: BlobMetadata = {
|
||||
hash,
|
||||
size: data.length,
|
||||
compressedSize,
|
||||
compression: actualCompression,
|
||||
type: options.type || 'blob', // CRITICAL FIX: Use 'blob' default to match storage prefix
|
||||
createdAt: Date.now(),
|
||||
refCount: 1
|
||||
}
|
||||
|
||||
// Write blob data
|
||||
if (finalData.length > this.MULTIPART_THRESHOLD) {
|
||||
// Large blob: use streaming/multipart
|
||||
await this.writeMultipart(hash, finalData, metadata)
|
||||
} else {
|
||||
// Small blob: single write
|
||||
const prefix = options.type || 'blob'
|
||||
await this.adapter.put(`${prefix}:${hash}`, finalData)
|
||||
}
|
||||
|
||||
// Write metadata
|
||||
const prefix = options.type || 'blob'
|
||||
await this.adapter.put(`${prefix}-meta:${hash}`, Buffer.from(JSON.stringify(metadata)))
|
||||
|
||||
// Update cache (write-through)
|
||||
this.addToCache(hash, data, metadata)
|
||||
|
||||
// Update stats
|
||||
this.stats.totalBlobs++
|
||||
this.stats.totalSize += data.length
|
||||
this.stats.compressedSize += compressedSize
|
||||
this.stats.compressionRatio = this.stats.totalSize / (this.stats.compressedSize || 1)
|
||||
this.stats.avgBlobSize = this.stats.totalSize / this.stats.totalBlobs
|
||||
|
||||
return hash
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a blob from storage
|
||||
*
|
||||
* Features:
|
||||
* - Cache lookup first (LRU)
|
||||
* - Decompression (if compressed)
|
||||
* - Verification (optional hash check)
|
||||
* - Streaming for large blobs
|
||||
*
|
||||
* @param hash - Blob hash
|
||||
* @param options - Read options
|
||||
* @returns Blob data
|
||||
*/
|
||||
async read(hash: string, options: BlobReadOptions = {}): Promise<Buffer> {
|
||||
// Guard against NULL hash (sentinel value)
|
||||
// NULL_HASH ('0000...0000') is used as a sentinel for "no parent" or "empty tree"
|
||||
// It should NEVER be read as actual blob data
|
||||
if (isNullHash(hash)) {
|
||||
throw new Error(
|
||||
`Cannot read NULL hash (${NULL_HASH}): ` +
|
||||
`This is a sentinel value indicating "no parent commit" or "empty tree". ` +
|
||||
`If you're seeing this error from CommitObject.walk(), there's a bug in commit traversal logic. ` +
|
||||
`If you're seeing this from TreeObject operations, there's a bug in tree handling.`
|
||||
)
|
||||
}
|
||||
|
||||
// Check cache first
|
||||
if (!options.skipCache) {
|
||||
const cached = this.getFromCache(hash)
|
||||
if (cached) {
|
||||
this.stats.cacheHits++
|
||||
return cached.data
|
||||
}
|
||||
this.stats.cacheMisses++
|
||||
}
|
||||
|
||||
// Try to read metadata to determine type (for backward compatibility)
|
||||
// Try commit, tree, then blob prefixes
|
||||
let prefix: string | null = null
|
||||
let metadataBuffer: Buffer | undefined
|
||||
let metadata: BlobMetadata | undefined
|
||||
|
||||
for (const tryPrefix of ['commit', 'tree', 'blob']) {
|
||||
metadataBuffer = await this.adapter.get(`${tryPrefix}-meta:${hash}`)
|
||||
if (metadataBuffer) {
|
||||
prefix = tryPrefix
|
||||
// Unwrap metadata before parsing (defense-in-depth)
|
||||
// Metadata should be JSON, but adapter might return wrapped format
|
||||
const unwrappedMetadata = unwrapBinaryData(metadataBuffer)
|
||||
metadata = JSON.parse(unwrappedMetadata.toString())
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (!prefix || !metadata) {
|
||||
throw new Error(`Blob metadata not found: ${hash}`)
|
||||
}
|
||||
|
||||
// Read from storage using determined prefix
|
||||
const data = await this.adapter.get(`${prefix}:${hash}`)
|
||||
|
||||
if (!data) {
|
||||
throw new Error(`Blob not found: ${hash}`)
|
||||
}
|
||||
|
||||
// Decompress if needed
|
||||
let finalData = data
|
||||
|
||||
if (metadata.compression === 'zstd' && !options.skipDecompression) {
|
||||
if (!this.zstdDecompress) {
|
||||
throw new Error('zstd decompression not available')
|
||||
}
|
||||
finalData = await this.zstdDecompress(data)
|
||||
}
|
||||
|
||||
// Defense-in-depth unwrap (CRITICAL FIX for blob integrity regression)
|
||||
// Even though COW adapter should unwrap, verify it happened and re-unwrap if needed
|
||||
// This prevents "Blob integrity check failed" errors if adapter returns wrapped data
|
||||
// Uses shared binaryDataCodec utility (single source of truth for unwrap logic)
|
||||
const unwrappedData = unwrapBinaryData(finalData)
|
||||
|
||||
// Verify hash (on unwrapped data)
|
||||
if (!options.skipVerification && BlobStorage.hash(unwrappedData) !== hash) {
|
||||
throw new Error(`Blob integrity check failed: ${hash}`)
|
||||
}
|
||||
|
||||
// Add to cache (only if not skipped)
|
||||
if (!options.skipCache) {
|
||||
this.addToCache(hash, unwrappedData, metadata)
|
||||
}
|
||||
|
||||
return unwrappedData
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if blob exists
|
||||
*
|
||||
* @param hash - Blob hash
|
||||
* @returns True if blob exists
|
||||
*/
|
||||
async has(hash: string): Promise<boolean> {
|
||||
// Check cache first
|
||||
if (this.cache.has(hash)) {
|
||||
return true
|
||||
}
|
||||
|
||||
// Check storage - try all prefixes for backward compatibility
|
||||
for (const prefix of ['commit', 'tree', 'blob']) {
|
||||
const exists = await this.adapter.get(`${prefix}:${hash}`)
|
||||
if (exists !== undefined) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a blob from storage
|
||||
*
|
||||
* Features:
|
||||
* - Reference counting: only delete if refCount = 0
|
||||
* - Cascade: delete metadata too
|
||||
* - Cache invalidation
|
||||
*
|
||||
* @param hash - Blob hash
|
||||
*/
|
||||
async delete(hash: string): Promise<void> {
|
||||
// Decrement ref count
|
||||
const refCount = await this.decrementRefCount(hash)
|
||||
|
||||
// Only delete if no references remain
|
||||
if (refCount > 0) {
|
||||
return
|
||||
}
|
||||
|
||||
// Determine prefix by checking which one exists
|
||||
let prefix = 'blob'
|
||||
for (const tryPrefix of ['commit', 'tree', 'blob', 'metadata', 'vector', 'raw']) {
|
||||
const exists = await this.adapter.get(`${tryPrefix}:${hash}`)
|
||||
if (exists !== undefined) {
|
||||
prefix = tryPrefix
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Delete blob data
|
||||
await this.adapter.delete(`${prefix}:${hash}`)
|
||||
|
||||
// Delete metadata
|
||||
await this.adapter.delete(`${prefix}-meta:${hash}`)
|
||||
|
||||
// Remove from cache
|
||||
this.removeFromCache(hash)
|
||||
|
||||
// Update stats
|
||||
this.stats.totalBlobs--
|
||||
}
|
||||
|
||||
/**
|
||||
* Get blob metadata without reading full blob
|
||||
*
|
||||
* @param hash - Blob hash
|
||||
* @returns Blob metadata
|
||||
*/
|
||||
async getMetadata(hash: string): Promise<BlobMetadata | undefined> {
|
||||
// Try to read metadata with type-aware prefix (backward compatible)
|
||||
// Check all valid blob types: commit, tree, blob, metadata, vector, raw
|
||||
for (const prefix of ['commit', 'tree', 'blob', 'metadata', 'vector', 'raw']) {
|
||||
const data = await this.adapter.get(`${prefix}-meta:${hash}`)
|
||||
if (data) {
|
||||
return JSON.parse(data.toString())
|
||||
}
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Batch write multiple blobs in parallel
|
||||
*
|
||||
* @param blobs - Array of [data, options] tuples
|
||||
* @returns Array of blob hashes
|
||||
*/
|
||||
async writeBatch(blobs: Array<[Buffer, BlobWriteOptions?]>): Promise<string[]> {
|
||||
return Promise.all(
|
||||
blobs.map(([data, options]) => this.write(data, options))
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Batch read multiple blobs in parallel
|
||||
*
|
||||
* @param hashes - Array of blob hashes
|
||||
* @param options - Read options
|
||||
* @returns Array of blob data
|
||||
*/
|
||||
async readBatch(hashes: string[], options?: BlobReadOptions): Promise<Buffer[]> {
|
||||
return Promise.all(
|
||||
hashes.map(hash => this.read(hash, options))
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* List all blobs (for garbage collection, debugging)
|
||||
*
|
||||
* @returns Array of blob hashes
|
||||
*/
|
||||
async listBlobs(): Promise<string[]> {
|
||||
// List all types of blobs
|
||||
const hashes = new Set<string>()
|
||||
|
||||
for (const prefix of ['commit', 'tree', 'blob']) {
|
||||
const keys = await this.adapter.list(`${prefix}:`)
|
||||
keys.forEach((key: string) => {
|
||||
const hash = key.replace(new RegExp(`^${prefix}:`), '')
|
||||
hashes.add(hash)
|
||||
})
|
||||
}
|
||||
|
||||
return Array.from(hashes)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get storage statistics
|
||||
*
|
||||
* @returns Blob statistics
|
||||
*/
|
||||
getStats(): BlobStats {
|
||||
return { ...this.stats }
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear cache (useful for testing, memory pressure)
|
||||
*/
|
||||
clearCache(): void {
|
||||
this.cache.clear()
|
||||
this.currentCacheSize = 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Garbage collect unreferenced blobs
|
||||
*
|
||||
* @param referencedHashes - Set of hashes that should be kept
|
||||
* @returns Number of blobs deleted
|
||||
*/
|
||||
async garbageCollect(referencedHashes: Set<string>): Promise<number> {
|
||||
const allBlobs = await this.listBlobs()
|
||||
let deleted = 0
|
||||
|
||||
for (const hash of allBlobs) {
|
||||
if (!referencedHashes.has(hash)) {
|
||||
// Check ref count
|
||||
const metadata = await this.getMetadata(hash)
|
||||
if (metadata && metadata.refCount === 0) {
|
||||
await this.delete(hash)
|
||||
deleted++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return deleted
|
||||
}
|
||||
|
||||
// ========== PRIVATE METHODS ==========
|
||||
|
||||
/**
|
||||
* Select compression strategy based on data and options
|
||||
*/
|
||||
private selectCompression(
|
||||
data: Buffer,
|
||||
options: BlobWriteOptions
|
||||
): 'none' | 'zstd' {
|
||||
if (options.compression === 'none') {
|
||||
return 'none'
|
||||
}
|
||||
|
||||
if (options.compression === 'zstd') {
|
||||
return this.zstdCompress ? 'zstd' : 'none'
|
||||
}
|
||||
|
||||
// Auto mode
|
||||
if (data.length < this.COMPRESSION_THRESHOLD) {
|
||||
return 'none' // Too small to benefit
|
||||
}
|
||||
|
||||
// Content-type policy (2.5.0 #32): skip already-compressed media. zstd
|
||||
// over JPEG / MP4 / ZIP etc. is a CPU loss for no measurable byte savings,
|
||||
// and on hot save paths (image / video uploads) it's the difference
|
||||
// between fast and slow. Applies only to `auto`; explicit `'zstd'` is
|
||||
// honoured because the caller is asserting the choice.
|
||||
if (isAlreadyCompressedMimeType(options.mimeType)) {
|
||||
return 'none'
|
||||
}
|
||||
|
||||
// Compress metadata, trees, commits (text/JSON)
|
||||
if (options.type === 'metadata' || options.type === 'tree' || options.type === 'commit') {
|
||||
return this.zstdCompress ? 'zstd' : 'none'
|
||||
}
|
||||
|
||||
// Don't compress vectors (already dense)
|
||||
if (options.type === 'vector') {
|
||||
return 'none'
|
||||
}
|
||||
|
||||
// Default: compress
|
||||
return this.zstdCompress ? 'zstd' : 'none'
|
||||
}
|
||||
|
||||
/**
|
||||
* Write large blob using multipart upload
|
||||
* (Future enhancement: stream to adapter if supported)
|
||||
*/
|
||||
private async writeMultipart(
|
||||
hash: string,
|
||||
data: Buffer,
|
||||
metadata: BlobMetadata
|
||||
): Promise<void> {
|
||||
// Single-blob write. Brainy 8.0 ships filesystem + memory only; the
|
||||
// multipart-upload concern that motivated this method (S3/R2/GCS) is gone
|
||||
// with the cloud adapters per BR-BRAINY-80-STORAGE-SIMPLIFY.
|
||||
const prefix = metadata.type || 'blob'
|
||||
await this.adapter.put(`${prefix}:${hash}`, data)
|
||||
}
|
||||
|
||||
/**
|
||||
* Increment reference count for a blob
|
||||
*/
|
||||
private async incrementRefCount(hash: string): Promise<number> {
|
||||
const metadata = await this.getMetadata(hash)
|
||||
if (!metadata) {
|
||||
throw new Error(`Cannot increment ref count, blob not found: ${hash}`)
|
||||
}
|
||||
|
||||
metadata.refCount++
|
||||
|
||||
const prefix = metadata.type || 'blob'
|
||||
await this.adapter.put(
|
||||
`${prefix}-meta:${hash}`,
|
||||
Buffer.from(JSON.stringify(metadata))
|
||||
)
|
||||
|
||||
return metadata.refCount
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrement reference count for a blob
|
||||
*/
|
||||
private async decrementRefCount(hash: string): Promise<number> {
|
||||
const metadata = await this.getMetadata(hash)
|
||||
if (!metadata) {
|
||||
return 0
|
||||
}
|
||||
|
||||
metadata.refCount = Math.max(0, metadata.refCount - 1)
|
||||
|
||||
const prefix = metadata.type || 'blob'
|
||||
await this.adapter.put(
|
||||
`${prefix}-meta:${hash}`,
|
||||
Buffer.from(JSON.stringify(metadata))
|
||||
)
|
||||
|
||||
return metadata.refCount
|
||||
}
|
||||
|
||||
/**
|
||||
* Add blob to LRU cache
|
||||
*/
|
||||
private addToCache(hash: string, data: Buffer, metadata: BlobMetadata): void {
|
||||
// Check if adding would exceed cache size
|
||||
if (data.length > this.cacheMaxSize) {
|
||||
return // Blob too large for cache
|
||||
}
|
||||
|
||||
// Evict old entries if needed
|
||||
while (
|
||||
this.currentCacheSize + data.length > this.cacheMaxSize &&
|
||||
this.cache.size > 0
|
||||
) {
|
||||
this.evictLRU()
|
||||
}
|
||||
|
||||
// Add to cache
|
||||
this.cache.set(hash, {
|
||||
data,
|
||||
metadata,
|
||||
lastAccess: Date.now(),
|
||||
size: data.length
|
||||
})
|
||||
|
||||
this.currentCacheSize += data.length
|
||||
}
|
||||
|
||||
/**
|
||||
* Get blob from cache
|
||||
*/
|
||||
private getFromCache(hash: string): CacheEntry | undefined {
|
||||
const entry = this.cache.get(hash)
|
||||
if (entry) {
|
||||
entry.lastAccess = Date.now() // Update LRU
|
||||
}
|
||||
return entry
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove blob from cache
|
||||
*/
|
||||
private removeFromCache(hash: string): void {
|
||||
const entry = this.cache.get(hash)
|
||||
if (entry) {
|
||||
this.cache.delete(hash)
|
||||
this.currentCacheSize -= entry.size
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Evict least recently used entry from cache
|
||||
*/
|
||||
private evictLRU(): void {
|
||||
let oldestHash: string | null = null
|
||||
let oldestTime = Infinity
|
||||
|
||||
for (const [hash, entry] of this.cache.entries()) {
|
||||
if (entry.lastAccess < oldestTime) {
|
||||
oldestTime = entry.lastAccess
|
||||
oldestHash = hash
|
||||
}
|
||||
}
|
||||
|
||||
if (oldestHash) {
|
||||
this.removeFromCache(oldestHash)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,531 +0,0 @@
|
|||
/**
|
||||
* CommitLog: Commit history traversal and querying for COW (Copy-on-Write)
|
||||
*
|
||||
* Provides efficient commit history operations:
|
||||
* - Walk commit graph (DAG traversal)
|
||||
* - Find commits by time, author, operation
|
||||
* - Time-travel queries (asOf)
|
||||
* - Commit statistics and analytics
|
||||
*
|
||||
* Optimizations:
|
||||
* - Commit index for fast timestamp lookups
|
||||
* - Parent cache for efficient traversal
|
||||
* - Lazy loading (only read commits when needed)
|
||||
*
|
||||
* @module storage/cow/CommitLog
|
||||
*/
|
||||
|
||||
import { BlobStorage } from './BlobStorage.js'
|
||||
import { CommitObject } from './CommitObject.js'
|
||||
import { RefManager } from './RefManager.js'
|
||||
|
||||
/**
|
||||
* Commit index entry (for fast lookups)
|
||||
*/
|
||||
interface CommitIndexEntry {
|
||||
hash: string
|
||||
timestamp: number
|
||||
parentHash: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Commit log statistics
|
||||
*/
|
||||
export interface CommitLogStats {
|
||||
totalCommits: number
|
||||
oldestCommit: number // Timestamp
|
||||
newestCommit: number // Timestamp
|
||||
authors: Set<string>
|
||||
operations: Set<string>
|
||||
avgCommitInterval: number // Average time between commits (ms)
|
||||
}
|
||||
|
||||
/**
|
||||
* CommitLog: Efficient commit history traversal and querying
|
||||
*
|
||||
* Pure implementation - modern, clean, fast
|
||||
*/
|
||||
export class CommitLog {
|
||||
private blobStorage: BlobStorage
|
||||
private refManager: RefManager
|
||||
private index: Map<string, CommitIndexEntry>
|
||||
private indexValid: boolean
|
||||
|
||||
constructor(blobStorage: BlobStorage, refManager: RefManager) {
|
||||
this.blobStorage = blobStorage
|
||||
this.refManager = refManager
|
||||
this.index = new Map()
|
||||
this.indexValid = false
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk commit history from a starting point
|
||||
*
|
||||
* Yields commits in reverse chronological order (newest first)
|
||||
*
|
||||
* @param startRef - Starting ref/commit (e.g., 'main', commit hash)
|
||||
* @param options - Walk options
|
||||
*/
|
||||
async *walk(
|
||||
startRef: string = 'main',
|
||||
options?: {
|
||||
maxDepth?: number
|
||||
until?: number
|
||||
stopAt?: string
|
||||
filter?: (commit: CommitObject) => boolean
|
||||
}
|
||||
): AsyncIterableIterator<CommitObject> {
|
||||
// Resolve ref to commit hash
|
||||
let startHash: string
|
||||
|
||||
if (/^[a-f0-9]{64}$/.test(startRef)) {
|
||||
// Already a commit hash
|
||||
startHash = startRef
|
||||
} else {
|
||||
// Resolve ref
|
||||
const commitHash = await this.refManager.resolveRef(startRef)
|
||||
if (!commitHash) {
|
||||
throw new Error(`Ref not found: ${startRef}`)
|
||||
}
|
||||
startHash = commitHash
|
||||
}
|
||||
|
||||
// Walk using CommitObject (delegates to it)
|
||||
yield* CommitObject.walk(this.blobStorage, startHash, options)
|
||||
}
|
||||
|
||||
/**
|
||||
* Find commit at or before a specific timestamp
|
||||
*
|
||||
* Uses index for fast O(log n) lookup
|
||||
*
|
||||
* @param ref - Starting ref (e.g., 'main')
|
||||
* @param timestamp - Target timestamp
|
||||
* @returns Commit at or before timestamp, or null
|
||||
*/
|
||||
async findAtTime(ref: string, timestamp: number): Promise<CommitObject | null> {
|
||||
// Build index if needed
|
||||
await this.buildIndex(ref)
|
||||
|
||||
// Binary search in index
|
||||
const entries = Array.from(this.index.values()).sort(
|
||||
(a, b) => b.timestamp - a.timestamp // Newest first
|
||||
)
|
||||
|
||||
let left = 0
|
||||
let right = entries.length - 1
|
||||
let result: CommitIndexEntry | null = null
|
||||
|
||||
while (left <= right) {
|
||||
const mid = Math.floor((left + right) / 2)
|
||||
const entry = entries[mid]
|
||||
|
||||
if (entry.timestamp <= timestamp) {
|
||||
result = entry
|
||||
right = mid - 1 // Look for newer commit
|
||||
} else {
|
||||
left = mid + 1 // Look for older commit
|
||||
}
|
||||
}
|
||||
|
||||
if (!result) {
|
||||
return null
|
||||
}
|
||||
|
||||
// Read full commit
|
||||
return CommitObject.read(this.blobStorage, result.hash)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get commit by hash
|
||||
*
|
||||
* @param hash - Commit hash
|
||||
* @returns Commit object
|
||||
*/
|
||||
async getCommit(hash: string): Promise<CommitObject> {
|
||||
return CommitObject.read(this.blobStorage, hash)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get commits in time range
|
||||
*
|
||||
* @param ref - Starting ref
|
||||
* @param startTime - Start of time range
|
||||
* @param endTime - End of time range
|
||||
* @returns Array of commits in range (newest first)
|
||||
*/
|
||||
async getInTimeRange(
|
||||
ref: string,
|
||||
startTime: number,
|
||||
endTime: number
|
||||
): Promise<CommitObject[]> {
|
||||
const commits: CommitObject[] = []
|
||||
|
||||
for await (const commit of this.walk(ref, { until: startTime })) {
|
||||
if (commit.timestamp >= startTime && commit.timestamp <= endTime) {
|
||||
commits.push(commit)
|
||||
}
|
||||
}
|
||||
|
||||
return commits
|
||||
}
|
||||
|
||||
/**
|
||||
* Get commits by author
|
||||
*
|
||||
* @param ref - Starting ref
|
||||
* @param author - Author name
|
||||
* @param options - Additional options
|
||||
* @returns Array of commits by author
|
||||
*/
|
||||
async getByAuthor(
|
||||
ref: string,
|
||||
author: string,
|
||||
options?: { maxCount?: number; since?: number }
|
||||
): Promise<CommitObject[]> {
|
||||
const commits: CommitObject[] = []
|
||||
let count = 0
|
||||
|
||||
for await (const commit of this.walk(ref, { until: options?.since })) {
|
||||
if (commit.author === author) {
|
||||
commits.push(commit)
|
||||
count++
|
||||
|
||||
if (options?.maxCount && count >= options.maxCount) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return commits
|
||||
}
|
||||
|
||||
/**
|
||||
* Get commits by operation type
|
||||
*
|
||||
* @param ref - Starting ref
|
||||
* @param operation - Operation type (e.g., 'add', 'update', 'delete')
|
||||
* @param options - Additional options
|
||||
* @returns Array of commits by operation
|
||||
*/
|
||||
async getByOperation(
|
||||
ref: string,
|
||||
operation: string,
|
||||
options?: { maxCount?: number; since?: number }
|
||||
): Promise<CommitObject[]> {
|
||||
const commits: CommitObject[] = []
|
||||
let count = 0
|
||||
|
||||
for await (const commit of this.walk(ref, { until: options?.since })) {
|
||||
if (commit.metadata?.operation === operation) {
|
||||
commits.push(commit)
|
||||
count++
|
||||
|
||||
if (options?.maxCount && count >= options.maxCount) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return commits
|
||||
}
|
||||
|
||||
/**
|
||||
* Get commit history as array
|
||||
*
|
||||
* @param ref - Starting ref
|
||||
* @param options - Walk options
|
||||
* @returns Array of commits (newest first)
|
||||
*/
|
||||
async getHistory(
|
||||
ref: string,
|
||||
options?: {
|
||||
maxCount?: number
|
||||
since?: number
|
||||
until?: number
|
||||
}
|
||||
): Promise<CommitObject[]> {
|
||||
const commits: CommitObject[] = []
|
||||
let count = 0
|
||||
|
||||
for await (const commit of this.walk(ref, {
|
||||
maxDepth: options?.maxCount,
|
||||
until: options?.until
|
||||
})) {
|
||||
if (options?.since && commit.timestamp < options.since) {
|
||||
continue
|
||||
}
|
||||
|
||||
commits.push(commit)
|
||||
count++
|
||||
|
||||
if (options?.maxCount && count >= options.maxCount) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return commits
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream commit history (memory-efficient for large histories)
|
||||
*
|
||||
* Yields commits one at a time without accumulating in memory.
|
||||
* Use this for large commit histories (1000s of commits) where
|
||||
* memory efficiency is important.
|
||||
*
|
||||
* @param ref - Starting ref
|
||||
* @param options - Walk options
|
||||
* @yields Commits in reverse chronological order (newest first)
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // Stream all commits without memory accumulation
|
||||
* for await (const commit of commitLog.streamHistory('main', { maxCount: 10000 })) {
|
||||
* console.log(commit.message)
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
async *streamHistory(
|
||||
ref: string,
|
||||
options?: {
|
||||
maxCount?: number
|
||||
since?: number
|
||||
until?: number
|
||||
}
|
||||
): AsyncIterableIterator<CommitObject> {
|
||||
let count = 0
|
||||
|
||||
for await (const commit of this.walk(ref, {
|
||||
maxDepth: options?.maxCount,
|
||||
until: options?.until
|
||||
})) {
|
||||
// Filter by since timestamp if provided
|
||||
if (options?.since && commit.timestamp < options.since) {
|
||||
continue
|
||||
}
|
||||
|
||||
yield commit
|
||||
count++
|
||||
|
||||
// Stop after maxCount commits
|
||||
if (options?.maxCount && count >= options.maxCount) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Count commits between two commits
|
||||
*
|
||||
* @param fromRef - Starting ref/commit
|
||||
* @param toRef - Ending ref/commit (optional, defaults to fromRef's parent)
|
||||
* @returns Number of commits between
|
||||
*/
|
||||
async countBetween(fromRef: string, toRef?: string): Promise<number> {
|
||||
const fromHash = await this.resolveToHash(fromRef)
|
||||
const toHash = toRef ? await this.resolveToHash(toRef) : null
|
||||
|
||||
return CommitObject.countBetween(this.blobStorage, fromHash, toHash!)
|
||||
}
|
||||
|
||||
/**
|
||||
* Find common ancestor of two commits (merge base)
|
||||
*
|
||||
* @param ref1 - First ref/commit
|
||||
* @param ref2 - Second ref/commit
|
||||
* @returns Common ancestor commit or null
|
||||
*/
|
||||
async findCommonAncestor(
|
||||
ref1: string,
|
||||
ref2: string
|
||||
): Promise<CommitObject | null> {
|
||||
const hash1 = await this.resolveToHash(ref1)
|
||||
const hash2 = await this.resolveToHash(ref2)
|
||||
|
||||
return CommitObject.findCommonAncestor(this.blobStorage, hash1, hash2)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get commit log statistics
|
||||
*
|
||||
* @param ref - Starting ref
|
||||
* @param options - Options
|
||||
* @returns Commit log statistics
|
||||
*/
|
||||
async getStats(
|
||||
ref: string = 'main',
|
||||
options?: { maxDepth?: number }
|
||||
): Promise<CommitLogStats> {
|
||||
const authors = new Set<string>()
|
||||
const operations = new Set<string>()
|
||||
const timestamps: number[] = []
|
||||
let totalCommits = 0
|
||||
|
||||
for await (const commit of this.walk(ref, options)) {
|
||||
totalCommits++
|
||||
authors.add(commit.author)
|
||||
timestamps.push(commit.timestamp)
|
||||
|
||||
if (commit.metadata?.operation) {
|
||||
operations.add(commit.metadata.operation)
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate average interval
|
||||
let avgInterval = 0
|
||||
if (timestamps.length > 1) {
|
||||
const intervals: number[] = []
|
||||
for (let i = 0; i < timestamps.length - 1; i++) {
|
||||
intervals.push(timestamps[i] - timestamps[i + 1])
|
||||
}
|
||||
avgInterval = intervals.reduce((a, b) => a + b, 0) / intervals.length
|
||||
}
|
||||
|
||||
return {
|
||||
totalCommits,
|
||||
oldestCommit: timestamps[timestamps.length - 1] ?? 0,
|
||||
newestCommit: timestamps[0] ?? 0,
|
||||
authors,
|
||||
operations,
|
||||
avgCommitInterval: avgInterval
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if commit is ancestor of another commit
|
||||
*
|
||||
* @param ancestorRef - Potential ancestor ref/commit
|
||||
* @param descendantRef - Descendant ref/commit
|
||||
* @returns True if ancestor is in descendant's history
|
||||
*/
|
||||
async isAncestor(ancestorRef: string, descendantRef: string): Promise<boolean> {
|
||||
const ancestorHash = await this.resolveToHash(ancestorRef)
|
||||
const descendantHash = await this.resolveToHash(descendantRef)
|
||||
|
||||
// Walk from descendant, check if we encounter ancestor
|
||||
for await (const commit of this.walk(descendantHash)) {
|
||||
const commitHash = CommitObject.hash(commit)
|
||||
if (commitHash === ancestorHash) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Get recent commits (last N)
|
||||
*
|
||||
* @param ref - Starting ref
|
||||
* @param count - Number of commits to retrieve
|
||||
* @returns Array of recent commits
|
||||
*/
|
||||
async getRecent(ref: string, count: number = 10): Promise<CommitObject[]> {
|
||||
return this.getHistory(ref, { maxCount: count })
|
||||
}
|
||||
|
||||
/**
|
||||
* Find commits with tag
|
||||
*
|
||||
* @param ref - Starting ref
|
||||
* @param tag - Tag to search for
|
||||
* @returns Array of commits with tag
|
||||
*/
|
||||
async findWithTag(ref: string, tag: string): Promise<CommitObject[]> {
|
||||
const commits: CommitObject[] = []
|
||||
|
||||
for await (const commit of this.walk(ref)) {
|
||||
if (CommitObject.hasTag(commit, tag)) {
|
||||
commits.push(commit)
|
||||
}
|
||||
}
|
||||
|
||||
return commits
|
||||
}
|
||||
|
||||
/**
|
||||
* Get first (oldest) commit
|
||||
*
|
||||
* @param ref - Starting ref
|
||||
* @returns Oldest commit
|
||||
*/
|
||||
async getFirstCommit(ref: string): Promise<CommitObject | null> {
|
||||
let oldest: CommitObject | null = null
|
||||
|
||||
for await (const commit of this.walk(ref)) {
|
||||
oldest = commit
|
||||
}
|
||||
|
||||
return oldest
|
||||
}
|
||||
|
||||
/**
|
||||
* Get latest commit
|
||||
*
|
||||
* @param ref - Starting ref
|
||||
* @returns Latest commit
|
||||
*/
|
||||
async getLatestCommit(ref: string): Promise<CommitObject | null> {
|
||||
for await (const commit of this.walk(ref, { maxDepth: 1 })) {
|
||||
return commit
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear index (useful for testing, after new commits)
|
||||
*/
|
||||
clearIndex(): void {
|
||||
this.index.clear()
|
||||
this.indexValid = false
|
||||
}
|
||||
|
||||
// ========== PRIVATE METHODS ==========
|
||||
|
||||
/**
|
||||
* Build commit index for fast lookups
|
||||
*
|
||||
* @param ref - Starting ref
|
||||
*/
|
||||
private async buildIndex(ref: string): Promise<void> {
|
||||
if (this.indexValid) {
|
||||
return // Already built
|
||||
}
|
||||
|
||||
this.index.clear()
|
||||
|
||||
for await (const commit of this.walk(ref)) {
|
||||
const hash = CommitObject.hash(commit)
|
||||
|
||||
this.index.set(hash, {
|
||||
hash,
|
||||
timestamp: commit.timestamp,
|
||||
parentHash: commit.parent
|
||||
})
|
||||
}
|
||||
|
||||
this.indexValid = true
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve ref or hash to commit hash
|
||||
*
|
||||
* @param refOrHash - Ref name or commit hash
|
||||
* @returns Commit hash
|
||||
*/
|
||||
private async resolveToHash(refOrHash: string): Promise<string> {
|
||||
if (/^[a-f0-9]{64}$/.test(refOrHash)) {
|
||||
return refOrHash // Already a hash
|
||||
}
|
||||
|
||||
const hash = await this.refManager.resolveRef(refOrHash)
|
||||
|
||||
if (!hash) {
|
||||
throw new Error(`Ref not found: ${refOrHash}`)
|
||||
}
|
||||
|
||||
return hash
|
||||
}
|
||||
}
|
||||
|
|
@ -1,563 +0,0 @@
|
|||
/**
|
||||
* CommitObject: Snapshot metadata for COW (Copy-on-Write)
|
||||
*
|
||||
* Similar to Git commits, represents a point-in-time snapshot of a Brainy instance.
|
||||
* Commits reference tree objects and parent commits, forming a directed acyclic graph (DAG).
|
||||
*
|
||||
* Structure:
|
||||
* - tree: hash of root tree object (contains all data)
|
||||
* - parent: hash of parent commit (null for initial commit)
|
||||
* - message: human-readable commit message
|
||||
* - author: who/what created this commit
|
||||
* - timestamp: when this commit was created
|
||||
* - metadata: additional commit metadata (tags, etc.)
|
||||
*
|
||||
* @module storage/cow/CommitObject
|
||||
*/
|
||||
|
||||
import { BlobStorage } from './BlobStorage.js'
|
||||
import { isNullHash } from './constants.js'
|
||||
|
||||
/**
|
||||
* Commit object structure
|
||||
*/
|
||||
export interface CommitObject {
|
||||
tree: string // Root tree hash
|
||||
parent: string | null // Parent commit hash (null for initial commit)
|
||||
message: string // Commit message
|
||||
author: string // Author (user, system, augmentation)
|
||||
timestamp: number // Unix timestamp (milliseconds)
|
||||
metadata?: {
|
||||
tags?: string[] // Tags (e.g., ['v1.0.0', 'production'])
|
||||
branch?: string // Branch name (e.g., 'main', 'experiment')
|
||||
operation?: string // Operation type (e.g., 'add', 'update', 'delete', 'merge')
|
||||
entityCount?: number // Number of entities at this commit
|
||||
relationshipCount?: number // Number of relationships at this commit
|
||||
[key: string]: any // Custom metadata
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* CommitBuilder: Fluent API for building commit objects
|
||||
*
|
||||
* Example:
|
||||
* ```typescript
|
||||
* const commit = await CommitBuilder.create(blobStorage)
|
||||
* .tree(treeHash)
|
||||
* .parent(parentHash)
|
||||
* .message('Add user entities')
|
||||
* .author('system')
|
||||
* .tag('v1.0.0')
|
||||
* .build()
|
||||
* ```
|
||||
*/
|
||||
export class CommitBuilder {
|
||||
private _tree?: string
|
||||
private _parent?: string | null
|
||||
private _message: string = 'Auto-commit'
|
||||
private _author: string = 'system'
|
||||
private _timestamp: number = Date.now()
|
||||
private _metadata: NonNullable<CommitObject['metadata']> = {}
|
||||
private blobStorage: BlobStorage
|
||||
|
||||
constructor(blobStorage: BlobStorage) {
|
||||
this.blobStorage = blobStorage
|
||||
}
|
||||
|
||||
static create(blobStorage: BlobStorage): CommitBuilder {
|
||||
return new CommitBuilder(blobStorage)
|
||||
}
|
||||
|
||||
/**
|
||||
* Set tree hash
|
||||
*/
|
||||
tree(hash: string): this {
|
||||
this._tree = hash
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Set parent commit hash (null for initial commit)
|
||||
*/
|
||||
parent(hash: string | null): this {
|
||||
this._parent = hash
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Set commit message
|
||||
*/
|
||||
message(message: string): this {
|
||||
this._message = message
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Set commit author
|
||||
*/
|
||||
author(author: string): this {
|
||||
this._author = author
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Set commit timestamp (defaults to now)
|
||||
*/
|
||||
timestamp(timestamp: number | Date): this {
|
||||
this._timestamp = typeof timestamp === 'number' ? timestamp : timestamp.getTime()
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Add tag to commit
|
||||
*/
|
||||
tag(tag: string): this {
|
||||
if (!this._metadata.tags) {
|
||||
this._metadata.tags = []
|
||||
}
|
||||
this._metadata.tags.push(tag)
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Set branch name
|
||||
*/
|
||||
branch(branch: string): this {
|
||||
this._metadata.branch = branch
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Set operation type
|
||||
*/
|
||||
operation(operation: string): this {
|
||||
this._metadata.operation = operation
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Set entity count
|
||||
*/
|
||||
entityCount(count: number): this {
|
||||
this._metadata.entityCount = count
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Set relationship count
|
||||
*/
|
||||
relationshipCount(count: number): this {
|
||||
this._metadata.relationshipCount = count
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Set custom metadata
|
||||
*/
|
||||
meta(key: string, value: any): this {
|
||||
this._metadata[key] = value
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Build and persist the commit object
|
||||
*
|
||||
* @returns Commit hash
|
||||
*/
|
||||
async build(): Promise<string> {
|
||||
if (!this._tree) {
|
||||
throw new Error('CommitBuilder: tree hash is required')
|
||||
}
|
||||
|
||||
const commit: CommitObject = {
|
||||
tree: this._tree,
|
||||
parent: this._parent ?? null,
|
||||
message: this._message,
|
||||
author: this._author,
|
||||
timestamp: this._timestamp,
|
||||
metadata: Object.keys(this._metadata).length > 0 ? this._metadata : undefined
|
||||
}
|
||||
|
||||
return CommitObject.write(this.blobStorage, commit)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* CommitObject: Represents a point-in-time snapshot in COW storage
|
||||
*/
|
||||
export class CommitObject {
|
||||
/**
|
||||
* Serialize commit object to Buffer
|
||||
*
|
||||
* Format: JSON (simple, debuggable)
|
||||
* Future: Could use protobuf for efficiency
|
||||
*
|
||||
* @param commit - Commit object
|
||||
* @returns Serialized commit
|
||||
*/
|
||||
static serialize(commit: CommitObject): Buffer {
|
||||
return Buffer.from(JSON.stringify(commit, null, 0)) // Compact JSON
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserialize commit object from Buffer
|
||||
*
|
||||
* @param data - Serialized commit
|
||||
* @returns Commit object
|
||||
*/
|
||||
static deserialize(data: Buffer): CommitObject {
|
||||
const commit = JSON.parse(data.toString())
|
||||
|
||||
// Validate structure
|
||||
if (typeof commit.tree !== 'string' || commit.tree.length !== 64) {
|
||||
throw new Error('Invalid commit object: tree must be 64-char SHA-256')
|
||||
}
|
||||
|
||||
if (commit.parent !== null && (typeof commit.parent !== 'string' || commit.parent.length !== 64)) {
|
||||
throw new Error('Invalid commit object: parent must be 64-char SHA-256 or null')
|
||||
}
|
||||
|
||||
if (typeof commit.message !== 'string') {
|
||||
throw new Error('Invalid commit object: message must be string')
|
||||
}
|
||||
|
||||
if (typeof commit.author !== 'string') {
|
||||
throw new Error('Invalid commit object: author must be string')
|
||||
}
|
||||
|
||||
if (typeof commit.timestamp !== 'number') {
|
||||
throw new Error('Invalid commit object: timestamp must be number')
|
||||
}
|
||||
|
||||
if (commit.metadata !== undefined && typeof commit.metadata !== 'object') {
|
||||
throw new Error('Invalid commit object: metadata must be object')
|
||||
}
|
||||
|
||||
return commit
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute hash of commit object
|
||||
*
|
||||
* @param commit - Commit object
|
||||
* @returns SHA-256 hash
|
||||
*/
|
||||
static hash(commit: CommitObject): string {
|
||||
const data = CommitObject.serialize(commit)
|
||||
return BlobStorage.hash(data)
|
||||
}
|
||||
|
||||
/**
|
||||
* Write commit object to blob storage
|
||||
*
|
||||
* @param blobStorage - Blob storage instance
|
||||
* @param commit - Commit object
|
||||
* @returns Commit hash
|
||||
*/
|
||||
static async write(blobStorage: BlobStorage, commit: CommitObject): Promise<string> {
|
||||
const data = CommitObject.serialize(commit)
|
||||
return blobStorage.write(data, { type: 'commit', compression: 'auto' })
|
||||
}
|
||||
|
||||
/**
|
||||
* Read commit object from blob storage
|
||||
*
|
||||
* @param blobStorage - Blob storage instance
|
||||
* @param hash - Commit hash
|
||||
* @returns Commit object
|
||||
*/
|
||||
static async read(blobStorage: BlobStorage, hash: string): Promise<CommitObject> {
|
||||
const data = await blobStorage.read(hash)
|
||||
return CommitObject.deserialize(data)
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if commit is initial commit (has no parent)
|
||||
*
|
||||
* @param commit - Commit object
|
||||
* @returns True if initial commit
|
||||
*/
|
||||
static isInitial(commit: CommitObject): boolean {
|
||||
return commit.parent === null
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if commit is merge commit (has multiple parents)
|
||||
* (Future enhancement: support merge commits with multiple parents)
|
||||
*
|
||||
* @param commit - Commit object
|
||||
* @returns True if merge commit
|
||||
*/
|
||||
static isMerge(commit: CommitObject): boolean {
|
||||
// For now, we only support single-parent commits
|
||||
// Future: extend to support multiple parents
|
||||
return commit.metadata?.merge !== undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if commit has a specific tag
|
||||
*
|
||||
* @param commit - Commit object
|
||||
* @param tag - Tag to check
|
||||
* @returns True if commit has tag
|
||||
*/
|
||||
static hasTag(commit: CommitObject, tag: string): boolean {
|
||||
return commit.metadata?.tags?.includes(tag) ?? false
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all tags from commit
|
||||
*
|
||||
* @param commit - Commit object
|
||||
* @returns Array of tags
|
||||
*/
|
||||
static getTags(commit: CommitObject): string[] {
|
||||
return commit.metadata?.tags ?? []
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk commit history (traverse DAG)
|
||||
*
|
||||
* Yields commits in reverse chronological order (newest first)
|
||||
*
|
||||
* @param blobStorage - Blob storage instance
|
||||
* @param startHash - Starting commit hash
|
||||
* @param options - Walk options
|
||||
*/
|
||||
static async *walk(
|
||||
blobStorage: BlobStorage,
|
||||
startHash: string,
|
||||
options?: {
|
||||
maxDepth?: number // Maximum depth to walk
|
||||
until?: number // Stop at this timestamp
|
||||
stopAt?: string // Stop at this commit hash
|
||||
filter?: (commit: CommitObject) => boolean
|
||||
}
|
||||
): AsyncIterableIterator<CommitObject> {
|
||||
let currentHash: string | null = startHash
|
||||
let depth = 0
|
||||
|
||||
// Guard against NULL hash (sentinel for "no parent")
|
||||
// The initial commit has parent = null or NULL_HASH ('0000...0000')
|
||||
// We must stop walking when we reach it, not try to read it
|
||||
while (currentHash && !isNullHash(currentHash)) {
|
||||
// Check max depth
|
||||
if (options?.maxDepth && depth >= options.maxDepth) {
|
||||
break
|
||||
}
|
||||
|
||||
// Read commit
|
||||
const commit = await CommitObject.read(blobStorage, currentHash)
|
||||
|
||||
// Check filter
|
||||
if (options?.filter && !options.filter(commit)) {
|
||||
currentHash = commit.parent
|
||||
depth++
|
||||
continue
|
||||
}
|
||||
|
||||
// Yield commit
|
||||
yield commit
|
||||
|
||||
// Check stop conditions
|
||||
if (options?.until && commit.timestamp < options.until) {
|
||||
break
|
||||
}
|
||||
|
||||
if (options?.stopAt && currentHash === options.stopAt) {
|
||||
break
|
||||
}
|
||||
|
||||
// Move to parent (can be null or NULL_HASH for initial commit)
|
||||
currentHash = commit.parent
|
||||
depth++
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find commit at or before a specific timestamp
|
||||
*
|
||||
* @param blobStorage - Blob storage instance
|
||||
* @param startHash - Starting commit hash (e.g., 'main' ref)
|
||||
* @param timestamp - Target timestamp
|
||||
* @returns Commit at or before timestamp, or null if not found
|
||||
*/
|
||||
static async findAtTime(
|
||||
blobStorage: BlobStorage,
|
||||
startHash: string,
|
||||
timestamp: number
|
||||
): Promise<CommitObject | null> {
|
||||
for await (const commit of CommitObject.walk(blobStorage, startHash)) {
|
||||
if (commit.timestamp <= timestamp) {
|
||||
return commit
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Get commit history as array (newest first)
|
||||
*
|
||||
* @param blobStorage - Blob storage instance
|
||||
* @param startHash - Starting commit hash
|
||||
* @param options - Walk options
|
||||
* @returns Array of commits
|
||||
*/
|
||||
static async getHistory(
|
||||
blobStorage: BlobStorage,
|
||||
startHash: string,
|
||||
options?: {
|
||||
maxDepth?: number
|
||||
until?: number
|
||||
stopAt?: string
|
||||
}
|
||||
): Promise<CommitObject[]> {
|
||||
const commits: CommitObject[] = []
|
||||
|
||||
for await (const commit of CommitObject.walk(blobStorage, startHash, options)) {
|
||||
commits.push(commit)
|
||||
}
|
||||
|
||||
return commits
|
||||
}
|
||||
|
||||
/**
|
||||
* Find common ancestor of two commits (merge base)
|
||||
*
|
||||
* Useful for diff/merge operations
|
||||
*
|
||||
* @param blobStorage - Blob storage instance
|
||||
* @param hash1 - First commit hash
|
||||
* @param hash2 - Second commit hash
|
||||
* @returns Common ancestor commit, or null if not found
|
||||
*/
|
||||
static async findCommonAncestor(
|
||||
blobStorage: BlobStorage,
|
||||
hash1: string,
|
||||
hash2: string
|
||||
): Promise<CommitObject | null> {
|
||||
// Build set of all ancestors of commit1
|
||||
const ancestors1 = new Set<string>()
|
||||
|
||||
for await (const commit of CommitObject.walk(blobStorage, hash1)) {
|
||||
ancestors1.add(CommitObject.hash(commit))
|
||||
}
|
||||
|
||||
// Walk commit2 history, find first commit in ancestors1
|
||||
for await (const commit of CommitObject.walk(blobStorage, hash2)) {
|
||||
const commitHash = CommitObject.hash(commit)
|
||||
if (ancestors1.has(commitHash)) {
|
||||
return commit
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Count commits between two commits
|
||||
*
|
||||
* @param blobStorage - Blob storage instance
|
||||
* @param fromHash - Starting commit hash
|
||||
* @param toHash - Ending commit hash
|
||||
* @returns Number of commits between (inclusive)
|
||||
*/
|
||||
static async countBetween(
|
||||
blobStorage: BlobStorage,
|
||||
fromHash: string,
|
||||
toHash: string
|
||||
): Promise<number> {
|
||||
let count = 0
|
||||
|
||||
for await (const commit of CommitObject.walk(blobStorage, fromHash, {
|
||||
stopAt: toHash
|
||||
})) {
|
||||
count++
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
/**
|
||||
* Get commits in time range
|
||||
*
|
||||
* @param blobStorage - Blob storage instance
|
||||
* @param startHash - Starting commit hash
|
||||
* @param startTime - Start of time range
|
||||
* @param endTime - End of time range
|
||||
* @returns Array of commits in range
|
||||
*/
|
||||
static async getInTimeRange(
|
||||
blobStorage: BlobStorage,
|
||||
startHash: string,
|
||||
startTime: number,
|
||||
endTime: number
|
||||
): Promise<CommitObject[]> {
|
||||
const commits: CommitObject[] = []
|
||||
|
||||
for await (const commit of CommitObject.walk(blobStorage, startHash, {
|
||||
until: startTime
|
||||
})) {
|
||||
if (commit.timestamp >= startTime && commit.timestamp <= endTime) {
|
||||
commits.push(commit)
|
||||
}
|
||||
}
|
||||
|
||||
return commits
|
||||
}
|
||||
|
||||
/**
|
||||
* Get commits by author
|
||||
*
|
||||
* @param blobStorage - Blob storage instance
|
||||
* @param startHash - Starting commit hash
|
||||
* @param author - Author name
|
||||
* @param options - Walk options
|
||||
* @returns Array of commits by author
|
||||
*/
|
||||
static async getByAuthor(
|
||||
blobStorage: BlobStorage,
|
||||
startHash: string,
|
||||
author: string,
|
||||
options?: { maxDepth?: number }
|
||||
): Promise<CommitObject[]> {
|
||||
const commits: CommitObject[] = []
|
||||
|
||||
for await (const commit of CommitObject.walk(blobStorage, startHash, {
|
||||
...options,
|
||||
filter: c => c.author === author
|
||||
})) {
|
||||
commits.push(commit)
|
||||
}
|
||||
|
||||
return commits
|
||||
}
|
||||
|
||||
/**
|
||||
* Get commits by operation type
|
||||
*
|
||||
* @param blobStorage - Blob storage instance
|
||||
* @param startHash - Starting commit hash
|
||||
* @param operation - Operation type (e.g., 'add', 'update', 'delete')
|
||||
* @param options - Walk options
|
||||
* @returns Array of commits by operation
|
||||
*/
|
||||
static async getByOperation(
|
||||
blobStorage: BlobStorage,
|
||||
startHash: string,
|
||||
operation: string,
|
||||
options?: { maxDepth?: number }
|
||||
): Promise<CommitObject[]> {
|
||||
const commits: CommitObject[] = []
|
||||
|
||||
for await (const commit of CommitObject.walk(blobStorage, startHash, {
|
||||
...options,
|
||||
filter: c => c.metadata?.operation === operation
|
||||
})) {
|
||||
commits.push(commit)
|
||||
}
|
||||
|
||||
return commits
|
||||
}
|
||||
}
|
||||
|
|
@ -1,547 +0,0 @@
|
|||
/**
|
||||
* RefManager: Branch and reference management for COW (Copy-on-Write)
|
||||
*
|
||||
* Similar to Git refs, manages symbolic names (branches, tags) that point to commits.
|
||||
*
|
||||
* Structure:
|
||||
* - refs/heads/main → commit hash (main branch)
|
||||
* - refs/heads/experiment → commit hash (experiment branch)
|
||||
* - refs/tags/v1.0.0 → commit hash (version tag)
|
||||
* - HEAD → ref name (current branch)
|
||||
*
|
||||
* Features:
|
||||
* - Branch management (create, delete, list)
|
||||
* - Tag management
|
||||
* - HEAD pointer (current branch)
|
||||
* - Fast-forward and force updates
|
||||
* - Atomic operations
|
||||
*
|
||||
* @module storage/cow/RefManager
|
||||
*/
|
||||
|
||||
import type { COWStorageAdapter } from './BlobStorage.js'
|
||||
import { compareCodePoints } from '../../utils/collation.js'
|
||||
|
||||
/**
|
||||
* Reference type
|
||||
*/
|
||||
export type RefType = 'branch' | 'tag' | 'remote'
|
||||
|
||||
/**
|
||||
* Reference object
|
||||
*/
|
||||
export interface Ref {
|
||||
name: string // Full ref name (e.g., 'refs/heads/main')
|
||||
commitHash: string // Commit hash this ref points to
|
||||
type: RefType // Reference type
|
||||
createdAt: number // When ref was created
|
||||
updatedAt: number // When ref was last updated
|
||||
metadata?: {
|
||||
description?: string
|
||||
author?: string
|
||||
[key: string]: any
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ref update options
|
||||
*/
|
||||
export interface RefUpdateOptions {
|
||||
force?: boolean // Force update (allow non-fast-forward)
|
||||
createOnly?: boolean // Only create, fail if exists
|
||||
updateOnly?: boolean // Only update, fail if doesn't exist
|
||||
expectedOldValue?: string // CAS: only update if current value matches
|
||||
}
|
||||
|
||||
/**
|
||||
* RefManager: Manages branches, tags, and HEAD pointer
|
||||
*
|
||||
* Pure implementation - no backward compatibility
|
||||
*/
|
||||
export class RefManager {
|
||||
private adapter: COWStorageAdapter
|
||||
private cache: Map<string, Ref>
|
||||
private cacheValid: boolean
|
||||
|
||||
constructor(adapter: COWStorageAdapter) {
|
||||
this.adapter = adapter
|
||||
this.cache = new Map()
|
||||
this.cacheValid = false
|
||||
}
|
||||
|
||||
/**
|
||||
* Get reference by name
|
||||
*
|
||||
* @param name - Reference name (e.g., 'main', 'refs/heads/main')
|
||||
* @returns Reference object or undefined
|
||||
*/
|
||||
async getRef(name: string): Promise<Ref | undefined> {
|
||||
const fullName = this.normalizeRefName(name)
|
||||
|
||||
// Check cache
|
||||
if (this.cacheValid && this.cache.has(fullName)) {
|
||||
return this.cache.get(fullName)
|
||||
}
|
||||
|
||||
// Read from storage
|
||||
const data = await this.adapter.get(`ref:${fullName}`)
|
||||
|
||||
if (!data) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
const ref = JSON.parse(data.toString()) as Ref
|
||||
|
||||
// Update cache
|
||||
this.cache.set(fullName, ref)
|
||||
|
||||
return ref
|
||||
}
|
||||
|
||||
/**
|
||||
* Set reference to point to commit
|
||||
*
|
||||
* @param name - Reference name
|
||||
* @param commitHash - Commit hash to point to
|
||||
* @param options - Update options
|
||||
*/
|
||||
async setRef(
|
||||
name: string,
|
||||
commitHash: string,
|
||||
options: RefUpdateOptions = {}
|
||||
): Promise<void> {
|
||||
const fullName = this.normalizeRefName(name)
|
||||
|
||||
// Validate commit hash format
|
||||
if (!/^[a-f0-9]{64}$/.test(commitHash)) {
|
||||
throw new Error(`Invalid commit hash: ${commitHash}`)
|
||||
}
|
||||
|
||||
// Check if ref exists
|
||||
const existing = await this.getRef(fullName)
|
||||
|
||||
|
||||
// Handle createOnly
|
||||
if (options.createOnly && existing) {
|
||||
throw new Error(`Ref already exists: ${fullName}`)
|
||||
}
|
||||
|
||||
// Handle updateOnly
|
||||
if (options.updateOnly && !existing) {
|
||||
throw new Error(`Ref does not exist: ${fullName}`)
|
||||
}
|
||||
|
||||
// Handle CAS (Compare-And-Swap)
|
||||
if (options.expectedOldValue !== undefined) {
|
||||
if (!existing || existing.commitHash !== options.expectedOldValue) {
|
||||
throw new Error(
|
||||
`Ref update failed: expected ${options.expectedOldValue}, ` +
|
||||
`got ${existing?.commitHash ?? 'none'}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Fast-forward verification is intentionally permissive: COW is a
|
||||
// single-writer subsystem locked by the storage adapter's writer lock,
|
||||
// so out-of-order updates can't reach this point. If multi-writer COW
|
||||
// is ever introduced, replace with a commit-ancestry walk.
|
||||
|
||||
// Create/update ref
|
||||
const ref: Ref = {
|
||||
name: fullName,
|
||||
commitHash,
|
||||
type: this.getRefType(fullName),
|
||||
createdAt: existing?.createdAt ?? Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
metadata: existing?.metadata
|
||||
}
|
||||
|
||||
// Write to storage
|
||||
await this.adapter.put(`ref:${fullName}`, Buffer.from(JSON.stringify(ref)))
|
||||
|
||||
// Update cache
|
||||
this.cache.set(fullName, ref)
|
||||
this.cacheValid = false // Invalidate for listRefs
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete reference
|
||||
*
|
||||
* @param name - Reference name
|
||||
*/
|
||||
async deleteRef(name: string): Promise<void> {
|
||||
const fullName = this.normalizeRefName(name)
|
||||
|
||||
// Don't allow deleting HEAD
|
||||
if (fullName === 'HEAD') {
|
||||
throw new Error('Cannot delete HEAD')
|
||||
}
|
||||
|
||||
// Don't allow deleting main if it's the only branch
|
||||
if (fullName === 'refs/heads/main') {
|
||||
const branches = await this.listRefs('branch')
|
||||
if (branches.length === 1) {
|
||||
throw new Error('Cannot delete last branch')
|
||||
}
|
||||
}
|
||||
|
||||
// Delete from storage
|
||||
await this.adapter.delete(`ref:${fullName}`)
|
||||
|
||||
// Update cache
|
||||
this.cache.delete(fullName)
|
||||
this.cacheValid = false
|
||||
}
|
||||
|
||||
/**
|
||||
* List all references
|
||||
*
|
||||
* @param type - Filter by type (optional)
|
||||
* @returns Array of references
|
||||
*/
|
||||
async listRefs(type?: RefType): Promise<Ref[]> {
|
||||
// Get all ref keys
|
||||
const keys = await this.adapter.list('ref:')
|
||||
|
||||
const refs: Ref[] = []
|
||||
|
||||
for (const key of keys) {
|
||||
const refName = key.replace(/^ref:/, '')
|
||||
|
||||
// Skip HEAD in listings (it's special)
|
||||
if (refName === 'HEAD') {
|
||||
continue
|
||||
}
|
||||
|
||||
const ref = await this.getRef(refName)
|
||||
|
||||
if (ref) {
|
||||
// Filter by type if requested
|
||||
if (!type || ref.type === type) {
|
||||
refs.push(ref)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Mark cache as valid
|
||||
this.cacheValid = true
|
||||
|
||||
return refs.sort((a, b) => compareCodePoints(a.name, b.name))
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy reference (create branch from existing ref)
|
||||
*
|
||||
* @param sourceName - Source reference name
|
||||
* @param targetName - Target reference name
|
||||
* @param options - Update options
|
||||
*/
|
||||
async copyRef(
|
||||
sourceName: string,
|
||||
targetName: string,
|
||||
options: RefUpdateOptions = {}
|
||||
): Promise<void> {
|
||||
const sourceRef = await this.getRef(sourceName)
|
||||
|
||||
if (!sourceRef) {
|
||||
throw new Error(`Source ref not found: ${sourceName}`)
|
||||
}
|
||||
|
||||
// Set target ref to same commit as source
|
||||
await this.setRef(targetName, sourceRef.commitHash, options)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current HEAD (current branch)
|
||||
*
|
||||
* @returns HEAD reference or undefined
|
||||
*/
|
||||
async getHead(): Promise<Ref | undefined> {
|
||||
const data = await this.adapter.get('ref:HEAD')
|
||||
|
||||
if (!data) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
const head = JSON.parse(data.toString()) as { ref: string }
|
||||
|
||||
// Resolve symbolic ref
|
||||
return this.getRef(head.ref)
|
||||
}
|
||||
|
||||
/**
|
||||
* Set HEAD to point to branch
|
||||
*
|
||||
* @param branchName - Branch name (e.g., 'main', 'refs/heads/experiment')
|
||||
*/
|
||||
async setHead(branchName: string): Promise<void> {
|
||||
const fullName = this.normalizeRefName(branchName)
|
||||
|
||||
// Verify branch exists
|
||||
const branch = await this.getRef(fullName)
|
||||
|
||||
if (!branch) {
|
||||
throw new Error(`Branch not found: ${fullName}`)
|
||||
}
|
||||
|
||||
if (branch.type !== 'branch') {
|
||||
throw new Error(`Cannot set HEAD to non-branch ref: ${fullName}`)
|
||||
}
|
||||
|
||||
// Set HEAD (symbolic ref)
|
||||
const head = { ref: fullName }
|
||||
await this.adapter.put('ref:HEAD', Buffer.from(JSON.stringify(head)))
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current commit hash (resolves HEAD)
|
||||
*
|
||||
* @returns Current commit hash or undefined
|
||||
*/
|
||||
async getCurrentCommit(): Promise<string | undefined> {
|
||||
const head = await this.getHead()
|
||||
return head?.commitHash
|
||||
}
|
||||
|
||||
/**
|
||||
* Create branch
|
||||
*
|
||||
* @param name - Branch name (e.g., 'experiment')
|
||||
* @param commitHash - Commit hash to point to
|
||||
* @param options - Create options
|
||||
*/
|
||||
async createBranch(
|
||||
name: string,
|
||||
commitHash: string,
|
||||
options?: { description?: string; author?: string }
|
||||
): Promise<void> {
|
||||
const fullName = this.normalizeRefName(name, 'branch')
|
||||
|
||||
await this.setRef(fullName, commitHash, { createOnly: true })
|
||||
|
||||
// Update metadata if provided
|
||||
if (options?.description || options?.author) {
|
||||
const ref = await this.getRef(fullName)
|
||||
if (ref) {
|
||||
ref.metadata = {
|
||||
...ref.metadata,
|
||||
description: options.description,
|
||||
author: options.author
|
||||
}
|
||||
await this.adapter.put(`ref:${fullName}`, Buffer.from(JSON.stringify(ref)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete branch
|
||||
*
|
||||
* @param name - Branch name
|
||||
*/
|
||||
async deleteBranch(name: string): Promise<void> {
|
||||
const fullName = this.normalizeRefName(name, 'branch')
|
||||
await this.deleteRef(fullName)
|
||||
}
|
||||
|
||||
/**
|
||||
* List all branches
|
||||
*
|
||||
* @returns Array of branch references
|
||||
*/
|
||||
async listBranches(): Promise<Ref[]> {
|
||||
return this.listRefs('branch')
|
||||
}
|
||||
|
||||
/**
|
||||
* Create tag
|
||||
*
|
||||
* @param name - Tag name (e.g., 'v1.0.0')
|
||||
* @param commitHash - Commit hash to point to
|
||||
* @param options - Create options
|
||||
*/
|
||||
async createTag(
|
||||
name: string,
|
||||
commitHash: string,
|
||||
options?: { description?: string; author?: string }
|
||||
): Promise<void> {
|
||||
const fullName = this.normalizeRefName(name, 'tag')
|
||||
|
||||
await this.setRef(fullName, commitHash, { createOnly: true })
|
||||
|
||||
// Update metadata if provided
|
||||
if (options?.description || options?.author) {
|
||||
const ref = await this.getRef(fullName)
|
||||
if (ref) {
|
||||
ref.metadata = {
|
||||
...ref.metadata,
|
||||
description: options.description,
|
||||
author: options.author
|
||||
}
|
||||
await this.adapter.put(`ref:${fullName}`, Buffer.from(JSON.stringify(ref)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete tag
|
||||
*
|
||||
* @param name - Tag name
|
||||
*/
|
||||
async deleteTag(name: string): Promise<void> {
|
||||
const fullName = this.normalizeRefName(name, 'tag')
|
||||
await this.deleteRef(fullName)
|
||||
}
|
||||
|
||||
/**
|
||||
* List all tags
|
||||
*
|
||||
* @returns Array of tag references
|
||||
*/
|
||||
async listTags(): Promise<Ref[]> {
|
||||
return this.listRefs('tag')
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if reference exists
|
||||
*
|
||||
* @param name - Reference name
|
||||
* @returns True if reference exists
|
||||
*/
|
||||
async hasRef(name: string): Promise<boolean> {
|
||||
const ref = await this.getRef(name)
|
||||
return ref !== undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Update reference to new commit (with validation)
|
||||
*
|
||||
* @param name - Reference name
|
||||
* @param newCommitHash - New commit hash
|
||||
* @param oldCommitHash - Expected old commit hash (for safety)
|
||||
*/
|
||||
async updateRef(
|
||||
name: string,
|
||||
newCommitHash: string,
|
||||
oldCommitHash?: string
|
||||
): Promise<void> {
|
||||
const options: RefUpdateOptions = {}
|
||||
|
||||
if (oldCommitHash) {
|
||||
options.expectedOldValue = oldCommitHash
|
||||
}
|
||||
|
||||
await this.setRef(name, newCommitHash, options)
|
||||
}
|
||||
|
||||
/**
|
||||
* Update metadata on an existing ref (merge semantics).
|
||||
*
|
||||
* @param name - Reference name
|
||||
* @param metadata - Metadata fields to merge into the ref
|
||||
*/
|
||||
async updateRefMetadata(name: string, metadata: Record<string, unknown>): Promise<void> {
|
||||
const fullName = this.normalizeRefName(name)
|
||||
const ref = await this.getRef(fullName)
|
||||
if (!ref) throw new Error(`Ref not found: ${fullName}`)
|
||||
ref.metadata = { ...ref.metadata, ...metadata }
|
||||
ref.updatedAt = Date.now()
|
||||
await this.adapter.put(`ref:${fullName}`, Buffer.from(JSON.stringify(ref)))
|
||||
this.cache.set(fullName, ref)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get commit hash for reference
|
||||
*
|
||||
* @param name - Reference name
|
||||
* @returns Commit hash or undefined
|
||||
*/
|
||||
async resolveRef(name: string): Promise<string | undefined> {
|
||||
const ref = await this.getRef(name)
|
||||
return ref?.commitHash
|
||||
}
|
||||
|
||||
/**
|
||||
* Find references pointing to commit
|
||||
*
|
||||
* @param commitHash - Commit hash
|
||||
* @returns Array of references pointing to this commit
|
||||
*/
|
||||
async findRefsPointingTo(commitHash: string): Promise<Ref[]> {
|
||||
const allRefs = await this.listRefs()
|
||||
return allRefs.filter(ref => ref.commitHash === commitHash)
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear cache (useful for testing)
|
||||
*/
|
||||
clearCache(): void {
|
||||
this.cache.clear()
|
||||
this.cacheValid = false
|
||||
}
|
||||
|
||||
// ========== PRIVATE METHODS ==========
|
||||
|
||||
/**
|
||||
* Normalize reference name to full format
|
||||
*
|
||||
* Examples:
|
||||
* - 'main' → 'refs/heads/main'
|
||||
* - 'v1.0.0' (with type='tag') → 'refs/tags/v1.0.0'
|
||||
* - 'refs/heads/experiment' → 'refs/heads/experiment'
|
||||
*
|
||||
* @param name - Reference name
|
||||
* @param type - Reference type hint
|
||||
* @returns Full reference name
|
||||
*/
|
||||
private normalizeRefName(name: string, type?: RefType): string {
|
||||
// Already full format
|
||||
if (name.startsWith('refs/')) {
|
||||
return name
|
||||
}
|
||||
|
||||
// HEAD is special
|
||||
if (name === 'HEAD') {
|
||||
return 'HEAD'
|
||||
}
|
||||
|
||||
// Infer type from name if not provided
|
||||
if (!type) {
|
||||
// Tags usually start with 'v' or contain dots
|
||||
if (name.startsWith('v') && /\d/.test(name)) {
|
||||
type = 'tag'
|
||||
} else {
|
||||
type = 'branch' // Default to branch
|
||||
}
|
||||
}
|
||||
|
||||
// Add prefix
|
||||
switch (type) {
|
||||
case 'branch':
|
||||
return `refs/heads/${name}`
|
||||
case 'tag':
|
||||
return `refs/tags/${name}`
|
||||
case 'remote':
|
||||
return `refs/remotes/${name}`
|
||||
default:
|
||||
return name
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get reference type from full name
|
||||
*
|
||||
* @param fullName - Full reference name
|
||||
* @returns Reference type
|
||||
*/
|
||||
private getRefType(fullName: string): RefType {
|
||||
if (fullName.startsWith('refs/heads/')) {
|
||||
return 'branch'
|
||||
} else if (fullName.startsWith('refs/tags/')) {
|
||||
return 'tag'
|
||||
} else if (fullName.startsWith('refs/remotes/')) {
|
||||
return 'remote'
|
||||
} else {
|
||||
return 'branch' // Default
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,359 +0,0 @@
|
|||
/**
|
||||
* TreeObject: Directory structure for COW (Copy-on-Write)
|
||||
*
|
||||
* Similar to Git trees, represents the structure of a Brainy instance at a point in time.
|
||||
* Trees contain entries mapping names to blob hashes.
|
||||
*
|
||||
* Structure:
|
||||
* - entities/ → tree hash (entity blobs)
|
||||
* - indexes/nouns → blob hash (HNSW noun index)
|
||||
* - indexes/metadata → blob hash (metadata index)
|
||||
* - indexes/graph → blob hash (graph adjacency index)
|
||||
* - indexes/deleted → blob hash (deleted items index)
|
||||
*
|
||||
* @module storage/cow/TreeObject
|
||||
*/
|
||||
|
||||
import { BlobStorage } from './BlobStorage.js'
|
||||
import { compareCodePoints } from '../../utils/collation.js'
|
||||
|
||||
/**
|
||||
* Tree entry: name → blob hash mapping
|
||||
*/
|
||||
export interface TreeEntry {
|
||||
name: string
|
||||
hash: string
|
||||
type: 'blob' | 'tree' // blob = leaf, tree = subtree
|
||||
size: number // Original size (uncompressed)
|
||||
}
|
||||
|
||||
/**
|
||||
* Tree object structure
|
||||
*/
|
||||
export interface TreeObject {
|
||||
entries: TreeEntry[]
|
||||
createdAt: number
|
||||
}
|
||||
|
||||
/**
|
||||
* TreeBuilder: Fluent API for building tree objects
|
||||
*
|
||||
* Example:
|
||||
* ```typescript
|
||||
* const tree = await TreeBuilder.create(blobStorage)
|
||||
* .addBlob('entities/abc123', entityHash, size)
|
||||
* .addBlob('indexes/nouns', nounsHash, size)
|
||||
* .build()
|
||||
* ```
|
||||
*/
|
||||
export class TreeBuilder {
|
||||
private entries: TreeEntry[] = []
|
||||
private blobStorage: BlobStorage
|
||||
|
||||
constructor(blobStorage: BlobStorage) {
|
||||
this.blobStorage = blobStorage
|
||||
}
|
||||
|
||||
static create(blobStorage: BlobStorage): TreeBuilder {
|
||||
return new TreeBuilder(blobStorage)
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a blob entry to the tree
|
||||
*
|
||||
* @param name - Entry name (e.g., 'entities/abc123')
|
||||
* @param hash - Blob hash
|
||||
* @param size - Original blob size
|
||||
*/
|
||||
addBlob(name: string, hash: string, size: number): this {
|
||||
this.entries.push({
|
||||
name,
|
||||
hash,
|
||||
type: 'blob',
|
||||
size
|
||||
})
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a subtree entry to the tree
|
||||
*
|
||||
* @param name - Subtree name (e.g., 'entities/')
|
||||
* @param treeHash - Tree hash
|
||||
* @param size - Total size of subtree
|
||||
*/
|
||||
addTree(name: string, treeHash: string, size: number): this {
|
||||
this.entries.push({
|
||||
name,
|
||||
hash: treeHash,
|
||||
type: 'tree',
|
||||
size
|
||||
})
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Build and persist the tree object
|
||||
*
|
||||
* @returns Tree hash
|
||||
*/
|
||||
async build(): Promise<string> {
|
||||
const tree: TreeObject = {
|
||||
// Code-point (UTF-8 byte) order so the serialized tree — and therefore its
|
||||
// content hash — is reproducible across environments (localeCompare's default
|
||||
// locale varies by OS/Node/ICU). Sorting happens only here at write time;
|
||||
// deserialize() preserves stored order, so existing trees keep their hashes
|
||||
// and stay valid — no migration needed.
|
||||
entries: this.entries.sort((a, b) => compareCodePoints(a.name, b.name)),
|
||||
createdAt: Date.now()
|
||||
}
|
||||
|
||||
return TreeObject.write(this.blobStorage, tree)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* TreeObject: Represents directory structure in COW storage
|
||||
*/
|
||||
export class TreeObject {
|
||||
/**
|
||||
* Serialize tree object to Buffer
|
||||
*
|
||||
* Format: JSON (simple, debuggable)
|
||||
* Future: Could use protobuf for efficiency
|
||||
*
|
||||
* @param tree - Tree object
|
||||
* @returns Serialized tree
|
||||
*/
|
||||
static serialize(tree: TreeObject): Buffer {
|
||||
return Buffer.from(JSON.stringify(tree, null, 0)) // Compact JSON
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserialize tree object from Buffer
|
||||
*
|
||||
* @param data - Serialized tree
|
||||
* @returns Tree object
|
||||
*/
|
||||
static deserialize(data: Buffer): TreeObject {
|
||||
const tree = JSON.parse(data.toString())
|
||||
|
||||
// Validate structure
|
||||
if (!tree.entries || !Array.isArray(tree.entries)) {
|
||||
throw new Error('Invalid tree object: missing entries array')
|
||||
}
|
||||
|
||||
if (typeof tree.createdAt !== 'number') {
|
||||
throw new Error('Invalid tree object: missing or invalid createdAt')
|
||||
}
|
||||
|
||||
// Validate entries
|
||||
for (const entry of tree.entries) {
|
||||
if (typeof entry.name !== 'string') {
|
||||
throw new Error(`Invalid tree entry: name must be string`)
|
||||
}
|
||||
if (typeof entry.hash !== 'string' || entry.hash.length !== 64) {
|
||||
throw new Error(`Invalid tree entry: hash must be 64-char SHA-256`)
|
||||
}
|
||||
if (entry.type !== 'blob' && entry.type !== 'tree') {
|
||||
throw new Error(`Invalid tree entry: type must be 'blob' or 'tree'`)
|
||||
}
|
||||
if (typeof entry.size !== 'number' || entry.size < 0) {
|
||||
throw new Error(`Invalid tree entry: size must be non-negative number`)
|
||||
}
|
||||
}
|
||||
|
||||
return tree
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute hash of tree object
|
||||
*
|
||||
* @param tree - Tree object
|
||||
* @returns SHA-256 hash
|
||||
*/
|
||||
static hash(tree: TreeObject): string {
|
||||
const data = TreeObject.serialize(tree)
|
||||
return BlobStorage.hash(data)
|
||||
}
|
||||
|
||||
/**
|
||||
* Write tree object to blob storage
|
||||
*
|
||||
* @param blobStorage - Blob storage instance
|
||||
* @param tree - Tree object
|
||||
* @returns Tree hash
|
||||
*/
|
||||
static async write(blobStorage: BlobStorage, tree: TreeObject): Promise<string> {
|
||||
const data = TreeObject.serialize(tree)
|
||||
return blobStorage.write(data, { type: 'tree', compression: 'auto' })
|
||||
}
|
||||
|
||||
/**
|
||||
* Read tree object from blob storage
|
||||
*
|
||||
* @param blobStorage - Blob storage instance
|
||||
* @param hash - Tree hash
|
||||
* @returns Tree object
|
||||
*/
|
||||
static async read(blobStorage: BlobStorage, hash: string): Promise<TreeObject> {
|
||||
const data = await blobStorage.read(hash)
|
||||
return TreeObject.deserialize(data)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get specific entry from tree
|
||||
*
|
||||
* @param tree - Tree object
|
||||
* @param name - Entry name
|
||||
* @returns Tree entry or undefined
|
||||
*/
|
||||
static getEntry(tree: TreeObject, name: string): TreeEntry | undefined {
|
||||
return tree.entries.find(e => e.name === name)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all blob entries from tree (non-recursive)
|
||||
*
|
||||
* @param tree - Tree object
|
||||
* @returns Array of blob entries
|
||||
*/
|
||||
static getBlobs(tree: TreeObject): TreeEntry[] {
|
||||
return tree.entries.filter(e => e.type === 'blob')
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all subtree entries from tree (non-recursive)
|
||||
*
|
||||
* @param tree - Tree object
|
||||
* @returns Array of tree entries
|
||||
*/
|
||||
static getSubtrees(tree: TreeObject): TreeEntry[] {
|
||||
return tree.entries.filter(e => e.type === 'tree')
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk tree recursively, yielding all blob entries
|
||||
*
|
||||
* @param blobStorage - Blob storage instance
|
||||
* @param tree - Tree object
|
||||
*/
|
||||
static async *walk(
|
||||
blobStorage: BlobStorage,
|
||||
tree: TreeObject
|
||||
): AsyncIterableIterator<TreeEntry> {
|
||||
for (const entry of tree.entries) {
|
||||
if (entry.type === 'blob') {
|
||||
yield entry
|
||||
} else {
|
||||
// Recurse into subtree
|
||||
const subtree = await TreeObject.read(blobStorage, entry.hash)
|
||||
yield* TreeObject.walk(blobStorage, subtree)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute total size of tree (recursive)
|
||||
*
|
||||
* @param blobStorage - Blob storage instance
|
||||
* @param tree - Tree object
|
||||
* @returns Total size in bytes
|
||||
*/
|
||||
static async getTotalSize(blobStorage: BlobStorage, tree: TreeObject): Promise<number> {
|
||||
let totalSize = 0
|
||||
|
||||
for await (const entry of TreeObject.walk(blobStorage, tree)) {
|
||||
totalSize += entry.size
|
||||
}
|
||||
|
||||
return totalSize
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new tree by updating a single entry
|
||||
* (Copy-on-write: creates new tree, doesn't modify original)
|
||||
*
|
||||
* @param blobStorage - Blob storage instance
|
||||
* @param tree - Original tree
|
||||
* @param name - Entry name to update
|
||||
* @param hash - New blob/tree hash
|
||||
* @param size - New size
|
||||
* @returns New tree hash
|
||||
*/
|
||||
static async updateEntry(
|
||||
blobStorage: BlobStorage,
|
||||
tree: TreeObject,
|
||||
name: string,
|
||||
hash: string,
|
||||
size: number
|
||||
): Promise<string> {
|
||||
const builder = TreeBuilder.create(blobStorage)
|
||||
|
||||
// Copy all entries except the one being updated
|
||||
for (const entry of tree.entries) {
|
||||
if (entry.name === name) {
|
||||
// Replace with new entry
|
||||
if (entry.type === 'blob') {
|
||||
builder.addBlob(name, hash, size)
|
||||
} else {
|
||||
builder.addTree(name, hash, size)
|
||||
}
|
||||
} else {
|
||||
// Keep existing entry
|
||||
if (entry.type === 'blob') {
|
||||
builder.addBlob(entry.name, entry.hash, entry.size)
|
||||
} else {
|
||||
builder.addTree(entry.name, entry.hash, entry.size)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If entry didn't exist, add it
|
||||
if (!TreeObject.getEntry(tree, name)) {
|
||||
builder.addBlob(name, hash, size)
|
||||
}
|
||||
|
||||
return builder.build()
|
||||
}
|
||||
|
||||
/**
|
||||
* Diff two trees, return changed/added/deleted entries
|
||||
*
|
||||
* @param tree1 - First tree (base)
|
||||
* @param tree2 - Second tree (comparison)
|
||||
* @returns Diff result
|
||||
*/
|
||||
static diff(tree1: TreeObject, tree2: TreeObject): {
|
||||
added: TreeEntry[]
|
||||
modified: TreeEntry[]
|
||||
deleted: TreeEntry[]
|
||||
} {
|
||||
const entries1 = new Map(tree1.entries.map(e => [e.name, e]))
|
||||
const entries2 = new Map(tree2.entries.map(e => [e.name, e]))
|
||||
|
||||
const added: TreeEntry[] = []
|
||||
const modified: TreeEntry[] = []
|
||||
const deleted: TreeEntry[] = []
|
||||
|
||||
// Find added and modified
|
||||
for (const [name, entry2] of entries2) {
|
||||
const entry1 = entries1.get(name)
|
||||
|
||||
if (!entry1) {
|
||||
added.push(entry2)
|
||||
} else if (entry1.hash !== entry2.hash) {
|
||||
modified.push(entry2)
|
||||
}
|
||||
}
|
||||
|
||||
// Find deleted
|
||||
for (const [name, entry1] of entries1) {
|
||||
if (!entries2.has(name)) {
|
||||
deleted.push(entry1)
|
||||
}
|
||||
}
|
||||
|
||||
return { added, modified, deleted }
|
||||
}
|
||||
}
|
||||
|
|
@ -1,100 +0,0 @@
|
|||
/**
|
||||
* Binary Data Codec: Single Source of Truth for Wrap/Unwrap Operations
|
||||
*
|
||||
* This module provides the ONLY implementation of binary data encoding/decoding
|
||||
* used across all storage adapters and blob storage.
|
||||
*
|
||||
* Design Principles:
|
||||
* - DRY: One implementation, used everywhere
|
||||
* - Single Responsibility: Only handles binary ↔ JSON conversion
|
||||
* - Type-Safe: Proper TypeScript types
|
||||
* - Defensive: Handles all edge cases
|
||||
*
|
||||
* Used by:
|
||||
* - BaseStorage COW adapter (write/read operations)
|
||||
* - BlobStorage (defense-in-depth verification)
|
||||
* - All storage adapters (via BaseStorage)
|
||||
*
|
||||
* @module storage/cow/binaryDataCodec
|
||||
*/
|
||||
|
||||
/**
|
||||
* Wrapped binary data format
|
||||
* Used when storing binary data in JSON-based storage
|
||||
*/
|
||||
export interface WrappedBinaryData {
|
||||
_binary: true
|
||||
data: string // base64-encoded
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if data is wrapped binary format
|
||||
*/
|
||||
export function isWrappedBinary(data: any): data is WrappedBinaryData {
|
||||
return (
|
||||
typeof data === 'object' &&
|
||||
data !== null &&
|
||||
data._binary === true &&
|
||||
typeof data.data === 'string'
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Unwrap binary data from JSON wrapper
|
||||
*
|
||||
* This is the SINGLE SOURCE OF TRUTH for unwrapping binary data.
|
||||
* All storage operations MUST use this function.
|
||||
*
|
||||
* Handles:
|
||||
* - Buffer → Buffer (pass-through)
|
||||
* - {_binary: true, data: "base64..."} → Buffer (unwrap)
|
||||
* - Plain object → Buffer (JSON stringify)
|
||||
* - Other types → Error
|
||||
*
|
||||
* @param data - Data to unwrap (may be Buffer, wrapped object, or plain object)
|
||||
* @returns Unwrapped Buffer
|
||||
* @throws Error if data type is invalid
|
||||
*/
|
||||
export function unwrapBinaryData(data: any): Buffer {
|
||||
// Case 1: Already a Buffer (no unwrapping needed)
|
||||
if (Buffer.isBuffer(data)) {
|
||||
return data
|
||||
}
|
||||
|
||||
// Case 2: Wrapped binary data {_binary: true, data: "base64..."}
|
||||
if (isWrappedBinary(data)) {
|
||||
return Buffer.from(data.data, 'base64')
|
||||
}
|
||||
|
||||
// Case 3: Plain object (shouldn't happen for binary blobs, but handle gracefully)
|
||||
if (typeof data === 'object' && data !== null) {
|
||||
return Buffer.from(JSON.stringify(data))
|
||||
}
|
||||
|
||||
// Case 4: String (convert to Buffer)
|
||||
if (typeof data === 'string') {
|
||||
return Buffer.from(data)
|
||||
}
|
||||
|
||||
// Case 5: Invalid type
|
||||
throw new Error(
|
||||
`Invalid data type for unwrap: ${typeof data}. ` +
|
||||
`Expected Buffer or {_binary: true, data: "base64..."}`
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure data is a Buffer
|
||||
*
|
||||
* Convenience function that combines type checking and unwrapping.
|
||||
* Use this when you need to ensure you have a Buffer.
|
||||
*
|
||||
* @param data - Data that should be or can be converted to Buffer
|
||||
* @returns Buffer
|
||||
*/
|
||||
export function ensureBuffer(data: any): Buffer {
|
||||
if (Buffer.isBuffer(data)) {
|
||||
return data
|
||||
}
|
||||
return unwrapBinaryData(data)
|
||||
}
|
||||
|
|
@ -1,59 +0,0 @@
|
|||
/**
|
||||
* COW Storage Constants
|
||||
*
|
||||
* Sentinel values and utilities for Copy-On-Write storage system.
|
||||
*
|
||||
* @module storage/cow/constants
|
||||
*/
|
||||
|
||||
/**
|
||||
* NULL_HASH - Sentinel value for "no parent commit" or "empty tree"
|
||||
*
|
||||
* In Git-like COW systems, we need a way to represent:
|
||||
* - Initial commit (has no parent)
|
||||
* - Empty tree (contains no files)
|
||||
*
|
||||
* We use a 64-character zero hash as a sentinel value.
|
||||
* This should NEVER be used as an actual content hash.
|
||||
*
|
||||
* @constant
|
||||
* @example
|
||||
* ```typescript
|
||||
* const builder = CommitBuilder.create(storage)
|
||||
* .tree(NULL_HASH) // Empty tree
|
||||
* .parent(null) // No parent (use null, not NULL_HASH)
|
||||
* .build()
|
||||
* ```
|
||||
*/
|
||||
export const NULL_HASH = '0000000000000000000000000000000000000000000000000000000000000000'
|
||||
|
||||
/**
|
||||
* Check if a hash is the NULL sentinel value
|
||||
*
|
||||
* @param hash - Hash to check (can be string or null)
|
||||
* @returns true if hash is null or NULL_HASH
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* if (isNullHash(commit.parent)) {
|
||||
* console.log('This is the initial commit')
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export function isNullHash(hash: string | null | undefined): boolean {
|
||||
return hash === null || hash === undefined || hash === NULL_HASH
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a hash is valid (non-null, non-empty, proper format)
|
||||
*
|
||||
* @param hash - Hash to check
|
||||
* @returns true if hash is a valid SHA-256 hash
|
||||
*/
|
||||
export function isValidHash(hash: string | null | undefined): boolean {
|
||||
if (isNullHash(hash)) {
|
||||
return false
|
||||
}
|
||||
// SHA-256 hash must be exactly 64 hexadecimal characters
|
||||
return typeof hash === 'string' && /^[a-f0-9]{64}$/.test(hash)
|
||||
}
|
||||
|
|
@ -52,30 +52,10 @@ export interface StorageOptions {
|
|||
[key: string]: any
|
||||
}
|
||||
|
||||
/** Branch name for COW storage (filesystem only). */
|
||||
branch?: string
|
||||
|
||||
/** Whether to enable COW blob compression. Default `true`. */
|
||||
enableCompression?: boolean
|
||||
|
||||
/** Operation tuning (timeouts, retry budgets) passed through to the adapter. */
|
||||
operationConfig?: OperationConfig
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach the COW (copy-on-write) options to the adapter so the storage's
|
||||
* branch + compression settings are honored when the adapter's
|
||||
* `initializeCOW()` hook fires later in `brain.init()`.
|
||||
*/
|
||||
function configureCOW(storage: any, options?: StorageOptions): void {
|
||||
if (typeof storage?.initializeCOW === 'function') {
|
||||
storage._cowOptions = {
|
||||
branch: options?.branch || 'main',
|
||||
enableCompression: options?.enableCompression !== false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve `StorageOptions` to a concrete storage adapter.
|
||||
*
|
||||
|
|
@ -85,9 +65,7 @@ function configureCOW(storage: any, options?: StorageOptions): void {
|
|||
* - `forceFileSystemStorage: true` returns `FileSystemStorage`.
|
||||
*/
|
||||
export async function createStorage(options: StorageOptions = {}): Promise<StorageAdapter> {
|
||||
const storage = await pickAdapter(options)
|
||||
configureCOW(storage, options)
|
||||
return storage
|
||||
return pickAdapter(options)
|
||||
}
|
||||
|
||||
async function pickAdapter(options: StorageOptions): Promise<StorageAdapter> {
|
||||
|
|
|
|||
|
|
@ -20,8 +20,7 @@ import type { Operation, RollbackAction } from '../types.js'
|
|||
*
|
||||
* Rollback strategy:
|
||||
* - Remove item from index
|
||||
*
|
||||
* Note: Works with both JsHnswVectorIndex and TypeAwareHNSWIndex
|
||||
|
||||
*/
|
||||
export class AddToHNSWOperation implements Operation {
|
||||
readonly name = 'AddToHNSW'
|
||||
|
|
|
|||
|
|
@ -5,10 +5,9 @@
|
|||
* Each operation can be executed and rolled back atomically.
|
||||
*
|
||||
* Supports:
|
||||
* - All 8 storage adapters (FileSystem, S3, Memory, OPFS, GCS, Azure, R2, TypeAware)
|
||||
* - Both storage adapters (FileSystem, Memory)
|
||||
* - Nouns (entities) and Verbs (relationships)
|
||||
* - Metadata and vector data
|
||||
* - COW (Copy-on-Write) storage
|
||||
*/
|
||||
|
||||
import type { StorageAdapter, HNSWNoun, HNSWVerb, NounMetadata, VerbMetadata } from '../../coreTypes.js'
|
||||
|
|
|
|||
|
|
@ -1099,7 +1099,6 @@ export interface BrainyConfig {
|
|||
* including plugin-provided factories (e.g. Cortex mmap). */
|
||||
rootDirectory?: string
|
||||
options?: any
|
||||
branch?: string // COW branch name (default: 'main')
|
||||
}
|
||||
|
||||
// Index configuration
|
||||
|
|
|
|||
|
|
@ -164,7 +164,8 @@ export interface BrainyInterface<T = unknown> {
|
|||
/**
|
||||
* Run pending data migrations, or preview what would change.
|
||||
*
|
||||
* @param options - Pass { dryRun: true } to preview without writing
|
||||
* @param options - Pass `{ dryRun: true }` to preview without writing;
|
||||
* pass `{ backupTo: path }` to persist a pre-migration snapshot.
|
||||
* @returns Migration result or preview depending on options
|
||||
*
|
||||
* @example
|
||||
|
|
@ -173,9 +174,9 @@ export interface BrainyInterface<T = unknown> {
|
|||
* const preview = await brain.migrate({ dryRun: true })
|
||||
* console.log(preview.affectedEntities)
|
||||
*
|
||||
* // Apply
|
||||
* const result = await brain.migrate()
|
||||
* console.log(result.backupBranch) // 'pre-migration-7.17.0'
|
||||
* // Apply with a restore point
|
||||
* const result = await brain.migrate({ backupTo: '/backups/pre-migration' })
|
||||
* console.log(result.backupPath) // '/backups/pre-migration'
|
||||
* ```
|
||||
*/
|
||||
migrate(options?: MigrateOptions): Promise<MigrationResult | MigrationPreview>
|
||||
|
|
|
|||
|
|
@ -1,459 +0,0 @@
|
|||
/**
|
||||
* VersionDiff - Deep Object Comparison for Entity Versions
|
||||
*
|
||||
* Provides deep diff between entity versions:
|
||||
* - Field-level change detection
|
||||
* - Nested object comparison
|
||||
* - Array diffing
|
||||
* - Type change detection
|
||||
* - Human-readable diff output
|
||||
*
|
||||
* NO MOCKS - Production implementation
|
||||
*/
|
||||
|
||||
import type { NounMetadata } from '../coreTypes.js'
|
||||
|
||||
/**
|
||||
* Types of changes in a diff
|
||||
*/
|
||||
export type ChangeType = 'added' | 'removed' | 'modified' | 'type-changed'
|
||||
|
||||
/**
|
||||
* A single field change in a diff
|
||||
*/
|
||||
export interface FieldChange {
|
||||
/** Path to the field (e.g., 'metadata.user.name') */
|
||||
path: string
|
||||
|
||||
/** Type of change */
|
||||
type: ChangeType
|
||||
|
||||
/** Old value (undefined for 'added') */
|
||||
oldValue?: any
|
||||
|
||||
/** New value (undefined for 'removed') */
|
||||
newValue?: any
|
||||
|
||||
/** Old type (for 'type-changed') */
|
||||
oldType?: string
|
||||
|
||||
/** New type (for 'type-changed') */
|
||||
newType?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete diff between two versions
|
||||
*/
|
||||
export interface VersionDiff {
|
||||
/** Entity ID being compared */
|
||||
entityId: string
|
||||
|
||||
/** From version number */
|
||||
fromVersion: number
|
||||
|
||||
/** To version number */
|
||||
toVersion: number
|
||||
|
||||
/** Fields that were added */
|
||||
added: FieldChange[]
|
||||
|
||||
/** Fields that were removed */
|
||||
removed: FieldChange[]
|
||||
|
||||
/** Fields that were modified */
|
||||
modified: FieldChange[]
|
||||
|
||||
/** Fields whose type changed */
|
||||
typeChanged: FieldChange[]
|
||||
|
||||
/** Total number of changes */
|
||||
totalChanges: number
|
||||
|
||||
/** Whether versions are identical */
|
||||
identical: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for diff comparison
|
||||
*/
|
||||
export interface DiffOptions {
|
||||
/** Entity ID (for context in output) */
|
||||
entityId: string
|
||||
|
||||
/** From version number */
|
||||
fromVersion: number
|
||||
|
||||
/** To version number */
|
||||
toVersion: number
|
||||
|
||||
/** Ignore these fields in comparison */
|
||||
ignoreFields?: string[]
|
||||
|
||||
/** Maximum depth for nested object comparison (default: 10) */
|
||||
maxDepth?: number
|
||||
|
||||
/** Include unchanged fields in output (default: false) */
|
||||
includeUnchanged?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare two entity versions and generate diff
|
||||
*
|
||||
* @param from Old version entity
|
||||
* @param to New version entity
|
||||
* @param options Diff options
|
||||
* @returns Diff between versions
|
||||
*/
|
||||
export function compareEntityVersions(
|
||||
from: NounMetadata,
|
||||
to: NounMetadata,
|
||||
options: DiffOptions
|
||||
): VersionDiff {
|
||||
const added: FieldChange[] = []
|
||||
const removed: FieldChange[] = []
|
||||
const modified: FieldChange[] = []
|
||||
const typeChanged: FieldChange[] = []
|
||||
|
||||
const ignoreFields = new Set(options.ignoreFields || [])
|
||||
const maxDepth = options.maxDepth ?? 10
|
||||
|
||||
// Compare objects recursively
|
||||
compareObjects(from, to, '', added, removed, modified, typeChanged, ignoreFields, 0, maxDepth)
|
||||
|
||||
const totalChanges = added.length + removed.length + modified.length + typeChanged.length
|
||||
const identical = totalChanges === 0
|
||||
|
||||
return {
|
||||
entityId: options.entityId,
|
||||
fromVersion: options.fromVersion,
|
||||
toVersion: options.toVersion,
|
||||
added,
|
||||
removed,
|
||||
modified,
|
||||
typeChanged,
|
||||
totalChanges,
|
||||
identical
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively compare two objects
|
||||
*/
|
||||
function compareObjects(
|
||||
from: any,
|
||||
to: any,
|
||||
path: string,
|
||||
added: FieldChange[],
|
||||
removed: FieldChange[],
|
||||
modified: FieldChange[],
|
||||
typeChanged: FieldChange[],
|
||||
ignoreFields: Set<string>,
|
||||
depth: number,
|
||||
maxDepth: number
|
||||
): void {
|
||||
if (depth >= maxDepth) {
|
||||
// Hit max depth - treat as single value
|
||||
if (!deepEqual(from, to)) {
|
||||
modified.push({
|
||||
path,
|
||||
type: 'modified',
|
||||
oldValue: from,
|
||||
newValue: to
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Get all keys from both objects
|
||||
const fromKeys = new Set(Object.keys(from || {}))
|
||||
const toKeys = new Set(Object.keys(to || {}))
|
||||
const allKeys = new Set([...fromKeys, ...toKeys])
|
||||
|
||||
for (const key of allKeys) {
|
||||
const fieldPath = path ? `${path}.${key}` : key
|
||||
|
||||
// Skip ignored fields
|
||||
if (ignoreFields.has(fieldPath) || ignoreFields.has(key)) {
|
||||
continue
|
||||
}
|
||||
|
||||
const fromHas = fromKeys.has(key)
|
||||
const toHas = toKeys.has(key)
|
||||
|
||||
if (!fromHas && toHas) {
|
||||
// Field added
|
||||
added.push({
|
||||
path: fieldPath,
|
||||
type: 'added',
|
||||
newValue: to[key]
|
||||
})
|
||||
} else if (fromHas && !toHas) {
|
||||
// Field removed
|
||||
removed.push({
|
||||
path: fieldPath,
|
||||
type: 'removed',
|
||||
oldValue: from[key]
|
||||
})
|
||||
} else {
|
||||
// Field exists in both - check for changes
|
||||
const fromValue = from[key]
|
||||
const toValue = to[key]
|
||||
|
||||
const fromType = getValueType(fromValue)
|
||||
const toType = getValueType(toValue)
|
||||
|
||||
if (fromType !== toType) {
|
||||
// Type changed
|
||||
typeChanged.push({
|
||||
path: fieldPath,
|
||||
type: 'type-changed',
|
||||
oldValue: fromValue,
|
||||
newValue: toValue,
|
||||
oldType: fromType,
|
||||
newType: toType
|
||||
})
|
||||
} else if (fromType === 'object' && toType === 'object') {
|
||||
// Recursively compare nested objects
|
||||
compareObjects(
|
||||
fromValue,
|
||||
toValue,
|
||||
fieldPath,
|
||||
added,
|
||||
removed,
|
||||
modified,
|
||||
typeChanged,
|
||||
ignoreFields,
|
||||
depth + 1,
|
||||
maxDepth
|
||||
)
|
||||
} else if (fromType === 'array' && toType === 'array') {
|
||||
// Compare arrays
|
||||
if (!arraysEqual(fromValue, toValue)) {
|
||||
modified.push({
|
||||
path: fieldPath,
|
||||
type: 'modified',
|
||||
oldValue: fromValue,
|
||||
newValue: toValue
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// Primitive value comparison
|
||||
if (!deepEqual(fromValue, toValue)) {
|
||||
modified.push({
|
||||
path: fieldPath,
|
||||
type: 'modified',
|
||||
oldValue: fromValue,
|
||||
newValue: toValue
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get human-readable type of a value
|
||||
*/
|
||||
function getValueType(value: any): string {
|
||||
if (value === null) return 'null'
|
||||
if (value === undefined) return 'undefined'
|
||||
if (Array.isArray(value)) return 'array'
|
||||
return typeof value
|
||||
}
|
||||
|
||||
/**
|
||||
* Deep equality check
|
||||
*/
|
||||
function deepEqual(a: any, b: any): boolean {
|
||||
if (a === b) return true
|
||||
if (a === null || b === null) return false
|
||||
if (a === undefined || b === undefined) return false
|
||||
|
||||
const typeA = getValueType(a)
|
||||
const typeB = getValueType(b)
|
||||
|
||||
if (typeA !== typeB) return false
|
||||
|
||||
if (typeA === 'array') {
|
||||
return arraysEqual(a, b)
|
||||
}
|
||||
|
||||
if (typeA === 'object') {
|
||||
return objectsEqual(a, b)
|
||||
}
|
||||
|
||||
// Primitive comparison
|
||||
return a === b
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare arrays for equality
|
||||
*/
|
||||
function arraysEqual(a: any[], b: any[]): boolean {
|
||||
if (a.length !== b.length) return false
|
||||
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
if (!deepEqual(a[i], b[i])) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare objects for equality
|
||||
*/
|
||||
function objectsEqual(a: any, b: any): boolean {
|
||||
const keysA = Object.keys(a)
|
||||
const keysB = Object.keys(b)
|
||||
|
||||
if (keysA.length !== keysB.length) return false
|
||||
|
||||
for (const key of keysA) {
|
||||
if (!keysB.includes(key)) return false
|
||||
if (!deepEqual(a[key], b[key])) return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Format diff as human-readable string
|
||||
*
|
||||
* @param diff Diff to format
|
||||
* @returns Formatted string
|
||||
*/
|
||||
export function formatDiff(diff: VersionDiff): string {
|
||||
const lines: string[] = []
|
||||
|
||||
lines.push(`Diff: ${diff.entityId} v${diff.fromVersion} → v${diff.toVersion}`)
|
||||
lines.push('')
|
||||
|
||||
if (diff.identical) {
|
||||
lines.push('No changes')
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
lines.push(`Total changes: ${diff.totalChanges}`)
|
||||
lines.push('')
|
||||
|
||||
if (diff.added.length > 0) {
|
||||
lines.push(`Added (${diff.added.length}):`)
|
||||
for (const change of diff.added) {
|
||||
lines.push(` + ${change.path}: ${formatValue(change.newValue)}`)
|
||||
}
|
||||
lines.push('')
|
||||
}
|
||||
|
||||
if (diff.removed.length > 0) {
|
||||
lines.push(`Removed (${diff.removed.length}):`)
|
||||
for (const change of diff.removed) {
|
||||
lines.push(` - ${change.path}: ${formatValue(change.oldValue)}`)
|
||||
}
|
||||
lines.push('')
|
||||
}
|
||||
|
||||
if (diff.modified.length > 0) {
|
||||
lines.push(`Modified (${diff.modified.length}):`)
|
||||
for (const change of diff.modified) {
|
||||
lines.push(` ~ ${change.path}:`)
|
||||
lines.push(` ${formatValue(change.oldValue)}`)
|
||||
lines.push(` → ${formatValue(change.newValue)}`)
|
||||
}
|
||||
lines.push('')
|
||||
}
|
||||
|
||||
if (diff.typeChanged.length > 0) {
|
||||
lines.push(`Type Changed (${diff.typeChanged.length}):`)
|
||||
for (const change of diff.typeChanged) {
|
||||
lines.push(` ! ${change.path}: ${change.oldType} → ${change.newType}`)
|
||||
lines.push(` ${formatValue(change.oldValue)}`)
|
||||
lines.push(` → ${formatValue(change.newValue)}`)
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
/**
|
||||
* Format value for display
|
||||
*/
|
||||
function formatValue(value: any): string {
|
||||
if (value === null) return 'null'
|
||||
if (value === undefined) return 'undefined'
|
||||
if (typeof value === 'string') return `"${value}"`
|
||||
if (typeof value === 'object') {
|
||||
try {
|
||||
return JSON.stringify(value)
|
||||
} catch {
|
||||
return '[Object]'
|
||||
}
|
||||
}
|
||||
return String(value)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get summary statistics about a diff
|
||||
*/
|
||||
export function getDiffStats(diff: VersionDiff): {
|
||||
changedFields: number
|
||||
addedFields: number
|
||||
removedFields: number
|
||||
modifiedFields: number
|
||||
typeChangedFields: number
|
||||
} {
|
||||
return {
|
||||
changedFields: diff.totalChanges,
|
||||
addedFields: diff.added.length,
|
||||
removedFields: diff.removed.length,
|
||||
modifiedFields: diff.modified.length,
|
||||
typeChangedFields: diff.typeChanged.length
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if diff has any changes
|
||||
*/
|
||||
export function hasChanges(diff: VersionDiff): boolean {
|
||||
return !diff.identical
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all changed field paths
|
||||
*/
|
||||
export function getChangedPaths(diff: VersionDiff): string[] {
|
||||
const paths = new Set<string>()
|
||||
|
||||
for (const change of diff.added) paths.add(change.path)
|
||||
for (const change of diff.removed) paths.add(change.path)
|
||||
for (const change of diff.modified) paths.add(change.path)
|
||||
for (const change of diff.typeChanged) paths.add(change.path)
|
||||
|
||||
return Array.from(paths).sort()
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter diff to only include specific paths
|
||||
*/
|
||||
export function filterDiff(diff: VersionDiff, paths: string[]): VersionDiff {
|
||||
const pathSet = new Set(paths)
|
||||
|
||||
const filterChanges = (changes: FieldChange[]) =>
|
||||
changes.filter((c) => pathSet.has(c.path) || paths.some((p) => c.path.startsWith(p + '.')))
|
||||
|
||||
const added = filterChanges(diff.added)
|
||||
const removed = filterChanges(diff.removed)
|
||||
const modified = filterChanges(diff.modified)
|
||||
const typeChanged = filterChanges(diff.typeChanged)
|
||||
|
||||
return {
|
||||
...diff,
|
||||
added,
|
||||
removed,
|
||||
modified,
|
||||
typeChanged,
|
||||
totalChanges: added.length + removed.length + modified.length + typeChanged.length,
|
||||
identical: added.length + removed.length + modified.length + typeChanged.length === 0
|
||||
}
|
||||
}
|
||||
|
|
@ -1,310 +0,0 @@
|
|||
/**
|
||||
* VersionIndex - Pure Key-Value Version Storage
|
||||
*
|
||||
* Stores version metadata using simple key-value storage:
|
||||
* - Version list per entity: __version_meta_{entityId}_{branch}
|
||||
* - Content stored separately by VersionStorage
|
||||
*
|
||||
* Key Design Decisions:
|
||||
* - Versions are NOT entities (no brain.add())
|
||||
* - Versions do NOT pollute find() results
|
||||
* - Simple O(1) lookups per entity
|
||||
* - Versions per entity is typically small (10-1000)
|
||||
*
|
||||
* NO MOCKS - Production implementation
|
||||
*/
|
||||
|
||||
import type { EntityVersion, VersionQuery } from './VersionManager.js'
|
||||
|
||||
/**
|
||||
* Internal storage structure for version metadata
|
||||
*/
|
||||
interface VersionMetadataStore {
|
||||
entityId: string
|
||||
branch: string
|
||||
versions: VersionEntry[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Individual version entry in the store
|
||||
*/
|
||||
interface VersionEntry {
|
||||
version: number
|
||||
timestamp: number
|
||||
contentHash: string
|
||||
commitHash?: string
|
||||
tag?: string
|
||||
description?: string
|
||||
author?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* VersionIndex - Pure key-value version metadata storage
|
||||
*
|
||||
* Uses simple JSON storage instead of creating entities.
|
||||
* This ensures versions never appear in find() results.
|
||||
*/
|
||||
export class VersionIndex {
|
||||
private brain: any // Brainy instance
|
||||
private initialized: boolean = false
|
||||
|
||||
constructor(brain: any) {
|
||||
this.brain = brain
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize version index
|
||||
*/
|
||||
async initialize(): Promise<void> {
|
||||
if (this.initialized) return
|
||||
this.initialized = true
|
||||
}
|
||||
|
||||
/**
|
||||
* Add version to index
|
||||
*
|
||||
* Stores version entry in key-value storage.
|
||||
* Handles deduplication by content hash.
|
||||
*
|
||||
* @param version Version metadata to store
|
||||
*/
|
||||
async addVersion(version: EntityVersion): Promise<void> {
|
||||
await this.initialize()
|
||||
|
||||
const key = this.getMetaKey(version.entityId, version.branch)
|
||||
const store = await this.loadStore(key) || {
|
||||
entityId: version.entityId,
|
||||
branch: version.branch,
|
||||
versions: []
|
||||
}
|
||||
|
||||
// Check for duplicate content hash (deduplication)
|
||||
const existing = store.versions.find(v => v.contentHash === version.contentHash)
|
||||
if (existing) {
|
||||
// Update tag/description if provided on duplicate save
|
||||
let updated = false
|
||||
if (version.tag && version.tag !== existing.tag) {
|
||||
existing.tag = version.tag
|
||||
updated = true
|
||||
}
|
||||
if (version.description && version.description !== existing.description) {
|
||||
existing.description = version.description
|
||||
updated = true
|
||||
}
|
||||
if (updated) {
|
||||
await this.saveStore(key, store)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Add new version entry
|
||||
store.versions.push({
|
||||
version: version.version,
|
||||
timestamp: version.timestamp,
|
||||
contentHash: version.contentHash,
|
||||
commitHash: version.commitHash,
|
||||
tag: version.tag,
|
||||
description: version.description,
|
||||
author: version.author
|
||||
})
|
||||
|
||||
await this.saveStore(key, store)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get versions for an entity
|
||||
*
|
||||
* @param query Version query with filters
|
||||
* @returns List of versions (newest first)
|
||||
*/
|
||||
async getVersions(query: VersionQuery): Promise<EntityVersion[]> {
|
||||
await this.initialize()
|
||||
|
||||
const branch = query.branch || this.brain.currentBranch
|
||||
const key = this.getMetaKey(query.entityId, branch)
|
||||
const store = await this.loadStore(key)
|
||||
if (!store) return []
|
||||
|
||||
// Convert entries to EntityVersion format
|
||||
let versions: EntityVersion[] = store.versions.map(entry => ({
|
||||
version: entry.version,
|
||||
entityId: store.entityId,
|
||||
branch: store.branch,
|
||||
timestamp: entry.timestamp,
|
||||
contentHash: entry.contentHash,
|
||||
commitHash: entry.commitHash || '',
|
||||
tag: entry.tag,
|
||||
description: entry.description,
|
||||
author: entry.author
|
||||
}))
|
||||
|
||||
// Apply filters
|
||||
if (query.tag) {
|
||||
versions = versions.filter(v => v.tag === query.tag)
|
||||
}
|
||||
if (query.startDate) {
|
||||
versions = versions.filter(v => v.timestamp >= query.startDate!)
|
||||
}
|
||||
if (query.endDate) {
|
||||
versions = versions.filter(v => v.timestamp <= query.endDate!)
|
||||
}
|
||||
|
||||
// Sort newest first (highest version number first)
|
||||
versions.sort((a, b) => b.version - a.version)
|
||||
|
||||
// Apply pagination
|
||||
const start = query.offset || 0
|
||||
const end = query.limit ? start + query.limit : undefined
|
||||
return versions.slice(start, end)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get specific version
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @param version Version number
|
||||
* @param branch Branch name
|
||||
* @returns Version metadata or null
|
||||
*/
|
||||
async getVersion(
|
||||
entityId: string,
|
||||
version: number,
|
||||
branch: string
|
||||
): Promise<EntityVersion | null> {
|
||||
const versions = await this.getVersions({ entityId, branch })
|
||||
return versions.find(v => v.version === version) || null
|
||||
}
|
||||
|
||||
/**
|
||||
* Get version by tag
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @param tag Version tag
|
||||
* @param branch Branch name
|
||||
* @returns Version metadata or null
|
||||
*/
|
||||
async getVersionByTag(
|
||||
entityId: string,
|
||||
tag: string,
|
||||
branch: string
|
||||
): Promise<EntityVersion | null> {
|
||||
const versions = await this.getVersions({ entityId, branch, tag })
|
||||
return versions[0] || null
|
||||
}
|
||||
|
||||
/**
|
||||
* Get version count for entity
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @param branch Branch name
|
||||
* @returns Number of versions
|
||||
*/
|
||||
async getVersionCount(entityId: string, branch: string): Promise<number> {
|
||||
const key = this.getMetaKey(entityId, branch)
|
||||
const store = await this.loadStore(key)
|
||||
return store?.versions.length || 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove version from index
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @param version Version number
|
||||
* @param branch Branch name
|
||||
*/
|
||||
async removeVersion(
|
||||
entityId: string,
|
||||
version: number,
|
||||
branch: string
|
||||
): Promise<void> {
|
||||
await this.initialize()
|
||||
|
||||
const key = this.getMetaKey(entityId, branch)
|
||||
const store = await this.loadStore(key)
|
||||
if (!store) return
|
||||
|
||||
const initialLength = store.versions.length
|
||||
store.versions = store.versions.filter(v => v.version !== version)
|
||||
|
||||
// Only save if something was removed
|
||||
if (store.versions.length < initialLength) {
|
||||
await this.saveStore(key, store)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all versions for an entity
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @param branch Branch name
|
||||
* @returns Number of versions deleted
|
||||
*/
|
||||
async clearVersions(entityId: string, branch: string): Promise<number> {
|
||||
const key = this.getMetaKey(entityId, branch)
|
||||
const store = await this.loadStore(key)
|
||||
if (!store) return 0
|
||||
|
||||
const count = store.versions.length
|
||||
|
||||
// Delete the store by saving null/empty
|
||||
await this.saveStore(key, { entityId, branch, versions: [] })
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all versioned entities (for cleanup/debugging)
|
||||
*
|
||||
* Note: This is an expensive operation that requires scanning.
|
||||
* In the simple key-value approach, we don't maintain a global index.
|
||||
* This method returns an empty array - use storage-level scanning if needed.
|
||||
*
|
||||
* @returns Empty array (not supported in simple approach)
|
||||
*/
|
||||
async getVersionedEntities(): Promise<string[]> {
|
||||
// In the simple key-value approach, we don't maintain a global index
|
||||
// of all versioned entities. This would require scanning storage.
|
||||
// For most use cases, you know which entities you've versioned.
|
||||
return []
|
||||
}
|
||||
|
||||
// ============= Private Helpers =============
|
||||
|
||||
/**
|
||||
* Generate storage key for version metadata
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @param branch Branch name
|
||||
* @returns Storage key
|
||||
*/
|
||||
private getMetaKey(entityId: string, branch: string): string {
|
||||
return `__version_meta_${entityId}_${branch}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Load version store from storage
|
||||
*
|
||||
* @param key Storage key
|
||||
* @returns Version store or null
|
||||
*/
|
||||
private async loadStore(key: string): Promise<VersionMetadataStore | null> {
|
||||
try {
|
||||
const store = await this.brain.storageAdapter.getMetadata(key)
|
||||
// Handle empty store
|
||||
if (!store || !store.versions) return null
|
||||
return store as VersionMetadataStore
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save version store to storage
|
||||
*
|
||||
* @param key Storage key
|
||||
* @param store Version store
|
||||
*/
|
||||
private async saveStore(key: string, store: VersionMetadataStore): Promise<void> {
|
||||
await this.brain.storageAdapter.saveMetadata(key, store)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,667 +0,0 @@
|
|||
/**
|
||||
* VersionManager - Entity-Level Versioning Engine
|
||||
*
|
||||
* Provides entity-level version control with:
|
||||
* - save() - Create entity version
|
||||
* - restore() - Restore entity to specific version (now updates all indexes)
|
||||
* - list() - List all versions of an entity
|
||||
* - compare() - Deep diff between versions
|
||||
* - prune() - Remove old versions (retention policies)
|
||||
*
|
||||
* Architecture:
|
||||
* - Versions stored as key-value pairs, NOT as entities (no index pollution)
|
||||
* - Content-addressable: SHA-256 hashing for deduplication
|
||||
* - Space-efficient: Only stores unique content
|
||||
* - Branch-aware: Versions tied to current branch
|
||||
* - restore() uses brain.update() to refresh ALL indexes (HNSW, metadata, graph)
|
||||
*
|
||||
* Storage keys:
|
||||
* - Version metadata: __version_meta_{entityId}_{branch}
|
||||
* - Version content: __system_version_{entityId}_{contentHash}
|
||||
*
|
||||
* ZERO-CONFIG - Works automatically with existing storage infrastructure.
|
||||
* NO MOCKS - Production implementation.
|
||||
*/
|
||||
|
||||
import { BaseStorage } from '../storage/baseStorage.js'
|
||||
import { VersionStorage } from './VersionStorage.js'
|
||||
import { VersionIndex } from './VersionIndex.js'
|
||||
import { VersionDiff, compareEntityVersions } from './VersionDiff.js'
|
||||
import type { NounMetadata } from '../coreTypes.js'
|
||||
|
||||
export interface EntityVersion {
|
||||
/** Version number (1-indexed, sequential per entity) */
|
||||
version: number
|
||||
|
||||
/** Entity ID */
|
||||
entityId: string
|
||||
|
||||
/** Branch this version was created on */
|
||||
branch: string
|
||||
|
||||
/** Commit hash containing this version */
|
||||
commitHash: string
|
||||
|
||||
/** Timestamp of version creation */
|
||||
timestamp: number
|
||||
|
||||
/** Optional user-provided tag (e.g., 'v1.0', 'before-refactor') */
|
||||
tag?: string
|
||||
|
||||
/** Optional description */
|
||||
description?: string
|
||||
|
||||
/** Content hash (SHA-256 of entity data) */
|
||||
contentHash: string
|
||||
|
||||
/** Author of this version */
|
||||
author?: string
|
||||
|
||||
/** Metadata about the version */
|
||||
metadata?: Record<string, any>
|
||||
}
|
||||
|
||||
export interface VersionQuery {
|
||||
/** Entity ID to query versions for */
|
||||
entityId: string
|
||||
|
||||
/** Optional: Filter by branch (default: current branch) */
|
||||
branch?: string
|
||||
|
||||
/** Optional: Limit number of versions returned */
|
||||
limit?: number
|
||||
|
||||
/** Optional: Skip first N versions */
|
||||
offset?: number
|
||||
|
||||
/** Optional: Filter by tag */
|
||||
tag?: string
|
||||
|
||||
/** Optional: Filter by date range */
|
||||
startDate?: number
|
||||
endDate?: number
|
||||
}
|
||||
|
||||
export interface SaveVersionOptions {
|
||||
/** Optional tag for this version (e.g., 'v1.0', 'milestone-1') */
|
||||
tag?: string
|
||||
|
||||
/** Optional description */
|
||||
description?: string
|
||||
|
||||
/** Optional author name */
|
||||
author?: string
|
||||
|
||||
/** Optional custom metadata */
|
||||
metadata?: Record<string, any>
|
||||
|
||||
/** Optional: Create commit automatically (default: false) */
|
||||
createCommit?: boolean
|
||||
|
||||
/** Optional: Commit message if createCommit is true */
|
||||
commitMessage?: string
|
||||
}
|
||||
|
||||
export interface RestoreOptions {
|
||||
/** Optional: Create version before restoring (for undo) */
|
||||
createSnapshot?: boolean
|
||||
|
||||
/** Optional: Tag for snapshot before restore */
|
||||
snapshotTag?: string
|
||||
}
|
||||
|
||||
export interface PruneOptions {
|
||||
/** Keep N most recent versions (required if keepVersions not set) */
|
||||
keepRecent?: number
|
||||
|
||||
/** Keep versions newer than timestamp (optional) */
|
||||
keepAfter?: number
|
||||
|
||||
/** Keep tagged versions (default: true) */
|
||||
keepTagged?: boolean
|
||||
|
||||
/** Dry run - don't actually delete (default: false) */
|
||||
dryRun?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* VersionManager - Core versioning engine
|
||||
*/
|
||||
export class VersionManager {
|
||||
private brain: any // Brainy instance
|
||||
private versionStorage: VersionStorage
|
||||
private versionIndex: VersionIndex
|
||||
private initialized: boolean = false
|
||||
|
||||
constructor(brain: any) {
|
||||
this.brain = brain
|
||||
this.versionStorage = new VersionStorage(brain)
|
||||
this.versionIndex = new VersionIndex(brain)
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an entity is a VFS file
|
||||
* VFS files store content in BlobStorage, not in entity.data
|
||||
*
|
||||
* @param entity Entity metadata object
|
||||
* @returns True if entity is a VFS file
|
||||
*/
|
||||
private isVFSFile(entity: any): boolean {
|
||||
return (
|
||||
entity?.isVFS === true &&
|
||||
entity?.vfsType === 'file' &&
|
||||
typeof entity?.path === 'string'
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if content is text-based for encoding decisions
|
||||
* @param mimeType MIME type of the content
|
||||
* @returns True if content should be stored as UTF-8 string
|
||||
*/
|
||||
private isTextContent(mimeType?: string): boolean {
|
||||
if (!mimeType) return false
|
||||
return (
|
||||
mimeType.startsWith('text/') ||
|
||||
mimeType === 'application/json' ||
|
||||
mimeType === 'application/javascript' ||
|
||||
mimeType === 'application/typescript' ||
|
||||
mimeType === 'application/xml' ||
|
||||
mimeType.includes('+xml') ||
|
||||
mimeType.includes('+json')
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize versioning system (lazy)
|
||||
*/
|
||||
async initialize(): Promise<void> {
|
||||
if (this.initialized) return
|
||||
|
||||
await this.versionStorage.initialize()
|
||||
await this.versionIndex.initialize()
|
||||
|
||||
this.initialized = true
|
||||
}
|
||||
|
||||
/**
|
||||
* Save a version of an entity
|
||||
*
|
||||
* Creates a version snapshot of the current entity state.
|
||||
* If createCommit is true, also creates a commit containing this version.
|
||||
*
|
||||
* @param entityId Entity ID to version
|
||||
* @param options Save options
|
||||
* @returns Created version metadata
|
||||
*/
|
||||
async save(
|
||||
entityId: string,
|
||||
options: SaveVersionOptions = {}
|
||||
): Promise<EntityVersion> {
|
||||
await this.initialize()
|
||||
|
||||
// Get current entity state
|
||||
const entity = await this.brain.getNounMetadata(entityId)
|
||||
if (!entity) {
|
||||
throw new Error(`Entity ${entityId} not found`)
|
||||
}
|
||||
|
||||
// FIX: For VFS file entities, fetch current content from blob storage
|
||||
// The entity.data field contains stale embedding text, not actual file content
|
||||
// VFS files store their real content in BlobStorage (content-addressable)
|
||||
if (this.isVFSFile(entity)) {
|
||||
if (!this.brain.vfs) {
|
||||
throw new Error(
|
||||
`Cannot version VFS file ${entityId}: VFS not initialized. ` +
|
||||
`Ensure brain.vfs is available before versioning VFS files.`
|
||||
)
|
||||
}
|
||||
|
||||
// Read fresh content from blob storage via VFS
|
||||
const freshContent: Buffer = await this.brain.vfs.readFile(entity.path)
|
||||
|
||||
// Store content with appropriate encoding
|
||||
// Text files as UTF-8 string (readable, smaller)
|
||||
// Binary files as base64 (safe for JSON serialization)
|
||||
if (this.isTextContent(entity.mimeType)) {
|
||||
entity.data = freshContent.toString('utf-8')
|
||||
} else {
|
||||
entity.data = freshContent.toString('base64')
|
||||
entity._vfsEncoding = 'base64' // Flag for restore to decode
|
||||
}
|
||||
}
|
||||
|
||||
// Get current branch
|
||||
const currentBranch = this.brain.currentBranch
|
||||
|
||||
// Get next version number
|
||||
const existingVersions = await this.versionIndex.getVersions({
|
||||
entityId,
|
||||
branch: currentBranch
|
||||
})
|
||||
const nextVersion = existingVersions.length + 1
|
||||
|
||||
// Calculate content hash
|
||||
const contentHash = this.versionStorage.hashEntity(entity)
|
||||
|
||||
// Check for duplicate (same content as last version)
|
||||
if (existingVersions.length > 0) {
|
||||
const lastVersion = existingVersions[existingVersions.length - 1]
|
||||
if (lastVersion.contentHash === contentHash) {
|
||||
// Content unchanged - return last version instead of creating duplicate
|
||||
return lastVersion
|
||||
}
|
||||
}
|
||||
|
||||
// Create commit if requested
|
||||
let commitHash: string
|
||||
if (options.createCommit) {
|
||||
const commitMessage =
|
||||
options.commitMessage || `Version ${nextVersion} of entity ${entityId}`
|
||||
|
||||
// Use brain's commit method (note: single options object)
|
||||
await this.brain.commit({
|
||||
message: commitMessage,
|
||||
author: options.author,
|
||||
metadata: {
|
||||
versionedEntity: entityId,
|
||||
version: nextVersion,
|
||||
...options.metadata
|
||||
}
|
||||
})
|
||||
|
||||
// Get the commit hash that was just created
|
||||
const refManager = this.brain.refManager
|
||||
const ref = await refManager.getRef(currentBranch)
|
||||
commitHash = ref.commitHash
|
||||
} else {
|
||||
// Use current HEAD commit
|
||||
const refManager = this.brain.refManager
|
||||
const ref = await refManager.getRef(currentBranch)
|
||||
if (!ref) {
|
||||
throw new Error(
|
||||
`No commit exists on branch ${currentBranch}. Create a commit first or use createCommit: true`
|
||||
)
|
||||
}
|
||||
commitHash = ref.commitHash
|
||||
}
|
||||
|
||||
// Create version metadata
|
||||
const version: EntityVersion = {
|
||||
version: nextVersion,
|
||||
entityId,
|
||||
branch: currentBranch,
|
||||
commitHash,
|
||||
timestamp: Date.now(),
|
||||
contentHash,
|
||||
tag: options.tag,
|
||||
description: options.description,
|
||||
author: options.author,
|
||||
metadata: options.metadata
|
||||
}
|
||||
|
||||
// Store version
|
||||
await this.versionStorage.saveVersion(version, entity)
|
||||
await this.versionIndex.addVersion(version)
|
||||
|
||||
return version
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all versions of an entity
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @param query Optional query filters
|
||||
* @returns List of versions (newest first)
|
||||
*/
|
||||
async list(
|
||||
entityId: string,
|
||||
query: Partial<VersionQuery> = {}
|
||||
): Promise<EntityVersion[]> {
|
||||
await this.initialize()
|
||||
|
||||
const currentBranch = this.brain.currentBranch
|
||||
|
||||
return this.versionIndex.getVersions({
|
||||
entityId,
|
||||
branch: query.branch || currentBranch,
|
||||
limit: query.limit,
|
||||
offset: query.offset,
|
||||
tag: query.tag,
|
||||
startDate: query.startDate,
|
||||
endDate: query.endDate
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a specific version of an entity
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @param version Version number (1-indexed)
|
||||
* @returns Version metadata
|
||||
*/
|
||||
async getVersion(
|
||||
entityId: string,
|
||||
version: number
|
||||
): Promise<EntityVersion | null> {
|
||||
await this.initialize()
|
||||
|
||||
const currentBranch = this.brain.currentBranch
|
||||
return this.versionIndex.getVersion(entityId, version, currentBranch)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get version by tag
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @param tag Version tag
|
||||
* @returns Version metadata
|
||||
*/
|
||||
async getVersionByTag(
|
||||
entityId: string,
|
||||
tag: string
|
||||
): Promise<EntityVersion | null> {
|
||||
await this.initialize()
|
||||
|
||||
const currentBranch = this.brain.currentBranch
|
||||
return this.versionIndex.getVersionByTag(entityId, tag, currentBranch)
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore entity to a specific version
|
||||
*
|
||||
* Overwrites current entity state with the specified version.
|
||||
* Optionally creates a snapshot before restoring for undo capability.
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @param version Version number or tag
|
||||
* @param options Restore options
|
||||
* @returns Restored version metadata
|
||||
*/
|
||||
async restore(
|
||||
entityId: string,
|
||||
version: number | string,
|
||||
options: RestoreOptions = {}
|
||||
): Promise<EntityVersion> {
|
||||
await this.initialize()
|
||||
|
||||
// Create snapshot before restoring (for undo)
|
||||
if (options.createSnapshot) {
|
||||
await this.save(entityId, {
|
||||
tag: options.snapshotTag || 'before-restore',
|
||||
description: `Snapshot before restoring to version ${version}`,
|
||||
metadata: { restoringTo: version }
|
||||
})
|
||||
}
|
||||
|
||||
// Get target version
|
||||
let targetVersion: EntityVersion | null
|
||||
if (typeof version === 'number') {
|
||||
targetVersion = await this.getVersion(entityId, version)
|
||||
} else {
|
||||
targetVersion = await this.getVersionByTag(entityId, version)
|
||||
}
|
||||
|
||||
if (!targetVersion) {
|
||||
throw new Error(
|
||||
`Version ${version} not found for entity ${entityId}`
|
||||
)
|
||||
}
|
||||
|
||||
// Load versioned entity data
|
||||
const versionedEntity = await this.versionStorage.loadVersion(targetVersion)
|
||||
if (!versionedEntity) {
|
||||
throw new Error(
|
||||
`Version data not found for entity ${entityId} version ${version}`
|
||||
)
|
||||
}
|
||||
|
||||
// FIX: For VFS file entities, write content back to blob storage
|
||||
// The versioned data contains the actual file content (not stale embedding text)
|
||||
// Using vfs.writeFile() ensures proper blob creation and metadata update
|
||||
if (this.isVFSFile(versionedEntity)) {
|
||||
if (!this.brain.vfs) {
|
||||
throw new Error(
|
||||
`Cannot restore VFS file ${entityId}: VFS not initialized. ` +
|
||||
`Ensure brain.vfs is available before restoring VFS files.`
|
||||
)
|
||||
}
|
||||
|
||||
// Decode content based on how it was stored
|
||||
let content: Buffer
|
||||
if (versionedEntity._vfsEncoding === 'base64') {
|
||||
// Binary file stored as base64
|
||||
content = Buffer.from(versionedEntity.data as string, 'base64')
|
||||
} else {
|
||||
// Text file stored as UTF-8 string
|
||||
content = Buffer.from(versionedEntity.data as string, 'utf-8')
|
||||
}
|
||||
|
||||
// Write content back to VFS - this handles:
|
||||
// - BlobStorage write (new hash)
|
||||
// - Entity metadata update
|
||||
// - Path resolver cache update
|
||||
await this.brain.vfs.writeFile(versionedEntity.path, content)
|
||||
|
||||
return targetVersion
|
||||
}
|
||||
|
||||
// For non-VFS entities, use existing brain.update() logic
|
||||
// Extract standard fields vs custom metadata
|
||||
// NounMetadata has: noun, data, createdAt, updatedAt, createdBy, service, confidence, weight
|
||||
const {
|
||||
noun,
|
||||
data,
|
||||
createdAt,
|
||||
updatedAt,
|
||||
createdBy,
|
||||
service,
|
||||
confidence,
|
||||
weight,
|
||||
...customMetadata
|
||||
} = versionedEntity
|
||||
|
||||
// Use brain.update() to restore - this updates ALL indexes (HNSW, metadata, graph)
|
||||
// This is critical: saveNounMetadata() only saves to storage without updating indexes
|
||||
await this.brain.update({
|
||||
id: entityId,
|
||||
data: data,
|
||||
type: noun,
|
||||
metadata: customMetadata,
|
||||
confidence: confidence,
|
||||
weight: weight,
|
||||
merge: false // Replace entirely, don't merge with existing metadata
|
||||
})
|
||||
|
||||
return targetVersion
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare two versions of an entity
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @param fromVersion Version number or tag (older)
|
||||
* @param toVersion Version number or tag (newer)
|
||||
* @returns Diff between versions
|
||||
*/
|
||||
async compare(
|
||||
entityId: string,
|
||||
fromVersion: number | string,
|
||||
toVersion: number | string
|
||||
): Promise<VersionDiff> {
|
||||
await this.initialize()
|
||||
|
||||
// Get versions
|
||||
const fromVer =
|
||||
typeof fromVersion === 'number'
|
||||
? await this.getVersion(entityId, fromVersion)
|
||||
: await this.getVersionByTag(entityId, fromVersion)
|
||||
|
||||
const toVer =
|
||||
typeof toVersion === 'number'
|
||||
? await this.getVersion(entityId, toVersion)
|
||||
: await this.getVersionByTag(entityId, toVersion)
|
||||
|
||||
if (!fromVer) {
|
||||
throw new Error(
|
||||
`Version ${fromVersion} not found for entity ${entityId}`
|
||||
)
|
||||
}
|
||||
if (!toVer) {
|
||||
throw new Error(
|
||||
`Version ${toVersion} not found for entity ${entityId}`
|
||||
)
|
||||
}
|
||||
|
||||
// Load entity data
|
||||
const fromEntity = await this.versionStorage.loadVersion(fromVer)
|
||||
const toEntity = await this.versionStorage.loadVersion(toVer)
|
||||
|
||||
if (!fromEntity || !toEntity) {
|
||||
throw new Error('Failed to load version data for comparison')
|
||||
}
|
||||
|
||||
// Compare versions
|
||||
return compareEntityVersions(fromEntity, toEntity, {
|
||||
fromVersion: fromVer.version,
|
||||
toVersion: toVer.version,
|
||||
entityId
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Prune old versions based on retention policy
|
||||
*
|
||||
* @param entityId Entity ID (or '*' for all entities)
|
||||
* @param options Prune options
|
||||
* @returns Number of versions deleted
|
||||
*/
|
||||
async prune(
|
||||
entityId: string,
|
||||
options: PruneOptions
|
||||
): Promise<{ deleted: number; kept: number }> {
|
||||
await this.initialize()
|
||||
|
||||
if (!options.keepRecent && !options.keepAfter) {
|
||||
throw new Error(
|
||||
'Must specify either keepRecent or keepAfter in prune options'
|
||||
)
|
||||
}
|
||||
|
||||
const currentBranch = this.brain.currentBranch
|
||||
|
||||
// Get all versions
|
||||
const versions = await this.versionIndex.getVersions({
|
||||
entityId,
|
||||
branch: currentBranch
|
||||
})
|
||||
|
||||
// Determine which versions to keep
|
||||
const toKeep = new Set<number>()
|
||||
const toDelete: EntityVersion[] = []
|
||||
|
||||
// Keep recent versions
|
||||
if (options.keepRecent) {
|
||||
const recentVersions = versions.slice(0, options.keepRecent)
|
||||
recentVersions.forEach((v) => toKeep.add(v.version))
|
||||
}
|
||||
|
||||
// Keep versions after timestamp
|
||||
if (options.keepAfter) {
|
||||
versions
|
||||
.filter((v) => v.timestamp >= options.keepAfter!)
|
||||
.forEach((v) => toKeep.add(v.version))
|
||||
}
|
||||
|
||||
// Keep tagged versions
|
||||
if (options.keepTagged !== false) {
|
||||
versions
|
||||
.filter((v) => v.tag !== undefined)
|
||||
.forEach((v) => toKeep.add(v.version))
|
||||
}
|
||||
|
||||
// Build delete list
|
||||
for (const version of versions) {
|
||||
if (!toKeep.has(version.version)) {
|
||||
toDelete.push(version)
|
||||
}
|
||||
}
|
||||
|
||||
// Dry run - just return counts
|
||||
if (options.dryRun) {
|
||||
return {
|
||||
deleted: toDelete.length,
|
||||
kept: toKeep.size
|
||||
}
|
||||
}
|
||||
|
||||
// Delete versions
|
||||
for (const version of toDelete) {
|
||||
await this.versionStorage.deleteVersion(version)
|
||||
await this.versionIndex.removeVersion(
|
||||
entityId,
|
||||
version.version,
|
||||
currentBranch
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
deleted: toDelete.length,
|
||||
kept: toKeep.size
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get version count for an entity
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @returns Number of versions
|
||||
*/
|
||||
async getVersionCount(entityId: string): Promise<number> {
|
||||
await this.initialize()
|
||||
|
||||
const currentBranch = this.brain.currentBranch
|
||||
return this.versionIndex.getVersionCount(entityId, currentBranch)
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if entity has versions
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @returns True if entity has versions
|
||||
*/
|
||||
async hasVersions(entityId: string): Promise<boolean> {
|
||||
const count = await this.getVersionCount(entityId)
|
||||
return count > 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Get latest version of an entity
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @returns Latest version metadata or null
|
||||
*/
|
||||
async getLatest(entityId: string): Promise<EntityVersion | null> {
|
||||
await this.initialize()
|
||||
|
||||
const versions = await this.list(entityId, { limit: 1 })
|
||||
return versions[0] || null
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all versions for an entity
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @returns Number of versions deleted
|
||||
*/
|
||||
async clear(entityId: string): Promise<number> {
|
||||
await this.initialize()
|
||||
|
||||
const result = await this.prune(entityId, {
|
||||
keepRecent: 0,
|
||||
keepTagged: false
|
||||
})
|
||||
|
||||
return result.deleted
|
||||
}
|
||||
}
|
||||
|
|
@ -1,250 +0,0 @@
|
|||
/**
|
||||
* VersionStorage - Hybrid Storage for Entity Versions
|
||||
*
|
||||
* Implements content-addressable storage for entity versions:
|
||||
* - SHA-256 content hashing for deduplication
|
||||
* - Uses BaseStorage.saveMetadata/getMetadata for storage
|
||||
* - Integrates with COW commit system
|
||||
* - Space-efficient: Only stores unique content
|
||||
*
|
||||
* Storage structure:
|
||||
* Version content is stored using system metadata keys:
|
||||
* __system_version_{entityId}_{contentHash}
|
||||
*
|
||||
* This integrates with BaseStorage's routing which places system keys
|
||||
* in the _system/ directory, keeping version data separate from entities.
|
||||
*
|
||||
* NO MOCKS - Production implementation
|
||||
*/
|
||||
|
||||
import { createHash } from 'crypto'
|
||||
import { BaseStorage } from '../storage/baseStorage.js'
|
||||
import type { NounMetadata } from '../coreTypes.js'
|
||||
import type { EntityVersion } from './VersionManager.js'
|
||||
|
||||
/**
|
||||
* VersionStorage - Content-addressable version storage
|
||||
*/
|
||||
export class VersionStorage {
|
||||
private brain: any // Brainy instance
|
||||
private initialized: boolean = false
|
||||
|
||||
constructor(brain: any) {
|
||||
this.brain = brain
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize version storage directories
|
||||
*/
|
||||
async initialize(): Promise<void> {
|
||||
if (this.initialized) return
|
||||
|
||||
// Version storage uses the same storage adapter as the main database
|
||||
// Directories are created automatically by the storage adapter
|
||||
|
||||
this.initialized = true
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate SHA-256 hash of entity content
|
||||
*
|
||||
* Used for content-addressable storage and deduplication
|
||||
*
|
||||
* @param entity Entity to hash
|
||||
* @returns SHA-256 hash (hex string)
|
||||
*/
|
||||
hashEntity(entity: NounMetadata): string {
|
||||
// Create stable JSON representation (sorted keys)
|
||||
const stableJson = this.toStableJson(entity)
|
||||
return createHash('sha256').update(stableJson).digest('hex')
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert entity to stable JSON (sorted keys for consistent hashing)
|
||||
*/
|
||||
private toStableJson(obj: any): string {
|
||||
if (obj === null) return 'null'
|
||||
if (obj === undefined) return 'undefined'
|
||||
if (typeof obj !== 'object') return JSON.stringify(obj)
|
||||
|
||||
if (Array.isArray(obj)) {
|
||||
const items = obj.map((item) => this.toStableJson(item))
|
||||
return `[${items.join(',') }]`
|
||||
}
|
||||
|
||||
// Sort object keys for stable hashing
|
||||
const sortedKeys = Object.keys(obj).sort()
|
||||
const pairs = sortedKeys.map((key) => {
|
||||
const value = this.toStableJson(obj[key])
|
||||
return `"${key}":${value}`
|
||||
})
|
||||
|
||||
return `{${pairs.join(',')}}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Save entity version to content-addressable storage
|
||||
*
|
||||
* @param version Version metadata
|
||||
* @param entity Entity data
|
||||
*/
|
||||
async saveVersion(
|
||||
version: EntityVersion,
|
||||
entity: NounMetadata
|
||||
): Promise<void> {
|
||||
await this.initialize()
|
||||
|
||||
// Content-addressable path: .brainy/versions/entities/{entityId}/{contentHash}.json
|
||||
const versionPath = this.getVersionPath(
|
||||
version.entityId,
|
||||
version.contentHash
|
||||
)
|
||||
|
||||
// Check if content already exists (deduplication)
|
||||
const exists = await this.contentExists(versionPath)
|
||||
if (exists) {
|
||||
// Content already stored - no need to write again
|
||||
return
|
||||
}
|
||||
|
||||
// Store entity data
|
||||
await this.writeVersionData(versionPath, entity)
|
||||
}
|
||||
|
||||
/**
|
||||
* Load entity version from storage
|
||||
*
|
||||
* @param version Version metadata
|
||||
* @returns Entity data or null if not found
|
||||
*/
|
||||
async loadVersion(version: EntityVersion): Promise<NounMetadata | null> {
|
||||
await this.initialize()
|
||||
|
||||
const versionPath = this.getVersionPath(
|
||||
version.entityId,
|
||||
version.contentHash
|
||||
)
|
||||
|
||||
try {
|
||||
return await this.readVersionData(versionPath)
|
||||
} catch (error) {
|
||||
console.error(`Failed to load version ${version.version}:`, error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete entity version from storage
|
||||
*
|
||||
* @param version Version to delete
|
||||
*/
|
||||
async deleteVersion(version: EntityVersion): Promise<void> {
|
||||
await this.initialize()
|
||||
|
||||
const versionPath = this.getVersionPath(
|
||||
version.entityId,
|
||||
version.contentHash
|
||||
)
|
||||
|
||||
await this.deleteVersionData(versionPath)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get version storage key
|
||||
*
|
||||
* Uses __system_ prefix so BaseStorage routes to system storage (_system/ directory)
|
||||
* This keeps version data separate from entity data.
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @param contentHash Content hash
|
||||
* @returns Storage key for version content
|
||||
*/
|
||||
private getVersionPath(entityId: string, contentHash: string): string {
|
||||
// Use system-prefixed key for BaseStorage.saveMetadata/getMetadata
|
||||
// BaseStorage recognizes __system_ prefix and routes to _system/ directory
|
||||
return `__system_version_${entityId}_${contentHash}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if content exists in storage
|
||||
*
|
||||
* @param key Storage key
|
||||
* @returns True if exists
|
||||
*/
|
||||
private async contentExists(key: string): Promise<boolean> {
|
||||
try {
|
||||
// Use getMetadata to check existence
|
||||
const adapter = this.brain.storageAdapter
|
||||
if (!adapter) return false
|
||||
|
||||
const data = await adapter.getMetadata(key)
|
||||
return data !== null
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write version data to storage
|
||||
*
|
||||
* @param key Storage key
|
||||
* @param entity Entity data
|
||||
*/
|
||||
private async writeVersionData(
|
||||
key: string,
|
||||
entity: NounMetadata
|
||||
): Promise<void> {
|
||||
const adapter = this.brain.storageAdapter
|
||||
|
||||
if (!adapter) {
|
||||
throw new Error('Storage adapter not available')
|
||||
}
|
||||
|
||||
// Use saveMetadata for storing version content
|
||||
// The key is system-prefixed so it routes to _system/ directory
|
||||
await adapter.saveMetadata(key, entity)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read version data from storage
|
||||
*
|
||||
* @param key Storage key
|
||||
* @returns Entity data
|
||||
*/
|
||||
private async readVersionData(key: string): Promise<NounMetadata> {
|
||||
const adapter = this.brain.storageAdapter
|
||||
|
||||
if (!adapter) {
|
||||
throw new Error('Storage adapter not available')
|
||||
}
|
||||
|
||||
// Use getMetadata for reading version content
|
||||
const entity = await adapter.getMetadata(key)
|
||||
if (!entity) {
|
||||
throw new Error(`Version data not found: ${key}`)
|
||||
}
|
||||
|
||||
return entity
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete version data from storage
|
||||
*
|
||||
* Note: Version content is content-addressed and immutable.
|
||||
* Deleting the version index entry (via VersionIndex.removeVersion) is sufficient.
|
||||
* The content may be shared with other versions (same contentHash).
|
||||
*
|
||||
* We don't actually delete version content to avoid breaking
|
||||
* other versions that may reference the same content hash.
|
||||
* A separate garbage collection process could clean up unreferenced content.
|
||||
*
|
||||
* @param key Storage key (unused - kept for API compatibility)
|
||||
*/
|
||||
private async deleteVersionData(_key: string): Promise<void> {
|
||||
// Version content is content-addressed and may be shared.
|
||||
// We don't delete it here to prevent breaking other versions.
|
||||
// The version INDEX is deleted via VersionIndex.removeVersion().
|
||||
// A GC process could clean up unreferenced content in the future.
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,520 +0,0 @@
|
|||
/**
|
||||
* VersioningAPI - Public API for Entity Versioning
|
||||
*
|
||||
* User-friendly wrapper around VersionManager with:
|
||||
* - Clean, simple API
|
||||
* - Smart defaults
|
||||
* - Error handling
|
||||
* - Type safety
|
||||
*
|
||||
* Usage:
|
||||
* const version = await brain.versions.save('entity-123', { tag: 'v1.0' })
|
||||
* const versions = await brain.versions.list('entity-123')
|
||||
* await brain.versions.restore('entity-123', 5)
|
||||
* const diff = await brain.versions.compare('entity-123', 2, 5)
|
||||
*
|
||||
* NO MOCKS - Production implementation
|
||||
*/
|
||||
|
||||
import { VersionManager } from './VersionManager.js'
|
||||
import type {
|
||||
EntityVersion,
|
||||
SaveVersionOptions,
|
||||
RestoreOptions,
|
||||
PruneOptions,
|
||||
VersionQuery
|
||||
} from './VersionManager.js'
|
||||
import type { VersionDiff, DiffOptions } from './VersionDiff.js'
|
||||
import type { BaseStorage } from '../storage/baseStorage.js'
|
||||
|
||||
/**
|
||||
* VersioningAPI - User-friendly versioning interface
|
||||
*/
|
||||
export class VersioningAPI {
|
||||
private manager: VersionManager
|
||||
private brain: any // Brainy instance
|
||||
|
||||
constructor(brain: any) {
|
||||
this.brain = brain
|
||||
this.manager = new VersionManager(brain as BaseStorage)
|
||||
}
|
||||
|
||||
/**
|
||||
* Save current state of entity as a new version
|
||||
*
|
||||
* Creates a version snapshot of the current entity state.
|
||||
* Automatically handles deduplication - if content hasn't changed,
|
||||
* returns the last version instead of creating a duplicate.
|
||||
*
|
||||
* @param entityId Entity ID to version
|
||||
* @param options Save options
|
||||
* @returns Created (or existing) version metadata
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // Simple save
|
||||
* const version = await brain.versions.save('user-123')
|
||||
*
|
||||
* // Save with tag and description
|
||||
* const version = await brain.versions.save('user-123', {
|
||||
* tag: 'v1.0',
|
||||
* description: 'Initial release',
|
||||
* author: 'alice'
|
||||
* })
|
||||
*
|
||||
* // Save and create commit
|
||||
* const version = await brain.versions.save('user-123', {
|
||||
* tag: 'milestone-1',
|
||||
* createCommit: true,
|
||||
* commitMessage: 'Milestone 1 complete'
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
async save(
|
||||
entityId: string,
|
||||
options: SaveVersionOptions = {}
|
||||
): Promise<EntityVersion> {
|
||||
return this.manager.save(entityId, options)
|
||||
}
|
||||
|
||||
/**
|
||||
* List all versions of an entity
|
||||
*
|
||||
* Returns versions sorted by version number (newest first).
|
||||
* Supports filtering by tag, date range, and pagination.
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @param options Query options
|
||||
* @returns List of versions (newest first)
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // Get all versions
|
||||
* const versions = await brain.versions.list('user-123')
|
||||
*
|
||||
* // Get last 10 versions
|
||||
* const recent = await brain.versions.list('user-123', { limit: 10 })
|
||||
*
|
||||
* // Get tagged versions
|
||||
* const tagged = await brain.versions.list('user-123', { tag: 'v*' })
|
||||
*
|
||||
* // Get versions from last 30 days
|
||||
* const recent = await brain.versions.list('user-123', {
|
||||
* startDate: Date.now() - 30 * 24 * 60 * 60 * 1000
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
async list(
|
||||
entityId: string,
|
||||
options: Partial<VersionQuery> = {}
|
||||
): Promise<EntityVersion[]> {
|
||||
return this.manager.list(entityId, options)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get specific version of an entity
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @param version Version number (1-indexed)
|
||||
* @returns Version metadata or null if not found
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const version = await brain.versions.getVersion('user-123', 5)
|
||||
* if (version) {
|
||||
* console.log(`Version ${version.version} created at ${new Date(version.timestamp)}`)
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
async getVersion(
|
||||
entityId: string,
|
||||
version: number
|
||||
): Promise<EntityVersion | null> {
|
||||
return this.manager.getVersion(entityId, version)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get version by tag
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @param tag Version tag
|
||||
* @returns Version metadata or null if not found
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const version = await brain.versions.getVersionByTag('user-123', 'v1.0')
|
||||
* ```
|
||||
*/
|
||||
async getVersionByTag(
|
||||
entityId: string,
|
||||
tag: string
|
||||
): Promise<EntityVersion | null> {
|
||||
return this.manager.getVersionByTag(entityId, tag)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get latest version of an entity
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @returns Latest version or null if no versions exist
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const latest = await brain.versions.getLatest('user-123')
|
||||
* ```
|
||||
*/
|
||||
async getLatest(entityId: string): Promise<EntityVersion | null> {
|
||||
return this.manager.getLatest(entityId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get version content without restoring
|
||||
*
|
||||
* Allows you to preview version data without modifying the current entity.
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @param version Version number or tag
|
||||
* @returns Version content
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // Preview version 5 without restoring
|
||||
* const oldData = await brain.versions.getContent('user-123', 5)
|
||||
* console.log('Version 5 had name:', oldData.name)
|
||||
*
|
||||
* // Compare with current
|
||||
* const current = await brain.getNounMetadata('user-123')
|
||||
* console.log('Current name:', current.name)
|
||||
* ```
|
||||
*/
|
||||
async getContent(
|
||||
entityId: string,
|
||||
version: number | string
|
||||
): Promise<any> {
|
||||
// Get version metadata
|
||||
let versionMeta: EntityVersion | null
|
||||
if (typeof version === 'number') {
|
||||
versionMeta = await this.manager.getVersion(entityId, version)
|
||||
} else {
|
||||
versionMeta = await this.manager.getVersionByTag(entityId, version)
|
||||
}
|
||||
|
||||
if (!versionMeta) {
|
||||
throw new Error(
|
||||
`Version ${version} not found for entity ${entityId}`
|
||||
)
|
||||
}
|
||||
|
||||
// Load version content
|
||||
const versionStorage = (this.manager as any).versionStorage
|
||||
const content = await versionStorage.loadVersion(versionMeta)
|
||||
|
||||
if (!content) {
|
||||
throw new Error(
|
||||
`Version content not found for entity ${entityId} version ${version}`
|
||||
)
|
||||
}
|
||||
|
||||
return content
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore entity to a specific version
|
||||
*
|
||||
* Overwrites current entity state with the specified version.
|
||||
* Optionally creates a snapshot before restoring for undo capability.
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @param version Version number or tag to restore to
|
||||
* @param options Restore options
|
||||
* @returns Restored version metadata
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // Simple restore
|
||||
* await brain.versions.restore('user-123', 5)
|
||||
*
|
||||
* // Restore with safety snapshot
|
||||
* await brain.versions.restore('user-123', 5, {
|
||||
* createSnapshot: true,
|
||||
* snapshotTag: 'before-restore'
|
||||
* })
|
||||
*
|
||||
* // Restore by tag
|
||||
* await brain.versions.restore('user-123', 'v1.0')
|
||||
* ```
|
||||
*/
|
||||
async restore(
|
||||
entityId: string,
|
||||
version: number | string,
|
||||
options: RestoreOptions = {}
|
||||
): Promise<EntityVersion> {
|
||||
return this.manager.restore(entityId, version, options)
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare two versions of an entity
|
||||
*
|
||||
* Generates a deep diff showing added, removed, modified, and type-changed fields.
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @param fromVersion Version number or tag (older)
|
||||
* @param toVersion Version number or tag (newer)
|
||||
* @returns Diff between versions
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // Compare version 2 to version 5
|
||||
* const diff = await brain.versions.compare('user-123', 2, 5)
|
||||
*
|
||||
* console.log(`Added fields: ${diff.added.length}`)
|
||||
* console.log(`Removed fields: ${diff.removed.length}`)
|
||||
* console.log(`Modified fields: ${diff.modified.length}`)
|
||||
*
|
||||
* // Print human-readable diff
|
||||
* import { formatDiff } from './VersionDiff.js'
|
||||
* console.log(formatDiff(diff))
|
||||
* ```
|
||||
*/
|
||||
async compare(
|
||||
entityId: string,
|
||||
fromVersion: number | string,
|
||||
toVersion: number | string
|
||||
): Promise<VersionDiff> {
|
||||
return this.manager.compare(entityId, fromVersion, toVersion)
|
||||
}
|
||||
|
||||
/**
|
||||
* Prune old versions based on retention policy
|
||||
*
|
||||
* Removes old versions while preserving recent and tagged versions.
|
||||
* Use dryRun to preview what would be deleted without actually deleting.
|
||||
*
|
||||
* @param entityId Entity ID (or '*' for all entities - NOT IMPLEMENTED YET)
|
||||
* @param options Prune options
|
||||
* @returns Count of deleted and kept versions
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // Keep last 10 versions, delete rest
|
||||
* const result = await brain.versions.prune('user-123', {
|
||||
* keepRecent: 10
|
||||
* })
|
||||
* console.log(`Deleted ${result.deleted} versions`)
|
||||
*
|
||||
* // Keep last 30 days, preserve tagged versions
|
||||
* const result = await brain.versions.prune('user-123', {
|
||||
* keepAfter: Date.now() - 30 * 24 * 60 * 60 * 1000,
|
||||
* keepTagged: true
|
||||
* })
|
||||
*
|
||||
* // Dry run - see what would be deleted
|
||||
* const result = await brain.versions.prune('user-123', {
|
||||
* keepRecent: 5,
|
||||
* dryRun: true
|
||||
* })
|
||||
* console.log(`Would delete ${result.deleted} versions`)
|
||||
* ```
|
||||
*/
|
||||
async prune(
|
||||
entityId: string,
|
||||
options: PruneOptions
|
||||
): Promise<{ deleted: number; kept: number }> {
|
||||
return this.manager.prune(entityId, options)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get version count for an entity
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @returns Number of versions
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const count = await brain.versions.count('user-123')
|
||||
* console.log(`Entity has ${count} versions`)
|
||||
* ```
|
||||
*/
|
||||
async count(entityId: string): Promise<number> {
|
||||
return this.manager.getVersionCount(entityId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if entity has any versions
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @returns True if entity has versions
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* if (await brain.versions.hasVersions('user-123')) {
|
||||
* console.log('Entity is versioned')
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
async hasVersions(entityId: string): Promise<boolean> {
|
||||
return this.manager.hasVersions(entityId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all versions for an entity
|
||||
*
|
||||
* WARNING: This permanently deletes all version history!
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @returns Number of versions deleted
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const deleted = await brain.versions.clear('user-123')
|
||||
* console.log(`Deleted ${deleted} versions`)
|
||||
* ```
|
||||
*/
|
||||
async clear(entityId: string): Promise<number> {
|
||||
return this.manager.clear(entityId)
|
||||
}
|
||||
|
||||
// ===== CONVENIENCE METHODS =====
|
||||
|
||||
/**
|
||||
* Quick save with auto-generated tag
|
||||
*
|
||||
* Generates tag in format: 'auto-{timestamp}'
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @param description Optional description
|
||||
* @returns Created version
|
||||
*/
|
||||
async quickSave(
|
||||
entityId: string,
|
||||
description?: string
|
||||
): Promise<EntityVersion> {
|
||||
return this.save(entityId, {
|
||||
tag: `auto-${Date.now()}`,
|
||||
description
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Undo last change (restore to previous version)
|
||||
*
|
||||
* Safely restores to previous version with automatic snapshot.
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @returns Restored version metadata
|
||||
*/
|
||||
async undo(entityId: string): Promise<EntityVersion | null> {
|
||||
const versions = await this.list(entityId, { limit: 2 })
|
||||
|
||||
if (versions.length < 2) {
|
||||
// No previous version to restore to
|
||||
return null
|
||||
}
|
||||
|
||||
const previousVersion = versions[1] // Second most recent
|
||||
|
||||
return this.restore(entityId, previousVersion.version, {
|
||||
createSnapshot: true,
|
||||
snapshotTag: 'before-undo'
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Get version history summary
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @returns Summary statistics
|
||||
*/
|
||||
async history(entityId: string): Promise<{
|
||||
total: number
|
||||
oldest?: EntityVersion
|
||||
newest?: EntityVersion
|
||||
tagged: number
|
||||
branches: string[]
|
||||
}> {
|
||||
const versions = await this.list(entityId)
|
||||
|
||||
const tagged = versions.filter((v) => v.tag !== undefined).length
|
||||
const branches = [...new Set(versions.map((v) => v.branch))]
|
||||
|
||||
return {
|
||||
total: versions.length,
|
||||
oldest: versions[versions.length - 1],
|
||||
newest: versions[0],
|
||||
tagged,
|
||||
branches
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Revert to previous version (alias for undo with better semantics)
|
||||
*
|
||||
* Restores entity to the previous version with automatic safety snapshot.
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @returns Restored version or null if not possible
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // Made a mistake? Revert!
|
||||
* await brain.update('user-123', { name: 'Wrong Name' })
|
||||
* await brain.versions.revert('user-123') // Back to previous state
|
||||
* ```
|
||||
*/
|
||||
async revert(entityId: string): Promise<EntityVersion | null> {
|
||||
return this.undo(entityId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Tag an existing version
|
||||
*
|
||||
* Updates the tag of an existing version.
|
||||
* Note: This creates a new version with the tag, not modifying the existing one.
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @param version Version number
|
||||
* @param tag New tag
|
||||
* @returns Updated version
|
||||
*/
|
||||
async tag(
|
||||
entityId: string,
|
||||
version: number,
|
||||
tag: string
|
||||
): Promise<EntityVersion> {
|
||||
// Get the version
|
||||
const existingVersion = await this.getVersion(entityId, version)
|
||||
if (!existingVersion) {
|
||||
throw new Error(`Version ${version} not found for entity ${entityId}`)
|
||||
}
|
||||
|
||||
// Create new version with tag
|
||||
// Note: This is a limitation - we can't modify existing versions
|
||||
// because they're immutable. Instead, we create a new version.
|
||||
return this.save(entityId, {
|
||||
tag,
|
||||
description: `Tagged version ${version} as ${tag}`,
|
||||
metadata: { originalVersion: version }
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Get diff between entity's current state and a version
|
||||
*
|
||||
* @param entityId Entity ID
|
||||
* @param version Version to compare against
|
||||
* @returns Diff showing changes
|
||||
*/
|
||||
async diffWithCurrent(
|
||||
entityId: string,
|
||||
version: number | string
|
||||
): Promise<VersionDiff> {
|
||||
// Save current state (will be deduplicated if unchanged)
|
||||
const currentVersion = await this.save(entityId, {
|
||||
tag: 'temp-compare',
|
||||
description: 'Temporary version for comparison'
|
||||
})
|
||||
|
||||
// Compare
|
||||
return this.compare(entityId, version, currentVersion.version)
|
||||
}
|
||||
}
|
||||
|
|
@ -104,8 +104,11 @@ export class VirtualFileSystem implements IVirtualFileSystem {
|
|||
private get blobStorage() {
|
||||
// TypeScript doesn't know about blobStorage on storage, use type assertion
|
||||
const storage = this.brain['storage'] as any
|
||||
if (!storage || !('blobStorage' in storage)) {
|
||||
throw new Error('BlobStorage not available. Requires COW-enabled storage adapter.')
|
||||
if (!storage?.blobStorage) {
|
||||
throw new Error(
|
||||
'BlobStorage not available. The storage adapter must run ' +
|
||||
'initializeBlobStorage() before the VFS is used (brain.init() does this).'
|
||||
)
|
||||
}
|
||||
return storage.blobStorage
|
||||
}
|
||||
|
|
@ -437,9 +440,13 @@ export class VirtualFileSystem implements IVirtualFileSystem {
|
|||
existingId = null
|
||||
}
|
||||
|
||||
// Detect MIME type BEFORE the blob write so the store's auto-compression
|
||||
// policy can skip zstd for already-compressed media (JPEG, MP4, ZIP, …).
|
||||
const mimeType = mimeDetector.detectMimeType(name, buffer)
|
||||
|
||||
// Unified blob storage for ALL files (no size-based branching)
|
||||
// Store in BlobStorage (content-addressable, auto-deduplication, streaming)
|
||||
const blobHash = await this.blobStorage.write(buffer)
|
||||
// Store in BlobStorage (content-addressable, auto-deduplication)
|
||||
const blobHash = await this.blobStorage.write(buffer, { mimeType })
|
||||
|
||||
// Get blob metadata (size, compression info)
|
||||
const blobMetadata = await this.blobStorage.getMetadata(blobHash)
|
||||
|
|
@ -448,12 +455,9 @@ export class VirtualFileSystem implements IVirtualFileSystem {
|
|||
type: 'blob',
|
||||
hash: blobHash,
|
||||
size: buffer.length,
|
||||
compressed: blobMetadata?.compressed
|
||||
compressed: blobMetadata ? blobMetadata.compression !== 'none' : undefined
|
||||
}
|
||||
|
||||
// Detect MIME type (using comprehensive MimeTypeDetector)
|
||||
const mimeType = mimeDetector.detectMimeType(name, buffer)
|
||||
|
||||
// Create metadata
|
||||
const metadata: VFSMetadata = {
|
||||
path,
|
||||
|
|
@ -2716,11 +2720,6 @@ export class VirtualFileSystem implements IVirtualFileSystem {
|
|||
return results
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all versions of a file (semantic versioning)
|
||||
*/
|
||||
|
||||
|
||||
createReadStream(path: string, options?: ReadStreamOptions): NodeJS.ReadableStream {
|
||||
// Lazy import to avoid circular dependencies
|
||||
const { VFSReadStream } = require('./streams/VFSReadStream.js')
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue