UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

1,958 lines • 156 kB
import { type PlatformPath } from "node:path";
import { type MemoryAnnouncement, type MemoryAttribution, type MemoryGovernanceDocName, type MemoryGovernanceDocs } from "./types.js";
import type { AssertAllKeysHandled } from "../ask-origin.js";
import { type EngineNotice } from "../engine-notice.js";
/** Cursor sidecar for the design/84 Seam B pair on the FileBackend (`{ [scope]: cursor }`). B3: control plane. */
export declare const CURSORS_FILE = "cursors.json";
/** The control-plane subdir name under a key dir — ONE spelling for every derivation and for the
 *  migration probes that move a control plane between key dirs. Exported for the sibling planes
 *  (dual-root's personal plane) so no second literal exists; not part of the package surface. */
export declare const CONTROL_PLANE_DIR = ".engine";
/** B3 fail-closed: a control-plane sidecar exists but cannot be trusted (unparseable / wrong shape).
 *  Read paths propagate it (materialize fails ⇒ the runner falls open to a memory-less session with
 *  onError); harvest converts it into a refused report (incident `sidecar_corrupt`). It is NEVER
 *  silently degraded to an empty ledger / unclaimed root — that would let a corrupted (or truncated)
 *  sidecar erase CAS baselines and re-open the root claim. */
export declare class ControlPlaneCorruptError extends Error {
    /** Structured discriminant for callers that fold ONE corruption family and rethrow the rest —
     *  branching on message text is banned (§B8). Only `"lock-ownership"` is minted today (the
     *  recoverable-as-incomplete family); absent = every other corruption (a definite state, throw). */
    readonly facet?: "lock-ownership";
    /** {@link ROOT_ANCHOR_DAMAGED} on the refusal of a store whose root anchor cannot be trusted ({@link rootAnchorRefusal}), with
     *  `detail` the two directories {@link reanchorMemoryStoreRoot} takes; absent on every other corruption. */
    readonly code?: typeof ROOT_ANCHOR_DAMAGED;
    readonly detail?: RootAnchorRefusalDetail;
    constructor(message: string, opts?: {
        cause?: unknown;
        facet?: "lock-ownership";
        rootAnchor?: RootAnchorRefusalDetail;
    });
}
/** The code a store is refused with when its control plane's root anchor cannot be trusted: absent while the control plane holds
 *  the store's account (a store last opened by an engine that recorded none, or an anchor removed by hand), or present and not a
 *  record (a link, not a regular file, not JSON, out of shape, an unknown version). Carried by a {@link ControlPlaneCorruptError}
 *  (the control plane's own damage class); the remedy is the one re-anchor. Not carried by an anchor the file system would not let
 *  the engine read (permissions, an I/O fault), nor by the refusal of a control plane that may have travelled with a moved engine
 *  root and whose own anchor cannot be read (its remedy is another). */
export declare const ROOT_ANCHOR_DAMAGED: "memory.root_anchor_damaged";
/** What a {@link ROOT_ANCHOR_DAMAGED} refusal carries beside its sentence: `path`, the store directory as its opener spelled it, and
 *  `controlDir`, its control plane — the two arguments of {@link reanchorMemoryStoreRoot} (`reanchorMemoryStoreRoot(path, { controlDir })`). */
export type RootAnchorRefusalDetail = {
    readonly path: string;
    readonly controlDir: string;
};
/** Whether `thrown` is a {@link ROOT_ANCHOR_DAMAGED} refusal, read off its `code` (a hostile accessor reads as absent): the reading
 *  the memory phase's person-facing notice classifies it by. */
export declare function isRootAnchorRefusal(thrown: unknown): boolean;
/**
 * CC-style repo PARTITION key: the repo root path, canonicalized, then slugged. Collisions across
 * repos require pathological sibling names and only merge their memory dirs (never corrupt them).
 *
 * RB-472 (design/161, four-repo receipts on record): the key CANONICALIZES first — without
 * realpath, the same repo reached through a symlink alias and through its physical path minted two
 * different partition keys = two memory dirs, silently splitting memory. `canonicalize` degrades to
 * plain resolve semantics for a not-yet-existing path (nearest existing ancestor + remainder).
 * Its input is the HOST-declared repo root; a model-reachable directory is keyed by
 * {@link deriveDirKey} instead, and that asymmetry is deliberate (see there).
 *
 * The case axis (once a known limit here) closes with the same call: the mint answers with the ON-DISK
 * spelling, so two case-variant spellings name ONE key on a case-INSENSITIVE volume, while on a
 * case-SENSITIVE volume they are two distinct directories and keep two (FOLDING would merge that pair).
 * Registered, not fixed: the PREVIOUS key was this realpath with the CALLER's casing = `deriveDirKey`'s
 * spelling, which the arm below adopts, EXCEPT under a case-varying symlink on a non-folding library.
 */
export declare function deriveRepoKey(repoRoot: string): string;
/** Sink for the mount-time partition-key incidents (`memory.partition_split` /
 *  `memory.partition_adopt_failed`). ONE shape for every host that can receive them — the runner's
 *  onError bridge, the engine, and the file backend. */
export type MemoryPartitionIncidentSink = (err: Error & {
    code?: string;
}) => void;
/** RB-472 adoption leg: a pre-5.x deployment keyed its repo partition by the resolve-only path, so
 *  when the two mints differ its `memory/` + `.engine/` + siblings live under {@link deriveDirKey}'s
 *  dir. Move the whole partition onto the canonical key (see {@link migrateKeyedPartition}). */
export declare function adoptLegacyRepoDirs(configRoot: string, repoRoot: string, onIncident?: MemoryPartitionIncidentSink): void;
/** Every spelling an earlier release keyed this repo's partition by, minus today's: the resolve-only key and the
 *  link-resolved, caller-cased key (`/var/TMP` keyed `-private-var-TMP`; today `-private-var-tmp`). */
export declare function earlierRepoKeysOf(repoRoot: string): string[];
/**
 * The REVERSE one-shot migration (ruled 2026-08-03): for the width of ONE release the control-plane
 * key canonicalized like the repo key does, which put a directory-pinned mount's `.engine` under the
 * canonical key. {@link deriveDirKey} is the control-plane mint again (that ruling's security half),
 * so such a control plane sits at an address this build no longer reads — move it back, once.
 *
 * Scoped to the `.engine` subtree on purpose: the canonical-key dir may host unrelated siblings.
 *
 * Known limit, registered rather than fixed: when the SAME physical directory is ALSO mounted under
 * its physical spelling, that mount's own resolve-keyed plane IS this migration's source dir, and the
 * probe cannot tell the two apart (both are `<key>/.engine`). Concurrently mounting one directory
 * under two spellings is outside what this probe can discriminate; the window it recovers from is one
 * release wide.
 */
export declare function adoptCanonicalKeyedControlDir(configRoot: string, dir: string, onIncident?: MemoryPartitionIncidentSink): void;
/**
 * `<configRoot>/<repoKey>/memory` — the repo-level stable mount (§2.7: taskRoot 外, worktree-shared).
 *
 * Worktree note (验收 L5, documented behavior): the KEY must be the BASE repo root. The runner passes
 * `deps.rootPath ?? taskRootPath` — when `rootPath` is configured, every derived worktree of that repo
 * shares ONE memory dir (a worktree moves the task cwd, never the memory mount); when `rootPath` is
 * NOT configured the taskRootPath fallback keys memory to the task's own checkout path, so an
 * isolated-worktree task without `rootPath` gets a worktree-private memory dir. That fallback is the
 * accepted degraded behavior (no silent cross-repo mixing; configure `rootPath` for worktree sharing).
 */
export declare function deriveRepoMemoryDir(configRoot: string, repoRoot: string): string;
/** design/142 §1.5 — the IDENTITY-keyed mount (v2 scope contract + a resolved project marker):
 *  `<configRoot>/proj-<projectId>/memory`. Unlike the path-derived {@link deriveRepoMemoryDir},
 *  this key survives rename/move/re-clone/container remounts — identity lives in the repo's marker,
 *  the mount stops referencing the path entirely. */
export declare function deriveProjectMemoryDir(configRoot: string, projectId: string): string;
/** Control-plane sibling of {@link deriveProjectMemoryDir} (B3: always on the config-root side). */
export declare function deriveProjectControlDir(configRoot: string, projectId: string): string;
/** design/142 §1.5 — the path→projectId HINT CACHE (`<configRoot>/project-id-hints.json`). NOT an
 *  identity source (the marker is the single truth source); purely the recovery breadcrumb for a
 *  deleted/lost marker: materialize can tell "this path used to carry marker X" and prompt a
 *  restore instead of silently minting a fresh identity. Best-effort on both faces (a corrupt hint
 *  file degrades to "no hints", never blocks a session). */
export declare const PROJECT_ID_HINTS_FILE = "project-id-hints.json";
export declare function recordProjectIdHint(configRoot: string, repoRoot: string, projectId: string): void;
export declare function lookupProjectIdHint(configRoot: string, repoRoot: string): string | undefined;
/** B3 — `<configRoot>/<dirKey>/.engine`: the engine CONTROL PLANE for a DIRECTORY-pinned mount (the
 *  memory dir itself is the key). ALWAYS on the config-root side — when the memory dir is configured
 *  in-repo, the control plane still lives here (model-invisible, not injected, not in-repo) — and
 *  keyed RESOLVE-ONLY, because the key input is a directory the model's file channel may be able to
 *  replace: see {@link deriveDirKey} for why canonicalizing it is a redirect handle.
 *  The repo-partition face has its own sibling mint, {@link deriveRepoControlPlaneDir}.
 *
 *  @contract memory.control_plane.key — the control plane of a directory-pinned memory store is `<config root>/<key>/.engine`, the
 *  key being the memory directory's absolute path, slugged: one formula for every build, so every build that opens a directory
 *  opens the same plane. An engine root moved by its operator carries its planes along, each still keyed by the path its directory
 *  had; the open of a directory under the root finds the plane that travelled with it and moves it onto the key its path has now
 *  ({@link adoptPlaneMovedWithRoot}), where its root anchor judges the open as for any moved store. None found ⇒ a new plane, said
 *  once when the directory already holds memory (`memory.control_plane_new_over_memory`) — unless the store is expected there (its
 *  opener declared it one that already exists, or this process saw it hold records as a zero-copy store), which refuses the open,
 *  writes no root anchor and records no store (`memory.store_absent`; the one-shot move of an earlier release's plane above still
 *  runs first); more than one ⇒ refused
 *  (`memory.control_plane_split`). */
export declare function deriveControlPlaneDir(configRoot: string, key: string): string;
/** B3 — the REPO-partition control plane: the sibling of {@link deriveRepoMemoryDir} under the SAME
 *  canonical repo key. Paired on purpose: {@link adoptLegacyRepoDirs} adopts the repo partition as ONE
 *  directory (`memory/` and `.engine/` inside it), so keying its control plane differently from its
 *  memory dir would strand one of the two on every alias-reached mount. Safe to canonicalize here —
 *  the key input is the host-declared repo root, not a directory the model can replace. */
export declare function deriveRepoControlPlaneDir(configRoot: string, repoRoot: string): string;
/** The directory a backend is pinned to — a File store's directory IS its storage (zero-copy) — or `undefined` for a backend
 *  without one (a DB store: sessions copy out of it into a projection). The one reading of that fact: an engine's zero-copy bit,
 *  the planes a deployment assembles and the store a sync reads all ask it. */
export declare function directoryPinOf(backend: unknown): string | undefined;
/** The control plane a backend publishes as its own (`controlPlaneRoot` — the file backend's), or `undefined` when it publishes
 *  none. The one reading of that fact: the plane an engine over the backend uses ({@link effectiveControlRootOf}), a deployment's
 *  admission and its capture carriers' key, and the store a deployment asks about ({@link refuseAbsentPinnedStore}). */
export declare function controlPlanePinOf(backend: unknown): string | undefined;
/**
 * THE control plane of the memory store at `dir` — the one reading every opener (the file backend, the
 * engine, the runner's plane assembly) and {@link reanchorMemoryStoreRoot} resolve through, so the plane a
 * store's root anchor is read from is the plane it was written to. A backend that pins its own control
 * plane (`pinnedBy.controlPlaneRoot` — the file backend) wins, else the explicit `controlDir`, else the
 * derivation off the config root ({@link deriveControlPlaneDir}) — preceded by the one-shot move of a plane
 * minted under the canonical key ({@link adoptCanonicalKeyedControlDir}), which is why that arm is not pure. Both the
 * explicit arm and the derived one look for the plane that travelled with a moved engine root ({@link adoptPlaneMovedWithRoot})
 * when the plane they answer IS the derivation for `dir` — the explicit `controlDir` recomputed from its own config root and
 * compared, never read from its name — so a host that pins the derivation it computed (a service's local file engine) is
 * served like the default.
 */
export declare function effectiveControlRootOf(dir: string, opts?: {
    controlDir?: string;
    pinnedBy?: unknown;
    onIncident?: MemoryPartitionIncidentSink;
}): string;
/**
 * Resolve the memory-engine config root: explicit (`RunnerDeps.memoryEngineDir`) → `AGENT_DATA_DIR` env → `~/.ai-agent`, in the
 * data root's one spelling ({@link dataRootSpelling}, NFC — the file stores' root reads the same), anchored at the process's
 * directory when relative — {@link resolveMemoryEngineRootFrom} over this process's facts. A value written decomposed whose own
 * directory holds data the NFC one does not (or both hold some) is said once per directory per process on the default seat
 * (`config.data_root_spelling_split`); the engine opens the NFC one and neither reads nor moves the other.
 */
export declare function resolveMemoryEngineRoot(explicit?: string): string;
/**
 * {@link resolveMemoryEngineRoot} as the engine opens it for a run: the split is said on the run's own notice seat (`onNotice`),
 * once per directory per seat; with no seat in hand, on the default seat once per directory per process.
 */
export declare function resolveRunMemoryEngineRoot(explicit: string | undefined, onNotice: ((notice: EngineNotice) => void) | undefined): string;
/**
 * The memory-engine config root from facts the caller hands in — for a host that computes where ANOTHER process's memory root is
 * (that process's `AGENT_DATA_DIR`, home and working directory): the explicit value, else `agentDataDir`, else `<home>/.ai-agent`,
 * in NFC; a relative one resolved at `cwd` (taken as given, never normalized; `..` folded, as {@link resolveMemoryEngineRoot} folds
 * it). It reads nothing of this process, touches no disk and says nothing; for this process's own facts it answers what
 * `resolveMemoryEngineRoot` answers. It answers the literal place: where a `..` cancels a name that is a link, the file stores' root
 * (which the kernel walks) can be another directory. The split of a decomposed spelling is not part of the answer — it needs the
 * disk: `dataRootSpellingSplitOf`.
 *
 * All three facts are given (`agentDataDir: undefined` writes out a process without one): a missing `agentDataDir` key, a `home`
 * that is not a string, a `cwd` that is not a non-empty absolute path (resolving a relative one would read this process's
 * directory), and on Windows a value whose resolution would still read the process ({@link memoryRootReadsProcess}: a drive-relative
 * `D:x`, or a relative value at a `cwd` with no drive) are refused `config.invalid_argument`.
 */
export declare function resolveMemoryEngineRootFrom(explicit: string | undefined, facts: {
    readonly agentDataDir: string | undefined;
    readonly home: string;
    readonly cwd: string;
}): string;
/**
 * Why resolving `written` at `cwd` under a path flavor would read this process, or `undefined`: on Windows a drive-relative value
 * (`D:x`, `D:`) is read against that drive's own directory, and a relative value at a `cwd` with no drive or share (`\w`) against the
 * process's current drive — both process facts the pure form does not read. On POSIX nothing does.
 */
export declare function memoryRootReadsProcess(written: string, cwd: string, api: PlatformPath): string | undefined;
/**
 * Filesystem-safe scope dir label. 评审 H5 (唯一映射): the cleaned slug alone is LOSSY
 * (`org:7` and `org/7` both fold to `org-7` — two tenants, one directory = cross-scope bleed), so any
 * scope whose cleaned form differs from the original gets a short content-hash suffix
 * (`org-7-a1b2c3`), making the mapping injective for all practical inputs; an already-safe scope maps
 * to itself (stable, human-readable). {@link registerScope} additionally FAIL-CLOSES on a registry
 * collision (two distinct scopes → one dir name), so even a hash collision cannot silently merge scopes.
 */
export declare function scopeDirName(scope: string): string;
/**
 * Whether `dir`'s volume FOLDS letter case — two names differing only in case address ONE
 * directory entry (the macOS/Windows default). Probed on the actual directory, never guessed from
 * the platform: case-sensitive APFS volumes and case-insensitive Linux mounts both exist, and this
 * answer gates a fail-closed isolation refusal, so it must describe the volume the scope dirs
 * really land on — a platform guess would fail OPEN exactly on the mismatched deployments.
 * `undefined` = the volume answered on neither leg (unwritable AND no letter-bearing entry to read
 * against); the caller must treat that as unresolved, never as either determined answer.
 * Every call measures: no answer outlives the call that measured it. A directory's `dev:ino` is
 * handed to a new directory once the old one is removed, and a file system that switches case
 * folding per directory gives the new one other semantics — an answer remembered under that
 * number would decide the new directory's isolation from the old one's. The probe stays lazy (a
 * registration asks only on a fold-equal pair) and costs a few tens of microseconds.
 * Exported for the layout pins; not part of the package surface.
 */
export declare function dirCaseFolds(dir: string): boolean | undefined;
/** The closure of every label {@link scopeDirName} can mint: a safe-form scope verbatim, or the
 *  folded form (leading `.`/`-` stripped) plus a hash suffix. One non-hidden path segment — never
 *  empty, never `.`/`..`, never a separator — so two labels are two distinct directory entries. */
