@sema-agent/core
Version:
Stateless, task-oriented AI agent core
199 lines (198 loc) • 14.2 kB
TypeScript
/**
* design/382 §4.3 / design/389 — the SESSION partition of the permission-rule store: where a
* `{kind:"session"}` scoped allow rule lives.
*
* A session authorization's home is the session's own lifetime — never the durable CRDT partition. The
* rows are ordinary {@link PersistedRule}s (scope `session`), and the unified store's ONE read
* query (`PermissionRuleStore.effective({ sessionId })`) splices this partition's rows IN FRONT of the
* durable partition's (the §4.1 narrowest-first reporting order: session > project > global), so every
* read-side consumer — the gate's conjunction arm, the coverage table, the consent prepare — takes them
* through the ONE eligibility predicate with zero second judges. The store's routing writer lands a
* session-scope `redemption-add` here; the durable partition never sees one.
*
* ## The contract (design/382 §8-Q6, settled here)
*
* A partition is addressed by a {@link SessionRowKey}: the engine mints it from the rule owner of the store it reads through and
* the session id ({@link sessionRowKeyOf}), so one owner's rows of a session are never another owner's, and a store with no owner
* (an anonymous task's) mints none and reads, writes and takes back nothing here. Every verb's first argument is that key, and
* every row a partition serves carries it as its scope's `sessionId`; the engine reads only rows whose scope is the key it handed
* over, and hands them on under the session id. A partition says so by declaring `addressedBy: "session-row-key"`.
*
* Two verbs every partition has, and a third a partition may have:
* · `read(key)` — the live rows of ONE owner in ONE session, that key's only.
* · `apply(key, add)` — land one redeemed authorization. Idempotent BY DOT (the redemption
* replay contract: `alreadyRedeemed` marks the dot as RECORDED, not the overlay as LANDED, so a
* replay must RE-APPLY, and this verb is what makes re-applying safe); refuses `session_ended`
* once the session's lifetime epoch is sealed — a late in-flight write after termination must not
* revive an authorization for a session that no longer exists.
* · `revoke(key, target)` — the person takes one row of THEIR session back before the session ends:
* the row of that identity (behavior, rule text) is gone with every add it carried, and a dot it carried
* never lands again in this session — a replayed redemption of it is an acknowledged write and an absent
* rule, exactly as a tombstoned dot is in the durable partition. Revoking is the tightening direction, so
* it takes no approval; it refuses `session_ended` like `apply` (there is nothing left to take back).
*
* Termination is still the HOST's act on its own implementation (see
* {@link InMemorySessionRulePartition.endSession}), not an engine verb: `revoke` takes ONE row back,
* ending the session takes all of them and seals the session.
*
* ## Lifecycle and durability
*
* The overlay lives WITH the session: a host that parks/checkpoints a session serializes its rows
* beside it and rehydrates them on resume (`snapshotSession`/`restoreSession` on the reference
* implementation, both addressed by the key) — that is how a session authorization survives a park without
* ever touching the persisted store, and why it still ends when the session ends. A host ends, snapshots and
* restores each owner's rows of a session under that owner's key. `sessionId` uniqueness is the host's
* duty (the `principal` posture): reusing an id declares "the same session".
*
* ## What this is NOT
*
* Not a durable backend: no dots are minted here (the redemption leg mints the audit dot exactly as the
* store leg does), no tombstones exist here, nothing here syncs. Every durable entrance — write
* deltas, sync in both directions, at-rest bytes — refuses or drops a session row
* (`permission-rule-store.ts`, the durable two-member face); this module is the OTHER side of that
* wall, and the wall is the design.
*/
import type { PersistedRule, RuleAdd, RuleBehavior, PersistedRuleMatch, PersistedRuleTool } from "./permission-rule-model.js";
import { type RuleOwner } from "./rule-owner.js";
/**
* How a session partition is addressed — the one word a partition declares ({@link SessionRulePartition.addressedBy}):
* `session-row-key`, its verbs are handed a {@link SessionRowKey} and the rows it serves carry that key as their scope's
* `sessionId`. A partition that declares no word of this set is refused when the provider is composed.
*/
export declare const SESSION_PARTITION_ADDRESSINGS: readonly ["session-row-key"];
export type SessionPartitionAddressing = (typeof SESSION_PARTITION_ADDRESSINGS)[number];
declare const SESSION_ROW_KEY: unique symbol;
/**
* The address of ONE owner's rows in ONE session: minted by {@link sessionRowKeyOf} from the rule owner and the session id,
* and nowhere else. Two different (owner, session) pairs never mint the same key, and a key has one spelling.
*/
export type SessionRowKey = string & {
readonly [SESSION_ROW_KEY]: true;
};
/**
* The key of `owner`'s rows in session `sessionId`: the JSON text of `["session-row", 1, "principal", <name>, <sessionId>]`, or of
* `["session-row", 1, "local-owner", <sessionId>]` for the local owner. The owner is read by `readRuleOwner` and the session id must
* be a non-empty string; anything else is refused (`config.invalid_argument`). Names and ids are compared byte for byte: no case
* folding, no Unicode normalization.
*/
export declare function sessionRowKeyOf(owner: RuleOwner, sessionId: string): SessionRowKey;
/** One redeemed authorization landing in a session's overlay: the rule's canonical shape plus the
* redemption's own add (dot + provenance) — the same fields a `redemption-add` delta carries, minus
* the scope (the verb's key IS the scope's `sessionId`, constructed by the partition so a caller cannot land a row
* whose scope names a different address than the one it handed over). */
export interface SessionRuleAdd {
behavior: RuleBehavior;
rule: string;
tool: PersistedRuleTool;
match: PersistedRuleMatch;
command: string;
add: RuleAdd;
}
/** What one overlay apply answered. `session_ended` is the epoch fence speaking: the write arrived at
* (or after) termination and landed nothing — the redemption reports the member `refused`. */
export type SessionRuleApplyResult = {
landed: true;
} | {
refused: "session_ended";
};
/** The identity of one session row a revocation names: its behavior and its canonical rule text (the address is the verb's
* key). Behavior is part of it because one text may stand as an allow and as a deny in one session. */
export interface SessionRuleTarget {
behavior: RuleBehavior;
rule: string;
}
/** What one revocation answered: how many rows of that identity were taken back (0 — there was none, a repeated revoke
* included; 1 — it is gone), or the epoch fence: the session already ended and holds nothing to take back. */
export type SessionRuleRevokeResult = {
revoked: number;
} | {
refused: "session_ended";
};
/**
* The session partition a deployment hands to `createPermissionRuleStoreProvider({ session })`. See the
* module doc for the contract; {@link InMemorySessionRulePartition} is the reference implementation and
* the semantics. A backend that keeps a session's rows beside its own session record (a host whose
* sessions are durable) may implement this over that storage — the law is LIFETIME-bound, not
* medium-bound: no tombstones, no sync, nothing outlives the session.
*/
export interface SessionRulePartition {
/** The declaration that this partition's verbs are handed a {@link SessionRowKey} and that the rows it serves carry it as their
* scope's `sessionId`. Declaring it states that every row the partition holds is stored under such a key: rows a partition
* stored under a bare session id are migrated to their owner's key, or dropped, before the declaration is made. */
readonly addressedBy: SessionPartitionAddressing;
/** The live rows of ONE owner in ONE session (`key`). An ended (or never-written) session reads as `[]`. */
read(key: SessionRowKey): Promise<readonly PersistedRule[]>;
/** Land one redeemed authorization — idempotent by dot, refused once the session ended. A dot this session revoked
* lands nothing and answers `landed` (an acknowledged write of a removed rule; the redemption's read-back says it is gone). */
apply(key: SessionRowKey, add: SessionRuleAdd): Promise<SessionRuleApplyResult>;
/** Take one row of the session back (every add of that identity), refused once the session ended. Its dots never land
* again in this session, and a restore of rows minted before the revocation into the SAME partition instance does not bring them
* back (the revocation is remembered in that instance's memory only: a snapshot cut before it and restored into another
* partition — another process, after a restart — brings the row back, so cut the snapshot again after a revocation). OPTIONAL: a partition
* without it serves and lands rows as before, its rows cannot be taken back before the session ends (a session-scope
* removal says so), and the engine offers no grant whose promise is that it can be ("allow this call for the session"). */
revoke?(key: SessionRowKey, target: SessionRuleTarget): Promise<SessionRuleRevokeResult>;
}
/**
* The reference overlay — in-memory, per-process, the semantics every host implementation must keep:
*
* · APPLY is idempotent by dot identity (a replayed redemption re-submits its recorded dot and
* changes nothing — the store's `foldDelta` discipline, verbatim);
* · TERMINATION seals FIRST, clears SECOND ({@link endSession}): the sealed-set membership is the
* session's lifetime epoch, flipped atomically before any state is dropped, so an in-flight write
* that lost the race lands on the seal and answers `session_ended` — never on a half-cleared
* session, and never as a row that outlives its session (design/382 §4.3, the r2-⑥ fence);
* · a sealed session never reopens — `apply` and `restoreSession` both refuse it, so "session ended"
* is a one-way fact exactly like a quarantined dot's;
* · SNAPSHOT/RESTORE ({@link snapshotSession}/{@link restoreSession}) are the park/resume carriage:
* the host serializes a session's rows into its checkpoint and rehydrates them on resume. Restore
* is fail-closed on shape — every row must be a session row of THE session being restored (a
* checkpoint is host-owned bytes, and a global row smuggled through this door would ride the
* merge point straight into adjudication).
*/
export declare class InMemorySessionRulePartition implements SessionRulePartition {
private readonly rows;
private readonly sealed;
/** How many times one session's row set has CHANGED. Reading a caller-owned value runs caller code,
* so a verb that reads its argument and then replaces a session's rows wholesale must be able to
* tell that something landed in between — otherwise it overwrites a grant that was already answered
* `landed:true`, and a consent nobody withdrew stops existing. Bumped by every landing, restore and
* termination; read across `restoreSession`'s snapshot. */
private readonly epochs;
/** The dots each live session revoked (`actor#counter`): never landed again by `apply`, dropped from what `restoreSession`
* installs. Gone with the session at `endSession` (the seal answers everything after it). */
private readonly revokedDots;
/** The declaration {@link SessionRulePartition.addressedBy} asks for: every verb here takes a {@link SessionRowKey}, and refuses
* (`config.invalid_argument`) anything that is not one — a bare session id included. */
readonly addressedBy: "session-row-key";
private bumpEpoch;
read(key: SessionRowKey): Promise<readonly PersistedRule[]>;
apply(key: SessionRowKey, add: SessionRuleAdd): Promise<SessionRuleApplyResult>;
/**
* The termination transfer: SEAL the lifetime epoch first (one atomic membership flip — after this
* line every in-flight `apply` holding this id answers `session_ended`), THEN drop the rows. The
* order is the whole fence: clear-then-seal would leave a window in which a late write re-grows a
* rule set for a session that is already gone. Idempotent; a never-seen id seals to the same place.
*/
endSession(key: SessionRowKey): void;
revoke(key: SessionRowKey, target: SessionRuleTarget): Promise<SessionRuleRevokeResult>;
/** The park half of the checkpoint carriage: this owner's rows of the session (`key`), serializable as-is — each row's scope
* carries the key, so the snapshot restores under the same key only. */
snapshotSession(key: SessionRowKey): Promise<readonly PersistedRule[]>;
/**
* The resume half. Fail-closed on every axis: a sealed session never rehydrates (termination is
* one-way), and every row must be a well-formed SESSION row of exactly this session — anything else
* in the checkpoint bytes is refused whole, loudly, because the merge point trusts this overlay to
* serve only what its contract says it holds.
*
* The rows also pass the SAME `normalizePersistedRule` re-projection the sync face runs on store
* rows (rule text parses, canonical spelling, stored tool/match/command agree with the text): this
* door takes host-owned checkpoint bytes with no redemption validator in front of them, and a row
* the engine could not re-project would otherwise sit one merge away from adjudication. Rows this
* overlay landed itself always pass — {@link InMemorySessionRulePartition.apply} runs the same screen,
* so the two doors agree on what a session row is and a snapshot of this overlay always restores —
* which is what makes a refusal here foreign damage, refused whole.
*/
restoreSession(key: SessionRowKey, rows: readonly PersistedRule[]): Promise<void>;
}
export {};