Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export type {
export { CostTracker, resolveModelPricing } from './loop/cost-tracker.js';
export type { IterationUpdate, LoopOptions, LoopResult } from './loop/executor.js';
export { runLoop } from './loop/executor.js';
export { appendProjectMemory, readProjectMemory } from './loop/memory.js';
export type { SwarmAgentResult, SwarmConfig, SwarmResult, SwarmStrategy } from './loop/swarm.js';
export { runSwarm } from './loop/swarm.js';
export { detectValidationCommands, runAllValidations, runValidation } from './loop/validation.js';
Expand Down
71 changes: 71 additions & 0 deletions src/loop/__tests__/memory.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { appendProjectMemory, formatMemoryPrompt, readProjectMemory } from '../memory.js';

describe('Project Memory', () => {
let testDir: string;

beforeEach(() => {
testDir = mkdtempSync(join(tmpdir(), 'ralph-memory-test-'));
});

afterEach(() => {
rmSync(testDir, { recursive: true, force: true });
});

describe('readProjectMemory', () => {
it('should return undefined when no memory exists', () => {
expect(readProjectMemory(testDir)).toBeUndefined();
});

it('should read existing memory', () => {
const ralphDir = join(testDir, '.ralph');
mkdirSync(ralphDir, { recursive: true });
writeFileSync(join(ralphDir, 'memory.md'), '## 2026-03-01\nThis project uses pnpm\n');
Comment thread Fixed

const result = readProjectMemory(testDir);
expect(result).toContain('pnpm');
});

it('should return undefined for empty memory file', () => {
const ralphDir = join(testDir, '.ralph');
mkdirSync(ralphDir, { recursive: true });
writeFileSync(join(ralphDir, 'memory.md'), '');
Comment thread Fixed

expect(readProjectMemory(testDir)).toBeUndefined();
});
});

describe('appendProjectMemory', () => {
it('should create .ralph directory and memory file', () => {
appendProjectMemory(testDir, 'Tests are in __tests__/');

const memoryPath = join(testDir, '.ralph', 'memory.md');
expect(existsSync(memoryPath)).toBe(true);

const content = readFileSync(memoryPath, 'utf-8');
expect(content).toContain('Tests are in __tests__/');
expect(content).toMatch(/^## \d{4}-\d{2}-\d{2}/);
});

it('should append multiple entries', () => {
appendProjectMemory(testDir, 'Entry 1');
appendProjectMemory(testDir, 'Entry 2');

const content = readFileSync(join(testDir, '.ralph', 'memory.md'), 'utf-8');
expect(content).toContain('Entry 1');
expect(content).toContain('Entry 2');
});
});

describe('formatMemoryPrompt', () => {
it('should format memory as a prompt section', () => {
const result = formatMemoryPrompt('This project uses pnpm');
expect(result).toContain('Project Memory');
expect(result).toContain('pnpm');
expect(result).toContain('.ralph/memory.md');
});
});
});
20 changes: 20 additions & 0 deletions src/loop/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import {
type PlanBudget,
} from './cost-tracker.js';
import { estimateLoop, formatEstimateDetailed } from './estimator.js';
import { appendProjectMemory, formatMemoryPrompt, readProjectMemory } from './memory.js';
import { checkFileBasedCompletion, createProgressTracker, type ProgressEntry } from './progress.js';
import { RateLimiter } from './rate-limiter.js';
import { analyzeResponse, hasExitSignal } from './semantic-analyzer.js';
Expand Down Expand Up @@ -556,6 +557,13 @@ export async function runLoop(options: LoopOptions): Promise<LoopResult> {
taskWithSkills = `${options.task}\n\n${skillsPrompt}`;
}

// Inject project memory from previous runs (if available)
const projectMemory = readProjectMemory(options.cwd);
if (projectMemory) {
taskWithSkills = `${taskWithSkills}\n\n${formatMemoryPrompt(projectMemory)}`;
log(chalk.dim(' Project memory loaded from .ralph/memory.md'));
}

// Build abbreviated spec summary for context builder (iterations 2+)
const specSummary = buildSpecSummary(options.cwd);

Expand Down Expand Up @@ -1665,6 +1673,18 @@ export async function runLoop(options: LoopOptions): Promise<LoopResult> {
log(chalk.dim(costTracker.formatStats()));
}

// Save a run summary to project memory for future runs
const isSuccess = exitReason === 'completed' || exitReason === 'file_signal';
const memorySummary = [
`Task: ${options.taskTitle || options.task.slice(0, 100)}`,
`Result: ${isSuccess ? 'success' : exitReason}`,
`Iterations: ${finalIteration}, Commits: ${commits.length}`,
];
if (costTracker) {
memorySummary.push(`Cost: ${formatCost(costTracker.getStats().totalCost.totalCost)}`);
}
appendProjectMemory(options.cwd, memorySummary.join('\n'));

return {
success: exitReason === 'completed' || exitReason === 'file_signal',
iterations: finalIteration,
Expand Down
75 changes: 75 additions & 0 deletions src/loop/memory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/**
* Project Memory
*
* Persistent memory file (.ralph/memory.md) that survives across separate `ralph run` invocations.
* The agent can learn project conventions, tool preferences, and patterns over time.
*/

import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';

const MEMORY_FILE = 'memory.md';
const MAX_MEMORY_BYTES = 8 * 1024; // 8KB max — keeps context window usage reasonable

/**
* Read the project memory file.
* Returns undefined if no memory exists yet.
*/
export function readProjectMemory(cwd: string): string | undefined {
try {
const memoryPath = join(cwd, '.ralph', MEMORY_FILE);
if (!existsSync(memoryPath)) return undefined;

const content = readFileSync(memoryPath, 'utf-8').trim();
if (!content) return undefined;

// Truncate if too large (keep the most recent entries)
if (Buffer.byteLength(content) > MAX_MEMORY_BYTES) {
const entries = content.split(/^## /m).filter((e) => e.trim());
let result = '';
// Build from newest to oldest, staying under budget
for (let i = entries.length - 1; i >= 0; i--) {
const entry = `## ${entries[i]}`;
if (Buffer.byteLength(result + entry) > MAX_MEMORY_BYTES) break;
result = entry + result;
}
return result.trim() || undefined;
}

return content;
} catch {
return undefined;
}
}

/**
* Append an entry to the project memory file.
*/
export function appendProjectMemory(cwd: string, entry: string): void {
try {
const ralphDir = join(cwd, '.ralph');
if (!existsSync(ralphDir)) mkdirSync(ralphDir, { recursive: true });

const memoryPath = join(ralphDir, MEMORY_FILE);
const timestamp = new Date().toISOString().split('T')[0];
const formatted = `## ${timestamp}\n${entry.trim()}\n\n`;

appendFileSync(memoryPath, formatted);
} catch {
// Non-critical — don't break the loop
}
}

/**
* Format memory content as a prompt section for injection into agent context.
*/
export function formatMemoryPrompt(memory: string): string {
return `## Project Memory (from previous runs)
The following notes were saved from previous ralph-starter runs on this project.
Use them to understand project conventions and avoid repeating mistakes.

${memory}

If you discover new project conventions or important patterns, append them to \`.ralph/memory.md\`.
`;
}
Loading