@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
206 lines • 9.98 kB
JavaScript
import { checkpointComponents } from "./compact-catalog-families.js";
import { COMPACT_LEAF_CODE_UNITS } from "./compact-content-store.js";
import { CompactReadError } from "./compact-read-lease.js";
import { baseStream, openBaseBytes } from "./compact-recovery-base.js";
import { producePage } from "./compact-recovery-bytes.js";
import { CompactRecoveryCatalog, componentBytes, } from "./compact-recovery-catalog.js";
import { catalogRootRef, childRef, parseBoundedId, parseContentRef, parsePageRef, protocolId, } from "./compact-recovery-ids.js";
import { TEXT_FIELDS, } from "./compact-recovery-manifest-shape.js";
import { CompactValues } from "./compact-values.js";
import { VerifiedComponents } from "./compact-verified-components.js";
import { manifestPage } from "./compact-manifest-page.js";
const MANIFEST = protocolId("manifest");
const chunks = (value) => {
const parts = [];
for (let start = 0; start < value.length; start += COMPACT_LEAF_CODE_UNITS)
parts.push(value.slice(start, start + COMPACT_LEAF_CODE_UNITS));
return parts;
};
/**
* One manifest and catalog per token, built once from the pinned root and released with the token. A component is
* verified once per frozen root (RULING-69 (2)): every later page or re-open on that root reuses the verified source,
* and the root's entries are dropped with the lease of the one token that pins it (`VerifiedComponents`). A source
* holds leaf positions, never bytes; S11b owns the current-page retry cache.
*/
export class RecoveryManifests {
constructor() {
this.catalogs = new CompactRecoveryCatalog();
this.building = new Map();
this.ready = new Map();
this.verified = new VerifiedComponents();
this.counter = 0;
}
manifest(token, lane, root, valid) {
let pending = this.building.get(token.id);
if (!pending) {
pending = this.build(token, lane, root, valid);
this.building.set(token.id, pending);
pending.then((built) => this.ready.set(token.id, built), () => this.building.delete(token.id));
}
return pending.then((built) => built.manifest);
}
/** A raw ref is validated before any use; without a built catalog no ref can name anything. */
read(tokenId, lane, root, ref) {
const parsed = parseContentRef(ref);
const built = this.ready.get(tokenId);
if (!parsed.ok || !built)
throw new CompactReadError("range");
return lane.cutStorage(root, (store, valid) => this.catalogs.read(store, built.root, parsed.value, valid));
}
get verifiedComponents() {
return this.verified.size;
}
/** `tokenId` pins `root` for the cache; a root another live token pins is a `FrozenRootPinnedError`. */
pin(tokenId, root) {
this.verified.pin(tokenId, root);
}
/**
* One page of a component's bytes at a raw byte offset, or of the cut's loaded base under its reserved ref (S11c,
* `compact-recovery-base.ts`); a ref that names a node or nothing is `range`. A first open verifies the source
* inside this request under its `signal`; it is cached only while the token still holds it.
*/
page(token, lane, root, ref, offset, signal) {
if (ref === "manifest")
return manifestPage(this.manifest(token, lane, root, () => { }), offset);
const tokenId = token.id;
const target = parsePageRef(ref);
const built = this.ready.get(tokenId);
if (!target.ok || !built)
throw new CompactReadError("range");
return lane.cutStorage(root, async (store, valid) => {
if (store.health.needsRecovery)
await store.repair();
let bytes = this.verified.get(root, target.value.ref);
if (!bytes) {
bytes =
target.value.kind === "base"
? await openBaseBytes(baseStream(root.transcript, built.manifest.catalogRoot, target.value.ref), valid, signal)
: componentBytes(await this.catalogs.read(store, built.root, target.value.ref, valid, signal));
if (this.ready.get(tokenId) === built)
this.verified.set(tokenId, root, target.value.ref, bytes);
}
return producePage(bytes, offset, valid);
});
}
release(tokenId) {
const built = this.ready.get(tokenId);
this.ready.delete(tokenId);
this.building.delete(tokenId);
this.verified.drop(tokenId);
if (built)
this.catalogs.release(built.store, built.root);
}
build(token, lane, root, valid) {
const ref = catalogRootRef(++this.counter);
const strings = {
socketEpoch: token.admission.socketEpoch,
admissionId: token.admission.admissionId,
session: token.admission.sessionId,
sessionEpoch: token.admission.sessionEpoch,
token: token.id,
leaf: token.cut.leafId,
activeMessage: token.cut.activeMessageId,
turn: token.cut.turnId,
};
return lane.cutStorage(root, async (store, cutValid) => {
const texts = new Map();
const oversized = [];
const owned = [];
for (const field of TEXT_FIELDS) {
const value = strings[field];
if (value === null) {
texts.set(field, null);
continue;
}
const bounded = parseBoundedId(value);
if (bounded.ok) {
texts.set(field, { id: bounded.value });
continue;
}
const leaves = chunks(value).map((chunk) => store.createLeaf(chunk));
owned.push(...leaves);
const component = { kind: MANIFEST, id: protocolId(field), leaves, owner: store.text.own(leaves) };
oversized.push({ field, component });
}
try {
const check = () => {
cutValid();
valid();
};
const cut = { store, values: new CompactValues(store), root, settled: lane.settledOf(root) };
const emitted = {};
const components = async function* () {
yield* oversized.map(({ component }) => component);
emitted.registry = yield* checkpointComponents(cut, check);
};
const built = await this.catalogs.build(store, ref, components(), check);
// The list is the cataloged registry's own (RULING-128): the bytes `checkpointDigest` covers, never a recompute.
const requiredKinds = emitted.registry?.requiredKinds;
if (!requiredKinds) {
this.catalogs.release(store, built);
throw new CompactReadError("ownership");
}
return await this.assemble(store, token, ref, built, oversized, texts, requiredKinds);
}
finally {
for (const { component } of oversized)
store.adjust(component.owner, -1, 0);
for (const leaf of owned)
store.adjust(leaf, -1, 0);
}
});
}
/** Owns `built` from here: a failure anywhere below releases the tree, so no owner outlives a refused build. */
async assemble(store, token, ref, built, oversized, texts, requiredKinds) {
try {
let leftmost = ref;
for (let level = 1; level < built.depth; level++)
leftmost = childRef(leftmost, 0);
const node = oversized.length ? await this.catalogs.read(store, built, leftmost) : undefined;
for (const [index, { field, component }] of oversized.entries()) {
const entry = node?.kind === "node" ? node.entries[index] : undefined;
// The oversized components went in first, so they are the leftmost leaf's first entries in field order;
// any other layout is this builder's own invariant broken, refused as a typed internal error.
if (!entry || entry.kind !== component.kind || entry.id !== component.id)
throw new CompactReadError("ownership");
texts.set(field, { ref: childRef(leftmost, index), length: entry.length, digest: entry.digest });
}
const text = (field) => {
const value = texts.get(field);
if (value === undefined)
throw new CompactReadError("ownership");
return value;
};
const required = (field) => text(field) ?? raise();
const manifest = {
format: "senpi-recovery-manifest",
version: 1,
socketEpoch: required("socketEpoch"),
admissionId: required("admissionId"),
routeKind: token.admission.routeKind,
session: required("session"),
sessionEpoch: required("sessionEpoch"),
generation: token.admission.generation,
sequence: token.cut.sequence,
historyVersion: token.cut.historyVersion,
token: required("token"),
leaf: text("leaf"),
activeMessage: text("activeMessage"),
turn: text("turn"),
checkpointDigest: built.digest,
catalogRoot: ref,
catalogRootLength: built.length,
requiredKinds,
};
return { manifest, root: built, store };
}
catch (cause) {
this.catalogs.release(store, built);
throw cause;
}
}
}
function raise() {
throw new CompactReadError("ownership");
}
//# sourceMappingURL=compact-recovery-manifest.js.map