import { type HistoryReference } from './history.js'; import type { TwinActionRevertSpec } from './actions.js'; import type { TwinAction, TwinActionPrecondition } from './actions.js'; import { type FieldChange } from './hash.js'; /** One twin's action ledger, addressed the way the control plane addresses state: * `worldPaths(stateService, controlRoot)`. `service` is the caller's label for it (in a world: * the world service id); `stateService` is the control-plane service whose ledger this is. * They differ whenever a twin records under a different state name than its world service id. */ export type LedgerRef = { /** the vendor/twin as the operator names it — what `diff` groups by and `replay` matches on */ service: string; /** the control-plane state service whose `actions.jsonl` this is (often === service) */ stateService: string; /** control root such that `worldPaths(stateService, controlRoot)` resolves the ledger */ controlRoot: string; }; /** One ledger's recorded position inside a marker. `count` is the row count at capture; * `lastActionId` is the verification anchor (see the marker note above). */ export type LedgerPosition = { service: string; stateService: string; count: number; lastActionId: string | null; /** the twin's history view and its position in it: what a branch at this mark starts from (ADR 0036 §5) */ view?: string; position?: number; }; export declare const MARKER_KIND = "volter.world.marker.v1"; export declare const CHANGESET_KIND = "volter.world.changeset.v1"; /** The base position a diff or changeset is taken against. */ export type WorldMarker = { kind: typeof MARKER_KIND; id: string; world: string; createdAt: string; /** Every ledger that existed at capture time. A ledger absent here is treated as position 0 * (a twin that recorded its first action AFTER the mark contributes its whole ledger). */ ledgers: LedgerPosition[]; /** the World clock's instant at the mark, or null when it ran on the machine's time (a run's position, ADR 0036 §5) */ clock?: string | null; /** whether the machine's fault door took the app's disk with the mark */ disk?: boolean; }; /** The id reserved for the synthetic "everything this world has ever recorded" base. */ export declare const WORLD_BOOT_MARKER_ID = "world-boot"; /** An action inside a delta/changeset, bound to the twin whose ledger recorded it. The raw * `TwinAction` is kept verbatim (provenance); `service`/`stateService` are the binding replay * needs to route it into the right twin of another world. */ export type ChangesetAction = { service: string; stateService: string; action: TwinAction; }; /** Per-vendor rollup of a delta, in first-occurrence order — the shape `diff` renders. */ export type VendorSummary = { service: string; count: number; operations: Array<{ operation: string; count: number; subjectIds: string[]; }>; }; export type LedgerDelta = { world: string; base: WorldMarker; /** every action after `base`, across every ledger, ordered by `occurredAt` */ actions: ChangesetAction[]; vendors: VendorSummary[]; total: number; /** Presentation only, outside changeset bodies: fields immediately before and after each write. */ fieldChanges?: Record>; }; export declare const fieldDiffKey: (service: string, stateService: string, id: string) => string; /** A verifier: one deterministic check against post-replay projected state — the CI assertion * of the operational PR (docs/concepts/the-model.md). The `assert` is the kernel's ONE check * expression (`TwinActionPrecondition`: subject/field/op/value, evaluated by * `checkPrecondition`), the same shape write-time preconditions and plan conflicts already * use — a verifier is that check pointed at a replay target instead of the authoring world. */ export type ChangesetVerifier = { /** caller-chosen handle, unique within the changeset (results key on it) */ id: string; /** the world service (twin) whose post-replay state the assert reads */ service: string; assert: TwinActionPrecondition; }; /** One verifier's outcome against a replay target. `assert` is repeated verbatim so the result * is readable on its own; `actual` is what the projected state held (omitted when undefined — * which is itself what `exists`/`not_exists` distinguish). */ export type ChangesetVerifierResult = { id: string; service: string; assert: TwinActionPrecondition; passed: boolean; actual?: unknown; }; /** The recorded outcome of `changeset verify` — ABOUT-the-body metadata, like approvals: it * lives on the object but is outside `contentHash`, and each verify REPLACES the previous * record (the provenance fields say exactly which run this is). */ export type ChangesetVerification = { at: string; /** where the replay landed — a world name, or 'ephemeral' for a throwaway target */ into: string; /** the body hash at verification time; a later body edit makes this visibly stale */ contentHash: string; /** sha256 over the post-replay projected state of every replay target — two verifies that * produced the same world state produce the same digest (the determinism receipt) */ worldDigest: string; passed: boolean; results: ChangesetVerifierResult[]; /** the world's checks (state-system.ts) that refused an entry — CI on deployment, run at verify */ refusals?: Array<{ actionId: string; service: string; check: string; reason: string; }>; }; /** One signature: who approved, when, against exactly which body hash. The hash-at-signing is * the point — an approval is meaningless without the bytes it bound to. */ export type ChangesetApproval = { principal: string; at: string; contentHash: string; note?: string; }; export type Changeset = { kind: typeof CHANGESET_KIND; id: string; name: string; /** the world it was authored in */ world: string; /** the marker id it forked from */ base: string; createdAt: string; actions: ChangesetAction[]; /** deterministic checks that must pass on replay — part of the hashed body when present, * so an approval also binds to WHAT was checked, not just what was done */ verifiers: ChangesetVerifier[]; /** latest verify run (replaced, never accumulated) — outside the hash, like approvals */ verification: ChangesetVerification | null; /** who signed, against `contentHash` */ approvals: ChangesetApproval[]; /** The governed push's outcome: receipts and, on a partial apply, the compensation report; null until applied. */ applied: ChangesetApplication | null; /** The human summary rendered deterministically from `actions` * at authoring (`narrateActions`). Outside the hash — it is DERIVED from the hashed actions, so * an approval already binds to it — and re-rendered on every read: a hand-edited narration no * longer equals its re-render, and the object is neither approvable nor applicable until * re-authored. */ narration?: string; /** The author's own words for the changeset (git's commit message) — what `volter changeset -m` * records. Outside the hash, like the narration; a reviewer reads both. */ message?: string; /** Who cut it, as the World names a caller (`key:`, `key: for:`, `person:`, `machine`, `person`, * `token`); the command on this machine records its signed-in person, and is absent when no one is signed in there. * Outside the hash, as approvals are (docs/contributing/architecture.md, "Who acted is recorded"). */ cutBy?: string; /** The person accountable for it: the cutting grant's person, else the pusher's person when it lands in a shared World * with none. Outside the hash. */ owner?: string; /** Who pushed it into the World that keeps this copy, a caller as `cutBy` names one. Outside the hash. */ pushedBy?: string; /** Set by `rebaseChangeset`: the hash this object was rebased from, and when. Outside the hash. */ rebasedFrom?: { contentHash: string; at: string; }; /** Where the parent log stood when this was cut, per state service (its entry count): * a rebase reads the parent's entries since here to name what moved under the changeset. Outside * the hash (metadata of the cut, not of the change). */ cut?: Record; /** sha256 over the canonical JSON of `{id, world, base, actions}` (+ `verifiers` when any) */ contentHash: string; }; export declare function assertSafeChangesetName(name: string, what?: string): string; /** The "everything ever recorded in this world" base: zero ledgers, so every ledger diffs from * position 0. Used when a world has no marks yet — `diff` must still answer, not refuse. */ export declare function worldBootMarker(world: string, createdAt: string): WorldMarker; /** Capture the current position of every ledger — the cross-service base marker. */ export declare function captureMarker(opts: { id: string; world: string; ledgers: LedgerRef[]; createdAt?: string; clock?: string | null; disk?: boolean; }): WorldMarker; /** A marker taken in world A says nothing about world B's ledgers — comparing them would * produce a confident, wrong delta. Refuse. */ export declare function assertMarkerBelongsTo(marker: WorldMarker, world: string): void; /** * Every action appended after `base`, across `ledgers`, in `occurredAt` order. * * A ledger is verified against its recorded position before any of it is reported: fewer rows * than the marker counted, or a different action id at that position, means the ledger was * rewritten and the marker no longer addresses anything real. That is a * loud error — quietly re-basing on a rewritten ledger is how a diff lies. */ export declare function diffLedgers(opts: { world: string; ledgers: LedgerRef[]; base: WorldMarker; /** each write's field changes, for a caller that shows them (default) */ fields?: boolean; /** with the records each twin's root observed since the base (a refresh's, an ingest's): a window's evidence (architecture, "Replicating an issue") */ observed?: boolean; }): LedgerDelta; /** Read each write's pre-state through the authoritative kernel projection. No UI history fold. */ export declare function describeActionFields(ledgers: LedgerRef[], actions: ChangesetAction[]): NonNullable; /** Group a delta by vendor, then by operation — both in FIRST-OCCURRENCE order, so the rollup * reads in the same causal order as the actions themselves. */ export declare function summarizeByVendor(actions: ChangesetAction[]): VendorSummary[]; /** What `changesetContentHash` needs to see — the immutable fields, with `verifiers` and `cut` optional. */ export type ChangesetHashable = Pick & Partial>; export declare function changesetContentHash(changeset: ChangesetHashable): string; /** A verifier that cannot be evaluated deterministically is refused at authoring time, not * discovered at verify time. */ export declare function assertValidVerifiers(verifiers: ChangesetVerifier[]): ChangesetVerifier[]; /** Freeze a delta into a named, content-addressed changeset. */ export declare function buildChangeset(opts: { name: string; world: string; base: string; actions: ChangesetAction[]; verifiers?: ChangesetVerifier[]; createdAt?: string; message?: string; cut?: Record; cutBy?: string; owner?: string; }): Changeset; /** Recompute and compare — a changeset whose bytes were edited after authoring is not the * object anyone approved. Callers render this as a warning or a hard failure as suits. */ export declare function changesetHashMatches(changeset: Changeset): boolean; export type ReplayTarget = { /** the changeset service this target satisfies */ service: string; /** the state service to write into (may differ from the source's) */ stateService: string; controlRoot: string; }; export type ReplayActionResult = { service: string; sourceActionId: string; /** the action id in the TARGET ledger — identical to `sourceActionId` whenever the target * state service matches the source's, which is what makes replay verifiable */ actionId: string; /** 'write' = through `applyTwinWrite` (the kernel write path); 'append' = recorded verbatim */ via: 'write' | 'append'; status: 'performed' | 'replayed'; }; export type ReplayReport = { changeset: string; contentHash: string; /** the authoring world */ world: string; into: string; total: number; performed: number; replayed: number; services: string[]; actions: ReplayActionResult[]; }; /** * Recover the `uniqueness` value `applyTwinWrite` folded into an action id, or report that the * id is not twin-write-shaped at all (a hand-written or pack-appended action). * * The id format is `twin:::::[:]` * and both `operation` and `subjectId` may themselves contain ':', so the id cannot be split * field-wise. A repeated write additionally carries an occurrence ordinal (`…#1`), stripped below. Instead the deterministic prefix is REBUILT from the action's own recorded parts — * if it matches, whatever follows is exactly the uniqueness seam. Getting this right is what * keeps billable occurrences (two identical AI completions in one millisecond) from collapsing * into one action on replay. */ export declare function twinWriteShape(action: TwinAction): { uniqueness?: string; } | null; /** * Replay a changeset's actions, in order, into `targets`. * * Two paths, and the split is about EXPRESSIVENESS, not preference: * - `write` — the default and the point: back through `applyTwinWrite`, the same kernel entry * an SDK call lands on. The target re-derives the action id from content, so it matches the * source id and a second replay is a total no-op. * - `append` — the honest fallback for actions the write path cannot express: multi-resource * `projection` transactions (applyTwinWrite carries only flat `fields`, so routing them * through it would silently DROP the creates/deletes/emits) and `revert`/`confirm` * bookkeeping rows. These are appended verbatim under `appendActionIfAbsent`, which is * id-keyed — so they are idempotent on re-replay too. * * `preconditions` are deliberately NOT replayed. They were evaluated against the authoring * world's state at author time; re-evaluating them against a different base would fail replays * that are perfectly valid recordings. Verifying a changeset against a target's state is the * verifiers' job, not a silent side effect of replay. Dropping them cannot change any action * id — preconditions are not part of the content hash. */ export declare function replayChangeset(changeset: Changeset, opts: { into: string; targets: ReplayTarget[]; available?: string[]; }): Promise; /** * Run a changeset's verifiers against post-replay state. Deterministic on purpose: each assert * reads the target's PROJECTED state (`projectResources` — the same projection the kernel's * preconditions and plan conflicts read) and is evaluated by `checkPrecondition` — the same * evaluator, so a verifier means exactly what a precondition means. The `worldDigest` is a * receipt over everything the verifiers could have seen: two runs that produced the same * post-replay state produce the same digest. * * `targets` are the same references replay wrote through — a verifier is only honest against * the ledgers the replay actually landed in. A verifier naming a service with no target is a * loud error (there is nothing real to check it against), never a silent pass. */ export declare function runChangesetVerifiers(changeset: Changeset, targets: ReplayTarget[], opts: { at: string; into: string; }): ChangesetVerification; /** Record `verification` on the object — REPLACING any prior run (the provenance fields carry * which run this is), never touching the hash the body is addressed by. */ export declare function withVerification(changeset: Changeset, verification: ChangesetVerification): Changeset; /** * Append an approval bound to the changeset's CURRENT body hash. Refuses when the stored * `contentHash` no longer matches the body: an object whose bytes moved after authoring is not * the object anyone reviewed, and signing it would launder the drift. Loud, never silent. */ export declare function approveChangeset(changeset: Changeset, opts: { principal: string; at?: string; note?: string; }): { changeset: Changeset; approval: ChangesetApproval; }; /** Everything `changeset status` reports — recomputed from the object, never trusted off * stored booleans (the same rule `planRequiresApproval` follows). */ export type ChangesetReadiness = { name: string; world: string; contentHash: string; /** stored hash matches the body */ hashOk: boolean; /** the different people whose approvals bind to the current hash, and how many this World requires */ approvers: number; required: number; /** a verification exists, binds to the current hash, and every verifier passed */ verified: boolean; verification: ChangesetVerification | null; /** every approval on the object */ approvals: number; /** approvals whose hash-at-signing is the current body hash — the only ones that count */ bindingApprovals: number; ready: boolean; /** empty exactly when ready */ reasons: string[]; }; /** Ready to apply: hashed as authored, verified against its current contents, and approved for them by `rules.approvals` * different people (the World's changeset rules; one when it names none). */ /** Whom an approval counts for: the person a key acts for (`key: for:`), else the principal itself. */ export declare function approverOf(principal: string): string; export declare function changesetReadiness(changeset: Changeset, rules?: { approvals?: number; }): ChangesetReadiness; /** The object with its application recorded — `applied` is outside the hash. */ export declare function withApplication(changeset: Changeset, application: ChangesetApplication): Changeset; /** One deterministic paragraph per twin, one sentence per operation, in first-occurrence order. */ export declare function narrateActions(actions: ChangesetAction[]): string; /** The recorded narration against its re-render — null when they agree or when the object carries none. */ export declare function narrationDrift(changeset: Pick & Partial>): { recorded: string; expected: string; } | null; export type ApplyReceipt = { actionId: string; service: string; stateService: string; status: 'confirmed' | 'replayed' | 'failed' | 'skipped'; pushId?: string; externalId?: string; url?: string; error?: string; }; export type CompensationEntry = { service: string; actionId: string; subject: { type: string; id: string; }; externalId?: string; /** the action's own revert spec when it carries one, else the inverse on the vendor id */ revert: TwinActionRevertSpec | { strategy: 'inverse'; }; }; /** How a push went: the receipts origin answered, recorded on the changeset object. */ export type ChangesetApplication = { at: string; contentHash: string; /** The destination the push went to. */ destination: { url: string; namespace: string; }; outcome: 'applied' | 'partial' | 'refused'; forced?: boolean; refusal?: string[]; receipts: ApplyReceipt[]; compensation: CompensationEntry[]; }; export type RebaseTarget = { service: string; stateService: string; controlRoot: string; }; export type RebaseActionResult = { actionId: string; service: string; status: 'unchanged' | 'rebased' | 'rebased-blind' | 'conflict'; moved?: Record; conflicts?: Array<{ subject: { type: string; id: string; }; field: string; op: string; expected?: unknown; actual: unknown; }>; }; export type RebaseReport = { changeset: string; from: string; to: string | null; at: string; outcome: 'unchanged' | 'rebased' | 'conflict'; actions: RebaseActionResult[]; }; export declare function rebaseChangeset(changeset: Changeset, opts: { targets: RebaseTarget[]; at?: string; }): { changeset: Changeset; report: RebaseReport; };