export declare const SCOPE_DIR_LABEL_RE: RegExp;
/** Prefix of the case-fold probe files the layout leaves (briefly) at a memory root. One spelling
 *  for the probe writer, for the migration's residue removal and for {@link STORE_OPEN_ARTIFACTS}. */
export declare const CASEFOLD_PROBE_PREFIX = ".casefold-probe-";
/** The four shapes a scope registry read can take. */
export declare const SCOPE_REGISTRY_SHAPES: readonly ["absent", "v1", "v2", "migrating"];
export type ScopeRegistryShape = (typeof SCOPE_REGISTRY_SHAPES)[number];
/** Which shapes the path-deriving read faces (`registerScope` / `scopeDirFor` / `registeredScopes`)
 *  may serve. `v1` (the pre-v2 file: a root-owning scope, `""` labels) and `migrating` (a v2 file
 *  carrying an unfinished move marker) are refused fail-closed: the registry then does not describe
 *  where entries physically live until {@link adoptRootScopeLayout} has run to completion. */
export declare const REGISTRY_SHAPE_DERIVES_PATHS: {
    readonly absent: true;
    readonly v1: false;
    readonly v2: true;
    readonly migrating: false;
};
export type DerivesPathsTableCoversEveryRegistryShape = AssertAllKeysHandled<Exclude<ScopeRegistryShape, keyof typeof REGISTRY_SHAPE_DERIVES_PATHS>>;
/** The unfinished-move marker: the physical root whose loose content is being moved into
 *  `<root>/<label>` for `owner`. Durable across crashes; whoever holds the registry lock next
 *  finishes it before doing anything else. */
export interface ScopeLayoutMigratingMarker {
    root: string;
    owner: string;
    label: string;
}
/** The v2 registry record. `rootOwner` is the scope that historically owned the memory root; it is
 *  consulted only to attribute loose root content during adoption and never derives a path. */
export interface ScopesRecordV2 {
    v: 2;
    scopes: Record<string, string>;
    rootOwner?: string;
    migrating?: ScopeLayoutMigratingMarker;
}
/** A parsed registry, tagged by shape. `v1` keeps the pre-v2 fields for the one-time conversion. */
export type ScopeRegistryRead = {
    shape: "absent";
    rec: ScopesRecordV2;
} | {
    shape: "v1";
    rootScope?: string;
    scopes: Record<string, string>;
} | {
    shape: "v2";
    rec: ScopesRecordV2;
} | {
    shape: "migrating";
    rec: ScopesRecordV2 & {
        migrating: ScopeLayoutMigratingMarker;
    };
};
/** Register `scope` in the durable registry (idempotent) and return its home `<memoryDir>/<label>`.
 *  The registered label is the truth for a scope that has one (a home never moves); the
 *  {@link scopeDirName} formula mints the label for a never-registered scope. Both collision arms
 *  run over the effective labels; the home is created on first registration and its physical form
 *  is proven on every call. Lock-serialized; a `v1`/`migrating` registry is refused. */
export declare function registerScope(memoryDir: string, controlDir: string, scope: string, opts?: {
    caseFoldingFs?: boolean;
}): string;
/** All registered scopes → label. A `v1`/`migrating` registry is refused. */
export declare function registeredScopes(controlDir: string): Record<string, string>;
/** The stable home directory of `scope`'s entry files: `<memoryDir>/<label>`, the REGISTERED label
 *  when there is one, the formula otherwise. Registers nothing. A `v1`/`migrating` registry is refused. */
export declare function scopeDirFor(memoryDir: string, controlDir: string, scope: string): string;
/** The scope registry's shape as it stands on disk (lock-free, journal-aware). Exported for the
 *  backend's cheap pre-check and for the layout pins; not part of the package surface. */
export declare function scopeRegistryShape(controlDir: string): ScopeRegistryShape;
/** The v1 path-key resolver (design A6): maps a memory-dir-relative persistent key written under the
 *  root-owning layout onto the ledger form `(scope, rel)`. The first segment names a registered
 *  non-owner label ⇒ that scope's home; otherwise the key belonged to the root owner. `undefined`
 *  when the row cannot be attributed (no root owner on record) — the caller keeps the row in its
 *  old form and refuses the operations that depend on it. Reads any registry shape (the conversion
 *  is independent of the physical move). */
export declare function v1MemoryPathKeyResolver(controlDir: string): (relPath: string) => {
    scope: string;
    rel: string;
} | undefined;
/** Options of {@link adoptRootScopeLayout}. `ownerCandidate` attributes loose root content when the
 *  registry records no root owner (the mount's write scope / a standalone batch's first add scope).
 *  `renew` is the caller's outer-lock heartbeat (the backend's transaction lock) — called before
 *  every filesystem action and every sidecar write, together with the registry lock's own. */
export interface AdoptRootScopeLayoutOptions {
    ownerCandidate?: string | null;
    onIncident?: MemoryPartitionIncidentSink;
    renew?: () => void;
    /** The one-time v1 sidecar key conversions, run in the adoption (before any later scope
     *  registration can change what a v1 key's first segment names). Each conversion is idempotent
     *  and takes its own sidecar lock. */
    convertSidecars?: (controlDir: string) => void;
}
/** The lock-free pre-check the backend's public faces ask before a registry-derived path: does the
 *  tree at `root` still need the adoption (a v1/migrating registry, or loose content at the root)?
 *  One journal-aware registry read plus one readdir; the adoption re-enumerates under the locks. */
export declare function layoutNeedsAdoption(root: string, controlDir: string): boolean;
/**
 * Adopt the per-scope layout for the physical tree at `root` (the engine's memory dir, or the
 * backend's directory root; both when they differ — they share one control plane, so the registry
 * conversion happens once). Runs under the registry lock; the caller holds any outer lock. Every
 * step is idempotent and the two-phase marker makes an interrupted move resumable by whoever holds
 * the lock next:
 *   0. registry shape: `absent` ⇒ an empty v2 record; `v1` ⇒ v2 with `rootOwner` = the old
 *      `rootScope` (the root owner is also given its label); `migrating` ⇒ that move is finished
 *      FIRST, whichever tree it names. The root's loose content is enumerated on every call — a v2
 *      registry proves nothing about THIS tree.
 *   1. loose content ⇒ owner = `rootOwner ?? ownerCandidate`; neither ⇒ `memory.layout_unowned_root_content`
 *      (names capped), registry converted, nothing moved.
 *   2. pre-checks, zero writes: the control plane inside the root; the owner's home a link/file, or
 *      a real non-empty directory without a marker for it; any loose name already present in the
 *      home — each refuses with {@link ControlPlaneCorruptError}.
 *   3. commit A: the v2 record with the owner registered, `rootOwner`, and the `migrating` marker.
 *   4. move: per entry, lstat the destination (absent ⇒ rename; present ⇒ refuse; source gone ⇒
 *      already moved); probe residue removed. No sidecar key and no index text is rewritten (the
 *      ledger form keys are location-free; the index heals through its rebuild law).
 *   5. `index-revs.json` cleared when one exists (fail-open snapshot; the next rebuild keeps model wording
 *      once) — with none there is no line number to void, and a read must not leave one behind.
 *   6. commit B: the marker removed; `memory.layout_migrated` disclosed.
 */
export declare function adoptRootScopeLayout(rootPath: string, controlDir: string, opts?: AdoptRootScopeLayoutOptions): void;
/** The memory layout's reading of a path: the tree's one physical-path mint over the spelling with its `..` folded
 *  first. The plane builds every path it keys, writes and reads with `join` from its configured roots, and `join`
 *  folds, so the plane's keys fold the same way: a root spelled `link/..` keys the directory its own joins reach
 *  (KNOWN-LIMITS KL-902-b). One mint behind both names — a second canonicalizer here is what let a key minted by this
 *  layout name a directory the fence resolved differently. */
export declare const canonicalize: (p: string) => string;
/** True iff `child` (canonicalized) is `root` or inside it. */
export declare function isContainedIn(root: string, child: string): boolean;
/** The codes the store's physical form refuses an act with — the whole family, one closed set: {@link TARGET_OUTSIDE_STORE},
 *  {@link SCOPE_HOME_NOT_DIRECTORY}, {@link CONTROL_PLANE_LINKS_UNSUPPORTED}, {@link CONTROL_PLANE_STRAYS}, {@link STORE_ROOT_SENSITIVE},
 *  {@link CONTROL_PLANE_SPLIT} and {@link STORE_ABSENT}. Each is a plain `Error` carrying `code` and a `detail` ({@link StoreFormRefusalDetail}). */
export declare const STORE_FORM_REFUSAL_CODES: readonly ["memory.target_outside_store", "memory.scope_home_not_directory", "memory.control_plane_links_unsupported", "memory.control_plane_strays", "memory.store_root_sensitive", "memory.control_plane_split", "memory.store_absent"];
export type StoreFormRefusalCode = (typeof STORE_FORM_REFUSAL_CODES)[number];
/** The code an act on a store path is refused with when it would land outside the store ({@link landsOutsideStore}). */
export declare const TARGET_OUTSIDE_STORE = "memory.target_outside_store";
/** The code a scope home that is not a real directory is refused with ({@link assertHomePhysicalForm}). */
export declare const SCOPE_HOME_NOT_DIRECTORY = "memory.scope_home_not_directory";
/** The code a File governance store's open is refused with when its control plane's file system cannot make a hard link
 *  (`probeControlPlaneLinks`, `control-objects.ts`; #3512). */
export declare const CONTROL_PLANE_LINKS_UNSUPPORTED = "memory.control_plane_links_unsupported";
/** The code an engine's construction is refused with when its backend carries a governance store that is not the File
 *  store over the engine's own control plane, and that control plane still holds carrier records (`controlPlaneStraysRefusal`;
 *  #3484, C-R1119 HB-5): records nobody reads would launder what they recorded, so they are adopted first. */
export declare const CONTROL_PLANE_STRAYS = "memory.control_plane_strays";
/** The code a store root (or the control plane beside it) that lies inside a path the write guard protects is refused with, before anything is
 *  created there ({@link assertStoreRootsNotSensitive}): a library written under `~/.ssh` is a library an escalation vector holds. */
export declare const STORE_ROOT_SENSITIVE = "memory.store_root_sensitive";
/** The code an open is refused with when the store's control plane stands in more than one place since its engine root moved
 *  ({@link controlPlaneSplitRefusal}): more than one plane travelled for it, or the one that travelled and the one at its key now
 *  both hold a record of one name with different contents. */
export declare const CONTROL_PLANE_SPLIT = "memory.control_plane_split";
/** The code an open is refused with when someone expects a store to exist at its directory and its control plane holds neither
 *  the store's root anchor nor its account ({@link storeAbsentRefusal}): the store was moved away, or the volume it lives on is
 *  not mounted, and an open that read "nothing here" as "a first open" would start an empty store in its place. */
export declare const STORE_ABSENT = "memory.store_absent";
/** Who expected the store a {@link STORE_ABSENT} refusal is about (`detail.expectedBy`): `process`, this process saw the store
 *  hold a record ({@link storeAbsence}); `declaration`, its opener declared it one that already exists (the file backend's
 *  `expectExistingStore`). Both at once answer `process` (withdrawing the declaration does not lift it). */
export declare const STORE_ABSENT_EXPECTED_BY: readonly ["process", "declaration"];
export type StoreAbsentExpectedBy = (typeof STORE_ABSENT_EXPECTED_BY)[number];
/** What a scope home can be besides a real directory (an `lstat` verdict). */
export declare const SCOPE_HOME_FORMS: readonly ["symlink", "file", "other"];
export type ScopeHomeForm = (typeof SCOPE_HOME_FORMS)[number];
/** How a refusal's sentence names each form. */
declare const SCOPE_HOME_FORM_PHRASE: {
    readonly symlink: "a symbolic link";
    readonly file: "a regular file";
    readonly other: "a special file";
};
export type HomeFormPhraseCoversEveryForm = AssertAllKeysHandled<Exclude<ScopeHomeForm, keyof typeof SCOPE_HOME_FORM_PHRASE>>;
/** Why a {@link TARGET_OUTSIDE_STORE} refusal refused — one word per seat, given where the refusal is minted: `act_outside`, an act's
 *  target resolves outside the store ({@link storeActRefusal}); `root_moved`, the store root resolves to another directory than the one
 *  its anchor records ({@link storeRootMovedRefusal}); `root_gone`, nothing stands at the root the anchor records
 *  ({@link storeRootAbsentRefusal}); `root_reanchored`, the store was re-anchored after the session acting on it opened it
 *  ({@link storeRootReanchoredRefusal}). */
export declare const TARGET_OUTSIDE_STORE_REASONS: readonly ["act_outside", "root_moved", "root_gone", "root_reanchored"];
export type TargetOutsideStoreReason = (typeof TARGET_OUTSIDE_STORE_REASONS)[number];
/** What a store-form refusal carries beside its sentence. Host paths live here and never in the sentence (on
 *  {@link CONTROL_PLANE_LINKS_UNSUPPORTED}, `path` is the control plane);
 *  `form` is present on {@link SCOPE_HOME_NOT_DIRECTORY} only; `outsideReason` is present on every {@link TARGET_OUTSIDE_STORE}
 *  refusal and only there, and says which of its cases it is ({@link TARGET_OUTSIDE_STORE_REASONS}); `controlDir`, `recorded` and `now`
 *  are data on every one of those but `act_outside`: the control plane whose root anchor refused (the `controlDir` to hand
 *  {@link reanchorMemoryStoreRoot}), the physical root the anchor records (spelled as the anchor records it: what a caller hands back
 *  as the re-anchor's `expectedFrom`), and where the root resolves now (for `root_reanchored`, the root the session opened);
 *  `row` and `of` are present on {@link STORE_ROOT_SENSITIVE} only: the table row the root lands on
 *  (a pattern of the write guard's list, as written) and which root it is (`path` is that root's spelling);
 *  `expectedBy` is present on {@link STORE_ABSENT} only, beside its `controlDir` (the control plane that holds neither anchor nor
 *  account; `path` is the store directory's spelling): who expected the store ({@link STORE_ABSENT_EXPECTED_BY}). */
export type StoreFormRefusalDetail = {
    readonly path: string;
    readonly form?: ScopeHomeForm;
    readonly outsideReason?: TargetOutsideStoreReason;
    readonly controlDir?: string;
    readonly recorded?: string;
    readonly now?: string;
    readonly row?: string;
    readonly of?: StoreRootKind;
    readonly expectedBy?: StoreAbsentExpectedBy;
};
/** Which root a {@link STORE_ROOT_SENSITIVE} refusal is about: the store's own directory, the control plane beside it, or the memory engine root a
 *  deployment's host verbs keep their own lock under. */
export type StoreRootKind = "store" | "control_plane" | "engine_root";
/** A refusal the store's physical form earns: a plain `Error` (never the control-plane-damage class —
 *  the engine's own account is intact, the layout it was handed is not the layout it needs) carrying a
 *  `code` and a `detail`. */
export type StoreFormRefusal = Error & {
    code: StoreFormRefusalCode;
    detail: StoreFormRefusalDetail;
};
/** A store-form refusal as read off a thrown value: its code, and for {@link TARGET_OUTSIDE_STORE} the case its seat named. */
export type StoreFormRefusalReading = {
    readonly code: Exclude<StoreFormRefusalCode, typeof TARGET_OUTSIDE_STORE>;
} | {
    readonly code: typeof TARGET_OUTSIDE_STORE;
    readonly outsideReason: TargetOutsideStoreReason;
};
/** The one reading of the family off a thrown value, beside its one mint (a hostile accessor reads as absent): a member's code, with —
 *  for {@link TARGET_OUTSIDE_STORE} — its `detail.outsideReason`, which every seat of that code gives; `undefined` for any other value,
 *  that code without one of its words included (no seat of the family makes it). */
export declare function storeFormRefusalReadingOf(thrown: unknown): StoreFormRefusalReading | undefined;
/** Seat 1 — an act the store's physical form refuses: `act` names what was refused (no path), `path` is the
 *  target whose directory resolves outside the store ({@link landsOutsideStore}). */
export declare function storeActRefusal(act: string, path: string): StoreFormRefusal;
/** Seat 2 — the store root no longer resolves to the physical root its control plane's anchor records
 *  ({@link anchorStoreRoot}) and the store holds memory; `path` is the root's spelling. The remedy names its
 *  arguments by what they are — never by a `detail` key, which a caller handed the sentence alone does not have —
 *  so the sentence stays path-free and says the step a person takes. */
export declare function storeRootMovedRefusal(path: string, anchor: {
    controlDir: string;
    recorded: string;
    now: string;
}): StoreFormRefusal;
/** Seat 2, re-anchored under a session: the store's anchor records another root than the one the session acting on it opened (for the
 *  file backend's commit, the root its caller says the session opened) — the store was re-anchored since
 *  ({@link reanchorMemoryStoreRoot}), so the session names a tree the store no longer has. The sentence states that mismatch, not the
 *  history behind it; the remedy is a new session (it opens the store where it is anchored now) and the store itself needs nothing.
 *  `recorded` is the anchored root, `now` the root the session opened. */
export declare function storeRootReanchoredRefusal(path: string, anchor: {
    controlDir: string;
    recorded: string;
    now: string;
}): StoreFormRefusal;
/** Seat 2, the root gone: the anchored root no longer exists while its control plane holds a store's account
 *  ({@link anchorStoreRoot}). A missing root lands where it would be created — the recorded one — so only
 *  its absence tells a store moved away (or deleted) from one never opened; the root is not re-created. */
