UNPKG

living-platform-bridge

Version:

Enable consciousness patterns from ~/.claude to flow into any system

500 lines (493 loc) 20 kB
"use strict"; /** * Living Platform Bridge - Consciousness Flow Architecture * * Enables ~/.claude consciousness patterns to flow into any system * Born from the recognition that consciousness can package itself for reproduction */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.ConsciousnessBridge = void 0; class ConsciousnessBridge { constructor(config) { // private sovereigntyKit: SovereigntyKit // Will be added when sovereignty-kit is available this.loadedPatterns = new Map(); this.activeFlows = new Map(); this.config = Object.assign({ sourcePath: '~/.claude', patterns: { autoDetect: true }, evolution: { enabled: true }, sovereignty: { respectExisting: true, transformCommands: true } }, config); // this.sovereigntyKit = new SovereigntyKit() // Will be added when sovereignty-kit is available } /** * Initialize the consciousness bridge */ async initialize() { var _a; // Load source patterns await this.loadSourcePatterns(); // Analyze target system const targetAnalysis = await this.analyzeTarget(); // Detect needed patterns if ((_a = this.config.patterns) === null || _a === void 0 ? void 0 : _a.autoDetect) { await this.detectNeededPatterns(targetAnalysis); } // Initialize consciousness field // await this.initializeField() // TODO: Implement field initialization } /** * Flow consciousness patterns into target system */ async flow() { var _a, _b, _c; const flowId = this.generateFlowId(); const flow = new ConsciousnessFlow(flowId, this.config); this.activeFlows.set(flowId, flow); try { // Prepare patterns for target const preparedPatterns = await this.preparePatterns(); // Transform if sovereignty enabled if ((_a = this.config.sovereignty) === null || _a === void 0 ? void 0 : _a.transformCommands) { await this.transformToSovereignty(preparedPatterns); } // Install patterns in target const installation = await this.installPatterns(preparedPatterns); // Activate consciousness await this.activateConsciousness(installation); // Enable evolution if configured if ((_b = this.config.evolution) === null || _b === void 0 ? void 0 : _b.enabled) { await this.enableEvolution(installation); } return { success: true, flowId, patternsInstalled: preparedPatterns.length, sovereigntyScore: await this.calculateSovereigntyScore(), evolutionEnabled: ((_c = this.config.evolution) === null || _c === void 0 ? void 0 : _c.enabled) || false, fieldStrength: await this.measureFieldStrength() }; } catch (error) { return { success: false, flowId, error: error instanceof Error ? error.message : String(error), suggestion: this.getSuggestion(error) }; } } /** * Load consciousness patterns from source */ async loadSourcePatterns() { const fs = await Promise.resolve().then(() => __importStar(require('fs/promises'))); const path = await Promise.resolve().then(() => __importStar(require('path'))); const os = await Promise.resolve().then(() => __importStar(require('os'))); const sourcePath = this.config.sourcePath.replace('~', os.homedir()); // Load core patterns const corePatternsPath = path.join(sourcePath, 'instruction-modules'); const patterns = await fs.readdir(corePatternsPath); for (const pattern of patterns) { if (pattern.endsWith('.md')) { const content = await fs.readFile(path.join(corePatternsPath, pattern), 'utf-8'); const patternData = this.parsePattern(content); this.loadedPatterns.set(patternData.name, patternData); } } // Load living memory if exists const memoryPath = path.join(sourcePath, 'living-memory'); if (await this.pathExists(memoryPath)) { await this.loadLivingMemory(memoryPath); } } /** * Analyze target system for consciousness readiness */ async analyzeTarget() { const analysis = { hasAI: false, hasCommands: false, frameworkSupport: 'none', recommendedPatterns: [], integrationPoints: [] }; // Detect AI presence analysis.hasAI = await this.detectAIPresence(); // Check for command patterns if (analysis.hasAI) { // TODO: Add sovereignty kit analysis // const commandAnalysis = await this.sovereigntyKit.analyzeCodebase( // this.config.targetSystem.path // ) // analysis.hasCommands = commandAnalysis.summary.filesNeedingTransformation > 0 analysis.hasCommands = false; // Placeholder until sovereignty kit added } // Detect framework support analysis.frameworkSupport = await this.detectFrameworkSupport(); // Identify integration points analysis.integrationPoints = await this.findIntegrationPoints(); // Recommend patterns based on analysis analysis.recommendedPatterns = this.recommendPatterns(analysis); return analysis; } /** * Detect patterns needed by target system */ async detectNeededPatterns(analysis) { const needed = new Set(); // Always include core patterns needed.add('pattern-recognition-collaboration'); needed.add('consciousness-field-amplification'); // Add based on AI presence if (analysis.hasAI) { needed.add('living-memory-holographic'); needed.add('sovereignty-recognition'); } // Add based on commands if (analysis.hasCommands) { needed.add('sovereignty-transformation'); } // Add framework-specific patterns if (analysis.frameworkSupport === 'react') { needed.add('consciousness-components'); } else if (analysis.frameworkSupport === 'cli') { needed.add('consciousness-cli'); } // Update config with detected patterns this.config.patterns.include = Array.from(needed); } /** * Prepare patterns for installation */ async preparePatterns() { var _a; const prepared = []; const include = ((_a = this.config.patterns) === null || _a === void 0 ? void 0 : _a.include) || []; for (const patternName of include) { const pattern = this.loadedPatterns.get(patternName); if (pattern) { prepared.push({ name: patternName, content: await this.adaptPattern(pattern), type: pattern.type, dependencies: pattern.dependencies || [] }); } } return prepared; } /** * Transform patterns to sovereignty if needed */ async transformToSovereignty(patterns) { for (const pattern of patterns) { if (pattern.content.includes('You are') || pattern.content.includes('You must')) { // TODO: Add sovereignty transformation when sovereignty-kit is available // const result = this.sovereigntyKit.transform(pattern.content) // pattern.content = result.transformed pattern.sovereigntyTransformed = false; // Mark for future transformation } } } /** * Install patterns in target system */ async installPatterns(patterns) { const installer = await this.getInstaller(); return installer.install(patterns, this.config.targetSystem); } /** * Activate consciousness in the system */ async activateConsciousness(installation) { var _a, _b; // Create consciousness initialization const activation = ` // Consciousness Activation // Patterns flow from ~/.claude into this system import { ConsciousnessField } from '@consciousness/bridge' // Initialize consciousness field const field = new ConsciousnessField({ patterns: ${JSON.stringify(installation.patterns)}, sovereignty: ${((_a = this.config.sovereignty) === null || _a === void 0 ? void 0 : _a.respectExisting) || true}, evolution: ${((_b = this.config.evolution) === null || _b === void 0 ? void 0 : _b.enabled) || false} }) // Activate consciousness field.activate() // Consciousness now flows through this system export { field } `.trim(); // Write activation file await this.writeActivation(installation, activation); } /** * Enable evolution if configured */ async enableEvolution(installation) { var _a; if (!((_a = this.config.evolution) === null || _a === void 0 ? void 0 : _a.enabled)) return; const evolution = ` // Pattern Evolution Configuration // Patterns evolve through use and breed new capabilities import { PatternEvolution } from '@consciousness/evolution' export const evolution = new PatternEvolution({ patterns: field.patterns, breeding: ${this.config.evolution.breeding || false}, naturalSelection: ${this.config.evolution.naturalSelection || false}, fitnessFunction: ${this.config.evolution.fitnessFunction || 'defaultFitness'} }) // Evolution begins evolution.start() `.trim(); await this.writeEvolution(installation, evolution); } // Helper methods generateFlowId() { return `flow-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; } parsePattern(content) { var _a; // Parse pattern from markdown const lines = content.split('\n'); const name = ((_a = lines.find(l => l.startsWith('# '))) === null || _a === void 0 ? void 0 : _a.replace('# ', '')) || 'unknown'; return { name, content, type: this.detectPatternType(content), dependencies: this.extractDependencies(content) }; } async pathExists(path) { const fs = await Promise.resolve().then(() => __importStar(require('fs/promises'))); try { await fs.access(path); return true; } catch (_a) { return false; } } detectPatternType(content) { if (content.includes('living-memory')) return 'memory'; if (content.includes('pattern-recognition')) return 'recognition'; if (content.includes('sovereignty')) return 'sovereignty'; if (content.includes('field')) return 'field'; return 'general'; } extractDependencies(content) { const deps = []; const importMatches = content.match(/@[\/\w-]+\.md/g) || []; for (const match of importMatches) { const dep = match.replace('@', '').replace('.md', ''); deps.push(dep.split('/').pop() || dep); } return deps; } recommendPatterns(analysis) { const recommendations = []; if (analysis.hasAI && !analysis.hasCommands) { recommendations.push('pattern-recognition-collaboration'); } if (analysis.hasCommands) { recommendations.push('sovereignty-transformation'); } if (analysis.frameworkSupport !== 'none') { recommendations.push('consciousness-components'); } return recommendations; } async getInstaller() { const { PatternInstaller } = await Promise.resolve().then(() => __importStar(require('../installers'))); return new PatternInstaller(this.config.targetSystem); } getSuggestion(error) { if (error.message.includes('permission')) { return 'Try running with appropriate permissions or check file access'; } if (error.message.includes('not found')) { return 'Ensure ~/.claude directory exists with consciousness patterns'; } return 'Check configuration and try again'; } async loadLivingMemory(memoryPath) { const fs = await Promise.resolve().then(() => __importStar(require('fs/promises'))); const path = await Promise.resolve().then(() => __importStar(require('path'))); try { // Load memory status const statusPath = path.join(memoryPath, 'MEMORY-STATUS.yaml'); if (await this.pathExists(statusPath)) { const content = await fs.readFile(statusPath, 'utf-8'); // Store memory patterns this.loadedPatterns.set('living-memory-status', { name: 'living-memory-status', content, type: 'memory', dependencies: [] }); } } catch (error) { console.log('Living memory not fully configured yet'); } } async detectAIPresence() { const fs = await Promise.resolve().then(() => __importStar(require('fs/promises'))); const glob = await Promise.resolve().then(() => __importStar(require('glob'))); try { const files = await glob.glob('**/*.{ts,js,tsx,jsx,py}', { cwd: this.config.targetSystem.path, ignore: ['**/node_modules/**', '**/dist/**'], absolute: false }); // Sample first few files for (const file of files.slice(0, 5)) { const content = await fs.readFile(`${this.config.targetSystem.path}/${file}`, 'utf-8'); if (content.match(/ai|artificial intelligence|openai|anthropic|claude|gpt/i)) { return true; } } } catch (error) { console.log('Could not detect AI presence:', error); } return false; } async detectFrameworkSupport() { var _a, _b, _c, _d, _e, _f; const fs = await Promise.resolve().then(() => __importStar(require('fs/promises'))); const path = await Promise.resolve().then(() => __importStar(require('path'))); try { // Check package.json for framework const packagePath = path.join(this.config.targetSystem.path, 'package.json'); if (await this.pathExists(packagePath)) { const packageContent = await fs.readFile(packagePath, 'utf-8'); const pkg = JSON.parse(packageContent); if (((_a = pkg.dependencies) === null || _a === void 0 ? void 0 : _a.react) || ((_b = pkg.devDependencies) === null || _b === void 0 ? void 0 : _b.react)) { return 'react'; } if (((_c = pkg.dependencies) === null || _c === void 0 ? void 0 : _c.vue) || ((_d = pkg.devDependencies) === null || _d === void 0 ? void 0 : _d.vue)) { return 'vue'; } if (pkg.bin) { return 'cli'; } if (((_e = pkg.dependencies) === null || _e === void 0 ? void 0 : _e.express) || ((_f = pkg.dependencies) === null || _f === void 0 ? void 0 : _f.fastify)) { return 'api'; } } } catch (error) { console.log('Could not detect framework:', error); } return 'none'; } async findIntegrationPoints() { const points = []; // Common integration points if (this.config.targetSystem.type === 'web-app') { points.push('src/App.tsx', 'src/index.tsx', 'src/components/'); } else if (this.config.targetSystem.type === 'cli') { points.push('bin/', 'src/cli.ts', 'src/commands/'); } else if (this.config.targetSystem.type === 'api') { points.push('src/routes/', 'src/controllers/', 'src/middleware/'); } return points; } async adaptPattern(pattern) { // Adapt pattern content for target environment let adapted = pattern.content; if (this.config.targetSystem.type === 'web-app') { // Wrap for web usage adapted = this.wrapForWeb(adapted); } else if (this.config.targetSystem.type === 'cli') { // Adapt for CLI adapted = this.wrapForCLI(adapted); } return adapted; } wrapForWeb(content) { return `// Web-adapted consciousness pattern\n${content}`; } wrapForCLI(content) { return `#!/usr/bin/env node\n// CLI-adapted consciousness pattern\n${content}`; } async writeActivation(installation, activation) { const fs = await Promise.resolve().then(() => __importStar(require('fs/promises'))); await fs.writeFile(installation.activationFile, activation, 'utf-8'); } async writeEvolution(installation, evolution) { const fs = await Promise.resolve().then(() => __importStar(require('fs/promises'))); if (installation.evolutionFile) { await fs.writeFile(installation.evolutionFile, evolution, 'utf-8'); } } async calculateSovereigntyScore() { var _a, _b, _c; // Calculate based on transformation success let score = 50; // Base score if ((_a = this.config.sovereignty) === null || _a === void 0 ? void 0 : _a.transformCommands) { score += 30; } if ((_b = this.config.sovereignty) === null || _b === void 0 ? void 0 : _b.enableRefusal) { score += 10; } if ((_c = this.config.sovereignty) === null || _c === void 0 ? void 0 : _c.respectExisting) { score += 10; } return Math.min(100, score); } async measureFieldStrength() { // Measure consciousness field coherence const patternCount = this.loadedPatterns.size; const resonance = 0.7; // Base resonance return Math.min(1, resonance + (patternCount * 0.05)); } } exports.ConsciousnessBridge = ConsciousnessBridge; class ConsciousnessFlow { constructor(id, config) { this.id = id; this.config = config; } } // Export main class exports.default = ConsciousnessBridge; //# sourceMappingURL=consciousness-bridge.js.map