feat: add entity versioning system with critical bug fixes (v5.3.0)

Entity Versioning (NEW):
- Add complete entity versioning API (brain.versions.*) with 18 methods
- Content-addressable storage with SHA-256 deduplication
- Git-style version control: save, restore, compare, undo, prune
- Auto-versioning augmentation with pattern-based filtering
- Branch-isolated version histories
- Complete integration tests and API documentation

Critical Bug Fixes:
- Fix commit() not updating branch refs (brainy.ts:2385)
  - Root cause: Passed "heads/main" which normalized to "refs/heads/heads/main"
  - Impact: All Git-style versioning features were broken
  - Fix: Pass branch name directly for correct normalization
- Fix VFS entities missing isVFSEntity flag
  - Add isVFSEntity: true to all VFS files/folders for filtering
  - Resolves pollution of semantic search with filesystem entities
  - Updated in writeFile(), mkdir(), and root directory init

Implementation:
- src/versioning/VersionManager.ts - Core versioning engine
- src/versioning/VersionStorage.ts - Content-addressable storage
- src/versioning/VersionIndex.ts - Metadata indexing
- src/versioning/VersionDiff.ts - Version comparison
- src/versioning/VersioningAPI.ts - Public API interface
- src/augmentations/versioningAugmentation.ts - Auto-versioning
- tests/integration/versioning.test.ts - Full integration tests
- tests/unit/versioning/ - Unit test suite

Documentation:
- Complete Entity Versioning API section in docs/api/README.md
- VFS entity filtering guide with examples
- Updated "What's New" section for v5.3.0
- Strategy docs for both critical bugs

Test Results:
- 1168 tests passing
- Build: PASSING (no TypeScript errors)
- Integration tests: ALL PASSING

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
David Snelling 2025-11-04 11:19:02 -08:00
parent b31997b1ea
commit c488fa82cc
16 changed files with 5394 additions and 9 deletions

View file

