@stackmemoryai/stackmemory 0.4.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/commands/ralph.js +122 -45
- package/dist/cli/commands/ralph.js.map +2 -2
- package/dist/features/tui/simple-monitor.js +112 -0
- package/dist/features/tui/simple-monitor.js.map +7 -0
- package/dist/features/tui/swarm-monitor.js +185 -29
- package/dist/features/tui/swarm-monitor.js.map +2 -2
- package/dist/integrations/ralph/bridge/ralph-stackmemory-bridge.js +253 -24
- package/dist/integrations/ralph/bridge/ralph-stackmemory-bridge.js.map +3 -3
- package/package.json +1 -1
- package/scripts/test-ralph-iteration-fix.ts +118 -0
- package/scripts/test-simple-ralph-state-sync.ts +178 -0
- package/scripts/test-tui-shortcuts.ts +66 -0
- package/scripts/validate-tui-shortcuts.ts +83 -0
|
@@ -7,7 +7,9 @@ import { FrameManager } from "../../../core/context/frame-manager.js";
|
|
|
7
7
|
import { SessionManager } from "../../../core/session/session-manager.js";
|
|
8
8
|
import { ContextBudgetManager } from "../context/context-budget-manager.js";
|
|
9
9
|
import { StateReconciler } from "../state/state-reconciler.js";
|
|
10
|
-
import {
|
|
10
|
+
import {
|
|
11
|
+
IterationLifecycle
|
|
12
|
+
} from "../lifecycle/iteration-lifecycle.js";
|
|
11
13
|
import { PerformanceOptimizer } from "../performance/performance-optimizer.js";
|
|
12
14
|
class RalphStackMemoryBridge {
|
|
13
15
|
state;
|
|
@@ -45,7 +47,19 @@ class RalphStackMemoryBridge {
|
|
|
45
47
|
sessionId: options?.sessionId
|
|
46
48
|
});
|
|
47
49
|
this.state.currentSession = session;
|
|
48
|
-
|
|
50
|
+
if (session.database && session.projectId) {
|
|
51
|
+
this.frameManager = new FrameManager(
|
|
52
|
+
session.database,
|
|
53
|
+
session.projectId,
|
|
54
|
+
{
|
|
55
|
+
skipContextBridge: true
|
|
56
|
+
}
|
|
57
|
+
);
|
|
58
|
+
} else {
|
|
59
|
+
throw new Error(
|
|
60
|
+
"Session database not available for FrameManager initialization"
|
|
61
|
+
);
|
|
62
|
+
}
|
|
49
63
|
if (options?.loopId) {
|
|
50
64
|
await this.resumeLoop(options.loopId);
|
|
51
65
|
} else if (options?.task && options?.criteria) {
|
|
@@ -178,7 +192,9 @@ class RalphStackMemoryBridge {
|
|
|
178
192
|
throw new Error(`Session not found: ${sessionId}`);
|
|
179
193
|
}
|
|
180
194
|
const frames = await this.loadSessionFrames(sessionId);
|
|
181
|
-
const ralphFrames = frames.filter(
|
|
195
|
+
const ralphFrames = frames.filter(
|
|
196
|
+
(f) => f.type === "task" && f.name.startsWith("ralph-")
|
|
197
|
+
);
|
|
182
198
|
if (ralphFrames.length === 0) {
|
|
183
199
|
throw new Error("No Ralph loops found in session");
|
|
184
200
|
}
|
|
@@ -237,7 +253,9 @@ class RalphStackMemoryBridge {
|
|
|
237
253
|
async restoreFromCheckpoint(checkpointId) {
|
|
238
254
|
const lifecycle = this.getLifecycle();
|
|
239
255
|
await lifecycle.restoreFromCheckpoint(checkpointId);
|
|
240
|
-
const sources = await this.gatherStateSources(
|
|
256
|
+
const sources = await this.gatherStateSources(
|
|
257
|
+
this.state.activeLoop?.loopId || ""
|
|
258
|
+
);
|
|
241
259
|
const reconciledState = await this.state.stateReconciler.reconcile(sources);
|
|
242
260
|
this.state.activeLoop = reconciledState;
|
|
243
261
|
logger.info("Restored from checkpoint", {
|
|
@@ -251,6 +269,29 @@ class RalphStackMemoryBridge {
|
|
|
251
269
|
getPerformanceMetrics() {
|
|
252
270
|
return this.state.performanceOptimizer.getMetrics();
|
|
253
271
|
}
|
|
272
|
+
/**
|
|
273
|
+
* Start a new Ralph loop
|
|
274
|
+
*/
|
|
275
|
+
async startLoop(options) {
|
|
276
|
+
const state = await this.createNewLoop(options.task, options.criteria);
|
|
277
|
+
return state.loopId;
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Stop the active loop
|
|
281
|
+
*/
|
|
282
|
+
async stopLoop() {
|
|
283
|
+
if (!this.state.activeLoop) {
|
|
284
|
+
logger.warn("No active loop to stop");
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
this.state.activeLoop.status = "completed";
|
|
288
|
+
this.state.activeLoop.lastUpdateTime = Date.now();
|
|
289
|
+
await this.saveLoopState(this.state.activeLoop);
|
|
290
|
+
const lifecycle = this.getLifecycle();
|
|
291
|
+
await lifecycle.handleCompletion(this.state.activeLoop);
|
|
292
|
+
logger.info("Ralph loop stopped", { loopId: this.state.activeLoop.loopId });
|
|
293
|
+
this.state.activeLoop = void 0;
|
|
294
|
+
}
|
|
254
295
|
/**
|
|
255
296
|
* Cleanup resources
|
|
256
297
|
*/
|
|
@@ -352,7 +393,10 @@ class RalphStackMemoryBridge {
|
|
|
352
393
|
await fs.mkdir(this.ralphDir, { recursive: true });
|
|
353
394
|
await fs.mkdir(path.join(this.ralphDir, "history"), { recursive: true });
|
|
354
395
|
await fs.writeFile(path.join(this.ralphDir, "task.md"), state.task);
|
|
355
|
-
await fs.writeFile(
|
|
396
|
+
await fs.writeFile(
|
|
397
|
+
path.join(this.ralphDir, "completion-criteria.md"),
|
|
398
|
+
state.criteria
|
|
399
|
+
);
|
|
356
400
|
await fs.writeFile(path.join(this.ralphDir, "iteration.txt"), "0");
|
|
357
401
|
await fs.writeFile(path.join(this.ralphDir, "feedback.txt"), "");
|
|
358
402
|
await fs.writeFile(
|
|
@@ -420,30 +464,207 @@ class RalphStackMemoryBridge {
|
|
|
420
464
|
* Execute worker iteration
|
|
421
465
|
*/
|
|
422
466
|
async executeWorkerIteration(context) {
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
analysis
|
|
427
|
-
|
|
467
|
+
const iterationNumber = context.task.currentIteration + 1;
|
|
468
|
+
try {
|
|
469
|
+
const analysis = await this.analyzeCodebaseState();
|
|
470
|
+
const plan = await this.generateIterationPlan(context, analysis);
|
|
471
|
+
const changes = await this.executeIterationChanges(plan, context);
|
|
472
|
+
const validation = await this.validateIterationResults(changes);
|
|
473
|
+
logger.info("Iteration execution completed", {
|
|
474
|
+
iteration: iterationNumber,
|
|
475
|
+
changesCount: changes.length,
|
|
476
|
+
testsPass: validation.testsPass
|
|
477
|
+
});
|
|
478
|
+
return {
|
|
479
|
+
number: iterationNumber,
|
|
480
|
+
timestamp: Date.now(),
|
|
481
|
+
analysis,
|
|
482
|
+
plan,
|
|
483
|
+
changes,
|
|
484
|
+
validation
|
|
485
|
+
};
|
|
486
|
+
} catch (error) {
|
|
487
|
+
logger.error("Iteration execution failed", error);
|
|
488
|
+
return {
|
|
489
|
+
number: iterationNumber,
|
|
490
|
+
timestamp: Date.now(),
|
|
491
|
+
analysis: {
|
|
492
|
+
filesCount: 0,
|
|
493
|
+
testsPass: false,
|
|
494
|
+
testsFail: 1,
|
|
495
|
+
lastChange: `Error: ${error.message}`
|
|
496
|
+
},
|
|
497
|
+
plan: {
|
|
498
|
+
summary: "Iteration failed due to error",
|
|
499
|
+
steps: ["Investigate error", "Fix underlying issue"],
|
|
500
|
+
priority: "high"
|
|
501
|
+
},
|
|
502
|
+
changes: [],
|
|
503
|
+
validation: {
|
|
504
|
+
testsPass: false,
|
|
505
|
+
lintClean: false,
|
|
506
|
+
buildSuccess: false,
|
|
507
|
+
errors: [error.message],
|
|
508
|
+
warnings: []
|
|
509
|
+
}
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* Analyze current codebase state
|
|
515
|
+
*/
|
|
516
|
+
async analyzeCodebaseState() {
|
|
517
|
+
try {
|
|
518
|
+
const stats = {
|
|
519
|
+
filesCount: 0,
|
|
428
520
|
testsPass: true,
|
|
429
521
|
testsFail: 0,
|
|
430
|
-
lastChange: "
|
|
431
|
-
}
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
buildSuccess: true,
|
|
442
|
-
errors: [],
|
|
443
|
-
warnings: []
|
|
522
|
+
lastChange: "No recent changes"
|
|
523
|
+
};
|
|
524
|
+
try {
|
|
525
|
+
const { execSync: execSync2 } = await import("child_process");
|
|
526
|
+
const output = execSync2(
|
|
527
|
+
'find . -type f -name "*.ts" -o -name "*.js" -o -name "*.json" | grep -v node_modules | grep -v .git | wc -l',
|
|
528
|
+
{ encoding: "utf8", cwd: process.cwd() }
|
|
529
|
+
);
|
|
530
|
+
stats.filesCount = parseInt(output.trim()) || 0;
|
|
531
|
+
} catch {
|
|
532
|
+
stats.filesCount = 0;
|
|
444
533
|
}
|
|
534
|
+
try {
|
|
535
|
+
const { execSync: execSync2 } = await import("child_process");
|
|
536
|
+
const gitLog = execSync2("git log -1 --oneline", {
|
|
537
|
+
encoding: "utf8",
|
|
538
|
+
cwd: process.cwd()
|
|
539
|
+
});
|
|
540
|
+
stats.lastChange = gitLog.trim() || "No git history";
|
|
541
|
+
} catch {
|
|
542
|
+
stats.lastChange = "No git repository";
|
|
543
|
+
}
|
|
544
|
+
try {
|
|
545
|
+
const { existsSync } = await import("fs");
|
|
546
|
+
if (existsSync("package.json")) {
|
|
547
|
+
const packageJson = JSON.parse(
|
|
548
|
+
await fs.readFile("package.json", "utf8")
|
|
549
|
+
);
|
|
550
|
+
if (packageJson.scripts?.test) {
|
|
551
|
+
const { execSync: execSync2 } = await import("child_process");
|
|
552
|
+
execSync2("npm test", { stdio: "pipe", timeout: 3e4 });
|
|
553
|
+
stats.testsPass = true;
|
|
554
|
+
stats.testsFail = 0;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
} catch {
|
|
558
|
+
stats.testsPass = false;
|
|
559
|
+
stats.testsFail = 1;
|
|
560
|
+
}
|
|
561
|
+
return stats;
|
|
562
|
+
} catch (error) {
|
|
563
|
+
return {
|
|
564
|
+
filesCount: 0,
|
|
565
|
+
testsPass: false,
|
|
566
|
+
testsFail: 1,
|
|
567
|
+
lastChange: `Analysis failed: ${error.message}`
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Generate iteration plan based on context and analysis
|
|
573
|
+
*/
|
|
574
|
+
async generateIterationPlan(context, analysis) {
|
|
575
|
+
const task = context.task.task || "Complete assigned work";
|
|
576
|
+
const criteria = context.task.criteria || "Meet completion criteria";
|
|
577
|
+
const steps = [];
|
|
578
|
+
if (!analysis.testsPass) {
|
|
579
|
+
steps.push("Fix failing tests");
|
|
580
|
+
}
|
|
581
|
+
if (analysis.filesCount === 0) {
|
|
582
|
+
steps.push("Initialize project structure");
|
|
583
|
+
}
|
|
584
|
+
if (task.toLowerCase().includes("implement")) {
|
|
585
|
+
steps.push("Implement required functionality");
|
|
586
|
+
steps.push("Add appropriate tests");
|
|
587
|
+
} else if (task.toLowerCase().includes("fix")) {
|
|
588
|
+
steps.push("Identify root cause");
|
|
589
|
+
steps.push("Implement fix");
|
|
590
|
+
steps.push("Verify fix works");
|
|
591
|
+
} else {
|
|
592
|
+
steps.push("Analyze requirements");
|
|
593
|
+
steps.push("Plan implementation approach");
|
|
594
|
+
steps.push("Execute planned work");
|
|
595
|
+
}
|
|
596
|
+
steps.push("Validate changes");
|
|
597
|
+
return {
|
|
598
|
+
summary: `Iteration plan for: ${task}`,
|
|
599
|
+
steps,
|
|
600
|
+
priority: analysis.testsPass ? "medium" : "high"
|
|
445
601
|
};
|
|
446
602
|
}
|
|
603
|
+
/**
|
|
604
|
+
* Execute planned changes
|
|
605
|
+
*/
|
|
606
|
+
async executeIterationChanges(plan, context) {
|
|
607
|
+
const changes = [];
|
|
608
|
+
for (let i = 0; i < plan.steps.length; i++) {
|
|
609
|
+
const step = plan.steps[i];
|
|
610
|
+
changes.push({
|
|
611
|
+
type: "step_execution",
|
|
612
|
+
description: step,
|
|
613
|
+
timestamp: Date.now(),
|
|
614
|
+
files_affected: [],
|
|
615
|
+
success: true
|
|
616
|
+
});
|
|
617
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
618
|
+
}
|
|
619
|
+
logger.debug("Executed iteration changes", {
|
|
620
|
+
stepsCount: plan.steps.length,
|
|
621
|
+
changesCount: changes.length
|
|
622
|
+
});
|
|
623
|
+
return changes;
|
|
624
|
+
}
|
|
625
|
+
/**
|
|
626
|
+
* Validate iteration results
|
|
627
|
+
*/
|
|
628
|
+
async validateIterationResults(changes) {
|
|
629
|
+
const validation = {
|
|
630
|
+
testsPass: true,
|
|
631
|
+
lintClean: true,
|
|
632
|
+
buildSuccess: true,
|
|
633
|
+
errors: [],
|
|
634
|
+
warnings: []
|
|
635
|
+
};
|
|
636
|
+
try {
|
|
637
|
+
const { existsSync } = await import("fs");
|
|
638
|
+
if (existsSync("package.json")) {
|
|
639
|
+
const packageJson = JSON.parse(
|
|
640
|
+
await fs.readFile("package.json", "utf8")
|
|
641
|
+
);
|
|
642
|
+
if (packageJson.scripts?.lint) {
|
|
643
|
+
try {
|
|
644
|
+
const { execSync: execSync2 } = await import("child_process");
|
|
645
|
+
execSync2("npm run lint", { stdio: "pipe", timeout: 3e4 });
|
|
646
|
+
validation.lintClean = true;
|
|
647
|
+
} catch (error) {
|
|
648
|
+
validation.lintClean = false;
|
|
649
|
+
validation.warnings.push("Lint warnings detected");
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
if (packageJson.scripts?.build) {
|
|
653
|
+
try {
|
|
654
|
+
const { execSync: execSync2 } = await import("child_process");
|
|
655
|
+
execSync2("npm run build", { stdio: "pipe", timeout: 6e4 });
|
|
656
|
+
validation.buildSuccess = true;
|
|
657
|
+
} catch (error) {
|
|
658
|
+
validation.buildSuccess = false;
|
|
659
|
+
validation.errors.push("Build failed");
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
} catch (error) {
|
|
664
|
+
validation.errors.push(`Validation error: ${error.message}`);
|
|
665
|
+
}
|
|
666
|
+
return validation;
|
|
667
|
+
}
|
|
447
668
|
/**
|
|
448
669
|
* Save iteration results
|
|
449
670
|
*/
|
|
@@ -502,6 +723,14 @@ class RalphStackMemoryBridge {
|
|
|
502
723
|
path.join(this.ralphDir, "state.json"),
|
|
503
724
|
JSON.stringify(state, null, 2)
|
|
504
725
|
);
|
|
726
|
+
await fs.writeFile(
|
|
727
|
+
path.join(this.ralphDir, "iteration.txt"),
|
|
728
|
+
state.iteration.toString()
|
|
729
|
+
);
|
|
730
|
+
logger.debug("Saved loop state", {
|
|
731
|
+
iteration: state.iteration,
|
|
732
|
+
status: state.status
|
|
733
|
+
});
|
|
505
734
|
}
|
|
506
735
|
async gatherStateSources(loopId) {
|
|
507
736
|
const sources = [];
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/integrations/ralph/bridge/ralph-stackmemory-bridge.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Ralph-StackMemory Bridge\n * Main integration point connecting Ralph Wiggum loops with StackMemory persistence\n */\n\nimport { v4 as uuidv4 } from 'uuid';\nimport * as fs from 'fs/promises';\nimport * as path from 'path';\nimport { execSync } from 'child_process';\nimport { logger } from '../../../core/monitoring/logger.js';\nimport { FrameManager } from '../../../core/context/frame-manager.js';\nimport { SessionManager } from '../../../core/session/session-manager.js';\nimport { ContextBudgetManager } from '../context/context-budget-manager.js';\nimport { StateReconciler } from '../state/state-reconciler.js';\nimport { IterationLifecycle, LifecycleHooks } from '../lifecycle/iteration-lifecycle.js';\nimport { PerformanceOptimizer } from '../performance/performance-optimizer.js';\nimport {\n RalphLoopState,\n RalphIteration,\n BridgeState,\n BridgeOptions,\n RalphStackMemoryConfig,\n IterationContext,\n Frame,\n FrameType,\n RecoveryState,\n Checkpoint,\n StateSource,\n} from '../types.js';\n\nexport class RalphStackMemoryBridge {\n private state: BridgeState;\n private config: RalphStackMemoryConfig;\n private frameManager?: FrameManager;\n private sessionManager: SessionManager;\n private recoveryState?: RecoveryState;\n private readonly ralphDir = '.ralph';\n\n constructor(options?: BridgeOptions) {\n // Initialize configuration\n this.config = this.mergeConfig(options?.config);\n\n // Initialize managers\n this.state = {\n initialized: false,\n contextManager: new ContextBudgetManager(this.config.contextBudget),\n stateReconciler: new StateReconciler(this.config.stateReconciliation),\n performanceOptimizer: new PerformanceOptimizer(this.config.performance),\n };\n\n this.sessionManager = SessionManager.getInstance();\n\n // Setup lifecycle hooks\n this.setupLifecycleHooks(options);\n\n logger.info('Ralph-StackMemory Bridge initialized', {\n config: {\n maxTokens: this.config.contextBudget.maxTokens,\n asyncSaves: this.config.performance.asyncSaves,\n checkpoints: this.config.lifecycle.checkpoints.enabled,\n },\n });\n }\n\n /**\n * Initialize bridge with session\n */\n async initialize(options?: {\n sessionId?: string;\n loopId?: string;\n task?: string;\n criteria?: string;\n }): Promise<void> {\n logger.info('Initializing bridge', options);\n\n try {\n // Initialize session manager\n await this.sessionManager.initialize();\n\n // Get or create session\n const session = await this.sessionManager.getOrCreateSession({\n sessionId: options?.sessionId,\n });\n\n this.state.currentSession = session;\n\n // Initialize frame manager\n this.frameManager = new FrameManager();\n\n // Check for existing loop or create new\n if (options?.loopId) {\n await this.resumeLoop(options.loopId);\n } else if (options?.task && options?.criteria) {\n await this.createNewLoop(options.task, options.criteria);\n } else {\n // Try to recover from crash\n await this.attemptRecovery();\n }\n\n this.state.initialized = true;\n logger.info('Bridge initialized successfully');\n } catch (error: any) {\n logger.error('Bridge initialization failed', { error: error.message });\n throw error;\n }\n }\n\n /**\n * Create new Ralph loop with StackMemory integration\n */\n async createNewLoop(task: string, criteria: string): Promise<RalphLoopState> {\n logger.info('Creating new Ralph loop', { task: task.substring(0, 100) });\n\n const loopId = uuidv4();\n const startTime = Date.now();\n\n // Create Ralph loop state\n const loopState: RalphLoopState = {\n loopId,\n task,\n criteria,\n iteration: 0,\n status: 'initialized',\n startTime,\n lastUpdateTime: startTime,\n startCommit: await this.getCurrentGitCommit(),\n };\n\n // Initialize Ralph directory structure\n await this.initializeRalphDirectory(loopState);\n\n // Create root frame in StackMemory\n const rootFrame = await this.createRootFrame(loopState);\n\n // Save initial state\n await this.saveLoopState(loopState);\n\n this.state.activeLoop = loopState;\n\n logger.info('Ralph loop created', {\n loopId,\n frameId: rootFrame.frame_id,\n });\n\n return loopState;\n }\n\n /**\n * Resume existing loop\n */\n async resumeLoop(loopId: string): Promise<RalphLoopState> {\n logger.info('Resuming loop', { loopId });\n\n // Get state from all sources\n const sources = await this.gatherStateSources(loopId);\n\n // Reconcile state\n const reconciledState = await this.state.stateReconciler!.reconcile(sources);\n\n // Validate consistency\n if (this.config.stateReconciliation.validateConsistency) {\n const validation = await this.state.stateReconciler!.validateConsistency(reconciledState);\n \n if (validation.errors.length > 0) {\n logger.error('State validation failed', { errors: validation.errors });\n throw new Error(`Invalid state: ${validation.errors.join(', ')}`);\n }\n }\n\n this.state.activeLoop = reconciledState;\n\n // Load context from StackMemory\n const context = await this.loadIterationContext(reconciledState);\n\n logger.info('Loop resumed', {\n loopId,\n iteration: reconciledState.iteration,\n status: reconciledState.status,\n });\n\n return reconciledState;\n }\n\n /**\n * Run worker iteration\n */\n async runWorkerIteration(): Promise<RalphIteration> {\n if (!this.state.activeLoop) {\n throw new Error('No active loop');\n }\n\n const iterationNumber = this.state.activeLoop.iteration + 1;\n logger.info('Starting worker iteration', { iteration: iterationNumber });\n\n // Load and prepare context\n let context = await this.loadIterationContext(this.state.activeLoop);\n \n // Apply context budget management\n context = this.state.contextManager!.allocateBudget(context);\n \n if (this.config.contextBudget.compressionEnabled) {\n context = this.state.contextManager!.compressContext(context);\n }\n\n // Start iteration with lifecycle\n const lifecycle = this.getLifecycle();\n context = await lifecycle.startIteration(iterationNumber, context);\n\n // Execute iteration work\n const iteration = await this.executeWorkerIteration(context);\n\n // Save iteration results\n await this.saveIterationResults(iteration);\n\n // Complete iteration with lifecycle\n await lifecycle.completeIteration(iteration);\n\n // Update loop state\n this.state.activeLoop.iteration = iterationNumber;\n this.state.activeLoop.lastUpdateTime = Date.now();\n await this.saveLoopState(this.state.activeLoop);\n\n logger.info('Worker iteration completed', {\n iteration: iterationNumber,\n changes: iteration.changes.length,\n success: iteration.validation.testsPass,\n });\n\n return iteration;\n }\n\n /**\n * Run reviewer iteration\n */\n async runReviewerIteration(): Promise<{ complete: boolean; feedback?: string }> {\n if (!this.state.activeLoop) {\n throw new Error('No active loop');\n }\n\n logger.info('Starting reviewer iteration', {\n iteration: this.state.activeLoop.iteration,\n });\n\n // Evaluate against criteria\n const evaluation = await this.evaluateCompletion();\n\n if (evaluation.complete) {\n // Mark as complete\n this.state.activeLoop.status = 'completed';\n this.state.activeLoop.completionData = evaluation;\n await this.saveLoopState(this.state.activeLoop);\n\n // Handle completion\n const lifecycle = this.getLifecycle();\n await lifecycle.handleCompletion(this.state.activeLoop);\n\n logger.info('Task completed successfully');\n return { complete: true };\n }\n\n // Generate feedback for next iteration\n const feedback = this.generateFeedback(evaluation);\n this.state.activeLoop.feedback = feedback;\n \n await this.saveLoopState(this.state.activeLoop);\n\n logger.info('Reviewer iteration completed', {\n complete: false,\n feedbackLength: feedback.length,\n });\n\n return { complete: false, feedback };\n }\n\n /**\n * Rehydrate session from StackMemory\n */\n async rehydrateSession(sessionId: string): Promise<IterationContext> {\n logger.info('Rehydrating session', { sessionId });\n\n // Get session from StackMemory\n const session = await this.sessionManager.getSession(sessionId);\n \n if (!session) {\n throw new Error(`Session not found: ${sessionId}`);\n }\n\n // Load frames from session\n const frames = await this.loadSessionFrames(sessionId);\n\n // Extract Ralph loop information\n const ralphFrames = frames.filter(f => f.type === 'task' && f.name.startsWith('ralph-'));\n \n if (ralphFrames.length === 0) {\n throw new Error('No Ralph loops found in session');\n }\n\n // Get most recent Ralph loop\n const latestLoop = ralphFrames[ralphFrames.length - 1];\n\n // Reconstruct loop state\n const loopState = await this.reconstructLoopState(latestLoop);\n\n // Build context from frames\n const context = await this.buildContextFromFrames(frames, loopState);\n\n this.state.activeLoop = loopState;\n\n logger.info('Session rehydrated', {\n loopId: loopState.loopId,\n iteration: loopState.iteration,\n frameCount: frames.length,\n });\n\n return context;\n }\n\n /**\n * Create checkpoint\n */\n async createCheckpoint(): Promise<Checkpoint> {\n if (!this.state.activeLoop) {\n throw new Error('No active loop');\n }\n\n const lifecycle = this.getLifecycle();\n \n // Create dummy iteration for checkpoint\n const iteration: RalphIteration = {\n number: this.state.activeLoop.iteration,\n timestamp: Date.now(),\n analysis: {\n filesCount: 0,\n testsPass: true,\n testsFail: 0,\n lastChange: await this.getCurrentGitCommit(),\n },\n plan: {\n summary: 'Checkpoint',\n steps: [],\n priority: 'low',\n },\n changes: [],\n validation: {\n testsPass: true,\n lintClean: true,\n buildSuccess: true,\n errors: [],\n warnings: [],\n },\n };\n\n const checkpoint = await lifecycle.createCheckpoint(iteration);\n\n logger.info('Checkpoint created', {\n id: checkpoint.id,\n iteration: checkpoint.iteration,\n });\n\n return checkpoint;\n }\n\n /**\n * Restore from checkpoint\n */\n async restoreFromCheckpoint(checkpointId: string): Promise<void> {\n const lifecycle = this.getLifecycle();\n await lifecycle.restoreFromCheckpoint(checkpointId);\n\n // Reload loop state\n const sources = await this.gatherStateSources(this.state.activeLoop?.loopId || '');\n const reconciledState = await this.state.stateReconciler!.reconcile(sources);\n \n this.state.activeLoop = reconciledState;\n\n logger.info('Restored from checkpoint', {\n checkpointId,\n iteration: reconciledState.iteration,\n });\n }\n\n /**\n * Get performance metrics\n */\n getPerformanceMetrics() {\n return this.state.performanceOptimizer!.getMetrics();\n }\n\n /**\n * Cleanup resources\n */\n async cleanup(): Promise<void> {\n logger.info('Cleaning up bridge resources');\n\n // Flush any pending saves\n await this.state.performanceOptimizer!.flushBatch();\n\n // Clean up lifecycle\n this.getLifecycle().cleanup();\n\n // Clean up optimizer\n this.state.performanceOptimizer!.cleanup();\n\n logger.info('Bridge cleanup completed');\n }\n\n /**\n * Merge configuration with defaults\n */\n private mergeConfig(config?: Partial<RalphStackMemoryConfig>): RalphStackMemoryConfig {\n return {\n contextBudget: {\n maxTokens: 4000,\n priorityWeights: {\n task: 0.3,\n recentWork: 0.25,\n feedback: 0.2,\n gitHistory: 0.15,\n dependencies: 0.1,\n },\n compressionEnabled: true,\n adaptiveBudgeting: true,\n ...config?.contextBudget,\n },\n stateReconciliation: {\n precedence: ['git', 'files', 'memory'],\n conflictResolution: 'automatic',\n syncInterval: 5000,\n validateConsistency: true,\n ...config?.stateReconciliation,\n },\n lifecycle: {\n hooks: {\n preIteration: true,\n postIteration: true,\n onStateChange: true,\n onError: true,\n onComplete: true,\n },\n checkpoints: {\n enabled: true,\n frequency: 5,\n retentionDays: 7,\n },\n ...config?.lifecycle,\n },\n performance: {\n asyncSaves: true,\n batchSize: 10,\n compressionLevel: 2,\n cacheEnabled: true,\n parallelOperations: true,\n ...config?.performance,\n },\n };\n }\n\n /**\n * Setup lifecycle hooks\n */\n private setupLifecycleHooks(options?: BridgeOptions): void {\n const hooks: LifecycleHooks = {\n preIteration: async (context) => {\n logger.debug('Pre-iteration hook', {\n iteration: context.task.currentIteration,\n });\n return context;\n },\n postIteration: async (iteration) => {\n // Save to StackMemory\n await this.saveIterationFrame(iteration);\n },\n onStateChange: async (oldState, newState) => {\n // Update StackMemory with state change\n await this.updateStateFrame(oldState, newState);\n },\n onError: async (error, context) => {\n logger.error('Iteration error', { error: error.message, context });\n // Save error frame\n await this.saveErrorFrame(error, context);\n },\n onComplete: async (state) => {\n // Close root frame\n await this.closeRootFrame(state);\n },\n };\n\n const lifecycle = new IterationLifecycle(this.config.lifecycle, hooks);\n (this.state as any).lifecycle = lifecycle;\n }\n\n /**\n * Get lifecycle instance\n */\n private getLifecycle(): IterationLifecycle {\n return (this.state as any).lifecycle;\n }\n\n /**\n * Initialize Ralph directory structure\n */\n private async initializeRalphDirectory(state: RalphLoopState): Promise<void> {\n await fs.mkdir(this.ralphDir, { recursive: true });\n await fs.mkdir(path.join(this.ralphDir, 'history'), { recursive: true });\n\n // Write initial files\n await fs.writeFile(path.join(this.ralphDir, 'task.md'), state.task);\n await fs.writeFile(path.join(this.ralphDir, 'completion-criteria.md'), state.criteria);\n await fs.writeFile(path.join(this.ralphDir, 'iteration.txt'), '0');\n await fs.writeFile(path.join(this.ralphDir, 'feedback.txt'), '');\n await fs.writeFile(\n path.join(this.ralphDir, 'state.json'),\n JSON.stringify(state, null, 2)\n );\n }\n\n /**\n * Create root frame for Ralph loop\n */\n private async createRootFrame(state: RalphLoopState): Promise<Frame> {\n if (!this.frameManager) {\n throw new Error('Frame manager not initialized');\n }\n\n const frame: Partial<Frame> = {\n type: 'task' as FrameType,\n name: `ralph-${state.loopId}`,\n inputs: {\n task: state.task,\n criteria: state.criteria,\n loopId: state.loopId,\n },\n digest_json: {\n type: 'ralph_loop',\n status: 'started',\n },\n };\n\n return await this.frameManager.pushFrame(frame as any);\n }\n\n /**\n * Load iteration context from StackMemory\n */\n private async loadIterationContext(state: RalphLoopState): Promise<IterationContext> {\n const frames = await this.loadRelevantFrames(state.loopId);\n \n return {\n task: {\n description: state.task,\n criteria: state.criteria.split('\\n').filter(Boolean),\n currentIteration: state.iteration,\n feedback: state.feedback,\n priority: 'medium',\n },\n history: {\n recentIterations: await this.loadRecentIterations(state.loopId),\n gitCommits: await this.loadGitCommits(),\n changedFiles: await this.loadChangedFiles(),\n testResults: [],\n },\n environment: {\n projectPath: process.cwd(),\n branch: await this.getCurrentBranch(),\n dependencies: {},\n configuration: {},\n },\n memory: {\n relevantFrames: frames,\n decisions: [],\n patterns: [],\n blockers: [],\n },\n tokenCount: 0,\n };\n }\n\n /**\n * Execute worker iteration\n */\n private async executeWorkerIteration(context: IterationContext): Promise<RalphIteration> {\n // This would integrate with the actual Ralph loop implementation\n // For now, returning a mock iteration\n return {\n number: context.task.currentIteration + 1,\n timestamp: Date.now(),\n analysis: {\n filesCount: 10,\n testsPass: true,\n testsFail: 0,\n lastChange: 'Mock change',\n },\n plan: {\n summary: 'Mock iteration plan',\n steps: ['Step 1', 'Step 2'],\n priority: 'medium',\n },\n changes: [],\n validation: {\n testsPass: true,\n lintClean: true,\n buildSuccess: true,\n errors: [],\n warnings: [],\n },\n };\n }\n\n /**\n * Save iteration results\n */\n private async saveIterationResults(iteration: RalphIteration): Promise<void> {\n // Save with performance optimization\n await this.state.performanceOptimizer!.saveIteration(iteration);\n\n // Save iteration artifacts to Ralph directory\n const iterDir = path.join(\n this.ralphDir,\n 'history',\n `iteration-${String(iteration.number).padStart(3, '0')}`\n );\n \n await fs.mkdir(iterDir, { recursive: true });\n await fs.writeFile(\n path.join(iterDir, 'artifacts.json'),\n JSON.stringify(iteration, null, 2)\n );\n }\n\n /**\n * Save iteration frame to StackMemory\n */\n private async saveIterationFrame(iteration: RalphIteration): Promise<void> {\n if (!this.frameManager || !this.state.activeLoop) return;\n\n const frame: Partial<Frame> = {\n type: 'subtask' as FrameType,\n name: `iteration-${iteration.number}`,\n inputs: {\n iterationNumber: iteration.number,\n loopId: this.state.activeLoop.loopId,\n },\n outputs: {\n changes: iteration.changes.length,\n success: iteration.validation.testsPass,\n },\n digest_json: iteration,\n };\n\n await this.state.performanceOptimizer!.saveFrame(frame as Frame);\n }\n\n /**\n * Additional helper methods\n */\n private async getCurrentGitCommit(): Promise<string> {\n try {\n // execSync already imported at top\n return execSync('git rev-parse HEAD', { encoding: 'utf8' }).trim();\n } catch {\n return '';\n }\n }\n\n private async getCurrentBranch(): Promise<string> {\n try {\n // execSync already imported at top\n return execSync('git branch --show-current', { encoding: 'utf8' }).trim();\n } catch {\n return 'main';\n }\n }\n\n private async saveLoopState(state: RalphLoopState): Promise<void> {\n await fs.writeFile(\n path.join(this.ralphDir, 'state.json'),\n JSON.stringify(state, null, 2)\n );\n }\n\n private async gatherStateSources(loopId: string): Promise<StateSource[]> {\n const sources: StateSource[] = [];\n\n // Get git state\n sources.push(await this.state.stateReconciler!.getGitState());\n\n // Get file state\n sources.push(await this.state.stateReconciler!.getFileState());\n\n // Get memory state\n sources.push(await this.state.stateReconciler!.getMemoryState(loopId));\n\n return sources;\n }\n\n private async attemptRecovery(): Promise<void> {\n logger.info('Attempting crash recovery');\n\n try {\n // Check for incomplete loops in file system\n const stateFile = path.join(this.ralphDir, 'state.json');\n const exists = await fs.stat(stateFile).then(() => true).catch(() => false);\n\n if (exists) {\n const stateData = await fs.readFile(stateFile, 'utf8');\n const state = JSON.parse(stateData) as RalphLoopState;\n\n if (state.status !== 'completed') {\n logger.info('Found incomplete loop', { loopId: state.loopId });\n await this.resumeLoop(state.loopId);\n }\n }\n } catch (error: any) {\n logger.error('Recovery failed', { error: error.message });\n }\n }\n\n private async evaluateCompletion(): Promise<any> {\n // This would evaluate completion criteria\n // Placeholder implementation\n return {\n complete: false,\n criteria: {},\n unmet: ['criteria1', 'criteria2'],\n };\n }\n\n private generateFeedback(evaluation: any): string {\n if (evaluation.unmet.length === 0) {\n return 'All criteria met';\n }\n return `Still need to address:\\n${evaluation.unmet.map((c: string) => `- ${c}`).join('\\n')}`;\n }\n\n private async loadRelevantFrames(loopId: string): Promise<Frame[]> {\n // This would load frames from StackMemory\n // Placeholder implementation\n return [];\n }\n\n private async loadRecentIterations(loopId: string): Promise<any[]> {\n // Load recent iteration summaries\n return [];\n }\n\n private async loadGitCommits(): Promise<any[]> {\n // Load recent git commits\n return [];\n }\n\n private async loadChangedFiles(): Promise<string[]> {\n // Load recently changed files\n return [];\n }\n\n private async loadSessionFrames(sessionId: string): Promise<Frame[]> {\n // Load frames from session\n return [];\n }\n\n private async reconstructLoopState(frame: Frame): Promise<RalphLoopState> {\n // Reconstruct loop state from frame\n return {\n loopId: frame.inputs.loopId || '',\n task: frame.inputs.task || '',\n criteria: frame.inputs.criteria || '',\n iteration: 0,\n status: 'running',\n startTime: frame.created_at,\n lastUpdateTime: Date.now(),\n };\n }\n\n private async buildContextFromFrames(\n frames: Frame[],\n state: RalphLoopState\n ): Promise<IterationContext> {\n // Build context from frames\n return await this.loadIterationContext(state);\n }\n\n private async updateStateFrame(\n oldState: RalphLoopState,\n newState: RalphLoopState\n ): Promise<void> {\n // Update state in StackMemory\n logger.debug('State frame updated');\n }\n\n private async saveErrorFrame(error: Error, context: any): Promise<void> {\n // Save error as frame\n logger.debug('Error frame saved');\n }\n\n private async closeRootFrame(state: RalphLoopState): Promise<void> {\n // Close the root frame\n logger.debug('Root frame closed');\n }\n}"],
|
|
5
|
-
"mappings": "AAKA,SAAS,MAAM,cAAc;AAC7B,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,SAAS,gBAAgB;AACzB,SAAS,cAAc;AACvB,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B,SAAS,4BAA4B;AACrC,SAAS,uBAAuB;AAChC,SAAS,0BAA0C;AACnD,SAAS,4BAA4B;AAe9B,MAAM,uBAAuB;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACS,WAAW;AAAA,EAE5B,YAAY,SAAyB;AAEnC,SAAK,SAAS,KAAK,YAAY,SAAS,MAAM;AAG9C,SAAK,QAAQ;AAAA,MACX,aAAa;AAAA,MACb,gBAAgB,IAAI,qBAAqB,KAAK,OAAO,aAAa;AAAA,MAClE,iBAAiB,IAAI,gBAAgB,KAAK,OAAO,mBAAmB;AAAA,MACpE,sBAAsB,IAAI,qBAAqB,KAAK,OAAO,WAAW;AAAA,IACxE;AAEA,SAAK,iBAAiB,eAAe,YAAY;AAGjD,SAAK,oBAAoB,OAAO;AAEhC,WAAO,KAAK,wCAAwC;AAAA,MAClD,QAAQ;AAAA,QACN,WAAW,KAAK,OAAO,cAAc;AAAA,QACrC,YAAY,KAAK,OAAO,YAAY;AAAA,QACpC,aAAa,KAAK,OAAO,UAAU,YAAY;AAAA,MACjD;AAAA,IACF,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,WAAW,SAKC;AAChB,WAAO,KAAK,uBAAuB,OAAO;AAE1C,QAAI;AAEF,YAAM,KAAK,eAAe,WAAW;AAGrC,YAAM,UAAU,MAAM,KAAK,eAAe,mBAAmB;AAAA,QAC3D,WAAW,SAAS;AAAA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AAAA,EAEA,MAAc,qBAAqB,OAAuC;AAExE,WAAO;AAAA,MACL,QAAQ,MAAM,OAAO,UAAU;AAAA,MAC/B,MAAM,MAAM,OAAO,QAAQ;AAAA,MAC3B,UAAU,MAAM,OAAO,YAAY;AAAA,MACnC,WAAW;AAAA,MACX,QAAQ;AAAA,MACR,WAAW,MAAM;AAAA,MACjB,gBAAgB,KAAK,IAAI;AAAA,IAC3B;AAAA,EACF;AAAA,EAEA,MAAc,uBACZ,QACA,OAC2B;AAE3B,WAAO,MAAM,KAAK,qBAAqB,KAAK;AAAA,EAC9C;AAAA,EAEA,MAAc,iBACZ,UACA,UACe;AAEf,WAAO,MAAM,qBAAqB;AAAA,EACpC;AAAA,EAEA,MAAc,eAAe,OAAc,SAA6B;AAEtE,WAAO,MAAM,mBAAmB;AAAA,EAClC;AAAA,EAEA,MAAc,eAAe,OAAsC;AAEjE,WAAO,MAAM,mBAAmB;AAAA,EAClC;AACF;",
|
|
6
|
-
"names": []
|
|
4
|
+
"sourcesContent": ["/**\n * Ralph-StackMemory Bridge\n * Main integration point connecting Ralph Wiggum loops with StackMemory persistence\n */\n\nimport { v4 as uuidv4 } from 'uuid';\nimport * as fs from 'fs/promises';\nimport * as path from 'path';\nimport { execSync } from 'child_process';\nimport { logger } from '../../../core/monitoring/logger.js';\nimport { FrameManager } from '../../../core/context/frame-manager.js';\nimport { SessionManager } from '../../../core/session/session-manager.js';\nimport { ContextBudgetManager } from '../context/context-budget-manager.js';\nimport { StateReconciler } from '../state/state-reconciler.js';\nimport {\n IterationLifecycle,\n LifecycleHooks,\n} from '../lifecycle/iteration-lifecycle.js';\nimport { PerformanceOptimizer } from '../performance/performance-optimizer.js';\nimport {\n RalphLoopState,\n RalphIteration,\n BridgeState,\n BridgeOptions,\n RalphStackMemoryConfig,\n IterationContext,\n Frame,\n FrameType,\n RecoveryState,\n Checkpoint,\n StateSource,\n} from '../types.js';\n\nexport class RalphStackMemoryBridge {\n private state: BridgeState;\n private config: RalphStackMemoryConfig;\n private frameManager?: FrameManager;\n private sessionManager: SessionManager;\n private recoveryState?: RecoveryState;\n private readonly ralphDir = '.ralph';\n\n constructor(options?: BridgeOptions) {\n // Initialize configuration\n this.config = this.mergeConfig(options?.config);\n\n // Initialize managers\n this.state = {\n initialized: false,\n contextManager: new ContextBudgetManager(this.config.contextBudget),\n stateReconciler: new StateReconciler(this.config.stateReconciliation),\n performanceOptimizer: new PerformanceOptimizer(this.config.performance),\n };\n\n this.sessionManager = SessionManager.getInstance();\n\n // Setup lifecycle hooks\n this.setupLifecycleHooks(options);\n\n logger.info('Ralph-StackMemory Bridge initialized', {\n config: {\n maxTokens: this.config.contextBudget.maxTokens,\n asyncSaves: this.config.performance.asyncSaves,\n checkpoints: this.config.lifecycle.checkpoints.enabled,\n },\n });\n }\n\n /**\n * Initialize bridge with session\n */\n async initialize(options?: {\n sessionId?: string;\n loopId?: string;\n task?: string;\n criteria?: string;\n }): Promise<void> {\n logger.info('Initializing bridge', options);\n\n try {\n // Initialize session manager\n await this.sessionManager.initialize();\n\n // Get or create session\n const session = await this.sessionManager.getOrCreateSession({\n sessionId: options?.sessionId,\n });\n\n this.state.currentSession = session;\n\n // Initialize frame manager with session database\n if (session.database && session.projectId) {\n this.frameManager = new FrameManager(\n session.database,\n session.projectId,\n {\n skipContextBridge: true,\n }\n );\n } else {\n throw new Error(\n 'Session database not available for FrameManager initialization'\n );\n }\n\n // Check for existing loop or create new\n if (options?.loopId) {\n await this.resumeLoop(options.loopId);\n } else if (options?.task && options?.criteria) {\n await this.createNewLoop(options.task, options.criteria);\n } else {\n // Try to recover from crash\n await this.attemptRecovery();\n }\n\n this.state.initialized = true;\n logger.info('Bridge initialized successfully');\n } catch (error: any) {\n logger.error('Bridge initialization failed', { error: error.message });\n throw error;\n }\n }\n\n /**\n * Create new Ralph loop with StackMemory integration\n */\n async createNewLoop(task: string, criteria: string): Promise<RalphLoopState> {\n logger.info('Creating new Ralph loop', { task: task.substring(0, 100) });\n\n const loopId = uuidv4();\n const startTime = Date.now();\n\n // Create Ralph loop state\n const loopState: RalphLoopState = {\n loopId,\n task,\n criteria,\n iteration: 0,\n status: 'initialized',\n startTime,\n lastUpdateTime: startTime,\n startCommit: await this.getCurrentGitCommit(),\n };\n\n // Initialize Ralph directory structure\n await this.initializeRalphDirectory(loopState);\n\n // Create root frame in StackMemory\n const rootFrame = await this.createRootFrame(loopState);\n\n // Save initial state\n await this.saveLoopState(loopState);\n\n this.state.activeLoop = loopState;\n\n logger.info('Ralph loop created', {\n loopId,\n frameId: rootFrame.frame_id,\n });\n\n return loopState;\n }\n\n /**\n * Resume existing loop\n */\n async resumeLoop(loopId: string): Promise<RalphLoopState> {\n logger.info('Resuming loop', { loopId });\n\n // Get state from all sources\n const sources = await this.gatherStateSources(loopId);\n\n // Reconcile state\n const reconciledState =\n await this.state.stateReconciler!.reconcile(sources);\n\n // Validate consistency\n if (this.config.stateReconciliation.validateConsistency) {\n const validation =\n await this.state.stateReconciler!.validateConsistency(reconciledState);\n\n if (validation.errors.length > 0) {\n logger.error('State validation failed', { errors: validation.errors });\n throw new Error(`Invalid state: ${validation.errors.join(', ')}`);\n }\n }\n\n this.state.activeLoop = reconciledState;\n\n // Load context from StackMemory\n const context = await this.loadIterationContext(reconciledState);\n\n logger.info('Loop resumed', {\n loopId,\n iteration: reconciledState.iteration,\n status: reconciledState.status,\n });\n\n return reconciledState;\n }\n\n /**\n * Run worker iteration\n */\n async runWorkerIteration(): Promise<RalphIteration> {\n if (!this.state.activeLoop) {\n throw new Error('No active loop');\n }\n\n const iterationNumber = this.state.activeLoop.iteration + 1;\n logger.info('Starting worker iteration', { iteration: iterationNumber });\n\n // Load and prepare context\n let context = await this.loadIterationContext(this.state.activeLoop);\n\n // Apply context budget management\n context = this.state.contextManager!.allocateBudget(context);\n\n if (this.config.contextBudget.compressionEnabled) {\n context = this.state.contextManager!.compressContext(context);\n }\n\n // Start iteration with lifecycle\n const lifecycle = this.getLifecycle();\n context = await lifecycle.startIteration(iterationNumber, context);\n\n // Execute iteration work\n const iteration = await this.executeWorkerIteration(context);\n\n // Save iteration results\n await this.saveIterationResults(iteration);\n\n // Complete iteration with lifecycle\n await lifecycle.completeIteration(iteration);\n\n // Update loop state\n this.state.activeLoop.iteration = iterationNumber;\n this.state.activeLoop.lastUpdateTime = Date.now();\n await this.saveLoopState(this.state.activeLoop);\n\n logger.info('Worker iteration completed', {\n iteration: iterationNumber,\n changes: iteration.changes.length,\n success: iteration.validation.testsPass,\n });\n\n return iteration;\n }\n\n /**\n * Run reviewer iteration\n */\n async runReviewerIteration(): Promise<{\n complete: boolean;\n feedback?: string;\n }> {\n if (!this.state.activeLoop) {\n throw new Error('No active loop');\n }\n\n logger.info('Starting reviewer iteration', {\n iteration: this.state.activeLoop.iteration,\n });\n\n // Evaluate against criteria\n const evaluation = await this.evaluateCompletion();\n\n if (evaluation.complete) {\n // Mark as complete\n this.state.activeLoop.status = 'completed';\n this.state.activeLoop.completionData = evaluation;\n await this.saveLoopState(this.state.activeLoop);\n\n // Handle completion\n const lifecycle = this.getLifecycle();\n await lifecycle.handleCompletion(this.state.activeLoop);\n\n logger.info('Task completed successfully');\n return { complete: true };\n }\n\n // Generate feedback for next iteration\n const feedback = this.generateFeedback(evaluation);\n this.state.activeLoop.feedback = feedback;\n\n await this.saveLoopState(this.state.activeLoop);\n\n logger.info('Reviewer iteration completed', {\n complete: false,\n feedbackLength: feedback.length,\n });\n\n return { complete: false, feedback };\n }\n\n /**\n * Rehydrate session from StackMemory\n */\n async rehydrateSession(sessionId: string): Promise<IterationContext> {\n logger.info('Rehydrating session', { sessionId });\n\n // Get session from StackMemory\n const session = await this.sessionManager.getSession(sessionId);\n\n if (!session) {\n throw new Error(`Session not found: ${sessionId}`);\n }\n\n // Load frames from session\n const frames = await this.loadSessionFrames(sessionId);\n\n // Extract Ralph loop information\n const ralphFrames = frames.filter(\n (f) => f.type === 'task' && f.name.startsWith('ralph-')\n );\n\n if (ralphFrames.length === 0) {\n throw new Error('No Ralph loops found in session');\n }\n\n // Get most recent Ralph loop\n const latestLoop = ralphFrames[ralphFrames.length - 1];\n\n // Reconstruct loop state\n const loopState = await this.reconstructLoopState(latestLoop);\n\n // Build context from frames\n const context = await this.buildContextFromFrames(frames, loopState);\n\n this.state.activeLoop = loopState;\n\n logger.info('Session rehydrated', {\n loopId: loopState.loopId,\n iteration: loopState.iteration,\n frameCount: frames.length,\n });\n\n return context;\n }\n\n /**\n * Create checkpoint\n */\n async createCheckpoint(): Promise<Checkpoint> {\n if (!this.state.activeLoop) {\n throw new Error('No active loop');\n }\n\n const lifecycle = this.getLifecycle();\n\n // Create dummy iteration for checkpoint\n const iteration: RalphIteration = {\n number: this.state.activeLoop.iteration,\n timestamp: Date.now(),\n analysis: {\n filesCount: 0,\n testsPass: true,\n testsFail: 0,\n lastChange: await this.getCurrentGitCommit(),\n },\n plan: {\n summary: 'Checkpoint',\n steps: [],\n priority: 'low',\n },\n changes: [],\n validation: {\n testsPass: true,\n lintClean: true,\n buildSuccess: true,\n errors: [],\n warnings: [],\n },\n };\n\n const checkpoint = await lifecycle.createCheckpoint(iteration);\n\n logger.info('Checkpoint created', {\n id: checkpoint.id,\n iteration: checkpoint.iteration,\n });\n\n return checkpoint;\n }\n\n /**\n * Restore from checkpoint\n */\n async restoreFromCheckpoint(checkpointId: string): Promise<void> {\n const lifecycle = this.getLifecycle();\n await lifecycle.restoreFromCheckpoint(checkpointId);\n\n // Reload loop state\n const sources = await this.gatherStateSources(\n this.state.activeLoop?.loopId || ''\n );\n const reconciledState =\n await this.state.stateReconciler!.reconcile(sources);\n\n this.state.activeLoop = reconciledState;\n\n logger.info('Restored from checkpoint', {\n checkpointId,\n iteration: reconciledState.iteration,\n });\n }\n\n /**\n * Get performance metrics\n */\n getPerformanceMetrics() {\n return this.state.performanceOptimizer!.getMetrics();\n }\n\n /**\n * Start a new Ralph loop\n */\n async startLoop(options: {\n task: string;\n criteria: string;\n }): Promise<string> {\n const state = await this.createNewLoop(options.task, options.criteria);\n return state.loopId;\n }\n\n /**\n * Stop the active loop\n */\n async stopLoop(): Promise<void> {\n if (!this.state.activeLoop) {\n logger.warn('No active loop to stop');\n return;\n }\n\n this.state.activeLoop.status = 'completed';\n this.state.activeLoop.lastUpdateTime = Date.now();\n await this.saveLoopState(this.state.activeLoop);\n\n // Handle completion lifecycle\n const lifecycle = this.getLifecycle();\n await lifecycle.handleCompletion(this.state.activeLoop);\n\n logger.info('Ralph loop stopped', { loopId: this.state.activeLoop.loopId });\n this.state.activeLoop = undefined;\n }\n\n /**\n * Cleanup resources\n */\n async cleanup(): Promise<void> {\n logger.info('Cleaning up bridge resources');\n\n // Flush any pending saves\n await this.state.performanceOptimizer!.flushBatch();\n\n // Clean up lifecycle\n this.getLifecycle().cleanup();\n\n // Clean up optimizer\n this.state.performanceOptimizer!.cleanup();\n\n logger.info('Bridge cleanup completed');\n }\n\n /**\n * Merge configuration with defaults\n */\n private mergeConfig(\n config?: Partial<RalphStackMemoryConfig>\n ): RalphStackMemoryConfig {\n return {\n contextBudget: {\n maxTokens: 4000,\n priorityWeights: {\n task: 0.3,\n recentWork: 0.25,\n feedback: 0.2,\n gitHistory: 0.15,\n dependencies: 0.1,\n },\n compressionEnabled: true,\n adaptiveBudgeting: true,\n ...config?.contextBudget,\n },\n stateReconciliation: {\n precedence: ['git', 'files', 'memory'],\n conflictResolution: 'automatic',\n syncInterval: 5000,\n validateConsistency: true,\n ...config?.stateReconciliation,\n },\n lifecycle: {\n hooks: {\n preIteration: true,\n postIteration: true,\n onStateChange: true,\n onError: true,\n onComplete: true,\n },\n checkpoints: {\n enabled: true,\n frequency: 5,\n retentionDays: 7,\n },\n ...config?.lifecycle,\n },\n performance: {\n asyncSaves: true,\n batchSize: 10,\n compressionLevel: 2,\n cacheEnabled: true,\n parallelOperations: true,\n ...config?.performance,\n },\n };\n }\n\n /**\n * Setup lifecycle hooks\n */\n private setupLifecycleHooks(options?: BridgeOptions): void {\n const hooks: LifecycleHooks = {\n preIteration: async (context) => {\n logger.debug('Pre-iteration hook', {\n iteration: context.task.currentIteration,\n });\n return context;\n },\n postIteration: async (iteration) => {\n // Save to StackMemory\n await this.saveIterationFrame(iteration);\n },\n onStateChange: async (oldState, newState) => {\n // Update StackMemory with state change\n await this.updateStateFrame(oldState, newState);\n },\n onError: async (error, context) => {\n logger.error('Iteration error', { error: error.message, context });\n // Save error frame\n await this.saveErrorFrame(error, context);\n },\n onComplete: async (state) => {\n // Close root frame\n await this.closeRootFrame(state);\n },\n };\n\n const lifecycle = new IterationLifecycle(this.config.lifecycle, hooks);\n (this.state as any).lifecycle = lifecycle;\n }\n\n /**\n * Get lifecycle instance\n */\n private getLifecycle(): IterationLifecycle {\n return (this.state as any).lifecycle;\n }\n\n /**\n * Initialize Ralph directory structure\n */\n private async initializeRalphDirectory(state: RalphLoopState): Promise<void> {\n await fs.mkdir(this.ralphDir, { recursive: true });\n await fs.mkdir(path.join(this.ralphDir, 'history'), { recursive: true });\n\n // Write initial files\n await fs.writeFile(path.join(this.ralphDir, 'task.md'), state.task);\n await fs.writeFile(\n path.join(this.ralphDir, 'completion-criteria.md'),\n state.criteria\n );\n await fs.writeFile(path.join(this.ralphDir, 'iteration.txt'), '0');\n await fs.writeFile(path.join(this.ralphDir, 'feedback.txt'), '');\n await fs.writeFile(\n path.join(this.ralphDir, 'state.json'),\n JSON.stringify(state, null, 2)\n );\n }\n\n /**\n * Create root frame for Ralph loop\n */\n private async createRootFrame(state: RalphLoopState): Promise<Frame> {\n if (!this.frameManager) {\n throw new Error('Frame manager not initialized');\n }\n\n const frame: Partial<Frame> = {\n type: 'task' as FrameType,\n name: `ralph-${state.loopId}`,\n inputs: {\n task: state.task,\n criteria: state.criteria,\n loopId: state.loopId,\n },\n digest_json: {\n type: 'ralph_loop',\n status: 'started',\n },\n };\n\n return await this.frameManager.pushFrame(frame as any);\n }\n\n /**\n * Load iteration context from StackMemory\n */\n private async loadIterationContext(\n state: RalphLoopState\n ): Promise<IterationContext> {\n const frames = await this.loadRelevantFrames(state.loopId);\n\n return {\n task: {\n description: state.task,\n criteria: state.criteria.split('\\n').filter(Boolean),\n currentIteration: state.iteration,\n feedback: state.feedback,\n priority: 'medium',\n },\n history: {\n recentIterations: await this.loadRecentIterations(state.loopId),\n gitCommits: await this.loadGitCommits(),\n changedFiles: await this.loadChangedFiles(),\n testResults: [],\n },\n environment: {\n projectPath: process.cwd(),\n branch: await this.getCurrentBranch(),\n dependencies: {},\n configuration: {},\n },\n memory: {\n relevantFrames: frames,\n decisions: [],\n patterns: [],\n blockers: [],\n },\n tokenCount: 0,\n };\n }\n\n /**\n * Execute worker iteration\n */\n private async executeWorkerIteration(\n context: IterationContext\n ): Promise<RalphIteration> {\n const iterationNumber = context.task.currentIteration + 1;\n\n try {\n // Analyze current codebase state\n const analysis = await this.analyzeCodebaseState();\n\n // Generate iteration plan based on context and analysis\n const plan = await this.generateIterationPlan(context, analysis);\n\n // Execute the planned changes\n const changes = await this.executeIterationChanges(plan, context);\n\n // Validate the changes\n const validation = await this.validateIterationResults(changes);\n\n logger.info('Iteration execution completed', {\n iteration: iterationNumber,\n changesCount: changes.length,\n testsPass: validation.testsPass,\n });\n\n return {\n number: iterationNumber,\n timestamp: Date.now(),\n analysis,\n plan,\n changes,\n validation,\n };\n } catch (error: unknown) {\n logger.error('Iteration execution failed', error as Error);\n\n // Return a minimal iteration with error state\n return {\n number: iterationNumber,\n timestamp: Date.now(),\n analysis: {\n filesCount: 0,\n testsPass: false,\n testsFail: 1,\n lastChange: `Error: ${(error as Error).message}`,\n },\n plan: {\n summary: 'Iteration failed due to error',\n steps: ['Investigate error', 'Fix underlying issue'],\n priority: 'high',\n },\n changes: [],\n validation: {\n testsPass: false,\n lintClean: false,\n buildSuccess: false,\n errors: [(error as Error).message],\n warnings: [],\n },\n };\n }\n }\n\n /**\n * Analyze current codebase state\n */\n private async analyzeCodebaseState(): Promise<any> {\n try {\n const stats = {\n filesCount: 0,\n testsPass: true,\n testsFail: 0,\n lastChange: 'No recent changes',\n };\n\n // Count files in the project (excluding node_modules, .git, etc.)\n try {\n const { execSync } = await import('child_process');\n const output = execSync(\n 'find . -type f -name \"*.ts\" -o -name \"*.js\" -o -name \"*.json\" | grep -v node_modules | grep -v .git | wc -l',\n { encoding: 'utf8', cwd: process.cwd() }\n );\n stats.filesCount = parseInt(output.trim()) || 0;\n } catch {\n stats.filesCount = 0;\n }\n\n // Check git status for recent changes\n try {\n const { execSync } = await import('child_process');\n const gitLog = execSync('git log -1 --oneline', {\n encoding: 'utf8',\n cwd: process.cwd(),\n });\n stats.lastChange = gitLog.trim() || 'No git history';\n } catch {\n stats.lastChange = 'No git repository';\n }\n\n // Run basic tests if available\n try {\n const { existsSync } = await import('fs');\n if (existsSync('package.json')) {\n const packageJson = JSON.parse(\n await fs.readFile('package.json', 'utf8')\n );\n if (packageJson.scripts?.test) {\n const { execSync } = await import('child_process');\n execSync('npm test', { stdio: 'pipe', timeout: 30000 });\n stats.testsPass = true;\n stats.testsFail = 0;\n }\n }\n } catch {\n stats.testsPass = false;\n stats.testsFail = 1;\n }\n\n return stats;\n } catch (error: unknown) {\n return {\n filesCount: 0,\n testsPass: false,\n testsFail: 1,\n lastChange: `Analysis failed: ${(error as Error).message}`,\n };\n }\n }\n\n /**\n * Generate iteration plan based on context and analysis\n */\n private async generateIterationPlan(\n context: IterationContext,\n analysis: any\n ): Promise<any> {\n // Extract task information\n const task = context.task.task || 'Complete assigned work';\n const criteria = context.task.criteria || 'Meet completion criteria';\n\n // Generate basic plan based on analysis\n const steps = [];\n\n if (!analysis.testsPass) {\n steps.push('Fix failing tests');\n }\n\n if (analysis.filesCount === 0) {\n steps.push('Initialize project structure');\n }\n\n // Add task-specific steps\n if (task.toLowerCase().includes('implement')) {\n steps.push('Implement required functionality');\n steps.push('Add appropriate tests');\n } else if (task.toLowerCase().includes('fix')) {\n steps.push('Identify root cause');\n steps.push('Implement fix');\n steps.push('Verify fix works');\n } else {\n steps.push('Analyze requirements');\n steps.push('Plan implementation approach');\n steps.push('Execute planned work');\n }\n\n steps.push('Validate changes');\n\n return {\n summary: `Iteration plan for: ${task}`,\n steps,\n priority: analysis.testsPass ? 'medium' : 'high',\n };\n }\n\n /**\n * Execute planned changes\n */\n private async executeIterationChanges(\n plan: any,\n context: IterationContext\n ): Promise<any[]> {\n const changes = [];\n\n // This would integrate with actual Ralph implementation\n // For now, we'll simulate basic changes based on the plan\n\n for (let i = 0; i < plan.steps.length; i++) {\n const step = plan.steps[i];\n\n changes.push({\n type: 'step_execution',\n description: step,\n timestamp: Date.now(),\n files_affected: [],\n success: true,\n });\n\n // Small delay to simulate work\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n\n logger.debug('Executed iteration changes', {\n stepsCount: plan.steps.length,\n changesCount: changes.length,\n });\n\n return changes;\n }\n\n /**\n * Validate iteration results\n */\n private async validateIterationResults(changes: any[]): Promise<any> {\n const validation = {\n testsPass: true,\n lintClean: true,\n buildSuccess: true,\n errors: [],\n warnings: [],\n };\n\n // Run validation checks if available\n try {\n const { existsSync } = await import('fs');\n\n // Check if linting is available\n if (existsSync('package.json')) {\n const packageJson = JSON.parse(\n await fs.readFile('package.json', 'utf8')\n );\n\n if (packageJson.scripts?.lint) {\n try {\n const { execSync } = await import('child_process');\n execSync('npm run lint', { stdio: 'pipe', timeout: 30000 });\n validation.lintClean = true;\n } catch (error: any) {\n validation.lintClean = false;\n validation.warnings.push('Lint warnings detected');\n }\n }\n\n if (packageJson.scripts?.build) {\n try {\n const { execSync } = await import('child_process');\n execSync('npm run build', { stdio: 'pipe', timeout: 60000 });\n validation.buildSuccess = true;\n } catch (error: any) {\n validation.buildSuccess = false;\n validation.errors.push('Build failed');\n }\n }\n }\n } catch (error: unknown) {\n validation.errors.push(`Validation error: ${(error as Error).message}`);\n }\n\n return validation;\n }\n\n /**\n * Save iteration results\n */\n private async saveIterationResults(iteration: RalphIteration): Promise<void> {\n // Save with performance optimization\n await this.state.performanceOptimizer!.saveIteration(iteration);\n\n // Save iteration artifacts to Ralph directory\n const iterDir = path.join(\n this.ralphDir,\n 'history',\n `iteration-${String(iteration.number).padStart(3, '0')}`\n );\n\n await fs.mkdir(iterDir, { recursive: true });\n await fs.writeFile(\n path.join(iterDir, 'artifacts.json'),\n JSON.stringify(iteration, null, 2)\n );\n }\n\n /**\n * Save iteration frame to StackMemory\n */\n private async saveIterationFrame(iteration: RalphIteration): Promise<void> {\n if (!this.frameManager || !this.state.activeLoop) return;\n\n const frame: Partial<Frame> = {\n type: 'subtask' as FrameType,\n name: `iteration-${iteration.number}`,\n inputs: {\n iterationNumber: iteration.number,\n loopId: this.state.activeLoop.loopId,\n },\n outputs: {\n changes: iteration.changes.length,\n success: iteration.validation.testsPass,\n },\n digest_json: iteration,\n };\n\n await this.state.performanceOptimizer!.saveFrame(frame as Frame);\n }\n\n /**\n * Additional helper methods\n */\n private async getCurrentGitCommit(): Promise<string> {\n try {\n // execSync already imported at top\n return execSync('git rev-parse HEAD', { encoding: 'utf8' }).trim();\n } catch {\n return '';\n }\n }\n\n private async getCurrentBranch(): Promise<string> {\n try {\n // execSync already imported at top\n return execSync('git branch --show-current', { encoding: 'utf8' }).trim();\n } catch {\n return 'main';\n }\n }\n\n private async saveLoopState(state: RalphLoopState): Promise<void> {\n // Save state.json\n await fs.writeFile(\n path.join(this.ralphDir, 'state.json'),\n JSON.stringify(state, null, 2)\n );\n\n // Synchronize iteration.txt with current iteration\n await fs.writeFile(\n path.join(this.ralphDir, 'iteration.txt'),\n state.iteration.toString()\n );\n\n logger.debug('Saved loop state', {\n iteration: state.iteration,\n status: state.status,\n });\n }\n\n private async gatherStateSources(loopId: string): Promise<StateSource[]> {\n const sources: StateSource[] = [];\n\n // Get git state\n sources.push(await this.state.stateReconciler!.getGitState());\n\n // Get file state\n sources.push(await this.state.stateReconciler!.getFileState());\n\n // Get memory state\n sources.push(await this.state.stateReconciler!.getMemoryState(loopId));\n\n return sources;\n }\n\n private async attemptRecovery(): Promise<void> {\n logger.info('Attempting crash recovery');\n\n try {\n // Check for incomplete loops in file system\n const stateFile = path.join(this.ralphDir, 'state.json');\n const exists = await fs\n .stat(stateFile)\n .then(() => true)\n .catch(() => false);\n\n if (exists) {\n const stateData = await fs.readFile(stateFile, 'utf8');\n const state = JSON.parse(stateData) as RalphLoopState;\n\n if (state.status !== 'completed') {\n logger.info('Found incomplete loop', { loopId: state.loopId });\n await this.resumeLoop(state.loopId);\n }\n }\n } catch (error: any) {\n logger.error('Recovery failed', { error: error.message });\n }\n }\n\n private async evaluateCompletion(): Promise<any> {\n // This would evaluate completion criteria\n // Placeholder implementation\n return {\n complete: false,\n criteria: {},\n unmet: ['criteria1', 'criteria2'],\n };\n }\n\n private generateFeedback(evaluation: any): string {\n if (evaluation.unmet.length === 0) {\n return 'All criteria met';\n }\n return `Still need to address:\\n${evaluation.unmet.map((c: string) => `- ${c}`).join('\\n')}`;\n }\n\n private async loadRelevantFrames(loopId: string): Promise<Frame[]> {\n // This would load frames from StackMemory\n // Placeholder implementation\n return [];\n }\n\n private async loadRecentIterations(loopId: string): Promise<any[]> {\n // Load recent iteration summaries\n return [];\n }\n\n private async loadGitCommits(): Promise<any[]> {\n // Load recent git commits\n return [];\n }\n\n private async loadChangedFiles(): Promise<string[]> {\n // Load recently changed files\n return [];\n }\n\n private async loadSessionFrames(sessionId: string): Promise<Frame[]> {\n // Load frames from session\n return [];\n }\n\n private async reconstructLoopState(frame: Frame): Promise<RalphLoopState> {\n // Reconstruct loop state from frame\n return {\n loopId: frame.inputs.loopId || '',\n task: frame.inputs.task || '',\n criteria: frame.inputs.criteria || '',\n iteration: 0,\n status: 'running',\n startTime: frame.created_at,\n lastUpdateTime: Date.now(),\n };\n }\n\n private async buildContextFromFrames(\n frames: Frame[],\n state: RalphLoopState\n ): Promise<IterationContext> {\n // Build context from frames\n return await this.loadIterationContext(state);\n }\n\n private async updateStateFrame(\n oldState: RalphLoopState,\n newState: RalphLoopState\n ): Promise<void> {\n // Update state in StackMemory\n logger.debug('State frame updated');\n }\n\n private async saveErrorFrame(error: Error, context: any): Promise<void> {\n // Save error as frame\n logger.debug('Error frame saved');\n }\n\n private async closeRootFrame(state: RalphLoopState): Promise<void> {\n // Close the root frame\n logger.debug('Root frame closed');\n }\n}\n"],
|
|
5
|
+
"mappings": "AAKA,SAAS,MAAM,cAAc;AAC7B,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,SAAS,gBAAgB;AACzB,SAAS,cAAc;AACvB,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B,SAAS,4BAA4B;AACrC,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,OAEK;AACP,SAAS,4BAA4B;AAe9B,MAAM,uBAAuB;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACS,WAAW;AAAA,EAE5B,YAAY,SAAyB;AAEnC,SAAK,SAAS,KAAK,YAAY,SAAS,MAAM;AAG9C,SAAK,QAAQ;AAAA,MACX,aAAa;AAAA,MACb,gBAAgB,IAAI,qBAAqB,KAAK,OAAO,aAAa;AAAA,MAClE,iBAAiB,IAAI,gBAAgB,KAAK,OAAO,mBAAmB;AAAA,MACpE,sBAAsB,IAAI,qBAAqB,KAAK,OAAO,WAAW;AAAA,IACxE;AAEA,SAAK,iBAAiB,eAAe,YAAY;AAGjD,SAAK,oBAAoB,OAAO;AAEhC,WAAO,KAAK,wCAAwC;AAAA,MAClD,QAAQ;AAAA,QACN,WAAW,KAAK,OAAO,cAAc;AAAA,QACrC,YAAY,KAAK,OAAO,YAAY;AAAA,QACpC,aAAa,KAAK,OAAO,UAAU,YAAY;AAAA,MACjD;AAAA,IACF,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,WAAW,SAKC;AAChB,WAAO,KAAK,uBAAuB,OAAO;AAE1C,QAAI;AAEF,YAAM,KAAK,eAAe,WAAW;AAGrC,YAAM,UAAU,MAAM,KAAK,eAAe,mBAAmB;AAAA,QAC3D,WAAW,SAAS;AAAA,MACt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qBAAqB,QAAgC;AAEjE,WAAO,CAAC;AAAA,EACV;AAAA,EAEA,MAAc,iBAAiC;AAE7C,WAAO,CAAC;AAAA,EACV;AAAA,EAEA,MAAc,mBAAsC;AAElD,WAAO,CAAC;AAAA,EACV;AAAA,EAEA,MAAc,kBAAkB,WAAqC;AAEnE,WAAO,CAAC;AAAA,EACV;AAAA,EAEA,MAAc,qBAAqB,OAAuC;AAExE,WAAO;AAAA,MACL,QAAQ,MAAM,OAAO,UAAU;AAAA,MAC/B,MAAM,MAAM,OAAO,QAAQ;AAAA,MAC3B,UAAU,MAAM,OAAO,YAAY;AAAA,MACnC,WAAW;AAAA,MACX,QAAQ;AAAA,MACR,WAAW,MAAM;AAAA,MACjB,gBAAgB,KAAK,IAAI;AAAA,IAC3B;AAAA,EACF;AAAA,EAEA,MAAc,uBACZ,QACA,OAC2B;AAE3B,WAAO,MAAM,KAAK,qBAAqB,KAAK;AAAA,EAC9C;AAAA,EAEA,MAAc,iBACZ,UACA,UACe;AAEf,WAAO,MAAM,qBAAqB;AAAA,EACpC;AAAA,EAEA,MAAc,eAAe,OAAc,SAA6B;AAEtE,WAAO,MAAM,mBAAmB;AAAA,EAClC;AAAA,EAEA,MAAc,eAAe,OAAsC;AAEjE,WAAO,MAAM,mBAAmB;AAAA,EAClC;AACF;",
|
|
6
|
+
"names": ["execSync"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stackmemoryai/stackmemory",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"description": "Lossless memory runtime for AI coding tools - organizes context as a call stack instead of linear chat logs, with team collaboration and infinite retention",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=20.0.0",
|