export declare function storeRootAbsentRefusal(path: string, anchor: {
    controlDir: string;
    recorded: string;
    now: string;
}): StoreFormRefusal;
/** Seat 3 — a scope home that is not a real directory. */
export declare function scopeHomeRefusal(form: ScopeHomeForm, path: string): StoreFormRefusal;
/** Seat 4 — the control plane at `path` is on a file system that refused a hard link (`fault`: the error code `link`
 *  answered, when it named one). The store publishes every control object with `link`, so it is not opened there. */
export declare function controlPlaneLinksRefusal(path: string, fault: string | undefined): StoreFormRefusal;
/** Seat 6 — a store root (`of: "store"`) or its control plane (`of: "control_plane"`) that lies inside a path the write guard's table protects
 *  (`row`: the row it lands on). Not opened and nothing created: the sentence names the row, never the path (`detail.path` is the spelling). */
export declare function storeRootSensitiveRefusal(of: StoreRootKind, path: string, row: string): StoreFormRefusal;
/** Seat 5 — an engine whose backend carries a governance store of its own over a control plane (`path`) that still holds
 *  that carrier's records from before (`strays`: the documents, and the count of entries per object kind): the engine
 *  reads its records through the carrier, so these would be read by nobody — a pollution marker, a hold, a capture
 *  opt-out nobody reads launders what it recorded. Not opened; the remedy is the explicit adoption. */
export declare function controlPlaneStraysRefusal(path: string, strays: {
    readonly docs: readonly string[];
    readonly objects: Readonly<Record<string, number>>;
}): StoreFormRefusal;
/** Seat 7 — the control plane of the store at `path` stands in more than one place under the memory engine root since the root moved
 *  ({@link adoptPlaneMovedWithRoot}): `planes` names the key directories; `documents` is empty when more than one plane travelled for
 *  the store, else it names the records (paths under a plane) the plane at the store's key now and the one that travelled both hold
 *  with different contents. The sentence names key directories and records, never a host path or a `detail` member. */
export declare function controlPlaneSplitRefusal(path: string, split: {
    readonly planes: readonly string[];
    readonly documents: readonly string[];
}): StoreFormRefusal;
/** What a {@link STORE_ABSENT} refusal says, one sentence per word of who expected the store; `satisfies` makes a word added without
 *  its sentence a tsc error. No host path: the directory and the control plane are `detail.path` / `detail.controlDir`. */
declare const STORE_ABSENT_SENTENCE: {
    readonly process: "this process saw this memory store hold records, and its control plane no longer holds its root anchor or its account — the store was moved away, or the volume it lives on was unmounted, while in use; refused: no new store was recorded in its place (no root anchor written, no store directory or anchor lock created); put the store's directory and its control plane back where they were (it opens again as it was, no restart needed), or, to start over with an empty store on purpose, open it from a new process that does not declare it an existing store (a deployment's personal store lives in the personal folder under the memory engine root)";
    readonly declaration: "this memory store was declared as one that already exists, but its control plane holds neither its root anchor nor its account — its directory was moved away, or the volume it lives on is not mounted; refused: no new store was recorded (no root anchor written, no store directory or anchor lock created); put the store's directory and its control plane back where they were (or mount the volume), then reopen; to start over with an empty store on purpose, open it without declaring it existing";
};
export type StoreAbsentSentenceCoversEveryExpectation = AssertAllKeysHandled<Exclude<StoreAbsentExpectedBy, keyof typeof STORE_ABSENT_SENTENCE>>;
/** Seat 8 — the store at `path` is expected to exist (`expectedBy`) and its control plane `controlDir` holds neither its root anchor
 *  nor its account ({@link anchorStoreRoot}): thrown before the anchor check creates anything (the control plane, the anchor's lock,
 *  the root, the anchor). The sentence promises what holds on every path to it — no store recorded — and nothing about a plane an
 *  opener's one-shot move ({@link effectiveControlRootOf}) brought to `controlDir` before the check. */
export declare function storeAbsentRefusal(path: string, controlDir: string, expectedBy: StoreAbsentExpectedBy): StoreFormRefusal;
/** Where an act at `p` lands: the physical path of its normalized spelling (the spelling a child path
 *  joined under it carries), a MISSING tail rejoined under the deepest existing directory (what the act
 *  creates) — a dangling link on that tail followed to where it points (what the act would create through
 *  it). Any other resolution fault (EACCES, ELOOP, ENOTDIR) is THROWN as itself: an act that
 *  cannot be placed is not performed — a failed resolution never implies the act would fail too
 *  (a link whose own mode refuses `realpath` is still followed by `unlink` and `rename`). */
export declare function landingPathOf(p: string): string;
/**
 * Whether a write, rename or delete at `target` would physically LAND outside the store, judged against the
 * store's `physicalRoot` (`true` = outside; the refusal is {@link storeActRefusal}). The target's directory, resolved through
 * every link on its existing prefix (a missing tail is what the act creates, under the deepest existing
 * directory), must be the root or inside it. `physicalRoot` is the root's physical form as the store
 * was opened and is not re-resolved here: a store mounted through a link is judged by what the link
 * resolved to, and a root spelling re-pointed after opening moves the acts, not the store. The final
 * component is not judged: `rename` and `unlink` act on it and never through it, and the engine's
 * writes open it no-follow — a link there is replaced, removed or refused, and what it points at is
 * untouched. A lexical spelling under the root proves nothing: a directory under it replaced by a link
 * keeps the spelling while the act follows the link out. A directory that cannot be resolved throws its
 * fault ({@link landingPathOf}).
 */
export declare function landsOutsideStore(physicalRoot: string, target: string): boolean;
/** mkdir -p convenience used by the engine/backend (0o700 like the file stores). */
export declare function ensureDirExists(dir: string): void;
/** The committed-rev ledger's file name (the file backend's account). Named here because the anchor reads
 *  its presence as "this control plane already holds a store". */
export declare const LEDGER_FILE = "revs.json";
/** The control-plane file recording the store root's physical path ({@link anchorStoreRoot}). */
export declare const ROOT_ANCHOR_FILE = "root-anchor.json";
/** What an ABSENT anchor means — the one law, whatever brought the control plane here (an engine that recorded no anchor, a
 *  one-shot key migration, a host's copy, an anchor removed by hand): a control plane holding nothing records the root (a first
 *  open — reached only when no one expects the store there: {@link anchorStoreRoot} refuses that case before it asks,
 *  {@link storeAbsence}); one already holding a store's account refuses ({@link rootAnchorRefusal}), and the one remedy is
 *  {@link reanchorMemoryStoreRoot}. The anchor has two writers: that first record, and the re-anchor. */
export declare function absentAnchorReading(controlPlaneHoldsStore: boolean): "record" | "refuse";
/** Forget every store this process opened and saw. Exported for the pins (a cell that removes a store it wrote and opens another at the
 *  same path); not part of the package surface. */
export declare function forgetStoresSeenInProcess(): void;
/**
 * THE question "is a store expected here and absent": the control plane `controlDir` holds neither the root anchor nor the
 * store's account ({@link controlPlaneHoldsStore}) while someone expects a store there — this process, which saw the zero-copy
 * store at that plane hold content ({@link storesInProcess}: on the disk at an anchor check, or landed by its own write) (`process`),
 * or the opener's declaration (`declared`, the file backend's construction only)
 * — answers who expects it ({@link STORE_ABSENT_EXPECTED_BY}); else `undefined`, and the absence reads as it always did (a first
 * open). No expectation ⇒ no file-system call. Every seat that would otherwise read "nothing here" as "a new store" asks it:
 * the anchor's absent arm, {@link ensureControlPlaneDir}, the capture records ({@link captureRecordsExpectingStore}), the engine's
 * session status and file-tool write gate, a deployment's store set and personal open, and — through {@link refuseAbsentPinnedStore}
 * — the personal plane's open, a deployment's erasure and a run's memory phase.
 */
export declare function storeAbsence(controlDir: string, declared?: boolean): StoreAbsentExpectedBy | undefined;
/** {@link storeAbsence} answered by its refusal ({@link storeAbsentRefusal}); `dir` names the store directory (`undefined` ⇒ as
 *  this process last saw it spelled, else the control plane). */
export declare function refuseAbsentStore(dir: string | undefined, controlDir: string, declared?: boolean): void;
/** THE way a directory of a store's control plane is made — the plane itself, or `sub` under it: a store expected there and
 *  absent ({@link storeAbsence}) is refused before anything is made, else `mkdir -p` ({@link ensureDirExists}). Every
 *  control-plane writer makes its directory through this one, so no write puts back a plane whose store is gone. */
export declare function ensureControlPlaneDir(controlDir: string, sub?: string): void;
/** {@link refuseAbsentStore} over the store of a backend pinned to its directory ({@link directoryPinOf}), at the control plane it
 *  publishes ({@link controlPlanePinOf}) — a deployment's own File store, asked before anything is opened or made beside it (its
 *  personal store, its erasure lock, a run's memory phase). A backend without a directory keeps no File store here: nothing is asked. */
export declare function refuseAbsentPinnedStore(backend: unknown): void;
/**
 * The capture opt-out records of the store whose control plane is `controlDir`, read through {@link storeAbsence}: a read the
 * carrier answers with no record, while that store is expected there and absent, throws its {@link STORE_ABSENT} refusal — the
 * indeterminate fault axis every reader already suppresses on (a record the carrier does answer stands, a store gone or not); a
 * listing throws it before the carrier is asked (an unknowable roster is not an empty one); a mark answers `"unpersisted"` without
 * asking the carrier (the record cannot land beside a store that is not there). Any carrier — the File store's, a host's — is held to
 * it, and a store nobody expects reads exactly as its carrier answers.
 */
export declare function captureRecordsExpectingStore(store: SessionCaptureRecordStore, controlDir: string): SessionCaptureRecordStore;
/**
 * The write half of "seen": this process's own write just landed the file at `path`. When `path` lies under the control plane of a
 * zero-copy store this process opened (the nearest such plane above it) and the file is content ({@link isStoreContent} — the census's
 * own per-item judge, so a mount's bookkeeping and what an open or a read leaves are not), the store is one this process saw from this
 * moment, not from its next anchor check — a write through the store's governance faces (a pollution marker, a capture opt-out, a
 * cursor) may never be followed by one. Called by the two ways a file lands in a store's control plane, after the file stands:
 * {@link atomicWriteFileSync} (every document, ledger, shadow copy, cursor and plan, and the commit journal every entry and evidence row
 * is written after) and a control object's publication (`control-objects.ts`). A plane no zero-copy store of this process sits on (a
 * copy-out projection's, a host's replica) is not looked up; the memory directory is not looked up either — what the engine writes
 * there puts back, canonicalizes or indexes what a commit through the control plane already holds.
 */
export declare function rememberStoreWrite(path: string): void;
/**
 * THE judgment of where one root of a memory store may live: not inside a path the write guard's table protects (`sensitiveRowOf` — the
 * `.ssh` / `.aws` / key-file rows of `RECOMMENDED_SENSITIVE_PATTERNS`, the one table, no second list). A library kept under `~/.ssh` is written by
 * the engine's own file I/O, which no write guard sees — the guard judges the model's tool calls, not the store — so the root is a
 * configuration fact to refuse, not a write to gate. Read on the root's spelling and on where it physically lands NOW (a link on its prefix, a
 * missing tail rejoined, as {@link landingPathOf} reads it; never kept between calls — a link retargeted since the last open is read again); a
 * root that cannot be placed is judged on its spelling and says what is wrong at the act that needs it. Throws {@link storeRootSensitiveRefusal}.
 */
export declare function assertRootNotSensitive(of: StoreRootKind, root: string): void;
/**
 * The store's two roots through that judgment: its directory and its control plane. Run at the head of {@link anchorStoreRoot}, which every opener
 * (a file backend's construction, an engine's mount) and every anchored face passes before it creates a root or writes under one — and by
 * {@link effectiveControlRootOf} before the one-shot move of a legacy control plane, which is the one write that precedes the anchor head. The
 * transaction lock ({@link tryStoreTxnLock}) judges the plane itself, for the faces that make it before they read the anchor.
 */
export declare function assertStoreRootsNotSensitive(dir: string, controlDir: string): void;
/** Options of {@link anchorStoreRoot}. */
export interface AnchorStoreRootOptions {
    /** Where `memory.root_anchor_rerecorded` and `memory.control_plane_new_over_memory` go. */
    onIncident?: MemoryPartitionIncidentSink;
    /** The clock `recordedAt` reads (the opener's injected clock). */
    now?: () => number;
    /** The opener declares the store one that already exists (the file backend's `expectExistingStore`, at its construction only):
     *  an absent anchor over a control plane that holds no store's account then refuses {@link STORE_ABSENT} instead of reading as a
     *  first open. Absent or `false` ⇒ the first-open reading, unless this process saw the store hold a record. */
    expectExisting?: boolean;
    /** The store is zero-copy — its directory IS the storage (the file backend itself; an engine over a backend pinned to its
     *  directory): a check that returns makes it one this process opened, and one it saw when the store holds content
     *  ({@link storeHoldsContent}) — or, later, when this process's own write lands content there ({@link rememberStoreWrite})
     *  ({@link storeAbsence}). A copy-out projection is rebuilt when lost and is never remembered. */
    remember?: boolean;
}
/**
 * THE store-root check, run by every opener (a file backend's construction, an engine's mount) and at the
 * head of every face that acts on the store: where the root `dir` physically resolves NOW, against the
 * anchor its control plane records. Equal ⇒ the anchored root, the one every act at a store path is judged
 * against. Unequal ⇒ {@link storeRootMovedRefusal} while the mount holds a record; equal but the root gone while the control plane holds a
 * store ⇒ {@link storeRootAbsentRefusal} — both thrown before anything in the store is written or the root is
 * created (only the anchor answers where the root is; a `mkdir` in its place does not). Unequal over a mount that holds no
 * record (an open's or a read's residue: the anchor, the registry, empty directories — the root of an engine root moved by
 * its operator, say) while nothing stands any more at the root the anchor records (the store moved away whole; a root
 * re-pointed while its old directory stands is refused as before) ⇒ nothing is guarded, so the root is recorded where it resolves now, under the anchor's lock, and
 * `memory.root_anchor_rerecorded` says which root the anchor had named. No anchor over a control plane that holds no store's account,
 * while someone expects the store there ({@link storeAbsence}: this process saw it hold a record, or the opener declared it existing
 * — `expectExisting`) ⇒ {@link storeAbsentRefusal}, outside the anchor's lock and before anything is created (taking the lock creates
 * the control plane): an opener racing to record the anchor at that moment makes this open refuse and the next succeed. No anchor
 * otherwise ⇒ {@link absentAnchorReading}, decided under the anchor's lock (a racing opener
 * that recorded it first is judged against): a control plane holding nothing creates the root and records
 * it (a first open, only when no one expects the store); one already holding a store's account is refused
 * {@link ROOT_ANCHOR_DAMAGED} before the root is created or an anchor written, its remedy the re-anchor. Nothing is kept between calls: the anchor is read every
 * time, so a re-anchor ({@link reanchorMemoryStoreRoot}) reaches every live holder at its next face. With `remember`, every return
 * makes the store one this process opened, and one it saw when the store holds content ({@link storeAbsence}).
 */
export declare function anchorStoreRoot(dir: string, controlDir: string, opts?: AnchorStoreRootOptions): string;
/** The redo journal a File store's transaction writes as its commit marker (control plane). */
export declare const STORE_JOURNAL_FILE = "journal.json";
/** The transaction lock's directory in the control plane; `owner` inside holds the holder's token. */
export declare const STORE_TXN_LOCK_DIR = "txn.lock";
/** A lock older than this is a crashed holder (stolen; the journal recovery inside the lock makes the steal safe). */
export declare const TXN_LOCK_STALE_MS = 30000;
/** Test hook: small constants so a crash-window leg does not really wait 15–30 s. */
export interface TxnLockTimings {
    staleMs?: number;
    waitMs?: number;
    stealGraceMs?: number;
}
/** A held transaction lock: its token, and a release that removes the lock only while the token is still ours. */
export interface StoreTxnLock {
    readonly token: string;
    readonly release: () => void;
}
/**
 * One attempt at the store's transaction lock (synchronous): the lock, or `undefined` while another holder has
 * it. Only the lock directory's EEXIST is contention; every other failure — the control plane unmakeable, a
 * probe or steal that faults, an occupant that is not a directory — throws {@link ControlPlaneCorruptError}
 * (a fault is never read as "busy, retry later"). Every acquisition writes an owner token (crypto-random)
 * before it returns. A held lock past its stale line (`now` against its mtime) that carries a token is a
 * crashed holder: stolen single-winner (an atomic rename to a unique tombstone; a racer's lost rename is
 * ENOENT) and re-attempted through a normal `mkdir` — never a bare rm + mkdir. A tokenless lock is a
 * mid-acquisition, never stolen. `observed` hears each held lock's mtime (a waiter's deadline extension).
 */
export declare function tryStoreTxnLock(controlDir: string, opts: {
    now: () => number;
    staleMs?: number;
    observed?: (mtimeMs: number) => void;
}): StoreTxnLock | undefined;
/** The commit boundary of a store transaction: the lock still names `token` — an absent or unreadable owner (a
 *  stolen, tombstoned lock) is lost too. A holder that stalled past the stale line was stolen from; acting on
 *  would overwrite the stealer's transaction. */
export declare function assertStoreTxnLockOwnership(controlDir: string, token: string): void;
/** The holder's heartbeat: refresh the lock's mtime (its stale line moves on) and re-prove it is still `token`'s —
 *  a holder stolen from throws {@link assertStoreTxnLockOwnership}'s refusal, never acts on. */