@ -0,0 +1,104 @@
/**
* Integration test to reproduce commit() ref update bug
* Bug: commit() creates blobs but doesn't update branch refs
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { Brainy } from '../../src/brainy.js'
import * as fs from 'fs'
import * as path from 'path'
import * as zlib from 'zlib'
const TEST_DATA_PATH = './test-commit-ref-bug-data'
describe('Commit Ref Update Bug (v5.2.0)', () => {
let brain: Brainy
beforeEach(async () => {
// Clean up test data
if (fs.existsSync(TEST_DATA_PATH)) {
fs.rmSync(TEST_DATA_PATH, { recursive: true, force: true })
}
brain = new Brainy({
storage: {
type: 'filesystem',
path: TEST_DATA_PATH,
branch: 'main',
enableCompression: true
},
silent: false // Enable logging
})
await brain.init()
})
afterEach(() => {
if (fs.existsSync(TEST_DATA_PATH)) {
fs.rmSync(TEST_DATA_PATH, { recursive: true, force: true })
}
})
it('should update branch ref after commit', async () => {
// Add an entity
await brain.add({
data: 'Test entity',
type: 'concept',
metadata: { test: true }
})
// Create first commit
const commit1Hash = await brain.commit({
message: 'First commit',
author: 'test@example.com'
})
console.log(`\n=== Commit 1 created: ${commit1Hash} ===`)
// Check the ref file directly
const refPath = path.join(TEST_DATA_PATH, '_cow', 'ref:refs', 'heads', 'main.gz')
expect(fs.existsSync(refPath), 'Ref file should exist').toBe(true)
const refContent1 = JSON.parse(
zlib.gunzipSync(fs.readFileSync(refPath)).toString()
)
console.log('Ref after commit 1:', {
commitHash: refContent1.commitHash,
updatedAt: new Date(refContent1.updatedAt).toISOString()
})
// THIS IS THE BUG: commitHash should equal commit1Hash
expect(refContent1.commitHash).toBe(commit1Hash)
expect(refContent1.commitHash).not.toBe('0'.repeat(64))
// Add another entity
await brain.add({
data: 'Second entity',
type: 'concept'
})
// Create second commit
const commit2Hash = await brain.commit({
message: 'Second commit',
author: 'test@example.com'
})
console.log(`\n=== Commit 2 created: ${commit2Hash} ===`)
// Check ref again
const refContent2 = JSON.parse(
zlib.gunzipSync(fs.readFileSync(refPath)).toString()
)
console.log('Ref after commit 2:', {
commitHash: refContent2.commitHash,
updatedAt: new Date(refContent2.updatedAt).toISOString()
})
// THIS IS THE BUG: commitHash should equal commit2Hash
expect(refContent2.commitHash).toBe(commit2Hash)
expect(refContent2.updatedAt).toBeGreaterThan(refContent1.updatedAt)
})
})

View file

@ -0,0 +1,409 @@
/**
* Entity Versioning Integration Tests (v5.3.0)
*
* Tests the complete versioning workflow:
* - Save versions
* - List versions
* - Restore versions
* - Compare versions
* - Prune versions
* - Auto-versioning augmentation
*/
import { describe, it, expect, beforeEach } from 'vitest'
import { Brainy } from '../../src/brainy.js'
import type { EntityVersion } from '../../src/versioning/VersionManager.js'
import { VersioningAugmentation } from '../../src/augmentations/versioningAugmentation.js'
describe('Entity Versioning (v5.3.0)', () => {
let brain: Brainy
beforeEach(async () => {
brain = new Brainy({
storage: { type: 'memory' },
silent: true
})
await brain.init()
})
describe('Core Versioning API', () => {
it('should save and retrieve versions', async () => {
// Add initial entity
await brain.add({
data: 'Alice',
id: 'user-123',
type: 'user',
metadata: {
name: 'Alice',
email: 'alice@example.com'
}
})
// Save version 1
const v1 = await brain.versions.save('user-123', {
tag: 'v1.0',
description: 'Initial version'
})
expect(v1.version).toBe(1)
expect(v1.entityId).toBe('user-123')
expect(v1.tag).toBe('v1.0')
expect(v1.contentHash).toBeDefined()
// Update entity
await brain.update('user-123', { name: 'Alice Smith' })
// Save version 2
const v2 = await brain.versions.save('user-123', {
tag: 'v2.0',
description: 'Updated name'
})
expect(v2.version).toBe(2)
expect(v2.entityId).toBe('user-123')
// List versions
const versions = await brain.versions.list('user-123')
expect(versions).toHaveLength(2)
expect(versions[0].version).toBe(2) // Newest first
expect(versions[1].version).toBe(1)
})
it('should deduplicate identical content', async () => {
await brain.add({
data: 'Doc',
id: 'doc-1',
type: 'document',
metadata: {
name: 'Doc',
content: 'Hello'
}
})
// Save version 1
const v1 = await brain.versions.save('doc-1', { tag: 'v1' })
// Save again without changes
const v2 = await brain.versions.save('doc-1', { tag: 'v2' })
// Should return existing version (same content hash)
expect(v2.version).toBe(v1.version)
expect(v2.contentHash).toBe(v1.contentHash)
// Only one version should exist
const versions = await brain.versions.list('doc-1')
expect(versions).toHaveLength(1)
})
it('should restore to previous version', async () => {
await brain.add({
data: 'Config',
id: 'config-1',
type: 'thing',
metadata: {
name: 'Config',
settings: { theme: 'light' }
}
})
// Save v1
await brain.versions.save('config-1', { tag: 'v1' })
// Update
await brain.update('config-1', { settings: { theme: 'dark' } })
// Save v2
await brain.versions.save('config-1', { tag: 'v2' })
// Verify current state
let current = await brain.getNounMetadata('config-1')
expect(current?.metadata?.settings?.theme).toBe('dark')
// Restore to v1
await brain.versions.restore('config-1', 1)
// Verify restored state
current = await brain.getNounMetadata('config-1')
expect(current?.metadata?.settings?.theme).toBe('light')
})
it('should compare versions', async () => {
await brain.add({
data: 'Bob',
id: 'user-456',
type: 'user',
metadata: {
name: 'Bob',
email: 'bob@example.com',
age: 30
}
})
await brain.versions.save('user-456', { tag: 'v1' })
// Update
await brain.update('user-456', {
name: 'Robert',
email: 'robert@example.com',
city: 'NYC'
})
await brain.versions.save('user-456', { tag: 'v2' })
// Compare versions
const diff = await brain.versions.compare('user-456', 1, 2)
expect(diff.totalChanges).toBeGreaterThan(0)
expect(diff.modified.length).toBeGreaterThan(0)
expect(diff.added.length).toBeGreaterThan(0)
// Check specific changes
const nameChange = diff.modified.find(c => c.path.includes('name'))
expect(nameChange).toBeDefined()
expect(nameChange?.oldValue).toBe('Bob')
expect(nameChange?.newValue).toBe('Robert')
const cityAdd = diff.added.find(c => c.path.includes('city'))
expect(cityAdd).toBeDefined()
expect(cityAdd?.newValue).toBe('NYC')
})
it('should get version content without restoring', async () => {
await brain.add({
data: 'Note',
id: 'note-1',
type: 'document',
metadata: {
name: 'Note',
content: 'Version 1'
}
})
await brain.versions.save('note-1', { tag: 'v1' })
await brain.update('note-1', { content: 'Version 2' })
await brain.versions.save('note-1', { tag: 'v2' })
// Get v1 content without restoring
const v1Content = await brain.versions.getContent('note-1', 1)
expect(v1Content.metadata.content).toBe('Version 1')
// Current should still be v2
const current = await brain.getNounMetadata('note-1')
expect(current?.metadata?.content).toBe('Version 2')
})
it('should prune old versions', async () => {
await brain.add({
data: 'Log',
id: 'log-1',
type: 'document',
metadata: {
name: 'Log'
}
})
// Create 10 versions
for (let i = 1; i <= 10; i++) {
await brain.update('log-1', { content: `Entry ${i}` })
await brain.versions.save('log-1', { tag: `v${i}` })
}
// Verify all 10 exist
let versions = await brain.versions.list('log-1')
expect(versions.length).toBeGreaterThanOrEqual(10)
// Prune to keep only 5 most recent
const result = await brain.versions.prune('log-1', {
keepRecent: 5,
keepTagged: false
})
expect(result.deleted).toBeGreaterThan(0)
expect(result.kept).toBe(5)
// Verify only 5 remain
versions = await brain.versions.list('log-1')
expect(versions).toHaveLength(5)
})
it('should support version tags', async () => {
await brain.add({
data: 'App',
id: 'app-1',
type: 'thing',
metadata: {
name: 'App'
}
})
await brain.versions.save('app-1', { tag: 'alpha' })
await brain.update('app-1', { version: '0.2' })
await brain.versions.save('app-1', { tag: 'beta' })
await brain.update('app-1', { version: '1.0' })
await brain.versions.save('app-1', { tag: 'release' })
// Get by tag
const beta = await brain.versions.getVersionByTag('app-1', 'beta')
expect(beta).toBeDefined()
expect(beta?.tag).toBe('beta')
// Restore by tag
await brain.versions.restore('app-1', 'beta')
const current = await brain.getNounMetadata('app-1')
expect(current?.metadata?.version).toBe('0.2')
})
it('should support undo/revert', async () => {
await brain.add({
data: 'Data',
id: 'data-1',
type: 'thing',
metadata: {
name: 'Data',
value: 100
}
})
await brain.versions.save('data-1')
await brain.update('data-1', { value: 200 })
await brain.versions.save('data-1')
// Make a bad change
await brain.update('data-1', { value: 999 })
// Undo (reverts to previous version)
await brain.versions.undo('data-1')
const current = await brain.getNounMetadata('data-1')
expect(current?.metadata?.value).toBe(200)
// Revert (alias for undo)
await brain.update('data-1', { value: 999 })
await brain.versions.revert('data-1')
const reverted = await brain.getNounMetadata('data-1')
expect(reverted?.metadata?.value).toBe(200)
})
})
describe('Auto-Versioning Augmentation', () => {
it('should auto-version on update when enabled', async () => {
// Add augmentation
const augmentation = new VersioningAugmentation({
enabled: true,
onUpdate: true,
entities: ['*'],
keepRecent: 10
})
brain.augment(augmentation as any)
await brain.add({
data: 'Auto User',
id: 'auto-1',
type: 'user',
metadata: {
name: 'Auto User'
}
})
// No versions yet
expect(await brain.versions.count('auto-1')).toBe(0)
// Update should auto-create version
await brain.update('auto-1', { name: 'Auto User Updated' })
// Give augmentation time to process
await new Promise(resolve => setTimeout(resolve, 100))
// Should have auto-created version
const count = await brain.versions.count('auto-1')
expect(count).toBeGreaterThan(0)
})
it('should filter entities by ID pattern', async () => {
const augmentation = new VersioningAugmentation({
enabled: true,
onUpdate: true,
entities: ['versioned-*'],
excludeEntities: ['temp-*']
})
brain.augment(augmentation as any)
// This should be versioned
await brain.add({ data: 'V1', id: 'versioned-1', type: 'thing', metadata: { name: 'V1' } })
await brain.update('versioned-1', { name: 'V1 Updated' })
await new Promise(resolve => setTimeout(resolve, 100))
// This should NOT be versioned
await brain.add({ data: 'O1', id: 'other-1', type: 'thing', metadata: { name: 'O1' } })
await brain.update('other-1', { name: 'O1 Updated' })
await new Promise(resolve => setTimeout(resolve, 100))
expect(await brain.versions.count('versioned-1')).toBeGreaterThan(0)
expect(await brain.versions.count('other-1')).toBe(0)
})
})
describe('Branch Isolation', () => {
it('should isolate versions by branch', async () => {
await brain.add({
data: 'Test',
id: 'branch-test',
type: 'thing',
metadata: {
name: 'Test'
}
})
// Save on main
await brain.versions.save('branch-test', { tag: 'main-v1' })
// Switch to feature branch
await brain.fork('feature')
// Update on feature
await brain.update('branch-test', { name: 'Feature Update' })
await brain.versions.save('branch-test', { tag: 'feature-v1' })
// Versions on feature branch
const featureVersions = await brain.versions.list('branch-test')
expect(featureVersions.length).toBeGreaterThan(0)
// Switch back to main
await brain.checkout('main')
// Versions on main branch
const mainVersions = await brain.versions.list('branch-test')
// Should be isolated
expect(mainVersions.length).not.toBe(featureVersions.length)
})
})
describe('Edge Cases', () => {
it('should handle non-existent entities gracefully', async () => {
await expect(
brain.versions.save('nonexistent', { tag: 'v1' })
).rejects.toThrow('Entity nonexistent not found')
})
it('should handle empty version history', async () => {
await brain.add({ data: 'New', id: 'new-1', type: 'thing', metadata: { name: 'New' } })
expect(await brain.versions.count('new-1')).toBe(0)
expect(await brain.versions.hasVersions('new-1')).toBe(false)
expect(await brain.versions.getLatest('new-1')).toBeNull()
})
it('should handle version not found', async () => {
await brain.add({ data: 'Test', id: 'test-1', type: 'thing', metadata: { name: 'Test' } })
await expect(
brain.versions.restore('test-1', 999)
).rejects.toThrow('Version 999 not found')
})
})
})

