repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/ultra/journal.ts
RawFile outline
- JournalFile line 9
- version line 10
- complete line 11
- entries line 12
- WorkflowJournalOptions line 15
- cwd line 16
- home line 17
- spec line 18
- args line 19
- FileWorkflowJournal line 22
- path line 23
- WorkflowRunStatus line 26
- SavedWorkflowRun line 28
- id line 29
- workflow line 30
- cwd line 31
- startedAt line 32
- status line 33
- spec line 34
- args line 35
- result line 36
- error line 37
- SaveWorkflowRunOptions line 40
- home line 41
- stableJson line 44
- journalId line 56
- agentDir line 69
- journalFile line 73
- runsDir line 81
- safeRunId line 85
- saveWorkflowRun line 89
- listWorkflowRuns line 97
- deleteWorkflowRun line 119
- readFile line 132
- writeFile line 146
- createWorkflowJournal line 151
- get line 158
- set line 161
- complete line 166
import { createHash } from "node:crypto";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { WorkflowJournal } from "./engine.ts";
import type { RunStepResult } from "./runner.ts";
import type { WorkflowSpec } from "./spec.ts";
interface JournalFile {
version: 1;
complete: boolean;
entries: Record<string, RunStepResult>;
}
export interface WorkflowJournalOptions {
cwd: string;
home?: string;
spec: WorkflowSpec;
args?: Record<string, unknown>;
}
export interface FileWorkflowJournal extends WorkflowJournal {
path: string;
}
export type WorkflowRunStatus = "running" | "completed" | "failed";
export interface SavedWorkflowRun {
id: string;
workflow: string;
cwd: string;
startedAt: string;
status: WorkflowRunStatus;
spec?: WorkflowSpec;
args?: Record<string, unknown>;
result?: unknown;
error?: string;
}
export interface SaveWorkflowRunOptions extends SavedWorkflowRun {
home?: string;
}
function stableJson(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
if (value && typeof value === "object") {
const record = value as Record<string, unknown>;
return `{${Object.keys(record)
.sort()
.map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`)
.join(",")}}`;
}
return JSON.stringify(value);
}
function journalId(opts: WorkflowJournalOptions): string {
return createHash("sha256")
.update(
stableJson({
cwd: opts.cwd,
workflow: opts.spec.name,
args: opts.args ?? null,
}),
)
.digest("hex")
.slice(0, 32);
}
function agentDir(home = os.homedir()): string {
return path.join(home, ".pi", "agent");
}
function journalFile(opts: WorkflowJournalOptions): string {
return path.join(
agentDir(opts.home),
"ultra-journals",
`${journalId(opts)}.json`,
);
}
function runsDir(home = os.homedir()): string {
return path.join(agentDir(home), "ultra-runs");
}
function safeRunId(id: string): boolean {
return /^[A-Za-z0-9_-]+$/.test(id);
}
export function saveWorkflowRun(opts: SaveWorkflowRunOptions): void {
if (!safeRunId(opts.id)) throw new Error("Invalid ultra run id");
const { home, ...run } = opts;
const file = path.join(runsDir(home), `${run.id}.json`);
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, `${JSON.stringify(run, null, 2)}\n`, "utf8");
}
export function listWorkflowRuns(home?: string): SavedWorkflowRun[] {
try {
return fs
.readdirSync(runsDir(home))
.filter((file) => file.endsWith(".json"))
.flatMap((file) => {
try {
return [
JSON.parse(
fs.readFileSync(path.join(runsDir(home), file), "utf8"),
) as SavedWorkflowRun,
];
} catch {
return [];
}
})
.sort((a, b) => b.startedAt.localeCompare(a.startedAt));
} catch {
return [];
}
}
export function deleteWorkflowRun(
home: string | undefined,
id: string,
): boolean {
if (!safeRunId(id)) return false;
try {
fs.unlinkSync(path.join(runsDir(home), `${id}.json`));
return true;
} catch {
return false;
}
}
function readFile(file: string): JournalFile {
try {
const parsed = JSON.parse(
fs.readFileSync(file, "utf8"),
) as Partial<JournalFile>;
if (parsed.version !== 1 || parsed.complete || !parsed.entries) {
return { version: 1, complete: false, entries: {} };
}
return { version: 1, complete: false, entries: parsed.entries };
} catch {
return { version: 1, complete: false, entries: {} };
}
}
function writeFile(file: string, data: JournalFile): void {
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, `${JSON.stringify(data, null, 2)}\n`, "utf8");
}
export function createWorkflowJournal(
opts: WorkflowJournalOptions,
): FileWorkflowJournal {
const file = journalFile(opts);
const data = readFile(file);
return {
path: file,
get(key) {
return data.entries[key];
},
set(key, result) {
if (!result.ok) return;
data.entries[key] = result;
writeFile(file, data);
},
complete() {
data.complete = true;
writeFile(file, data);
},
};
}