Repository navigation
Expand file tree
/
Copy pathrun-store.ts
More file actions
59 lines (53 loc) · 2.72 KB
/
Copy pathrun-store.ts
File metadata and controls
59 lines (53 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import type { StartOptions, StepName } from "@codehands/contracts";
import type { SandboxResult } from "../runtime/sandbox.js";
import type { Verdict } from "./prompts.js";
// Everything the engine needs to carry on after a restart: what each finished step gave,
// and where the run stands. One file per run, next to its step files:
// <runsRoot>/<sessionId>/run.json. Saved before every event goes out.
export interface RunState {
options: StartOptions;
status: "running" | "stopped" | "awaiting_approval" | "failed";
step?: StepName; // the step running now
analysis?: string; // set when analyze finished
plan?: string; // set when plan finished
implemented?: boolean; // Claude Code finished: the change is in the worktree
tests?: SandboxResult; // the test step's result, output cut short
review?: { verdict: Verdict; text: string }; // set when review finished, or failed
lastSeq: number; // the last event sent, so seq carries on
files: number; // step files written so far
costUsd: number;
}
// Session ids name folders, so one like ../../x must never reach the disk.
const SAFE_ID = /^[\w-]+$/;
export class RunStore {
constructor(private readonly root: string) { }
// Writes to a temp file first, so a crash mid-write can't leave half a state.
save(state: RunState): void {
const dir = join(this.root, state.options.sessionId);
mkdirSync(dir, { recursive: true });
const file = join(dir, "run.json");
writeFileSync(`${file}.tmp`, JSON.stringify(state));
renameSync(`${file}.tmp`, file);
}
// undefined when the session isn't the engine's: a Claude Code run, or an unknown id.
load(sessionId: string): RunState | undefined {
if (!SAFE_ID.test(sessionId)) return undefined;
let text: string;
try {
text = readFileSync(join(this.root, sessionId, "run.json"), "utf8");
} catch (err) {
if ((err as NodeJS.ErrnoException).code === "ENOENT") return undefined;
throw err;
}
return JSON.parse(text) as RunState;
}
// Every run with a state file, including ones from before a restart.
ids(): string[] {
if (!existsSync(this.root)) return [];
return readdirSync(this.root, { withFileTypes: true })
.filter((d) => d.isDirectory() && existsSync(join(this.root, d.name, "run.json")))
.map((d) => d.name);
}
}