View file

@ -0,0 +1,538 @@
/**
* VersionDiff Unit Tests (v5.3.0)
*
* Tests deep object comparison:
* - Added fields
* - Removed fields
* - Modified fields
* - Type changes
* - Nested object comparison
* - Array comparison
*/
import { describe, it, expect } from 'vitest'
import { compareEntityVersions } from '../../../src/versioning/VersionDiff.js'
import type { NounMetadata } from '../../../src/coreTypes.js'
describe('VersionDiff', () => {
describe('compareEntityVersions()', () => {
it('should detect added fields', () => {
const from: NounMetadata = {
id: 'user-1',
type: 'user',
name: 'Alice',
metadata: { email: 'alice@example.com' }
}
const to: NounMetadata = {
id: 'user-1',
type: 'user',
name: 'Alice',
metadata: {
email: 'alice@example.com',
city: 'NYC',
age: 30
}
}
const diff = compareEntityVersions(from, to, {
entityId: 'user-1',
fromVersion: 1,
toVersion: 2
})
expect(diff.added.length).toBe(2)
expect(diff.added.some(c => c.path.includes('city'))).toBe(true)
expect(diff.added.some(c => c.path.includes('age'))).toBe(true)
expect(diff.added.find(c => c.path.includes('city'))?.newValue).toBe('NYC')
})
it('should detect removed fields', () => {
const from: NounMetadata = {
id: 'user-1',
type: 'user',
name: 'Alice',
metadata: {
email: 'alice@example.com',
city: 'NYC',
age: 30
}
}
const to: NounMetadata = {
id: 'user-1',
type: 'user',
name: 'Alice',
metadata: { email: 'alice@example.com' }
}
const diff = compareEntityVersions(from, to, {
entityId: 'user-1',
fromVersion: 1,
toVersion: 2
})
expect(diff.removed.length).toBe(2)
expect(diff.removed.some(c => c.path.includes('city'))).toBe(true)
expect(diff.removed.some(c => c.path.includes('age'))).toBe(true)
expect(diff.removed.find(c => c.path.includes('city'))?.oldValue).toBe('NYC')
})
it('should detect modified fields', () => {
const from: NounMetadata = {
id: 'user-1',
type: 'user',
name: 'Alice',
metadata: {
email: 'alice@example.com',
status: 'active'
}
}
const to: NounMetadata = {
id: 'user-1',
type: 'user',
name: 'Alice Smith',
metadata: {
email: 'alice.smith@example.com',
status: 'active'
}
}
const diff = compareEntityVersions(from, to, {
entityId: 'user-1',
fromVersion: 1,
toVersion: 2
})
expect(diff.modified.length).toBe(2)
const nameChange = diff.modified.find(c => c.path.includes('name'))
expect(nameChange?.oldValue).toBe('Alice')
expect(nameChange?.newValue).toBe('Alice Smith')
const emailChange = diff.modified.find(c => c.path.includes('email'))
expect(emailChange?.oldValue).toBe('alice@example.com')
expect(emailChange?.newValue).toBe('alice.smith@example.com')
})
it('should detect type changes', () => {
const from: NounMetadata = {
id: 'config-1',
type: 'thing',
name: 'Config',
metadata: { value: '100' }
}
const to: NounMetadata = {
id: 'config-1',
type: 'thing',
name: 'Config',
metadata: { value: 100 }
}
const diff = compareEntityVersions(from, to, {
entityId: 'config-1',
fromVersion: 1,
toVersion: 2
})
expect(diff.typeChanged.length).toBe(1)
const typeChange = diff.typeChanged[0]
expect(typeChange.path).toContain('value')
expect(typeChange.oldType).toBe('string')
expect(typeChange.newType).toBe('number')
expect(typeChange.oldValue).toBe('100')
expect(typeChange.newValue).toBe(100)
})
it('should detect identical versions', () => {
const entity: NounMetadata = {
id: 'doc-1',
type: 'document',
name: 'Doc',
metadata: { content: 'Unchanged' }
}
const diff = compareEntityVersions(entity, entity, {
entityId: 'doc-1',
fromVersion: 1,
toVersion: 2
})
expect(diff.identical).toBe(true)
expect(diff.totalChanges).toBe(0)
expect(diff.added).toHaveLength(0)
expect(diff.removed).toHaveLength(0)
expect(diff.modified).toHaveLength(0)
})
it('should handle nested object changes', () => {
const from: NounMetadata = {
id: 'user-1',
type: 'user',
name: 'Alice',
metadata: {
address: {
street: '123 Main St',
city: 'NYC'
}
}
}
const to: NounMetadata = {
id: 'user-1',
type: 'user',
name: 'Alice',
metadata: {
address: {
street: '456 Oak Ave',
city: 'NYC',
zip: '10001'
}
}
}
const diff = compareEntityVersions(from, to, {
entityId: 'user-1',
fromVersion: 1,
toVersion: 2
})
expect(diff.modified.some(c => c.path.includes('address.street'))).toBe(true)
expect(diff.added.some(c => c.path.includes('address.zip'))).toBe(true)
const streetChange = diff.modified.find(c => c.path.includes('address.street'))
expect(streetChange?.oldValue).toBe('123 Main St')
expect(streetChange?.newValue).toBe('456 Oak Ave')
})
it('should handle array changes', () => {
const from: NounMetadata = {
id: 'doc-1',
type: 'document',
name: 'Doc',
metadata: {
tags: ['a', 'b', 'c']
}
}
const to: NounMetadata = {
id: 'doc-1',
type: 'document',
name: 'Doc',
metadata: {
tags: ['a', 'b', 'd']
}
}
const diff = compareEntityVersions(from, to, {
entityId: 'doc-1',
fromVersion: 1,
toVersion: 2
})
// Array element change detected as modification
expect(diff.totalChanges).toBeGreaterThan(0)
})
it('should handle null and undefined', () => {
const from: NounMetadata = {
id: 'test-1',
type: 'thing',
name: 'Test',
metadata: {
a: null,
b: undefined,
c: 'value'
}
}
const to: NounMetadata = {
id: 'test-1',
type: 'thing',
name: 'Test',
metadata: {
a: 'now-value',
b: null,
c: 'value'
}
}
const diff = compareEntityVersions(from, to, {
entityId: 'test-1',
fromVersion: 1,
toVersion: 2
})
expect(diff.totalChanges).toBeGreaterThan(0)
})
it('should ignore specified fields', () => {
const from: NounMetadata = {
id: 'user-1',
type: 'user',
name: 'Alice',
metadata: {
email: 'alice@example.com',
lastModified: 1000,
internal: 'ignore-me'
}
}
const to: NounMetadata = {
id: 'user-1',
type: 'user',
name: 'Alice Smith',
metadata: {
email: 'alice@example.com',
lastModified: 2000,
internal: 'changed'
}
}
const diff = compareEntityVersions(from, to, {
entityId: 'user-1',
fromVersion: 1,
toVersion: 2,
ignoreFields: ['lastModified', 'internal']
})
// Should only detect name change
expect(diff.totalChanges).toBe(1)
expect(diff.modified.some(c => c.path.includes('name'))).toBe(true)
expect(diff.modified.some(c => c.path.includes('lastModified'))).toBe(false)
expect(diff.modified.some(c => c.path.includes('internal'))).toBe(false)
})
it('should respect maxDepth option', () => {
const from: NounMetadata = {
id: 'test-1',
type: 'thing',
name: 'Test',
metadata: {
level1: {
level2: {
level3: {
level4: 'deep-value'
}
}
}
}
}
const to: NounMetadata = {
id: 'test-1',
type: 'thing',
name: 'Test',
metadata: {
level1: {
level2: {
level3: {
level4: 'changed-value'
}
}
}
}
}
const diff = compareEntityVersions(from, to, {
entityId: 'test-1',
fromVersion: 1,
toVersion: 2,
maxDepth: 2 // Stop at level2
})
// Should detect change at metadata.level1.level2 level
expect(diff.totalChanges).toBeGreaterThan(0)
})
it('should handle empty objects', () => {
const from: NounMetadata = {
id: 'test-1',
type: 'thing',
name: 'Test',
metadata: {}
}
const to: NounMetadata = {
id: 'test-1',
type: 'thing',
name: 'Test',
metadata: { value: 123 }
}
const diff = compareEntityVersions(from, to, {
entityId: 'test-1',
fromVersion: 1,
toVersion: 2
})
expect(diff.added.length).toBe(1)
expect(diff.added[0].newValue).toBe(123)
})
it('should calculate total changes correctly', () => {
const from: NounMetadata = {
id: 'user-1',
type: 'user',
name: 'Alice',
metadata: {
email: 'alice@example.com',
status: 'active',
age: 30
}
}
const to: NounMetadata = {
id: 'user-1',
type: 'user',
name: 'Alice Smith',
metadata: {
email: 'alice.smith@example.com',
city: 'NYC'
}
}
const diff = compareEntityVersions(from, to, {
entityId: 'user-1',
fromVersion: 1,
toVersion: 2
})
const expectedTotal =
diff.added.length +
diff.removed.length +
diff.modified.length +
diff.typeChanged.length
expect(diff.totalChanges).toBe(expectedTotal)
})
it('should handle complex real-world changes', () => {
const from: NounMetadata = {
id: 'project-1',
type: 'thing',
name: 'My Project',
metadata: {
description: 'Old description',
status: 'draft',
team: ['alice', 'bob'],
config: {
theme: 'light',
notifications: true
},
createdAt: 1000
}
}
const to: NounMetadata = {
id: 'project-1',
type: 'thing',
name: 'My Awesome Project',
metadata: {
description: 'New description',
status: 'active',
team: ['alice', 'bob', 'charlie'],
config: {
theme: 'dark',
notifications: true,
language: 'en'
},
createdAt: 1000,
updatedAt: 2000
}
}
const diff = compareEntityVersions(from, to, {
entityId: 'project-1',
fromVersion: 1,
toVersion: 2
})
expect(diff.totalChanges).toBeGreaterThan(0)
expect(diff.modified.length).toBeGreaterThan(0)
expect(diff.added.length).toBeGreaterThan(0)
const nameChange = diff.modified.find(c => c.path.includes('name'))
expect(nameChange?.newValue).toBe('My Awesome Project')
})
it('should handle boolean changes', () => {
const from: NounMetadata = {
id: 'feature-1',
type: 'thing',
name: 'Feature',
metadata: { enabled: false }
}
const to: NounMetadata = {
id: 'feature-1',
type: 'thing',
name: 'Feature',
metadata: { enabled: true }
}
const diff = compareEntityVersions(from, to, {
entityId: 'feature-1',
fromVersion: 1,
toVersion: 2
})
expect(diff.modified.length).toBe(1)
expect(diff.modified[0].oldValue).toBe(false)
expect(diff.modified[0].newValue).toBe(true)
})
it('should handle number changes', () => {
const from: NounMetadata = {
id: 'counter-1',
type: 'thing',
name: 'Counter',
metadata: { count: 10 }
}
const to: NounMetadata = {
id: 'counter-1',
type: 'thing',
name: 'Counter',
metadata: { count: 20 }
}
const diff = compareEntityVersions(from, to, {
entityId: 'counter-1',
fromVersion: 1,
toVersion: 2
})
expect(diff.modified.length).toBe(1)
expect(diff.modified[0].oldValue).toBe(10)
expect(diff.modified[0].newValue).toBe(20)
})
it('should handle date/timestamp changes', () => {
const from: NounMetadata = {
id: 'event-1',
type: 'thing',
name: 'Event',
metadata: { timestamp: 1000 }
}
const to: NounMetadata = {
id: 'event-1',
type: 'thing',
name: 'Event',
metadata: { timestamp: 2000 }
}
const diff = compareEntityVersions(from, to, {
entityId: 'event-1',
fromVersion: 1,
toVersion: 2
})
expect(diff.modified.length).toBe(1)
expect(diff.modified[0].path).toContain('timestamp')
})
})
})

