@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
226 lines • 10.1 kB
JavaScript
import { createHash } from "node:crypto";
import { BaseContentHash } from "../../core/session-file-identity.js";
import { readPersistedBase, } from "../../core/session-transcript-journal.js";
import { stageBootstrap, TailBudget, TranscriptTail } from "./accepted-transcript-tail.js";
import { StagedReadError } from "./compact-transfer-staging.js";
/**
* What an epoch keeps of every accepted entry after persistence released its text: its id, kind and parent link
* (RULING-61 Q1 = C). Each record is charged no less than the heap it holds, so this budget bounds the retained heap
* itself, and the record count to at most 8 MiB / 40 B = 209,715 (records of empty strings).
*/
export const DEFAULT_TRANSCRIPT_ANCESTRY_BYTES = 8 * 1024 * 1024;
/** Three 8-byte array slots (id, kind, parent), plus the half more a growing array may hold unused: 36, to 40. */
const ANCESTRY_RECORD_BYTES = 40;
/** A distinct kind's row in the epoch's kind table: key, value, chain and bucket slots, doubled for table growth. */
const KIND_NAME_BYTES = 64;
/** A string's heap: a 16-byte header and its code units (one byte each when all are ASCII, else two), 8-aligned. */
const stringBytes = (value) => value === ""
? 0
: Math.ceil((16 + (Buffer.byteLength(value) === value.length ? value.length : 2 * value.length)) / 8) * 8;
/**
* The first `count` entries of an epoch's columns. The lane only appends to its columns (a `replace` starts new ones),
* so this prefix never changes: a root freezes in O(1) without a copy and never sees an entry accepted after it.
*/
class AcceptedEntries {
constructor(ids, kinds, parents, count) {
this.ids = ids;
this.kinds = kinds;
this.parents = parents;
this.count = count;
}
/** The ids of the first `end` entries, as the base reader takes them. */
idsBefore(end) {
return this.ids.slice(0, Math.min(end, this.count));
}
*[Symbol.iterator]() {
for (let index = 0; index < this.count; index++)
yield { index, id: this.ids[index], kind: this.kinds[index], parentId: this.parents[index] };
}
}
/** The transcript component of one epoch, changed only by accepted transitions (R3.C1.1). */
export class AcceptedTranscript {
/** Entry texts are staged into, and spill through, the owning lane's staging store (S12a). */
constructor(staging) {
this.version = 0;
this.leafId = null;
this.base = null;
this.entryIds = [];
this.kinds = [];
this.parents = [];
/** Each distinct kind once per epoch, so every record of a kind shares one string whatever the producer sent. */
this.kindNames = new Map();
this.ancestryBytes = 0;
/** One bound for this epoch's tails, a superseded tail a live cut still holds included (carry 65a). */
this.budget = new TailBudget();
this.unavailable = null;
this.staging = staging;
this.tail = new TranscriptTail(staging, null, this.budget);
}
get historyVersion() {
return this.version;
}
get available() {
return this.unavailable === null;
}
/**
* Applies a bootstrap whose entry texts the internal bootstrap reader staged first: a bootstrap refused at a bound
* leaves the epoch's transcript typed unavailable with nothing kept, never partial.
*/
bootstrap(transitions) {
const staged = stageBootstrap(this.staging, transitions);
if (!staged)
return this.markUnavailable("transcript_tail_over_byte_limit");
try {
for (const transition of transitions)
this.apply(transition, staged.get(transition));
}
finally {
for (const content of staged.values())
this.staging.abandon(content);
}
}
/** `staged`: the append's entry text, already staged by the bootstrap reader; this transcript adopts it if kept. */
apply(transition, staged) {
this.version += 1;
if (transition.kind === "replace") {
this.tail.supersede();
this.base = transition.base;
this.entryIds = [];
this.kinds = [];
this.parents = [];
this.kindNames = new Map();
this.ancestryBytes = 0;
this.tail = new TranscriptTail(this.staging, transition.base, this.budget);
this.unavailable = null;
this.missingFrom = undefined;
return;
}
if (transition.kind === "unavailable") {
this.markUnavailable(transition.reason);
return;
}
if (transition.kind === "persisted") {
this.persisted(transition.persistence);
return;
}
if (this.unavailable !== null && this.missingFrom === undefined)
return;
if (transition.kind === "append") {
const index = this.entryIds.length;
if (!this.retainAncestry(transition.id, transition.type, transition.parentId))
return;
if (transition.persistence)
this.persisted(transition.persistence);
const unpersisted = index + (this.base?.count ?? 0) >= (this.tail.persistence?.count ?? 0);
if (this.missingFrom === undefined && unpersisted && transition.entry !== undefined) {
const content = staged ?? this.tail.stage(index, transition.entry);
if (content)
this.tail.adopt(index, content);
else
this.markUnavailable("transcript_tail_over_byte_limit", index);
}
this.leafId = transition.id;
}
else
this.leafId = transition.leafId;
}
/**
* Charges what the record really holds: its slots, its id, a kind the epoch has not seen, and a parent link unless it
* shares the previous entry's own id string (the common chain).
*/
retainAncestry(id, type, parentId) {
const previous = this.entryIds.at(-1);
const shared = previous !== undefined && previous === parentId;
const kind = this.kindNames.get(type);
const bytes = ANCESTRY_RECORD_BYTES +
stringBytes(id) +
(kind === undefined ? KIND_NAME_BYTES + stringBytes(type) : 0) +
(shared ? 0 : stringBytes(parentId ?? ""));
if (this.ancestryBytes + bytes > DEFAULT_TRANSCRIPT_ANCESTRY_BYTES) {
this.markUnavailable("transcript_ancestry_over_byte_limit");
return false;
}
if (kind === undefined)
this.kindNames.set(type, type);
this.entryIds.push(id);
this.kinds.push(kind ?? type);
this.parents.push(shared ? previous : parentId);
this.ancestryBytes += bytes;
return true;
}
/** `missingFrom` marks a tail-bound refusal recoverable; any other reason, or a second one, stays for the version. */
markUnavailable(reason, missingFrom) {
this.missingFrom = this.unavailable === null ? missingFrom : undefined;
this.unavailable ??= reason;
process.stderr.write(`senpi rpc acceptance: transcript component unavailable: ${reason}\n`);
}
freeze() {
return Object.freeze({
historyVersion: this.version,
leafId: this.leafId,
base: this.base,
accepted: new AcceptedEntries(this.entryIds, this.kinds, this.parents, this.entryIds.length),
ancestryBytes: this.ancestryBytes,
tail: this.tail,
count: this.entryIds.length,
unavailable: this.unavailable,
});
}
persisted(persistence) {
this.tail.persisted(persistence, this.base?.count ?? 0);
// Every entry the version holds no text for is now read from the file by identity (RULING-80 (4)).
if (this.missingFrom !== undefined && persistence.count - (this.base?.count ?? 0) >= this.entryIds.length) {
this.missingFrom = undefined;
this.unavailable = null;
}
}
/** Releases the epoch's tail content once no root of it can be read any longer. */
release() {
this.tail.releaseAll();
}
}
/**
* The root's entries: its base read only through the captured identity, then its own accepted values from its own
* segments, held for the whole read so a persistence report during it cannot drop what it reads. A segment read by
* identity that is gone or holds other bytes is typed, never other content (RULING-78 (2)).
*/
export async function readTranscriptRoot(root) {
if (root.unavailable !== null)
return { ok: false, error: root.unavailable };
const hold = root.tail.hold(root.count, root.base?.count ?? 0);
try {
const persistence = hold.persistence;
const base = root.base ??
(persistence &&
hold.fileCount > 0 && {
fileIdentity: persistence.fileIdentity,
count: 0,
idFingerprint: createHash("sha256").digest("hex"),
contentFingerprint: new BaseContentHash().digest(),
});
const persisted = base
? readPersistedBase(base, root.accepted.idsBefore(hold.fileCount))
: { ok: true, entries: [] };
if (!persisted.ok)
return persisted;
const entries = [...persisted.entries];
for (let index = hold.fileCount; index < root.count; index++) {
if (!hold.has(index))
return { ok: false, error: "transcript_tail_trimmed" };
let text = "";
for await (const chunk of hold.chunks(index))
text += chunk;
entries.push(JSON.parse(text));
}
return { ok: true, entries };
}
catch (cause) {
if (cause instanceof StagedReadError)
return { ok: false, error: `transcript_${cause.reason}` };
throw cause;
}
finally {
hold.release();
}
}
//# sourceMappingURL=accepted-transcript.js.map