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
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ This repository is an npm workspace monorepo:
- `packages/workflow-graph`: Graph rules shared by the editor and the server (handles, conditions, legacy upgrades, run-readiness checks).
- `packages/workflow-engine`: Reusable workflow runtime.
- `design-system/`: Git submodule with UI tokens/components.
- `data/runs/`: Runtime run snapshots (gitignored); the newest 20 are kept.
- `data/runs/`: Runtime run snapshots (gitignored); the newest 20 within 800,000 bytes are kept, and a run over 90,000 bytes is saved shortened with its full record in `data/runs/full/` (see `docs/run-persistence.md`).
- `data/workflow.json`: The learner's canvas, saved by the editor (gitignored).
- `apps/server/src/report`: `npm run report`, the workflow and run report for an LLM grader.
- `.config/config.json`: Provider/model definitions (committed); schema in `docs/configuration.md`.
Expand Down
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ Each run/resume operation persists `data/runs/<start time>_<runId>.json` (format
- `currentNodeId`
- `waitingForInput`

The newest 20 runs are kept; paused runs are never deleted. The editor also saves the canvas to `data/workflow.json` (`PUT /api/workflow`) and loads it first. `npm run report` (`apps/server/src/report`) turns both into the text an LLM grader reads; see `docs/report.md`.
The newest 20 runs within 800,000 bytes are kept; paused runs are kept while they can be resumed. A run over 90,000 bytes is saved with its longest texts shortened (and, as a last resort, middle log entries left out), and in full under `data/runs/full/`, which sessions do not save (`apps/server/src/services/run-size.ts`). The editor also saves the canvas to `data/workflow.json` (`PUT /api/workflow`) and loads it first. `npm run report` (`apps/server/src/report`) turns both into the text an LLM grader reads; see `docs/report.md`.

## Paused-run restoration

Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export interface CreateAppOptions {
dataDir?: string;
projectRoot: string;
runsToKeep?: WorkflowRouterOptions['runsToKeep'];
pausedRunTtlMs?: WorkflowRouterOptions['pausedRunTtlMs'];
resolveModels?: WorkflowRouterOptions['resolveModels'];
now?: WorkflowRouterOptions['now'];
maxSteps?: number;
Expand Down Expand Up @@ -40,6 +41,7 @@ export function createApp(options: CreateAppOptions): { app: Express; store: Run
dataDir: options.dataDir ?? path.dirname(options.runsDir),
projectRoot: options.projectRoot,
runsToKeep: options.runsToKeep,
pausedRunTtlMs: options.pausedRunTtlMs,
resolveModels: options.resolveModels,
now: options.now,
maxSteps: options.maxSteps,
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ async function bootstrap() {
dataDir: config.dataDir,
projectRoot: config.projectRoot,
maxSteps: config.maxSteps,
pausedRunTtlMs: config.pausedRunTtlMs,
preflight: (graph) => llmService.preflight(graph),
resolveModels: (graph) => {
const current = readConfig(configStore);
Expand Down
6 changes: 6 additions & 0 deletions apps/server/src/report/build.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,12 @@ describe('buildReport', () => {
expect(run).toContain('Branch taken: Otherwise (no condition matched) → Researcher');
});

it('says when a run was saved with shortened texts', async () => {
const record = { ...(await recordRun(researchWorkflow(), { Researcher: 'READY' })), shortenedTexts: 3 };
const run = section(buildReport(input({ runs: runsOf([record]) })), '### Run 1 (');
expect(run).toContain('- Saved shortened: 3 long texts were cut to keep the run within the workspace save limit');
});

it('reads legacy runs that have no start time, models or condition type', () => {
const workflow = researchWorkflow() as WorkflowGraph;
workflow.nodes.find((node) => node.id === 'gate')!.type = 'if';
Expand Down
5 changes: 5 additions & 0 deletions apps/server/src/report/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -817,6 +817,11 @@ function runOutcome(view: RunView): string[] {
function describeRunInFull(view: RunView, current: AnalysedWorkflow | null, info: ReportModelInfo): string[] {
const lines = [`### Run ${view.number} (started ${formatTime(view.run.startedAtMs)})`, ''];
lines.push(`- Status: ${view.record.status}, ${runDuration(view)}`);
if (view.record.shortenedTexts) {
lines.push(
`- Saved shortened: ${view.record.shortenedTexts} long ${view.record.shortenedTexts === 1 ? 'text was' : 'texts were'} cut to keep the run within the workspace save limit; each cut is marked.`
);
}
if (view.isCurrent === true) lines.push('- Workflow: the current workflow');
if (view.isCurrent === false && current) {
const changes = describeChanges(view.workflow, current);
Expand Down
8 changes: 7 additions & 1 deletion apps/server/src/routes/workflows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ export interface WorkflowRouterOptions {
projectRoot: string;
/** Run files kept on disk. Default 20. */
runsToKeep?: number;
/** How long a paused run can be resumed; older paused runs are pruned like finished ones. */
pausedRunTtlMs?: number;
/** Model id each agent node of `graph` will run with. */
resolveModels?: (graph: WorkflowGraph) => Record<string, string>;
now?: () => Date;
Expand Down Expand Up @@ -90,7 +92,11 @@ export function createWorkflowRouter(options: WorkflowRouterOptions): Router {
};
try {
await saveRunRecord(runsDir, record);
await pruneRunRecords(runsDir, runsToKeep);
await pruneRunRecords(runsDir, {
keep: runsToKeep,
pausedRunTtlMs: options.pausedRunTtlMs,
now: () => now().getTime()
});
} catch (error) {
logger.error('Failed to persist run result', error);
}
Expand Down
223 changes: 223 additions & 0 deletions apps/server/src/services/persistence.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import type { WorkflowRunRecord } from '@agentflow/types';
import { RUN_RECORD_FORMAT_VERSION } from '@agentflow/types';
import {
FULL_RUNS_DIR,
listRunRecords,
pruneRunRecords,
readRunRecord,
runFileName,
saveRunRecord
} from './persistence.js';
import { RUN_FILE_LIMIT_BYTES, RUNS_TOTAL_LIMIT_BYTES, fitRunRecord } from './run-size.js';

let runsDir: string;
let sequence = 0;

beforeEach(async () => {
runsDir = path.join(await fs.mkdtemp(path.join(os.tmpdir(), 'agentflow-runs-')), 'runs');
});

afterEach(async () => {
await fs.rm(path.dirname(runsDir), { recursive: true, force: true });
});

/** A completed run whose agent wrote `outputLength` characters. */
function run(outputLength: number, overrides: Partial<WorkflowRunRecord> = {}): WorkflowRunRecord {
sequence += 1;
const output = 'x'.repeat(outputLength);
const startedAt = new Date(Date.parse('2026-12-04T10:00:00.000Z') + sequence * 60_000).toISOString();
return {
formatVersion: RUN_RECORD_FORMAT_VERSION,
runId: `run-${sequence}`,
startedAt,
finishedAt: startedAt,
workflow: { nodes: [{ id: 'start', type: 'start', x: 0, y: 0 }], connections: [] },
models: {},
logs: [
{ timestamp: startedAt, nodeId: 'a', type: 'step_start', content: 'Agent' },
{
timestamp: startedAt,
nodeId: 'a',
type: 'subagent_call_end',
content: JSON.stringify({ callId: 'call-1', subagentNodeId: 'b', output })
},
{ timestamp: startedAt, nodeId: 'a', type: 'llm_response', content: output }
],
status: 'completed',
state: { previous_output: output, a: output },
currentNodeId: null,
waitingForInput: false,
...overrides
};
}

const savedSize = async (record: WorkflowRunRecord) => (await fs.stat(path.join(runsDir, runFileName(record)))).size;
const savedCopy = async (record: WorkflowRunRecord): Promise<WorkflowRunRecord> =>
JSON.parse(await fs.readFile(path.join(runsDir, runFileName(record)), 'utf-8')) as WorkflowRunRecord;
const fullCopyExists = (record: WorkflowRunRecord) =>
fs.access(path.join(runsDir, FULL_RUNS_DIR, runFileName(record))).then(
() => true,
() => false
);

describe('fitRunRecord', () => {
it('leaves a record that fits as it is', () => {
const record = run(1_000);
const fitted = fitRunRecord(record);
expect(fitted.shortenedTexts).toBe(0);
expect(JSON.parse(fitted.text)).toEqual(record);
});

it('shortens the longest texts to fit, keeps JSON log events parseable and marks each cut', () => {
const record = run(60_000);
const fitted = fitRunRecord(record);
expect(Buffer.byteLength(fitted.text)).toBeLessThanOrEqual(RUN_FILE_LIMIT_BYTES);
expect(fitted.shortenedTexts).toBe(4);
const saved = JSON.parse(fitted.text) as WorkflowRunRecord;
expect(saved.shortenedTexts).toBe(4);
expect(saved.logs[0].content).toBe('Agent');
const event = JSON.parse(saved.logs[1].content) as { callId: string; output: string };
expect(event.callId).toBe('call-1');
expect(event.output).toMatch(/more characters were cut when this run was saved/);
expect(saved.logs[2].content.startsWith('x'.repeat(1_000))).toBe(true);
expect(saved.state?.previous_output).toMatch(/more characters were cut/);
expect(saved.workflow).toEqual(record.workflow);
});

it('keeps the state of a paused run, which it resumes from, when shortening the logs is enough', () => {
const record = run(40_000, { status: 'paused', waitingForInput: true, currentNodeId: 'gate' });
const saved = JSON.parse(fitRunRecord(record).text) as WorkflowRunRecord;
expect(saved.state).toEqual(record.state);
expect(saved.logs[2].content).toMatch(/more characters were cut/);
});

it("shortens a paused run's state too when the logs alone are not enough", () => {
const record = run(60_000, { status: 'paused', waitingForInput: true, currentNodeId: 'gate' });
const fitted = fitRunRecord(record);
expect(Buffer.byteLength(fitted.text)).toBeLessThanOrEqual(RUN_FILE_LIMIT_BYTES);
const saved = JSON.parse(fitted.text) as WorkflowRunRecord;
expect(saved.state?.previous_output).toMatch(/more characters were cut/);
});

it('leaves out log entries from the middle of a run that loops to the step limit, keeping its start and end', () => {
const record = run(100);
record.logs = Array.from({ length: 600 }, (_, index) => ({
timestamp: record.startedAt!,
nodeId: 'a',
type: 'llm_response',
content: `entry ${index} ${'x'.repeat(2_000)}`
}));
const fitted = fitRunRecord(record);
expect(Buffer.byteLength(fitted.text)).toBeLessThanOrEqual(RUN_FILE_LIMIT_BYTES);
const saved = JSON.parse(fitted.text) as WorkflowRunRecord;
const marker = saved.logs.find((entry) => entry.nodeId === 'system');
expect(marker?.type).toBe('warn');
expect(marker?.content).toMatch(/^\d+ log entries from the middle of this run were left out when it was saved/);
expect(saved.logs[0].content.startsWith('entry 0 ')).toBe(true);
expect(saved.logs.at(-1)?.content.startsWith('entry 599 ')).toBe(true);
expect(saved.logs.length).toBeGreaterThan(100);
});

it('keeps counting the cuts of a record restored from a shortened copy', () => {
const shortened = JSON.parse(fitRunRecord(run(150_000)).text) as WorkflowRunRecord;
const { shortenedTexts: _count, ...restored } = shortened;
const fitted = fitRunRecord({ ...restored, status: 'completed' });
expect(fitted.shortenedTexts).toBe(0);
expect((JSON.parse(fitted.text) as WorkflowRunRecord).shortenedTexts).toBe(shortened.shortenedTexts);
});
});

describe('saveRunRecord', () => {
it('saves a small run once, with no full copy', async () => {
const record = run(1_000);
await saveRunRecord(runsDir, record);
expect(await savedCopy(record)).toEqual(record);
expect(await fullCopyExists(record)).toBe(false);
});

it('saves a big run shortened, keeps the full record beside it, and reads the full one while it exists', async () => {
const record = run(150_000);
await saveRunRecord(runsDir, record);
expect(await savedSize(record)).toBeLessThanOrEqual(RUN_FILE_LIMIT_BYTES);
expect((await savedCopy(record)).shortenedTexts).toBeGreaterThan(0);
expect(await fullCopyExists(record)).toBe(true);
expect(await readRunRecord(runsDir, record.runId)).toEqual(record);
expect((await listRunRecords(runsDir)).map((stored) => stored.record)).toEqual([record]);

// A return visit: the session saved data/runs but not data/runs/full.
await fs.rm(path.join(runsDir, FULL_RUNS_DIR), { recursive: true });
const restored = await readRunRecord(runsDir, record.runId);
expect(restored?.shortenedTexts).toBeGreaterThan(0);
expect(restored?.logs[2].content).toMatch(/more characters were cut/);
});

it('drops the full copy when the run is saved again small enough', async () => {
const record = run(150_000, { status: 'paused', waitingForInput: true, currentNodeId: 'gate', state: {} });
await saveRunRecord(runsDir, record);
expect(await fullCopyExists(record)).toBe(true);
await saveRunRecord(runsDir, { ...record, logs: record.logs.slice(0, 1), status: 'completed' });
expect(await fullCopyExists(record)).toBe(false);
});
});

describe('pruneRunRecords', () => {
it('keeps the newest runs within the count', async () => {
const records = [run(100), run(100), run(100)];
for (const record of records) await saveRunRecord(runsDir, record);
expect(await pruneRunRecords(runsDir, { keep: 2 })).toEqual([records[0].runId]);
});

it('deletes the oldest runs, and their full copies, until the saved files fit the total limit', async () => {
const records = Array.from({ length: 12 }, () => run(150_000));
for (const record of records) await saveRunRecord(runsDir, record);
const deleted = await pruneRunRecords(runsDir);
const kept = await listRunRecords(runsDir);
expect(deleted.length).toBeGreaterThan(0);
expect(deleted).toContain(records[0].runId);
expect(kept.reduce((total, stored) => total + stored.sizeBytes, 0)).toBeLessThanOrEqual(RUNS_TOTAL_LIMIT_BYTES);
expect(kept.map((stored) => stored.record.runId)).toContain(records[11].runId);
expect(await fullCopyExists(records[0])).toBe(false);
});

it('keeps only the newest runs: from the first that does not fit, older ones go too', async () => {
const older = run(100);
const big = run(150_000);
const newer = Array.from({ length: 9 }, () => run(150_000));
for (const record of [older, big, ...newer]) await saveRunRecord(runsDir, record);
const deleted = await pruneRunRecords(runsDir);
expect(deleted).toEqual(expect.arrayContaining([older.runId, big.runId]));
});

it('counts paused runs toward the total before keeping finished ones', async () => {
const paused = run(150_000, { status: 'paused', waitingForInput: true, currentNodeId: 'gate' });
await saveRunRecord(runsDir, paused);
for (let index = 0; index < 9; index += 1) await saveRunRecord(runsDir, run(150_000));
await pruneRunRecords(runsDir);
const kept = await listRunRecords(runsDir);
expect(kept.map((stored) => stored.record.runId)).toContain(paused.runId);
expect(kept.reduce((total, stored) => total + stored.sizeBytes, 0)).toBeLessThanOrEqual(RUNS_TOTAL_LIMIT_BYTES);
});

it('prunes a paused run like a finished one once it can no longer be resumed', async () => {
const paused = run(100, { status: 'paused', waitingForInput: true, currentNodeId: 'gate' });
await saveRunRecord(runsDir, paused);
await saveRunRecord(runsDir, run(100));
const day = 24 * 60 * 60 * 1000;
expect(await pruneRunRecords(runsDir, { keep: 1, pausedRunTtlMs: day })).toEqual([]);
const later = () => Date.now() + 2 * day;
expect(await pruneRunRecords(runsDir, { keep: 1, pausedRunTtlMs: day, now: later })).toEqual([paused.runId]);
});

it('never deletes a paused run', async () => {
const paused = run(150_000, { status: 'paused', waitingForInput: true, currentNodeId: 'gate' });
await saveRunRecord(runsDir, paused);
for (let index = 0; index < 12; index += 1) await saveRunRecord(runsDir, run(150_000));
const deleted = await pruneRunRecords(runsDir);
expect(deleted).not.toContain(paused.runId);
expect(await readRunRecord(runsDir, paused.runId)).toEqual(paused);
});
});
Loading
Loading