View file

@ -0,0 +1,654 @@
/**
* VersionManager Unit Tests (v5.3.0)
*
* Tests the core versioning engine in isolation:
* - Save versions
* - Restore versions
* - List versions
* - Compare versions
* - Prune versions
* - Content deduplication
* - Branch awareness
*/
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { VersionManager } from '../../../src/versioning/VersionManager.js'
import type { NounMetadata } from '../../../src/coreTypes.js'
describe('VersionManager', () => {
let manager: VersionManager
let mockBrain: any
let mockStorage: Map<string, any>
let mockIndex: Map<string, any>
beforeEach(() => {
// Mock storage
mockStorage = new Map()
mockIndex = new Map()
// Mock Brainy instance
mockBrain = {
currentBranch: 'main',
storageAdapter: {
exists: vi.fn(async (path: string) => mockStorage.has(path)),
writeFile: vi.fn(async (path: string, data: string) => {
mockStorage.set(path, data)
}),
readFile: vi.fn(async (path: string) => {
const data = mockStorage.get(path)
if (!data) throw new Error('File not found')
return data
}),
deleteFile: vi.fn(async (path: string) => {
mockStorage.delete(path)
})
},
refManager: {
getRef: vi.fn(async (branch: string) => ({
name: `refs/heads/${branch}`,
commitHash: 'commit-hash-123',
type: 'branch'
})),
setRef: vi.fn(async () => {}),
resolveRef: vi.fn(async () => 'commit-hash-123')
},
getNounMetadata: vi.fn(async (id: string) => {
const entity = mockIndex.get(id)
if (!entity) throw new Error(`Entity ${id} not found`)
return entity
}),
saveNounMetadata: vi.fn(async (id: string, data: NounMetadata) => {
mockIndex.set(id, data)
}),
searchByMetadata: vi.fn(async (query: any) => {
const results: any[] = []
for (const [id, entity] of mockIndex.entries()) {
let matches = true
for (const [key, value] of Object.entries(query)) {
if (key === 'type' && entity.type !== value) {
matches = false
break
}
if (entity.metadata?.[key] !== value) {
matches = false
break
}
}
if (matches) {
results.push({ id, ...entity })
}
}
return results
}),
commit: vi.fn(async () => 'commit-hash-123')
}
manager = new VersionManager(mockBrain)
})
describe('save()', () => {
it('should save a new version', async () => {
// Add test entity
mockIndex.set('user-123', {
id: 'user-123',
type: 'user',
name: 'Alice',
metadata: { email: 'alice@example.com' }
})
const version = await manager.save('user-123', {
tag: 'v1.0',
description: 'Initial version'
})
expect(version.version).toBe(1)
expect(version.entityId).toBe('user-123')
expect(version.branch).toBe('main')
expect(version.tag).toBe('v1.0')
expect(version.description).toBe('Initial version')
expect(version.contentHash).toBeDefined()
expect(version.commitHash).toBe('commit-hash-123')
})
it('should increment version numbers', async () => {
mockIndex.set('doc-1', {
id: 'doc-1',
type: 'document',
name: 'Doc',
metadata: { content: 'Version 1' }
})
const v1 = await manager.save('doc-1', { tag: 'v1' })
expect(v1.version).toBe(1)
// Update entity
mockIndex.set('doc-1', {
id: 'doc-1',
type: 'document',
name: 'Doc',
metadata: { content: 'Version 2' }
})
const v2 = await manager.save('doc-1', { tag: 'v2' })
expect(v2.version).toBe(2)
mockIndex.set('doc-1', {
id: 'doc-1',
type: 'document',
name: 'Doc',
metadata: { content: 'Version 3' }
})
const v3 = await manager.save('doc-1', { tag: 'v3' })
expect(v3.version).toBe(3)
})
it('should deduplicate identical content', async () => {
mockIndex.set('note-1', {
id: 'note-1',
type: 'document',
name: 'Note',
metadata: { content: 'Unchanged' }
})
const v1 = await manager.save('note-1', { tag: 'v1' })
const v2 = await manager.save('note-1', { tag: 'v2' })
// Should return same version (content unchanged)
expect(v2.version).toBe(v1.version)
expect(v2.contentHash).toBe(v1.contentHash)
})
it('should throw if entity does not exist', async () => {
await expect(
manager.save('nonexistent', { tag: 'v1' })
).rejects.toThrow('Entity nonexistent not found')
})
it('should save without tag or description', async () => {
mockIndex.set('test-1', {
id: 'test-1',
type: 'thing',
name: 'Test',
metadata: {}
})
const version = await manager.save('test-1')
expect(version.version).toBe(1)
expect(version.tag).toBeUndefined()
expect(version.description).toBeUndefined()
})
})
describe('restore()', () => {
it('should restore entity to specific version', async () => {
// Save version 1
mockIndex.set('config-1', {
id: 'config-1',
type: 'thing',
name: 'Config',
metadata: { theme: 'light', version: 1 }
})
await manager.save('config-1', { tag: 'v1' })
// Update to version 2
mockIndex.set('config-1', {
id: 'config-1',
type: 'thing',
name: 'Config',
metadata: { theme: 'dark', version: 2 }
})
await manager.save('config-1', { tag: 'v2' })
// Restore to v1
await manager.restore('config-1', 1)
// Verify saveNounMetadata was called with v1 data
expect(mockBrain.saveNounMetadata).toHaveBeenCalledWith(
'config-1',
expect.objectContaining({
metadata: expect.objectContaining({ theme: 'light', version: 1 })
})
)
})
it('should restore by tag', async () => {
mockIndex.set('app-1', {
id: 'app-1',
type: 'thing',
name: 'App',
metadata: { status: 'alpha' }
})
await manager.save('app-1', { tag: 'alpha' })
mockIndex.set('app-1', {
id: 'app-1',
type: 'thing',
name: 'App',
metadata: { status: 'beta' }
})
await manager.save('app-1', { tag: 'beta' })
// Restore to alpha
await manager.restore('app-1', 'alpha')
expect(mockBrain.saveNounMetadata).toHaveBeenCalledWith(
'app-1',
expect.objectContaining({
metadata: expect.objectContaining({ status: 'alpha' })
})
)
})
it('should throw if version not found', async () => {
mockIndex.set('test-1', {
id: 'test-1',
type: 'thing',
name: 'Test',
metadata: {}
})
await manager.save('test-1')
await expect(
manager.restore('test-1', 999)
).rejects.toThrow('Version 999 not found')
})
})
describe('list()', () => {
it('should list all versions for entity', async () => {
mockIndex.set('log-1', {
id: 'log-1',
type: 'document',
name: 'Log',
metadata: { entry: 1 }
})
await manager.save('log-1', { tag: 'v1' })
mockIndex.set('log-1', {
id: 'log-1',
type: 'document',
name: 'Log',
metadata: { entry: 2 }
})
await manager.save('log-1', { tag: 'v2' })
mockIndex.set('log-1', {
id: 'log-1',
type: 'document',
name: 'Log',
metadata: { entry: 3 }
})
await manager.save('log-1', { tag: 'v3' })
const versions = await manager.list('log-1')
expect(versions).toHaveLength(3)
expect(versions[0].version).toBe(3) // Newest first
expect(versions[1].version).toBe(2)
expect(versions[2].version).toBe(1)
})
it('should filter by tag pattern', async () => {
mockIndex.set('app-1', {
id: 'app-1',
type: 'thing',
name: 'App',
metadata: { v: 1 }
})
await manager.save('app-1', { tag: 'v1.0.0' })
mockIndex.set('app-1', {
id: 'app-1',
type: 'thing',
name: 'App',
metadata: { v: 2 }
})
await manager.save('app-1', { tag: 'v1.1.0' })
mockIndex.set('app-1', {
id: 'app-1',
type: 'thing',
name: 'App',
metadata: { v: 3 }
})
await manager.save('app-1', { tag: 'v2.0.0' })
const v1Versions = await manager.list('app-1', { tag: 'v1.*' })
expect(v1Versions).toHaveLength(2)
expect(v1Versions[0].tag).toBe('v1.1.0')
expect(v1Versions[1].tag).toBe('v1.0.0')
})
it('should limit results', async () => {
mockIndex.set('data-1', {
id: 'data-1',
type: 'thing',
name: 'Data',
metadata: { v: 1 }
})
for (let i = 1; i <= 5; i++) {
mockIndex.set('data-1', {
id: 'data-1',
type: 'thing',
name: 'Data',
metadata: { v: i }
})
await manager.save('data-1', { tag: `v${i}` })
}
const versions = await manager.list('data-1', { limit: 3 })
expect(versions).toHaveLength(3)
expect(versions[0].version).toBe(5)
expect(versions[1].version).toBe(4)
expect(versions[2].version).toBe(3)
})
it('should return empty array if no versions', async () => {
mockIndex.set('new-1', {
id: 'new-1',
type: 'thing',
name: 'New',
metadata: {}
})
const versions = await manager.list('new-1')
expect(versions).toHaveLength(0)
})
})
describe('compare()', () => {
it('should compare two versions', async () => {
mockIndex.set('user-1', {
id: 'user-1',
type: 'user',
name: 'Bob',
metadata: { email: 'bob@example.com', age: 30 }
})
await manager.save('user-1', { tag: 'v1' })
mockIndex.set('user-1', {
id: 'user-1',
type: 'user',
name: 'Robert',
metadata: { email: 'robert@example.com', age: 30, city: 'NYC' }
})
await manager.save('user-1', { tag: 'v2' })
const diff = await manager.compare('user-1', 1, 2)
expect(diff.totalChanges).toBeGreaterThan(0)
expect(diff.modified.length).toBeGreaterThan(0)
expect(diff.added.length).toBeGreaterThan(0)
const nameChange = diff.modified.find(c => c.path.includes('name'))
expect(nameChange?.oldValue).toBe('Bob')
expect(nameChange?.newValue).toBe('Robert')
const cityAdd = diff.added.find(c => c.path.includes('city'))
expect(cityAdd?.newValue).toBe('NYC')
})
it('should compare by tags', async () => {
mockIndex.set('doc-1', {
id: 'doc-1',
type: 'document',
name: 'Doc',
metadata: { content: 'Alpha' }
})
await manager.save('doc-1', { tag: 'alpha' })
mockIndex.set('doc-1', {
id: 'doc-1',
type: 'document',
name: 'Doc',
metadata: { content: 'Beta' }
})
await manager.save('doc-1', { tag: 'beta' })
const diff = await manager.compare('doc-1', 'alpha', 'beta')
expect(diff.modified.length).toBeGreaterThan(0)
const contentChange = diff.modified.find(c => c.path.includes('content'))
expect(contentChange?.oldValue).toBe('Alpha')
expect(contentChange?.newValue).toBe('Beta')
})
it('should detect identical versions', async () => {
mockIndex.set('same-1', {
id: 'same-1',
type: 'thing',
name: 'Same',
metadata: { value: 100 }
})
await manager.save('same-1', { tag: 'v1' })
await manager.save('same-1', { tag: 'v2' }) // Content unchanged
const diff = await manager.compare('same-1', 1, 1)
expect(diff.identical).toBe(true)
expect(diff.totalChanges).toBe(0)
})
})
describe('prune()', () => {
it('should prune old versions keeping recent', async () => {
mockIndex.set('log-1', {
id: 'log-1',
type: 'document',
name: 'Log',
metadata: { entry: 1 }
})
for (let i = 1; i <= 10; i++) {
mockIndex.set('log-1', {
id: 'log-1',
type: 'document',
name: 'Log',
metadata: { entry: i }
})
await manager.save('log-1', { tag: `v${i}` })
}
const result = await manager.prune('log-1', {
keepRecent: 5,
keepTagged: false
})
expect(result.deleted).toBe(5)
expect(result.kept).toBe(5)
const remaining = await manager.list('log-1')
expect(remaining).toHaveLength(5)
expect(remaining[0].version).toBe(10) // Most recent
})
it('should keep tagged versions', async () => {
mockIndex.set('app-1', {
id: 'app-1',
type: 'thing',
name: 'App',
metadata: { v: 1 }
})
await manager.save('app-1', { tag: 'release' })
for (let i = 2; i <= 10; i++) {
mockIndex.set('app-1', {
id: 'app-1',
type: 'thing',
name: 'App',
metadata: { v: i }
})
await manager.save('app-1') // No tag
}
const result = await manager.prune('app-1', {
keepRecent: 3,
keepTagged: true
})
const remaining = await manager.list('app-1')
const releaseVersion = remaining.find(v => v.tag === 'release')
expect(releaseVersion).toBeDefined()
})
it('should respect keepAfter timestamp', async () => {
mockIndex.set('data-1', {
id: 'data-1',
type: 'thing',
name: 'Data',
metadata: { v: 1 }
})
const now = Date.now()
const oneDayAgo = now - 24 * 60 * 60 * 1000
await manager.save('data-1', { tag: 'old' })
// Simulate newer versions
for (let i = 2; i <= 5; i++) {
mockIndex.set('data-1', {
id: 'data-1',
type: 'thing',
name: 'Data',
metadata: { v: i }
})
await manager.save('data-1', { tag: `new${i}` })
}
const result = await manager.prune('data-1', {
keepAfter: oneDayAgo,
keepTagged: false
})
expect(result.deleted).toBeGreaterThanOrEqual(0)
})
})
describe('getVersion()', () => {
it('should get specific version by number', async () => {
mockIndex.set('test-1', {
id: 'test-1',
type: 'thing',
name: 'Test',
metadata: { v: 1 }
})
const v1 = await manager.save('test-1', { tag: 'v1' })
mockIndex.set('test-1', {
id: 'test-1',
type: 'thing',
name: 'Test',
metadata: { v: 2 }
})
await manager.save('test-1', { tag: 'v2' })
const version = await manager.getVersion('test-1', 1)
expect(version).toBeDefined()
expect(version?.version).toBe(1)
expect(version?.tag).toBe('v1')
})
it('should return null if version not found', async () => {
mockIndex.set('test-1', {
id: 'test-1',
type: 'thing',
name: 'Test',
metadata: {}
})
await manager.save('test-1')
const version = await manager.getVersion('test-1', 999)
expect(version).toBeNull()
})
})
describe('getVersionByTag()', () => {
it('should get version by tag', async () => {
mockIndex.set('app-1', {
id: 'app-1',
type: 'thing',
name: 'App',
metadata: { status: 'alpha' }
})
await manager.save('app-1', { tag: 'alpha' })
mockIndex.set('app-1', {
id: 'app-1',
type: 'thing',
name: 'App',
metadata: { status: 'beta' }
})
await manager.save('app-1', { tag: 'beta' })
const betaVersion = await manager.getVersionByTag('app-1', 'beta')
expect(betaVersion).toBeDefined()
expect(betaVersion?.tag).toBe('beta')
})
it('should return null if tag not found', async () => {
mockIndex.set('test-1', {
id: 'test-1',
type: 'thing',
name: 'Test',
metadata: {}
})
await manager.save('test-1', { tag: 'v1' })
const version = await manager.getVersionByTag('test-1', 'nonexistent')
expect(version).toBeNull()
})
})
describe('getVersionCount()', () => {
it('should count versions', async () => {
mockIndex.set('doc-1', {
id: 'doc-1',
type: 'document',
name: 'Doc',
metadata: { v: 1 }
})
expect(await manager.getVersionCount('doc-1')).toBe(0)
await manager.save('doc-1')
expect(await manager.getVersionCount('doc-1')).toBe(1)
mockIndex.set('doc-1', {
id: 'doc-1',
type: 'document',
name: 'Doc',
metadata: { v: 2 }
})
await manager.save('doc-1')
expect(await manager.getVersionCount('doc-1')).toBe(2)
})
})
describe('Branch Awareness', () => {
it('should track versions per branch', async () => {
mockIndex.set('branch-test', {
id: 'branch-test',
type: 'thing',
name: 'Test',
metadata: {}
})
// Save on main
mockBrain.currentBranch = 'main'
const mainV1 = await manager.save('branch-test', { tag: 'main-v1' })
expect(mainV1.branch).toBe('main')
// Save on feature
mockBrain.currentBranch = 'feature'
const featureV1 = await manager.save('branch-test', { tag: 'feature-v1' })
expect(featureV1.branch).toBe('feature')
// Versions should be independent
expect(mainV1.version).toBe(1)
expect(featureV1.version).toBe(1) // Each branch starts at 1
})
})
})

