#!/usr/bin/env node
import { fileURLToPath as __fileURLToPath } from 'url';
import { dirname as __pathDirname } from 'path';
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __pathDirname(__filename);
import { RalphStackMemoryBridge } from "./bridge/ralph-stackmemory-bridge.js";
class RalphIntegrationDemo {
  bridge;
  constructor() {
    const config = {
      contextBudget: {
        maxTokens: 2e3,
        // Smaller budget for demo
        compressionEnabled: true,
        adaptiveBudgeting: true
      },
      performance: {
        asyncSaves: true,
        batchSize: 5,
        compressionLevel: 1,
        cacheEnabled: true
      },
      lifecycle: {
        checkpoints: {
          enabled: true,
          frequency: 3,
          // Checkpoint every 3 iterations
          retentionDays: 1
          // Short retention for demo
        }
      }
    };
    this.bridge = new RalphStackMemoryBridge({
      config,
      debug: true
    });
  }
  /**
   * Run the integration demo
   */
  async run() {
    console.log("\n\u{1F916} Ralph-StackMemory Integration Demo\n");
    try {
      await this.demonstrateInitialization();
      await this.demonstrateIterations();
      await this.demonstrateRecovery();
      await this.demonstrateMetrics();
      console.log("\n\u2705 Demo completed successfully!\n");
    } catch (error) {
      console.error("\n\u274C Demo failed:", error.message);
      throw error;
    } finally {
      await this.cleanup();
    }
  }
  /**
   * Demonstrate initialization
   */
  async demonstrateInitialization() {
    console.log("\u{1F4CB} Phase 1: Initialization");
    console.log("==========================");
    await this.bridge.initialize();
    const task = "Implement user authentication system with JWT";
    const criteria = [
      "- User registration endpoint working",
      "- Login endpoint returns JWT token",
      "- Protected routes validate JWT",
      "- Password hashing implemented",
      "- Tests pass with >80% coverage"
    ].join("\n");
    const loopState = await this.bridge.createNewLoop(task, criteria);
    console.log(`\u2713 Created Ralph loop: ${loopState.loopId}`);
    console.log(`\u2713 Task: ${task.substring(0, 50)}...`);
    console.log(`\u2713 Status: ${loopState.status}`);
    console.log(`\u2713 Iteration: ${loopState.iteration}`);
    console.log();
  }
  /**
   * Demonstrate iterations with context management
   */
  async demonstrateIterations() {
    console.log("\u{1F504} Phase 2: Iteration Management");
    console.log("=================================");
    const maxIterations = 5;
    for (let i = 0; i < maxIterations; i++) {
      console.log(`
--- Iteration ${i + 1} ---`);
      console.log("\u{1F527} Running worker iteration...");
      const iteration = await this.bridge.runWorkerIteration();
      console.log(`\u2713 Analysis: ${iteration.analysis.filesCount} files, tests ${iteration.analysis.testsPass ? "pass" : "fail"}`);
      console.log(`\u2713 Plan: ${iteration.plan.summary}`);
      console.log(`\u2713 Changes: ${iteration.changes.length} modifications`);
      console.log(`\u2713 Validation: ${iteration.validation.testsPass ? "pass" : "fail"}`);
      console.log("\u{1F440} Running reviewer iteration...");
      const review = await this.bridge.runReviewerIteration();
      if (review.complete) {
        console.log("\u{1F389} Task completed!");
        break;
      } else {
        console.log(`\u{1F4DD} Feedback: ${review.feedback?.substring(0, 100)}...`);
      }
      const usage = this.bridge.getPerformanceMetrics();
      console.log(`\u{1F4CA} Token usage: ${usage.tokenCount} / Context load: ${usage.contextLoadTime}ms`);
      if ((i + 1) % 3 === 0) {
        console.log("\u{1F4BE} Creating checkpoint...");
        const checkpoint = await this.bridge.createCheckpoint();
        console.log(`\u2713 Checkpoint: ${checkpoint.id}`);
      }
      await new Promise((resolve) => setTimeout(resolve, 1e3));
    }
  }
  /**
   * Demonstrate crash recovery
   */
  async demonstrateRecovery() {
    console.log("\n\u{1F691} Phase 3: Crash Recovery");
    console.log("===========================");
    const sessionId = "demo-session-123";
    try {
      console.log("\u{1F504} Simulating session rehydration...");
      console.log("\u2713 Loading context from StackMemory...");
      console.log("\u2713 Reconciling state from git, files, and memory...");
      console.log("\u2713 Applying context budget constraints...");
      console.log("\u2713 Resuming from last iteration...");
      console.log("\u{1F4C8} Recovery successful!");
      console.log("  - Context loaded: 2.1s");
      console.log("  - State reconciled: 0.3s");
      console.log("  - Memory usage: 45MB");
      console.log("  - Cache hit rate: 78%");
    } catch (error) {
      console.log(`\u26A0\uFE0F  Recovery simulation: ${error.message}`);
    }
  }
  /**
   * Demonstrate performance metrics
   */
  async demonstrateMetrics() {
    console.log("\n\u{1F4CA} Phase 4: Performance Metrics");
    console.log("================================");
    const metrics = this.bridge.getPerformanceMetrics();
    console.log("Performance Summary:");
    console.log(`  Iteration Time: ${metrics.iterationTime}ms avg`);
    console.log(`  Context Load Time: ${metrics.contextLoadTime}ms avg`);
    console.log(`  State Save Time: ${metrics.stateSaveTime}ms avg`);
    console.log(`  Memory Usage: ${Math.round(metrics.memoryUsage / 1024 / 1024)}MB`);
    console.log(`  Token Count: ${metrics.tokenCount}`);
    console.log(`  Cache Hit Rate: ${Math.round(metrics.cacheHitRate * 100)}%`);
    console.log("\nOptimization Features:");
    console.log("  \u2713 Async frame saves with batching");
    console.log("  \u2713 Context compression and budget management");
    console.log("  \u2713 State reconciliation with conflict resolution");
    console.log("  \u2713 Lifecycle hooks for clean integration");
    console.log("  \u2713 Checkpoint-based recovery");
  }
  /**
   * Cleanup resources
   */
  async cleanup() {
    console.log("\n\u{1F9F9} Cleaning up...");
    await this.bridge.cleanup();
    console.log("\u2713 Resources cleaned up");
  }
}
async function main() {
  const demo = new RalphIntegrationDemo();
  try {
    await demo.run();
  } catch (error) {
    console.error("Demo failed:", error.message);
    if (process.env.DEBUG) {
      console.error(error.stack);
    }
    process.exit(1);
  }
}
if (import.meta.url === `file://${process.argv[1]}`) {
  main().catch(console.error);
}
export {
  RalphIntegrationDemo
};
//# sourceMappingURL=ralph-integration-demo.js.map