export declare function renewStoreTxnLock(controlDir: string, token: string): void;
/** Wait for the store's transaction lock: one {@link tryStoreTxnLock} per round, paced 20–60 ms (the wait
 *  yields the event loop every round), until the deadline — `waitMs`, extended to an observed lock's stale
 *  line plus the steal grace. Past it: a loud timeout. */
export declare function acquireStoreTxnLock(controlDir: string, opts: {
    now: () => number;
    timings?: TxnLockTimings;
}): Promise<StoreTxnLock>;
/** What {@link reanchorMemoryStoreRoot} changed. */
export interface StoreRootReanchor {
    /** The physical root the anchor recorded before; absent when no readable anchor stood. */
    readonly from?: string;
    /** The physical root it records now. */
    readonly to: string;
    /** The control plane the anchor lives in. */
    readonly controlDir: string;
}
/**
 * The TRANSIENT sweep record: per erasure requestId, the projection paths it deleted, kept in the
 * control plane only until the derived-index sweep has cleared every MEMORY.md line naming them (the
 * paths spell slugs, so the durable chain and the attestation never hold them). Written from the
 * request's journal right after its commit point, and by recovery from a journal it rolls forward;
 * swept and settled by `MemoryEngine.eraseMemoryEntries` under this file's lock. A request with a
 * record is `partial` on `indexLine`. A row's paths are relative to the store root
 * ({@link erasureSweepRecordPathOf}) and are read at the root the store is opened at now
 * ({@link erasureSweepOwedAt}), so a row binds no root and follows a re-anchor. A record that cannot
 * be read or written, or a row path that is absolute or leaves the root, refuses like every strict
 * control-plane file (fail-closed).
 */
export declare const ERASURE_SWEEP_RECORD_FILE = "erasure-sweeps.json";
export declare const ERASURE_SWEEP_RECORD_WHAT = "memory erasure sweep record";
export interface ErasureSweepRecordFile {
    v: 1;
    requests: Record<string, string[]>;
}
export declare function coerceErasureSweepRecord(raw: unknown): ErasureSweepRecordFile;
/** The row path of `target`, a projection `requestId` deleted under `storeRoot`: relative to the root's
 *  physical form, the target placed as the act gate places a delete ({@link landsOutsideStore}: its directory
 *  where it lands, the final component as spelled) — so every spelling of one root records one row. A target
 *  that does not land under the root is refused (fail-closed; the text names no path — paths spell slugs). */
export declare function erasureSweepRecordPathOf(storeRoot: string, requestId: string, target: string): string;
/** The paths `requestId`'s row owes, at the root the store is opened at now (`[]` without a row). */
export declare function erasureSweepOwedAt(file: ErasureSweepRecordFile, storeRoot: string, requestId: string): string[];
/**
 * The ONE way a recorded root anchor changes: point it at where `dir` resolves now — a store moved on
 * purpose, an anchor that is damaged, or one that is absent while the control plane holds the store's account
 * (the {@link ROOT_ANCHOR_DAMAGED} refusal's `detail.path` and `detail.controlDir` are its two arguments). `opts.controlDir` names the store's control plane exactly as its
 * opener does (the explicit `controlDir` the backend / engine was given, absent for the derived one) and
 * resolves through the same reading ({@link effectiveControlRootOf}). Refused (`config.memory_reanchor`) when
 * `dir` is not an existing directory, and when that control plane holds neither an anchor nor a store — a
 * mistaken `controlDir` would otherwise record an anchor no opener reads. Moves nothing and says nothing
 * about whether the directory holds the same store. A re-anchor is a transaction of the store: it holds the
 * store's transaction lock ({@link acquireStoreTxnLock}; a commit in progress is waited for, never crossed) and
 * is refused while the control plane owes anything at the recorded root ({@link rootBoundObligationOf}: a
 * committed transaction pending recovery — its journal names paths under the recorded root and is replayed
 * there first, never carried over; with the anchor absent no release from this one on opens the store to replay it, so that
 * refusal names the releases that do). Every live holder judges against the new anchor at its next face.
 * `opts.expectedFrom` is the root the caller confirmed the store moved from — a refusal's `detail.recorded`, handed back as it
 * came: compared character for character, under the anchor's lock and before the re-anchor writes, with the physical root the
 * anchor records; another root, or an anchor that is absent or cannot be read, refuses (`config.memory_reanchor`) and records
 * nothing, so the store a person confirmed is the store re-anchored. Finding the control plane comes first and is an open's own step
 * either way (a plane that travelled with a moved root is brought to its key, {@link effectiveControlRootOf}), so the anchor compared is
 * the one every opener reads. Without it, a damaged anchor is replaced like any other.
 * Discloses `memory.root_reanchored` on `opts.onIncident`.
 */
export declare function reanchorMemoryStoreRoot(dir: string, opts?: {
    controlDir?: string;
    expectedFrom?: string;
    onIncident?: MemoryPartitionIncidentSink;
}): Promise<StoreRootReanchor>;
/** The one remedy every surfaced permission refusal carries — `undefined` unless `err` is a write
 *  the file system refused on PERMISSIONS (`EACCES` / `EPERM`) at a path INSIDE `memoryDir` (a
 *  refusal elsewhere — a control plane kept outside the store — is not this store's to fix). The
 *  engine never changes permission bits on a store — a session's read-only layers are its policy,
 *  not file-system state — so bits that refuse a write were set by someone else, and nothing here
 *  clears them (an engine from 7.30.x or earlier left inherited layers read-only on disk). */
export declare function permissionRemedyOf(err: unknown, memoryDir: string): string | undefined;
/** Attach {@link permissionRemedyOf} to a permission refusal inside `memoryDir` — in place, so the
 *  error keeps its class and `code` (callers branch on both), and once (an inner seat that already
 *  named its store wins over an outer one). Any other value is returned untouched. */
export declare function withPermissionRemedy<T>(err: T, memoryDir: string): T;
/** B2/L4 — the control-plane subdir holding gate-rejected originals. ONE name for all three writers
 *  (engine harvest, engine derived-index rung, backend inbound gate): they write the same directory,
 *  so its name and its permissions must not depend on which of them ran first. */
export declare const QUARANTINE_DIR = "quarantine";
/** REF-A9 — what {@link clearContainedPath} reports back; both hosts escalate `detail` into
 *  their report channel (harvest `quarantineFailures` / inbound `quarantine_failed` findings). */
export interface QuarantineOutcome {
    /** The captured copy: its name among the governance store's `quarantine` objects. Absent ⇔ the capture itself failed. */
    dest?: string;
    /** True ⇔ the model-visible file no longer holds the suspect content (deleted, or tombstoned). */
    removed: boolean;
    /** WHAT this containment left at the model-visible path, which is the only thing a following restore
     *  may overwrite (see {@link restoreContainedBaseline}). ABSENT ⇔ the path was freed. Present ⇔ either
     *  this engine's own tombstone (the clear-in-place rung) or the suspect bytes themselves (neither rung
     *  worked) — in both cases replacing it takes nobody else's work, and in neither case may anything the
     *  restore did not put there be destroyed. A path found rewritten after it was read reports the bytes that
     *  were read: the newer bytes there are not them, so a following restore keeps its hands off. */
    leftOnPlane?: string;
    /** Set on ANY deviation from the clean capture+delete path — never a silent best-effort downgrade. */
    detail?: string;
}
/**
 * Write `content` to `path`, refusing to follow a symlink at the FINAL component (`O_NOFOLLOW`).
 *
 * Every containment write in this domain is a check-then-use: the path was judged in-root when the
 * scan read it, and the write happens later. A symlink dropped in that window turns a containment
 * response — the thing whose job is removing suspect bytes — into a write through the link, i.e.
 * this process putting its own committed memory content wherever the link points. Re-checking
 * before writing cannot close a race; the kernel resolving and rejecting in one step can.
 *
 * SCOPE, stated exactly because the difference matters: `O_NOFOLLOW` constrains the LAST component
 * only. An ANCESTOR directory swapped for a symlink in the same window still redirects the write,
 * and closing that needs per-component `openat`-style traversal from a pinned root descriptor —
 * which Node's `fs` does not expose (there is no relative-open API), so it is not reachable here
 * without native bindings. What this buys is the leaf variant, which is the cheap one; the ancestor
 * variant stays open and is recorded with the rest of the family rather than papered over.
 *
 * Throws like `writeFileSync`, including ELOOP when the final component IS a symlink, and EACCES for a
 * file whose own bits refuse the write. A write changes only the NAME it writes. A file with one name is
 * rewritten in place (its inode and mode stay). A HARD link is the same tamper as a symlink by other
 * means — the file's bytes live under a second name, possibly outside the store, and an in-place write
 * would change them there too — so a file the open finds with more names is never written in place.
 * One such name is the engine's own: a staging name a no-replace restore stopped between its `link` and
 * its `unlink` left beside the file; it is removed first ({@link dropStagingSecondNames}), the interrupted
 * restore's last step. A file that still has another name gets a new file under THIS name, written the
 * way the store commits a file ({@link atomicWriteFileSync}: an exclusive no-follow sibling, 0o600,
 * renamed over this name); the other names keep their file, its bytes and its mode. Residual: a path
 * replaced by another file between the open and that rename is replaced again (the window every
 * rename-based store write has). The in-place write goes through `writeFileSync` on the open descriptor,
 * which writes every byte or throws — a bare `writeSync` may short-write, and reporting a truncated
 * restore as contained (after the truncation already destroyed the destination) is the failure this
 * guard exists to prevent.
 */
export declare function writeFileNoFollow(path: string, content: string): void;
/** {@link writeFileNoFollow}'s NO-REPLACE twin: write `content` only if nothing is at `path`. `"written"`
 *  when the bytes landed, `"kept"` when it was occupied; every other failure throws like the twin (a
 *  write that could not be ATTEMPTED must not read as one that chose not to). `O_EXCL | O_CREAT` is the
 *  atomic form — an `existsSync`-then-write pair is a TOCTOU with exactly the window this closes — and
 *  it refuses a symlink at the final component on its own (POSIX `EEXIST` on a link, dangling or not),
 *  so the twin's no-follow property is kept without a second check. `mode` is the created file's
 *  permission bits (under the process umask): a caller putting bytes back into a seat it vacated passes
 *  the vacated file's, so the seat's permissions are what they were less what the umask clears; with
 *  none passed (the file's bits went with it) the file is created owner-only, {@link PRIVATE_FILE_MODE} —
 *  the File backend's mode for its projections; a copy-out projection's materialize creates at 0644
 *  less the umask, so there a file put back is never wider than its siblings. */
export declare function writeFileNoReplace(path: string, content: string, mode?: number): "written" | "kept";
/**
 * The third twin, for a seat a removal vacated: put `content` back at `path` only where the removal left
 * nothing or blank bytes ({@link carriesEntry}), judged and written through ONE descriptor — a writer that
 * replaces the file by a rename between the look and the write keeps its file (the write lands on the
 * inode that was looked at). `"written"` = the bytes landed; `"kept"` = a file with content stands there
 * (left as found); `"blocked"` = something other than a regular file stands there (a directory, a link, a
 * pipe) — left as found. Nothing there ⇒ {@link writeFileNoReplace}, owner-only (the removed file's bits went
 * with it; the seat is not left wider than the store writes it). A file with more than one name is
 * written the way {@link writeFileNoFollow} writes it (never in place). The in-place write is positional
 * from byte 0 (the read moved the offset past any blank bytes) and loops until every byte is written. Any
 * other failure throws. Residual windows: an in-place writer on the same inode between the read and the
 * truncate; for a file with more than one name, a writer between this close and the twin's open.
 */
export declare function putBackOverNothingOrBlank(path: string, content: string): "written" | "kept" | "blocked";
/** THE minter of every staging name the engine puts beside a plane file while it is displaced:
 *  `<owner>.staging-<ms>-<pid>-<seq>`. One grammar for every site, so one recognizer
 *  ({@link stagingNamePattern}) knows the names the engine can have left beside a seat. */
export declare function mintStagingName(owner: string, now: () => number): string;
/** The grammar {@link mintStagingName} and {@link claimStaging} write, as a recognizer — of ONE owner's
 *  generations when `owner` is given; otherwise of every staging name an engine has minted beside a seat,
 *  for the three owners it mints them for: an instruction hold (`hold-<ms>-<12 hex>`), a copy-out seat a mount
 *  retires (`retired`, projection-ledger.ts) and a crash-residue capture (`<16 hex>-residue-<entry id>.md`,
 *  {@link quarantineObjectNameOf}), whose clock-named
 *  `<ms>-residue-<id>.md` of earlier releases — and the `<ms>-residue-<id>.md.staging` of 7.55.0 and earlier
 *  — are included (a name already on disk does not lose its owner with an upgrade). A prefix or a bare
 *  `.staging-` suffix would adopt any name a writer chose on the strength of its spelling. Minted and
 *  recognised side by side so the two cannot drift. */
/** The staging owner a mount moves a retired copy-out seat aside under (projection-ledger.ts). */
export declare const RETIRED_STAGING_OWNER = "retired";
export declare function stagingNamePattern(owner?: string): RegExp;
/** Take exclusive hold of a staged name by an atomic same-directory rename to a name minted HERE: the
 *  staged name lives in a WRITABLE directory, so a plain read-then-unlink could delete a replacement that
 *  landed between the two while reporting success over the earlier bytes. After the claim, what the rename
 *  moved is what every later read and unlink addresses. Returns the claim when it took, the original when
 *  the directory refused it (a hardening, not a precondition — a caller that removes on the strength of
 *  the claim checks which one it got). Residual: a writer enumerating the directory can still replace the
 *  CLAIM name before it is read — nothing Node's `fs` closes that, and the window is narrower than the one
 *  it replaces. */
export declare function claimStaging(stagingPath: string): string;
/** Whether `path` names the file `ref` describes: a regular file on the same device with the same inode,
 *  read without following a link at `path`. */
export declare function isSameFile(path: string, ref: {
    readonly dev: number;
    readonly ino: number;
}): boolean;
/**
 * Remove every staging name an engine minted ({@link stagingNamePattern}) beside `seat` that is another
 * name of the file `opened` describes — the un-dropped half of a no-replace restore stopped between its
 * `link` and its `unlink`. Called by a write about to replace that file's bytes: removing the name loses
 * nothing the write itself does not overwrite, and touches only names in the engine's staging grammar (a name
 * is read as the engine's own by its spelling and by being the same file, so a hard link someone made and
 * spelled that way goes too; every other hard-link copy, snapshot name and planted link stays, with its file).
 * Not claimed first: a claim is a `rename`, which replaces whatever already stands at the claim name.
 * Residual: a file put at that minted name between the check and the removal is removed — only a writer of
 * this directory can put it there, and it can remove the name itself. Answers how many names went.
 */
export declare function dropStagingSecondNames(seat: string, opened: {
    readonly dev: number;
    readonly ino: number;
}): number;
/**
 * The ONE way a committed baseline goes back after {@link clearContainedPath} emptied its seat —
 * the inverse half of that function, beside it so the removal word and its readers stay in one module.
 * Every containment arm calls it — the engine's and the backend's inbound gate — and
 * the rule is ONE sentence: THE RESTORE MAY ONLY OVERWRITE WHAT THE CONTAINMENT ITSELF LEFT AT THE PATH.
 * The removal's own account of what it left (`leftOnPlane` — nothing, our tombstone, or the suspect
 * bytes) is re-read and compared immediately before the write, through a read that refuses a link, a
 * pipe and anything but a regular file: a caller that awaited the committed store cannot assume what
 * the removal saw still holds, on ANY of the three arms. Anything else — a freed path, a path somebody
 * took back, a path that could not be verified — takes the no-replace write, which is the right answer
 * for all of them at once: it lands iff nothing is there. Residual window: the read-to-open gap, with
 * nothing suspended in it.
 *
 * Declining never weakens containment. Where the suspect bytes were removed they are already in
 * quarantine; where they were NOT, the only way the comparison fails is that somebody replaced them —
 * which took them off the plane as surely as the removal would have.
 *
 * `mode` is the bits a freed path is created with — the caller's own projection mode, owner-only when
 * none is passed (as the store writes its own); a file the containment left in place keeps its own.
 */
export declare function restoreContainedBaseline(path: string, committed: string, leftOnPlane: string | undefined, mode?: number): "written" | "kept" | "failed";
/** What keeping one suspect file's copy came to: the name its copy is kept under among the governance store's
 *  `quarantine` objects, or why no copy could be kept. */
export type QuarantineCapture = {
    readonly name: string;
} | {
    readonly failed: string;
};
/** The governance store's quarantine objects, as a capture writes them. */
export type QuarantineObjects = Pick<import("./types.js").MemoryGovernanceObjects, "putObject" | "getObject">;
/** Write `(kind, name)` once for a writer whose record is the FIRST one under that name (a capture name, a pollution
 *  slot, an imported record): `"created"` ⇔ this call wrote `bytes`; `"existed"` ⇔ an object stands under the name and
 *  reads back — the same bytes (the put answered so), or other bytes the put refused to overwrite: the record that
 *  stands is the first one, and the writer moves on (the next capture name; the standing record's reading). A refusal
 *  no readable object explains (a store that fails, an entry that is no object, a name the store refuses) is the put's
 *  own and is thrown. The File store's synchronous paths take its twin, `putFileControlObjectOnce` (`control-objects.ts`). */