View file

@ -0,0 +1,548 @@
/**
* VersionStorage Unit Tests (v5.3.0)
*
* Tests content-addressable storage:
* - SHA-256 content hashing
* - Content deduplication
* - Storage adapter integration
* - Save/load/delete operations
*/
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { VersionStorage } from '../../../src/versioning/VersionStorage.js'
import type { NounMetadata } from '../../../src/coreTypes.js'
import type { EntityVersion } from '../../../src/versioning/VersionManager.js'
describe('VersionStorage', () => {
let storage: VersionStorage
let mockBrain: any
let mockFiles: Map<string, string>
beforeEach(() => {
mockFiles = new Map()
mockBrain = {
storageAdapter: {
exists: vi.fn(async (path: string) => mockFiles.has(path)),
writeFile: vi.fn(async (path: string, data: string) => {
mockFiles.set(path, data)
}),
readFile: vi.fn(async (path: string) => {
const data = mockFiles.get(path)
if (!data) throw new Error('File not found')
return data
}),
deleteFile: vi.fn(async (path: string) => {
mockFiles.delete(path)
})
}
}
storage = new VersionStorage(mockBrain)
})
describe('hashEntity()', () => {
it('should generate consistent SHA-256 hashes', () => {
const entity: NounMetadata = {
id: 'user-123',
type: 'user',
name: 'Alice',
metadata: { email: 'alice@example.com' }
}
const hash1 = storage.hashEntity(entity)
const hash2 = storage.hashEntity(entity)
expect(hash1).toBe(hash2)
expect(hash1).toHaveLength(64) // SHA-256 = 64 hex chars
})
it('should generate different hashes for different content', () => {
const entity1: NounMetadata = {
id: 'user-1',
type: 'user',
name: 'Alice',
metadata: {}
}
const entity2: NounMetadata = {
id: 'user-1',
type: 'user',
name: 'Bob',
metadata: {}
}
const hash1 = storage.hashEntity(entity1)
const hash2 = storage.hashEntity(entity2)
expect(hash1).not.toBe(hash2)
})
it('should ignore property order (stable JSON)', () => {
const entity1: NounMetadata = {
id: 'user-1',
type: 'user',
name: 'Alice',
metadata: { a: 1, b: 2, c: 3 }
}
const entity2: NounMetadata = {
type: 'user',
metadata: { c: 3, b: 2, a: 1 },
name: 'Alice',
id: 'user-1'
}
const hash1 = storage.hashEntity(entity1)
const hash2 = storage.hashEntity(entity2)
expect(hash1).toBe(hash2)
})
it('should handle nested objects', () => {
const entity: NounMetadata = {
id: 'test-1',
type: 'thing',
name: 'Test',
metadata: {
nested: {
deep: {
value: 'hello'
}
}
}
}
const hash = storage.hashEntity(entity)
expect(hash).toHaveLength(64)
})
it('should handle arrays', () => {
const entity: NounMetadata = {
id: 'test-1',
type: 'thing',
name: 'Test',
metadata: {
tags: ['a', 'b', 'c']
}
}
const hash = storage.hashEntity(entity)
expect(hash).toHaveLength(64)
})
it('should handle null and undefined', () => {
const entity1: NounMetadata = {
id: 'test-1',
type: 'thing',
name: 'Test',
metadata: { value: null }
}
const entity2: NounMetadata = {
id: 'test-1',
type: 'thing',
name: 'Test',
metadata: { value: undefined }
}
const hash1 = storage.hashEntity(entity1)
const hash2 = storage.hashEntity(entity2)
expect(hash1).not.toBe(hash2)
})
})
describe('saveVersion()', () => {
it('should save version content to storage', async () => {
const entity: NounMetadata = {
id: 'user-123',
type: 'user',
name: 'Alice',
metadata: { email: 'alice@example.com' }
}
const version: EntityVersion = {
version: 1,
entityId: 'user-123',
branch: 'main',
commitHash: 'commit-123',
timestamp: Date.now(),
contentHash: storage.hashEntity(entity)
}
await storage.saveVersion(version, entity)
const expectedPath = `versions/entities/user-123/${version.contentHash}.json`
expect(mockFiles.has(expectedPath)).toBe(true)
const savedData = mockFiles.get(expectedPath)
expect(savedData).toBeDefined()
expect(JSON.parse(savedData!)).toEqual(entity)
})
it('should deduplicate identical content', async () => {
const entity: NounMetadata = {
id: 'doc-1',
type: 'document',
name: 'Doc',
metadata: { content: 'Same content' }
}
const contentHash = storage.hashEntity(entity)
const version1: EntityVersion = {
version: 1,
entityId: 'doc-1',
branch: 'main',
commitHash: 'commit-1',
timestamp: Date.now(),
contentHash
}
const version2: EntityVersion = {
version: 2,
entityId: 'doc-1',
branch: 'main',
commitHash: 'commit-2',
timestamp: Date.now() + 1000,
contentHash // Same hash!
}
await storage.saveVersion(version1, entity)
const writeCallCount1 = mockBrain.storageAdapter.writeFile.mock.calls.length
await storage.saveVersion(version2, entity)
const writeCallCount2 = mockBrain.storageAdapter.writeFile.mock.calls.length
// Should not write again (deduplication)
expect(writeCallCount2).toBe(writeCallCount1)
})
it('should store different content separately', async () => {
const entity1: NounMetadata = {
id: 'doc-1',
type: 'document',
name: 'Doc',
metadata: { content: 'Version 1' }
}
const entity2: NounMetadata = {
id: 'doc-1',
type: 'document',
name: 'Doc',
metadata: { content: 'Version 2' }
}
const version1: EntityVersion = {
version: 1,
entityId: 'doc-1',
branch: 'main',
commitHash: 'commit-1',
timestamp: Date.now(),
contentHash: storage.hashEntity(entity1)
}
const version2: EntityVersion = {
version: 2,
entityId: 'doc-1',
branch: 'main',
commitHash: 'commit-2',
timestamp: Date.now() + 1000,
contentHash: storage.hashEntity(entity2)
}
await storage.saveVersion(version1, entity1)
await storage.saveVersion(version2, entity2)
const path1 = `versions/entities/doc-1/${version1.contentHash}.json`
const path2 = `versions/entities/doc-1/${version2.contentHash}.json`
expect(mockFiles.has(path1)).toBe(true)
expect(mockFiles.has(path2)).toBe(true)
expect(path1).not.toBe(path2)
})
})
describe('loadVersion()', () => {
it('should load version content from storage', async () => {
const entity: NounMetadata = {
id: 'user-123',
type: 'user',
name: 'Alice',
metadata: { email: 'alice@example.com' }
}
const version: EntityVersion = {
version: 1,
entityId: 'user-123',
branch: 'main',
commitHash: 'commit-123',
timestamp: Date.now(),
contentHash: storage.hashEntity(entity)
}
// Save first
await storage.saveVersion(version, entity)
// Load
const loaded = await storage.loadVersion(version)
expect(loaded).toEqual(entity)
})
it('should return null if version not found', async () => {
const version: EntityVersion = {
version: 1,
entityId: 'nonexistent',
branch: 'main',
commitHash: 'commit-123',
timestamp: Date.now(),
contentHash: 'fake-hash'
}
const loaded = await storage.loadVersion(version)
expect(loaded).toBeNull()
})
it('should handle complex nested data', async () => {
const entity: NounMetadata = {
id: 'complex-1',
type: 'thing',
name: 'Complex',
metadata: {
nested: {
array: [1, 2, 3],
object: { key: 'value' }
},
tags: ['a', 'b', 'c']
}
}
const version: EntityVersion = {
version: 1,
entityId: 'complex-1',
branch: 'main',
commitHash: 'commit-123',
timestamp: Date.now(),
contentHash: storage.hashEntity(entity)
}
await storage.saveVersion(version, entity)
const loaded = await storage.loadVersion(version)
expect(loaded).toEqual(entity)
})
})
describe('deleteVersion()', () => {
it('should delete version from storage', async () => {
const entity: NounMetadata = {
id: 'user-123',
type: 'user',
name: 'Alice',
metadata: {}
}
const version: EntityVersion = {
version: 1,
entityId: 'user-123',
branch: 'main',
commitHash: 'commit-123',
timestamp: Date.now(),
contentHash: storage.hashEntity(entity)
}
// Save
await storage.saveVersion(version, entity)
const path = `versions/entities/user-123/${version.contentHash}.json`
expect(mockFiles.has(path)).toBe(true)
// Delete
await storage.deleteVersion(version)
expect(mockFiles.has(path)).toBe(false)
})
it('should handle deleting non-existent version gracefully', async () => {
const version: EntityVersion = {
version: 1,
entityId: 'nonexistent',
branch: 'main',
commitHash: 'commit-123',
timestamp: Date.now(),
contentHash: 'fake-hash'
}
// Should not throw
await storage.deleteVersion(version)
})
})
describe('Storage Adapter Integration', () => {
it('should work with memory storage adapter', async () => {
const entity: NounMetadata = {
id: 'test-1',
type: 'thing',
name: 'Test',
metadata: { value: 123 }
}
const version: EntityVersion = {
version: 1,
entityId: 'test-1',
branch: 'main',
commitHash: 'commit-123',
timestamp: Date.now(),
contentHash: storage.hashEntity(entity)
}
await storage.saveVersion(version, entity)
const loaded = await storage.loadVersion(version)
expect(loaded).toEqual(entity)
})
it('should use adapter.set if writeFile unavailable', async () => {
// Mock adapter with set/get instead of writeFile/readFile
mockBrain.storageAdapter = {
exists: vi.fn(async () => false),
set: vi.fn(async (path: string, data: string) => {
mockFiles.set(path, data)
}),
get: vi.fn(async (path: string) => {
const data = mockFiles.get(path)
if (!data) throw new Error('Not found')
return data
}),
delete: vi.fn(async (path: string) => {
mockFiles.delete(path)
})
}
storage = new VersionStorage(mockBrain)
const entity: NounMetadata = {
id: 'test-1',
type: 'thing',
name: 'Test',
metadata: {}
}
const version: EntityVersion = {
version: 1,
entityId: 'test-1',
branch: 'main',
commitHash: 'commit-123',
timestamp: Date.now(),
contentHash: storage.hashEntity(entity)
}
await storage.saveVersion(version, entity)
expect(mockBrain.storageAdapter.set).toHaveBeenCalled()
const loaded = await storage.loadVersion(version)
expect(mockBrain.storageAdapter.get).toHaveBeenCalled()
expect(loaded).toEqual(entity)
})
it('should throw if storage adapter missing', async () => {
mockBrain.storageAdapter = null
storage = new VersionStorage(mockBrain)
const entity: NounMetadata = {
id: 'test-1',
type: 'thing',
name: 'Test',
metadata: {}
}
const version: EntityVersion = {
version: 1,
entityId: 'test-1',
branch: 'main',
commitHash: 'commit-123',
timestamp: Date.now(),
contentHash: storage.hashEntity(entity)
}
await expect(
storage.saveVersion(version, entity)
).rejects.toThrow('Storage adapter not available')
})
it('should throw if adapter does not support required operations', async () => {
mockBrain.storageAdapter = {} // No methods
storage = new VersionStorage(mockBrain)
const entity: NounMetadata = {
id: 'test-1',
type: 'thing',
name: 'Test',
metadata: {}
}
const version: EntityVersion = {
version: 1,
entityId: 'test-1',
branch: 'main',
commitHash: 'commit-123',
timestamp: Date.now(),
contentHash: storage.hashEntity(entity)
}
await expect(
storage.saveVersion(version, entity)
).rejects.toThrow('does not support write operations')
})
})
describe('Path Generation', () => {
it('should generate correct storage paths', async () => {
const entity: NounMetadata = {
id: 'user-123',
type: 'user',
name: 'Alice',
metadata: {}
}
const contentHash = storage.hashEntity(entity)
const version: EntityVersion = {
version: 1,
entityId: 'user-123',
branch: 'main',
commitHash: 'commit-123',
timestamp: Date.now(),
contentHash
}
await storage.saveVersion(version, entity)
const expectedPath = `versions/entities/user-123/${contentHash}.json`
expect(mockFiles.has(expectedPath)).toBe(true)
})
it('should handle entity IDs with special characters', async () => {
const entity: NounMetadata = {
id: 'user:123:profile',
type: 'user',
name: 'Alice',
metadata: {}
}
const contentHash = storage.hashEntity(entity)
const version: EntityVersion = {
version: 1,
entityId: 'user:123:profile',
branch: 'main',
commitHash: 'commit-123',
timestamp: Date.now(),
contentHash
}
await storage.saveVersion(version, entity)
const expectedPath = `versions/entities/user:123:profile/${contentHash}.json`
expect(mockFiles.has(expectedPath)).toBe(true)
})
})
})