Virtual Filesystem (VFS)

Intelligent file management with semantic search, tree traversal, and relationship tracking.

Overview

Brainy's VFS provides a semantic file system where files are not just bytes, but entities with meaning, relationships, and searchable content. Build file explorers, IDEs, and knowledge systems that never crash from infinite recursion.

vfs-quickstart.js
import { Brainy } from '@soulcraft/brainy'

const brain = new Brainy({
  storage: { type: 'filesystem', path: './brainy-data' }
})
await brain.init()

// Get the VFS interface
const vfs = brain.vfs()
await vfs.init()

// Write files
await vfs.writeFile('/src/index.js', 'console.log("Hello")')
await vfs.writeFile('/docs/README.md', '# My Project')

// Semantic search - find by content meaning
const results = await vfs.search('logging and console output')
console.log(results) // [{ path: '/src/index.js', ... }]

File Operations

writeFile()

Write content to a file, creating parent directories automatically.

vfs.writeFile(path: string, content: string): Promise<void>
write-examples.js
// Write a new file
await vfs.writeFile('/projects/app/src/index.ts', `
import { Brainy } from '@soulcraft/brainy'
export const brain = new Brainy()
`)

// Overwrite existing file
await vfs.writeFile('/config.json', JSON.stringify({ port: 3000 }))

// Parent directories created automatically
await vfs.writeFile('/deep/nested/path/file.txt', 'content')

readFile()

Read the contents of a file.

vfs.readFile(path: string): Promise<string>
read-examples.js
const content = await vfs.readFile('/src/index.ts')
console.log(content)

// Parse JSON files
const config = JSON.parse(await vfs.readFile('/config.json'))

unlink()

Delete a file.

vfs.unlink(path: string): Promise<void>
unlink-example.js
await vfs.unlink('/temp/cache.json')

stat()

Get file or directory metadata.

vfs.stat(path: string): Promise<{
  isFile: boolean,
  isDirectory: boolean,
  size: number,
  mtime: Date
}>

Directory Operations

mkdir()

Create a directory. Parent directories are created automatically.

vfs.mkdir(path: string): Promise<void>

readdir()

List directory contents.

vfs.readdir(path: string): Promise<string[]>
directory-operations.js
// Create directories
await vfs.mkdir('/projects/new-app/src')

// List directory contents
const files = await vfs.readdir('/projects')
console.log(files) // ['new-app', 'other-project']

rmdir()

Remove a directory.

vfs.rmdir(path: string): Promise<void>

Tree Navigation

getTreeStructure()

Get a hierarchical tree structure with safety limits to prevent infinite recursion.

vfs.getTreeStructure(path: string, options?: {
  maxDepth?: number,
  sort?: 'name' | 'mtime' | 'size'
}): Promise<TreeNode>
tree-structure.js
// Get project tree (safe from infinite recursion)
const tree = await vfs.getTreeStructure('/projects', {
  maxDepth: 3,
  sort: 'name'
})

// tree = {
//   name: 'projects',
//   type: 'directory',
//   children: [
//     { name: 'app', type: 'directory', children: [...] },
//     { name: 'lib', type: 'directory', children: [...] }
//   ]
// }

getDescendants()

Get all descendants of a directory as a flat list.

vfs.getDescendants(path: string): Promise<string[]>
descendants.js
// Get all files in a project
const allFiles = await vfs.getDescendants('/projects/app')
// ['/projects/app/src/index.ts', '/projects/app/package.json', ...]

Semantic Search

search()

Find files by semantic meaning of their content.

vfs.search(query: string, options?: {
  path?: string,
  limit?: number,
  threshold?: number
}): Promise<SearchResult[]>
semantic-search.js
// Find files about authentication
const authFiles = await vfs.search('user authentication and login')

// Search within a specific directory
const docs = await vfs.search('API documentation', {
  path: '/docs',
  limit: 10
})

// Find similar files
const similar = await vfs.search('React components with hooks', {
  threshold: 0.7  // Minimum similarity
})