export declare function putControlObjectOnce(objects: Pick<import("./types.js").MemoryGovernanceObjects, "putObject" | "getObject">, kind: import("./types.js").MemoryControlObjectKind, name: string, bytes: Uint8Array): Promise<"created" | "existed">;
/** The longest name a store keeps an object under, in UTF-8 bytes — one file name on the file systems the File store runs on. */
export declare const CONTROL_OBJECT_NAME_MAX_BYTES = 255;
/** The name of a `quarantine` object, one spelling for every copy the engine keeps there (#2877, C-R983 K2):
 *  `<the first 16 hex digits of the SHA-256 of its bytes>-<label>`. The name is a function of the bytes and of what
 *  they are a copy of, never of when they were kept, so the same bytes contained again (a withheld file the model
 *  writes back at every harvest) meet the copy that already stands and keep no second one. `content` is the bytes, or
 *  their SHA-256 in hex when the writer holds only that (a hold's row). The label is the last segment of `source` —
 *  the suspect file's path, or a bare label for a copy that has no plane path — with each character that is no part of
 *  a legal object name or would read as more than one line (a `\`, legal in a POSIX file name; a NUL; any other control
 *  character) spelled as the percent form of its UTF-8 bytes ({@link labelCharSpelled}), and cut between spellings where
 *  the name would pass `CONTROL_OBJECT_NAME_MAX_BYTES − 2` bytes (room for a numbered capture name, `.1` … `.9`): a file
 *  whose own name is as long as a file name can be still gets its copy, and two copies of the same bytes under one long
 *  label still meet. */
export declare function quarantineObjectNameOf(content: Uint8Array | {
    readonly sha256: string;
}, source: string): string;
/** The name a copy is tried under on `attempt` (0…10): its {@link quarantineObjectNameOf} first, then suffixed. Two
 *  different copies can share a base (a digest-prefix collision, or a name something else was planted under), so a
 *  capture is written ONCE (a standing name is never replaced) and suffixed when the name holds other bytes; bounded —
 *  after the numbered tries, one last name keyed by pid+counter (unique within this process) either lands or the
 *  capture fails. */
export declare function quarantineCaptureName(base: string, attempt: number): string;
/** Keep `content` — the already-read bytes of the suspect file at `source`, or of the copy `source` labels (its text,
 *  or the raw bytes of a file read as they lie) — as a `quarantine` object of the governance store. A capture name
 *  holding exactly these bytes already keeps them: the capture answers that name and writes nothing (one copy however
 *  often the same bytes are contained). A name holding other bytes is passed over to the next of the capture names
 *  ({@link quarantineCaptureName}). */
export declare function captureIntoQuarantine(objects: QuarantineObjects, source: string, content: string | Uint8Array): Promise<QuarantineCapture>;
/** The governance store's quarantine objects, as an erasure finds and removes them. A reader that must see damage hands
 *  in the store's damage-visible view (`standingControlObjectsOf`, `consolidation.ts`): for the File store its listing
 *  names every entry standing in the kind's directory; any other store's listing is its own (KL-3466-c). */
export type QuarantineErasureObjects = Pick<import("./types.js").MemoryGovernanceObjects, "listObjects" | "getObject" | "deleteObject">;
/** What one erasure did to the quarantine objects. `removed` — the copies of an erased entry this call deleted;
 *  `remaining` — the copies it could not delete AND the objects it could not read to tell (an object that stands unread
 *  is never read as none of the request's: fail-closed, it keeps the request partial); `unreadable` — how many of
 *  `remaining` are those unread objects; `unattributed` — the objects read whose bytes name no entry id (a fragment, an
 *  index copy), counted and left. */
export interface QuarantineErasure {
    removed: number;
    remaining: number;
    unreadable: number;
    unattributed: number;
}
/**
 * Delete every `quarantine` object whose bytes are a copy of an erased entry — the frontmatter `id` they carry is in `ids`
 * — through the store's object verbs: one law for every carrier, the File store's directory and a database store alike.
 * Only the `quarantine` kind is read and only a name its listing gave is deleted; a pollution marker, an import receipt
 * or a hold's capture is never touched, whatever its bytes say. An object the store answers as gone between the listing
 * and the read or the delete is not counted. A listing that fails (or answers anything but a list of names) throws
 * `ControlPlaneCorruptError` — an enumeration that fails is never an empty kind; the lane that called decides what its
 * attestation says about that (the File face refuses and a replay converges; the degraded lane answers `unverified`).
 */
export declare function eraseQuarantineCopies(objects: QuarantineErasureObjects, ids: ReadonlySet<string>): Promise<QuarantineErasure>;
/**
 * Take the suspect file at `path` off the model-visible plane once its copy is kept (`capture`): unlink it, else
 * clear it to a tombstone in place. `content` is the bytes the caller read and captured; a path that now reads back
 * DIFFERENT bytes is left alone — they were written after the capture was read, so they are not the suspect copy,
 * and removing them would destroy bytes no copy holds (a read that cannot run removes as before: only a successful
 * read of other bytes stops the removal).
 *
 * ONE implementation for the engine's harvest rungs and the backend's inbound gate (REF-A9: two line-for-line twins
 * had drifted twice). The derived-index rung clears its file instead of tombstoning it — the index is rebuilt from
 * entry frontmatter — so it does not come through here.
 */
export declare function clearContainedPath(path: string, content: string, capture: QuarantineCapture): QuarantineOutcome;
/** Keep the copies of a derived file (its already-read `text`) before a containment overwrites it — the index's
 *  clear and its restore, which take whatever stands (the index is derived: its prose has no entry a later judgment
 *  could hang on, so the containment wins over the copy, as a capture that fails never stopped it). The copy is a
 *  store write (`keep`, which awaits), so the file is read again after it (`reread`: the caller's act-gated read that
 *  never follows a link, so a path re-pointed in that window is refused, not copied) and bytes rewritten in that
 *  window are kept too — at most three copies; a file still moving after that has its last version uncopied, and
 *  says so. `landed` ⇔ every version that stood was copied; `failed` says why each that was not. */
export declare function keepCopiesBeforeOverwrite(text: string, keep: (bytes: string) => Promise<true | string>, reread: () => string | undefined): Promise<{
    landed: boolean;
    failed: string[];
}>;
/** The name prefix of {@link atomicWriteFileSync}'s temporary file, created beside its target and renamed onto it.
 *  One spelling for the writer and for {@link STORE_OPEN_ARTIFACTS}. */
export declare const ATOMIC_WRITE_TMP_PREFIX = ".tmp-";
/** The name prefix of the two files a File governance store's open makes at its control plane's top level to try one
 *  hard link, and removes before the open answers (`probeControlPlaneLinks`, `control-objects.ts`; #3512). One
 *  spelling for the probe and for {@link STORE_OPEN_ARTIFACTS}: a probe cut short between its two steps leaves an
 *  inert file, never a record. */
export declare const LINK_PROBE_PREFIX = ".link-probe-";
/** The infix of a stolen lock's tombstone, `<lock directory><infix><unique>`: both mkdir mutexes (the sidecar lock
 *  and the store's transaction lock) rename a crashed holder's lock to it before removing it. One spelling for both
 *  steals and for {@link STORE_OPEN_ARTIFACTS}. */
export declare const LOCK_TOMB_INFIX = ".stale-";
/** The control-plane file holding a File store's durable identity (`{ v: 1, storeId }`) — minted exclusively on the
 *  first READ that needs one, the export faces (the snapshot composite and the governance slice): a bundle names the
 *  store it came from, an empty one too. One spelling for the mint, for {@link readStoreIdentity} and for
 *  {@link STORE_OPEN_ARTIFACTS}. */
export declare const STORE_IDENTITY_FILE = "store-identity.json";
/** The store identity recorded in `controlDir`, or `undefined` when nothing stands there. A file that cannot be read, is
 *  not JSON or is out of shape throws {@link ControlPlaneCorruptError} (a bad identity is never read as "none" — that
 *  would mint a second one). The one reader of the file: the export faces and the store-set census read it alike. */
export declare function readStoreIdentity(controlDir: string): string | undefined;
/**
 * The named artifacts of a File store's mount — the files an OPEN or a READ of the store may leave there, by place
 * and exact name (or fixed prefix); the list the contract `memory.deployment.store_set` names. Opening anchors the
 * root (the anchor, written through a temporary file under its lock) and tries one hard link between two dot-files at
 * the control plane's top level, removed before the open answers (#3512); a read registers the scope it reads (the
 * registry and its commit journal, under the registry's lock); a refused request or a recovery takes the store's
 * transaction lock; a lock found stale is stolen through a tombstone; an export mints the store's identity on its first
 * need ({@link STORE_IDENTITY_FILE}); a registration of two labels that differ only
 * in letter case probes the volume with a dot-file at the memory directory's top level — on any volume, folding or not,
 * on every such registration (`dirCaseFolds`).
 *  - control plane, top level, a file: one of `files`, or a name starting with one of `filePrefixes`;
 *  - control plane, top level, a directory: one of `lockDirs`, or its tombstone `<lock>.stale-…` — the whole tree;
 *  - memory directory, top level, a file: a name starting with one of `memoryFilePrefixes`.
 * Nothing is matched at another depth or by another pattern: a record's name may begin with these spellings (a
 * capture opt-out record is named after its session id, and `.tmp-x` is a session id), so a pattern below the top
 * level would hide it. The anchor, the registry and its journal and the identity are artifacts as an open or a read
 * leaves them, whole ({@link namedArtifactFault}). The list is a promise a host's assertions read: a change to it
 * carries its reason with it.
 */
export declare const STORE_OPEN_ARTIFACTS: Readonly<{
    files: readonly string[];
    filePrefixes: readonly string[];
    lockDirs: readonly string[];
    memoryFilePrefixes: readonly string[];
}>;
/** Whether the non-directory item at `rel` — its path segments under a File store's control plane (`"control"`) or
 *  memory directory (`"memory"`) — is one of {@link STORE_OPEN_ARTIFACTS}. Exported for the closure pins. */
export declare function isStoreOpenArtifact(where: "control" | "memory", rel: readonly string[]): boolean;
/**
 * Whether a File store's mount holds a record: a non-directory item under its control plane or its memory directory
 * that is not one of {@link STORE_OPEN_ARTIFACTS} — a file only a write leaves. Opening the store, reading it and a
 * request it refused leave named artifacts only, so none of them makes the mount hold a record; a write lands at
 * least one file that is not named (a ledger, an evidence row, an entry, a capture record). A directory that cannot
 * be read — any failure but absence; a link that leads nowhere, at it or above it, is no absence — counts as holding
 * one: a store may be there, and opening it says what is; so does a named artifact that stands but cannot be read as
 * what it is (the root anchor, the scope registry or its journal, the store identity that is a link, not a regular
 * file, unreadable, not JSON or out of shape — an open or a read leaves them whole; see {@link namedArtifactFault}). Read from the disk at each call. This answers "does a store live on this mount"; whether a root must stay guarded
 * by its anchor is {@link controlPlaneHoldsStore}'s question.
 */
export declare function storeHoldsRecord(memoryDir: string, controlDir: string): boolean;
/**
 * Whether a File store holds anything a new, empty store recorded in its place would lose — what makes a zero-copy store one this
 * process saw ({@link storeAbsence}): the census of {@link storeHoldsRecord}, less what a session's mount keeps there while nothing is
 * written: every item it lists is judged by {@link isStoreContent}, the judge a landed write is judged by too.
 *
 * Two questions, two predicates: {@link storeHoldsRecord} answers "does a store live on this mount" — a deployment's store set and
 * the anchor's moved-root guard read it, and a store that served a session lives there even if nothing was written; this one answers
 * "would a new, empty store here lose something", which only the table's write condition at an anchor check asks.
 */
export declare function storeHoldsContent(memoryDir: string, controlDir: string): boolean;
/**
 * The first fault among a File store's named artifacts ({@link STORE_OPEN_ARTIFACTS}`.files`), or `undefined`: the one answer
 * {@link storeHoldsRecord} counts a mount as holding a store by and an open of that mount refuses by. A mount in a deployment's
 * store set because its anchor, registry or journal cannot be read is opened as one fault — the same for the anchor (which the
 * store's constructor already refuses) and for the registry (which only a first read refuses): one reading of "damaged", one
 * loudness.
 */
export declare function storeOpenArtifactFault(memoryDir: string, controlDir: string): ControlPlaneCorruptError | undefined;
/** S2-B — the File governance store's file for the `announcements` document (the queued memory-change
 *  announcements, drained at session-first inject): one file, one bounded queue PER SCOPE inside it (see
 *  {@link enqueueMemoryAnnouncement}). */
export declare const ANNOUNCEMENTS_FILE = "announcements.json";
/** S2-B — bounded queue, per scope: overflow FOLDS (oldest dropped, counted) instead of growing
 *  unbounded. The bound, the fold count and the standing-condition sweep are all one scope's —
 *  a scope that floods its own queue never pushes another scope's notices out. */
export declare const MEMORY_ANNOUNCEMENTS_MAX = 20;
/** S2-C — per-file write-rejection counts (the beforeWrite silent-reject fuse; O-F9/C-F7: scoped
 *  state in `.engine/`, so the count survives suspend/resume and backend re-construction). */
export declare const SCAN_FUSE_FILE = "scan-fuse.json";
/** Rejections at which the write-time feedback mutes (S2-C: 拒 ≥3 次熔断为静默拒). */
export declare const SCAN_FUSE_THRESHOLD = 3;
/** Options of {@link acquireSidecarLock}. `waitCapMs` exists FOR the wait-bound pins (same hook shape
 *  as the file backend's txn-lock timings) — production callers leave it at {@link LOCK_WAIT_CAP_MS}. */
export interface SidecarLockOptions {
    onDeadline?: "proceed" | "throw";
    waitCapMs?: number;
}
/** Cross-process mutex via mkdir (atomic on POSIX). A lock older than {@link LOCK_STALE_MS} is
 *  presumed crashed and stolen; after the wait cap we proceed anyway (fail-open — these sidecars are
 *  not CAS-load-bearing, and wedging a session start on a lock would be worse).
 *
 *  opus 1.258 review (MED, steal TOCTOU): a bare rmSync+mkdir steal lets TWO stealers both win (B's
 *  force-rm deletes A's FRESH lock). The steal is made single-winner by an atomic `renameSync` of the
 *  stale lock dir to a unique tombstone first — rename is atomic, exactly one racer succeeds; the
 *  loser's rename throws ENOENT and it loops back to a normal mkdir wait. The deadline branch keeps
 *  the documented proceed-anyway semantics but steals through the same single-winner gate.
 *
 *  Wait-bound (ruled 2026-08-04): EVERY round runs the same three steps — attempt, diagnose, then
 *  the deadline check and the pause. The two "retry immediately" shortcuts this loop used to take
 *  (holder released between mkdir and stat; steal attempted) skipped both of the last two, so a
 *  condition that keeps answering the same way spun this synchronous loop at full speed and never
 *  reached its own cap. Only a held lock (EEXIST) is waited on: a lock directory that cannot be created
 *  (read-only mount, full volume, revoked permission, a missing parent) throws its own error at once. */
export declare function acquireSidecarLock(lockDir: string, opts?: SidecarLockOptions): string;
/** 证伪式复审 L2-analog: re-verify the owner token at the COMMIT POINT — a stolen-from holder
 *  aborts instead of writing over the stealer. A FOREIGN token always aborts (positive proof the
 *  lock is someone else's now). What an ABSENT/UNREADABLE owner file means splits by caller family
 *  (backlog #255): the fail-closed LEDGER family (`"strict"` — challenges/lineage via
 *  lockedStrictUpdate) treats unprovable ownership as lost — those sidecars promise their commit
 *  point is fenced, and "cannot disprove" is not a fence; the fail-open calibration family
 *  (`"lenient"`, the pre-#255 shape — e.g. the scope registry, whose sidecars self-heal at the next
 *  locked update) keeps the leniency, because its token writes are best-effort and an absent owner
 *  file there is the documented pre-token degraded shape, not evidence of a steal. */
export declare function assertSidecarLockOwnership(lockDir: string, token: string, what: string, mode?: "strict" | "lenient"): void;
/** What a drain or a peek answers for the scopes it was asked about. */
export interface DrainedMemoryAnnouncements {
    /** The asked scopes' fold counts, summed. */
    folded: number;
    /** The asked scopes' announcements, in enqueue-time order. */
    queue: MemoryAnnouncement[];
    /** Notices found in the queue file WITHOUT a scope (the pre-per-scope file form, or a hand-written
     *  line): they belong to no queue, so no session ever reads them — they are discarded on the first
     *  locked rewrite and only their number is kept, for the operator face. A drain hands the number
     *  over once and resets it; a peek reports it without resetting. */
    unscopedDiscarded: number;
}
/** Say a refused notice filing to the host (`memory.announce_failed`): which filing (`stage`) and why. Every
 *  place that files a notice is fail-open and says this when the queue refuses (the engine's router, the File
 *  backend's store notices). No sink ⇒ nothing said; a throwing sink never propagates — it must not
 *  re-introduce the fault the fail-open avoids, nor recurse into the queue. */
