@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
273 lines • 13.1 kB
JavaScript
import { CompactReadError, CompactReadLease } from "./compact-read-lease.js";
import { RecoveryManifests } from "./compact-recovery-manifest.js";
import { RecoveryStreams } from "./compact-recovery-streams.js";
import { retiredTokenFailure, tokenStaleness } from "./compact-recovery-staleness.js";
import { RecoveryRefusedError, recovered, refusalReason, repairNeeded, storageUnavailable, } from "./compact-recovery-types.js";
/**
* The checkpoint tokens of one host (S08a/S08b, R3.C1.2-C1.5). A freeze pins one complete accepted root in one
* synchronous step and mints a token naming the cut's accepted identities as the next generation of its stream;
* nothing is published when the root is incomplete. Issuing a generation invalidates the stream's previous token
* at once and reclaims its root as soon as the operations in flight on it unwind, whether or not its holder ever
* releases it. Every lookup validates the caller, the token and the cut before I/O and after every await.
*/
export class RecoveryCheckpoints {
constructor() {
this.checkpoints = new Map();
/** Every token minted here, with the admission it was minted for; a holder's copy or a forgery is not in it. */
this.issued = new WeakMap();
this.streams = new RecoveryStreams();
this.manifests = new RecoveryManifests();
this.refusals = new Map();
this.unavailable = new Map();
this.ended = new Set();
this.minted = 0;
this.frozen = 0;
this.reclaimed = 0;
}
get open() {
return this.checkpoints.size;
}
tokens() {
return [...this.checkpoints.values()].map(({ token }) => token);
}
/** The stream a caller's admissions share, as a bounded description; undefined once its peer or session ended. */
stream(caller) {
return this.streams.describe(caller);
}
/** Whether any stream of this peer incarnation still routes the admission: one indexed lookup (#5274). */
routesAdmission(socketEpoch, admissionId) {
return this.streams.routes(socketEpoch, admissionId);
}
/** Runs once per token when its lease ends, however it ended (a release, a reclaim, its peer's end). */
onTokenEnd(listener) {
this.ended.add(listener);
}
status() {
return {
open: this.checkpoints.size,
streams: this.streams.size,
frozen: this.frozen,
reclaimed: this.reclaimed,
refused: Object.fromEntries(this.refusals),
unavailable: Object.fromEntries(this.unavailable),
};
}
/** The next generation of the route's stream: a failed freeze advances nothing and pins nothing. */
freeze(route, lane, join = false) {
if (lane.retired)
return this.refuse(repairNeeded("lane_retired"));
const current = join ? this.checkpoints.get(this.streams.get(route)?.current ?? "") : undefined;
if (current && this.check(current.token, route).ok) {
this.streams.join(route);
return recovered(current);
}
const root = lane.freeze();
if (root.current === undefined) {
lane.release(root);
return this.refuse(storageUnavailable("compact_state_unavailable"));
}
const generation = lane.generations.next();
if (generation === undefined) {
lane.release(root);
return this.refuse(storageUnavailable("unavailable"));
}
const id = `${route.socketEpoch}:${++this.minted}`;
// One token per root (RULING-69 (2)): a root already pinned is a broken invariant, thrown before any stream moves.
this.manifests.pin(id, root);
const { retired } = this.streams.next(route, root.sessionEpoch, id, generation);
const admission = Object.freeze({ ...route, sessionEpoch: root.sessionEpoch, generation });
const token = Object.freeze({
kind: "checkpoint",
id,
admission,
cut: Object.freeze({
sessionEpoch: root.sessionEpoch,
sequence: root.sequence,
historyVersion: root.transcript.historyVersion,
leafId: root.transcript.leafId,
activeMessageId: root.activeMessageId,
turnId: root.turnId,
}),
});
const lease = new CompactReadLease(() => {
this.manifests.release(token.id);
lane.release(root);
this.checkpoints.delete(token.id);
for (const listener of this.ended)
listener(token.id);
}, () => {
const stale = this.staleness(token, lane);
if (stale)
throw new RecoveryRefusedError(stale);
});
const checkpoint = {
token,
lane,
root,
lease,
hold: (read) => lease.hold(read),
retain: () => ({ lane, root, hold: (read) => read(), end: lease.retain() }),
};
this.issued.set(token, admission);
this.checkpoints.set(token.id, checkpoint);
this.frozen += 1;
this.reclaim(retired);
return recovered(checkpoint);
}
/** Idempotent, and never another token's: the root goes once this token's last operation unwinds. */
release(token) {
this.checkpoints.get(token.id)?.lease.release();
}
/**
* A peer incarnation is gone: its streams end and every checkpoint it froze is reclaimed whether or not its
* holder ever releases it (RULING-50 (2)); an operation still in flight on one is refused as `peer_gone` and
* its root goes once that operation unwinds.
*/
forgetPeer(socketEpoch) {
this.streams.forgetPeer(socketEpoch);
for (const { token } of [...this.checkpoints.values()])
if (token.admission.socketEpoch === socketEpoch)
this.reclaim(token.id);
}
/**
* The routing session ended for good (RULING-56 (2)): its stream records go on every peer, since a sealed handle is
* never re-attached. Its tokens keep their lifetime (a queued attach view reads its root to delivery, RULING-51
* Q2 A); live access to one is refused as `session_closed`, read from its retired lane.
*/
forgetSession(sessionId) {
this.streams.forgetSession(sessionId);
}
/**
* An admission ended (a detach today; S14 extends this): its route leaves the stream, the counter stays, and the
* token it minted is reclaimed like a superseded one (RULING-56 (4)), with or without its stream record. Idempotent.
* `_retirement` is RULING-119's compile-time proof: a client action, or a `RouteAnnouncement` already emitted.
*/
retireRoute(caller, admissionId, _retirement) {
const current = this.streams.get(caller)?.current;
this.streams.retireRoute(caller, admissionId);
if ((this.streams.get(caller)?.routes.size ?? 0) > 0)
return;
this.reclaim(current);
for (const { token } of [...this.checkpoints.values()]) {
const { socketEpoch, sessionId, admissionId: minter } = token.admission;
if (socketEpoch === caller.socketEpoch && sessionId === caller.sessionId && minter === admissionId)
this.reclaim(token.id);
}
}
/**
* The caller's claim on a token it named by id, before any request state is touched: a token superseded while an
* operation still holds it answers `superseded_token` with the newer generation (RULING-70 (3), RULING-50 (2)).
*/
check(token, caller) {
const claimed = this.claim(token, caller);
return claimed.ok ? recovered(token) : claimed;
}
/** The pinned transcript root (version, leaf, accepted ids, base identity); its bytes are read by S11's page route. */
transcript(token, caller) {
const claimed = this.claim(token, caller);
if (!claimed.ok)
return claimed;
const { transcript } = claimed.value.root;
return transcript.unavailable === null
? recovered(transcript)
: this.refuse(storageUnavailable(transcript.unavailable));
}
readSettled(token, caller) {
return this.read(token, caller, (lane, root) => lane.readSettled(root));
}
readCurrent(token, caller) {
return this.read(token, caller, (lane, root) => lane.readCurrent(root));
}
readComponents(token, caller) {
return this.read(token, caller, (lane, root) => lane.readCurrentComponents(root));
}
readActive(token, caller) {
return this.read(token, caller, (lane, root) => lane.readCurrentActive(root));
}
readCalls(token, caller) {
return this.read(token, caller, (lane, root) => lane.readCurrentCalls(root));
}
/** The bounded manifest of the cut (S09, R4.B1): built once per token from its pinned root, never a component list. */
catalog(token, caller) {
return this.read(token, caller, (lane, root, lease) => this.manifests.manifest(token, lane, root, () => lease.assert()));
}
/** One catalog node or component under the token, verified against its parent's digest before it is decoded. */
readCatalog(token, caller, ref) {
return this.read(token, caller, (lane, root) => this.manifests.read(token.id, lane, root, ref));
}
/**
* One bounded page (at most `FRAGMENT_MAX_BYTES` raw bytes) of a catalog component at a raw byte offset, under the
* same claim and lease as every read (S11a; the cursor, ordinal and request limits around it are S11b). `signal` is
* the request's budget: a first open's verification is charged to it and stops, typed `aborted`, when it aborts.
*/
readCatalogPage(token, caller, ref, offset, signal) {
return this.read(token, caller, (lane, root) => this.manifests.page(token, lane, root, ref, offset, signal));
}
/** Components verified under the live frozen roots (RULING-69 (2)); a root's entries go with its lease. */
get verifiedComponents() {
return this.manifests.verifiedComponents;
}
async read(token, caller, component) {
const claimed = this.claim(token, caller);
if (!claimed.ok)
return claimed;
const { lease, lane, root } = claimed.value;
try {
return recovered(await lease.run(() => component(lane, root, lease)));
}
catch (cause) {
return this.refused(token, lane, cause);
}
}
/**
* Invalidates a token the owner retires (superseded, replaced, route retired, or its peer gone): the root goes after
* its in-flight operations. Counted only when this is what released it, never after its holder's own release.
*/
reclaim(id) {
if (id !== undefined && this.checkpoints.get(id)?.lease.release())
this.reclaimed += 1;
}
/**
* Only a token minted here for the asking peer + session is looked at (RULING-56 (1)): anything else is
* `unknown_token` with no state. A retired one is then described by the asker's own stream before any I/O.
*/
claim(token, caller) {
const admission = this.issued.get(token);
if (admission?.socketEpoch !== caller.socketEpoch || admission.sessionId !== caller.sessionId)
return this.refuse(repairNeeded("unknown_token"));
const checkpoint = this.checkpoints.get(token.id);
if (!checkpoint)
return this.refuse(retiredTokenFailure(this.streams.get(admission), admission));
try {
checkpoint.lease.assert();
}
catch (cause) {
return this.refused(token, checkpoint.lane, cause);
}
return recovered(checkpoint);
}
/** Why a once-valid token no longer names a readable cut (`compact-recovery-staleness.ts`). */
staleness(token, lane) {
return tokenStaleness(this.streams.get(token.admission), token, lane);
}
/** A refused operation names the cut's staleness first; a store that could not serve it is storage_unavailable. */
refused(token, lane, cause) {
const stale = this.staleness(token, lane);
if (stale)
return this.refuse(stale);
if (cause instanceof RecoveryRefusedError)
return this.refuse(cause.failure);
if (cause instanceof CompactReadError)
return this.refuse(cause.reason === "released" ? repairNeeded("released") : storageUnavailable(cause.reason));
throw cause;
}
/** Every typed failure leaves through here, counted by its reason; a storage refusal also by its detail. */
refuse(failure) {
const reason = refusalReason(failure);
this.refusals.set(reason, (this.refusals.get(reason) ?? 0) + 1);
if (failure.kind === "storage_unavailable")
this.unavailable.set(failure.reason, (this.unavailable.get(failure.reason) ?? 0) + 1);
return { ok: false, failure };
}
}
//# sourceMappingURL=compact-recovery-state.js.map