UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

277 lines (276 loc) • 18.5 kB
/** * Re-keying the rows one identity seat files under one value of its identity axis to another value — the policy seat's * principal ({@link import("./session-policy-store.js").SessionPolicyStore.rekeyPrincipal}), the background-agent seat's * isolation scope ({@link import("./background-agent-store.js").BackgroundAgentStore.rekeyScope}), and the two seats that record * a run's whole identity — the checkpoint seat ({@link import("./checkpoint-store.js").CheckpointStore.rekeyIdentity}) and the * tool-result seat ({@link import("./tool-result-store.js").ToolResultStore.rekeyIdentity}): both axes of a row at once, in * place — one-step seats. How a key is spelled, how the counters carry over, which cell is the axis and which row is this * move's own stay inside the seat; a caller hands it the pair of values and the step. * * The steps are one closed set ({@link REKEY_MODES}): `plan` previews the whole move and writes nothing; `arrive` files a * copy of every source row under the target key and leaves the source rules where they are; `leave` erases the source * rows that arrived; `withdraw` erases the arrivals — the compensation of a caller whose own commit failed. A two-step seat * runs plan → arrive → (the caller's commit) → leave, or withdraw when the commit failed; a one-step seat offers `plan` * and `leave` only ({@link ONE_STEP_REKEY_MODES}) and its `leave` runs after the commit and before the two-step seats' * `leave` (`identity_rekey.step_order`). * * This module holds what the seats share: the input readings, the answer composition, the scope value reading, the one law * that re-files a run's identity ({@link rekeyOwnerIdentity}) — and, for the policy seat, whose keys carry a counter that must * never roll back, the stamp arithmetic and the one judge that turns the rows and marks a backend read into the writes each * step makes. The checkpoint row law lives in `checkpoint-rekey.ts` (it reads the row judges, which this module must not * import). Its run-time imports are the owner reading and the judges that reading rests on, so every store module reaches it * without a cycle. */ import type { RuleOwner } from "./rule-owner.js"; import type { OwnerIdentity } from "./owner-identity.js"; /** * The steps of one re-key, one closed set: `plan` = the preview of the whole move (zero writes); `arrive` = the target key * gets its row, the source rules stay; `leave` = the source rows that arrived are erased (only those the arrival matches); * `withdraw` = the arrivals are erased (the compensation before the caller's own commit). Each identity seat's re-key * member is REQUIRED: a backend that cannot move a row leaves an identity migration nothing to call. A seat whose rows * cannot be in two places at once offers the subset {@link ONE_STEP_REKEY_MODES}. * * @contract identity_rekey.plan_is_execution — `mode: "plan"` reads exactly what `arrive` and `leave` will read and throws * each of the refusals they would throw on that reading (malformed input, an unreadable mark, row or directory, an * undecodable stored record), with the same code; with no writer on either key, `plan` answering `conflicting: 0` means * `arrive` answers `done` and the following `leave` erases every arrived row. A storage fault on a write is not such a * refusal: it is thrown when it happens and the caller resumes as after a crash. The caller keeps writers off both keys * from `arrive` until `leave` or `withdraw` completes, and before re-running any mode after a crash; `withdraw` is legal * only before the caller's own commit has acted on the arrival. For a one-step seat, `plan` judges every row with the * same function `leave` writes with, so with no writer on the rows `plan` answering `conflicting: 0` means `leave` re-files * every row `plan` counted. */ export declare const REKEY_MODES: readonly ["plan", "arrive", "leave", "withdraw"]; export type RekeyMode = (typeof REKEY_MODES)[number]; /** * The steps a one-step seat offers: a subset of {@link REKEY_MODES}, not a closed set of its own — a row whose key is its * token (a checkpoint) or its ref (a tool result) is re-filed in place, so there is no arrival to land or to withdraw. * * @contract identity_rekey.step_order — A move runs `plan` on every seat, then `arrive` on the two-step seats (session * policy, background agent), then the caller's own commit of its access change, then `leave` on the one-step seats * (checkpoint, tool result — in either order: neither reads the other's rows), then `leave` on the two-step seats; `withdraw` * undoes `arrive` and is legal only before that commit, and a one-step seat is never withdrawn because it has not moved yet. * Each seat receives, from the one mapping of the move, the pairs on its own axes — the policy seat the principal pair, the * background-agent seat each scope pair, the checkpoint and tool-result seats the principal pair and every scope pair. The * caller keeps writers, resumers (resolve, reopen, recordExecutionOutcome, setPendingSteer callers) and readers of tool * results (the runs of either identity) off the rows from `plan` until the last `leave` completes. After the commit no step * refuses the move: a row a seat cannot carry stays where it is and the next `plan` counts it. */ export declare const ONE_STEP_REKEY_MODES: readonly ["plan", "leave"]; export type OneStepRekeyMode = (typeof ONE_STEP_REKEY_MODES)[number]; /** The policy seat's input: the owner whose rows move (an alias the store's own key reading applies included), the * principal they move to, and the step. */ export interface PrincipalRekeyInput { readonly from: RuleOwner; readonly toPrincipal: string; readonly mode: RekeyMode; } /** The background-agent seat's input: the isolation scope whose rows move, the scope they move to, and the step. */ export interface ScopeRekeyInput { readonly fromScope: string; readonly toScope: string; readonly mode: RekeyMode; } /** One pair of scope values — the background-agent seat's input spelling without the step. */ export type ScopeRekeyPair = Omit<ScopeRekeyInput, "mode">; /** The one-step seats' input (checkpoint, tool result): the principal pair, the scope pairs (exact values the caller hands * over — the engine parses no deployment's scope vocabulary; the list may be empty), and the step. */ export interface IdentityRekeyInput { readonly fromPrincipal: string; readonly toPrincipal: string; readonly scopes: readonly ScopeRekeyPair[]; readonly mode: OneStepRekeyMode; } /** One mapping of a move as a one-step seat applies it: the principal pair and the scope pairs (the input without the step). */ export type IdentityRekeyMap = Omit<IdentityRekeyInput, "mode">; /** The answer arms, one union (a closed set): counts only, never a key value (the same grain as a refusal of a move). */ type RekeyAnswer = /** `rows` = the rows filed under the source value now; `conflicting` = the rows this move cannot carry: on a two-step seat * the keys `arrive` would refuse — a target occupied by a row that is not this move's arrival, or a key whose state the * seat cannot vouch for; on the one-step seat the rows this engine cannot read whole (judged `lacking`). */ { readonly kind: "plan"; readonly rows: number; readonly conflicting: number; } /** `rows`: for `arrive`, the source rows now in place at their targets as this move's arrivals (landed by this call or * found landed); for `leave`, the source rows this call erased — for the one-step seat's `leave`, the rows this call * re-filed; for `withdraw`, the arrivals this call erased. */ | { readonly kind: "done"; readonly mode: "arrive" | "leave" | "withdraw"; readonly rows: number; } /** `arrive` refused the whole call and wrote nothing: `conflicting` keys of `rows` source rows would not move. */ | { readonly kind: "conflict"; readonly mode: "arrive"; readonly rows: number; readonly conflicting: number; }; export type RekeyPlan = Extract<RekeyAnswer, { kind: "plan"; }>; export type RekeyDone = Extract<RekeyAnswer, { kind: "done"; }>; export type RekeyConflict = Extract<RekeyAnswer, { kind: "conflict"; }>; /** * The `plan` answer of the seats that record a run's whole identity (checkpoint, tool result): {@link RekeyPlan}'s counts and * `unpairedScopeRows` — of the rows counted, those whose principal the move changes while no scope pair names their partition's * value (the partition the row records, or the principal it implies — {@link rekeyOwnerIdentity}): the rows a caller who forgot a * scope pair would leave under the new person and the old partition. A pair `{ s → s }` keeps `s` on purpose and is not counted. * Counted, never refused. The two-step seats keep {@link RekeyPlan}: the * policy seat keys on the person only and the background-agent seat on the scope only, so neither can tell a person moving * without their partition. */ export interface IdentityRekeyPlan extends RekeyPlan { readonly unpairedScopeRows: number; } /** The answer one step gives over its counts: `rows` the source rows judged, `conflicting` the rows this move cannot carry * (the plan arm's reading), `acted` the rows a `leave` or `withdraw` erased or re-filed. `arrive` refuses the whole call * when any key conflicts. */ export declare function rekeyAnswerOf(mode: RekeyMode, counts: { rows: number; conflicting: number; acted: number; }): RekeyPlan | RekeyDone | RekeyConflict; /** The scope a background-agent row is filed under, read the way the seat's `put` reads it: a non-empty string, or * `undefined` (no scope — a row the fallback read would serve to anybody); and the source scope of every seat's scope * pair (the checkpoint seat's `fromScope`). */ export declare function agentScopeOf(raw: unknown): string | undefined; /** The policy seat's input reading — before any read or write: a fresh, frozen copy, or a `TypeError` naming the key. */ export declare function readPrincipalRekeyInput(entry: string, value: unknown): PrincipalRekeyInput; /** The background-agent seat's input reading — before any read or write: a fresh, frozen copy, or a `TypeError`. */ export declare function readScopeRekeyInput(entry: string, value: unknown): ScopeRekeyInput; /** * The one-step seats' input reading — before any read or write: a fresh, frozen copy, or a `TypeError` naming the key. * The principals are names — the source read as a stored name is ({@link recordedPrincipalNameOf}: a name an earlier release admitted and * filed rows under can be moved off), the target judged as a name about to be written; a source scope is read as {@link agentScopeOf} reads a row's scope (one source reading across * the seats: a resource slice's scope needs only be a non-empty string), a target scope as a name (it is written into a * row's `durableApproval.scope`, which is read by the name rule). The pairs are a mapping: no source twice, no target * twice, and no target that is another pair's source (a chain — moved here at once and by the background-agent seat pair * by pair, it would end two ways, and a re-run would move the middle value on). A pair whose two values are equal moves * nothing and says the scope stays on purpose: a row of the moving person filed in it is not counted in * {@link IdentityRekeyPlan.unpairedScopeRows}. */ export declare function readIdentityRekeyInput(entry: string, value: unknown): IdentityRekeyInput; /** What {@link rekeyOwnerIdentity} answers for one recorded identity. */ export type OwnerIdentityRekeyVerdict = /** The mapping changes neither the person nor the partition's value: not this move's. */ { readonly kind: "untouched"; } /** The identity to record instead, in the canonical form; `partitionLeft` = the person changed and no pair names the partition's * value (it keeps it — a pair `{ s → s }` says that is on purpose). */ | { readonly kind: "rekeyed"; readonly identity: OwnerIdentity; readonly partitionLeft: boolean; }; /** * THE law that re-files a run's identity under one move — every seat that records a whole identity (a checkpoint row's principal * and partition, a tool result's owner, a host's own page of them) reads its record into an {@link OwnerIdentity} and writes what this * answers. Each axis moves by its own pairs: * - the person: `fromPrincipal` becomes `toPrincipal`; any other value — the anonymous identity (`null`) included — stays; * - the partition is a VALUE: the scope the record names, or — when it names none — its principal (the `isolationScopeOf` * reading); a scope pair whose source is that value moves it, and nothing else does (the person moving never moves it). The * anonymous identity with no recorded scope has no partition value; * - the result is recorded in the canonical form (`ownerIdentityOf`): the scope only when it differs from the principal. * Selection compares values, never spelling: a record that names its own principal as its scope is the record that names none, and * a record whose values the mapping does not change is `untouched` whatever its spelling. */ export declare function rekeyOwnerIdentity(identity: OwnerIdentity, map: IdentityRekeyMap): OwnerIdentityRekeyVerdict; /** A one-step seat's verdict over one row, as its answer counts it: not this move's, re-filed (`partitionLeft` as * {@link rekeyOwnerIdentity} says), or selected but left as it is (a row this engine cannot read whole). */ export type OneStepRekeyCount = { readonly kind: "untouched"; } | { readonly kind: "rekeyed"; readonly partitionLeft: boolean; } | { readonly kind: "unrekeyable"; }; /** The answer of one step of a one-step seat over the verdicts it reached, one per row it looked at: `plan` counts the selected * rows, the unrekeyable among them and the re-filed ones that leave their partition; `leave` counts the rows it re-filed. */ export declare function oneStepRekeyAnswerOf(mode: OneStepRekeyMode, verdicts: readonly OneStepRekeyCount[]): IdentityRekeyPlan | RekeyDone; /** A key's counters: `rev` counts within a lineage, `gen` names the lineage. */ export interface RekeyStamp { readonly rev: number; readonly gen: number; } /** A row's counters as the law reads them. `readable: false` = the row's rules cannot be read: it moves as it lies, its * counters are never compared, and `rev` / `gen` are only the numbers its bytes carry (0 where they carry none). */ export interface RekeyRowStamp extends RekeyStamp { readonly readable: boolean; } /** The record an `arrive` leaves on the SOURCE key's mark — the one evidence of which target row is this move's own: the * target, the source row's stamp when it arrived (`"unreadable"` for a row whose rules could not be read), and the stamp * the arrival landed at. Any ordinary write of the source key replaces its mark and so drops the record. */ export interface RekeyArrivalRecord { readonly to: string; readonly from: RekeyStamp | "unreadable"; readonly at: RekeyStamp; } /** A key's mark as the law reads it: its counters, whether its lineage is lost (a backend's tombstone or seal: no * evidence of what a reader enforces), and the arrival record it carries. */ export interface RekeyMarkReading { readonly stamp: RekeyStamp; readonly lineageLost: boolean; readonly arrival?: RekeyArrivalRecord; } /** One session's two keys, as a backend read them: the row and mark under the source value, and under the target. */ export interface PrincipalRekeyKeyState { readonly sourceRow: RekeyRowStamp | null; readonly sourceMark: RekeyMarkReading | null; readonly targetRow: RekeyRowStamp | null; readonly targetMark: RekeyMarkReading | null; } /** The writes one step makes on one session's keys, in the order a backend makes them. */ export type PrincipalRekeyWrite = /** `arrive`: (a1) the source mark becomes `sourceMark` carrying `record` — skipped when `sourceMark` is `null`, the record * being there already; (a2) the target mark becomes `record.at`; (a3) the target row is the source row, stamped * `record.at` when readable, moved as it lies otherwise. */ { readonly kind: "arrive"; readonly record: RekeyArrivalRecord; readonly sourceMark: RekeyStamp | null; } /** `arrive` over a source key holding only a mark: the target mark becomes `mark`; the source mark stays. */ | { readonly kind: "merge-marks"; readonly mark: RekeyStamp; } /** `leave`: (l1) the source mark becomes `mark`, still carrying `record`; (l2) the source row is removed. */ | { readonly kind: "leave"; readonly mark: RekeyStamp; readonly record: RekeyArrivalRecord; } /** `withdraw`: (w1) the target mark becomes `targetMark` and (w2) the target row is removed — both only when * `targetMark` is set; (w3) the source mark becomes `sourceMark`, without the record. */ | { readonly kind: "withdraw"; readonly targetMark: RekeyStamp | undefined; readonly sourceMark: RekeyStamp; }; /** The per-position maximum of two stamps — the one operator the counter law is written in. */ export declare function stampMax(a: RekeyStamp, b: RekeyStamp): RekeyStamp; /** The ARRIVAL STAMP of a readable row landing on a key whose mark is `targetMark` (`null` = none): the per-position * maximum of the row's own stamp and the key's next-write stamp `(mark.rev + 1, mark.gen)` — the write-floor law. */ export declare function arrivalStampOf(row: RekeyStamp, targetMark: RekeyStamp | null): RekeyStamp; /** The ERASE STEP of a key (what `deleteBySession` does to one key, and what `leave` / `withdraw` do): the mark keeps the * higher number and opens the next lineage, `max(mark.gen, row.gen) + 1`. */ export declare function eraseStepOf(mark: RekeyStamp | null, row: RekeyStamp): RekeyStamp; /** * THE judge of one policy-seat step over the sessions a backend read: the answer, and per session the writes the step * makes (`undefined` = none). `arrive` with any conflicting session writes nothing. Both bundled backends gather their * keys and apply these writes; neither re-derives a stamp or a match. */ export declare function judgePrincipalRekey(mode: RekeyMode, to: string, keys: readonly PrincipalRekeyKeyState[]): { answer: RekeyPlan | RekeyDone | RekeyConflict; writes: readonly (PrincipalRekeyWrite | undefined)[]; }; export {};