@sema-agent/core
Version:
Stateless, task-oriented AI agent core
264 lines (263 loc) • 18.1 kB
TypeScript
import type { ExecutionEnv } from "../../internal/harness-types.js";
import { PROJECT_ID_REGEX, type ProjectSeat } from "../project-seat.js";
/** Per-segment cap, measured AFTER encoding. A conservative portability policy adopted as contract
* (research (d) recommendation — NOT a verified third-party hard limit; uuidv7 = 36 chars fits). */
export declare const SCOPE_SEGMENT_MAX_ENCODED = 64;
/**
* Canonical injective encoding for a raw identifier entering a scope key: everything outside
* `[A-Za-z0-9._-]` becomes `%XX` (UTF-8 bytes), INCLUDING `%` itself (that self-encoding is what
* makes the map injective — no `__`-style collidable escapes). Throws when the encoded segment
* exceeds {@link SCOPE_SEGMENT_MAX_ENCODED} (an over-long principal is a deployment config error)
* or when the raw value is empty.
*/
export declare function encodeScopeSegment(raw: string): string;
/**
* Inverse of {@link encodeScopeSegment}, CANONICAL-FORM ONLY: the input must be
* exactly what the encoder produces — safe chars stay bare (so `%41` for `A` is refused: two
* spellings of one identity must not mint two keys), `%XX` sequences must decode as valid UTF-8
* (fatal decoder — no U+FFFD smoothing), and the 64-char cap holds here too (parse side enforces
* what the format side promised). Every refusal carries `config.memory_scope_key`.
*/
export declare function decodeScopeSegment(encoded: string): string;
export type ParsedScopeKey = {
kind: "user";
principal: string;
}
/** A principal's layer that never leaves the store it is written in: personal plane, never replicated
* ({@link isReplicableScope}). */
| {
kind: "userlocal";
principal: string;
} | {
kind: "org";
tenant: string;
} | {
kind: "proj";
tenant: string;
projectId: string;
} | {
kind: "userproj";
principal: string;
projectId: string;
}
/** No recognized v2 prefix: an opaque legacy scope (fully valid under the v2 contract too). */
| {
kind: "legacy";
raw: string;
};
export declare function formatUserScope(principal: string): string;
export declare function formatUserLocalScope(principal: string): string;
export declare function formatOrgScope(tenant: string): string;
export declare function formatProjScope(tenant: string, projectId: string): string;
export declare function formatUserProjScope(principal: string, projectId: string): string;
/**
* Parse a scope key under the v2 contract. A key carrying a recognized prefix MUST be well-formed
* (fail-loud — a malformed `proj:` key under an explicit opt-in is a config error, not an opaque
* scope), and so must a key that spells one of the five without carrying it exactly — another case,
* a full-width colon, surrounding whitespace: the prefixes are reserved, so such a spelling is neither
* read as the kind it imitates nor left to pass as an opaque scope (`config.memory_scope_key`).
* Anything else parses as `{ kind: "legacy" }` and keeps today's opaque behavior. NEVER call this on a
* deployment that has not opted in (see module header).
*/
export declare function parseScopeKey(key: string): ParsedScopeKey;
/**
* THE org-scope judge for a host that admits, stores or routes org keys: is `key` a well-formed v2 org
* scope — `org:` followed by ONE encoded segment ({@link encodeScopeSegment}'s alphabet, at most
* {@link SCOPE_SEGMENT_MAX_ENCODED} encoded characters, canonical spelling)? It is {@link parseScopeKey}'s own
* reading, asked as a yes/no: a malformed `org:` key (an unencoded non-ASCII character, an over-long
* segment, a non-canonical escape) answers `false` here where `parseScopeKey` would throw, and a key of any
* other kind (`user:`, `proj:`, an unprefixed opaque string) answers `false` too. A prefix-plus-any-non-space
* pattern restated outside core answers a different question and disagrees on exactly those inputs.
*/
export declare function isOrgScopeKey(key: string): boolean;
/** True when a v2-parsed key is a principal's own layer (`user:` / `userlocal:` / `userproj:`). */
export declare function isPersonalScope(parsed: ParsedScopeKey): boolean;
/** True when the key's layer lives on the PERSONAL plane (the home mount, design/142 §2 表: the
* user/userproj/org rows, and `userlocal:`) — these keys must never project into an in-repo memory dir (they
* would leak to every collaborator AND enter commit history; extended the F9 gate from personal to org).
* `proj:`/legacy stay repo-planed. The plane says where a layer may NOT be projected, not where its
* authority is: `org:` is owned by the center, `userlocal:` by the store it is written in
* ({@link isReplicableScope}).
*
* @contract memory.identity_absence.opaque_key — the memory of an owner with no identity is keyed by an opaque,
* unprefixed key the deployment chooses (such as `local`) and never by a sentinel principal: no `user:` key stands for
* identity absence (a `user:local` key is the key of a principal named `local`), so this function answers `false`
* for that layer — it stays on the project plane. The engine mints no key for identity absence. Read as an
* owner, it is the `local-owner` arm of `RuleOwner` (core/rule-owner.ts), not a principal. A principal's memory is
* keyed by that principal's keys (`user:<P>` and the principal's project layers); moving this layer to a principal
* is a re-keying of its entries (`migrateScope`), and the engine never reads the opaque name as a principal.
* Admission authorizes by the caller's principal (`MemoryScopeAdmissionInput`), never by a layer's owner. */
export declare function isPersonalPlaneScope(parsed: ParsedScopeKey): boolean;
/** Who owns a memory layer, for a question asked of its owner rather than of whoever acts on it: a principal (its own
* layers), a tenant (the organization's layers), or the deployment itself (an opaque key). */
export type MemoryScopeOwner = {
kind: "principal";
principal: string;
} | {
kind: "tenant";
tenant: string;
} | {
kind: "deployment";
};
/**
* THE owner reading of a scope key: `user:` / `userlocal:` / `userproj:` are a principal's own layers, `org:` / `proj:` a
* tenant's, and an opaque key the deployment's — every key of a session without the v2 contract (where `user:42` is an
* opaque spelling, never principal `42`), and an unprefixed key under it. Under v2 a malformed reserved key throws
* `config.memory_scope_key`, as {@link parseScopeKey} does. A kind the switch does not handle is a compile error.
*/
export declare function memoryScopeOwnerOf(scope: string, scopeContract: "v2" | undefined): MemoryScopeOwner;
/**
* THE replication judge: may a sync carry `key`'s entries to another store? Every key may, except the
* `userlocal:` family — read as the parser reads a key's reserved prefix ({@link reservedPrefixOf}: exactly, else
* folded — another case, a full-width colon, compatibility letters, surrounding whitespace), well-formed or not,
* and under any scope contract: the prefix is reserved, so a deployment that never opted in to v2 is
* answered by the spelling too (the safe direction for a layer its owner keeps off every other store). A key
* the parser refuses as a `userlocal:` spelling is therefore never replicable: one reading, two askers.
* `syncMemoryScope` refuses such a scope before any read or request (`config.memory_scope_key`), and
* `memoryTravelGapOf` reports it `local_only`. A value that is not a string is not a key and throws.
*/
export declare function isReplicableScope(key: string): boolean;
/**
* design/142 §7 S1 hard gate (复审 F9): until S1b per-scope physical roots land, ALL scopes of a
* session materialize under ONE root — so a v2 session mixing personal-plane keys ({@link isPersonalPlaneScope}) with an
* IN-REPO memory dir would project personal memory into the repo (the exact §2.7 leak shape:
* personal notes committed to a shared/open repo). Fail-loud, never fail-open: this throws a
* `config.`-coded error the prepare path must NOT swallow.
*/
export declare function assertScopeContractPlacement(args: {
parsedScopes: readonly ParsedScopeKey[];
memoryDir: string;
/** The repo/workspace root the session works in (undefined = no repo context, gate passes). */
repoRoot: string | undefined;
}): void;
/** Repo-root marker file: minted once (by scaffold/deployment, NEVER by the engine), committed, and
* from then on the project's identity survives clone/copy/rename/machine/cloud-sandbox. */
export declare const PROJECT_MARKER_PATH = ".sema/project";
/** The project id's one format (defined beside the project seat, `../project-seat.ts`). */
export { PROJECT_ID_REGEX };
/** Canonicalize a project UUID for equality comparisons across markers, declarations, and v2 write keys. */
export declare function normalizeProjectId(projectId: string): string;
/** Serialize a marker file body (scaffold-side helper; the engine itself never writes one). */
export declare function formatProjectMarker(projectId: string): string;
/** Closed discriminant words carried on project-identity and v2 memory project-write refusal details (`terminal.detail = { kind: "coded", detail }`). */
export declare const PROJECT_IDENTITY_REFUSAL_KINDS: readonly ["mismatch", "marker_unreadable", "write_project_mismatch", "write_without_verdict"];
export type ProjectIdentityRefusalKind = (typeof PROJECT_IDENTITY_REFUSAL_KINDS)[number];
/** Closed reason words carried on `{ kind: "marker_unreadable" }` refusal details (no file content, no error prose, no out-of-workspace path). */
export declare const PROJECT_MARKER_UNREADABLE_REASONS: readonly ["io_error", "unparseable", "not_uuid", "nested", "repo_root_unreadable"];
export type ProjectMarkerUnreadableReason = (typeof PROJECT_MARKER_UNREADABLE_REASONS)[number];
/** Parse a marker body: TOML-subset `key = value` lines, `#` comments and blank lines ignored,
* optional quotes around the value. Unknown keys are ignored (forward-compatible).
* ANY line that starts a `projectId` assignment but is not one canonical UUID assignment is a
* CORRUPT marker (fail-loud, `config.memory_project_marker`) — an empty value, an unclosed quote,
* a non-UUID, or a DUPLICATE projectId line must never degrade to "no marker" (that would be a
* silent identity change back to the path key). Returns null only when NO projectId line exists. */
export declare function parseProjectMarker(body: string): {
projectId: string;
} | null;
/** What the marker walk reads through: the filesystem the task root names — the leg's execution env (any `ExecutionEnv`
* satisfies it), or the host's ({@link hostProjectMarkerFs}) for a leg that has none. */
export type ProjectMarkerFs = Pick<ExecutionEnv, "exists" | "readTextFile">;
/** The host filesystem as a {@link ProjectMarkerFs} — what a leg whose env does no I/O reads its task root through (its
* root is a host path: the deployment's `rootPath`). `exists` answers `false` only for a path that is not there; any
* other failure is an error, never an absence. Read synchronously, as the memory phase always read the marker: a leg
* with no I/O of its own gains no event-loop turn from its project read (its scheduling against sibling legs stays). */
export declare const hostProjectMarkerFs: ProjectMarkerFs;
/** The filesystem a leg's task root names: its execution env — its read limits included — or the host's only when the env
* declares it is the no-I/O placeholder (`performsIo` is `false`: a leg with no env, or one handed none). An undeclared env
* is read through, never past. */
export declare function projectMarkerFsOf(env: ExecutionEnv): ProjectMarkerFs;
/** Machine-readable detail carried on project-identity and v2 memory project-write refusals
* (`terminal.detail = { kind: "coded", detail }`), unified on the closed `kind` discriminant
* ({@link PROJECT_IDENTITY_REFUSAL_KINDS}). */
export type ProjectIdentityRefusalDetail = {
readonly kind: "mismatch";
readonly declared: string;
readonly marker: string;
readonly markerPath: string;
} | {
readonly kind: "marker_unreadable";
/** The marker's path when it sits at the task root itself (`<task root>/.sema/project`); absent for one at a directory above it
* (the repository root above a task root, a nested level between them) — a path outside the workspace is not carried. */
readonly markerPath?: string;
readonly reason: Exclude<ProjectMarkerUnreadableReason, "repo_root_unreadable">;
} | {
readonly kind: "marker_unreadable";
readonly reason: "repo_root_unreadable";
} | {
readonly kind: "write_project_mismatch";
readonly writeScope: string;
readonly writeProjectId: string;
readonly verdictProjectId: string;
readonly verdictSource: "marker" | "declared";
} | {
readonly kind: "write_without_verdict";
readonly writeScope: string;
readonly writeProjectId: string;
};
/**
* design/142 §1.1 — resolve a project's identity. READS ONLY THE MARKER (复审 F2: never derives an
* identity from a git remote; remote-URL normalization is a scaffold-side minting heuristic, not an
* identity source). v1 scope (复审 F10): ONE marker at the project root —
* - inside a git repo, the root is the REPO root; a marker at a nested directory that is not the
* repo root is fail-loud (`config.memory_project_marker_nested`) — monorepo sub-project identity
* is a future need-signal, not a silent second identity;
* - outside git, the given rootDir IS the project root (path-form local projects).
* Read through `fs` — the filesystem `rootDir` names (a remote env's marker lives in that env). A lookup
* the filesystem could not answer, or a marker it could not read, is `config.memory_project_marker` (never "no marker").
* Returns null when no marker exists. The leg's verdict over this read is {@link resolveSessionProject}.
*/
export declare function resolveProjectId(fs: ProjectMarkerFs, rootDir: string): Promise<{
projectId: string;
markerDir: string;
} | null>;
/** A leg's project identity. `marker` = the checkout's `.sema/project` (a declaration, when present,
* equals it); `declared` = `TaskSpec.project.id` (or the seat its parent handed it) in a checkout that carries no marker. */
export interface SessionProject {
readonly id: string;
readonly source: "marker" | "declared";
}
/** The ONE verdict every reader of a leg's project identity reads (the `workspace_changed` frame, memory v2). */
export interface SessionProjectVerdict {
/** The root the verdict was decided on (the leg's task root): a reader keeping facts about ANOTHER root (memory's
* per-partition marker hint) reads the verdict as a fact about this root only. */
readonly root: string;
/** ABSENT = no marker and no declaration, or the marker could not be read ({@link markerFault} says why). */
readonly project?: SessionProject;
/** The leg's project SEAT: the verdict's id with the texts that belong to it ({@link resolveSessionProject} says which) — present
* iff {@link project} is. What the leg hands its children and what its project texts are read from. */
readonly seat?: ProjectSeat;
/** Why the marker could not be read (nested / corrupt / unreadable), on a leg that declared no project — reported by
* the caller, NOT thrown here: only a reader that consumes project identity refuses with it (memory v2 `proj:` /
* `userproj:` keys). A leg that DECLARED a project consumes it, so there the fault is thrown. */
readonly markerFault?: Error & {
code: string;
detail?: ProjectIdentityRefusalDetail;
};
}
/** Project the manifest-face unreadable-marker fact from a `SessionProjectVerdict.markerFault` (same mint as P-e detail, zero second read). */
export declare function projectMarkerUnreadableOf(fault: SessionProjectVerdict["markerFault"]): {
readonly reason: ProjectMarkerUnreadableReason;
readonly markerPath?: string;
} | undefined;
/**
* The leg's ONE project-identity judge, called once per leg on the task root, over seats already screened
* (`screenProjectSeat`, at the spec's read and at the internals' door). Precedence:
* 1. `declared` (`TaskSpec.project`): checked against any workspace marker (`config.project_identity_mismatch` on
* disagreement, the marker's own code on an unreadable marker).
* 2. The leg's own workspace marker (`.sema/project`): decides when present (`source: "marker"`), even over an
* `inherited` seat; an unreadable marker on a leg with no `declared` yields `{ root, markerFault }` (no project verdict —
* identical to a root leg).
* 3. `inherited` (the seat a delegated child's parent handed it, on the trusted internals): its id is used ONLY when both (1)
* and (2) yield none (`source: "declared"`), never compared against the child's marker.
* The texts belong to the id: the verdict's {@link SessionProjectVerdict.seat} is `declared` whole; else `inherited` whole when its
* id is the verdict's id (no marker, or a marker naming that id); else the verdict's id alone.
*/
export declare function resolveSessionProject(fs: ProjectMarkerFs, taskRoot: string, declared: ProjectSeat | undefined, inherited?: ProjectSeat): Promise<SessionProjectVerdict>;
/**
* Under `scopeContract: "v2"`, enforce project-identity consistency for a memory session against the leg's ONE
* verdict ({@link SessionProjectVerdict}): rethrow an unreadable-marker fault for sessions consuming project identity
* (`proj:` / `userproj:` scopes or writeScope), and refuse a project-scoped `writeScope` when the leg has no verdict
* (`write_without_verdict`) or targets a different project (`write_project_mismatch`, case-insensitive via
* {@link normalizeProjectId}). Called before any on-disk adoption or hint write so a refused leg mutates nothing.
*/
export declare function assertMemoryProjectVerdict(sessionProject: SessionProjectVerdict, scopes: readonly string[], writeScope: string | null): void;