export declare function sayAnnounceFailure(sink: MemoryPartitionIncidentSink | undefined, stage: string, cause: unknown): void;
export declare const PATCH_PLAN_IO_CONFLICT_REASON = "planning_io_error: patch planning failed (see operator incident log for details)";
export declare function bindImportPlanIncidentSink(plan: object, sink: MemoryPartitionIncidentSink | undefined): void;
export declare function sanitizeImportPatchConflicts(conflicts: readonly {
    readonly id: string;
    readonly reason: string;
}[], plan: object, fallbackSink: MemoryPartitionIncidentSink | undefined, planFaults: ReadonlyMap<string, unknown>): Array<{
    id: string;
    reason: string;
}>;
export declare function normalizeReplayedImportReport<T extends {
    conflicts: Array<{
        id: string;
        reason: string;
    }>;
}>(report: T, plan: object, fallbackSink: MemoryPartitionIncidentSink | undefined): T;
/**
 * S2-B — enqueue one announcement into the governance store's `announcements` document (one serialized
 * `updateDoc`; bounded with overflow folding). What the queue means — the per-scope bound, the fold, the
 * standing-condition sweep below — is this function's `fn`; the store only keeps the document. The File
 * store writes it before this call's first await (its update is synchronous underneath), so a caller that
 * does not wait still finds the line on disk when the call returns, as it did when the queue was a file.
 *
 * `opts.supersedesPrefix` (#495) declares this announcement to be a STANDING CONDITION — one whose
 * sentence is re-derived at every entry point until the condition clears — and names the family it
 * belongs to by line prefix. Every queued line of that family is a STALE READING of the same
 * condition, so the queue is made to hold exactly one of them, always the current one:
 *   · the identical line already queued unread ⇒ no-op, and no write at all;
 *   · otherwise every queued item with that prefix is dropped and this one appended.
 * Merely SKIPPING a repeat is not enough, and that was the first form of this: a condition that goes
 * A → B → A inside one unread window would leave `A, B` in the queue and a reader looking at B as the
 * latest state — the fix for a flood turning into a wrong answer. Replacement makes the last word the
 * true one.
 *
 * All of it runs INSIDE the locked read-modify-write, which is the point: a caller that peeked first
 * and enqueued after would race a concurrent drain, and two processes could both peek-miss.
 * Deliberately keyed on the LINE, not on a structural id — two states that render the same sentence
 * are, to every consumer, the same statement. Deliberately opt-in: an ordinary event repeating IS
 * news, and only its author knows which kind it is. Callers using it pass ONE item (a standing
 * condition is one sentence), and the prefix must name the family precisely — anything else sharing
 * it would be dropped as a stale sibling.
 */
export declare function enqueueMemoryAnnouncement(docs: MemoryGovernanceDocs, ann: MemoryAnnouncement, opts?: {
    supersedesPrefix?: string;
}): Promise<void>;
/**
 * S2-B — drain the queues of `scopes` (session-first inject, 时机①): returns what those scopes had
 * queued and resets exactly them. Every other scope's queue is left as it was, for the session that
 * mounts it — the drain that empties a queue is a reader of that queue, never a bystander. A document
 * never written answers empty without an update (no lock, no write).
 */
export declare function drainMemoryAnnouncements(docs: MemoryGovernanceDocs, scopes: readonly string[]): Promise<DrainedMemoryAnnouncements>;
/** Test/observability peek of `scopes` (the document as last committed, non-destructive). */
export declare function peekMemoryAnnouncements(docs: MemoryGovernanceDocs, scopes: readonly string[]): Promise<DrainedMemoryAnnouncements>;
/**
 * Move every scope's queue from one store's `announcements` document to another's (a mount-key switch
 * re-homes a control plane, and the notices queued under the old key must not be orphaned — meaningful
 * between two File stores; a store keyed by scope has nothing to move). Each line keeps its scope; the
 * destination's per-scope bounds apply once the lines land, and the fold counts are carried. The only
 * whole-document read there is: it hands lines to the same scopes' queues elsewhere, never to a reader.
 * The move is three steps (read, destination, retirement): a drain of the source between the read and the
 * retirement, a second move of the same source, or a retry after a failed retirement can leave a line (and
 * a fold count) in both places — over-delivery, never loss (KL-3307-c). The Runner moves a queue once per
 * marker switch: its hint is read and recorded in one synchronous step (`prepare-memory.ts`).
 */
export declare function transferMemoryAnnouncements(from: MemoryGovernanceDocs, to: MemoryGovernanceDocs): Promise<void>;
/** The fuse key for a memory file: the ledger form `(scope, rel)` (`rel` relative to the scope's
 *  home, `/`-separated) — location-free, so a home move never re-keys a count. */
export declare function scanFuseKey(scope: string, rel: string): string;
/** S2-C — record one write-time scan rejection for `key` ({@link scanFuseKey}); returns the count
 *  BEFORE this bump (callers mute the feedback when it is already ≥ {@link SCAN_FUSE_THRESHOLD}). */
export declare function bumpScanFuse(controlDir: string, key: string): number;
/** S2-C — the current fuse count for `key` (0 = never rejected / cleared). */
/** The derived-index snapshot: target → the entry rev and the index line AS OF the last rebuild whose
 *  index landed. It answers one question for {@link indexLineIsStale}: did the entry change since the
 *  line was written while the line did not (the injected index would otherwise answer the OLD value
 *  to the next session)? `line` is in {@link normalizeIndexLine} form, and absent for a snapshot an
 *  older engine wrote (a bare rev string): the line is then unknown, so nothing is judged stale.
 *  Control plane, best-effort, fail-open (absent/corrupt ⇒ {}). */
export interface IndexRevSnapshot {
    rev: string;
    line?: string;
}
export declare function readIndexRevs(controlDir: string): Record<string, IndexRevSnapshot>;
/** The comparison form of an index line: trimmed, every run of whitespace one space. Case and every
 *  visible character stay — only a whitespace difference reads as "the model did not re-word it". */
export declare function normalizeIndexLine(line: string): string;
/** Whether one line of a memory index (`MEMORY.md`) holds text — THE reading of a blank index line: the index rebuild keeps a line of
 *  prose only when it does (and drops the trailing blanks), and the census counts an index as memory only when one of its lines does
 *  ({@link isMemoryContent}). Blanks, a newline's carriage return and a byte-order mark are no text. */
export declare function indexLineHoldsText(line: string): boolean;
/** The one judge of a model-worded index line: stale = the entry's rev moved since the snapshot AND the
 *  line is still the text the snapshot recorded (the model has not re-worded it since), both sides
 *  compared in {@link normalizeIndexLine} form. A line the model changed is its own word and wins; a
 *  snapshot without a line cannot say, so it never judges stale. */
export declare function indexLineIsStale(snapshot: IndexRevSnapshot | undefined, entryRev: string, line: string): boolean;
export declare function writeIndexRevs(controlDir: string, revs: Record<string, Required<IndexRevSnapshot>>): void;
export declare function scanFuseCount(controlDir: string, key: string): number;
/**
 * @contract memory.session_incarnation.proven_mismatch_only — only a PROVEN mismatch (both sides
 * known and different) separates a record from the identity reading it; an absent incarnation on
 * either side — a record written before the axis existed, a deployment that wires no resolver, a
 * resolver that threw, a synthesized fail-closed record, a record imported from another plane —
 * always BINDS, which is the pre-incarnation behavior. Every leg's conservative direction is
 * therefore its old one, and the only way to lose a binding is to prove it belongs to someone else.
 */
export declare function sessionRecordBindsIncarnation(recorded: string | undefined, asking: string | undefined): boolean;
/** The incarnation this layer ACTS on: an unusable token is the unnamed occupant, never a throw. */
export declare function usableSessionIncarnation(raw: string | undefined): string | undefined;
/** The control objects one session record kind is kept through (`pollution`, `capture`). */
type SessionRecordObjects = Pick<import("./types.js").MemoryGovernanceObjects, "putObject" | "getObject" | "listObjects">;
/** How a per-session record read names the identity reading; absent ⇒ every record binds. */
export interface SessionIdentityRead {
    incarnation?: string;
    /** Called when a standing record was SET ASIDE as another occupant's, with the incarnation it carries — never silent. */
    onSeparated?: (recorded: string) => void;
}
/** Directory (under the control plane) holding one marker file per polluted session. */
export declare const SESSION_POLLUTION_DIR = "session-pollution";
export interface SessionPollutionRecord {
    at: number;
    reason: string;
    /** design/336 §2.2 — the structured mechanical cause of the exposure (the value an origin marker
     *  minted off this record carries). ADDITIVE: records written before the field existed read as
     *  honestly cause-less (the mint then falls back to `"observed"`); old readers narrow-take the
     *  two fields they know. */
    cause?: import("./types.js").MemoryOriginCause;
    /** the occupant that minted this record ({@link sessionRecordBindsIncarnation}). ADDITIVE:
     *  absent (no resolver wired, or written before the axis) ⇒ it binds every occupant. */
    incarnation?: string;
}
/** The part of a governance store the session pollution markers are kept through: its control objects of kind
 *  `pollution`, one per record slot ({@link sessionRecordName}). */
export type SessionPollutionObjects = Pick<import("./types.js").MemoryGovernanceObjects, "putObject" | "getObject" | "listObjects">;
/**
 * Mark `sessionId` polluted (idempotent; the FIRST record wins — the object is written once, never replaced).
 *
 * The outcome distinguishes the two ways a durable marker can exist after the call, because the
 * write-once create is the only ATOMIC answer to "who made this transition" available anywhere in the
 * stack (#324a, adversarial-review round 5): a check-then-act pre-read lets two concurrent markers
 * of one session both believe they were first, and a once-per-session disclosure keyed on that would
 * announce twice. `"created"` ⇔ THIS call minted the marker; `"existed"` ⇔ it was already there (a
 * repeat mark, a resumed session, or a racing peer that won the create); `"unpersisted"` ⇔ the marker
 * could not be written at all — the caller must keep its own in-memory mark and disclose (the session
 * stays polluted for this process either way).
 */
export type SessionPollutionMarkOutcome = "created" | "existed" | "unpersisted";
export declare function markSessionPolluted(objects: SessionPollutionObjects, sessionId: string, reason: string, now: () => number, cause?: import("./types.js").MemoryOriginCause, incarnation?: string): Promise<SessionPollutionMarkOutcome>;
/** Read the durable pollution record for `sessionId` (undefined = no marker).
 *  A marker that EXISTS still reads as polluted whether or not its bytes can be read or parsed
 *  (fail-closed: neither corruption nor an unreadable object may launder the state) — a synthesized
 *  record stands in. Only ABSENCE is clean: a store that cannot answer whether a slot stands reads as
 *  polluted, never as clean (the store's law — a fault is never an absence). */
export declare function readSessionPollution(objects: SessionPollutionObjects, sessionId: string, identity?: SessionIdentityRead): Promise<SessionPollutionRecord | undefined>;
/**
 * design/178 v2-c §3-3 — enumerate EVERY durable pollution marker (the export snapshot's pollution
 * face; `readSessionPollution` stays the per-session read). Same fail-closed record posture as the
 * per-session read: a marker that stands but cannot be read or parsed answers a synthesized
 * record, never a silent omission (corruption must not launder the state out of an export). A kind
 * with no objects is the genuine empty state; an enumeration failure THROWS (the store's law) — a
 * listing that silently dropped markers would export a package that launders pollution.
 */
export declare function listSessionPollution(objects: SessionPollutionObjects): Promise<Record<string, SessionPollutionRecord>>;
/**
 * design/178 v2-c §5.3 — the STRICT durable pollution import. Deliberately NOT
 * `markSessionPolluted`: that leg is best-effort-with-disclosure and mints its own `at`, so a
 * bundle's source record (the governance fact being carried) could neither land verbatim nor prove
 * durability. This leg writes the SOURCE record verbatim (written once); when the slot already stands
 * it reads the standing record back and COMPARES — equal = converged no-op, different = the
 * destination's first-mark-wins record stands and the divergence is REPORTED (`"divergent"`), never
 * silently absorbed. A write failure THROWS (the import aborts with its latch standing — §1-2⑤).
 */
export declare function importSessionPollution(objects: SessionPollutionObjects, sessionId: string, record: SessionPollutionRecord): Promise<"written" | "already" | "divergent">;
/** Directory (under the control plane) holding one record file per capture-opted-out session. */
export declare const SESSION_CAPTURE_OPTOUT_DIR = "session-capture-optout";
/** The durable capture opt-out record. `reason` is host/engine-authored (the declaring channel),
 *  never model text. */
export interface SessionCaptureOptOutRecord {
    at: number;
    reason: string;
    /** the occupant that declared this opt-out ({@link sessionRecordBindsIncarnation}).
     *  ADDITIVE: absent ⇒ binds every occupant, which is also where a carrier that drops it lands. */
    incarnation?: string;
}
/** Outcome vocabulary shared with the pollution marker (the same one-way form, written once): `"created"` ⇔ THIS
 *  call minted the record; `"existed"` ⇔ already recorded (a resumed session / an idempotent
 *  re-declaration); `"unpersisted"` ⇔ the record could not be written — the CALLER must refuse to
 *  run (design/383 §2.8: an opt-out that only holds in-process is broken by the first resume, so
 *  "could not persist" is a named refusal, never a silent in-process-only degrade — the deliberate
 *  divergence from the pollution marker's best-effort arm). */
export type SessionCaptureOptOutMarkOutcome = "created" | "existed" | "unpersisted";
/** The part of a governance store the capture opt-out records are kept through: its control objects of kind `capture`,
 *  one per record slot ({@link sessionRecordName}). A reader that must tell a record that stands unreadable from a store
 *  that cannot answer hands in the store's damage-visible view (`standingControlObjectsOf`, `consolidation.ts`): its
 *  listing names every entry standing where a record belongs. */
export type SessionCaptureObjects = SessionRecordObjects;
/** Mark `sessionId` capture-opted-out (idempotent; the FIRST record wins — the object is written once, never replaced).
 *  Incarnation law: first-record-wins is per IDENTITY — a new occupant whose declaration meets a stranger's standing
 *  record mints its own slot instead of answering `"existed"` ({@link sessionRecordName}). Never throws: a record that
 *  cannot be written, or a slot that stands as no readable object, answers `"unpersisted"` (the caller refuses to run). */
export declare function markSessionCaptureObjects(objects: SessionCaptureObjects, sessionId: string, record: SessionCaptureOptOutRecord): Promise<SessionCaptureOptOutMarkOutcome>;
/** Read the durable capture opt-out record for `sessionId` (undefined = capture is on). Fail-closed exactly like the
 *  pollution read: a record that STANDS but cannot be read or parsed answers opted-out (a synthesized record stands in).
 *  Only ABSENCE reads as "capture on". A store that cannot establish whether a record exists THROWS — the engine's
 *  `sessionCaptureOptOutOrFault` catch turns it into the INDETERMINATE fault axis (the same fail-closed suppression,
 *  honestly attributed: an outage is never reported as a user request). `objects` is the damage-visible view. */
export declare function readSessionCaptureObjects(objects: SessionCaptureObjects, sessionId: string, identity?: SessionIdentityRead): Promise<SessionCaptureOptOutRecord | undefined>;
/**
 * Enumerate EVERY durable capture opt-out record (the consolidation eligibility arm's roster read — design/383 §2.4).
 * Same fail-closed posture as {@link listSessionPollution}: a record that stands but cannot be read answers synthesized
 * (never silently omitted); a kind with no objects is the genuine empty state; an enumeration failure THROWS — a listing
 * that silently dropped records would let the distiller amplify content its author asked to withhold.
 */
export declare function listSessionCaptureObjects(objects: SessionCaptureObjects): Promise<Record<string, SessionCaptureOptOutRecord>>;
/**
 * design/383 §2.1b — the control-plane carrier a HOST may substitute for the capture opt-out
 * record's read/write/list (server F1: on a stateless multi-replica deployment the file form is
 * invisible to the resume replica — "record not found" would break exactly toward capture). The
 * core default (#3484) is the `capture` objects of the governance store the engine keeps its documents
 * in (`governanceCaptureRecordStore`, `consolidation.ts`): the File store's directory — byte-identical
 * names and bytes — or the store the backend carries, the same for every replica that opens it.
 * CONTRACT (each leg mirrors the objects' law above):
 *  - `mark` is create-only/first-record-wins and must answer `"unpersisted"` (never throw) when the
 *    carrier cannot durably land the record;
 *  - `read` is fail-closed: a record that exists but cannot be decoded answers a synthesized
 *    record, never `undefined`; a store that cannot establish whether a record EXISTS (an outage)
 *    may THROW — the engine treats a throwing read as the INDETERMINATE fault axis (commit
 *    boundaries suppress fail-closed), which is the honest answer there: it must not fabricate a
 *    record ("a user request that never happened") and must not answer `undefined` ("no record"
 *    breaks exactly toward capture);
 *  - `list` throws on an enumeration failure (an unreadable roster is not an empty one).
 * DUAL FORM (#511 件2, additive): each leg may answer `T` OR `Promise<T>` — a SQL/remote carrier is
 * async by nature and could not implement the sync-only trio at all. Every core consumption point
 * awaits (or `.then`-chains where a sync public seat must stay sync-transparent), so a sync store's
 * behavior is unchanged and an async store's Promise legs keep the exact same contract per leg:
 * a rejected `mark` promise is held to the `"unpersisted"` refusal arm, a rejected `read` promise
 * is the INDETERMINATE fault axis, a rejected `list` promise propagates as the enumeration failure.
 */
export interface SessionCaptureRecordStore {
    mark(sessionId: string, record: SessionCaptureOptOutRecord): SessionCaptureOptOutMarkOutcome | Promise<SessionCaptureOptOutMarkOutcome>;
    /** `identity` names the occupant asking (absent ⇒ every record under the id binds, which is
     *  also what a carrier that ignores the parameter keeps — no carrier has to change). One that DOES
     *  persist the field keys its rows by (sessionId, incarnation): first record per IDENTITY wins. */
    read(sessionId: string, identity?: SessionIdentityRead): SessionCaptureOptOutRecord | undefined | Promise<SessionCaptureOptOutRecord | undefined>;
    list(): Record<string, SessionCaptureOptOutRecord> | Promise<Record<string, SessionCaptureOptOutRecord>>;
}
/** The retrieved-account sidecar (control plane): entry id → { count, lastAt }. */
export declare const USAGE_RETRIEVED_FILE = "usage-retrieved.json";
/** Bound on tracked ids — over the cap, the entries with the OLDEST `lastAt` are evicted first
 *  (a popularity account tolerates forgetting cold ids; unbounded growth does not tolerate itself). */
