@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
254 lines • 12.2 kB
JavaScript
import { randomUUID } from "node:crypto";
import { open, rename, rm, stat } from "node:fs/promises";
import { basename, dirname, join, resolve } from "node:path";
import { createAdmissionLine, openSessionStore, openSyncSessionStore, } from "@earendil-works/pi-agent-core";
import { captureFileIdentity } from "../session-file-identity.js";
import { createJsonlImporter } from "../session-import/jsonl-import.js";
/** The S07 importer's key rule: an entry id that starts with `~` gets one more, so it cannot equal a positional key. */
export const storeKeyOf = (entryId) => (entryId.startsWith("~") ? `~${entryId}` : entryId);
const STALE = "session-store/projection-stale/";
const staleKey = (path) => STALE + encodeURIComponent(path);
const codeOf = (error) => error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : "unknown";
const messageOf = (error) => (error instanceof Error ? error.message : String(error));
function projectionImage(header, entries) {
return [JSON.stringify(header), ...entries.map((entry) => entry.line)].map((line) => `${line}\n`).join("");
}
async function stampOf(path) {
try {
const value = await stat(path);
return { size: value.size, mtimeMs: value.mtimeMs, ctimeMs: value.ctimeMs };
}
catch (error) {
if (codeOf(error) === "ENOENT")
return undefined;
throw error;
}
}
/** Today's atomic replace, asynchronous: a temp file written and synced beside the target, then renamed over it. */
async function replaceAtomically(path, contents) {
const mode = (await modeOf(path)) ?? 0o600;
const temp = join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
const handle = await open(temp, "wx", mode);
let identity;
try {
await handle.writeFile(contents);
await handle.sync();
identity = await captureFileIdentity(handle.fd, path);
}
finally {
await handle.close();
}
try {
await rename(temp, path);
}
catch (error) {
await rm(temp, { force: true });
throw error;
}
return identity;
}
async function modeOf(path) {
try {
return (await stat(path)).mode & 0o777;
}
catch (error) {
if (codeOf(error) === "ENOENT")
return undefined;
throw error;
}
}
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
const staleSessionIdOf = (mark) => isRecord(mark) && typeof mark.sessionId === "string" ? mark.sessionId : undefined;
/** A provided ProjectionFiles is called as a method, so a class implementing it keeps its `this`; its identity is unknown. */
async function replaceWith(files, path, contents) {
if (files === undefined)
return replaceAtomically(path, contents);
await files.replace(path, contents);
return undefined;
}
/**
* A SessionManager's binding to the durable store (S20b). Every write commits to the store first; the JSONL is its
* projection. A projection write that fails after the commit never throws (the store took the entry): it commits a
* durable stale mark, warns once per failed write, and the JSONL is rewritten from the store off the caller's call.
* The binding adds no synchronous filesystem call to the session path: stamps and reprojection run on its admission
* line.
*/
export class DurableSessionBinding {
constructor(binding, handle, importer, admission, warn, hooks, projectedSize) {
this.stale = false;
// Bumped by every store commit: a deferred whole-image ledger record is skipped once a later write superseded it.
this.generation = 0;
// Projected appends not yet in the ledger, in file order. A later append's record carries them, so a burst of appends
// keeps the ledger's prefix chain even though only the last one's record runs.
this.unrecordedTails = [];
// A whole-file write whose ledger record a later append superseded: the chain has no start until a record covers the
// whole file, so the next record writes today's whole image instead of the tails.
this.wholeUnrecorded = false;
this.binding = binding;
this.handle = handle;
this.importer = importer;
this.admission = admission;
this.warn = warn;
this.hooks = hooks;
this.projectedSize = projectedSize;
}
static async open(binding, sessionFile, sessionId, headerLine, warn, hooks) {
const { store, epoch } = binding;
const path = resolve(sessionFile);
const admission = createAdmissionLine();
const importer = createJsonlImporter({ store, epoch, admission });
let id = sessionId;
let reprojected = false;
if ((await stampOf(path)) !== undefined) {
const mark = await store.getDocument(staleKey(path));
const markedId = staleSessionIdOf(mark);
if (markedId !== undefined) {
const stored = await openSessionStore(store, epoch).load(markedId);
if (stored === undefined)
throw new Error(`the store marks ${path} stale but holds no session ${markedId}`);
await reprojectFile(importer, admission, binding, hooks, path, projectionImage(stored.header, stored.entries));
id = markedId;
reprojected = true;
}
else {
id = (await importer.importFile(path)).sessionId;
}
}
const handle = await openSyncSessionStore(store, epoch).open(id, JSON.parse(headerLine));
const size = (await stampOf(path))?.size ?? 0;
return {
session: new DurableSessionBinding(binding, handle, importer, admission, warn, hooks, size),
reprojected,
};
}
/** Store first: a refusal throws here, on the caller's call, and nothing was taken. */
commitAppend(entries) {
this.handle.appendSync(entries);
this.generation++;
}
commitRewrite(headerLine, entries) {
this.handle.rewriteSync(JSON.parse(headerLine), entries);
this.generation++;
}
/** While stale, the JSONL is not appended to: it is rewritten whole from the store. */
projectionStale() {
return this.stale;
}
/** The caller appended `entry`'s line to the file. The ledger records only those bytes, asynchronously. */
projected(sessionFile, entry) {
const path = resolve(sessionFile);
const offset = this.projectedSize;
this.projectedSize += Buffer.byteLength(entry.line) + 1;
const sessionId = String(this.handle.header().id);
this.unrecordedTails.push({ key: entry.key, line: entry.line, offset });
this.record(path, async () => {
const tails = [...this.unrecordedTails];
const whole = this.wholeUnrecorded ? projectionImage(this.handle.header(), this.handle.entries()) : undefined;
const written = await stampOf(path);
if (written === undefined)
return;
if (whole === undefined)
await this.importer.recordProjectedTail(path, sessionId, tails, written);
else
await this.importer.recordProjection(path, whole, written);
this.unrecordedTails.splice(0, tails.length);
if (whole !== undefined)
this.wholeUnrecorded = false;
});
}
/** The caller wrote the whole file from today's serializer: record that image, unless a later write supersedes it. */
recordWhole(sessionFile) {
const path = resolve(sessionFile);
const contents = projectionImage(this.handle.header(), this.handle.entries());
this.projectedSize = Buffer.byteLength(contents);
this.unrecordedTails = [];
this.wholeUnrecorded = true;
this.record(path, async () => {
const written = await stampOf(path);
if (written === undefined)
return;
await this.importer.recordProjection(path, contents, written);
this.wholeUnrecorded = false;
});
}
/** Marks the projection stale in the store (durable, so a crash before the repair still reprojects on open). */
projectionFailed(sessionFile, error) {
const path = resolve(sessionFile);
let unmarked = "";
if (!this.stale) {
try {
const data = { sessionId: String(this.handle.header().id) };
this.binding.store.commitSync(this.binding.epoch, [{ op: "put", key: staleKey(path), data }], () => { });
}
catch (markError) {
unmarked = `; the stale mark was not stored (${messageOf(markError)})`;
}
this.stale = true;
}
this.warn({ path, code: codeOf(error), message: `${messageOf(error)}${unmarked}` });
}
/** The file no longer matches the store (it was rewritten from an older image): mark it stale and reproject. */
markProjectionStale(sessionFile) {
const path = resolve(sessionFile);
if (!this.stale) {
const data = { sessionId: String(this.handle.header().id) };
this.binding.store.commitSync(this.binding.epoch, [{ op: "put", key: staleKey(path), data }], () => { });
this.stale = true;
}
this.scheduleRepair(path);
}
/** Settles once any scheduled reprojection and ledger record has run (tests and orderly shutdown). */
settled() {
return this.admission.admit(async () => { });
}
// One repair per stale write, serialized on the admission line and fully asynchronous. A repair that a later write
// overtook keeps the mark and runs again; one that fails warns, so a persistent failure is reported on each write.
scheduleRepair(sessionFile) {
const path = resolve(sessionFile);
void this.admission
.admit(async () => {
if (!this.stale)
return;
const generation = this.generation;
const contents = projectionImage(this.handle.header(), this.handle.entries());
this.hooks.beforeWrite(path);
this.hooks.afterReplace(path, await replaceWith(this.binding.files, path, contents));
if (generation !== this.generation)
return this.scheduleRepair(path);
this.binding.store.commitSync(this.binding.epoch, [{ op: "delete", key: staleKey(path) }], () => { });
this.stale = false;
this.projectedSize = Buffer.byteLength(contents);
this.unrecordedTails = [];
this.wholeUnrecorded = false;
const written = await stampOf(path);
if (written !== undefined && generation === this.generation) {
await this.importer.recordProjection(path, contents, written);
}
})
.catch((error) => this.projectionFailed(path, error));
}
// A ledger record a later write superseded (it committed while this one awaited) is dropped, not reported: the later
// write records its own projection, or marks the projection stale.
record(path, write) {
const generation = this.generation;
void this.admission
.admit(async () => {
if (generation === this.generation)
await write();
})
.catch((error) => {
if (generation !== this.generation)
return;
this.warn({ path, code: codeOf(error), message: `projection ledger not recorded: ${messageOf(error)}` });
});
}
}
async function reprojectFile(importer, admission, binding, hooks, path, contents) {
hooks.beforeWrite(path);
hooks.afterReplace(path, await replaceWith(binding.files, path, contents));
const written = await stampOf(path);
if (written !== undefined)
await admission.admit(() => importer.recordProjection(path, contents, written));
binding.store.commitSync(binding.epoch, [{ op: "delete", key: staleKey(path) }], () => { });
}
//# sourceMappingURL=durable-binding.js.map