UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

204 lines (203 loc) • 16.6 kB
/** * PrepareTask's file-history phase, verbatim from the driver: the DV-14 first-touch * policy door, the `RunnerDeps.fileHistoryStore` / `fileHistoryCapture` and `TaskSpec.fileHistory` bad-value doors, the restoreFiles / resumeAt / rewindFilesTo combination gates, the run's history coordinates * (canonical root, recording scope, filesystem identity), the fork carry, the child-scope refusal, the * rewind RESTORE itself (anchor translation in "before" mode, the per-file ledger, partial-restore * policy), the `trackFileEdit` hook the hands band calls before every mutation lane, and the turn-start * boundary seat runtask drives. * * Runs INSIDE the driver's prepare try-block, after the session's checkout is read (`sessionRoot`) and the * env is resolved: every refusal here throws through to the driver's prepare-throw catch (a minted * ownedEnv is destroyed there, a resumeAt branch written back, the session view forgotten). The phase acquires * no resource of its own — the two seats it returns are closures over the store the deployment owns. * * The request door (the bad-value doors and every refusal the request decides alone) lives in * `./file-history-request.ts` and runs BEFORE the session is acquired; this phase receives its resolution. * The module-level helpers below the phase (`adoptForkedFileHistory` with its per-store carry memo, * `createFileHistoryBoundarySeat`, `resolveFileHistoryCoordinates` / `resolveFileHistoryScope` / * `fileHistoryFilesystemIdentity`, `childScopeRewindRefusal`) moved with it unchanged; the two the test * suite reaches through the driver are re-exported from there. The restore itself and the reading of its * answer live in `./file-history-restore.ts`, shared with the out-of-run rewind (`./rewind-files.ts`), which * also reaches down here for the coordinates and the fork carry — a rewind outside a run is the same history * operation as the one this phase runs. */ import type { ExecutionEnv } from "../../internal/harness.js"; import type { RunnerDeps, TaskResult, TaskSpec, TrackFileEditHook } from "../types.js"; import type { FileHistoryStore } from "../file-history-store.js"; import type { FileHistoryBoundarySeat, RunInternals } from "./contracts.js"; import type { FileHistoryRequest } from "./file-history-request.js"; import { type OwnLogReader } from "./file-history-restore.js"; import { tellLeftAsIs } from "./left-as-is-seat.js"; import type { RewindOutcome } from "./rewind-outcome.js"; import type { SessionRootRead } from "../session-checkout.js"; /** * Whether a leg can change a file through a tool it mounts — read off its valve before its roster is assembled: an engine tool whose * catalog effect is a write (the file tools, the shell, a delegation or a workflow that runs other legs — the catalog's one statement, * an undeclared effect read as a write), any caller tool, or a protocol peer (MCP, A2A) the valve leaves. A leg that answers no has * nothing its file history could record, so where its session's checkout cannot be resolved it runs and records nothing (the * session checkout's `writes`) rather than being refused for a history it would never write. */ export declare function legMayWriteFiles(input: { leaves: (tool: { name: string; }) => boolean; leavesPeer: (prefix: string) => boolean; callerTools: readonly { name: string; }[] | undefined; mcp: readonly { name: string; }[] | undefined; a2a: readonly { name: string; }[] | undefined; }): boolean; export interface PrepareFileHistoryInput { /** borrowed-readonly — the deployment seats this phase reads: the first-touch failure policy, the history * store and its capture switch (all validated HERE, once), the incident sink, the notice seat (the person's half of a * boundary that was not recorded), and the retired-epoch diagnostic probe. */ deps: Pick<RunnerDeps, "onError" | "onNotice">; /** borrowed-readonly — the REBOUND spec's rewind request fields and off-switch word and the caller's cancel signal for the restore. */ spec: Pick<TaskSpec, "resumeAt" | "restoreFiles" | "acceptPartialRestore" | "signal">; /** borrowed-readonly — the request door's resolution ({@link resolveFileHistoryRequest}), judged before the session was * acquired: every refusal the request and the deployment's seats decide on their own has already thrown. */ request: FileHistoryRequest; /** borrowed-readonly — the trusted lineage a delegating parent handed this run and the caller's root (both absent for a root run * and for a host's own fork), read for the recording-scope decision only; and the Runner's session * read-state seats, whose restore channel the restore writes the paths it moved into. */ internals: Pick<RunInternals, "fileHistoryLineage" | "callerRoot" | "sessionReadStates"> | undefined; /** borrowed-readonly — the run's resolved env (owned or static or the stub); every history verb runs * against ITS filesystem ops. Never rebound or destroyed here. */ executionEnv: ExecutionEnv; /** borrowed-readonly — the SESSION's root, where its history is keyed (`OpenedSessionCheckout.sessionRoot`; a `null` leg's reads the session's tree); read only when the leg records or restores. */ sessionRoot: () => Promise<SessionRootRead>; /** borrowed-readonly — where a fork's source keyed its history (`recordedRootOf` over this session's copy of it); read by the fork carry only. */ forkSourceRoot: (origin: string) => Promise<string | undefined>; /** borrowed-readonly — the "real fs env" fact (`ownedEnv !== undefined || deps.executionEnv !== undefined`). */ handsEnabled: boolean; /** borrowed-readonly — the acquired session id: the session key of the restore, the read-state channel and every sentence. */ sessionId: string; /** borrowed-readonly — the acquired session, read for the log's own entries (`getEntry`, the rewind target's membership); never written here. */ session: OwnLogReader; /** borrowed-readonly — whether this session is a fork that works in a tree of its own (`forkHasOwnTree`, judged once by the driver * over the row it read): such a run records no file history and restores none ({@link announceForkCheckoutUnrecorded}). */ forkWithOwnTree: boolean; /** borrowed-readonly — the acquired session's row as the driver read it once: its occupant (the run's OWN history scope is * `fileHistoryScopeOf(sessionId, own)`) and its fork lineage. Absent for a run with no store (it names no scope, so the driver made no read for it); a read that threw leaves the run with no history scope of its own. */ row?: LegRowRead; /** borrowed-readonly — the run's abort controller (driver-minted); only its `signal` is read, composed * with `spec.signal` for the restore. */ abortController: AbortController; /** borrowed-readonly — the session's once-per-session record, for the restore's telling of the files it left as they are. */ onceLedger: Parameters<typeof tellLeftAsIs>[0]["onceLedger"]; /** borrowed-mutable — the leg's record of what its rewind did ({@link RewindOutcome}; absent on a leg that asks for none): the restore * writes whether the tree moved, and this phase the restore it accepted. */ rewindOutcome?: RewindOutcome; } /** The acquired session's row cells, read once (`getMetadata`): its own occupant (`own`), its fork lineage (`origin`, and the occupant * of it the fork was cut from, `originIncarnation`), or `fault` when the read threw. */ export interface LegRowRead { origin?: string; originIncarnation?: string; own?: string; fault: boolean; } export interface PrepareFileHistoryResult { /** borrowed-readonly — the hook the hands band calls before every mutation lane; `undefined` when the * run does not record (no store, capture turned off by any layer, or no real fs env). */ trackFileEdit: TrackFileEditHook | undefined; /** borrowed-readonly — the turn-start boundary seat runtask drives; `undefined` when not live or when * this run records into its ROOT session's scope (a child mints no boundaries). */ fileHistoryBoundary: FileHistoryBoundarySeat | undefined; /** borrowed-mutable — the non-fatal rewind disclosures (`TaskResult.rewindNotes`). Mutation owners after * this call: none — every push happens inside this phase; the driver only reads it into `Prepared`. */ rewindNotes: NonNullable<TaskResult["rewindNotes"]>; /** borrowed-readonly — whether this run RECORDS file history (store wired, no layer turned capture off, AND hands); restore reads the store seat. */ fileHistoryEnabled: boolean; /** borrowed-readonly — the manifest's word: `"on"` iff live, else `"disabled"` (whichever layer or missing half). */ fileHistoryFact: "on" | "disabled"; /** borrowed-readonly — the scope this run's first-touch records land in (own session's, or the root * session's for a same-tree delegated child); `undefined` when the run has none (no store, its row read threw, or the address was refused). */ historyScope: string | undefined; /** borrowed-readonly — the canonical history root every history verb keys against. */ historyRoot: string; /** borrowed-readonly — the filesystem identity of the env (the lineage's second tree coordinate). */ historyFs: string; } export declare function prepareFileHistory(input: PrepareFileHistoryInput): Promise<PrepareFileHistoryResult>; /** * The fourth liveness word: a fork that works in a tree of its own records no file history (`forkHasOwnTree`), said to the operator * through the driver's once-per-session ledger (`onceOnError`) — unless a layer declared capture off, a decision the other words keep * silent about too. Advisory: a throwing sink does not fail the run. */ export declare function announceForkCheckoutUnrecorded(onceOnError: NonNullable<RunnerDeps["onError"]>, request: Pick<FileHistoryRequest, "captureOff" | "declaredOff">, sessionId: string): void; /** * Carry a forked session's file history from its source's history address into the fork's own scope (the seat §5 names). The source * address is the fork row's lineage cell read whole — `fileHistoryScopeOf(forkedFrom, forkedFromIncarnation)`, the occupant the fork was * cut from — so no row of the source is read and an id that changed hands since is never consulted: the address names the occupant, not * whoever holds the id now. A fork row that names no occupant of its source (`forkedFromIncarnation` not a token) has no source address — * half an address is no address, the same reading as a run whose own occupant cannot be read — and carries nothing, said once; so does a * source whose id {@link fileHistoryScopeOf} refuses an address. * The source's records carry no root — they are joined back on the fork's: they are carried only when the source keyed them against the fork's * own root (`roots`, both canonical; either unknown is not the same root), and otherwise nothing is carried, said once. * Never throws and never fails the turn: a store that cannot carry, or a fork with no source to carry from, leaves the fork with an empty * history, which is DEGRADED (a pre-fork boundary is not restorable from the new session) and not * wrong (nothing is silently mis-restored — the restore seat answers "no boundary" honestly). */ export declare function adoptForkedFileHistory(store: FileHistoryStore, lineage: Pick<LegRowRead, "origin" | "originIncarnation">, sessionId: string, ownScope: string, onError: RunnerDeps["onError"], roots: { own: () => Promise<string | undefined>; source: (origin: string) => Promise<string | undefined>; }): Promise<void>; /** A rewind on a session whose row could not be read: with no occupant there is no history address to restore from (the run's restore * seat and the out-of-run `Runner.rewindFiles` both refuse with it). The one mint, nothing planned: `transient` — the session store did * not answer, and the same rewind can succeed once it does. */ export declare function unaddressedRewindRefusal(sessionId: string, target: string): Error & { code?: string; }; /** * The run's two file-history COORDINATES, resolved once where store/env/root meet (module-level per * the body ratchet): * - `historyRoot` — ONE canonical root coordinate for every history verb: capture keys (rel-under-root * vs absolute, DV-6) must agree with the canonical containment keys the hands band mints — a * symlinked root spelling (macOS /var → /private/var) would otherwise record in-root files as * absolute and un-tether them from the root they live in. * - `historyScope` — WHICH scope this run's first-touch records land in. A top-level run owns its own * (`ownScope`: its row's address, `fileHistoryScopeOf`; none when the row read threw or the function refused). A delegated child that was handed a {@link RunInternals.fileHistoryLineage} and * runs on the SAME canonical root records into the lineage's scope — the root session's — so the * edits a child makes on the user's behalf are part of the ONE history the user rewinds from * (before this, a child's first touch minted its baseline in a scope no rewind ever read, and the * parent's own later first touch of that file recorded the child-modified bytes as pristine). A * child on a DIFFERENT root keeps its own scope: keys are root-relative and carry no root, so a * record minted under a worktree re-joined against the root session's tree would converge a file * that run never edited — the structural out-of-scope guarantee the store contract opens with. * Same-tree equality is judged on TWO coordinates, both minted here: the CANONICAL root spelling * both sides minted their keys against, and the FILESYSTEM the env is a view of * ({@link fileHistoryFilesystemIdentity}) — a path string alone is not a tree (two per-task * sandboxes can both spell `/workspace` and hold unrelated files). * The root is the SESSION's (`sessionRootOf`), never the leg's own, so every rewind joins each record back where it was made; a child that * stands at its caller's root (`callerRoot`, on the lineage's filesystem) works where its caller works and keys against the caller's * history root — the lineage's, which for a caller on a `null` leg is that caller's session root, not where it stands. With no * session root given (the run neither records nor restores) nothing is coordinated: own scope, no root, no filesystem identity. */ export declare function resolveFileHistoryCoordinates<S extends string | undefined>(env: ExecutionEnv, sessionRoot: string | undefined, lineage: RunInternals["fileHistoryLineage"], ownScope: S, callerRoot?: string): Promise<{ historyRoot: string; historyScope: string | S; historyFs: string; }>; /** The ONE reading of {@link RunInternals.fileHistoryLineage} (see {@link resolveFileHistoryCoordinates}): * the lineage's scope iff BOTH tree coordinates match; otherwise the run's own scope. */ export declare function resolveFileHistoryScope<S extends string | undefined>(lineage: RunInternals["fileHistoryLineage"], historyRoot: string, historyFs: string, ownScope: S): string | S; /** * WHICH filesystem an env is a view of — the second coordinate of tree identity for the file-history * lineage, read from what the env's MINTER states rather than inferred from a path: * · an env that DECLARES its paths host-local (`pathsAreHostLocal` — `NodeExecutionEnv`, a host lane) is the * control-plane host's filesystem — every such env is one tree, whatever interface it drives it through; * · otherwise a remote workspace names itself through its {@link WorkspaceHandle} (provider + sandbox, and * the device lane's id when stamped) — two runs on one sandbox share a tree, two sandboxes never do; * · anything else — an env declaring `hostLocalPaths: false` with no handle, or one whose declaration is * missing or malformed (read as not host-local) — is attested to nothing, so it is its OWN tree: a * per-instance token, which still matches when the child literally holds the parent's env object and * never matches a fresh per-task mint. * A remote handle that cannot be read (an env not yet connected) falls to the per-instance arm for * the same reason: unattested is not shared. */ export declare function fileHistoryFilesystemIdentity(env: ExecutionEnv): string;