export declare const USAGE_RETRIEVED_MAX_IDS = 4096;
/** One retrieved-account row. */
export interface RetrievedAccountRow {
    count: number;
    lastAt: number;
}
/** Record one retrieval (a search/get hit actually RETURNED to the model) for each id. Journaled +
 *  locked like every sidecar; throws propagate to the caller, which treats them fail-open. */
export declare function recordRetrievedAccount(controlDir: string, ids: readonly string[], now: () => number): void;
/** Journal-aware read of the retrieved account (observability/tests; nothing in the engine's
 *  retention/ranking paths consumes it — see the section note). */
export declare function readRetrievedAccount(controlDir: string): Record<string, RetrievedAccountRow>;
/** S2-C — clear the fuse for files harvest just ACCEPTED (a committed write resets the strike count). */
export declare function clearScanFuse(controlDir: string, keys: Iterable<string>): void;
/** The write-ahead harvest lineage ledger (control plane, fail-closed). */
export declare const LINEAGE_FILE = "lineage.json";
/** The challenge generation-event ledger (control plane, fail-closed). */
export declare const CHALLENGES_FILE = "challenges.json";
/** The design/336 delegation-settlement ledger (control plane, fail-closed). */
export declare const DELEGATION_SETTLEMENT_FILE = "delegation-settlement.json";
/** The design/336 session open/close account (control plane, fail-closed). */
export declare const SESSION_ACCOUNTS_FILE = "session-accounts.json";
/** A governance document's File coordinates. A name outside {@link MEMORY_GOVERNANCE_DOC_NAMES} is refused
 *  (`memory.governance_doc_unknown`) — never mapped to a file of its own. */
export declare function fileGovernanceDocOf(name: MemoryGovernanceDocName): {
    readonly file: string;
    readonly what: string;
};
/** Per-commit lineage AUDIT history (bookkeeping, fail-open, bounded rotation) — the load-bearing
 *  queries never read it; it exists so the deduped contribution set is not the only trace. */
export declare const LINEAGE_AUDIT_FILE = "lineage-audit.json";
/** Bound on retained audit rows (oldest rotated out first). */
export declare const LINEAGE_AUDIT_MAX_ROWS = 2048;
/** The challenged-history account (design/180 B-3: collect-only, fail-open bookkeeping —
 *  the mechanical shadow of "user saw a retrieved entry and corrected it in the same session"). */
export declare const CHALLENGED_HISTORY_FILE = "usage-challenged-history.json";
/** The locked, journaled, FAIL-CLOSED sidecar update. `coerce` must throw
 *  {@link ControlPlaneCorruptError} on any unacceptable shape; only ENOENT reads as the empty
 *  initial state (`undefined` handed to `coerce`). Exported module-level (not on the root barrel)
 *  for the strict-account family's siblings (design/336 slice 2: the delegation-settlement /
 *  session-account / instruction-hold sidecars live in their own module but MUST be this exact
 *  lock+journal discipline — a second implementation would be a drift seam). `onUnreadable` is for a
 *  record whose loss only narrows what it lets happen (the copy-out projection ledger): a journal or file
 *  that cannot be read is then answered by it instead of refused, and the next write replaces both. */
export declare function lockedStrictUpdate<S, T>(controlDir: string, fileName: string, what: string, coerce: (raw: unknown) => S, fn: (current: S) => {
    next?: S;
    result: T;
}, onUnreadable?: (err: ControlPlaneCorruptError) => S): T;
/** Remove a fail-closed sidecar under its lock (a journal rolls forward first) when `removable` answers `true` for its
 *  committed value — the delete half of handing a document over to another store (#3484: the control-plane adoption
 *  removes the replica's copy once the carrier holds the same value). Answers `"removed"`, `"absent"` (nothing stood)
 *  or `"kept"` (`removable` refused the value). Same lock and ownership fence as {@link lockedStrictUpdate}. */
export declare function lockedStrictRemove(controlDir: string, fileName: string, what: string, removable: (committed: unknown) => boolean): "removed" | "absent" | "kept";
/** Lock-less strict READ (journal-aware): a parseable journal wins (committed next state); an
 *  unparseable journal, or an unreadable/unparseable file, is corrupt. Exported module-level for
 *  the strict-account family's siblings (see {@link lockedStrictUpdate}). */
export declare function readStrictSidecar(controlDir: string, fileName: string, what: string): unknown;
/** One committed contribution: session → entry, latest rev/at only (the load-bearing invariant is
 *  "which sessions contributed this id", not the per-commit history — that is the audit account). */
export interface LineageContribution {
    lastRev: string;
    lastAt: number;
    /** the occupant that made this contribution, carried from the staged txn at promotion as
     *  `marked` is. Absent ⇒ unknown ⇒ the row answers every occupant of the id (the old superset). */
    incarnation?: string;
    /** design/336 — carried from the staged row at promotion: the contribution's content (at
     *  `lastRev`) carries its external-origin marker, so the pollution retroaction sweeps owe it no
     *  challenge (the account travels with the entry). Absence = unmarked content — the sweeps'
     *  domain (older vintages read as unmarked, the conservative side). */
    marked?: true;
    /** `"overlap"` ⇔ this session never committed the entry: it was another live writer of the layer
     *  while a committing session's window ran, so the bytes may be its ({@link MemoryAttribution}).
     *  Such a row carries no incarnation (it binds every occupant of the id). Absent ⇔ the session
     *  committed the entry — an overlap landing on that row later keeps it so ({@link landContribution}). */
    attribution?: Extract<MemoryAttribution, "overlap">;
}
/** One staged (pre-commit) row: an entry this transaction WOULD commit. `kind: "latch-only"` marks
 *  a bundle-import SYNTHETIC latch row (design/178 v2-c §1): it withholds the id on the model-visible
 *  read faces exactly like a real staged row, but it is NOT a contribution — the erasure lane's
 *  capture-and-clear strikes it without crediting its txn's sessionId, and the host adjudication
 *  refuses to touch its transaction (the import protocol's receipt-gated release is the only exit). */
export interface LineagePendingRow {
    entryId: string;
    rev: string;
    kind?: "latch-only";
    /** design/336 — set ⇔ the staged content CARRIES its external-origin marker (`frontmatter.origin`
     *  in the very rev this row names): the exposure account travels WITH the entry, so promotion
     *  settlement owes it no pollution challenge (challenging it would re-quarantine a tag-admission
     *  at the read face). Absence = the row's content is unmarked (older vintages included) — the
     *  conservative side: an unmarked row of a marked session is challenged. */
    marked?: true;
    /** The session this row is a contribution of, when it is not the transaction's own: another live
     *  writer of the layer in the committing window. Present ⇔ `attribution` is `"overlap"`; the row then
     *  promotes under this session with no incarnation. */
    sessionId?: string;
    attribution?: Extract<MemoryAttribution, "overlap">;
}
/** One staged transaction: rows land BEFORE `applyPatches`; the commit credential lands after it
 *  succeeds; promotion consumes both. A pending txn without a credential is the crash window —
 *  it is NEVER auto-discarded (design/180 r5: the applyPatches-success→credential-write gap is
 *  undecidable on the pinned backend contract; the host adjudicates via the explicit API). */
export interface LineagePendingTxn {
    sessionId: string;
    at: number;
    rows: LineagePendingRow[];
    /** the occupant that staged this transaction, carried onto every contribution it
     *  promotes. Absent ⇒ unknown occupant, which binds every reader of the id. */
    incarnation?: string;
    /** Present ⇔ `applyPatches` returned and its applied set was durably recorded. */
    credential?: {
        appliedIds: string[];
        at: number;
    };
    /** design/178 v2-c §1 — present ⇔ this txn is a bundle-import SYNTHETIC LATCH: it never promotes
     *  (no credential is ever written), the generic adjudication REFUSES both arms on it, and the only
     *  release channel is {@link releaseImportLatch} (durable completion-receipt precondition). An
     *  older binary reads it as an ordinary uncredentialed pending txn and reports it undecidable —
     *  the accepted mixed-version posture (the drain precondition of the ledger family applies). */
    kind?: "latch-only";
}
/** Stage this transaction's would-commit rows BEFORE `applyPatches` (write-ahead). Throws on any
 *  write/lock/corruption failure — the caller refuses the whole harvest (fail-closed). */
export declare function stageLineagePending(docs: MemoryGovernanceDocs, txnId: string, sessionId: string, rows: readonly LineagePendingRow[], now: () => number, incarnation?: string): Promise<void>;
/** Discard a staged transaction that never reached `applyPatches` (the pre-commit abort path —
 *  step ③ of the handshake, or a refused commit). Safe by construction: nothing was committed. */
export declare function discardLineagePending(docs: MemoryGovernanceDocs, txnId: string): Promise<void>;
/** Record the commit credential — `applyPatches` returned, these ids were APPLIED (non-delete ops).
 *  Written before promotion so a crash between the two converges by credential, never by reading
 *  the backend's current state back (design/180 r4: later syncs/updates rewrite that scene). */
export declare function recordLineageCredential(docs: MemoryGovernanceDocs, txnId: string, appliedIds: readonly string[], now: () => number): Promise<void>;
/** What one promotion moved into the committed set. */
export interface LineagePromotion {
    entryId: string;
    sessionId: string;
    rev: string;
    /** design/336 — carried through from {@link LineagePendingRow.marked}: the promoted content
     *  already carries its external-origin marker, so promotion settlement skips the pollution
     *  challenge for it. */
    marked?: true;
}
/** Promote a CREDENTIALED pending transaction: rows named by the credential's applied set join the
 *  committed contribution set (deduped by (entryId, sessionId) — a repeat pair takes the incoming
 *  lastRev and the credential's date, never grows the set); rows NOT in the applied set (conflicted/refused ops) are
 *  dropped without ever becoming ancestry. Throws when the txn is unknown or uncredentialed. */
export declare function promoteLineagePending(docs: MemoryGovernanceDocs, txnId: string): Promise<LineagePromotion[]>;
/** The host adjudication for the UNDECIDABLE crash window (a pending txn with no credential —
 *  design/180 r5: never auto-discarded). `"promote"` = the host verified the commit landed (all
 *  staged rows join the committed set); `"discard"` = the host verified it did not. Idempotent on
 *  an unknown txn. Also accepts a credentialed txn (then `"promote"` follows the credential). */
export declare function adjudicateLineagePending(docs: MemoryGovernanceDocs, txnId: string, action: "promote" | "discard", now: () => number): Promise<LineagePromotion[]>;
/** Reconciliation (harvest-opening / host-triggered): promote every CREDENTIALED orphan pending
 *  txn; report the uncredentialed ones (their latch stays until the host adjudicates). */
export declare function reconcileLineage(docs: MemoryGovernanceDocs): Promise<{
    promoted: LineagePromotion[];
    undecidable: Array<{
        txnId: string;
        sessionId: string;
        entryIds: string[];
        kind?: "latch-only";
    }>;
}>;
/** design/178 v2-c §1 — the import COMPLETION-RECEIPT directory (control plane): one `wx`-minted
 *  JSON per bundle hash, written only after the import's governance legs all landed. Its presence
 *  is {@link releaseImportLatch}'s hard precondition and the idempotent re-import's short-circuit
 *  credential. */
export declare const IMPORT_RECEIPTS_DIR = "import-receipts";
/** Where the File store keeps each kind of control object: a directory under its control plane (`control-objects.ts` keeps the objects;
 *  a plane that travelled with a moved root is merged by these names, {@link isOneTimeRecord}). */
export declare const FILE_CONTROL_OBJECT_DIRS: Readonly<{
    pollution: string;
    "import-receipt": string;
    quarantine: string;
    hold: string;
    "clearance-custody": string;
    capture: string;
}>;
/** Where a File store stages an object's bytes before publishing them under the object's name. Never a kind's
 *  directory: a listing of a kind answers published names only. */
export declare const CONTROL_OBJECT_STAGE_DIR = ".control-object-stage";
/** The lineage txn id of a bundle import's synthetic latch (ONE latch per bundle — a re-import of
 *  the same bundle re-stages the same txn id, which is what makes the latch idempotent). */
export declare function importLatchTxnId(bundleHash: string): string;
/** The name a bundle's completion receipt is kept under: the store's control object of kind `import-receipt`
 *  `<bundleHash>.json`. */
export declare function importReceiptName(bundleHash: string): string;
/**
 * design/178 v2-c §1-1 — stage the bundle import's SYNTHETIC LATCH: one pending lineage txn
 * (txnId = {@link importLatchTxnId}) whose rows name every bundle entry id, every row and the txn
 * itself carrying the structural `kind: "latch-only"` seat. From this write until
 * {@link releaseImportLatch}, those ids are withheld on every model-visible read face (the same
 * dirty-latch consumption real staged rows get) — a crash anywhere inside the import leaves the
 * withhold standing (durable pending row), and re-staging the same bundle is an idempotent
 * overwrite with identical content. Never credentialed, never promoted.
 */
export declare function stageImportLatch(docs: MemoryGovernanceDocs, bundleHash: string, rows: ReadonlyArray<{
    entryId: string;
    rev: string;
}>, now: () => number): Promise<string>;
/**
 * design/178 v2-c §1-2⑥ — the ONE latch release channel. Hard precondition: the durable completion
 * receipt for the bundle is IN PLACE (the store's `import-receipt` object `<bundleHash>.json`, minted
 * after the governance legs all landed) — absent receipt ⇒ loud refusal, the latch stands, and
 * convergence is re-running the same bundle import. A receipt the store cannot answer for is refused
 * like a missing one, never read as absent (fail-closed). Idempotent: an already-released (absent)
 * txn is a no-op; a NON-latch txn under the id is refused (this is never a generic discard).
 */
export declare function releaseImportLatch(store: MemoryGovernanceDocs & Pick<import("./types.js").MemoryGovernanceObjects, "getObject">, txnId: string): Promise<void>;
/** The DIRTY-LATCH set: every entry id named by ANY pending row (credentialed or not). While an id
 *  is latched, its model-visible read faces (index mechanical rows / memory_search / memory_get)
 *  refuse — "the account is not settled, the content does not go on the table". Throws on a
 *  corrupt ledger (integrity unknown ≠ no latch). */
export declare function lineageLatchedIds(docs: MemoryGovernanceDocs): Promise<Set<string>>;
/** Every committed contribution of `sessionId` (the pollution-retroaction sweep input, and the
 *  erasure lane's sessionId-selector resolver, which keeps only the rows without `attribution` — the
 *  entries the session committed, never those it was only an overlap writer of). Throws on a corrupt ledger. Lookups are
 *  OWN-property (the twin law {@link lineageAccountOfEntry} states): a prototype-member sessionId
 *  such as "constructor" indexes truthy on EVERY plain object, so a bare lookup would attribute
 *  the WHOLE committed set to it — behind the erasure selector that phantom is a whole-store
 *  delete, the exact shape the selector type forbids. Belt over the null-proto parse rebuild:
 *  this guard stays honest even against a map minted elsewhere.
 *  `asking` names the occupant whose contributions are wanted: a row is kept unless it
 *  PROVABLY belongs to another ({@link sessionRecordBindsIncarnation}). An absent `asking`, and
 *  every unstamped row, keeps the whole by-id set — the superset this face has always answered, and
 *  the conservative side here (a sweep that challenges too little publishes). */
export declare function lineageContributionsOfSession(docs: MemoryGovernanceDocs, sessionId: string, asking?: string): Promise<Array<{
    entryId: string;
    lastRev: string;
    lastAt: number;
    marked?: true;
    attribution?: "overlap";
}>>;
/** design/178 v2-a §1.3 — the BY-ENTRY lineage account, from ONE parse of the ledger (the
 *  by-session read's transpose; the committed set is keyed by entryId, so the index is O(1) after
 *  the load — the load itself still parses and validates the whole account). BOTH halves come from
 *  the same read on purpose (adversarial r3): contributors (committed rows; pending rows are NOT
 *  contributions — the account is unsettled) and the dirty-latch fact (any pending row naming this
 *  id). Deriving them from two separate reads let a promotion land between them and assemble a
 *  scene no instant exhibited — empty ancestry AND no latch. Unknown entry ⇒ empty/false. Throws
 *  {@link ControlPlaneCorruptError} on a corrupt ledger — an audit answer is never assembled over
 *  an account whose integrity is unknown. Lookups are own-property (a prototype-member entryId
 *  such as "constructor" must answer the empty account, never a phantom). */
export declare function lineageAccountOfEntry(docs: MemoryGovernanceDocs, entryId: string): Promise<{
    contributors: Array<{
        sessionId: string;
        lastRev: string;
        lastAt: number;
        attribution?: "overlap";
    }>;
    pendingLatched: boolean;
}>;
/** Drop an entry's lineage rows once the entry is DELETED (an applied tombstone) — space hygiene
 *  only, taken at the harvest that saw the applied delete (design/180 §10). */
