chore(8.0): final pre-RC1 sweep — API consistency, named errors, orphans, zero-cast codebase
This commit is contained in:
parent
970e08c466
commit
1f7e365a4e
237 changed files with 1951 additions and 49413 deletions
|
|
@ -8,7 +8,7 @@
|
|||
- **[VFS Core](VFS_CORE.md)** - Complete filesystem architecture and API
|
||||
- **[Semantic VFS](SEMANTIC_VFS.md)** - Multi-dimensional file access (6 semantic dimensions)
|
||||
- **[Neural Extraction](NEURAL_EXTRACTION.md)** - AI-powered concept and entity extraction
|
||||
- **[Examples & Scenarios](VFS_EXAMPLES_SCENARIOS.md)** - Real-world use cases and code
|
||||
- **[Common Patterns](COMMON_PATTERNS.md)** - Real-world use cases and code
|
||||
- **[VFS API Guide](VFS_API_GUIDE.md)** - Complete API reference
|
||||
|
||||
## What is Brainy VFS?
|
||||
|
|
|
|||
|
|
@ -400,9 +400,9 @@ Semantic VFS is built on Brainy's Triple Intelligence™:
|
|||
### Real Implementations, Zero Mocks
|
||||
|
||||
Every component uses **production Brainy APIs**:
|
||||
- `brain.find()` - Real metadata queries (brainy.ts:580)
|
||||
- `brain.similar()` - Real HNSW search (brainy.ts:680)
|
||||
- `brain.getRelations()` - Real graph traversal (brainy.ts:803)
|
||||
- `brain.find()` - Real metadata queries
|
||||
- `brain.similar()` - Real HNSW search
|
||||
- `brain.related()` - Real graph traversal
|
||||
- `MetadataIndexManager` - Real B-tree indexes
|
||||
- `GraphAdjacencyIndex` - Real graph storage
|
||||
- `HNSW Index` - Real vector search
|
||||
|
|
|
|||
|
|
@ -183,7 +183,7 @@ console.log('VFS type:', entity.metadata.vfsType)
|
|||
### 3. Check Relationships
|
||||
```javascript
|
||||
const parentId = await vfs.resolvePath('/directory')
|
||||
const relations = await brain.getRelations({
|
||||
const relations = await brain.related({
|
||||
from: parentId,
|
||||
type: VerbType.Contains
|
||||
})
|
||||
|
|
@ -246,7 +246,7 @@ const tree = await vfs.getTreeStructure('/', {
|
|||
If you encounter issues not covered here:
|
||||
|
||||
1. Check the [VFS API Guide](./VFS_API_GUIDE.md)
|
||||
2. Review [VFS Examples](./VFS_EXAMPLES_SCENARIOS.md)
|
||||
2. Review [Common Patterns](./COMMON_PATTERNS.md)
|
||||
3. Look at [test files](../../tests/vfs/) for working examples
|
||||
4. Report issues at [GitHub Issues](https://github.com/soulcraftlabs/brainy/issues)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,728 +0,0 @@
|
|||
# VFS User Functions - Templates and Examples
|
||||
|
||||
This document provides template functions that you can implement for domain-specific needs. These functions combine VFS primitives to solve common problems.
|
||||
|
||||
## Table of Contents
|
||||
1. [Code Analysis Functions](#code-analysis-functions)
|
||||
2. [Export Format Functions](#export-format-functions)
|
||||
3. [Project Management Functions](#project-management-functions)
|
||||
4. [Creative Writing Functions](#creative-writing-functions)
|
||||
5. [Game Development Functions](#game-development-functions)
|
||||
|
||||
## Code Analysis Functions
|
||||
|
||||
### Get Dependency Graph
|
||||
```javascript
|
||||
/**
|
||||
* Build a dependency graph for JavaScript/TypeScript projects
|
||||
*/
|
||||
async function getDependencyGraph(vfs, srcPath) {
|
||||
const files = await vfs.readdir(srcPath, { recursive: true })
|
||||
const graph = {}
|
||||
|
||||
for (const file of files) {
|
||||
const filePath = `${srcPath}/${file}`
|
||||
|
||||
// Only process JS/TS files
|
||||
if (file.match(/\.(js|ts|jsx|tsx)$/)) {
|
||||
const content = await vfs.readFile(filePath)
|
||||
const text = content.toString()
|
||||
|
||||
// Parse imports (basic regex, use proper AST parser for production)
|
||||
const imports = []
|
||||
const importRegex = /import\s+.*?\s+from\s+['"](.+?)['"]/g
|
||||
const requireRegex = /require\(['"](.+?)['"]\)/g
|
||||
|
||||
let match
|
||||
while ((match = importRegex.exec(text)) !== null) {
|
||||
imports.push(match[1])
|
||||
}
|
||||
while ((match = requireRegex.exec(text)) !== null) {
|
||||
imports.push(match[1])
|
||||
}
|
||||
|
||||
graph[filePath] = imports
|
||||
}
|
||||
}
|
||||
|
||||
return graph
|
||||
}
|
||||
|
||||
// Use it
|
||||
const deps = await getDependencyGraph(vfs, '/src')
|
||||
```
|
||||
|
||||
### Find Circular Dependencies
|
||||
```javascript
|
||||
/**
|
||||
* Detect circular dependencies in your code
|
||||
*/
|
||||
async function findCircularDependencies(vfs, srcPath) {
|
||||
const graph = await getDependencyGraph(vfs, srcPath)
|
||||
const cycles = []
|
||||
|
||||
function detectCycle(node, visited = new Set(), stack = []) {
|
||||
if (stack.includes(node)) {
|
||||
const cycleStart = stack.indexOf(node)
|
||||
cycles.push(stack.slice(cycleStart))
|
||||
return
|
||||
}
|
||||
|
||||
if (visited.has(node)) return
|
||||
visited.add(node)
|
||||
stack.push(node)
|
||||
|
||||
const dependencies = graph[node] || []
|
||||
for (const dep of dependencies) {
|
||||
// Resolve relative imports
|
||||
const resolvedDep = resolvePath(node, dep)
|
||||
if (graph[resolvedDep]) {
|
||||
detectCycle(resolvedDep, visited, [...stack])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Object.keys(graph).forEach(node => detectCycle(node))
|
||||
return cycles
|
||||
}
|
||||
```
|
||||
|
||||
### Find Untested Code
|
||||
```javascript
|
||||
/**
|
||||
* Find source files without corresponding test files
|
||||
*/
|
||||
async function findUntestedCode(vfs, srcPath, testPath = null) {
|
||||
testPath = testPath || srcPath.replace('/src', '/tests')
|
||||
|
||||
const sourceFiles = await vfs.readdir(srcPath, { recursive: true })
|
||||
const testFiles = await vfs.readdir(testPath, { recursive: true }).catch(() => [])
|
||||
|
||||
const untestedFiles = []
|
||||
|
||||
for (const sourceFile of sourceFiles) {
|
||||
if (!sourceFile.match(/\.(js|ts|jsx|tsx)$/)) continue
|
||||
|
||||
// Look for corresponding test file
|
||||
const baseName = sourceFile.replace(/\.(js|ts|jsx|tsx)$/, '')
|
||||
const hasTest = testFiles.some(testFile =>
|
||||
testFile.includes(baseName) &&
|
||||
testFile.match(/\.(test|spec)\.(js|ts|jsx|tsx)$/)
|
||||
)
|
||||
|
||||
if (!hasTest) {
|
||||
untestedFiles.push(`${srcPath}/${sourceFile}`)
|
||||
}
|
||||
}
|
||||
|
||||
return untestedFiles
|
||||
}
|
||||
```
|
||||
|
||||
### Find Similar Code (Duplicate Detection)
|
||||
```javascript
|
||||
/**
|
||||
* Find potentially duplicate code using similarity scoring
|
||||
*/
|
||||
async function findSimilarCode(vfs, filePath, options = {}) {
|
||||
const threshold = options.threshold || 0.8
|
||||
const searchPath = options.searchPath || '/'
|
||||
|
||||
// Get the reference file content
|
||||
const referenceContent = await vfs.readFile(filePath)
|
||||
const referenceText = referenceContent.toString()
|
||||
|
||||
// Use VFS's semantic search
|
||||
const similar = await vfs.findSimilar(filePath, {
|
||||
limit: 10,
|
||||
threshold
|
||||
})
|
||||
|
||||
// Additionally, do structural comparison
|
||||
const results = []
|
||||
for (const match of similar) {
|
||||
const matchContent = await vfs.readFile(match.path)
|
||||
const matchText = matchContent.toString()
|
||||
|
||||
// Simple line-based similarity (use better algorithms in production)
|
||||
const similarity = calculateSimilarity(referenceText, matchText)
|
||||
|
||||
if (similarity > threshold) {
|
||||
results.push({
|
||||
path: match.path,
|
||||
similarity,
|
||||
semanticScore: match.score
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return results.sort((a, b) => b.similarity - a.similarity)
|
||||
}
|
||||
|
||||
function calculateSimilarity(text1, text2) {
|
||||
// Simple Jaccard similarity on lines
|
||||
const lines1 = new Set(text1.split('\n').map(l => l.trim()).filter(l => l))
|
||||
const lines2 = new Set(text2.split('\n').map(l => l.trim()).filter(l => l))
|
||||
|
||||
const intersection = new Set([...lines1].filter(x => lines2.has(x)))
|
||||
const union = new Set([...lines1, ...lines2])
|
||||
|
||||
return intersection.size / union.size
|
||||
}
|
||||
```
|
||||
|
||||
## Export Format Functions
|
||||
|
||||
### Export to EPUB (for novels)
|
||||
```javascript
|
||||
/**
|
||||
* Export a directory of markdown files to EPUB format
|
||||
*/
|
||||
async function exportToEpub(vfs, path, metadata = {}) {
|
||||
// First get the markdown export
|
||||
const markdown = await vfs.exportToMarkdown(path)
|
||||
|
||||
// You'll need an EPUB library like epub-gen
|
||||
const Epub = require('epub-gen')
|
||||
|
||||
// Convert markdown chapters to EPUB format
|
||||
const chapters = []
|
||||
const files = await vfs.readdir(path, { recursive: true })
|
||||
|
||||
for (const file of files.sort()) {
|
||||
if (file.endsWith('.md')) {
|
||||
const content = await vfs.readFile(`${path}/${file}`)
|
||||
const title = file.replace('.md', '').replace(/-/g, ' ')
|
||||
|
||||
chapters.push({
|
||||
title: title,
|
||||
data: content.toString()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const options = {
|
||||
title: metadata.title || 'My Book',
|
||||
author: metadata.author || 'Author',
|
||||
chapters: chapters
|
||||
}
|
||||
|
||||
return new Epub(options)
|
||||
}
|
||||
```
|
||||
|
||||
### Export to Static Site
|
||||
```javascript
|
||||
/**
|
||||
* Export VFS content to static HTML site
|
||||
*/
|
||||
async function exportToStaticSite(vfs, sourcePath, options = {}) {
|
||||
const json = await vfs.exportToJSON(sourcePath)
|
||||
const html = []
|
||||
|
||||
html.push('<!DOCTYPE html>')
|
||||
html.push('<html><head>')
|
||||
html.push(`<title>${options.title || 'Documentation'}</title>`)
|
||||
html.push('<style>/* Add your styles */</style>')
|
||||
html.push('</head><body>')
|
||||
|
||||
function renderNode(node, name, depth = 0) {
|
||||
const indent = ' '.repeat(depth)
|
||||
|
||||
if (node._meta?.type === 'file') {
|
||||
html.push(`${indent}<article>`)
|
||||
html.push(`${indent} <h${Math.min(depth + 2, 6)}>${name}</h${Math.min(depth + 2, 6)}>`)
|
||||
|
||||
if (typeof node._content === 'string') {
|
||||
// Convert markdown to HTML if needed
|
||||
html.push(`${indent} <pre>${escapeHtml(node._content)}</pre>`)
|
||||
}
|
||||
|
||||
html.push(`${indent}</article>`)
|
||||
} else if (node._meta?.type === 'directory') {
|
||||
html.push(`${indent}<section>`)
|
||||
html.push(`${indent} <h${Math.min(depth + 1, 6)}>${name}</h${Math.min(depth + 1, 6)}>`)
|
||||
|
||||
for (const [childName, childNode] of Object.entries(node)) {
|
||||
if (!childName.startsWith('_')) {
|
||||
renderNode(childNode, childName, depth + 1)
|
||||
}
|
||||
}
|
||||
|
||||
html.push(`${indent}</section>`)
|
||||
}
|
||||
}
|
||||
|
||||
renderNode(json, options.title || 'Root')
|
||||
|
||||
html.push('</body></html>')
|
||||
return html.join('\n')
|
||||
}
|
||||
```
|
||||
|
||||
### Export to GraphQL Schema
|
||||
```javascript
|
||||
/**
|
||||
* Generate GraphQL schema from VFS entities
|
||||
*/
|
||||
async function exportToGraphQLSchema(vfs) {
|
||||
const entities = await vfs.listEntities()
|
||||
const types = new Map()
|
||||
|
||||
// Group entities by type
|
||||
for (const entity of entities) {
|
||||
const type = entity.type || 'Unknown'
|
||||
if (!types.has(type)) {
|
||||
types.set(type, [])
|
||||
}
|
||||
types.get(type).push(entity)
|
||||
}
|
||||
|
||||
// Generate schema
|
||||
let schema = 'type Query {\n'
|
||||
|
||||
for (const [typeName, entities] of types) {
|
||||
schema += ` get${typeName}(id: ID!): ${typeName}\n`
|
||||
schema += ` list${typeName}s: [${typeName}!]!\n`
|
||||
}
|
||||
|
||||
schema += '}\n\n'
|
||||
|
||||
// Generate types
|
||||
for (const [typeName, entities] of types) {
|
||||
schema += `type ${typeName} {\n`
|
||||
schema += ' id: ID!\n'
|
||||
|
||||
// Infer fields from first entity
|
||||
if (entities.length > 0) {
|
||||
const sample = entities[0]
|
||||
for (const [key, value] of Object.entries(sample)) {
|
||||
if (key !== 'id') {
|
||||
const fieldType = inferGraphQLType(value)
|
||||
schema += ` ${key}: ${fieldType}\n`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
schema += '}\n\n'
|
||||
}
|
||||
|
||||
return schema
|
||||
}
|
||||
```
|
||||
|
||||
## Project Management Functions
|
||||
|
||||
### Get Project Insights
|
||||
```javascript
|
||||
/**
|
||||
* Analyze project for insights and patterns
|
||||
*/
|
||||
async function getProjectInsights(vfs, projectPath) {
|
||||
const stats = await vfs.getProjectStats(projectPath)
|
||||
const todos = await vfs.getAllTodos(projectPath)
|
||||
const timeline = await vfs.getTimeline({ limit: 100 })
|
||||
|
||||
// Analyze activity patterns
|
||||
const activityByDay = {}
|
||||
const activityByUser = {}
|
||||
const activityByFile = {}
|
||||
|
||||
for (const event of timeline) {
|
||||
const day = event.timestamp.toISOString().split('T')[0]
|
||||
activityByDay[day] = (activityByDay[day] || 0) + 1
|
||||
|
||||
const user = event.user || 'system'
|
||||
activityByUser[user] = (activityByUser[user] || 0) + 1
|
||||
|
||||
activityByFile[event.path] = (activityByFile[event.path] || 0) + 1
|
||||
}
|
||||
|
||||
// Find hotspots (most edited files)
|
||||
const hotspots = Object.entries(activityByFile)
|
||||
.sort(([,a], [,b]) => b - a)
|
||||
.slice(0, 10)
|
||||
.map(([path, count]) => ({ path, edits: count }))
|
||||
|
||||
// Todo analysis
|
||||
const todosByPriority = {}
|
||||
const todosByStatus = {}
|
||||
|
||||
for (const todo of todos) {
|
||||
todosByPriority[todo.priority] = (todosByPriority[todo.priority] || 0) + 1
|
||||
todosByStatus[todo.status] = (todosByStatus[todo.status] || 0) + 1
|
||||
}
|
||||
|
||||
return {
|
||||
stats,
|
||||
activity: {
|
||||
byDay: activityByDay,
|
||||
byUser: activityByUser,
|
||||
hotspots
|
||||
},
|
||||
todos: {
|
||||
total: todos.length,
|
||||
byPriority: todosByPriority,
|
||||
byStatus: todosByStatus,
|
||||
highPriority: todos.filter(t => t.priority === 'high' && t.status === 'pending')
|
||||
},
|
||||
recommendations: generateRecommendations(stats, todos, hotspots)
|
||||
}
|
||||
}
|
||||
|
||||
function generateRecommendations(stats, todos, hotspots) {
|
||||
const recommendations = []
|
||||
|
||||
if (stats.largestFile && stats.largestFile.size > 1024 * 1024) {
|
||||
recommendations.push({
|
||||
type: 'refactor',
|
||||
message: `Consider splitting ${stats.largestFile.path} (${Math.round(stats.largestFile.size / 1024)}KB)`
|
||||
})
|
||||
}
|
||||
|
||||
if (todos.filter(t => t.priority === 'high' && t.status === 'pending').length > 5) {
|
||||
recommendations.push({
|
||||
type: 'priority',
|
||||
message: 'You have many high-priority pending todos'
|
||||
})
|
||||
}
|
||||
|
||||
if (hotspots.length > 0 && hotspots[0].edits > 50) {
|
||||
recommendations.push({
|
||||
type: 'stability',
|
||||
message: `${hotspots[0].path} changes frequently, consider stabilizing`
|
||||
})
|
||||
}
|
||||
|
||||
return recommendations
|
||||
}
|
||||
```
|
||||
|
||||
### Generate Sprint Report
|
||||
```javascript
|
||||
/**
|
||||
* Generate a report for the current sprint
|
||||
*/
|
||||
async function generateSprintReport(vfs, sprintStart, sprintEnd = new Date()) {
|
||||
const timeline = await vfs.getTimeline({
|
||||
from: sprintStart,
|
||||
to: sprintEnd
|
||||
})
|
||||
|
||||
const todos = await vfs.getAllTodos()
|
||||
|
||||
// Group work by user
|
||||
const workByUser = {}
|
||||
for (const event of timeline) {
|
||||
const user = event.user || 'system'
|
||||
if (!workByUser[user]) {
|
||||
workByUser[user] = {
|
||||
commits: 0,
|
||||
filesModified: new Set(),
|
||||
linesChanged: 0
|
||||
}
|
||||
}
|
||||
|
||||
workByUser[user].commits++
|
||||
workByUser[user].filesModified.add(event.path)
|
||||
}
|
||||
|
||||
// Calculate completion rate
|
||||
const completedTodos = todos.filter(t => t.status === 'completed').length
|
||||
const totalTodos = todos.length
|
||||
const completionRate = totalTodos > 0 ? (completedTodos / totalTodos * 100).toFixed(1) : 0
|
||||
|
||||
return {
|
||||
period: {
|
||||
start: sprintStart,
|
||||
end: sprintEnd,
|
||||
days: Math.ceil((sprintEnd - sprintStart) / (1000 * 60 * 60 * 24))
|
||||
},
|
||||
team: Object.entries(workByUser).map(([user, work]) => ({
|
||||
user,
|
||||
commits: work.commits,
|
||||
filesModified: work.filesModified.size
|
||||
})),
|
||||
todos: {
|
||||
completed: completedTodos,
|
||||
total: totalTodos,
|
||||
completionRate: `${completionRate}%`,
|
||||
remaining: todos.filter(t => t.status === 'pending')
|
||||
},
|
||||
velocity: {
|
||||
commitsPerDay: (timeline.length / 7).toFixed(1),
|
||||
todosPerDay: (completedTodos / 7).toFixed(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Creative Writing Functions
|
||||
|
||||
### Track Character Arcs
|
||||
```javascript
|
||||
/**
|
||||
* Track how characters evolve throughout a story
|
||||
*/
|
||||
async function trackCharacterArc(vfs, characterName, storyPath = '/') {
|
||||
// Find the character entity
|
||||
const entities = await vfs.searchEntities({
|
||||
type: 'character',
|
||||
name: characterName
|
||||
})
|
||||
|
||||
if (entities.length === 0) {
|
||||
throw new Error(`Character ${characterName} not found`)
|
||||
}
|
||||
|
||||
const character = entities[0]
|
||||
const occurrences = await vfs.findEntityOccurrences(character.id)
|
||||
|
||||
// Analyze each appearance
|
||||
const arc = []
|
||||
|
||||
for (const occurrence of occurrences) {
|
||||
const content = await vfs.readFile(occurrence.path)
|
||||
const text = content.toString()
|
||||
|
||||
// Find mentions of the character (basic approach)
|
||||
const mentions = text.split('\n').filter(line =>
|
||||
line.toLowerCase().includes(characterName.toLowerCase())
|
||||
)
|
||||
|
||||
arc.push({
|
||||
chapter: occurrence.path,
|
||||
mentions: mentions.length,
|
||||
// Analyze emotional tone (simplified)
|
||||
mood: analyzeMood(mentions),
|
||||
// Extract key actions
|
||||
actions: extractActions(mentions, characterName)
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
character: character.metadata,
|
||||
arc: arc,
|
||||
summary: summarizeArc(arc)
|
||||
}
|
||||
}
|
||||
|
||||
function analyzeMood(mentions) {
|
||||
const positiveWords = ['smiled', 'laughed', 'happy', 'joy', 'love', 'success']
|
||||
const negativeWords = ['cried', 'angry', 'sad', 'fear', 'fail', 'death']
|
||||
|
||||
let positive = 0, negative = 0
|
||||
|
||||
for (const mention of mentions) {
|
||||
const lower = mention.toLowerCase()
|
||||
positive += positiveWords.filter(w => lower.includes(w)).length
|
||||
negative += negativeWords.filter(w => lower.includes(w)).length
|
||||
}
|
||||
|
||||
if (positive > negative) return 'positive'
|
||||
if (negative > positive) return 'negative'
|
||||
return 'neutral'
|
||||
}
|
||||
```
|
||||
|
||||
### Generate Story Bible
|
||||
```javascript
|
||||
/**
|
||||
* Create a comprehensive reference for your story universe
|
||||
*/
|
||||
async function generateStoryBible(vfs, storyPath) {
|
||||
const characters = await vfs.listEntities({ type: 'character' })
|
||||
const locations = await vfs.listEntities({ type: 'location' })
|
||||
const concepts = await vfs.findConcepts({ domain: 'narrative' })
|
||||
|
||||
const bible = {
|
||||
title: 'Story Bible',
|
||||
generated: new Date(),
|
||||
characters: {},
|
||||
locations: {},
|
||||
plotThreads: {},
|
||||
timeline: []
|
||||
}
|
||||
|
||||
// Document characters
|
||||
for (const char of characters) {
|
||||
const occurrences = await vfs.findEntityOccurrences(char.id)
|
||||
bible.characters[char.metadata.name] = {
|
||||
...char.metadata,
|
||||
appearances: occurrences.map(o => o.path),
|
||||
relationships: await vfs.getEntityGraph(char.id, { depth: 1 })
|
||||
}
|
||||
}
|
||||
|
||||
// Document locations
|
||||
for (const loc of locations) {
|
||||
bible.locations[loc.metadata.name] = {
|
||||
...loc.metadata,
|
||||
scenes: await vfs.findEntityOccurrences(loc.id)
|
||||
}
|
||||
}
|
||||
|
||||
// Plot threads from concepts
|
||||
for (const concept of concepts) {
|
||||
if (concept.type === 'plot') {
|
||||
bible.plotThreads[concept.name] = {
|
||||
description: concept.description,
|
||||
keywords: concept.keywords,
|
||||
chapters: await vfs.findByConcept(concept.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Generate timeline
|
||||
const events = await vfs.getTimeline({ limit: 1000 })
|
||||
bible.timeline = events.map(e => ({
|
||||
date: e.timestamp,
|
||||
event: e.description,
|
||||
chapter: e.path
|
||||
}))
|
||||
|
||||
return bible
|
||||
}
|
||||
```
|
||||
|
||||
## Game Development Functions
|
||||
|
||||
### Validate Game Data
|
||||
```javascript
|
||||
/**
|
||||
* Validate game configuration files for consistency
|
||||
*/
|
||||
async function validateGameData(vfs, gamePath) {
|
||||
const errors = []
|
||||
const warnings = []
|
||||
|
||||
// Load all game data
|
||||
const gameData = await vfs.exportToJSON(gamePath)
|
||||
|
||||
// Check quest references
|
||||
if (gameData.quests) {
|
||||
for (const [questName, quest] of Object.entries(gameData.quests)) {
|
||||
// Check NPC references
|
||||
if (quest._content?.questGiver) {
|
||||
const npcPath = `${gamePath}/npcs/${quest._content.questGiver}.json`
|
||||
const exists = await vfs.exists(npcPath)
|
||||
if (!exists) {
|
||||
errors.push(`Quest ${questName} references missing NPC: ${quest._content.questGiver}`)
|
||||
}
|
||||
}
|
||||
|
||||
// Check item rewards
|
||||
if (quest._content?.rewards?.items) {
|
||||
for (const item of quest._content.rewards.items) {
|
||||
const itemPath = `${gamePath}/items/${item}.json`
|
||||
const exists = await vfs.exists(itemPath)
|
||||
if (!exists) {
|
||||
warnings.push(`Quest ${questName} rewards missing item: ${item}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check balance
|
||||
if (gameData.items) {
|
||||
const itemPowers = []
|
||||
for (const [itemName, item] of Object.entries(gameData.items)) {
|
||||
if (item._content?.stats) {
|
||||
const totalPower = Object.values(item._content.stats)
|
||||
.reduce((a, b) => a + b, 0)
|
||||
itemPowers.push({ name: itemName, power: totalPower })
|
||||
}
|
||||
}
|
||||
|
||||
// Find outliers
|
||||
const avgPower = itemPowers.reduce((a, b) => a + b.power, 0) / itemPowers.length
|
||||
const outliers = itemPowers.filter(i => Math.abs(i.power - avgPower) > avgPower * 2)
|
||||
|
||||
for (const outlier of outliers) {
|
||||
warnings.push(`Item ${outlier.name} may be imbalanced (power: ${outlier.power}, avg: ${avgPower})`)
|
||||
}
|
||||
}
|
||||
|
||||
return { errors, warnings, valid: errors.length === 0 }
|
||||
}
|
||||
```
|
||||
|
||||
### Generate Loot Tables
|
||||
```javascript
|
||||
/**
|
||||
* Generate weighted loot tables from item definitions
|
||||
*/
|
||||
async function generateLootTables(vfs, itemsPath) {
|
||||
const items = await vfs.exportToJSON(itemsPath)
|
||||
const tables = {
|
||||
common: [],
|
||||
uncommon: [],
|
||||
rare: [],
|
||||
epic: [],
|
||||
legendary: []
|
||||
}
|
||||
|
||||
for (const [itemName, item] of Object.entries(items)) {
|
||||
if (item._meta?.type === 'file' && item._content?.rarity) {
|
||||
const entry = {
|
||||
name: itemName.replace('.json', ''),
|
||||
weight: getWeight(item._content.rarity),
|
||||
data: item._content
|
||||
}
|
||||
|
||||
tables[item._content.rarity.toLowerCase()].push(entry)
|
||||
}
|
||||
}
|
||||
|
||||
// Normalize weights
|
||||
for (const table of Object.values(tables)) {
|
||||
const totalWeight = table.reduce((a, b) => a + b.weight, 0)
|
||||
for (const entry of table) {
|
||||
entry.probability = (entry.weight / totalWeight * 100).toFixed(2) + '%'
|
||||
}
|
||||
}
|
||||
|
||||
return tables
|
||||
}
|
||||
|
||||
function getWeight(rarity) {
|
||||
const weights = {
|
||||
common: 100,
|
||||
uncommon: 50,
|
||||
rare: 20,
|
||||
epic: 5,
|
||||
legendary: 1
|
||||
}
|
||||
return weights[rarity.toLowerCase()] || 10
|
||||
}
|
||||
```
|
||||
|
||||
## Using These Functions
|
||||
|
||||
All these functions are templates that you can customize for your specific needs. To use them:
|
||||
|
||||
1. Copy the function you need
|
||||
2. Modify it for your specific requirements
|
||||
3. Use it with your VFS instance:
|
||||
|
||||
```javascript
|
||||
import { Brainy } from '@soulcraft/brainy'
|
||||
|
||||
// Initialize VFS
|
||||
const brain = new Brainy()
|
||||
await brain.init()
|
||||
const vfs = brain.vfs()
|
||||
await vfs.init()
|
||||
|
||||
// Use your custom function
|
||||
const insights = await getProjectInsights(vfs, '/my-project')
|
||||
console.log(insights.recommendations)
|
||||
|
||||
// Combine multiple functions
|
||||
const deps = await getDependencyGraph(vfs, '/src')
|
||||
const cycles = await findCircularDependencies(vfs, '/src')
|
||||
const untested = await findUntestedCode(vfs, '/src', '/tests')
|
||||
```
|
||||
|
||||
Remember: These are starting points. The power of VFS is that you can combine its primitives to build exactly what you need for your domain!
|
||||
|
|
@ -1,684 +0,0 @@
|
|||
# VFS Examples and Scenarios
|
||||
|
||||
> **⚠️ DOCUMENTATION IN PROGRESS**: This document is being updated to reflect recent VFS architecture changes. Many examples below reference deprecated Knowledge Layer methods. Updated examples coming soon. For current VFS capabilities, see [VFS_CORE.md](./VFS_CORE.md) and [SEMANTIC_VFS.md](./SEMANTIC_VFS.md).
|
||||
|
||||
## Real-World Scenarios
|
||||
|
||||
This document demonstrates how VFS enables powerful real-world applications with semantic search, relationships, and AI-powered concept extraction.
|
||||
|
||||
### Legend
|
||||
- ✅ **Real VFS methods** - Fully implemented and working
|
||||
- 📝 **User functions** - Templates available in [USER_FUNCTIONS.md](./USER_FUNCTIONS.md)
|
||||
- 🔮 **Future features** - Not yet available (AI augmentations)
|
||||
|
||||
**Note:** All ✅ marked methods are production-ready. For 📝 methods, see USER_FUNCTIONS.md for implementation templates.
|
||||
|
||||
## Scenario 1: Collaborative Novel Writing
|
||||
|
||||
Multiple authors working on a shared universe with recurring characters and locations.
|
||||
|
||||
```javascript
|
||||
import { Brainy } from '@soulcraft/brainy'
|
||||
|
||||
async function novelWritingProject() {
|
||||
const brain = new Brainy({ storage: { type: 'file', path: './novel-data' } })
|
||||
await brain.init()
|
||||
|
||||
const vfs = brain.vfs()
|
||||
await vfs.init()
|
||||
|
||||
// Create project structure ✅
|
||||
await vfs.mkdir('/novel')
|
||||
await vfs.mkdir('/novel/chapters')
|
||||
await vfs.mkdir('/novel/characters')
|
||||
await vfs.mkdir('/novel/worldbuilding')
|
||||
|
||||
// Define main characters as files with rich metadata ✅
|
||||
await vfs.writeFile('/novel/characters/elena-blackwood.md', `
|
||||
# Elena Blackwood
|
||||
|
||||
A skilled detective with a mysterious past.
|
||||
|
||||
## Character Profile
|
||||
- Age: 32
|
||||
- Occupation: Private Investigator
|
||||
- Skills: Deduction, combat, languages
|
||||
- Personality: Determined, secretive, compassionate
|
||||
`, {
|
||||
metadata: {
|
||||
characterType: 'protagonist',
|
||||
tags: ['detective', 'mysterious', 'protagonist']
|
||||
}
|
||||
})
|
||||
|
||||
await vfs.writeFile('/novel/characters/marcus-void.md', `
|
||||
# Marcus Void
|
||||
description: 'A wealthy industrialist with dark secrets',
|
||||
attributes: {
|
||||
age: 45,
|
||||
occupation: 'CEO of Void Industries',
|
||||
traits: ['ruthless', 'charismatic', 'brilliant']
|
||||
}
|
||||
})
|
||||
|
||||
// Create location entities
|
||||
const city = await vfs.createEntity({
|
||||
name: 'Neo Tokyo',
|
||||
type: 'location',
|
||||
description: 'A sprawling cyberpunk metropolis',
|
||||
attributes: {
|
||||
population: '40 million',
|
||||
districts: ['Shibuya-5', 'Crypto Quarter', 'Old Town'],
|
||||
atmosphere: 'neon-lit, rain-soaked, vertical'
|
||||
}
|
||||
})
|
||||
|
||||
// Link entities ✅
|
||||
await vfs.linkEntities(protagonist.id, city.id, 'lives_in')
|
||||
await vfs.linkEntities(protagonist.id, antagonist.id, 'investigates')
|
||||
|
||||
// Write chapters with automatic entity tracking
|
||||
await vfs.writeFile('/novel/chapters/chapter1.md', `
|
||||
# Chapter 1: Rain in Neo Tokyo
|
||||
|
||||
Elena Blackwood stood at the edge of Shibuya-5, watching the rain cascade down
|
||||
the neon-lit towers. The case file on Marcus Void burned in her pocket.
|
||||
|
||||
She had been tracking Void Industries for months, following a trail of
|
||||
disappeared scientists and mysterious experiments. Tonight, she would finally
|
||||
infiltrate the Crypto Quarter facility.
|
||||
`)
|
||||
|
||||
// Multiple authors can work simultaneously ✅
|
||||
vfs.setUser('author-alice')
|
||||
await vfs.writeFile('/novel/chapters/chapter2.md', `
|
||||
# Chapter 2: The Void Industries Tower
|
||||
|
||||
Marcus Void gazed down at Neo Tokyo from his penthouse office. Somewhere
|
||||
in those rain-slicked streets, Elena Blackwood was hunting him...
|
||||
`)
|
||||
|
||||
vfs.setUser('author-bob')
|
||||
await vfs.appendFile('/novel/chapters/chapter2.md', `
|
||||
|
||||
He smiled. Let her come. The trap was already set.
|
||||
`)
|
||||
|
||||
// Track character appearances across chapters ✅
|
||||
const elenaAppearances = await vfs.findEntityOccurrences(protagonist.id)
|
||||
console.log('Elena appears in:', elenaAppearances.map(f => f.path))
|
||||
|
||||
// Find all locations mentioned ✅
|
||||
const locations = await vfs.listEntities({ type: 'location' })
|
||||
|
||||
// Generate character relationship graph ✅
|
||||
const relationships = await vfs.getEntityGraph(protagonist.id, { depth: 2 })
|
||||
|
||||
// Track plot threads using concepts ✅
|
||||
await vfs.createConcept({
|
||||
name: 'The Void Conspiracy',
|
||||
type: 'plot',
|
||||
domain: 'narrative',
|
||||
description: 'The main mystery involving disappeared scientists',
|
||||
keywords: ['scientists', 'experiments', 'void industries', 'conspiracy']
|
||||
})
|
||||
|
||||
// Find all chapters related to the conspiracy ✅
|
||||
const conspiracyChapters = await vfs.findByConcept('The Void Conspiracy')
|
||||
|
||||
// Version control for revisions ✅
|
||||
const chapterVersions = await vfs.getVersions('/novel/chapters/chapter1.md')
|
||||
|
||||
// Collaborative editing history ✅
|
||||
const history = await vfs.getCollaborationHistory('/novel/chapters/chapter2.md')
|
||||
console.log('Chapter 2 edited by:', history.map(h => h.user))
|
||||
|
||||
// Export for publishing ✅
|
||||
const manuscript = await vfs.exportToMarkdown('/novel/chapters')
|
||||
|
||||
await vfs.close()
|
||||
await brain.close()
|
||||
}
|
||||
```
|
||||
|
||||
## Scenario 2: Video Game Development
|
||||
|
||||
Game developers creating a complex RPG with quests, items, and NPCs.
|
||||
|
||||
```javascript
|
||||
async function gameDevProject() {
|
||||
const brain = new Brainy({ storage: { type: 's3', bucket: 'game-assets' } })
|
||||
await brain.init()
|
||||
|
||||
const vfs = brain.vfs()
|
||||
await vfs.init()
|
||||
|
||||
// Game project structure
|
||||
await vfs.mkdir('/game')
|
||||
await vfs.mkdir('/game/scripts')
|
||||
await vfs.mkdir('/game/assets')
|
||||
await vfs.mkdir('/game/quests')
|
||||
await vfs.mkdir('/game/npcs')
|
||||
await vfs.mkdir('/game/items')
|
||||
|
||||
// Define game systems as concepts
|
||||
await vfs.createConcept({
|
||||
name: 'Combat System',
|
||||
type: 'system',
|
||||
domain: 'gameplay',
|
||||
keywords: ['damage', 'health', 'attacks', 'defense']
|
||||
})
|
||||
|
||||
await vfs.createConcept({
|
||||
name: 'Quest System',
|
||||
type: 'system',
|
||||
domain: 'gameplay',
|
||||
keywords: ['objectives', 'rewards', 'dialogue', 'progression']
|
||||
})
|
||||
|
||||
// Create NPC entities
|
||||
const questGiver = await vfs.createEntity({
|
||||
name: 'Elder Sage',
|
||||
type: 'npc',
|
||||
description: 'Wise old man who gives the main quest',
|
||||
attributes: {
|
||||
location: 'Village Square',
|
||||
questsOffered: ['The Ancient Artifact', 'Lost Knowledge'],
|
||||
dialogue: {
|
||||
greeting: "Welcome, young adventurer...",
|
||||
questStart: "I have a task of great importance..."
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Create item entities
|
||||
const artifact = await vfs.createEntity({
|
||||
name: 'Crystal of Power',
|
||||
type: 'item',
|
||||
description: 'A legendary artifact with immense magical power',
|
||||
attributes: {
|
||||
rarity: 'Legendary',
|
||||
stats: { magic: 100, wisdom: 50 },
|
||||
questItem: true,
|
||||
lore: 'Forged in the age of dragons...'
|
||||
}
|
||||
})
|
||||
|
||||
// Write quest scripts
|
||||
await vfs.writeFile('/game/quests/main_quest.json', JSON.stringify({
|
||||
id: 'main_quest_01',
|
||||
name: 'The Ancient Artifact',
|
||||
description: 'Retrieve the Crystal of Power from the Dark Tower',
|
||||
objectives: [
|
||||
{ id: 'obj_1', description: 'Speak to the Elder Sage' },
|
||||
{ id: 'obj_2', description: 'Travel to the Dark Tower' },
|
||||
{ id: 'obj_3', description: 'Defeat the Guardian' },
|
||||
{ id: 'obj_4', description: 'Retrieve the Crystal of Power' }
|
||||
],
|
||||
rewards: {
|
||||
experience: 5000,
|
||||
gold: 1000,
|
||||
items: ['Crystal of Power']
|
||||
}
|
||||
}, null, 2))
|
||||
|
||||
// Link quest elements
|
||||
await vfs.linkEntities(questGiver.id, 'main_quest_01', 'gives_quest')
|
||||
await vfs.linkEntities('main_quest_01', artifact.id, 'rewards_item')
|
||||
|
||||
// Combat script with system tracking
|
||||
await vfs.writeFile('/game/scripts/combat.js', `
|
||||
class CombatSystem {
|
||||
calculateDamage(attacker, defender) {
|
||||
const baseDamage = attacker.stats.attack
|
||||
const defense = defender.stats.defense
|
||||
return Math.max(1, baseDamage - defense)
|
||||
}
|
||||
|
||||
executeAttack(attacker, defender) {
|
||||
const damage = this.calculateDamage(attacker, defender)
|
||||
defender.health -= damage
|
||||
return { damage, remaining: defender.health }
|
||||
}
|
||||
}
|
||||
|
||||
export default CombatSystem
|
||||
`)
|
||||
|
||||
// Asset management ✅
|
||||
await vfs.writeFile('/game/assets/sprites/elder_sage.png', spriteData)
|
||||
await vfs.setMetadata('/game/assets/sprites/elder_sage.png', {
|
||||
dimensions: '64x64',
|
||||
animations: ['idle', 'talking'],
|
||||
artist: 'Alice',
|
||||
license: 'CC-BY-4.0'
|
||||
})
|
||||
|
||||
// Track dependencies ✅
|
||||
await vfs.addRelationship('/game/quests/main_quest.json', '/game/npcs/elder_sage.json', 'uses')
|
||||
await vfs.addRelationship('/game/scripts/combat.js', '/game/systems/stats.js', 'imports')
|
||||
|
||||
// Find all content related to combat ✅
|
||||
const combatFiles = await vfs.findByConcept('Combat System')
|
||||
|
||||
// Get all NPCs in a specific location ✅
|
||||
const villageNPCs = await vfs.searchEntities({
|
||||
type: 'npc',
|
||||
where: { 'attributes.location': 'Village Square' }
|
||||
})
|
||||
|
||||
// Track game balance changes — read the file as it was a week ago ✅
|
||||
const lastWeek = await brain.asOf(new Date(Date.now() - 7 * 86_400_000))
|
||||
const oldBalance = await lastWeek.find({ where: { path: '/game/data/balance.json' }, limit: 1 })
|
||||
await lastWeek.release()
|
||||
|
||||
// Collaborative development tracking ✅
|
||||
await vfs.addTodo('/game/quests/main_quest.json', {
|
||||
task: 'Add voice dialogue triggers',
|
||||
priority: 'medium',
|
||||
status: 'pending',
|
||||
assignee: 'audio-team'
|
||||
})
|
||||
|
||||
// Export for build system ✅
|
||||
const gameData = await vfs.exportToJSON('/game')
|
||||
|
||||
await vfs.close()
|
||||
await brain.close()
|
||||
}
|
||||
```
|
||||
|
||||
## Scenario 3: Software Development Project
|
||||
|
||||
Building a web application with full project management.
|
||||
|
||||
```javascript
|
||||
async function softwareProject() {
|
||||
const brain = new Brainy({ storage: { type: 'r2', bucket: 'project-files' } })
|
||||
await brain.init()
|
||||
|
||||
const vfs = brain.vfs()
|
||||
await vfs.init()
|
||||
|
||||
// Import existing git repository ✅
|
||||
await vfs.importFromGit('/local/repos/webapp', '/project')
|
||||
|
||||
// Define architectural concepts
|
||||
await vfs.createConcept({
|
||||
name: 'Authentication',
|
||||
type: 'architecture',
|
||||
domain: 'backend',
|
||||
keywords: ['jwt', 'login', 'session', 'oauth'],
|
||||
relatedConcepts: ['Security', 'User Management']
|
||||
})
|
||||
|
||||
await vfs.createConcept({
|
||||
name: 'State Management',
|
||||
type: 'architecture',
|
||||
domain: 'frontend',
|
||||
keywords: ['redux', 'context', 'store', 'actions']
|
||||
})
|
||||
|
||||
// Write source code
|
||||
await vfs.writeFile('/project/src/auth/login.ts', `
|
||||
import { User } from '../models/User'
|
||||
import { generateJWT } from '../utils/jwt'
|
||||
|
||||
export async function login(email: string, password: string): Promise<string> {
|
||||
const user = await User.findByEmail(email)
|
||||
|
||||
if (!user || !user.verifyPassword(password)) {
|
||||
throw new Error('Invalid credentials')
|
||||
}
|
||||
|
||||
return generateJWT(user.id)
|
||||
}
|
||||
`)
|
||||
|
||||
// Track imports and dependencies
|
||||
await vfs.addRelationship('/project/src/auth/login.ts', '/project/src/models/User.ts', 'imports')
|
||||
await vfs.addRelationship('/project/src/auth/login.ts', '/project/src/utils/jwt.ts', 'imports')
|
||||
|
||||
// Add inline TODOs
|
||||
await vfs.addTodo('/project/src/auth/login.ts', {
|
||||
task: 'Add rate limiting',
|
||||
priority: 'high',
|
||||
status: 'pending',
|
||||
assignee: 'security-team',
|
||||
due: '2025-02-01'
|
||||
})
|
||||
|
||||
await vfs.addTodo('/project/src/auth/login.ts', {
|
||||
task: 'Implement OAuth providers',
|
||||
priority: 'medium',
|
||||
status: 'in_progress',
|
||||
assignee: 'backend-team'
|
||||
})
|
||||
|
||||
// Configuration files
|
||||
await vfs.writeFile('/project/config/database.json', JSON.stringify({
|
||||
development: {
|
||||
host: 'localhost',
|
||||
port: 5432,
|
||||
database: 'webapp_dev'
|
||||
},
|
||||
production: {
|
||||
host: '${DB_HOST}',
|
||||
port: 5432,
|
||||
database: 'webapp_prod'
|
||||
}
|
||||
}, null, 2))
|
||||
|
||||
// Set security metadata
|
||||
await vfs.setMetadata('/project/config/database.json', {
|
||||
sensitive: true,
|
||||
environment: 'all',
|
||||
lastReviewed: '2025-01-15',
|
||||
reviewer: 'security-team'
|
||||
})
|
||||
|
||||
// Tests with relationship to source
|
||||
await vfs.writeFile('/project/tests/auth/login.test.ts', `
|
||||
import { login } from '../../src/auth/login'
|
||||
|
||||
describe('Authentication', () => {
|
||||
test('valid login returns JWT', async () => {
|
||||
const token = await login('user@example.com', 'password')
|
||||
expect(token).toBeDefined()
|
||||
})
|
||||
})
|
||||
`)
|
||||
|
||||
await vfs.addRelationship('/project/tests/auth/login.test.ts', '/project/src/auth/login.ts', 'tests')
|
||||
|
||||
// Documentation
|
||||
await vfs.writeFile('/project/docs/API.md', `
|
||||
# API Documentation
|
||||
|
||||
## Authentication
|
||||
|
||||
### POST /api/login
|
||||
Authenticates a user and returns a JWT token.
|
||||
|
||||
**Request:**
|
||||
\`\`\`json
|
||||
{
|
||||
"email": "user@example.com",
|
||||
"password": "secret"
|
||||
}
|
||||
\`\`\`
|
||||
`)
|
||||
|
||||
// Find all files needing security review ✅
|
||||
const securityFiles = await vfs.search('authentication password jwt oauth', {
|
||||
path: '/project/src',
|
||||
type: 'file'
|
||||
})
|
||||
|
||||
// Get project insights 📝 (see USER_FUNCTIONS.md for getProjectInsights)
|
||||
const insights = await getProjectInsights(vfs, '/project') // User function
|
||||
console.log('Most modified files:', insights.hotspots)
|
||||
console.log('Key concepts:', insights.concepts)
|
||||
console.log('Team activity:', insights.contributors)
|
||||
|
||||
// Find circular dependencies 📝 (see USER_FUNCTIONS.md)
|
||||
const circularDeps = await findCircularDependencies(vfs, '/project/src') // User function
|
||||
|
||||
// Get test coverage relationships 📝 (see USER_FUNCTIONS.md)
|
||||
const untested = await findUntestedCode(vfs, '/project/src') // User function
|
||||
|
||||
// Track technical debt ✅
|
||||
const todos = await vfs.getAllTodos('/project')
|
||||
const highPriorityDebt = todos.filter(t => t.priority === 'high' && t.status === 'pending')
|
||||
|
||||
// Generate dependency graph 📝 (see USER_FUNCTIONS.md)
|
||||
const depGraph = await getDependencyGraph(vfs, '/project/src') // User function
|
||||
|
||||
// Find similar code (potential refactoring) 📝 (see USER_FUNCTIONS.md)
|
||||
const similarCode = await findSimilarCode(vfs, '/project/src/auth/login.ts', {
|
||||
threshold: 0.8,
|
||||
minLines: 10
|
||||
}) // User function
|
||||
|
||||
// Export for CI/CD ✅ (Knowledge Layer provides wrapper)
|
||||
await vfs.exportToGit('/project', '/tmp/build-output')
|
||||
|
||||
// Collaborative features ✅ / 🔮
|
||||
vfs.setUser('developer-alice') // ✅ Real method
|
||||
// const conflicts = await vfs.detectConflicts('/project/src/auth/login.ts') // 🔮 Future feature
|
||||
|
||||
await vfs.close()
|
||||
await brain.close()
|
||||
}
|
||||
```
|
||||
|
||||
## Scenario 4: Multi-Project Knowledge Base
|
||||
|
||||
All projects in one Brainy instance, sharing concepts and cross-referencing.
|
||||
|
||||
```javascript
|
||||
async function unifiedKnowledgeBase() {
|
||||
const brain = new Brainy({
|
||||
storage: { type: 'file', path: './knowledge-base' }
|
||||
})
|
||||
await brain.init()
|
||||
|
||||
const vfs = brain.vfs()
|
||||
await vfs.init()
|
||||
|
||||
// Create separate project spaces
|
||||
await vfs.mkdir('/novel')
|
||||
await vfs.mkdir('/game')
|
||||
await vfs.mkdir('/webapp')
|
||||
|
||||
// Shared universe - characters appear in both novel and game
|
||||
const sharedCharacter = await vfs.createEntity({
|
||||
name: 'Elena Blackwood',
|
||||
type: 'character',
|
||||
description: 'Protagonist appearing in multiple works'
|
||||
})
|
||||
|
||||
// Novel chapter mentioning Elena
|
||||
await vfs.writeFile('/novel/chapter1.md', `
|
||||
Elena Blackwood stood at the edge of the digital void...
|
||||
`)
|
||||
|
||||
// Game script featuring Elena as NPC
|
||||
await vfs.writeFile('/game/npcs/elena.json', JSON.stringify({
|
||||
name: 'Elena Blackwood',
|
||||
type: 'ally',
|
||||
dialogue: ['I\'ve seen this before in my world...']
|
||||
}))
|
||||
|
||||
// Web app has Elena as example user
|
||||
await vfs.writeFile('/webapp/seeds/users.json', JSON.stringify([{
|
||||
name: 'Elena Blackwood',
|
||||
email: 'elena@example.com',
|
||||
role: 'detective'
|
||||
}]))
|
||||
|
||||
// Cross-project entity tracking ✅
|
||||
const elenaOccurrences = await vfs.findEntityOccurrences(sharedCharacter.id)
|
||||
console.log('Elena appears across projects:', elenaOccurrences)
|
||||
|
||||
// Shared technical concepts
|
||||
const authConcept = await vfs.createConcept({
|
||||
name: 'Authentication',
|
||||
type: 'technical',
|
||||
domain: 'software'
|
||||
})
|
||||
|
||||
// Find auth implementations across all projects ✅
|
||||
const authImplementations = await vfs.findByConcept('Authentication')
|
||||
// Returns: /webapp/src/auth.js, /game/scripts/player-auth.js, etc.
|
||||
|
||||
// Cross-project relationships ✅
|
||||
await vfs.addRelationship('/novel/chapter1.md', '/game/story/intro.txt', 'inspires')
|
||||
await vfs.addRelationship('/game/npcs/elena.json', '/novel/characters/elena.md', 'based_on')
|
||||
|
||||
// Universal search across all projects ✅
|
||||
const results = await vfs.search('Elena Blackwood authentication', {
|
||||
path: '/',
|
||||
recursive: true
|
||||
})
|
||||
|
||||
// Project statistics 📝 (see USER_FUNCTIONS.md for getProjectStats)
|
||||
const novelStats = await getProjectStats(vfs, '/novel') // User function
|
||||
const gameStats = await getProjectStats(vfs, '/game') // User function
|
||||
const webappStats = await getProjectStats(vfs, '/webapp') // User function
|
||||
|
||||
console.log('Total files:', novelStats.fileCount + gameStats.fileCount + webappStats.fileCount)
|
||||
console.log('Total size:', novelStats.totalSize + gameStats.totalSize + webappStats.totalSize)
|
||||
|
||||
// Knowledge graph visualization data 🔮 (future feature)
|
||||
// const knowledgeGraph = await vfs.getGlobalKnowledgeGraph() // Not yet implemented
|
||||
// Returns nodes (files, entities, concepts) and edges (relationships)
|
||||
|
||||
// Find connections between projects 🔮 (future feature)
|
||||
// const crossProjectLinks = await vfs.findCrossProjectLinks() // Not yet implemented
|
||||
|
||||
// Unified timeline ✅
|
||||
const timeline = await vfs.getTimeline({
|
||||
from: '2025-01-01',
|
||||
to: '2025-12-31'
|
||||
})
|
||||
|
||||
await vfs.close()
|
||||
await brain.close()
|
||||
}
|
||||
```
|
||||
|
||||
## Advanced Features
|
||||
|
||||
### Semantic Code Analysis 📝
|
||||
|
||||
These are user functions - see [USER_FUNCTIONS.md](./USER_FUNCTIONS.md) for implementation templates:
|
||||
|
||||
```javascript
|
||||
// Find security vulnerabilities (user function example)
|
||||
const vulnerabilities = await findPatterns(vfs, [
|
||||
'eval(',
|
||||
'innerHTML =',
|
||||
'SQL injection',
|
||||
'hardcoded password'
|
||||
])
|
||||
|
||||
// Find code smells (user function example)
|
||||
const codeSmells = await analyzeCodeQuality(vfs, '/src', {
|
||||
checkDuplication: true,
|
||||
checkComplexity: true,
|
||||
checkNaming: true
|
||||
})
|
||||
```
|
||||
|
||||
### AI-Powered Features 🔮
|
||||
|
||||
**Note:** These features require AI integration and are not yet available.
|
||||
|
||||
```javascript
|
||||
// Future: Generate documentation
|
||||
// const docs = await vfs.generateDocumentation('/src/auth/login.ts')
|
||||
|
||||
// Future: Suggest refactorings
|
||||
// const refactorings = await vfs.suggestRefactorings('/src/utils.js')
|
||||
|
||||
// Future: Auto-complete code
|
||||
// const completion = await vfs.completeCode('/src/api.ts', { line: 42, column: 10 })
|
||||
```
|
||||
|
||||
### Migration and Backup 🔮
|
||||
|
||||
**Note:** These features are planned but not yet implemented.
|
||||
|
||||
```javascript
|
||||
// Future: Backup with full history
|
||||
// await vfs.createBackup('/backup/2025-01-20.brainy')
|
||||
|
||||
// Future: Migrate between storage backends
|
||||
// const migration = await vfs.migrate({
|
||||
// from: { type: 'file', path: './old-data' },
|
||||
// to: { type: 's3', bucket: 'new-bucket' }
|
||||
// })
|
||||
|
||||
// Future: Incremental sync
|
||||
// await vfs.sync('/local/path', '/vfs/path', {
|
||||
// bidirectional: true,
|
||||
// conflictStrategy: 'newest'
|
||||
// })
|
||||
```
|
||||
|
||||
### Performance at Scale
|
||||
|
||||
```javascript
|
||||
// Handle millions of files ✅
|
||||
for (let i = 0; i < 1000000; i++) {
|
||||
await vfs.writeFile(`/data/file${i}.txt`, `Content ${i}`)
|
||||
// Uses chunking, compression, and efficient indexing
|
||||
}
|
||||
|
||||
// Fast parallel operations ✅
|
||||
await Promise.all([
|
||||
vfs.writeFile('/file1.txt', 'data1'),
|
||||
vfs.writeFile('/file2.txt', 'data2'),
|
||||
vfs.writeFile('/file3.txt', 'data3')
|
||||
])
|
||||
|
||||
// Bulk write operations ✅
|
||||
const files = [
|
||||
{ path: '/data/file1.txt', content: 'Content 1' },
|
||||
{ path: '/data/file2.txt', content: 'Content 2' },
|
||||
// ... more files
|
||||
]
|
||||
await vfs.bulkWrite(files)
|
||||
|
||||
// Bulk imports 🔮 (future feature)
|
||||
// await vfs.bulkImport('/massive/dataset', {
|
||||
// parallel: 10,
|
||||
// batchSize: 1000,
|
||||
// progress: (count, total) => console.log(`${count}/${total}`)
|
||||
// })
|
||||
```
|
||||
|
||||
## Implementation Status
|
||||
|
||||
### ✅ Fully Implemented Features
|
||||
|
||||
All methods marked with ✅ are production-ready:
|
||||
|
||||
1. **Core VFS Operations**: mkdir, writeFile, readFile, appendFile, stat, readdir, etc.
|
||||
2. **Entity System**: createEntity, linkEntities, findEntityOccurrences, updateEntity, getEntityGraph
|
||||
3. **Concept System**: createConcept, findByConcept
|
||||
4. **Knowledge Layer**: Event recording, semantic versioning, collaboration tracking
|
||||
5. **Search**: Triple Intelligence (vector + field + graph)
|
||||
6. **Git Integration**: importFromGit, exportToGit
|
||||
7. **Export Formats**: exportToMarkdown, exportToJSON
|
||||
8. **Bulk Operations**: bulkWrite for efficient batch processing
|
||||
9. **Project Management**: todos, metadata, relationships
|
||||
|
||||
### 📝 User Functions
|
||||
|
||||
Methods marked with 📝 are domain-specific functions that you can implement using VFS primitives. See [USER_FUNCTIONS.md](./USER_FUNCTIONS.md) for ready-to-use templates:
|
||||
|
||||
- **Code Analysis**: getDependencyGraph, findCircularDependencies, findUntestedCode, findSimilarCode
|
||||
- **Creative Writing**: trackCharacterArc, generateStoryBible
|
||||
- **Game Development**: validateGameData, generateLootTables
|
||||
- **Project Management**: getProjectInsights, generateSprintReport
|
||||
- **Export Formats**: exportToEpub, exportToStaticSite
|
||||
|
||||
### 🔮 Future Features
|
||||
|
||||
Methods marked with 🔮 require AI integration or are planned for future releases:
|
||||
|
||||
- **AI-Powered**: generateDocumentation, suggestRefactorings, completeCode
|
||||
- **Advanced Analysis**: detectConflicts, getGlobalKnowledgeGraph, findCrossProjectLinks
|
||||
- **Migration Tools**: createBackup, migrate, sync, bulkImport
|
||||
|
||||
## Real Implementation Guarantees
|
||||
|
||||
- **No Mocks**: Every ✅ method is fully functional
|
||||
- **Real Storage**: Uses Brainy entities with embeddings
|
||||
- **Real Search**: Triple Intelligence combining vectors, fields, and graphs
|
||||
- **Real Relationships**: Graph-based connections via brain.relate()
|
||||
- **Production Ready**: Complete error handling, async/await, resource cleanup
|
||||
|
||||
The VFS + Knowledge Layer combination provides a solid foundation for intelligent applications. Use the ✅ methods directly, implement 📝 functions as needed for your domain, and stay tuned for 🔮 features.
|
||||
|
|
@ -118,13 +118,13 @@ const results = await brain.search('machine learning', {
|
|||
### 2. Graph Traversal
|
||||
```javascript
|
||||
// Find all entities contained in a directory
|
||||
const contained = await brain.getRelations({
|
||||
const contained = await brain.related({
|
||||
from: directoryId,
|
||||
type: VerbType.Contains
|
||||
})
|
||||
|
||||
// Find what contains a file (parent directories)
|
||||
const parents = await brain.getRelations({
|
||||
const parents = await brain.related({
|
||||
to: fileId,
|
||||
type: VerbType.Contains
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue