import type { SubjectFields } from './hash.js'; import { type Receipt } from './log.js'; import type { TwinResource } from './serve.js'; export type TwinActionOp = 'set' | 'revert'; export type TwinActionPreconditionOp = 'exists' | 'not_exists' | 'eq' | 'neq' | 'version_eq'; export type TwinActionPrecondition = { subject: { type: string; id: string; }; field: string; op: TwinActionPreconditionOp; value?: unknown; }; export type TwinActionRevertSpec = { strategy: 'inverse' | 'suppress' | 'compensating-action'; operation?: string; fields?: SubjectFields; }; export type ProjectedResource = { type: string; id: string; fields: SubjectFields; }; export type ProjectedResourcePatch = { type: string; id: string; fields: SubjectFields; }; export type ProjectedResourceRef = { type: string; id: string; }; export type ProjectedDelivery = { kind: 'webhook' | 'event' | 'notification'; target: string; payload: Record; }; export type ActionProjection = { creates?: ProjectedResource[]; updates?: ProjectedResourcePatch[]; deletes?: ProjectedResourceRef[]; emits?: ProjectedDelivery[]; }; export type TwinAction = { id: string; service: string; op: TwinActionOp; subject: { type: string; id: string; }; occurredAt: string; actor?: { kind: 'agent' | 'human' | 'bot' | 'system'; id?: string; }; /** Optional vendor operation name, e.g. `issue.update` or `message.send`. */ operation?: string; /** The caller's own request key, when it asked for at-most-once. Provenance, AND the marker that * makes replay identity ignore `occurredAt`: the whole point of a request key is that a retry * arriving at a different millisecond is the SAME request, so comparing the two bodies must not * fail on the timestamp. Without this, a caller that did not pin `occurredAt` got a thrown * "Conflicting duplicate twin action" — a 500 where it had asked for idempotence. */ idempotencyKey?: string; /** Raw operation input (provenance); not projected — `fields`/`projection` carry the state change. */ input?: Record; /** Preconditions are evaluated against the current projected twin state before append. */ preconditions?: TwinActionPrecondition[]; fields?: SubjectFields; projection?: ActionProjection; revertsActionId?: string; /** A pending row a snapshot import planted (contract "A snapshot import never plants a push"): * still local state the projection serves, never awaiting push until released on purpose. */ quarantined?: { at: string; by: string; }; /** Optional machine-readable hint for how a UI/pack should construct a revert. */ revert?: TwinActionRevertSpec; /** * Request-scoped correlation id (D3 — the purpose-3 audit trail: "who reviewed the * change that caused this real write"). Always present on an appended action — * appendAction/appendActionIfAbsent generate one when the caller doesn't supply it — * and threaded through to the push-ledger row(s) a push against this action produces * (see pushLedger.ts), so an action row and its push-ledger row(s) join on this id * alone, with no dependence on actionId/pushId naming conventions. */ correlationId?: string; /** The W3C `traceparent` of the request that caused this action, when it carried a valid one * (trace-context.ts). Authoring metadata like correlationId: excluded from replay identity. */ traceparent?: string; }; export type TwinTransactionCommit = TwinAction; export type TwinTransactionCommitOp = TwinActionOp; export type TwinTransactionPrecondition = TwinActionPrecondition; export type TwinTransactionRevertSpec = TwinActionRevertSpec; export declare class TwinActionPreconditionError extends Error { readonly actionId: string; readonly failed: TwinActionPrecondition; constructor(actionId: string, failed: TwinActionPrecondition); } /** Subjects a `set` action touches: its own subject, every projection resource, and every * precondition subject — a precondition established the action's validity against that * subject's state, so remote movement there is drift for this action too. */ export declare function touchedSubjects(action: TwinAction): Array<{ type: string; id: string; }>; export declare function observeAppends(observer: ((action: TwinAction, root: string | undefined) => void) | undefined): void; export declare function runWithCorrelationId(id: string, fn: () => T): T; export declare function currentCorrelationId(): string | undefined; export declare function appendAction(action: TwinAction, root?: string): TwinAction; /** Append `action` only if no exact action with the same id already exists — the whole * replay/precondition/append decision runs under the service projection + actions locks, so it's * atomic across processes (two concurrent identical writes converge to ONE action; distinct * writes both land). A reused id with different content fails loudly. */ export declare function appendActionIfAbsent(action: TwinAction, root?: string): { action: TwinAction; appended: boolean; placeholder?: true; }; /** * Append `build(n)` as an OCCURRENCE: the nth time this exact write has been made. * * A local vendor write is an occurrence, not a replay — two calls are two actions, even * byte-identical in the same instant (docs/contributing/architecture.md, "The state kernel", * "A local write is an occurrence"). `appendActionIfAbsent` cannot express that: its identity is content, and * content provably cannot separate "the same request delivered twice" from "the same change made * twice". So a caller wanting at-most-once passes an explicit key and uses that function; a caller * recording what actually happened uses this one. * * The ordinal keeps every EXISTING action id byte-identical: occurrence 0 is `build(0)`'s own id, * and only a genuine repeat becomes `#1`, `#2`. It is derived under the same projection + * actions locks as the append, so two processes racing take different ordinals rather than * colliding, and it is deterministic — replaying one sequence of writes onto a fresh root yields * the same ordinals, which is what serve-path determinism requires. */ export declare function appendActionOccurrence(base: TwinAction, root?: string): { action: TwinAction; appended: boolean; placeholder?: true; }; /** * Append several writes of ONE service as occurrences, in order, under one projection + actions lock and as one store * append: each lands with the id, ordinal and correlation `appendActionOccurrence` would give it called once per write * in the same order (a write's ordinal counts the batch's earlier writes as taken). Preconditions are checked against * the state the earlier ones made, which only the one-at-a-time path sees. While a placeholder pull is open a write * lands as the placeholder's entries, as `appendActionOccurrence`'s does. */ export declare function appendActionOccurrences(bases: readonly TwinAction[], root?: string): Array<{ action: TwinAction; appended: boolean; placeholder?: true; }>; /** Occurrence 0 IS the base id — so nothing that exists today changes shape. The appender owns * this math; a caller passing an already-ordinalled id would stack them (`…#1#1`). */ export declare function occurrenceId(base: string, ordinal: number): string; export type AtomicActionDecision = { kind: 'skip'; value: T; } | { kind: 'append'; action: TwinAction; value: T; /** `'occurrence'` (default) appends every call, with the ordinal and the first occurrence's * merge base. `'caller'` is at-most-once on the caller's own identity — what an * `idempotencyKey` or `actionId` means. It rides on the DECISION rather than on the * function's arguments because only the callback knows which write it chose. */ identity?: 'occurrence' | 'caller'; }; /** * Evaluate current projected state and optionally append one action under ONE service projection * transaction (the shared projection lock plus the action-log lock). This is the narrow * state-dependent seam for vendor operations whose acceptance and resulting fields depend on the * latest observed + local projection (for example, immutable version publish). * * The callback must remain synchronous and side-effect free: it computes a decision from the * supplied snapshot. Durable state changes only through the returned action, which this helper * appends before releasing the lock. */ export declare function decideAndAppendAction(service: string, decide: (resources: TwinResource[]) => AtomicActionDecision, root?: string, /** A narrower indexed snapshot, read under the same lock; it must cover every decision and precondition. */ read?: () => TwinResource[]): { value: T; action?: TwinAction; appended: boolean; placeholder?: true; }; export declare function appendTransactionCommit(commit: TwinTransactionCommit, root?: string): TwinTransactionCommit; export declare function listActions(service: string, root?: string): TwinAction[]; /** The kernel's ONE deterministic check: does `actual` satisfy the precondition expression? * Shared by write-time preconditions (here), plan conflict detection (plan.ts) and changeset * verifiers (changeset.ts) — one evaluator, so a check means the same thing everywhere. */ export declare function checkPrecondition(precondition: TwinActionPrecondition, actual: unknown): boolean; /** Look a precondition subject's field up in projected resources (undefined = no resource or * no field — exactly what `exists`/`not_exists` distinguish). */ export declare function projectedPreconditionValue(precondition: TwinActionPrecondition, resources: TwinResource[]): unknown; /** * Project the action log over the observed mirror → current twin resources. * `set` actions overlay fields (creating subjects that don't exist in the mirror); * reverted and confirmed actions are skipped (confirmed facts come from the * observed log instead, so they are not projected twice). */ /** THE TREE (log.ts): what a read sees — the nearest checkpoint plus the entries since; the parent's * entries, then this branch's, skipping any the parent already holds. `until` folds only the * branch entries BEFORE that id — the state a write saw at its own append (the rebase's * evaluation point). */ export declare function projectResources(service: string, root?: string, opts?: { until?: string; }): TwinResource[]; /** A read of another pack's store that cannot choose: the subject it looks for (or, with none named, the store itself) * is held by more than one service of the World. A reader answers it as the vendor answers a credential it cannot * resolve; it is never a server error. */ export declare class OwnerStoreAmbiguousError extends Error { constructor(owner: string, roots: string[], subject?: { type: string; id: string; }); } /** * ANOTHER pack's rows, read by contract (architecture A3: one vendor's store split across two packs, googleoauth's tokens * read by webrisk; the reader's manifest declares the pair, `ownerReads`): the * owner's tree, from wherever the World keeps the owner's store (`ownerStoreRoots`). Read only: the rows are frozen and * shared. It claims no journal identity (the twin answering is the reader). * * With `subject`, the store that holds that subject (the token a request presents): `[]` when none does, and * `OwnerStoreAmbiguousError` only when more than one does, so a second service running the owning pack never breaks a * lookup of what only one of them issued. Without it, the one store there is, and `OwnerStoreAmbiguousError` when the * World holds two. */ export declare function projectOwnerResources(owner: string, root?: string, subject?: { type: string; id: string; }): readonly TwinResource[]; /** The local → vendor id aliases the landed copies carry: a read by the id a caller was handed before * its write was performed resolves to the row the vendor now owns. */ export declare function subjectAliases(service: string, root?: string): Map; /** Resolve a subject id through the aliases: the vendor's id when a confirm rebound it, else the id itself. */ export declare function resolveSubjectId(service: string, type: string, id: string, root?: string): string; /** * Confirm a local action after it was pushed to the real vendor: record the * confirmed fields as an OBSERVED event (origin 'external' — it's now real) and * append a `confirm` action mapping the local action → that observed event id. * Projection then drops the local action (the fact lives in the observed log), so * the change is counted exactly once. Returns the observed event id. */ export declare function confirmAction(opts: { service: string; actionId: string; subject: { type: string; id: string; }; fields: SubjectFields; /** Additional observed resources landed by the same compound action, under the same lock. */ additionalObservations?: Array<{ subject: { type: string; id: string; }; fields: SubjectFields; }>; /** The subject id the VENDOR minted for this write (the push outcome's externalId). When it * differs from the local id, the landed copy carries the vendor's id and `aliasOf` names the * local one, so a read by either id finds the row. */ vendorSubjectId?: string; /** the receipt on the landed copy; `deployed` when omitted (the push performed it) */ receipt?: Partial; occurredAt: string; root?: string; }): { observedEventId: string; observedEventIds: string[]; }; export type RevertOutcome = { status: 'reverted'; revertId: string; } | { status: 'already-reverted'; } | { status: 'confirmed'; } | { status: 'not-found'; } | { status: 'not-revertable'; op: TwinActionOp; }; /** * Revert one pending `set` action — decision AND append under the service projection + * actions locks, so a concurrent writer (a connector confirming the same action from * another process) cannot land between the check and the revert: the whole read-decide- * append is ONE critical section. Idempotent: a repeat answers 'already-reverted'. * Only `set` rows are revertable — reverting a revert or a confirm is a category error. */ export declare function revertAction(opts: { service: string; actionId: string; occurredAt: string; root?: string; }): RevertOutcome; /** The LOCAL OVERLAY: pending actions (set, not reverted, not yet confirmed) — the divergence * from the mirror, what a twin's projection folds over the observed state. A QUARANTINED row * (contract "A snapshot import never plants a push") is still local state and stays here; it * leaves only the PUSHABLE suffix below. */ export declare function pendingActions(service: string, root?: string): TwinAction[]; /** A twin's OWN bookkeeping in its action log — a subject type beginning with `_` (stripe's * `_idempotency` store, for one): part of the overlay the twin serves from, never a change the * app made. It is not pushed or deployed. It is not in the log a user reads, a diff or a changeset either, except the * World's people (`isWorldPerson`). */ export declare function isTwinBookkeeping(action: Pick): boolean; /** A person a twin's pages sign in (`_person`, people.ts): bookkeeping to the kernel, and the one bookkeeping the log * a user reads, the diff and every changeset carry, so an account replayed into another World signs in there. A * replay writes its committed row (the email, the password's hash and what the sign-up keeps), never the sign-up. * ADR 0025. */ export declare function isWorldPerson(action: Pick): boolean; /** Whether an action is in the World's history as a user reads it, diffs it and cuts changesets from it. */ export declare function inWorldHistory(action: Pick): boolean; /** The PUSHABLE suffix — `log origin..HEAD` as the push arm, the pending door, plans and the * unpushed count read it: the overlay minus quarantined rows (an import is a copy, not a * decision; releasing a quarantined row is an explicit act, never a scheduler's) and minus the * twin's own bookkeeping. */ export declare function pushablePendingActions(service: string, root?: string): TwinAction[];