findSimilar()

Find files similar to a given file.

vfs.findSimilar(path: string, limit?: number): Promise<SearchResult[]>
find-similar.js
// Find files similar to index.ts
const similar = await vfs.findSimilar('/src/index.ts', 5)
// Returns 5 most similar files

Metadata & Relationships

getMetadata()

Get metadata attached to a file.

vfs.getMetadata(path: string): Promise<Record<string, any>>

getRelationships()

Get relationships between files.

vfs.getRelationships(path: string): Promise<Relationship[]>

addRelationship()

Create a relationship between two files.

vfs.addRelationship(
  sourcePath: string,
  targetPath: string,
  type: string
): Promise<void>
relationships.js
// Connect test to implementation
await vfs.addRelationship(
  '/src/auth.js',
  '/tests/auth.test.js',
  'tested-by'
)

// Get all relationships for a file
const rels = await vfs.getRelationships('/src/auth.js')
// [{ target: '/tests/auth.test.js', type: 'tested-by' }]

Project Analysis

getTodos()

Extract TODO comments from a file.

vfs.getTodos(path: string): Promise<Todo[]>

getAllTodos()

Get all TODO comments across the project.

vfs.getAllTodos(path?: string): Promise<Todo[]>
todos.js
// Get TODOs from a file
const fileTodos = await vfs.getTodos('/src/index.ts')

// Get all TODOs in project
const allTodos = await vfs.getAllTodos('/projects/app')
// [{ file: '/src/auth.ts', line: 42, text: 'TODO: Add rate limiting' }]

getProjectStats()

Get statistics about a project.

vfs.getProjectStats(path: string): Promise<{
  totalFiles: number,
  totalSize: number,
  fileTypes: Record<string, number>,
  lastModified: Date
}>
project-stats.js
const stats = await vfs.getProjectStats('/projects/app')
console.log(stats)
// {
//   totalFiles: 128,
//   totalSize: 524288,
//   fileTypes: { '.ts': 45, '.tsx': 32, '.json': 5 },
//   lastModified: 2024-03-15T10:30:00Z
// }

searchEntities()

Search for extracted entities within files.

vfs.searchEntities(query: string, options?: {
  types?: string[],
  path?: string
}): Promise<Entity[]>

Complete Example

vfs-complete-example.js
import { Brainy } from '@soulcraft/brainy'

// Initialize with persistent storage
const brain = new Brainy({
  storage: { type: 'filesystem', path: './brainy-data' }
})
await brain.init()

const vfs = brain.vfs()
await vfs.init()

// Create project structure
await vfs.mkdir('/myproject/src')
await vfs.mkdir('/myproject/tests')
await vfs.mkdir('/myproject/docs')

// Write files
await vfs.writeFile('/myproject/src/auth.ts', `
// TODO: Add rate limiting
export async function authenticate(token: string) {
  // Verify JWT token
  return verifyToken(token)
}
`)

await vfs.writeFile('/myproject/tests/auth.test.ts', `
import { authenticate } from '../src/auth'
test('authenticates valid token', async () => {
  const result = await authenticate('valid-token')
  expect(result).toBeTruthy()
})
`)

// Create relationship
await vfs.addRelationship(
  '/myproject/src/auth.ts',
  '/myproject/tests/auth.test.ts',
  'tested-by'
)

// Semantic search
const authFiles = await vfs.search('authentication and JWT')
console.log('Auth files:', authFiles)

// Get project tree
const tree = await vfs.getTreeStructure('/myproject', { maxDepth: 2 })
console.log('Project structure:', JSON.stringify(tree, null, 2))

// Get all TODOs
const todos = await vfs.getAllTodos('/myproject')
console.log('TODOs:', todos)

// Get project stats
const stats = await vfs.getProjectStats('/myproject')
console.log('Stats:', stats)

Safety Features

VFS includes built-in safety features to prevent common issues:

See Also

Next: Neural API →