@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
102 lines • 4.44 kB
JavaScript
import { createHash } from "node:crypto";
import { closeSync, fstatSync, openSync, readSync } from "node:fs";
import { parseSessionEntryLine, SESSION_READ_BUFFER_SIZE, SessionLineSplitter } from "./session-entry-file.js";
/** The committed transcript changes a consumer has not taken yet; it exists only once a consumer began it. */
export class TranscriptJournal {
constructor() {
this.pending = [];
}
record(...transitions) {
this.pending.push(...transitions);
}
drain() {
const taken = this.pending;
this.pending = [];
return taken;
}
}
/** One entry's part of `idFingerprint`, whatever the parsed line holds; the recovery base scan hashes the same. */
export const fingerprintLine = (entry) => `${entry.type}\u0000${entry.id}\n`;
function fingerprint(entries) {
const hash = createHash("sha256");
for (const entry of entries)
hash.update(fingerprintLine(entry));
return hash.digest("hex");
}
/** The parent link of a file entry; the session header has none. */
const entryParent = (entry) => (entry.type === "session" ? null : entry.parentId);
/** Describe the loaded/written entries now; the owning descriptor supplies their identity asynchronously. */
export function captureTranscriptBase(entries) {
return {
count: entries.length,
idFingerprint: fingerprint(entries),
history: entries.filter((entry) => entry.type !== "session").length,
};
}
/**
* Reads `base` through its captured identity only. It stops at `count`, so a legal append after the base is never
* read, and a replaced, truncated or rewritten file is a typed failure, never a full or current-file read.
*/
export function readPersistedBase(base, acceptedIds = []) {
let fd;
try {
fd = openSync(base.fileIdentity.path, "r");
}
catch {
return { ok: false, error: "base_file_missing" };
}
try {
const stat = fstatSync(fd, { bigint: true });
if (String(stat.dev) !== base.fileIdentity.dev || String(stat.ino) !== base.fileIdentity.ino)
return { ok: false, error: "base_file_replaced" };
const entries = [];
const take = (line) => {
const entry = parseSessionEntryLine(line);
if (entry && entries.length < base.count + acceptedIds.length)
entries.push(entry);
};
const splitter = new SessionLineSplitter();
const buffer = Buffer.allocUnsafe(SESSION_READ_BUFFER_SIZE);
while (entries.length < base.count + acceptedIds.length) {
const bytesRead = readSync(fd, buffer, 0, buffer.length, null);
if (bytesRead === 0) {
take(splitter.finish());
break;
}
for (const line of splitter.push(buffer.subarray(0, bytesRead)))
take(line);
}
if (entries.length < base.count + acceptedIds.length)
return { ok: false, error: "base_file_truncated" };
if (fingerprint(entries.slice(0, base.count)) !== base.idFingerprint ||
acceptedIds.some((id, index) => entries[base.count + index]?.id !== id))
return { ok: false, error: "base_fingerprint_mismatch" };
return { ok: true, entries };
}
finally {
closeSync(fd);
}
}
/**
* A manager's whole transcript as transitions: its persisted base, each entry not on that base as its own append,
* then its leaf. `unpersisted` is undefined when a trimmed mirror no longer holds those entries.
*/
export function snapshotTranscript(state) {
if (state.unpersisted === undefined)
return [{ kind: "unavailable", reason: "transcript_tail_trimmed" }];
// A line read from disk is not checked against FileEntry: one without a string id cannot be an ancestry node.
if (state.unpersisted.some((entry) => typeof entry.id !== "string"))
return [{ kind: "unavailable", reason: "transcript_entry_unidentified" }];
return [
{ kind: "replace", base: state.base },
...state.unpersisted.map((entry) => ({
kind: "append",
id: entry.id,
type: entry.type,
parentId: entryParent(entry),
...(state.persistence ? { persistence: state.persistence } : { entry: state.own(entry) }),
})),
{ kind: "leaf", leafId: state.leafId },
];
}
//# sourceMappingURL=session-transcript-journal.js.map