faf-cli
Version: 
š½ TURBO-CAT: The Rapid Catalytic Converter ⢠Project DNA ⨠for ANY AI ⢠Fully Integrated with React, Next.js, Svelte, TypeScript, Vite & n8n ⢠FREE FOREVER ⢠10,000+ developers ⢠Championship Edition
317 lines ⢠12.2 kB
JavaScript
;
/**
 * Smart FAF Command Logic
 * Contextually aware command that adapts based on project state
 *
 * Flow:
 * 1. No .faf ā auto (create)
 * 2. Score < 99 ā enhance (boost)
 * 3. Still < 99 ā chat (interactive)
 * 4. Score 99-100 ā bi-sync (maintain)
 * 5. Already perfect ā status/commit
 */
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 });
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const child_process_1 = require("child_process");
class SmartFaf {
    stateFile = '.faf-state.json';
    fafFile = '.faf';
    /**
     * Main entry point - smart contextual command
     */
    async execute() {
        // CRITICAL: Check if we're in home or root directory
        const currentDir = process.cwd();
        const homeDir = require('os').homedir();
        if (currentDir === homeDir || currentDir === '/') {
            console.log('\nā ļø  For speed and safety, we do not work on ROOT directories.');
            console.log('Please provide or cd my-project\n');
            return;
        }
        const state = this.getState();
        console.log('šļø FAF Smart Mode Engaged...\n');
        // Decision tree based on current state
        if (!state.exists) {
            this.runCommand('auto', 'Creating your .faf file...');
            return;
        }
        // Check current score
        if (state.score >= 99) {
            if (!state.synced) {
                this.runCommand('bi-sync', 'š Perfect score! Syncing with CLAUDE.md...');
                this.updateState({ synced: true });
                // After bi-sync, suggest commit
                this.displayChampionshipScore(99);
                console.log('ā Run: faf commit');
                console.log('   Lock in this excellence forever\n');
                return;
            }
            else if (!state.locked) {
                // They've synced but haven't committed - remind them
                this.suggestCommit(state);
                return;
            }
            else {
                this.showStatus(state);
            }
            return;
        }
        // Score < 99 - Progressive enhancement
        if (!state.lastEnhanced) {
            this.runCommand('enhance', `š Boosting from ${state.score}%...`);
            this.updateState({ lastEnhanced: true });
            // Re-check score after enhance
            const newScore = this.getCurrentScore();
            if (newScore >= 99) {
                console.log(`\nšÆ Achieved ${newScore}%! You're done!`);
                this.updateState({ score: newScore });
            }
            else {
                console.log(`\nš Now at ${newScore}%. Run 'faf' again or 'faf chat' for help.`);
                this.updateState({ score: newScore });
            }
            return;
        }
        if (!state.lastChatted) {
            console.log(`š Current score: ${state.score}%`);
            console.log('\nšÆ Getting to 99% requires some human context.');
            console.log('\nOptions:');
            console.log('  1. faf chat    ā Let me ask you questions (recommended)');
            console.log('  2. faf index   ā See all commands and drive yourself');
            console.log('  3. faf score --details ā See what\'s missing\n');
            this.updateState({ lastChatted: true });
            return;
        }
        // User has tried everything, show escape routes
        this.showEscapeRoutes(state);
    }
    /**
     * Get current FAF state from file and system
     */
    getState() {
        const exists = fs.existsSync(this.fafFile);
        if (!exists) {
            return {
                exists: false,
                score: 0,
                lastEnhanced: false,
                lastChatted: false,
                synced: false,
                locked: false
            };
        }
        // Load saved state
        let savedState = {};
        if (fs.existsSync(this.stateFile)) {
            try {
                savedState = JSON.parse(fs.readFileSync(this.stateFile, 'utf-8'));
            }
            catch (e) {
                // State file corrupted, start fresh
            }
        }
        // Check if context is committed (locked)
        let isLocked = savedState.locked || false;
        if (fs.existsSync(this.fafFile)) {
            const fafContent = fs.readFileSync(this.fafFile, 'utf-8');
            if (fafContent.includes('excellence_locked: true')) {
                isLocked = true;
            }
        }
        return {
            exists: true,
            score: this.getCurrentScore(),
            lastEnhanced: savedState.lastEnhanced || false,
            lastChatted: savedState.lastChatted || false,
            synced: savedState.synced || false,
            locked: isLocked
        };
    }
    /**
     * Get current FAF score by parsing .faf file
     */
    getCurrentScore() {
        if (!fs.existsSync(this.fafFile))
            return 0;
        try {
            const content = fs.readFileSync(this.fafFile, 'utf-8');
            const scoreMatch = content.match(/ai_score:\s*(\d+)%?/);
            if (scoreMatch) {
                return parseInt(scoreMatch[1]);
            }
            // Fallback: run score command and parse output
            const cliPath = path.join(__dirname, 'cli.js');
            const output = (0, child_process_1.execSync)(`node "${cliPath}" score`, {
                encoding: 'utf-8',
                cwd: process.cwd(),
                stdio: ['pipe', 'pipe', 'pipe']
            });
            const outputMatch = output.match(/Score:\s*(\d+)/);
            if (outputMatch) {
                return parseInt(outputMatch[1]);
            }
        }
        catch (e) {
            // Error getting score, assume needs improvement
            return 50;
        }
        return 50; // Default middle score
    }
    /**
     * Update state file
     */
    updateState(updates) {
        let state = {};
        if (fs.existsSync(this.stateFile)) {
            try {
                state = JSON.parse(fs.readFileSync(this.stateFile, 'utf-8'));
            }
            catch (e) {
                // Start fresh if corrupted
            }
        }
        state = { ...state, ...updates };
        fs.writeFileSync(this.stateFile, JSON.stringify(state, null, 2));
    }
    /**
     * Run a FAF command
     */
    runCommand(command, message) {
        console.log(message);
        console.log('ā'.repeat(50) + '\n');
        try {
            (0, child_process_1.execSync)(`faf ${command}`, { stdio: 'inherit' });
        }
        catch (e) {
            console.error(`\nā Command failed. Try 'faf ${command}' directly.`);
        }
    }
    /**
     * Show current status for perfect score
     */
    showStatus(state) {
        console.log('š FAF Status: PERFECT\n');
        console.log(`ā
 Score: ${state.score}%`);
        console.log('ā
 Synced with CLAUDE.md');
        if (state.locked) {
            console.log('ā
 Context locked');
        }
        console.log('\nšÆ Your AI understands everything!');
        console.log('\nMaintenance commands:');
        console.log('  ⢠faf watch    ā Auto-sync on changes');
        console.log('  ⢠faf trust    ā Verify integrity');
        console.log('  ⢠faf share    ā Share with others');
    }
    /**
     * Show escape routes when stuck
     */
    showEscapeRoutes(state) {
        console.log(`š Still at ${state.score}%\n`);
        console.log('šŖ Escape Routes:\n');
        console.log('  š° faf chat         ā Interactive mode (easy)');
        console.log('  šļø  faf index        ā See all 30+ commands');
        console.log('  š faf score --fix  ā Auto-fix missing items');
        console.log('  š faf edit         ā Manual edit .faf file');
        console.log('  š faf reset        ā Start over fresh\n');
        console.log('š” Tip: Most users reach 99% with "faf chat"');
    }
    /**
     * Display championship score with ASCII art
     */
    displayChampionshipScore(score) {
        console.log();
        console.log('āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā');
        console.log('ā       š CHAMPIONSHIP SCORE š      ā');
        console.log('ā āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā£');
        console.log(`ā              ${score >= 99 ? 'ā' : '  '} ${String(score).padStart(3)}% ${score >= 99 ? 'ā' : '  '}             ā`);
        console.log('ā āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā£');
        if (score >= 99) {
            console.log('ā     šÆ PERFECT AI READINESS! šÆ    ā');
            console.log('ā        You are at POLE POSITION!   ā');
        }
        else if (score >= 85) {
            console.log('ā      ⨠EXCELLENT PROGRESS! ⨠    ā');
            console.log('ā         Championship level!        ā');
        }
        else if (score >= 70) {
            console.log('ā       š GOOD PROGRESS! š         ā');
            console.log('ā        Keep pushing forward!       ā');
        }
        else {
            console.log('ā       š± GROWING STRONG! š±        ā');
            console.log('ā         Room to improve!           ā');
        }
        console.log('āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā');
        console.log();
    }
    /**
     * Suggest commit when at 99% but not locked
     */
    suggestCommit(state) {
        this.displayChampionshipScore(state.score);
        console.log('Your AI context is perfect, but not locked in.\n');
        console.log('ā Run: faf commit');
        console.log('   Lock in this excellence forever');
        console.log('   (Your context will never degrade)\n');
        console.log('Or continue with:');
        console.log('  ⢠faf bi-sync  ā Keep files synchronized');
        console.log('  ⢠faf status   ā See current state');
    }
    /**
     * Reset state for fresh start
     */
    resetState() {
        if (fs.existsSync(this.stateFile)) {
            fs.unlinkSync(this.stateFile);
        }
        console.log('š State reset. Run "faf" to start fresh.');
    }
}
// Export for CLI integration
exports.default = SmartFaf;
// Direct execution support
if (require.main === module) {
    const smartFaf = new SmartFaf();
    // Check for reset flag
    if (process.argv.includes('--reset')) {
        smartFaf.resetState();
    }
    else {
        smartFaf.execute().catch(console.error);
    }
}
//# sourceMappingURL=smart-faf.js.map