export declare function clearLineageForEntries(docs: MemoryGovernanceDocs, entryIds: readonly string[]): Promise<void>;
/**
 * design/178 v2-b §7.2-3 — capture-and-clear an erased id set's lineage in ONE strict-lock write:
 *  - the COMMITTED contributors of each id are captured (the attestation's testimony) and the rows
 *    dropped (the organic tombstone's space hygiene, same terminal state);
 *  - every PENDING txn's staged rows naming these ids are STRUCK in the same write — a promotion
 *    landing after this lock releases iterates rows the strike already removed, so a late harvest
 *    can never write a deleted id's lineage row back (the read and the clear being two separate
 *    lock spans was exactly the interleave that both missed a landing contributor and then erased
 *    the record of having missed it).
 * Struck pending rows contribute to the returned set the session the commit path would promote them
 * under — their own `sessionId` (an overlap row: another live writer's), else their txn's — EXCEPT
 * rows carrying the structural `kind: "latch-only"` seat (an import protocol's synthetic latch is not
 * a contributing session; the row is still struck). Returns id → contributing session ids
 * (committed ∪ struck). NON-durable by design: a crash between the caller's journal close and this
 * call loses the return set — the caller's replay re-runs it idempotently and its attestation
 * carries the chain's pre-captured set (honest downgrade, never a fabricated rebuild).
 */
export declare function captureAndClearLineageForEntries(docs: MemoryGovernanceDocs, entryIds: readonly string[]): Promise<Map<string, string[]>>;
/** One (entryId, sessionId) pair whose imported value LOST to the destination's standing row —
 *  design/178 v2-c §5.1's disclosure seat (kept is always "destination": the in-account fact is
 *  never overwritten by an equal-time divergent import, only reported). */
export interface LineageImportDivergence {
    entryId: string;
    sessionId: string;
    kept: "destination";
}
/**
 * design/178 v2-c §5.1 — the lineage FIDELITY importer: write bundle lineage rows into the
 * committed set VERBATIM (`lastRev`/`lastAt` carried byte-for-byte: the promote leg dates a contribution by its credential,
 * the import carries the exporter's date — neither reads a clock here). Deterministic same-key merge, idempotent under
 * re-import of the same bundle:
 *  - destination has no (entryId, sessionId) row ⇒ the source row lands verbatim;
 *  - both present, source `lastAt` is GREATER ⇒ source wins ("last contribution" is a time-axis
 *    fact); destination greater ⇒ destination stands (no divergence — the merge is deterministic);
 *  - equal `lastAt`, equal `lastRev` ⇒ no-op; equal `lastAt`, DIFFERENT `lastRev` ⇒ the
 *    destination row stands and the pair is reported (first-mark-wins side: an in-account fact is
 *    never rewritten by an外来 package; the disagreement must not be silent).
 * Throws on a corrupt ledger (fail-closed family).
 */
export declare function importLineageCommitted(docs: MemoryGovernanceDocs, rows: ReadonlyArray<{
    entryId: string;
    sessionId: string;
    lastRev: string;
    lastAt: number;
    marked?: true;
    attribution?: "overlap";
}>): Promise<LineageImportDivergence[]>;
/** Full-ledger read (tests / host observability). Throws on corruption. */
export declare function readLineageRecord(docs: MemoryGovernanceDocs): Promise<{
    committed: Record<string, Record<string, LineageContribution>>;
    pending: Record<string, LineagePendingTxn>;
}>;
/** Fail-open per-commit AUDIT history (bounded rotation) — never consulted by the load-bearing
 *  queries; a broken audit account degrades silently, exactly like the retrieved account. */
export declare function appendLineageAudit(controlDir: string, rows: ReadonlyArray<{
    entryId: string;
    sessionId: string;
    rev: string;
    at: number;
}>): void;
/** One challenge/resolve event. Append-only; the exclusion predicate is DERIVED ("any unresolved
 *  challenge generation exists"), never stored as a mutable flag. */
export interface ChallengeEvent {
    /** Stable identity for idempotent replay: the automatic arm derives it from the pollution event
     *  anchor (`pollution:<sessionId>:<markedAt>:<entryId>`); the host arm derives it from the
     *  caller's requestId (`<requestId>:<entryId>`). Same eventId replayed = same generation (a lost
     *  ack retried never opens a second generation); a DIFFERENT eventId with the same reason is a
     *  genuinely new event and opens a new generation (no immunity hole). */
    eventId: string;
    entryId: string;
    kind: "challenge" | "resolve";
    /** The generation this event opened (challenge) or closed (resolve). */
    generation: number;
    at: number;
    reason: string;
    /** Evidence grade — v2 mints only "S" (structural) events. */
    grade?: "S";
    /** Audit record only (the exclusion predicate keys the entry ID, never the rev). */
    challengedRev?: string;
}
/** One challenge assignment {@link appendChallengeEvents} returns. `replayed` = the eventId already
 *  existed (idempotent retry — the ORIGINAL generation is returned, no new one opens). */
export interface ChallengeAssignment {
    entryId: string;
    eventId: string;
    generation: number;
    at: number;
    replayed: boolean;
}
/**
 * design/180 §10 — the challenge ledger's SIZE CALIBRATION.
 *
 * The ledger is append-only and cannot be rotated: the exclusion predicate is DERIVED from the events
 * ("a challenge generation with no matching resolve"), so dropping the oldest rows would silently
 * un-withhold their entries — taint laundering, the exact failure the fail-closed family exists to
 * prevent. The bound is therefore a DISCLOSURE threshold, not a cap: crossing it changes nothing about
 * what the ledger holds, it tells the deployment the account needs attention.
 *
 * Calibrated against what actually degrades, which is not disk: every append REWRITES the whole file
 * under the strict lock, and every model-visible read path ({@link challengedEntryIds}, called on each
 * index rebuild and each memory tool call) PARSES it whole. At ~200 bytes per event, 10k events is a
 * ~2 MB parse on a read path that runs per tool call — the point where "an audit account nobody looks
 * at" becomes a latency the session feels. A deployment reaching it should resolve the settled
 * generations (they stay in the file, and that is the point) or archive the account deliberately.
 */
export declare const CHALLENGE_LEDGER_MAX_EVENTS = 10000;
/** What {@link appendChallengeEvents} returns: the per-request assignments plus the ledger's size
 *  AFTER the append — the caller owns disclosure (this module has no sink), and reading the size here
 *  costs nothing because the record is already in hand under the lock. */
export interface ChallengeAppendResult {
    assignments: ChallengeAssignment[];
    /** Total events in the ledger after this append, or `undefined` when nothing was appended — the
     *  empty-request fast path takes no lock and reads nothing, so it has no size to report and must not
     *  report a made-up `0` (a caller comparing that against the bound would read "tiny", not "unknown"). */
    eventCount: number | undefined;
}
/** Append S-grade challenge events (idempotent per eventId, generation allocation inside the strict
 *  lock). Every NEW eventId opens a NEW generation for its entry — a resolve of an earlier
 *  generation never immunizes the entry against later pollution (design/180 R-8). */
export declare function appendChallengeEvents(docs: MemoryGovernanceDocs, events: ReadonlyArray<{
    eventId: string;
    entryId: string;
    reason: string;
    challengedRev?: string;
}>, now: () => number): Promise<ChallengeAppendResult>;
/** The trusted resolve: closes EXACTLY the named generation (a later challenge's generation stays
 *  open — resolves never blanket-clear). Idempotent: resolving an already-resolved generation is a
 *  no-op. `resolved` is false ⇔ no such open generation existed.
 *
 *  `eventCount` rides along for the same reason it does on {@link appendChallengeEvents}: a resolve
 *  APPENDS an event too, so it crosses the size bound exactly as a challenge does (independent
 *  falsification review, verified — hanging the disclosure off the challenge writer alone leaves a ledger
 *  that crossed the bound on a resolve silent until the next challenge, which may never come).
 *  `undefined` when nothing was appended. */
export declare function resolveChallengeEvent(docs: MemoryGovernanceDocs, entryId: string, generation: number, reason: string, now: () => number, requestId?: string): Promise<{
    resolved: boolean;
    eventCount: number | undefined;
}>;
/** The exclusion predicate's input: entry id → its LATEST unresolved challenge generation. An entry
 *  appears iff at least one challenge generation has no matching resolve. Throws on corruption —
 *  consumers refuse service (integrity unknown ≠ clean). */
export declare function challengedEntryIds(docs: MemoryGovernanceDocs): Promise<Map<string, {
    generation: number;
    at: number;
}>>;
/** Full event read (host audit / tests). Throws on corruption. */
export declare function readChallengeEvents(docs: MemoryGovernanceDocs): Promise<ChallengeEvent[]>;
/** Which fail-closed control-plane ledger a rebuild targets: the governance documents a host may explicitly reset and
 *  announce (where a document is kept, and how it is read and changed, is the store's answer — {@link fileGovernanceDocOf}
 *  for a File store; which of them may be cleared after corruption is this set's). Each member is a document name:
 *  {@link fileGovernanceDocOf} takes nothing else, so a member outside the documents does not compile. */
export type StrictControlPlaneLedger = "lineage" | "challenges";
/** The rebuild targets, in the order their files are read (the export fence fingerprints them in this order). */
export declare const STRICT_CONTROL_PLANE_LEDGERS: readonly StrictControlPlaneLedger[];
/** What one rebuild did — the deployment's record of a taint-bearing account it chose to reset. */
export interface ControlPlaneRebuildReceipt {
    ledger: StrictControlPlaneLedger;
    /** The corrupt file (and its journal, when one existed) moved aside — never deleted. */
    quarantinedTo: string[];
    at: number;
}
/**
 * design/180 §10 — rebuild a CORRUPT fail-closed ledger, explicitly.
 *
 * The fail-closed family refuses service on corruption precisely because a silent "start fresh" would
 * LAUNDER taint (a challenged entry re-enters the prompt; a polluted session's contributions become
 * untraceable). That refusal is permanent by design — which left a deployment whose disk really did
 * corrupt with no way back other than deleting engine files by hand. This is that way back, and its
 * whole shape is "never automatic":
 *  · the caller names the ledger — nothing in the engine calls this on its own;
 *  · a HEALTHY ledger is REFUSED (`memory.control_plane_not_corrupt`) — a rebuild is only ever the
 *    answer to a corruption that is already blocking every read, never a way to clear an account;
 *  · the corrupt bytes are QUARANTINED beside the file, never deleted: what the ledger held is
 *    exactly the evidence someone will want after a laundering decision;
 *  · the caller (the engine's host API) announces the rebuild — a reset of this account changes what
 *    the model may see, so it is not a silent repair.
 */
/** Lock-less probe: does this fail-closed ledger currently REFUSE reads? The rebuild's own check runs
 *  again under the lock (this one is for a caller that must decide something — announce, refuse — before
 *  taking the lock). `false` for a ledger that reads cleanly, including an absent one (genuinely empty). */
export declare function isStrictControlPlaneLedgerCorrupt(controlDir: string, ledger: StrictControlPlaneLedger): boolean;
export declare function rebuildStrictControlPlaneLedger(controlDir: string, ledger: StrictControlPlaneLedger, now: () => number): ControlPlaneRebuildReceipt;
/** One challenged-history row: how often a retrieved-then-corrected event hit this entry. */
export interface ChallengedHistoryRow {
    count: number;
    lastAt: number;
    lastOp: "update" | "tombstone";
}
/** Record mechanical correction shadows (same-session retrieved → update/tombstone committed).
 *  Collect-only by contract: NOTHING in the engine reads this back into any decision (v3 candidate
 *  evidence only — design/178 ③-1 三级账 discipline). Throws propagate; callers treat fail-open. */
export declare function recordChallengedHistory(controlDir: string, rows: ReadonlyArray<{
    entryId: string;
    op: "update" | "tombstone";
}>, now: () => number): void;
/** Journal-aware read (observability/tests only — no engine consumer exists, on purpose). */
export declare function readChallengedHistory(controlDir: string): Record<string, ChallengedHistoryRow>;
export declare const PROJECTION_DEBTS_FILE = "projection-debts.json";
/** One standing debt: the plane file at `(scope, rel)` — `rel` relative to the scope's home,
 *  `/`-separated — belongs to committed entry `entryId`, whose id write-back has not landed; `rev`
 *  is the rev the projection was staged against (the CAS baseline a reconciling harvest hands its
 *  update). The key is the ledger form: location-free, so a home move never re-keys a row. */
export interface ProjectionDebtRow {
    scope: string;
    rel: string;
    entryId: string;
    rev: string;
    at: number;
}
/** WRITE-AHEAD staging. Upsert discipline: a stage lands only when the seat has NO standing row,
 *  the standing row is the stager's OWN entry (a rev refresh), or the standing row is the entry the
 *  stager itself just judged stale (`replaces` — the same-harvest stale-then-remint lane). It never
 *  blindly replaces ANOTHER writer's protection: a lagging process that validated an old row before
 *  pausing must not overwrite the row a faster sibling staged at the same seat (its own commit then
 *  CAS-conflicts and its tuple-keyed clear misses the survivor — the account converges instead of
 *  emptying). Called before the backend transaction; the caller degrades LOUDLY (report warning)
 *  on a refused stage rather than refusing the harvest — the ledger is duplicate-admission
 *  protection, not the commit's integrity. */
export declare function stageProjectionDebts(controlDir: string, rows: ReadonlyArray<{
    scope: string;
    rel: string;
    entryId: string;
    rev: string;
    replaces?: string;
}>, now: () => number): {
    refused: Array<{
        scope: string;
        rel: string;
        entryId: string;
    }>;
};
/** Settle (remove) rows by ROW IDENTITY — (scope, rel, entryId), never the bare seat: the write-back
 *  landed, the staged claim turned out stale, or a materialize re-projected the seat. Identity
 *  matters: a stale-clear judged against an OLD row must not delete the NEWER row a later staging
 *  upserted at the same seat. Missing rows are a no-op (idempotent). */
export declare function settleProjectionDebts(controlDir: string, rows: ReadonlyArray<{
    scope: string;
    rel: string;
    entryId: string;
}>): void;
/** Strict read (ENOENT ⇒ empty; corrupt ⇒ throws — the caller's fail-closed arm owns the refusal).
 *  A v1 record is converted in the ledger's lock on this first read. Rows the registry
 *  could not attribute stay on the record's `unresolved` seat and are not served. */
export declare function readProjectionDebts(controlDir: string): ProjectionDebtRow[];
/** The rows a key-form conversion could not attribute (audit read; empty on a converted ledger). */
export declare function unresolvedProjectionDebts(controlDir: string): Array<{
    relPath: string;
    entryId: string;
}>;
/** One seat of a copy-out replica's projection ledger: the engine left entry `id`'s content at `rel` (home-relative,
 *  `/`-separated) under `scope`'s home, and that file read as rev `rev` (`revOfText`) when it did. */
export interface ProjectionLedgerRow {
    readonly scope: string;
    readonly rel: string;
    readonly id: string;
    readonly rev: string;
}
/** The copy-out projection ledger as it stands (a committed journal first): its rows (none when there is no ledger), or why it
 *  cannot be read — a ledger that cannot be read is no ledger to its reader, never a partial one. */
export declare function readProjectionLedger(controlDir: string): {
    rows: ProjectionLedgerRow[];
} | {
    unreadable: string;
};
/** Change the ledger under its lock: `drop` removes a row only while the ledger still holds it exactly (seat, id and rev — a row
 *  another writer upserted since is not this change's to remove), then `upsert` sets each seat's row. A ledger that cannot be read
 *  is replaced by what this change leaves (`rebuilt`: true only when that replacement was written — a change that leaves nothing
 *  to write leaves the unreadable record standing and says `rebuilt: false`). Throws when the write itself fails. */
export declare function updateProjectionLedger(controlDir: string, change: {
    readonly drop?: readonly ProjectionLedgerRow[];
    readonly upsert?: readonly ProjectionLedgerRow[];
}): {
    rebuilt: boolean;
};
/**
 * REF-C6 — write EVERY byte of `data` to `fd`, looping until the OS has taken all of them.
 *
 * A bare `writeSync(fd, data)` issues ONE write(2) and may legally SHORT-WRITE (POSIX): it returns
 * how many bytes it took and silently drops the rest. `src/stores/file/fs-atomic.ts` already
 * documents and fixes this defect class twice (`writeThenLink`'s "silently SHORT-WRITES" note and
 * `AppendLog.append`'s RB-66 loop) — it was never propagated to the memory-engine control plane,
 * where a short write would fsync+rename a TRUNCATED sidecar/entry into place while every
 * fail-closed check upstream still reported success. Zero progress throws instead of spinning.
 */
export declare function writeAllSync(fd: number, data: string): void;
/** B3/H4 — TORN-WRITE-safe atomic replace (R5, ruling 2026-08-02: wording narrowed, no dirsync
 *  added): tmp file in the SAME directory (rename atomicity needs one fs), content fsync'd, then
 *  renamed over the target. A crash can leave the OLD content or the NEW content, never a torn
 *  file. What this does NOT promise: the rename itself surviving a power loss — the directory entry
 *  is not fsync'd (stores/file/fs-atomic.ts has the dir-fsync variant for stores that need it), so
 *  a crash in that window can resurface the old content. Sidecars tolerate that (they are rebuilt
 *  or re-derived); do not route data that can't through here. Throws on failure (fail-closed: a
 *  sidecar that cannot be written must not be silently skipped). The tmp file is opened by the one
 *  exclusive opener ({@link openExclusiveTemp}): a name already standing there (a link or a file somebody placed)
 *  is skipped for a fresh one, never a file this write truncates or writes through. One of the two ways a file lands in a store's
 *  control plane: once it stands, a store this process opened learns it ({@link rememberStoreWrite}). */
export declare function atomicWriteFileSync(path: string, data: string): void;
/** Content-gated {@link atomicWriteFileSync} for a DERIVED/control-plane file: a byte-identical
 *  rewrite (the common case on a repeat mount over an unchanged store) is skipped entirely, so the
 *  file's mtime stays put. ONLY for files whose mtime carries no meaning of its own — a lock or a
 *  heartbeat file's mtime IS its signal and must keep calling {@link atomicWriteFileSync} directly. */
export declare function writeIfChanged(path: string, data: string): void;
export {};