@sema-agent/core
Version:
Stateless, task-oriented AI agent core
337 lines (336 loc) • 27.8 kB
TypeScript
/**
* design/389 — ONE permission-rule store, partitioned by SOURCE.
*
* A rule comes from one of four sources — `org | user | project | session` — and the four differ in
* polarity, authority and evolution (an org snapshot is replaced whole by a server administrator; a
* user/project rule is one human click folded into an OR-Set CRDT; a session grant lives exactly as long
* as its session). Those differences are WRITE LAWS, and each partition keeps its own. What is one is the
* READ: "which rules stand for this owner, in this session, and what does each one's standing look like"
* is a single question, so it has a single answer — {@link PermissionRuleStore.effective}, a query the
* store answers across every partition with each row's `source` and `status`, the org shadow predicate
* applied inside the store rather than at each caller.
*
* ## Composition, not inheritance
*
* {@link createPermissionRuleStoreProvider} is the ONE way to build the store. A deployment hands it
* partition backends — the durable CRDT partition (`DurableRulePartitionProvider`: file, in-memory, an
* out-of-repo SQL twin), an org partition config (its snapshot source and staleness bound), a session
* partition — and the engine composes them. The org and session partition LAWS are engine code the
* backend cannot weaken; the durable partition's law is the exported pure fold every backend runs.
* A partition a deployment does not configure does not exist: its source answers nothing, and the
* provider's `partitions` face says so, so a manifest reads a declaration rather than inferring one.
*
* ## Source is a projection of the row's address
*
* `user` ⟺ scope `global`, `project` ⟺ scope `project`, `session` ⟺ scope `session`. A row never carries
* a second source byte that could drift from its scope — {@link ruleSourceOf} is the whole mapping.
*
* ## One write path, routed by scope
*
* `writerOf(store)` hands back a writer whose `apply` routes a `redemption-add` by the delta's scope: a
* session scope lands in the session partition (idempotent by dot, refused `session_ended` past the
* session's epoch seal), the two durable scopes take the CRDT partition's compare-and-set. The consent
* protocol therefore has ONE write path with ONE result vocabulary ({@link RuleWriteOutcome}); the
* durable backend keeps refusing a session row loudly should one ever reach it — the route is the
* store's, the fence stays the partition's.
*/
import type { PersistedRule, RuleScope } from "./permission-rule-model.js";
import { type DurableRulePartitionProvider, type QuarantinedRuleAdd, type RemovalLiveness } from "./permission-rule-store.js";
import { type RuleOwner } from "./rule-owner.js";
import { type RuleStoreFault } from "./rule-store-fault.js";
import { type OrgRulePartitionConfig, type OrgRuleResolution } from "./permission-rule-org.js";
import { type SessionRulePartition, type SessionRuleRevokeResult, type SessionRuleTarget } from "./permission-rule-session.js";
import type { StoreDurability, StoreFidelity } from "./checkpoint-store.js";
import { type AutoStripRowReason } from "./auto-strip.js";
import { type MountedPeersSeat } from "./a2a-bound-grant.js";
import type { AllowRuleBinding } from "./allow-rule-shadow.js";
/** The three sources a personal rule row can come from (every source but the org partition's), each word spelled here once — the
* closed set a reader of the words enumerates. The published faces that predate it read the same set as `Exclude<RuleSource, "org">`
* (a derivation of these words, kept so their declared types do not move). */
export type PersonalRuleSource = "user" | "project" | "session";
/** The four sources a rule can come from — CC's settings-layer vocabulary folded onto sema's four. */
export type RuleSource = "org" | PersonalRuleSource;
/** The source of a row is a projection of its scope — `global` is the `user` source. */
export declare function ruleSourceOf(scope: RuleScope): Exclude<RuleSource, "org">;
/** One live personal rule in the effective view: the row itself, its source, and its standing under the
* org partition (`shadowed-by-org` = an org deny reaches an ALLOW row's command pattern; see
* `orgRuleShadows` — a personal deny/ask row is never shadowed: it only ever tightens, and the org
* partition's power over the personal store is to override an allow, not a refusal). */
export interface EffectivePermissionRule extends PersistedRule {
source: Exclude<RuleSource, "org">;
status: "live" | "shadowed-by-org";
/** Present iff auto mode does not use this ALLOW row — in `auto` it clears no call and the calls it names go to the classifier
* (the allow layer's strip, `storedRowAutoStrip`): `whole_shell` (it reaches every shell command) or `code_runner` (it opens a
* program that runs whatever code it is given). Derived here, like `source` and `status`, from the row alone: a run's own facts
* — a leg that declares `TaskSpec.classifyAllShell`, a tool that answers to the shell under another name — stand more rows down
* in that run, and that run records it (`permission.allow_rule_not_used_in_auto`, attention `audit`). Absent on a row auto mode uses as
* written, on a row whose text reads as no allow rule (it grants nothing in any mode) and on every deny / ask row; read off the
* row's text, so a malformed row never fails the read. */
autoStrip?: AutoStripRowReason;
/** Present iff this is an ALLOW row naming an A2A peer (`a2a__<peer>`, `a2a__<peer>__<skill>`) that the deployment's mounted-peers seat
* ({@link PermissionRuleStoreConfig.a2aPeers}) registers inside the trust boundary now: whether the row is bound to the peer's
* identity now ({@link AllowRuleBinding}; the bound-grant law's reading of its live adds' stamps against the registration's). Derived
* from the row and the registration alone, like `autoStrip`: whether a call is asked is the run's question — a skill the registration
* marks irreversible or leaving the organization, and every call of a deployment that isolates its peers (`RunnerDeps.a2a.isolatePeers`,
* a switch of the Runner's this store never sees), are still asked, and the ask says why. Absent on every other row, on every row of a
* store with no seat, and where the seat could not be read — absence is no claim. */
binding?: AllowRuleBinding;
}
/** A durable rule identity every add of which is tombstoned — the rule no longer stands, and its
* tombstone identity is still visible in the partition. Session rows never appear here (they die
* with their session and leave no tombstone). */
export interface RemovedPermissionRule {
behavior: import("./permission-rule-model.js").RuleBehavior;
rule: string;
scope: RuleScope;
source: "user" | "project";
status: "removed";
}
/** One read of the person's store as every consumer of it reads it, the failure law applied (a run's one reader of it,
* `person-path-rows.ts`, takes it; the rule lanes and the read station read it). */
export interface PersonRowsRead {
/** The rows this read stands on: each partition it read, as read; each it could not read, the deny and ask rows of the
* run's last successful read of that partition (none before one). This session's rows first. */
readonly rules: readonly EffectivePermissionRule[];
/** The org partition's resolution off this read. Absent when the whole read failed — {@link unreadable} says why. */
readonly org?: OrgRuleResolution;
/** Present iff a personal partition (or the whole read) could not be read: the failure's line. */
readonly unreadable?: string;
/** Beside {@link unreadable}: why, as closed reason words — one fault per failed partition, or one over every partition a read that
* failed whole took out ({@link EffectivePermissionRules.unreadableFaults}). */
readonly unreadableFaults?: readonly RuleStoreFault[];
/** The personal rows this read stands on that could not be read whole ({@link EffectivePermissionRules.unreadableRows}: as written
* when their identity read, else at their strictest reading): each partition's own when it was read, the run's last successful read's
* when it could not be. Absent when none. */
readonly unreadableRows?: NonNullable<EffectivePermissionRules["unreadableRows"]>;
}
/** THE answer of the store's one read query. */
export interface EffectivePermissionRules {
/** Live personal rows, in reporting order: this session's rows first (the narrowest standing yes), then
* the durable partition in its own table order — byte-equivalent to the pre-389 splice. */
rules: EffectivePermissionRule[];
/** Tombstoned durable identities (introspection). */
removed: RemovedPermissionRule[];
/** The org partition's resolution. `ungoverned` on a deployment with no org partition. */
org: OrgRuleResolution;
/** The durable partition's revision — the optimistic-concurrency anchor for its writes. 0 when the partition could not be read
* ({@link unreadable}) or its revision could not be ({@link unreadableRev}); neither anchors a write. */
rev: number;
/** Present iff the durable partition was read and its revision could not be read as data (an object or a function where a revision
* belongs, a read that throws): the line names why. No check reads a revision, so every row stands as read, in every permission
* mode; `rev` is then 0 and anchors no write — the engine's add entries take no write off this read (they answer that the store
* could not be read: nothing committed), and a host that writes off this view checks this member as it checks {@link unreadable}. */
unreadableRev?: string;
/** Present iff a PERSONAL partition could not be read — the durable one (its user / project rows; `removed` is then
* empty and `rev` 0) or the session one: the failed partition's rows are absent from `rules`, while the rows of the
* partition that WAS read stand, and so does the org resolution beside them (a flaky personal store must not become an
* org governance outage). The line names the failure (both lines, `; `-joined, when both failed). A consumer that needs
* the durable rows treats this as a read failure — {@link effectiveOrThrow} is that reading; the gate's personal lane
* and the leg's path-row read skip the failed partition's rows, disclosed, and judge by the rest. */
unreadable?: string;
/** Beside {@link unreadable}: the sources whose partition could not be read (`user` and `project` — the durable
* partition; `session`), in that order — the rows `rules` does not carry. The flat list of {@link unreadableFaults}' sources. */
unreadableSources?: readonly Exclude<RuleSource, "org">[];
/** Beside {@link unreadable}: WHY each failed partition could not be read — one fault per partition (the durable one covers the
* `user` and `project` sources together), each a closed reason word read off the refusal's code and members
* ({@link ruleStoreFaultReasonOf}); never the refusal's text and never a path. A store that reports `unreadable` without it states
* no cause, and the reader says so. */
unreadableFaults?: readonly RuleStoreFault[];
/** Disclosure lines from the personal partitions (a session partition that could not be read, rows it
* served that are not canonical session rows of this session). The org partition's lines ride
* `org.disclosures`. */
disclosures: string[];
/** The personal rows that take no part in any check — a foreign writer's or a hand edit's, in practice — each with its text as
* served (an allow row whose text could not be read: the spelling of its stored fields or `(unreadable)`) and why:
* `scope_root_not_absolute` (its project scope root is not a complete absolute path; `scopeRoot` as served, a
* non-string root as its type), or an ALLOW row whose text is not a rule this grammar reads or not the canonical spelling of
* the row's own stored fields (`invalid_rule_text` / `metadata_mismatch`, {@link normalizePersistedRule}'s words) — or one a member of
* which could not be read as the type it holds (the faults {@link unreadableRows} names on a deny or ask row: `invalid_rule_text`
* for its text, `metadata_mismatch` for another member; `rule` is the spelling of its fields or `(unreadable)` when the text is the
* one; `member` — present on such a row only — the first member that could not be read), of the durable partition or of the session
* one (its session's). An entry whose behavior word could not be read or is outside deny / ask / allow is NOT dropped here: it enters
* {@link unreadableRows} at its strictest reading (`member: "behavior"`). The optional `element` member is retained on the exported
* type for host-supplied views; the in-tree rule readers no longer produce it. A deny or ask row is never left out for its spelling.
* Absent when none. The reader tells the person (`config.entries_not_applied`, kind `stored_rule_row`). */
droppedRows?: ReadonlyArray<{
readonly reason: "scope_root_not_absolute";
readonly rule: string;
readonly scopeRoot: string;
} | {
readonly reason: "invalid_rule_text" | "metadata_mismatch";
readonly rule: string;
readonly member?: string;
readonly element?: {
readonly partition: "durable" | "session";
readonly index: number;
readonly read: string;
};
}>;
/** The personal rows a member of which could not be read as the type it holds — deny and "ask me each time" rows, AND any entry whose
* behavior word could not be read (non-object, missing, non-string, throwing read, or a text outside deny / ask / allow): a read that
* throws, an object or a function where a value belongs, a list that is no list, and — every member a row holds: its behavior word,
* text, tool, match word and command (strings), its scope (an object), its list of adds (objects each holding its dot, an object
* holding its actor and counter; a hole, a primitive, an add with no dot, a dot with no actor or counter, or an add whose identity
* stamp only its prototype supplies — a stamp is an authorization, the add's own member only — there is an add that cannot be read) —
* a value that is none (absent, `null`, a number, a boolean). Such a member is the row's fault, never its partition's: the row is
* never read as no row, nor as a weaker one, and never ends a run (an entry whose behavior is no word of deny / ask / allow stands at
* its strictest reading with `behavior: "ask"` and `member: "behavior"`, since nothing says it was not a deny or an ask). The durable
* partition's rows and the session partition's are read the same way. Which reading it takes depends on WHICH member it is:
* · Its IDENTITY read — the stored fields the row's checks read to tell whether it reaches a call and what it then says (`tool`,
* `match`, and `command` save on a whole-tool row) — or, where one of them could not be read, its text did and is a rule this
* grammar reads: the row's identity is then ALL its text's (tool, match and command from the text's parse, the ones that read
* included — never one source's member beside another's), so what it reaches is what the text it is named by says; a row whose
* every identity member read is judged by them, as a row served whole is (its text, when it disagrees, too). Each member is read by
* one ordinary get, so an accessor's or a prototype's answer is the member's. The row stands in `rules` as written, in every
* permission mode, exactly as a row read whole (`reach` is `as_read`). Its text, when that is the member, reads as the canonical
* spelling of its stored tool, match and command — what its checks judge it by — or, when those spell no rule this grammar reads,
* as `(unreadable)`, a text that is no rule (an earlier grammar's row's reading); its scope reads as the widest (`global`; a session
* row's, its session); a whole-tool row's command as `""`; its adds are those that could be read, or — none could — one unnamed add
* (`{ dot: { actor: "", counter: 0 }, origin: "user", createdAt: "" }`: a dot no write makes, so no redemption, delete or
* reconciliation names it), so it is live — a row whose adds read as an empty list no longer exists and is not named.
* · Its identity could not be read from its fields nor from its text (or its behavior word could not be read): what it refuses is
* unknown, so it is not in `rules`, and it is never read as no row. It stands at its STRICTEST reading over the calls it may reach
* (`reach`, in its scope): such a call takes the answer a call takes while a partition cannot be read — no allow row clears it, a
* readable deny still refuses it, a readable ask row reaching it still asks (both questions ride the call), otherwise it is the store
* form's question — and every other row stands as read. `reach` is `{ tool }` when the row's tool reads as a tool name and only the
* gate judges rows like it (an ask row of any tool; a deny or unknown-behavior row of a tool whose rules speak for no path face):
* the calls a readable row of that tool would be read for. It is `every` otherwise — a deny or unknown-behavior row of a tool whose
* rules the path tables of the file, shell and search checks also read (those tables cannot hold a row nobody can read), or a row
* whose tool cannot be read — and while such a row stands, a path check that is no call refuses, as for a partition that could not
* be read.
* `behavior` is the row's own word (`"ask"` when its behavior word could not be read); `scope` is present when the row's scope reads
* as a durable scope or, a session partition's row, as its session's (absent: everywhere); `rule` is the row's ONE name: the text it
* stands under in `rules` for a row that stands as written (the spelling of its fields when the text is the member), the text as served
* otherwise (`(unreadable)` when the text is the member) — `removePersistedRule` retires only rows stored whole and answers `failed`
* (`committed: "no"`, telling the person to remove it in the store) when a displayed name matches a damaged restriction or standalone
* unretireable row; `member` the first member that could not be read; `reason` the word an allow row left out for the same fault takes
* (`invalid_rule_text` for its text, `metadata_mismatch` for another member). Absent when none. The reader tells the person
* (`config.entries_not_applied`, kind `stored_rule_row`). A date object where a time belongs is no such fault: it reads as its ISO text. */
unreadableRows?: ReadonlyArray<{
readonly reason: "invalid_rule_text" | "metadata_mismatch";
readonly rule: string;
readonly behavior: "deny" | "ask";
readonly member: string;
readonly reach: "as_read" | "every" | {
readonly tool: string;
};
readonly scope?: RuleScope;
}>;
}
/**
* The host-visible store, already anchored to one owner. One read verb, which never throws: each
* partition reports its own failure in the view — a PERSONAL partition's read failure (the durable one's, the
* session one's) as `unreadable` / `unreadableSources`, with that partition's rows absent and the other's present
* (served-but-non-canonical session rows stay a `disclosures` line), the ORG partition's as its `status`. The unit
* that fails is the partition: the org verdict stands while a personal partition is down, each personal partition's
* rows stand while the other is down, and the personal rows stand while an org source is down.
*/
export interface PermissionRuleStore {
effective(query?: {
sessionId?: string;
}): Promise<EffectivePermissionRules>;
/** design/182 §5.2 — the durable partition's quarantine area, for introspection. */
quarantined?(): Promise<QuarantinedRuleAdd[]>;
/** The durable partition's declared durability; an undeclared backend reads fail-closed as `"process-local"`. */
readonly durability?: StoreDurability;
readonly fidelity?: StoreFidelity;
}
/**
* The unified provider — the ONE `RunnerDeps.permissionRuleStore` seam. `partitions` is the declaration
* face: the wiring manifest's cells and the ask evidence's `not_wired` words read it verbatim instead of
* inferring from three separate seams.
*/
export interface PermissionRuleStoreProvider {
/** The store for one verified principal. `undefined` (or the empty string, the same absence) ⇒ zero personal rules — but the org
* partition still adjudicates: governance applies to everyone, an anonymous task included. A value that is not a principal name
* is refused (thrown) before the durable backend is asked. */
forPrincipal(principal: string | undefined): PermissionRuleStore;
/** design/182 §4.5 — the identity-less local bucket. Present iff the durable backend has one. */
forLocalOwner?(): PermissionRuleStore;
readonly partitions: Readonly<{
durable: boolean;
org: boolean;
session: boolean;
}>;
/** The deployment's mounted-peers seat as configured ({@link PermissionRuleStoreConfig.a2aPeers}): the one source of the identity
* stamp every grant the engine writes for an inside A2A peer carries — the run's card and the consent protocol's record read it.
* Absent ⇒ the engine writes no stamp. */
readonly a2aPeers?: MountedPeersSeat;
/** Take one of `owner`'s rows of session `sessionId` back — the session partition's `revoke`, handed that owner's key of the session
* ({@link sessionRowKeyOf}), then that key read back from the session partition alone — only after an answer that is one of the
* partition's two arms: `stillLive` is whether the target still stands there (`unknown` when the read-back could not be taken or
* was not made, or a row whose identity could not be read stands there, which may be it). The one take-back entry: present (an
* own enumerable member) exactly when the configured session partition has that verb; it touches no durable partition.
* `removePersistedRule` with a session scope is the one caller a host needs; the session call grant is offered only where it is
* present (a grant whose promise is that it can be taken back). An owner that names no bucket, or an unusable session id, is
* refused (`config.invalid_argument`). */
revokeSessionRule?(owner: RuleOwner, sessionId: string, target: SessionRuleTarget): Promise<SessionRuleRevokeResult & {
readonly stillLive: RemovalLiveness;
}>;
}
/**
* The store one task reads its person's rules from. The unauthenticated floor is enforced HERE, not merely asked of the
* provider: an absent principal resolves to zero personal rules, and a provider that forgot it would hand one person's
* standing approvals to an anonymous task. The ONE exception is an explicitly declared LOCAL-OWNER deployment, where "no
* principal" is the typed absence of identity — the machine owner's own bucket (a provider with no such face resolves
* the anonymous store; {@link createPermissionRuleLanes} refuses that declaration loudly). "No principal" is ABSENCE only —
* `undefined`, and the empty string the engine has always spelled the same ({@link readPrincipal}). A principal that was provided
* and is not a name (white space, an invisible or control character) is a bad value and is refused here: read as absence it
* would be the machine owner's bucket on a local-owner deployment.
*/
export declare function ownerStoreOf(provider: PermissionRuleStoreProvider, principal: string | undefined, localOwnerDeclared: boolean): PermissionRuleStore;
/** What {@link createPermissionRuleStoreProvider} composes. */
export interface PermissionRuleStoreConfig {
/** The durable CRDT partition (user + project sources). Absent ⇒ no personal rules exist on this
* deployment (the rule lane does not arm), and no session grant can land either (the redemption
* dot is minted by the durable replica). */
durable?: DurableRulePartitionProvider;
/** The org partition. Its PRESENCE is the governance declaration (design/182 §7.4 D3): under it the
* org adjudication surface must always be effective, and an unreadable snapshot fails the whole
* decision boundary closed. */
org?: OrgRulePartitionConfig;
/** The session partition. Absent ⇒ the session source does not exist: a session-scope redemption is
* refused loudly (nowhere to land), and `effective()` carries no session rows. Present, it must declare
* `addressedBy: "session-row-key"` (its verbs are handed the engine's key of an owner's rows in a session,
* never a bare session id); a partition that does not is refused (`config.invalid_argument`). */
session?: SessionRulePartition;
/**
* The A2A peers as the deployment registers them NOW (the declarations it hands its runs, `A2aServerSpec[]`), read each time the
* engine writes a grant for an inside peer or says a listed row's binding. Its presence is the switch: present, an inside peer's card
* offers "do not ask me again about this peer" (`a2a__<peer>`, bound to the stamp the peer's registration carries — its `fingerprint`,
* as written), the consent record carries that stamp and the redemption writes it onto the rule's add; absent, the engine writes no
* stamp anywhere (an inside peer's card offers no such option). A peer the seat does not register inside gets no stamp.
*/
a2aPeers?: MountedPeersSeat;
}
/**
* Compose the unified store over its partition backends. This is the boot gate of the org declaration
* (`createOrgRulePartition` refuses a config naming no source) and the ONLY constructor of the store.
*/
export declare function createPermissionRuleStoreProvider(cfg: PermissionRuleStoreConfig): PermissionRuleStoreProvider;
/**
* The one read query for a consumer that NEEDS the durable rows (a write's optimistic-concurrency anchor,
* a coverage judgment, a removal): an `unreadable` durable partition is a thrown read failure here, so
* the caller's existing "could not read the permission-rule store" arm fires — the gate lane is the one
* consumer that reads the word itself.
*/
export declare function effectiveOrThrow(store: PermissionRuleStore, query?: {
sessionId?: string;
}): Promise<EffectivePermissionRules>;
/**
* The one read query, addressed by owner (design/182 §7.3 introspection, design/389 form): resolve the
* owner's store and ask it. Nothing is assembled here — a consumer that needs the effective view with
* `source`/`status` per row and the org resolution beside it gets the store's own answer.
*/
export declare function effectivePermissionRules(opts: {
provider: PermissionRuleStoreProvider;
principal?: string;
owner?: RuleOwner;
sessionId?: string;
}): Promise<EffectivePermissionRules>;
/** Owner routing shared by the introspection entry: either a principal or the local owner, never both. */
export declare function resolveOwnerStore(opts: {
provider: PermissionRuleStoreProvider;
principal?: string;
owner?: RuleOwner;
}): PermissionRuleStore;