Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust
203 KB
Raw Blame
//! Single-writer SQLite actor.
//!
//! Every mutating SQL statement flows through one dedicated OS thread that
//! owns the writer [`rusqlite::Connection`]. Callers send [`WriteCmd`]
//! variants over an mpsc channel and receive results back through a
//! `oneshot`. This pattern eliminates the `database is locked` failure
//! mode that bit cognee (#2717) — there is exactly one writer at all
//! times, by construction.

use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};

use ai_memory_core::{
    AgentKind, AgentMessage, ApiCredentialId, HandoffAcceptance, HandoffId, IdentityKey,
    ManagedRunId, MessageClaim, MessageId, NewAgentMessage, NewHandoff, NewObservation, NewPage,
    NewSession, NewSessionUsage, NewUser, ObservationId, OwnerFilter, PageId, PagePath, ProjectId,
    Sanitized, SessionId, UserId, UserRole, WorkspaceId,
};
use rusqlite::Connection;
use tokio::sync::{mpsc, oneshot};
use uuid::Uuid;

use crate::api_credentials;
use crate::auto_improve::{
    ApproveAutoImproveProposal, ApproveAutoImproveProposalResult, FailAutoImproveProposal,
    RejectAutoImproveProposal, StageAutoImproveRun, StagedAutoImproveRun,
    StagedAutoImproveRunReport,
};
use crate::error::{StoreError, StoreResult};
use crate::ops::{
    self, AdmittedSession, DeleteWorkspaceSummary, EmbeddingWrite, HookSessionAdmission,
    IdleEndCandidate, IdleEndResult, IngestObservationOutcome, LifecycleOnlyEndOutcome,
    MergeProjectPage, MergeProjectSummary, MoveSessionSummary, MoveSummary,
    ObservationPruneOutcome, PagesMode, PurgeSummary, ReorgSummary,
};
use crate::session_consolidation::SessionConsolidationJob;
use crate::users::{self, TOKEN_HASH_LEN};
use crate::web_sessions::{self, WebSession};
use crate::workstream::{
    FinishWorkstreamRun, FinishedWorkstreamRun, LinkManagedRunSessionInScope,
    LinkOrAdoptManagedRunSession, ManagedRunSessionLink, PrepareWorkstreamRun,
    PreparedWorkstreamRun, RenameWorkstream, RenamedWorkstream,
};

/// Result of atomically claiming the startup context assembled for one hook.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct StartupContextAcceptance {
    /// The requested single-use handoff changed from open to accepted.
    pub handoff_accepted: bool,
    /// The requested managed synchronization packet changed to delivered.
    pub managed_context_accepted: bool,
}

/// Commands accepted by the writer thread.
pub(crate) enum WriteCmd {
    GetOrCreateWorkspace {
        name: String,
        reply: oneshot::Sender<StoreResult<WorkspaceId>>,
    },
    GetOrCreateProject {
        workspace_id: WorkspaceId,
        name: String,
        repo_path: Option<String>,
        reply: oneshot::Sender<StoreResult<ProjectId>>,
    },
    GetOrCreateProjectAs {
        workspace_id: WorkspaceId,
        name: String,
        repo_path: Option<String>,
        creator: Option<ai_memory_core::UserId>,
        reply: oneshot::Sender<StoreResult<(ProjectId, bool)>>,
    },
    SetNewProjectMode {
        mode: crate::AccessMode,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    SetAccessMode {
        project_id: ProjectId,
        mode: crate::AccessMode,
        reply: oneshot::Sender<StoreResult<Option<crate::AccessMode>>>,
    },
    SetProjectProfileFlags {
        project_id: ProjectId,
        flags: crate::ProjectProfileFlags,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    RecordProfileHarvest {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        candidates: Vec<crate::NewProfileCandidate>,
        mark: crate::ProfileHarvestMark,
        reply: oneshot::Sender<StoreResult<usize>>,
    },
    ClearProfileHarvestMarks {
        reply: oneshot::Sender<StoreResult<usize>>,
    },
    RecordProfileEntries {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        entries: Vec<crate::ProfileLedgerEntry>,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    ResolveProjectByIdentity {
        workspace_id: WorkspaceId,
        identity: ai_memory_core::repository_identity::RepositoryIdentity,
        style: ai_memory_core::repository_identity::IdentityStyle,
        promote: bool,
        name: String,
        repo_path: Option<String>,
        candidate: Option<ProjectId>,
        creator: Option<ai_memory_core::UserId>,
        reply: oneshot::Sender<StoreResult<(ProjectId, ops::IdentityResolution)>>,
    },
    ResolveProjectNameForWrite {
        workspace_id: WorkspaceId,
        name: String,
        principal: Option<crate::ProjectPrincipal>,
        distinguishes_operators: bool,
        promote: bool,
        reply: oneshot::Sender<StoreResult<ops::ProjectNameWriteResolution>>,
    },
    ResolveProjectAliasesForWrite {
        workspace_id: WorkspaceId,
        canonical: String,
        aliases: ai_memory_core::repository_identity::MarkerAliases,
        repository: ai_memory_core::repository_identity::RepositoryIdentity,
        principal: Option<crate::ProjectPrincipal>,
        distinguishes_operators: bool,
        reply: oneshot::Sender<StoreResult<Option<ops::ProjectAliasWriteResolution>>>,
    },
    EnsureProjectWorkspace {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    EnsureWorkspaceWithId {
        id: WorkspaceId,
        name: String,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    EnsureProjectWithId {
        id: ProjectId,
        workspace_id: WorkspaceId,
        name: String,
        repo_path: Option<String>,
        identity: Option<ai_memory_core::repository_identity::RepositoryIdentity>,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    ScopeIsPurged {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    PurgedSessionIds {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        reply: oneshot::Sender<StoreResult<Vec<SessionId>>>,
    },
    RecordBootstrapChunk {
        fingerprint: String,
        chunk_index: u32,
        pages_json: String,
        rationale: String,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    LoadBootstrapProgress {
        fingerprint: String,
        reply: oneshot::Sender<StoreResult<Vec<ops::BootstrapChunkRecord>>>,
    },
    ClearBootstrapProgress {
        fingerprint: String,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    UpsertPage {
        page: NewPage,
        reply: oneshot::Sender<StoreResult<PageId>>,
    },
    UpsertPageFromDisk {
        page: NewPage,
        reply: oneshot::Sender<StoreResult<PageId>>,
    },
    UpsertPageIf {
        page: NewPage,
        precondition: ops::PagePrecondition,
        reply: oneshot::Sender<StoreResult<ops::ConditionalUpsert>>,
    },
    UpsertPageBatch {
        pages: Vec<NewPage>,
        reply: oneshot::Sender<StoreResult<Vec<PageId>>>,
    },
    UpsertPageBatchIf {
        pages: Vec<(NewPage, ops::PagePrecondition)>,
        reply: oneshot::Sender<StoreResult<ops::ConditionalBatchUpsert>>,
    },
    DeletePage {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        path: PagePath,
        /// Authenticated operator recorded in the `audit_log` row (NULL when
        /// single-user / unauthenticated).
        author_id: Option<ai_memory_core::UserId>,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    DeletePageIfLatest {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        path: PagePath,
        expected_latest_id: PageId,
        author_id: Option<ai_memory_core::UserId>,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    BeginSession {
        session: NewSession,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    EndSession {
        session_id: SessionId,
        summary_page_id: Option<PageId>,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    EndSessionWithHandoff {
        session_id: SessionId,
        summary_page_id: Option<PageId>,
        handoff: NewHandoff,
        reply: oneshot::Sender<StoreResult<HandoffId>>,
    },
    EndLifecycleOnlySession {
        session_id: SessionId,
        reply: oneshot::Sender<StoreResult<LifecycleOnlyEndOutcome>>,
    },
    UpsertTokenCalls {
        session_id: SessionId,
        calls: Vec<ai_memory_core::TokenCall>,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    UpsertSessionUsage {
        usage: NewSessionUsage,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    EndIdleSessions {
        candidates: Vec<IdleEndCandidate>,
        enqueue_consolidation: bool,
        reply: oneshot::Sender<StoreResult<Vec<IdleEndResult>>>,
    },
    /// Test-only: [`WriteCmd::EndIdleSessions`] with a pre-stamp hook that
    /// runs on the writer connection BEFORE each candidate's stamp
    /// transaction opens, racing an effect into the window between the
    /// tick's page write and the stamp.
    #[cfg(test)]
    EndIdleSessionsPreStamp {
        candidates: Vec<IdleEndCandidate>,
        enqueue_consolidation: bool,
        pre_stamp: Box<dyn FnMut(&mut Connection) + Send>,
        reply: oneshot::Sender<StoreResult<Vec<IdleEndResult>>>,
    },
    SweepHollowProjects {
        min_age_days: u32,
        reply: oneshot::Sender<StoreResult<Vec<String>>>,
    },
    CloseAbandonedSessions {
        cutoff_us: i64,
        reply: oneshot::Sender<StoreResult<u64>>,
    },
    InsertObservation {
        obs: NewObservation,
        reply: oneshot::Sender<StoreResult<ObservationId>>,
    },
    InsertObservationIngest {
        obs: NewObservation,
        ingest_key: String,
        reply: oneshot::Sender<StoreResult<IngestObservationOutcome>>,
    },
    AdmitHookSessionEvent {
        session: NewSession,
        obs: NewObservation,
        owner_filter: OwnerFilter,
        ingest_key: Option<String>,
        moved_from_cwd: Option<String>,
        reply: oneshot::Sender<StoreResult<HookSessionAdmission>>,
    },
    EndAdmittedSession {
        admitted: AdmittedSession,
        summary_page_id: Option<PageId>,
        occurred_at: Option<i64>,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    EndAdmittedSessionWithHandoff {
        admitted: AdmittedSession,
        summary_page_id: Option<PageId>,
        handoff: NewHandoff,
        occurred_at: Option<i64>,
        reply: oneshot::Sender<StoreResult<HandoffId>>,
    },
    EndAdmittedLifecycleOnlySession {
        admitted: AdmittedSession,
        occurred_at: Option<i64>,
        reply: oneshot::Sender<StoreResult<LifecycleOnlyEndOutcome>>,
    },
    CompleteObservationIngest {
        project_id: ProjectId,
        ingest_key: String,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    CompleteObservationIngestIfClaimed {
        project_id: ProjectId,
        ingest_key: String,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    EnqueueSessionConsolidation {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        session_id: SessionId,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    EnqueueSessionCheckpoint {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        session_id: SessionId,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    ClaimSessionConsolidation {
        now: i64,
        stale_before: i64,
        reply: oneshot::Sender<StoreResult<Option<SessionConsolidationJob>>>,
    },
    CompleteSessionConsolidation {
        job: SessionConsolidationJob,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    FailSessionConsolidation {
        job: SessionConsolidationJob,
        error: String,
        retry_at: Option<i64>,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    ReleaseSessionConsolidation {
        job: SessionConsolidationJob,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    ReconcileSessionConsolidationCompleted {
        session_id: SessionId,
        reply: oneshot::Sender<StoreResult<usize>>,
    },
    InsertHandoff {
        handoff: NewHandoff,
        reply: oneshot::Sender<StoreResult<HandoffId>>,
    },
    CheckpointSessionHandoff {
        handoff: NewHandoff,
        reply: oneshot::Sender<StoreResult<Option<HandoffId>>>,
    },
    AcceptHandoff {
        acceptance: HandoffAcceptance,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    /// Expire every open handoff in one scope (#513). See
    /// [`ops::expire_open_handoffs`] for why this ignores the automatic
    /// sweep's exemptions.
    ExpireOpenHandoffs {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        owner_filter: OwnerFilter,
        older_than_us: Option<i64>,
        author_id: Option<ai_memory_core::UserId>,
        reply: oneshot::Sender<StoreResult<u64>>,
    },
    /// Record that an embed attempt produced no embedding (#528).
    RecordEmbedFailure {
        page_id: PageId,
        outcome: crate::ops::EmbedOutcome,
        detail: Option<String>,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    CancelHandoff {
        handoff_id: HandoffId,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        owner_filter: OwnerFilter,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    /// Send a cross-project message into a recipient project's inbox (V64).
    InsertMessage {
        message: NewAgentMessage,
        reply: oneshot::Sender<StoreResult<MessageId>>,
    },
    /// Pop (claim exactly once) a message from a recipient project's inbox.
    PopMessage {
        claim: MessageClaim,
        specific_id: Option<MessageId>,
        reply: oneshot::Sender<StoreResult<Option<AgentMessage>>>,
    },
    /// Take a pending message out of the queue so its sender can edit it.
    BeginMessageEdit {
        to_workspace_id: WorkspaceId,
        to_project_id: ProjectId,
        message_id: MessageId,
        reply: oneshot::Sender<StoreResult<Option<AgentMessage>>>,
    },
    /// Return an `editing` message to the queue, with new text or unchanged.
    FinishMessageEdit {
        to_workspace_id: WorkspaceId,
        to_project_id: ProjectId,
        message_id: MessageId,
        replacement: Option<(Option<String>, String)>,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    /// Retract still-pending outbox messages a project has sent.
    CancelMessages {
        from_workspace_id: WorkspaceId,
        from_project_id: ProjectId,
        specific_id: Option<MessageId>,
        reply: oneshot::Sender<StoreResult<u64>>,
    },
    /// Retro-fit sessions + observations to per-cwd projects and graveyard
    /// mash-up pages. Executed in one transaction for atomicity.
    Reorg {
        /// Workspace whose legacy mash-up pages and sessions are being reorged.
        workspace_id: WorkspaceId,
        /// Each entry is `(session_id, new_project_id)`.
        plan: Vec<(SessionId, ProjectId)>,
        reply: oneshot::Sender<StoreResult<ReorgSummary>>,
    },
    BumpAccess {
        page_ids: Vec<PageId>,
        actor: Option<IdentityKey>,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    BumpClientActivity {
        /// `(client, utc_day, reads_delta, writes_delta)` buckets.
        entries: Vec<(String, i64, u32, u32)>,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    RecordPageFeedback {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        path: PagePath,
        kind: ai_memory_core::FeedbackKind,
        reason: Option<String>,
        author_id: Option<ai_memory_core::UserId>,
        params: crate::decay::DecayParams,
        reply: oneshot::Sender<StoreResult<Option<(PageId, f64)>>>,
    },
    SoftDeleteForDecayIfLatest {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        path: PagePath,
        expected_latest_id: PageId,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    SoftDeleteForReconcileIfLatest {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        path: PagePath,
        expected_latest_id: PageId,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    HardDeleteDecayedPageChain {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        path: PagePath,
        tombstone_id: PageId,
        expected_latest_id: Option<PageId>,
        cutoff_us: i64,
        reply: oneshot::Sender<StoreResult<usize>>,
    },
    PruneConsolidatedObservations {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        cutoff_us: i64,
        batch: usize,
        reply: oneshot::Sender<StoreResult<ObservationPruneOutcome>>,
    },
    HealCatchAllRepoPaths {
        home: Option<String>,
        reply: oneshot::Sender<StoreResult<u64>>,
    },
    StoreEmbedding {
        page_id: PageId,
        vector_bytes: Vec<u8>,
        provider: String,
        model: String,
        dim: u32,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    StoreEmbeddingBatch {
        embeddings: Vec<EmbeddingWrite>,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    StoreAbstractEmbeddingBatch {
        embeddings: Vec<EmbeddingWrite>,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    DeleteAbstractEmbedding {
        page_id: PageId,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    DeleteStalePageEmbeddings {
        workspace_id: WorkspaceId,
        project_id: Option<ProjectId>,
        provider: String,
        model: String,
        dim: u32,
        reply: oneshot::Sender<StoreResult<u64>>,
    },
    /// Delete a project's rows (pages, sessions, observations, handoffs,
    /// embeddings) in one transaction. Returns the paths of every page file
    /// that must be removed from disk by the caller.
    ///
    /// A logical delete unless `compaction` is [`ops::Compaction::Reclaim`]:
    /// freed bytes stay in the file until it is rewritten.
    PurgeProject {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        /// Human-readable `workspace/project` label forwarded into the summary.
        label: String,
        /// Authenticated operator recorded in the `audit_log` row (NULL when
        /// single-user / unauthenticated).
        author_id: Option<ai_memory_core::UserId>,
        /// Purge even when a managed workstream still holds a live run lease.
        force: bool,
        /// Whether to reclaim the freed bytes afterwards (`VACUUM`).
        compaction: crate::ops::Compaction,
        /// [`crate::ops::PurgeMode::Preview`] stops right after counting and
        /// never issues the delete — unlike [`WriteCmd::MoveSession`]'s dry
        /// run, which runs the real write and rolls it back. See
        /// [`crate::ops::PurgeMode`]'s doc for why: a rolled-back delete on a
        /// large project would still hold the writer actor for as long as a
        /// real purge does.
        mode: crate::ops::PurgeMode,
        reply: oneshot::Sender<StoreResult<PurgeSummary>>,
    },
    /// Delete one session and everything derived from it, inside a single
    /// `(workspace, project)` scope. See [`ops::purge_session`].
    PurgeSession {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        session_id: SessionId,
        /// Authenticated operator recorded in the `audit_log` row.
        author_id: Option<ai_memory_core::UserId>,
        /// Whether to reclaim the freed bytes afterwards (`VACUUM`).
        compaction: crate::ops::Compaction,
        /// [`crate::ops::PurgeMode::Preview`] stops right after counting and
        /// never issues the delete — see [`crate::ops::PurgeMode`]'s doc.
        mode: crate::ops::PurgeMode,
        owner: Option<IdentityKey>,
        reply: oneshot::Sender<StoreResult<crate::ops::PurgeSessionSummary>>,
    },
    /// Final `wal_checkpoint(TRUNCATE)`, then close the connection and stop
    /// the actor. See [`WriterHandle::checkpoint_and_close`].
    Close {
        reply: oneshot::Sender<()>,
    },
    /// Test seam: read `PRAGMA journal_size_limit` off the writer's own
    /// connection, the only place the pragma is set.
    #[cfg(test)]
    JournalSizeLimit {
        reply: oneshot::Sender<StoreResult<i64>>,
    },
    /// Reclaim free pages on demand: rebuild the FTS indexes and `VACUUM`,
    /// deleting nothing. See [`ops::compact`].
    Compact {
        reply: oneshot::Sender<StoreResult<crate::ops::CompactSummary>>,
    },
    /// Delete the superseded ledger page versions the pre-#660 indexer left
    /// behind, and nothing else. See [`ops::reclaim_ledger_versions`].
    ReclaimLedgerVersions {
        /// Report what would go without deleting it.
        dry_run: bool,
        /// Also drop each ledger's live row, not just its superseded versions.
        drop_latest: bool,
        /// Whether to reclaim the freed bytes afterwards (`VACUUM`).
        compaction: crate::ops::Compaction,
        reply: oneshot::Sender<StoreResult<crate::ops::ReclaimLedgerVersionsSummary>>,
    },
    /// Delete a workspace row (its `workspace_id` FKs cascade projects/pages/
    /// sessions/…). Refused when non-empty unless `force`.
    DeleteWorkspace {
        workspace_id: WorkspaceId,
        force: bool,
        /// Whether to reclaim the freed bytes afterwards (`VACUUM`).
        compaction: crate::ops::Compaction,
        /// [`crate::ops::PurgeMode::Preview`] stops right after counting and
        /// never issues the delete — see [`crate::ops::PurgeMode`]'s doc.
        mode: crate::ops::PurgeMode,
        reply: oneshot::Sender<StoreResult<DeleteWorkspaceSummary>>,
    },
    /// Rename a workspace's `name` column (UUID-keyed dir doesn't move).
    RenameWorkspace {
        workspace_id: WorkspaceId,
        new_name: String,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    /// Re-stamp a project's `workspace_id` across every domain table in one
    /// transaction, keeping the same `project_id` (a lossless cross-workspace
    /// "true move"). The caller renames the on-disk dir and ensures the
    /// destination workspace row exists first.
    MoveProjectWorkspace {
        project_id: ProjectId,
        from_workspace: WorkspaceId,
        to_workspace: WorkspaceId,
        reply: oneshot::Sender<StoreResult<MoveSummary>>,
    },
    /// Merge one project id into another in the same workspace. The wiki
    /// layer supplies a compare-and-write plan for every latest source page.
    MergeProject {
        workspace_id: WorkspaceId,
        source_project: ProjectId,
        target_project: ProjectId,
        pages: Vec<MergeProjectPage>,
        commit: bool,
        reply: oneshot::Sender<StoreResult<MergeProjectSummary>>,
    },
    /// Re-stamp one session and its dependent rows (observations, handoffs,
    /// consolidation jobs, auto-improve runs and claim, session page) into
    /// another scope in one transaction. `commit = false` rolls back after
    /// counting so the reply is an exact dry run.
    MoveSession {
        session_id: SessionId,
        target_workspace: WorkspaceId,
        target_project: ProjectId,
        pages: PagesMode,
        author_id: Option<UserId>,
        commit: bool,
        reply: oneshot::Sender<StoreResult<MoveSessionSummary>>,
    },
    /// Validate and, when `commit`, apply a batch of session-time
    /// corrections scoped to `(workspace_id, project_id)`, in one
    /// transaction (`ai-memory repair-backfill-timestamps`). `commit = false`
    /// rolls back after validating, so the reply is an exact dry run.
    RepairSessionTimes {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        candidates: Vec<ops::SessionTimesCandidate>,
        now_us: i64,
        author_id: Option<UserId>,
        commit: bool,
        reply: oneshot::Sender<StoreResult<ops::RepairSessionTimesSummary>>,
    },
    /// Rename a project's `name` column without moving any files (the wiki
    /// is flat on disk). Fails with [`crate::error::StoreError::ProjectNameTaken`]
    /// when `new_name` is already used in the same workspace.
    RenameProject {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        new_name: String,
        /// Authenticated operator recorded in the `audit_log` row (NULL when
        /// single-user / unauthenticated).
        author_id: Option<ai_memory_core::UserId>,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    /// One-shot in-place OKF conformance of every latest page row.
    OkfMigrateLatestPages {
        reply: oneshot::Sender<StoreResult<Vec<ops::OkfMigratedPage>>>,
    },
    /// Idempotent in-place repair of date-only OKF `stale_after` values.
    RepairDateOnlyStaleAfter {
        reply: oneshot::Sender<StoreResult<ops::StaleAfterRepair>>,
    },
    /// Read-only count of latest rows still lacking OKF conformance.
    OkfNonconformantCount {
        reply: oneshot::Sender<StoreResult<u64>>,
    },
    /// Record a completed cross-session ("experience") pass for a scope.
    MarkExperiencePassRun {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    /// Record a successfully-applied wiki-structure migration.
    InsertWikiMigration {
        name: String,
        /// Unix microseconds UTC.
        applied_at: i64,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    BootstrapRoot {
        username: String,
        name: Option<String>,
        email: Option<String>,
        password_hash: String,
        reply: oneshot::Sender<StoreResult<UserId>>,
    },
    RecoverRoot {
        username: String,
        name: Option<String>,
        email: Option<String>,
        password_hash: String,
        reply: oneshot::Sender<StoreResult<UserId>>,
    },
    GrantMemory {
        user_id: UserId,
        repository_id: ProjectId,
        role: crate::GrantLevel,
        granted_by: Option<UserId>,
        reply: oneshot::Sender<StoreResult<crate::grants::GrantOutcome>>,
    },
    RevokeMemory {
        user_id: UserId,
        repository_id: ProjectId,
        revoked_by: Option<UserId>,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    CreateHumanUser {
        new_user: NewUser,
        role: UserRole,
        password_hash: Option<String>,
        must_change_password: bool,
        reply: oneshot::Sender<StoreResult<UserId>>,
    },
    ResetHumanPassword {
        user_id: UserId,
        password_hash: String,
        must_change_password: bool,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    SetUserDisabled {
        user_id: UserId,
        disabled: bool,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    PatchUser {
        user_id: UserId,
        name: Option<Option<String>>,
        email: Option<Option<String>>,
        role: Option<UserRole>,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    ChangePassword {
        user_id: UserId,
        expected_password_hash: String,
        new_password_hash: String,
        session_id: Uuid,
        new_session_hash: [u8; TOKEN_HASH_LEN],
        new_csrf_hash: [u8; TOKEN_HASH_LEN],
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    IssueWebSession {
        user_id: UserId,
        expected_password_hash: String,
        expected_role: UserRole,
        expected_must_change: bool,
        session_hash: [u8; TOKEN_HASH_LEN],
        csrf_hash: [u8; TOKEN_HASH_LEN],
        reply: oneshot::Sender<StoreResult<WebSession>>,
    },
    RevokeWebSession {
        session_hash: [u8; TOKEN_HASH_LEN],
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    TouchWebSession {
        session_id: Uuid,
        last_used_at: i64,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    CreateApiCredential {
        id: ApiCredentialId,
        user_id: UserId,
        label: String,
        token_hash: [u8; TOKEN_HASH_LEN],
        preview: Option<String>,
        /// Refuse with [`StoreError::InvalidState`] when the user already
        /// holds this many active credentials. Checked on the writer thread,
        /// so concurrent creates cannot both slip under the limit.
        max_active: Option<usize>,
        reply: oneshot::Sender<StoreResult<ApiCredentialId>>,
    },
    RotateApiCredential {
        id: ApiCredentialId,
        new_token_hash: [u8; TOKEN_HASH_LEN],
        preview: Option<String>,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    RevokeApiCredential {
        id: ApiCredentialId,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    TouchApiCredential {
        id: ApiCredentialId,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    BindApiCredentialPepperVerifier {
        verifier: String,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    TouchUserLastSeen {
        user_id: UserId,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    StageAutoImproveRun {
        input: StageAutoImproveRun,
        reply: oneshot::Sender<StoreResult<StagedAutoImproveRun>>,
    },
    StageAutoImproveRunForOwner {
        input: StageAutoImproveRun,
        owner: Option<IdentityKey>,
        reply: oneshot::Sender<StoreResult<StagedAutoImproveRunReport>>,
    },
    RejectAutoImproveProposal {
        input: RejectAutoImproveProposal,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    FailAutoImproveProposal {
        input: FailAutoImproveProposal,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    ApproveAutoImproveProposal {
        input: ApproveAutoImproveProposal,
        reply: oneshot::Sender<StoreResult<ApproveAutoImproveProposalResult>>,
    },
    EnsureAutoImproveSchedulerState {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    ClaimAutoImproveSchedulerSession {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        session_id: SessionId,
        ended_at: i64,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    RecordAutoImproveClaimFailure {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        session_id: SessionId,
        error: String,
        reply: oneshot::Sender<StoreResult<u32>>,
    },
    RecordMaintenanceJobSuccess {
        job: crate::maintenance::MaintenanceJob,
        reply: oneshot::Sender<StoreResult<()>>,
    },
    PrepareWorkstreamRun {
        input: PrepareWorkstreamRun,
        owner_user: Option<String>,
        force_unlock: bool,
        reply: oneshot::Sender<StoreResult<PreparedWorkstreamRun>>,
    },
    HeartbeatManagedRun {
        run_id: ManagedRunId,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    CancelManagedRun {
        run_id: ManagedRunId,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    LinkManagedRunSession {
        run_id: ManagedRunId,
        agent: AgentKind,
        native_session_id: String,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    LinkOrAdoptManagedRunSession {
        input: LinkOrAdoptManagedRunSession,
        reply: oneshot::Sender<StoreResult<ManagedRunSessionLink>>,
    },
    LinkManagedRunSessionInScope {
        input: LinkManagedRunSessionInScope,
        reply: oneshot::Sender<StoreResult<ManagedRunSessionLink>>,
    },
    AcceptManagedRunContext {
        run_id: ManagedRunId,
        reply: oneshot::Sender<StoreResult<bool>>,
    },
    AcceptStartupContext {
        handoff: Option<HandoffAcceptance>,
        managed_run_id: Option<ManagedRunId>,
        receiving_session: Option<NewSession>,
        busy_since: jiff::Timestamp,
        reply: oneshot::Sender<StoreResult<StartupContextAcceptance>>,
    },
    FinishWorkstreamRun {
        authority: crate::ManagedRunAuthority,
        input: FinishWorkstreamRun,
        recover_expired: bool,
        reply: oneshot::Sender<StoreResult<FinishedWorkstreamRun>>,
    },
    RenameWorkstream {
        input: RenameWorkstream,
        reply: oneshot::Sender<StoreResult<RenamedWorkstream>>,
    },
    AuthorizeProject {
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        principal: crate::ProjectPrincipal,
        distinguishes_operators: bool,
        need: crate::ProjectAccess,
        reply: oneshot::Sender<StoreResult<Result<(), ai_memory_core::AuthzError>>>,
    },
    Shutdown,
}

/// Cheap, cloneable handle that submits commands to the writer.
#[derive(Clone)]
pub struct WriterHandle {
    inner: Arc<WriterInner>,
}

struct WriterInner {
    tx: Option<mpsc::Sender<WriteCmd>>,
    join: Mutex<Option<JoinHandle<()>>>,
    #[cfg(test)]
    before_join: Option<Box<dyn FnOnce() + Send + Sync>>,
}

impl WriterHandle {
    /// Take ownership of `conn` and spawn the writer thread.
    pub(crate) fn spawn(conn: Connection) -> Self {
        let (tx, rx) = mpsc::channel(1024);
        let handle = thread::Builder::new()
            .name("ai-memory-writer".into())
            .spawn(move || worker_loop(conn, rx))
            .expect("spawn writer thread");

        Self {
            inner: Arc::new(WriterInner {
                tx: Some(tx),
                join: Mutex::new(Some(handle)),
                #[cfg(test)]
                before_join: None,
            }),
        }
    }

    /// Resolve a workspace by name, creating it atomically if missing.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or
    /// propagates the SQL error from [`ops::get_or_create_workspace`].
    pub async fn get_or_create_workspace(
        &self,
        name: impl Into<String>,
    ) -> StoreResult<WorkspaceId> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::GetOrCreateWorkspace {
            name: name.into(),
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// The per-project authorization choke point (#708), evaluated on the
    /// **writer** connection as defense in depth for writes: a write decision
    /// is made against the same connection that will perform the write, so it
    /// cannot race a concurrent grant/access-mode change between a read-pool
    /// check and the write.
    ///
    /// Returns `Ok(Ok(()))` when admitted, `Ok(Err(Forbidden))` when a
    /// restricted project refuses the caller, and `Err(_)` only on an
    /// infrastructure failure. In slice 2 every project is `open`, so this is a
    /// pass-through.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or
    /// propagates the SQL error from the authz resolver.
    pub async fn authorize_project(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        principal: crate::ProjectPrincipal,
        distinguishes_operators: bool,
        need: crate::ProjectAccess,
    ) -> StoreResult<Result<(), ai_memory_core::AuthzError>> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::AuthorizeProject {
            workspace_id,
            project_id,
            principal,
            distinguishes_operators,
            need,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Resolve a project by `(workspace_id, name)`, creating it atomically
    /// if missing.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or
    /// propagates the SQL error from [`ops::get_or_create_project`].
    pub async fn get_or_create_project(
        &self,
        workspace_id: WorkspaceId,
        name: impl Into<String>,
        repo_path: Option<String>,
    ) -> StoreResult<ProjectId> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::GetOrCreateProject {
            workspace_id,
            name: name.into(),
            repo_path,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// [`Self::get_or_create_project`] on behalf of `creator`, who is recorded
    /// as the project's `created_by` in the same transaction when this call
    /// creates the row. Returns whether it did — see
    /// [`ops::get_or_create_project_as`].
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or
    /// propagates the SQL error.
    pub async fn get_or_create_project_as(
        &self,
        workspace_id: WorkspaceId,
        name: impl Into<String>,
        repo_path: Option<String>,
        creator: Option<ai_memory_core::UserId>,
    ) -> StoreResult<(ProjectId, bool)> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::GetOrCreateProjectAs {
            workspace_id,
            name: name.into(),
            repo_path,
            creator,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Set the access mode newly created projects start in — the server's
    /// `[auth] new_projects_restricted`. Called once at startup; until then,
    /// and on every install that never calls it, new projects are open.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down.
    pub async fn set_new_project_mode(&self, mode: crate::AccessMode) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::SetNewProjectMode { mode, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Set one project's access mode, returning the mode it had, or `None` when
    /// there is no such project.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or
    /// propagates the SQL error.
    pub async fn set_access_mode(
        &self,
        project_id: ProjectId,
        mode: crate::AccessMode,
    ) -> StoreResult<Option<crate::AccessMode>> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::SetAccessMode {
            project_id,
            mode,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Persist a project's `[profile]` flags (forwarded from its marker at
    /// session start). A no-op when they already match.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or
    /// propagates the SQL error.
    pub async fn set_project_profile_flags(
        &self,
        project_id: ProjectId,
        flags: crate::ProjectProfileFlags,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::SetProjectProfileFlags {
            project_id,
            flags,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Record one project's profile candidates and advance its harvest marks
    /// in one transaction. Re-recording a candidate is a no-op; returns how
    /// many were new.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or
    /// propagates the SQL error.
    pub async fn record_profile_harvest(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        candidates: Vec<crate::NewProfileCandidate>,
        mark: crate::ProfileHarvestMark,
    ) -> StoreResult<usize> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::RecordProfileHarvest {
            workspace_id,
            project_id,
            candidates,
            mark,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Record the profile entries the harvester wrote into a profile scope,
    /// in one transaction.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or
    /// propagates the SQL error.
    pub async fn record_profile_entries(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        entries: Vec<crate::ProfileLedgerEntry>,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::RecordProfileEntries {
            workspace_id,
            project_id,
            entries,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Forget every profile harvest mark (`ai-memory profile rebuild`).
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or
    /// propagates the SQL error.
    pub async fn clear_profile_harvest_marks(&self) -> StoreResult<usize> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::ClearProfileHarvestMarks { reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Resolve the project a repository identity routes to, creating it when
    /// needed — see [`ops::resolve_project_by_identity`] for the rules.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or
    /// propagates the SQL error.
    #[allow(clippy::too_many_arguments)]
    pub async fn resolve_project_by_identity(
        &self,
        workspace_id: WorkspaceId,
        identity: ai_memory_core::repository_identity::RepositoryIdentity,
        style: ai_memory_core::repository_identity::IdentityStyle,
        name: impl Into<String>,
        repo_path: Option<String>,
        candidate: Option<ProjectId>,
        creator: Option<ai_memory_core::UserId>,
    ) -> StoreResult<(ProjectId, ops::IdentityResolution)> {
        self.resolve_project_by_identity_inner(
            workspace_id,
            identity,
            style,
            false,
            name,
            repo_path,
            candidate,
            creator,
        )
        .await
    }

    #[allow(clippy::too_many_arguments)]
    async fn resolve_project_by_identity_inner(
        &self,
        workspace_id: WorkspaceId,
        identity: ai_memory_core::repository_identity::RepositoryIdentity,
        style: ai_memory_core::repository_identity::IdentityStyle,
        promote: bool,
        name: impl Into<String>,
        repo_path: Option<String>,
        candidate: Option<ProjectId>,
        creator: Option<ai_memory_core::UserId>,
    ) -> StoreResult<(ProjectId, ops::IdentityResolution)> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::ResolveProjectByIdentity {
            workspace_id,
            identity,
            style,
            promote,
            name: name.into(),
            repo_path,
            candidate,
            creator,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Resolve repository identity for capture and allow transactional
    /// canonical-name promotion after authorization.
    #[allow(clippy::too_many_arguments)]
    pub async fn resolve_project_by_identity_for_capture(
        &self,
        workspace_id: WorkspaceId,
        identity: ai_memory_core::repository_identity::RepositoryIdentity,
        style: ai_memory_core::repository_identity::IdentityStyle,
        name: impl Into<String>,
        repo_path: Option<String>,
        candidate: Option<ProjectId>,
        creator: Option<ai_memory_core::UserId>,
    ) -> StoreResult<(ProjectId, ops::IdentityResolution)> {
        self.resolve_project_by_identity_inner(
            workspace_id,
            identity,
            style,
            true,
            name,
            repo_path,
            candidate,
            creator,
        )
        .await
    }

    /// Resolve marker aliases inside one workspace and atomically authorize any
    /// Phase 1 canonical-name promotion. Returns `None` when no alias exists.
    pub async fn resolve_project_aliases_for_write(
        &self,
        workspace_id: WorkspaceId,
        canonical: impl Into<String>,
        aliases: ai_memory_core::repository_identity::MarkerAliases,
        repository: ai_memory_core::repository_identity::RepositoryIdentity,
        principal: Option<crate::ProjectPrincipal>,
        distinguishes_operators: bool,
    ) -> StoreResult<Option<ops::ProjectAliasWriteResolution>> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::ResolveProjectAliasesForWrite {
            workspace_id,
            canonical: canonical.into(),
            aliases,
            repository,
            principal,
            distinguishes_operators,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    pub(crate) async fn resolve_project_name_for_write(
        &self,
        workspace_id: WorkspaceId,
        name: impl Into<String>,
        principal: Option<crate::ProjectPrincipal>,
        distinguishes_operators: bool,
    ) -> StoreResult<ops::ProjectNameWriteResolution> {
        self.resolve_project_name_for_write_mode(
            workspace_id,
            name,
            principal,
            distinguishes_operators,
            true,
        )
        .await
    }

    pub(crate) async fn resolve_project_name_for_write_without_promotion(
        &self,
        workspace_id: WorkspaceId,
        name: impl Into<String>,
        principal: Option<crate::ProjectPrincipal>,
        distinguishes_operators: bool,
    ) -> StoreResult<ops::ProjectNameWriteResolution> {
        self.resolve_project_name_for_write_mode(
            workspace_id,
            name,
            principal,
            distinguishes_operators,
            false,
        )
        .await
    }

    async fn resolve_project_name_for_write_mode(
        &self,
        workspace_id: WorkspaceId,
        name: impl Into<String>,
        principal: Option<crate::ProjectPrincipal>,
        distinguishes_operators: bool,
        promote: bool,
    ) -> StoreResult<ops::ProjectNameWriteResolution> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::ResolveProjectNameForWrite {
            workspace_id,
            name: name.into(),
            principal,
            distinguishes_operators,
            promote,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Assert that a project still belongs to the supplied workspace.
    ///
    /// # Errors
    /// Returns [`StoreError::NotFound`] when the `(workspace_id, project_id)`
    /// pair is stale, [`StoreError::WriterClosed`] if the actor has shut down,
    /// or propagates the SQL error.
    pub async fn ensure_project_workspace(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::EnsureProjectWorkspace {
            workspace_id,
            project_id,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Insert a workspace with an **explicit id** (idempotent). Used by
    /// `reindex` to recreate a scope under the id recovered from the wiki
    /// directory name. See [`ops::ensure_workspace_with_id`].
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn ensure_workspace_with_id(
        &self,
        id: WorkspaceId,
        name: impl Into<String>,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::EnsureWorkspaceWithId {
            id,
            name: name.into(),
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Insert a project with an **explicit id** under `workspace_id`
    /// (idempotent). See [`ops::ensure_project_with_id`].
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn ensure_project_with_id(
        &self,
        id: ProjectId,
        workspace_id: WorkspaceId,
        name: impl Into<String>,
        repo_path: Option<String>,
        identity: Option<ai_memory_core::repository_identity::RepositoryIdentity>,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::EnsureProjectWithId {
            id,
            workspace_id,
            name: name.into(),
            repo_path,
            identity,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Whether the scope was purged by `purge_project` / `delete_workspace` and
    /// tombstoned. `reindex` consults this before recreating a scope from
    /// on-disk `_meta.md` so a purge that crashed before its files were removed
    /// cannot be silently undone (#607). Routed through the writer actor
    /// because it owns the connection and is always present.
    pub async fn scope_is_purged(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
    ) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::ScopeIsPurged {
            workspace_id,
            project_id,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Session ids tombstoned by `purge_session` in this scope. The wiki
    /// reindex consults these so a purge whose page-file removal did not
    /// complete cannot be undone by the next pass (#701). Loaded once per
    /// directory per pass, not once per page. Routed through the writer actor
    /// for the same reason [`Self::scope_is_purged`] is.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn purged_session_ids(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
    ) -> StoreResult<Vec<SessionId>> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::PurgedSessionIds {
            workspace_id,
            project_id,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Durably record one completed bootstrap chunk's output, keyed by a
    /// fingerprint of the run's inputs (#621). See
    /// [`crate::ops::record_bootstrap_chunk`].
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn record_bootstrap_chunk(
        &self,
        fingerprint: String,
        chunk_index: u32,
        pages_json: String,
        rationale: String,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::RecordBootstrapChunk {
            fingerprint,
            chunk_index,
            pages_json,
            rationale,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Load every recorded chunk for `fingerprint`, ordered by chunk index.
    /// See [`crate::ops::load_bootstrap_progress`].
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn load_bootstrap_progress(
        &self,
        fingerprint: String,
    ) -> StoreResult<Vec<ops::BootstrapChunkRecord>> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::LoadBootstrapProgress {
            fingerprint,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Delete every recorded chunk for `fingerprint`. Call once a bootstrap
    /// run completes successfully. See [`crate::ops::clear_bootstrap_progress`].
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn clear_bootstrap_progress(&self, fingerprint: String) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::ClearBootstrapProgress {
            fingerprint,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Begin a session (idempotent on the supplied id).
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn begin_session(&self, session: NewSession) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::BeginSession { session, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Mark a session ended, optionally linking its summary page, and persist
    /// the observation generation covered by this end.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn end_session(
        &self,
        session_id: SessionId,
        summary_page_id: Option<PageId>,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::EndSession {
            session_id,
            summary_page_id,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Record native response usage and refresh its session total atomically.
    pub async fn upsert_token_calls(
        &self,
        session_id: SessionId,
        calls: Vec<ai_memory_core::TokenCall>,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::UpsertTokenCalls {
            session_id,
            calls,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Record a session's reported cumulative token usage (token-cost
    /// visibility). Idempotent-safe: the upsert keeps `MAX(existing,
    /// reported)` per column, so calling this twice with the same or an
    /// older report never lowers a stored total.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL/state errors
    /// (including the FK violation from an unknown `usage.session_id`).
    pub async fn upsert_session_usage(&self, usage: NewSessionUsage) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::UpsertSessionUsage { usage, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Atomically end a session and insert its automatic handoff.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL/state errors.
    pub async fn end_session_with_handoff(
        &self,
        session_id: SessionId,
        summary_page_id: Option<PageId>,
        handoff: NewHandoff,
    ) -> StoreResult<HandoffId> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::EndSessionWithHandoff {
            session_id,
            summary_page_id,
            handoff,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Atomically end a lifecycle-only session and reopen the handoff claimed
    /// by that exact receiver, if one exists.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL/state errors.
    pub async fn end_lifecycle_only_session(
        &self,
        session_id: SessionId,
    ) -> StoreResult<LifecycleOnlyEndOutcome> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::EndLifecycleOnlySession {
            session_id,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// End a batch of idle sessions the server-side tick selected
    /// ([`crate::reader::ReaderPool::idle_open_sessions`]), one writer
    /// command per tick. See [`ops::idle_end_sessions`] for the guarded-
    /// write and watermark semantics; a lost candidate (a real `SessionEnd`
    /// won the race) is reported, never an error.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL/state errors.
    pub async fn end_idle_sessions(
        &self,
        candidates: Vec<IdleEndCandidate>,
        enqueue_consolidation: bool,
    ) -> StoreResult<Vec<IdleEndResult>> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::EndIdleSessions {
            candidates,
            enqueue_consolidation,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Test-only: [`Self::end_idle_sessions`] with a `pre_stamp` hook that
    /// runs on the writer connection BEFORE each candidate's stamp
    /// transaction opens — not inside it — so a test can race a real effect
    /// into the window between the tick's page write and the stamp without
    /// sleeps.
    #[cfg(test)]
    pub async fn end_idle_sessions_pre_stamp(
        &self,
        candidates: Vec<IdleEndCandidate>,
        enqueue_consolidation: bool,
        pre_stamp: Box<dyn FnMut(&mut rusqlite::Connection) + Send>,
    ) -> StoreResult<Vec<IdleEndResult>> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::EndIdleSessionsPreStamp {
            candidates,
            enqueue_consolidation,
            pre_stamp,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Delete hollow project rows (no data of any kind) older than
    /// `min_age_days`; returns the deleted names. See
    /// [`ops::sweep_hollow_projects`].
    ///
    /// # Errors
    /// Propagates store failures.
    pub async fn sweep_hollow_projects(&self, min_age_days: u32) -> StoreResult<Vec<String>> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::SweepHollowProjects {
            min_age_days,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Close every session, in every scope, open with no activity since
    /// before `cutoff_us` (safety net). No usage, no
    /// consolidation — see [`ops::close_abandoned_sessions`] for why.
    /// Returns the number of sessions closed.
    ///
    /// # Errors
    /// Propagates store failures.
    pub async fn close_abandoned_sessions(&self, cutoff_us: i64) -> StoreResult<u64> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::CloseAbandonedSessions {
            cutoff_us,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Append an observation row.
    ///
    /// Takes [`Sanitized<NewObservation>`] — the privacy strip is enforced by
    /// the type system at the store boundary, so an unsanitized observation
    /// cannot reach disk by construction ([`Sanitized::new`] is the single
    /// constructor and applies the scrub).
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn insert_observation(
        &self,
        obs: Sanitized<NewObservation>,
    ) -> StoreResult<ObservationId> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::InsertObservation {
            obs: obs.into_inner(),
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Claim a keyed hook event and append its observation atomically.
    ///
    /// The outcome tells the hook router whether it inserted a new observation,
    /// must resume incomplete downstream effects, or can skip a fully completed
    /// replay. Keys are scoped to the observation's project.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn insert_observation_ingest(
        &self,
        obs: Sanitized<NewObservation>,
        ingest_key: String,
    ) -> StoreResult<IngestObservationOutcome> {
        let obs = obs.into_inner();
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::InsertObservationIngest {
            obs,
            ingest_key,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Atomically validate/admit a hook session and insert its observation.
    /// `moved_from_cwd` marks an explicit native relocation; see
    /// `ops::admit_hook_session_event`.
    pub async fn admit_hook_session_event(
        &self,
        session: NewSession,
        obs: Sanitized<NewObservation>,
        owner_filter: OwnerFilter,
        ingest_key: Option<String>,
        moved_from_cwd: Option<String>,
    ) -> StoreResult<HookSessionAdmission> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::AdmitHookSessionEvent {
            session,
            obs: obs.into_inner(),
            owner_filter,
            ingest_key,
            moved_from_cwd,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Guarded hook end.
    ///
    /// `occurred_at` is the SessionEnd event's own original time (microseconds),
    /// when known; `None` falls back to "now" at the store boundary.
    pub async fn end_admitted_session(
        &self,
        admitted: AdmittedSession,
        summary_page_id: Option<PageId>,
        occurred_at: Option<i64>,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::EndAdmittedSession {
            admitted,
            summary_page_id,
            occurred_at,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Guarded hook end plus automatic handoff.
    ///
    /// `occurred_at` is the SessionEnd event's own original time (microseconds),
    /// when known; `None` falls back to "now" at the store boundary.
    pub async fn end_admitted_session_with_handoff(
        &self,
        admitted: AdmittedSession,
        summary_page_id: Option<PageId>,
        handoff: NewHandoff,
        occurred_at: Option<i64>,
    ) -> StoreResult<HandoffId> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::EndAdmittedSessionWithHandoff {
            admitted,
            summary_page_id,
            handoff,
            occurred_at,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Guarded hook lifecycle-only end.
    ///
    /// `occurred_at` is the SessionEnd event's own original time (microseconds),
    /// when known; `None` falls back to "now" at the store boundary.
    pub async fn end_admitted_lifecycle_only_session(
        &self,
        admitted: AdmittedSession,
        occurred_at: Option<i64>,
    ) -> StoreResult<LifecycleOnlyEndOutcome> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::EndAdmittedLifecycleOnlySession {
            admitted,
            occurred_at,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Mark a keyed hook event complete after all downstream effects finish.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL/state errors.
    pub async fn complete_observation_ingest(
        &self,
        project_id: ProjectId,
        ingest_key: String,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::CompleteObservationIngest {
            project_id,
            ingest_key,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Mark a keyed hook event complete if its observation claim exists.
    ///
    /// Returns `false` for an unkeyed or unrelated duplicate recovery attempt.
    pub async fn complete_observation_ingest_if_claimed(
        &self,
        project_id: ProjectId,
        ingest_key: String,
    ) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::CompleteObservationIngestIfClaimed {
            project_id,
            ingest_key,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Persist one opt-in SessionEnd consolidation job for the current
    /// observation generation. Duplicate generations are idempotent.
    pub async fn enqueue_session_consolidation(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        session_id: SessionId,
    ) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::EnqueueSessionConsolidation {
            workspace_id,
            project_id,
            session_id,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Persist one checkpoint job (PreCompact / PostCompaction) for the
    /// current observation generation. Duplicate generations are idempotent.
    /// The session may already have ended: a resumed session keeps
    /// `ended_at` while it captures again.
    pub async fn enqueue_session_checkpoint(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        session_id: SessionId,
    ) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::EnqueueSessionCheckpoint {
            workspace_id,
            project_id,
            session_id,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Atomically claim the oldest due session consolidation job (SessionEnd
    /// or checkpoint).
    pub async fn claim_session_consolidation(
        &self,
        now: i64,
        stale_before: i64,
    ) -> StoreResult<Option<SessionConsolidationJob>> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::ClaimSessionConsolidation {
            now,
            stale_before,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Mark a claimed SessionEnd consolidation job complete.
    pub async fn complete_session_consolidation(
        &self,
        job: SessionConsolidationJob,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::CompleteSessionConsolidation { job, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Record a failed SessionEnd consolidation attempt.
    pub async fn fail_session_consolidation(
        &self,
        job: SessionConsolidationJob,
        error: String,
        retry_at: Option<i64>,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::FailSessionConsolidation {
            job,
            error,
            retry_at,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Return an in-flight SessionEnd consolidation job to the durable queue.
    pub async fn release_session_consolidation(
        &self,
        job: SessionConsolidationJob,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::ReleaseSessionConsolidation { job, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Reconcile a session's durable consolidation job row to `completed` after
    /// a manual `memory_consolidate` produced the page out-of-band. Never
    /// touches a `running` lease. Returns the number of rows updated.
    pub async fn reconcile_session_consolidation_completed(
        &self,
        session_id: SessionId,
    ) -> StoreResult<usize> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::ReconcileSessionConsolidationCompleted {
            session_id,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Insert a new handoff in `open` state.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn insert_handoff(&self, handoff: NewHandoff) -> StoreResult<HandoffId> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::InsertHandoff { handoff, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Publish a live session's turn-checkpoint baton; `None` when the session
    /// already ended or is gone. See `ops::checkpoint_session_handoff`.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn checkpoint_session_handoff(
        &self,
        handoff: NewHandoff,
    ) -> StoreResult<Option<HandoffId>> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::CheckpointSessionHandoff { handoff, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Mark a handoff accepted by the given agent / session.
    ///
    /// Returns whether this call is the one that claimed it; `false` means the
    /// row was already taken, does not belong to the expected workspace and
    /// project, or its owner does not admit this caller. The body must not reach
    /// the agent on `false`. `receiving_cwd` is where the claiming session is
    /// starting, and bounds the sweep of superseded automatic handoffs.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn accept_handoff(&self, acceptance: HandoffAcceptance) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::AcceptHandoff {
            acceptance,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Expire every open handoff in one scope, optionally only those older
    /// than `older_than_us`. Returns how many changed.
    ///
    /// Unlike the automatic sweep this does not spare manual or
    /// different-directory handoffs: those are precisely what a leftover
    /// backlog is made of. It is a state change, not a delete — the summary
    /// and provenance survive.
    ///
    /// # Errors
    /// [`StoreError::WriterClosed`], or a propagated SQL error.
    pub async fn expire_open_handoffs(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        owner_filter: OwnerFilter,
        older_than_us: Option<i64>,
        author_id: Option<ai_memory_core::UserId>,
    ) -> StoreResult<u64> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::ExpireOpenHandoffs {
            workspace_id,
            project_id,
            owner_filter,
            older_than_us,
            author_id,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Record that an embed attempt on `page_id` did not produce an
    /// embedding, so a failed or skipped page is attributable afterwards
    /// rather than only in container logs (#528).
    ///
    /// Success records nothing — that is already implied by a
    /// `page_embeddings` row — so the common path pays no extra write.
    ///
    /// # Errors
    /// [`StoreError::WriterClosed`], or a propagated SQL error.
    pub async fn record_embed_failure(
        &self,
        page_id: PageId,
        outcome: crate::ops::EmbedOutcome,
        detail: Option<String>,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::RecordEmbedFailure {
            page_id,
            outcome,
            detail,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Mark an open handoff expired so it will no longer be consumed.
    ///
    /// Returns `true` when an open handoff was changed, `false` when the id was
    /// already accepted/expired, outside the expected workspace and project,
    /// or missing.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn cancel_handoff(
        &self,
        handoff_id: HandoffId,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        owner_filter: OwnerFilter,
    ) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::CancelHandoff {
            handoff_id,
            workspace_id,
            project_id,
            owner_filter,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Send a cross-project message into a recipient project's inbox (V64).
    ///
    /// Fails when the recipient inbox is already at
    /// [`crate::ops::MAX_PENDING_INBOX_MESSAGES`] pending.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn insert_message(&self, message: NewAgentMessage) -> StoreResult<MessageId> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::InsertMessage { message, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Pop (claim exactly once) a message from a recipient project's inbox.
    ///
    /// With `specific_id`, pops that message; otherwise the oldest pending one.
    /// Returns `None` when nothing matched or another session claimed it first —
    /// the body must not reach the agent on `None`.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn pop_message(
        &self,
        claim: MessageClaim,
        specific_id: Option<MessageId>,
    ) -> StoreResult<Option<AgentMessage>> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::PopMessage {
            claim,
            specific_id,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Take a pending message out of its recipient's queue so it can be
    /// edited. Returns the message to edit, or `None` when it is no longer
    /// pending in that project (already collected, held, or not there).
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn begin_message_edit(
        &self,
        to_workspace_id: WorkspaceId,
        to_project_id: ProjectId,
        message_id: MessageId,
    ) -> StoreResult<Option<AgentMessage>> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::BeginMessageEdit {
            to_workspace_id,
            to_project_id,
            message_id,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Return an `editing` message to the queue. With `replacement` the
    /// subject and body are replaced; without it the message returns
    /// unchanged. Returns `false` when the message is not in `editing` in that
    /// project.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn finish_message_edit(
        &self,
        to_workspace_id: WorkspaceId,
        to_project_id: ProjectId,
        message_id: MessageId,
        replacement: Option<(Option<String>, String)>,
    ) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::FinishMessageEdit {
            to_workspace_id,
            to_project_id,
            message_id,
            replacement,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Retract still-pending outbox messages a project has sent. With
    /// `specific_id`, cancels just that one; otherwise every pending message
    /// this project sent. Returns how many were cancelled.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn cancel_messages(
        &self,
        from_workspace_id: WorkspaceId,
        from_project_id: ProjectId,
        specific_id: Option<MessageId>,
    ) -> StoreResult<u64> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::CancelMessages {
            from_workspace_id,
            from_project_id,
            specific_id,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Store (or replace) the embedding for one page (M9).
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn store_embedding(
        &self,
        page_id: PageId,
        vector_bytes: Vec<u8>,
        provider: String,
        model: String,
        dim: u32,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::StoreEmbedding {
            page_id,
            vector_bytes,
            provider,
            model,
            dim,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Store or replace a batch of embeddings in one SQLite transaction.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn store_embeddings(&self, embeddings: Vec<EmbeddingWrite>) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::StoreEmbeddingBatch {
            embeddings,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Store or replace a batch of L0 abstract embeddings
    /// (`page_abstract_embeddings`) in one SQLite transaction.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn store_abstract_embeddings(
        &self,
        embeddings: Vec<EmbeddingWrite>,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::StoreAbstractEmbeddingBatch {
            embeddings,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Remove a page's L0 abstract embedding row (`page_abstract_embeddings`),
    /// if any. Called when a page is rewritten without its frontmatter
    /// `abstract:` so the abstract stream never ranks a line the page no
    /// longer carries.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn delete_abstract_embedding(&self, page_id: PageId) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::DeleteAbstractEmbedding { page_id, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Remove embedding rows in a workspace/project scope whose triple does not match the configured provider/model/dim.
    ///
    /// Used when re-embedding after a model migration (e.g. Gemini → OpenRouter).
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn delete_stale_page_embeddings(
        &self,
        workspace_id: WorkspaceId,
        project_id: Option<ProjectId>,
        provider: String,
        model: String,
        dim: u32,
    ) -> StoreResult<u64> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::DeleteStalePageEmbeddings {
            workspace_id,
            project_id,
            provider,
            model,
            dim,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Bump access counters for a set of pages (M8 reinforcement term).
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn bump_access(&self, page_ids: Vec<PageId>) -> StoreResult<()> {
        self.bump_access_for_actor(page_ids, None).await
    }

    /// Bump shared access counters and record each identified operator once per
    /// page for the optional access-breadth retention term.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn bump_access_for_actor(
        &self,
        page_ids: Vec<PageId>,
        actor: Option<IdentityKey>,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::BumpAccess {
            page_ids,
            actor,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Fold buffered per-client MCP tool-call counts into their
    /// `(client, day)` buckets. Entries are deltas, not totals. Labels must
    /// already be normalized; each UTC day retains a bounded number of named
    /// clients and folds later names into the stable overflow bucket.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`], rejects malformed labels with
    /// [`StoreError::InvalidState`], or propagates SQL errors.
    pub async fn bump_client_activity(
        &self,
        entries: Vec<(String, i64, u32, u32)>,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::BumpClientActivity { entries, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Record one explicit feedback signal for a page and update its
    /// derived salience. Returns `None` when the path has no latest
    /// version in that scope.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    #[allow(clippy::too_many_arguments)]
    pub async fn record_page_feedback(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        path: PagePath,
        kind: ai_memory_core::FeedbackKind,
        reason: Option<String>,
        author_id: Option<ai_memory_core::UserId>,
        params: crate::decay::DecayParams,
    ) -> StoreResult<Option<(PageId, f64)>> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::RecordPageFeedback {
            workspace_id,
            project_id,
            path,
            kind,
            reason,
            author_id,
            params,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Tombstone the expected latest page identified by the forget sweep.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn soft_delete_for_decay_if_latest(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        path: PagePath,
        expected_latest_id: PageId,
    ) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::SoftDeleteForDecayIfLatest {
            workspace_id,
            project_id,
            path,
            expected_latest_id,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Tombstone the expected latest page whose file the watcher's reconcile
    /// pass found missing on two consecutive passes (opt-in, see #929).
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn soft_delete_for_reconcile_if_latest(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        path: PagePath,
        expected_latest_id: PageId,
    ) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::SoftDeleteForReconcileIfLatest {
            workspace_id,
            project_id,
            path,
            expected_latest_id,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Permanently delete one eligible decay tombstone and its ancestry chain.
    /// The expected latest-page state is checked in the same transaction so a
    /// page recreated at the same path cannot be removed accidentally.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    #[allow(clippy::too_many_arguments)]
    pub async fn hard_delete_decayed_page_chain(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        path: PagePath,
        tombstone_id: PageId,
        expected_latest_id: Option<PageId>,
        cutoff_us: i64,
    ) -> StoreResult<usize> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::HardDeleteDecayedPageChain {
            workspace_id,
            project_id,
            path,
            tombstone_id,
            expected_latest_id,
            cutoff_us,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Delete one bounded batch of raw observations whose session was already
    /// consolidated into a live summary page, repairing the session end
    /// watermark in the same transaction.
    ///
    /// One batch is one transaction and one mailbox message, so a multi-million
    /// row prune never holds the write lock across the whole run — every other
    /// pending write interleaves between batches.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn prune_consolidated_observations(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        cutoff_us: i64,
        batch: usize,
    ) -> StoreResult<ObservationPruneOutcome> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::PruneConsolidatedObservations {
            workspace_id,
            project_id,
            cutoff_us,
            batch,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// NULL out catch-all project `repo_path` rows so existing installs
    /// self-heal on upgrade: the broad sentinels (`$HOME` and the filesystem
    /// root) plus any path that exists locally but is not a git work-tree
    /// root. Idempotent; returns the number of rows healed.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
    pub async fn heal_catch_all_repo_paths(&self, home: Option<String>) -> StoreResult<u64> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::HealCatchAllRepoPaths { home, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Delete a project's rows in one atomic transaction. Logical unless
    /// `compaction` is [`ops::Compaction::Reclaim`].
    ///
    /// ON DELETE CASCADE propagates the delete through pages, sessions,
    /// observations, handoffs, and page_embeddings automatically. The
    /// returned [`PurgeSummary`] includes pre-delete row counts and
    /// the distinct page paths that the caller must remove from disk.
    ///
    /// `mode = `[`ops::PurgeMode::Preview`] stops right after counting and
    /// never issues the delete — see [`ops::purge_project`] for why, and for
    /// the two collateral counts (`collateral_observations_deleted`,
    /// `collateral_handoffs_denulled`) either mode reports.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or
    /// propagates the SQL error from the purge transaction.
    #[allow(clippy::too_many_arguments)]
    pub async fn purge_project(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        label: impl Into<String>,
        author_id: Option<ai_memory_core::UserId>,
        force: bool,
        compaction: crate::ops::Compaction,
        mode: crate::ops::PurgeMode,
    ) -> StoreResult<PurgeSummary> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::PurgeProject {
            workspace_id,
            project_id,
            label: label.into(),
            author_id,
            force,
            compaction,
            mode,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Delete one session by id, with everything derived from it, inside a
    /// single `(workspace, project)` scope.
    ///
    /// Scope is enforced in the store: a session that does not belong to the
    /// named workspace and project is [`StoreError::NotFound`] and nothing is
    /// deleted. See [`ops::purge_session`] for what is and is not removed —
    /// in particular, handoffs this session *accepted* are left alone.
    ///
    /// Server callers must go through `Wiki::purge_session` instead, which
    /// holds the wiki mutation guard across this deletion and the page-file
    /// cleanup. Calling this directly commits the rows with no guard, so a
    /// watcher reindex can reinsert the page before the file is removed (#653).
    ///
    /// `mode = `[`ops::PurgeMode::Preview`] stops right after counting and
    /// never issues the delete — see [`ops::purge_session`] for why, and for
    /// the two collateral counts (`collateral_observations_deleted`,
    /// `collateral_handoffs_denulled`) either mode reports.
    ///
    /// # Errors
    /// [`StoreError::NotFound`] when the session is absent from that scope,
    /// [`StoreError::WriterClosed`], or a propagated SQL error.
    pub async fn purge_session(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        session_id: SessionId,
        author_id: Option<ai_memory_core::UserId>,
        compaction: crate::ops::Compaction,
        mode: crate::ops::PurgeMode,
    ) -> StoreResult<crate::ops::PurgeSessionSummary> {
        self.purge_session_with_owner(
            workspace_id,
            project_id,
            session_id,
            author_id,
            compaction,
            mode,
            None,
        )
        .await
    }

    /// Purge only a session stamped with this exact operator, never shared legacy rows.
    /// Cross-project cascades are refused. Ownership is checked by the writer transaction.
    ///
    /// # Errors
    /// Returns NotFound for a foreign/shared session, or propagates store failures.
    pub async fn purge_owned_session(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        session_id: SessionId,
        owner: IdentityKey,
        author_id: Option<UserId>,
        mode: crate::ops::PurgeMode,
    ) -> StoreResult<crate::ops::PurgeSessionSummary> {
        self.purge_session_with_owner(
            workspace_id,
            project_id,
            session_id,
            author_id,
            crate::ops::Compaction::Skip,
            mode,
            Some(owner),
        )
        .await
    }

    #[allow(clippy::too_many_arguments)]
    async fn purge_session_with_owner(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        session_id: SessionId,
        author_id: Option<UserId>,
        compaction: crate::ops::Compaction,
        mode: crate::ops::PurgeMode,
        owner: Option<IdentityKey>,
    ) -> StoreResult<crate::ops::PurgeSessionSummary> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::PurgeSession {
            workspace_id,
            project_id,
            session_id,
            author_id,
            compaction,
            mode,
            owner,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Delete a workspace and, via the `workspace_id` cascade, every project /
    /// page / session under it. Refuses a non-empty workspace unless `force`.
    ///
    /// `mode = `[`ops::PurgeMode::Preview`] stops right after counting and
    /// never issues the delete — see [`ops::delete_workspace`] for why, and
    /// for the two collateral counts (`collateral_observations_deleted`,
    /// `collateral_handoffs_denulled`) either mode reports.
    ///
    /// # Errors
    /// [`StoreError::WorkspaceNotEmpty`] when it still holds projects and
    /// `force` is false; [`StoreError::NotFound`] when the workspace is absent;
    /// [`StoreError::WriterClosed`] if the actor has shut down.
    pub async fn delete_workspace(
        &self,
        workspace_id: WorkspaceId,
        force: bool,
        compaction: crate::ops::Compaction,
        mode: crate::ops::PurgeMode,
    ) -> StoreResult<DeleteWorkspaceSummary> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::DeleteWorkspace {
            workspace_id,
            force,
            compaction,
            mode,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Truncate the WAL, close the writer's connection and stop the actor,
    /// waiting until that has happened. Later calls fail with
    /// [`StoreError::WriterClosed`]. Returns at once if the actor already
    /// stopped.
    ///
    /// Queued behind every command already accepted, so it also waits for a
    /// long-running one (a `VACUUM`); callers bound it with a timeout. A
    /// checkpoint a reader holds back is logged, never an error.
    pub async fn checkpoint_and_close(&self) {
        let (tx, rx) = oneshot::channel();
        if self.send(WriteCmd::Close { reply: tx }).await.is_ok() {
            // The reply follows the checkpoint and the connection close; a
            // dropped sender means the actor stopped without answering.
            let _ = rx.await;
        }
    }

    /// `PRAGMA journal_size_limit` as the writer's connection reports it.
    #[cfg(test)]
    pub(crate) async fn journal_size_limit(&self) -> StoreResult<i64> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::JournalSizeLimit { reply: tx }).await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Reclaim free pages on demand, deleting nothing.
    ///
    /// Runs through the writer actor like every other exclusive operation, so
    /// it cannot overlap a write: `VACUUM` takes an exclusive lock and would
    /// otherwise contend with one.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or
    /// propagates the SQL error from the rebuild or `VACUUM`.
    pub async fn compact(&self) -> StoreResult<crate::ops::CompactSummary> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::Compact { reply: tx }).await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Delete the superseded ledger page versions the pre-#660 indexer left
    /// behind. See [`ops::reclaim_ledger_versions`].
    ///
    /// # Errors
    /// Propagates the store error from the scan, delete, FTS rebuild or
    /// `VACUUM`, plus [`StoreError::WriterClosed`].
    pub async fn reclaim_ledger_versions(
        &self,
        dry_run: bool,
        drop_latest: bool,
        compaction: crate::ops::Compaction,
    ) -> StoreResult<crate::ops::ReclaimLedgerVersionsSummary> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::ReclaimLedgerVersions {
            dry_run,
            drop_latest,
            compaction,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Rename a workspace (column-only; the on-disk dir is UUID-keyed).
    ///
    /// # Errors
    /// [`StoreError::WorkspaceNameTaken`] / [`StoreError::InvalidWorkspaceName`]
    /// / [`StoreError::NotFound`] / [`StoreError::WriterClosed`].
    pub async fn rename_workspace(
        &self,
        workspace_id: WorkspaceId,
        new_name: impl Into<String>,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::RenameWorkspace {
            workspace_id,
            new_name: new_name.into(),
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Re-stamp a project's `workspace_id` to `to_workspace` across every
    /// domain table in one transaction, keeping the same `project_id`. This is
    /// the lossless cross-workspace move: pages, sessions, observations and
    /// supersession history all follow. The destination workspace row must
    /// already exist; the caller renames the on-disk dir afterwards.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down,
    /// [`StoreError::NotFound`] if the project is absent from the source
    /// workspace, or propagates the SQL error (e.g. a
    /// `UNIQUE(workspace_id, name)` collision when the destination already
    /// holds a same-named project — the caller routes that merge case to
    /// copy+purge instead).
    pub async fn move_project_workspace(
        &self,
        project_id: ProjectId,
        from_workspace: WorkspaceId,
        to_workspace: WorkspaceId,
    ) -> StoreResult<MoveSummary> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::MoveProjectWorkspace {
            project_id,
            from_workspace,
            to_workspace,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Atomically merge one project id into another in the same workspace.
    pub async fn merge_project(
        &self,
        workspace_id: WorkspaceId,
        source_project: ProjectId,
        target_project: ProjectId,
        pages: Vec<MergeProjectPage>,
        commit: bool,
    ) -> StoreResult<MergeProjectSummary> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::MergeProject {
            workspace_id,
            source_project,
            target_project,
            pages,
            commit,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Re-stamp one session, its observations, the handoffs it produced, its
    /// consolidation jobs, auto-improve runs and scheduler claim, and its
    /// `sessions/<id>.md` page (per `pages`) into
    /// `(target_workspace, target_project)` in one transaction. With
    /// `commit = false` the transaction is rolled back after counting, so the
    /// summary is an exact dry run. The target project must already exist;
    /// the caller moves the on-disk page file afterwards. `author_id` is the
    /// operator recorded on the audit row. A target equal to the session
    /// row's own scope re-homes only the rows still lying elsewhere
    /// (`session_moved = false`); see [`ops::move_session`].
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down,
    /// [`StoreError::NotFound`] if the session or the target project is
    /// absent, [`StoreError::PagePathTaken`] when [`PagesMode::Move`] would
    /// collide with a latest page in the target scope, or propagates the SQL
    /// error.
    pub async fn move_session(
        &self,
        session_id: SessionId,
        target_workspace: WorkspaceId,
        target_project: ProjectId,
        pages: PagesMode,
        author_id: Option<UserId>,
        commit: bool,
    ) -> StoreResult<MoveSessionSummary> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::MoveSession {
            session_id,
            target_workspace,
            target_project,
            pages,
            author_id,
            commit,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Validate and, when `commit`, apply a batch of session-time
    /// corrections scoped to `(workspace_id, project_id)`, in one
    /// transaction. `commit = false` performs the same validation and writes
    /// then rolls back, so the reply is an exact dry run. See
    /// [`ops::repair_session_times`].
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or
    /// propagates the SQL error. Per-candidate scope/validation problems are
    /// reported in the returned summary, not as an `Err`.
    pub async fn repair_session_times(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        candidates: Vec<ops::SessionTimesCandidate>,
        now_us: i64,
        author_id: Option<UserId>,
        commit: bool,
    ) -> StoreResult<ops::RepairSessionTimesSummary> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::RepairSessionTimes {
            workspace_id,
            project_id,
            candidates,
            now_us,
            author_id,
            commit,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Rename a project within its workspace (column-only; no file moves).
    ///
    /// # Errors
    /// Returns [`crate::error::StoreError::WriterClosed`] if the actor has
    /// shut down, [`crate::error::StoreError::ProjectNameTaken`] if
    /// `new_name` is already in use in the same workspace, or
    /// [`crate::error::StoreError::InvalidProjectName`] for invalid names.
    pub async fn rename_project(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        new_name: impl Into<String>,
        author_id: Option<ai_memory_core::UserId>,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::RenameProject {
            workspace_id,
            project_id,
            new_name: new_name.into(),
            author_id,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Conform every latest page row to OKF in place (docs/okf.md);
    /// returns the rewritten pages so the wiki layer can align files.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or
    /// propagates the SQL error.
    pub async fn okf_migrate_latest_pages(&self) -> StoreResult<Vec<ops::OkfMigratedPage>> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::OkfMigrateLatestPages { reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Instantaneous write-queue depth as `(queued, capacity)`. A queue
    /// pinned near capacity means writers are being backpressured — the
    /// wedged-writer signal `status` surfaces (2.0 item 7).
    #[must_use]
    pub fn queue_depth(&self) -> (usize, usize) {
        let Some(tx) = self.inner.tx.as_ref() else {
            return (0, 0);
        };
        let max = tx.max_capacity();
        (max.saturating_sub(tx.capacity()), max)
    }

    /// Record a completed cross-session ("experience") pass for a scope.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or
    /// propagates the SQL error.
    pub async fn mark_experience_pass_run(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::MarkExperiencePassRun {
            workspace_id,
            project_id,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Repair, in place, the OKF `stale_after` that older builds copied
    /// verbatim from a date-only `expires_at`; returns every date-only page
    /// so the wiki layer can align the files.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or
    /// propagates the SQL error.
    pub async fn repair_date_only_stale_after(&self) -> StoreResult<ops::StaleAfterRepair> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::RepairDateOnlyStaleAfter { reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Count latest page rows still lacking OKF conformance (read-only).
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or
    /// propagates the SQL error.
    pub async fn okf_nonconformant_count(&self) -> StoreResult<u64> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::OkfNonconformantCount { reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Record a wiki-structure migration as successfully applied.
    ///
    /// Called by the wiki migration runner immediately after [`WikiMigration::up`]
    /// returns `Ok`. `applied_at` is unix microseconds UTC. If the name is
    /// already present the call is a no-op (idempotent insert-or-ignore).
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or
    /// propagates the SQL error.
    pub async fn insert_wiki_migration(&self, name: String, applied_at: i64) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::InsertWikiMigration {
            name,
            applied_at,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Retro-fit sessions and their observations to per-cwd projects and
    /// graveyard any mash-up pages. The `plan` slice contains
    /// `(session_id, new_project_id)` pairs. Everything runs in one
    /// SQLite transaction — either fully committed or fully rolled back.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or
    /// propagates the SQL error from the reorg transaction.
    pub async fn reorg_sessions(
        &self,
        workspace_id: WorkspaceId,
        plan: Vec<(SessionId, ProjectId)>,
    ) -> StoreResult<ReorgSummary> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::Reorg {
            workspace_id,
            plan,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Upsert a batch of pages atomically (one SQL transaction).
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down,
    /// or propagates the SQL error from [`ops::upsert_pages_batch`].
    pub async fn upsert_pages_batch(&self, pages: Vec<NewPage>) -> StoreResult<Vec<PageId>> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::UpsertPageBatch { pages, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Atomically upsert a batch only when every latest-version precondition
    /// still holds in the write transaction.
    pub async fn upsert_pages_batch_if(
        &self,
        pages: Vec<(NewPage, ops::PagePrecondition)>,
    ) -> StoreResult<ops::ConditionalBatchUpsert> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::UpsertPageBatchIf { pages, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Upsert a page (creating it or superseding the existing latest
    /// version when the body has changed).
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or
    /// propagates the SQL error from [`ops::upsert_page`].
    pub async fn upsert_page(&self, page: NewPage) -> StoreResult<PageId> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::UpsertPage { page, reply: tx }).await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Reindex a disk page, checking session-purge tombstones in the write
    /// transaction. A live manual replacement at a purged session's path is
    /// preserved; a leftover session summary cannot recreate deleted rows.
    ///
    /// # Errors
    /// Returns [`StoreError::SessionPurged`] for a purged summary, or the
    /// writer/SQL errors from [`Self::upsert_page`].
    pub async fn upsert_page_from_disk(&self, page: NewPage) -> StoreResult<PageId> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::UpsertPageFromDisk { page, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// [`Self::upsert_page`] only when `precondition` holds for the latest
    /// version at the page's path, checked in the write's own transaction.
    ///
    /// # Errors
    /// As [`Self::upsert_page`]. A precondition that does not hold is not an
    /// error: it returns [`ops::ConditionalUpsert::Mismatch`] and writes nothing.
    pub async fn upsert_page_if(
        &self,
        page: NewPage,
        precondition: ops::PagePrecondition,
    ) -> StoreResult<ops::ConditionalUpsert> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::UpsertPageIf {
            page,
            precondition,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Delete every version of a page (by path) from the index. The wiki file
    /// removal is the caller's concern; this drops the derived rows so the
    /// page stops appearing in search/recent (the watcher does NOT reconcile
    /// file deletions — it only handles create/modify events).
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or a
    /// SQL error from the delete.
    pub async fn delete_page(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        path: PagePath,
        author_id: Option<ai_memory_core::UserId>,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::DeletePage {
            workspace_id,
            project_id,
            path,
            author_id,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Delete every version of `path` only if `expected_latest_id` is still
    /// the latest version. Returns `false` without mutation when the page was
    /// refreshed or removed after the caller selected it.
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or a
    /// SQL error from the conditional delete.
    pub async fn delete_page_if_latest(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        path: PagePath,
        expected_latest_id: PageId,
        author_id: Option<ai_memory_core::UserId>,
    ) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::DeletePageIfLatest {
            workspace_id,
            project_id,
            path,
            expected_latest_id,
            author_id,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// One-shot root bootstrap. `password_hash` is already Argon2id PHC.
    ///
    /// # Errors
    /// Writer closed, duplicate identity, already completed, SQL.
    pub async fn bootstrap_root(
        &self,
        username: String,
        name: Option<String>,
        email: Option<String>,
        password_hash: String,
    ) -> StoreResult<UserId> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::BootstrapRoot {
            username,
            name,
            email,
            password_hash,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Break-glass root reset. Does not touch API credentials.
    ///
    /// # Errors
    /// Writer closed, duplicate, SQL.
    pub async fn recover_root(
        &self,
        username: String,
        name: Option<String>,
        email: Option<String>,
        password_hash: String,
    ) -> StoreResult<UserId> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::RecoverRoot {
            username,
            name,
            email,
            password_hash,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Grant `user_id` `role` on `repository_id` (#708).
    ///
    /// `granted_by` is the operator making the change, or `None` when they
    /// act through the root bearer token (no `users` row).
    ///
    /// # Errors
    /// Writer closed or SQL.
    pub async fn grant_memory(
        &self,
        user_id: UserId,
        repository_id: ProjectId,
        role: crate::GrantLevel,
        granted_by: Option<UserId>,
    ) -> StoreResult<crate::grants::GrantOutcome> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::GrantMemory {
            user_id,
            repository_id,
            role,
            granted_by,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Revoke whatever `user_id` actively holds on `repository_id`.
    ///
    /// Returns whether anything was in force to revoke, so calling it twice is
    /// harmless and still reports honestly.
    ///
    /// # Errors
    /// Writer closed or SQL.
    pub async fn revoke_memory(
        &self,
        user_id: UserId,
        repository_id: ProjectId,
        revoked_by: Option<UserId>,
    ) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::RevokeMemory {
            user_id,
            repository_id,
            revoked_by,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Insert a human identity. `new_user` MUST already have been validated.
    /// No API credential is created.
    ///
    /// # Errors
    /// Writer closed, duplicate username/email, SQL.
    pub async fn create_human_user(
        &self,
        new_user: NewUser,
        role: UserRole,
        password_hash: Option<String>,
        must_change_password: bool,
    ) -> StoreResult<UserId> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::CreateHumanUser {
            new_user,
            role,
            password_hash,
            must_change_password,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Admin password reset. Revokes web sessions.
    ///
    /// # Errors
    /// Writer closed / SQL.
    pub async fn reset_human_password(
        &self,
        user_id: UserId,
        password_hash: String,
        must_change_password: bool,
    ) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::ResetHumanPassword {
            user_id,
            password_hash,
            must_change_password,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Enable or disable human login. Disable revokes sessions.
    ///
    /// # Errors
    /// Last recoverable root, writer closed, SQL.
    pub async fn set_user_disabled(&self, user_id: UserId, disabled: bool) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::SetUserDisabled {
            user_id,
            disabled,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Patch name/email/role. `Some(None)` clears an optional field.
    ///
    /// # Errors
    /// Last recoverable root, duplicate email, writer closed, SQL.
    pub async fn patch_user(
        &self,
        user_id: UserId,
        name: Option<Option<String>>,
        email: Option<Option<String>>,
        role: Option<UserRole>,
    ) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::PatchUser {
            user_id,
            name,
            email,
            role,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Change password for the current session and rotate its cookies.
    ///
    /// # Errors
    /// Concurrent password change, writer closed, SQL.
    pub async fn change_password(
        &self,
        user_id: UserId,
        expected_password_hash: String,
        new_password_hash: String,
        session_id: Uuid,
        new_session_hash: [u8; TOKEN_HASH_LEN],
        new_csrf_hash: [u8; TOKEN_HASH_LEN],
    ) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::ChangePassword {
            user_id,
            expected_password_hash,
            new_password_hash,
            session_id,
            new_session_hash,
            new_csrf_hash,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Recheck PHC, role, disabled state, and must-change state, then insert
    /// a web session.
    ///
    /// # Errors
    /// Credentials no longer valid, writer closed, SQL.
    pub async fn issue_web_session(
        &self,
        user_id: UserId,
        expected_password_hash: String,
        expected_role: UserRole,
        expected_must_change: bool,
        session_hash: [u8; TOKEN_HASH_LEN],
        csrf_hash: [u8; TOKEN_HASH_LEN],
    ) -> StoreResult<WebSession> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::IssueWebSession {
            user_id,
            expected_password_hash,
            expected_role,
            expected_must_change,
            session_hash,
            csrf_hash,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Logout: revoke one session by secret hash.
    ///
    /// # Errors
    /// Writer closed / SQL.
    pub async fn revoke_web_session(
        &self,
        session_hash: [u8; TOKEN_HASH_LEN],
    ) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::RevokeWebSession {
            session_hash,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Touch `web_sessions.last_used_at` at most once per minute.
    ///
    /// # Errors
    /// Writer closed / SQL.
    pub async fn touch_web_session(
        &self,
        session_id: Uuid,
        last_used_at: i64,
    ) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::TouchWebSession {
            session_id,
            last_used_at,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Insert a native API credential. `id` is caller-chosen.
    ///
    /// # Errors
    /// Duplicate hash, writer closed, SQL.
    pub async fn create_api_credential(
        &self,
        id: ApiCredentialId,
        user_id: UserId,
        label: String,
        token_hash: [u8; TOKEN_HASH_LEN],
        preview: Option<String>,
    ) -> StoreResult<ApiCredentialId> {
        self.send_create_api_credential(id, user_id, label, token_hash, preview, None)
            .await
    }

    /// Insert a native API credential unless `user_id` already holds
    /// `max_active` active ones.
    ///
    /// # Errors
    /// [`StoreError::InvalidState`] at the limit; duplicate hash, writer
    /// closed, SQL.
    pub async fn create_api_credential_within_limit(
        &self,
        id: ApiCredentialId,
        user_id: UserId,
        label: String,
        token_hash: [u8; TOKEN_HASH_LEN],
        preview: Option<String>,
        max_active: usize,
    ) -> StoreResult<ApiCredentialId> {
        self.send_create_api_credential(id, user_id, label, token_hash, preview, Some(max_active))
            .await
    }

    async fn send_create_api_credential(
        &self,
        id: ApiCredentialId,
        user_id: UserId,
        label: String,
        token_hash: [u8; TOKEN_HASH_LEN],
        preview: Option<String>,
        max_active: Option<usize>,
    ) -> StoreResult<ApiCredentialId> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::CreateApiCredential {
            id,
            user_id,
            label,
            token_hash,
            preview,
            max_active,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Rotate a native API credential hash and un-revoke it.
    ///
    /// # Errors
    /// Duplicate hash, writer closed, SQL.
    pub async fn rotate_api_credential(
        &self,
        id: ApiCredentialId,
        new_token_hash: [u8; TOKEN_HASH_LEN],
        preview: Option<String>,
    ) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::RotateApiCredential {
            id,
            new_token_hash,
            preview,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Revoke a native API credential. Idempotent.
    ///
    /// # Errors
    /// Writer closed / SQL.
    pub async fn revoke_api_credential(&self, id: ApiCredentialId) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::RevokeApiCredential { id, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Touch `api_credentials.last_used_at`.
    ///
    /// # Errors
    /// Writer closed / SQL.
    pub async fn touch_api_credential(&self, id: ApiCredentialId) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::TouchApiCredential { id, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Record the Argon2id verifier for the configured native-key pepper.
    ///
    /// # Errors
    /// Writer closed / SQL.
    pub async fn bind_api_credential_pepper_verifier(&self, verifier: String) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::BindApiCredentialPepperVerifier {
            verifier,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Update `last_seen_at = now()` for the user. Called fire-and-forget
    /// by the auth middleware on every authenticated request. Returns
    /// `false` when the user doesn't exist (caller authenticated against
    /// a token whose user vanished mid-request — already a logic error
    /// elsewhere).
    ///
    /// # Errors
    /// Returns [`StoreError::WriterClosed`] / [`StoreError::Sqlite`].
    pub async fn touch_user_last_seen(&self, user_id: UserId) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::TouchUserLastSeen { user_id, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Stage one auto-improvement run and all proposals in one SQL transaction.
    pub async fn stage_auto_improve_run(
        &self,
        input: StageAutoImproveRun,
    ) -> StoreResult<StagedAutoImproveRun> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::StageAutoImproveRun { input, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Stage an auto-improvement run in an optional typed operator bucket,
    /// reporting target collisions without discarding sibling proposals.
    pub async fn stage_auto_improve_run_for_owner(
        &self,
        input: StageAutoImproveRun,
        owner: Option<IdentityKey>,
    ) -> StoreResult<StagedAutoImproveRunReport> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::StageAutoImproveRunForOwner {
            input,
            owner,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Reject a pending auto-improvement proposal and append an event.
    pub async fn reject_auto_improve_proposal(
        &self,
        input: RejectAutoImproveProposal,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::RejectAutoImproveProposal { input, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Mark a pending auto-improvement proposal failed and append an event.
    pub async fn fail_auto_improve_proposal(
        &self,
        input: FailAutoImproveProposal,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::FailAutoImproveProposal { input, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Approve a pending auto-improvement proposal in a DB-only transaction.
    pub async fn approve_auto_improve_proposal(
        &self,
        input: ApproveAutoImproveProposal,
    ) -> StoreResult<ApproveAutoImproveProposalResult> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::ApproveAutoImproveProposal { input, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Initialise background auto-improvement scheduler state without resetting
    /// an existing watermark.
    pub async fn ensure_auto_improve_scheduler_state(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::EnsureAutoImproveSchedulerState {
            workspace_id,
            project_id,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Atomically claim a completed session for scheduled auto-improvement
    /// before any LLM work runs. Returns `false` if another scheduler/manual run
    /// already claimed or reviewed the session.
    pub async fn claim_auto_improve_scheduler_session(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        session_id: SessionId,
        ended_at: i64,
    ) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::ClaimAutoImproveSchedulerSession {
            workspace_id,
            project_id,
            session_id,
            ended_at,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Record a failed scheduled review, releasing the session's claim for
    /// another attempt and returning the new attempt count. Returns `0` when the
    /// session holds no claim, which is the manual path.
    ///
    /// # Errors
    /// Returns an error when the writer is closed or the statement fails.
    pub async fn record_auto_improve_claim_failure(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        session_id: SessionId,
        error: &str,
    ) -> StoreResult<u32> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::RecordAutoImproveClaimFailure {
            workspace_id,
            project_id,
            session_id,
            error: error.to_owned(),
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Persist a global maintenance job's successful completion time.
    pub async fn record_maintenance_job_success(
        &self,
        job: crate::maintenance::MaintenanceJob,
    ) -> StoreResult<()> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::RecordMaintenanceJobSuccess { job, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Select a workstream and open its single active managed-run lease.
    pub async fn prepare_workstream_run(
        &self,
        input: PrepareWorkstreamRun,
    ) -> StoreResult<PreparedWorkstreamRun> {
        self.prepare_workstream_run_owned(input, None).await
    }

    /// Select a workstream and stamp the operator bucket used by safe recovery.
    pub async fn prepare_workstream_run_owned(
        &self,
        input: PrepareWorkstreamRun,
        owner_user: Option<String>,
    ) -> StoreResult<PreparedWorkstreamRun> {
        self.prepare_workstream_run_owned_with_unlock(input, owner_user, false)
            .await
    }

    /// Select a workstream, optionally replacing this same operator's active
    /// lease in the same writer transaction.
    pub async fn prepare_workstream_run_owned_with_unlock(
        &self,
        input: PrepareWorkstreamRun,
        owner_user: Option<String>,
        force_unlock: bool,
    ) -> StoreResult<PreparedWorkstreamRun> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::PrepareWorkstreamRun {
            input,
            owner_user,
            force_unlock,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Extend a managed-run lease. Returns false for missing/stale runs.
    pub async fn heartbeat_managed_run(&self, run_id: ManagedRunId) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::HeartbeatManagedRun { run_id, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Release a managed-run lease after a handled launcher failure.
    pub async fn cancel_managed_run(&self, run_id: ManagedRunId) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::CancelManagedRun { run_id, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Attach the harness-native session observed by a managed SessionStart.
    pub async fn link_managed_run_session(
        &self,
        run_id: ManagedRunId,
        agent: AgentKind,
        native_session_id: impl Into<String>,
    ) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::LinkManagedRunSession {
            run_id,
            agent,
            native_session_id: native_session_id.into(),
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Link an exact run or safely recover a stale Codex daemon run id.
    pub async fn link_or_adopt_managed_run_session(
        &self,
        input: LinkOrAdoptManagedRunSession,
    ) -> StoreResult<ManagedRunSessionLink> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::LinkOrAdoptManagedRunSession { input, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Link the native session a later hook event of a managed run reported,
    /// within the run's own project and operator boundary.
    pub async fn link_managed_run_session_in_scope(
        &self,
        input: LinkManagedRunSessionInScope,
    ) -> StoreResult<ManagedRunSessionLink> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::LinkManagedRunSessionInScope { input, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Acknowledge successful SessionStart delivery for a managed run.
    pub async fn accept_managed_run_context(&self, run_id: ManagedRunId) -> StoreResult<bool> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::AcceptManagedRunContext { run_id, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Atomically claim the handoff and managed ledger selected for one
    /// SessionStart response.
    ///
    /// When a managed run was requested but is no longer claimable, the
    /// handoff remains open and both result fields are false. `busy_since` is
    /// the same cutoff the selection used
    /// ([`crate::ReaderPool::startup_handoff`]), re-applied in the claim's
    /// transaction: a baton whose open source captured anything after it stays
    /// open.
    pub async fn accept_startup_context(
        &self,
        handoff: Option<HandoffAcceptance>,
        managed_run_id: Option<ManagedRunId>,
        receiving_session: Option<NewSession>,
        busy_since: jiff::Timestamp,
    ) -> StoreResult<StartupContextAcceptance> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::AcceptStartupContext {
            handoff,
            managed_run_id,
            receiving_session,
            busy_since,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Index an immutable transcript segment and release the run lease.
    pub async fn finish_workstream_run(
        &self,
        authority: crate::ManagedRunAuthority,
        input: FinishWorkstreamRun,
    ) -> StoreResult<FinishedWorkstreamRun> {
        self.finish_workstream_run_inner(authority, input, false)
            .await
    }

    /// Finish an expired run for its original owner when it was not superseded.
    pub async fn recover_expired_workstream_run(
        &self,
        authority: crate::ManagedRunAuthority,
        input: FinishWorkstreamRun,
    ) -> StoreResult<FinishedWorkstreamRun> {
        self.finish_workstream_run_inner(authority, input, true)
            .await
    }

    async fn finish_workstream_run_inner(
        &self,
        authority: crate::ManagedRunAuthority,
        input: FinishWorkstreamRun,
        recover_expired: bool,
    ) -> StoreResult<FinishedWorkstreamRun> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::FinishWorkstreamRun {
            authority,
            input,
            recover_expired,
            reply: tx,
        })
        .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    /// Retitle one checkout-local workstream, leaving its selection and
    /// activity timestamps untouched.
    pub async fn rename_workstream(
        &self,
        input: RenameWorkstream,
    ) -> StoreResult<RenamedWorkstream> {
        let (tx, rx) = oneshot::channel();
        self.send(WriteCmd::RenameWorkstream { input, reply: tx })
            .await?;
        rx.await.map_err(|_| StoreError::WriterClosed)?
    }

    async fn send(&self, cmd: WriteCmd) -> StoreResult<()> {
        self.inner
            .tx
            .as_ref()
            .ok_or(StoreError::WriterClosed)?
            .send(cmd)
            .await
            .map_err(|_| StoreError::WriterClosed)
    }
}

impl Drop for WriterInner {
    fn drop(&mut self) {
        // A full mailbox cannot accept Shutdown. Drop the last sender before
        // joining so the worker still exits after draining accepted commands.
        // Keeping the sender alive here would leave it waiting for more work
        // forever while this thread waits for it to finish.
        if let Some(tx) = self.tx.take() {
            let _ = tx.try_send(WriteCmd::Shutdown);
        }
        #[cfg(test)]
        if let Some(before_join) = self.before_join.take() {
            before_join();
        }
        if let Some(handle) = self.join.lock().expect("writer join mutex poisoned").take() {
            let _ = handle.join();
        }
    }
}

/// Dispatch one operation's result back to its caller. Logs a warn
/// when the receiver was dropped (caller cancelled their `.await` or
/// hit a timeout) so the operator sees backpressure / cancellation
/// noise instead of silent loss. The result itself is consumed by
/// the failed `send` and discarded — the caller's await has already
/// returned a JoinError-shaped failure by this point.
fn send_or_warn<T>(reply: oneshot::Sender<T>, result: T, op: &'static str) {
    if reply.send(result).is_err() {
        tracing::warn!(
            op,
            "writer reply dropped — caller cancelled or oneshot receiver closed"
        );
    }
}

fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
    // The mode a newly created project starts in — the server's
    // `[auth] new_projects_restricted`, set once at startup. Held here because
    // this actor performs every project insert, so no creation path can
    // forget to apply it.
    let mut new_project_mode = crate::AccessMode::Open;
    while let Some(cmd) = rx.blocking_recv() {
        match cmd {
            WriteCmd::SetNewProjectMode { mode, reply } => {
                new_project_mode = mode;
                send_or_warn(reply, Ok(()), "set_new_project_mode");
            }
            WriteCmd::SetAccessMode {
                project_id,
                mode,
                reply,
            } => {
                let result = crate::grants::set_access_mode(&conn, project_id, mode);
                send_or_warn(reply, result, "set_access_mode");
            }
            WriteCmd::SetProjectProfileFlags {
                project_id,
                flags,
                reply,
            } => {
                let result = crate::profile::set_project_profile_flags(&conn, project_id, flags);
                send_or_warn(reply, result, "set_project_profile_flags");
            }
            WriteCmd::RecordProfileHarvest {
                workspace_id,
                project_id,
                candidates,
                mark,
                reply,
            } => {
                let result = crate::profile::record_profile_harvest(
                    &mut conn,
                    workspace_id,
                    project_id,
                    &candidates,
                    mark,
                );
                send_or_warn(reply, result, "record_profile_harvest");
            }
            WriteCmd::RecordProfileEntries {
                workspace_id,
                project_id,
                entries,
                reply,
            } => {
                let result = crate::profile::record_profile_entries(
                    &mut conn,
                    workspace_id,
                    project_id,
                    &entries,
                );
                send_or_warn(reply, result, "record_profile_entries");
            }
            WriteCmd::ClearProfileHarvestMarks { reply } => {
                let result = crate::profile::clear_profile_harvest_marks(&conn);
                send_or_warn(reply, result, "clear_profile_harvest_marks");
            }
            WriteCmd::Shutdown => {
                // Dropping the receiver drains the queue, but a sender that
                // already holds a permit can still push afterwards; that
                // command would never be dropped and its caller would wait
                // forever. Closing first and receiving until `None` waits for
                // those in-flight sends, and dropping each command drops its
                // reply, so every caller sees `WriterClosed`.
                rx.close();
                while rx.blocking_recv().is_some() {}
                break;
            }
            WriteCmd::AuthorizeProject {
                workspace_id,
                project_id,
                principal,
                distinguishes_operators,
                need,
                reply,
            } => {
                let result = crate::project_authz::resolve_project_authz(
                    &conn,
                    workspace_id,
                    project_id,
                    &principal,
                    distinguishes_operators,
                )
                .map(|ctx| ctx.authorize(need));
                send_or_warn(reply, result, "authorize_project");
            }
            WriteCmd::GetOrCreateWorkspace { name, reply } => {
                let result = ops::get_or_create_workspace(&mut conn, &name);
                send_or_warn(reply, result, "get_or_create_workspace");
            }
            WriteCmd::GetOrCreateProject {
                workspace_id,
                name,
                repo_path,
                reply,
            } => {
                // Through the creator-aware path with no creator, so the
                // server's new-project mode applies here too.
                let result = ops::get_or_create_project_as(
                    &mut conn,
                    &workspace_id,
                    &name,
                    repo_path.as_deref(),
                    None,
                    new_project_mode,
                )
                .map(|(id, _)| id);
                send_or_warn(reply, result, "get_or_create_project");
            }
            WriteCmd::GetOrCreateProjectAs {
                workspace_id,
                name,
                repo_path,
                creator,
                reply,
            } => {
                let result = ops::get_or_create_project_as(
                    &mut conn,
                    &workspace_id,
                    &name,
                    repo_path.as_deref(),
                    creator,
                    new_project_mode,
                );
                send_or_warn(reply, result, "get_or_create_project_as");
            }
            WriteCmd::ResolveProjectByIdentity {
                workspace_id,
                identity,
                style,
                promote,
                name,
                repo_path,
                candidate,
                creator,
                reply,
            } => {
                let result = ops::resolve_project_by_identity(
                    &mut conn,
                    &workspace_id,
                    &identity,
                    style,
                    promote,
                    &name,
                    repo_path.as_deref(),
                    candidate,
                    creator,
                    new_project_mode,
                );
                send_or_warn(reply, result, "resolve_project_by_identity");
            }
            WriteCmd::ResolveProjectNameForWrite {
                workspace_id,
                name,
                principal,
                distinguishes_operators,
                promote,
                reply,
            } => {
                let result = ops::resolve_project_name_for_write(
                    &mut conn,
                    &workspace_id,
                    &name,
                    principal.as_ref(),
                    distinguishes_operators,
                    promote,
                    new_project_mode,
                );
                send_or_warn(reply, result, "resolve_project_name_for_write");
            }
            WriteCmd::ResolveProjectAliasesForWrite {
                workspace_id,
                canonical,
                aliases,
                repository,
                principal,
                distinguishes_operators,
                reply,
            } => {
                let result = ops::resolve_project_aliases_for_write(
                    &mut conn,
                    &workspace_id,
                    &canonical,
                    &aliases,
                    &repository,
                    principal.as_ref(),
                    distinguishes_operators,
                );
                send_or_warn(reply, result, "resolve_project_aliases_for_write");
            }
            WriteCmd::EnsureProjectWorkspace {
                workspace_id,
                project_id,
                reply,
            } => {
                let result = ops::ensure_project_workspace(&conn, &workspace_id, &project_id);
                send_or_warn(reply, result, "ensure_project_workspace");
            }
            WriteCmd::EnsureWorkspaceWithId { id, name, reply } => {
                let result = ops::ensure_workspace_with_id(&mut conn, id, &name);
                send_or_warn(reply, result, "ensure_workspace_with_id");
            }
            WriteCmd::EnsureProjectWithId {
                id,
                workspace_id,
                name,
                repo_path,
                identity,
                reply,
            } => {
                let result = ops::ensure_project_with_id(
                    &mut conn,
                    id,
                    workspace_id,
                    &name,
                    repo_path.as_deref(),
                    identity.as_ref(),
                );
                send_or_warn(reply, result, "ensure_project_with_id");
            }
            WriteCmd::ScopeIsPurged {
                workspace_id,
                project_id,
                reply,
            } => {
                let result = ops::scope_is_purged(&conn, &workspace_id, &project_id);
                send_or_warn(reply, result, "scope_is_purged");
            }
            WriteCmd::PurgedSessionIds {
                workspace_id,
                project_id,
                reply,
            } => {
                let result = ops::purged_session_ids(&conn, &workspace_id, &project_id);
                send_or_warn(reply, result, "purged_session_ids");
            }
            WriteCmd::RecordBootstrapChunk {
                fingerprint,
                chunk_index,
                pages_json,
                rationale,
                reply,
            } => {
                let result = ops::record_bootstrap_chunk(
                    &conn,
                    &fingerprint,
                    chunk_index,
                    &pages_json,
                    &rationale,
                );
                send_or_warn(reply, result, "record_bootstrap_chunk");
            }
            WriteCmd::LoadBootstrapProgress { fingerprint, reply } => {
                let result = ops::load_bootstrap_progress(&conn, &fingerprint);
                send_or_warn(reply, result, "load_bootstrap_progress");
            }
            WriteCmd::ClearBootstrapProgress { fingerprint, reply } => {
                let result = ops::clear_bootstrap_progress(&conn, &fingerprint);
                send_or_warn(reply, result, "clear_bootstrap_progress");
            }
            WriteCmd::UpsertPage { page, reply } => {
                let result = ops::upsert_page(&mut conn, &page);
                send_or_warn(reply, result, "upsert_page");
            }
            WriteCmd::UpsertPageFromDisk { page, reply } => {
                let result = ops::upsert_page_from_disk(&mut conn, &page);
                send_or_warn(reply, result, "upsert_page_from_disk");
            }
            WriteCmd::UpsertPageIf {
                page,
                precondition,
                reply,
            } => {
                let result = ops::upsert_page_if(&mut conn, &page, precondition);
                send_or_warn(reply, result, "upsert_page_if");
            }
            WriteCmd::DeletePage {
                workspace_id,
                project_id,
                path,
                author_id,
                reply,
            } => {
                let result =
                    ops::delete_page(&mut conn, workspace_id, project_id, &path, author_id);
                send_or_warn(reply, result, "delete_page");
            }
            WriteCmd::DeletePageIfLatest {
                workspace_id,
                project_id,
                path,
                expected_latest_id,
                author_id,
                reply,
            } => {
                let result = ops::delete_page_if_latest(
                    &mut conn,
                    workspace_id,
                    project_id,
                    &path,
                    expected_latest_id,
                    author_id,
                );
                send_or_warn(reply, result, "delete_page_if_latest");
            }
            WriteCmd::UpsertPageBatch { pages, reply } => {
                let result = ops::upsert_pages_batch(&mut conn, &pages);
                send_or_warn(reply, result, "upsert_pages_batch");
            }
            WriteCmd::UpsertPageBatchIf { pages, reply } => {
                let result = ops::upsert_pages_batch_if(&mut conn, &pages);
                send_or_warn(reply, result, "upsert_pages_batch_if");
            }
            WriteCmd::BeginSession { session, reply } => {
                let result = ops::begin_session(&mut conn, &session);
                send_or_warn(reply, result, "begin_session");
            }
            WriteCmd::EndSession {
                session_id,
                summary_page_id,
                reply,
            } => {
                let result = ops::end_session(&mut conn, &session_id, summary_page_id.as_ref());
                send_or_warn(reply, result, "end_session");
            }
            WriteCmd::UpsertTokenCalls {
                session_id,
                calls,
                reply,
            } => {
                let result = ops::upsert_token_calls(&mut conn, session_id, &calls);
                send_or_warn(reply, result, "upsert_token_calls");
            }
            WriteCmd::UpsertSessionUsage { usage, reply } => {
                let result = ops::upsert_session_usage(&conn, &usage);
                send_or_warn(reply, result, "upsert_session_usage");
            }
            WriteCmd::EndSessionWithHandoff {
                session_id,
                summary_page_id,
                handoff,
                reply,
            } => {
                let result = ops::end_session_with_handoff(
                    &mut conn,
                    &session_id,
                    summary_page_id.as_ref(),
                    &handoff,
                );
                send_or_warn(reply, result, "end_session_with_handoff");
            }
            WriteCmd::EndLifecycleOnlySession { session_id, reply } => {
                let result = ops::end_lifecycle_only_session(&mut conn, &session_id);
                send_or_warn(reply, result, "end_lifecycle_only_session");
            }
            WriteCmd::EndIdleSessions {
                candidates,
                enqueue_consolidation,
                reply,
            } => {
                let result = ops::idle_end_sessions(&mut conn, &candidates, enqueue_consolidation);
                send_or_warn(reply, result, "idle_end_sessions");
            }
            #[cfg(test)]
            WriteCmd::EndIdleSessionsPreStamp {
                candidates,
                enqueue_consolidation,
                pre_stamp,
                reply,
            } => {
                let mut pre_stamp = pre_stamp;
                let result = ops::idle_end_sessions_pre_stamp(
                    &mut conn,
                    &candidates,
                    enqueue_consolidation,
                    &mut pre_stamp,
                );
                send_or_warn(reply, result, "idle_end_sessions_pre_stamp");
            }
            WriteCmd::SweepHollowProjects {
                min_age_days,
                reply,
            } => {
                let result = ops::sweep_hollow_projects(&mut conn, min_age_days);
                send_or_warn(reply, result, "sweep_hollow_projects");
            }
            WriteCmd::CloseAbandonedSessions { cutoff_us, reply } => {
                let result = ops::close_abandoned_sessions(&conn, cutoff_us);
                send_or_warn(reply, result, "close_abandoned_sessions");
            }
            WriteCmd::InsertObservation { obs, reply } => {
                let result = ops::insert_observation(&mut conn, &obs);
                send_or_warn(reply, result, "insert_observation");
            }
            WriteCmd::InsertObservationIngest {
                obs,
                ingest_key,
                reply,
            } => {
                let result = ops::insert_observation_keyed(&mut conn, &obs, &ingest_key);
                send_or_warn(reply, result, "insert_observation_ingest");
            }
            WriteCmd::AdmitHookSessionEvent {
                session,
                obs,
                owner_filter,
                ingest_key,
                moved_from_cwd,
                reply,
            } => {
                let result = ops::admit_hook_session_event(
                    &mut conn,
                    &session,
                    &obs,
                    &owner_filter,
                    ingest_key.as_deref(),
                    moved_from_cwd.as_deref(),
                );
                send_or_warn(reply, result, "admit_hook_session_event");
            }
            WriteCmd::EndAdmittedSession {
                admitted,
                summary_page_id,
                occurred_at,
                reply,
            } => {
                let result = ops::end_admitted_session(
                    &mut conn,
                    &admitted,
                    summary_page_id.as_ref(),
                    occurred_at,
                );
                send_or_warn(reply, result, "end_admitted_session");
            }
            WriteCmd::EndAdmittedSessionWithHandoff {
                admitted,
                summary_page_id,
                handoff,
                occurred_at,
                reply,
            } => {
                let result = ops::end_admitted_session_with_handoff(
                    &mut conn,
                    &admitted,
                    summary_page_id.as_ref(),
                    &handoff,
                    occurred_at,
                );
                send_or_warn(reply, result, "end_admitted_session_with_handoff");
            }
            WriteCmd::EndAdmittedLifecycleOnlySession {
                admitted,
                occurred_at,
                reply,
            } => {
                let result =
                    ops::end_admitted_lifecycle_only_session(&mut conn, &admitted, occurred_at);
                send_or_warn(reply, result, "end_admitted_lifecycle_only_session");
            }
            WriteCmd::CompleteObservationIngest {
                project_id,
                ingest_key,
                reply,
            } => {
                let result = ops::complete_observation_ingest(&mut conn, &project_id, &ingest_key);
                send_or_warn(reply, result, "complete_observation_ingest");
            }
            WriteCmd::CompleteObservationIngestIfClaimed {
                project_id,
                ingest_key,
                reply,
            } => {
                let result = ops::complete_observation_ingest_if_claimed(
                    &mut conn,
                    &project_id,
                    &ingest_key,
                );
                send_or_warn(reply, result, "complete_observation_ingest_if_claimed");
            }
            WriteCmd::EnqueueSessionConsolidation {
                workspace_id,
                project_id,
                session_id,
                reply,
            } => {
                let result = crate::session_consolidation::enqueue(
                    &mut conn,
                    workspace_id,
                    project_id,
                    session_id,
                );
                send_or_warn(reply, result, "enqueue_session_consolidation");
            }
            WriteCmd::EnqueueSessionCheckpoint {
                workspace_id,
                project_id,
                session_id,
                reply,
            } => {
                let result = crate::session_consolidation::enqueue_checkpoint(
                    &mut conn,
                    workspace_id,
                    project_id,
                    session_id,
                );
                send_or_warn(reply, result, "enqueue_session_checkpoint");
            }
            WriteCmd::ClaimSessionConsolidation {
                now,
                stale_before,
                reply,
            } => {
                let result = crate::session_consolidation::claim_next(&mut conn, now, stale_before);
                send_or_warn(reply, result, "claim_session_consolidation");
            }
            WriteCmd::CompleteSessionConsolidation { job, reply } => {
                let result = crate::session_consolidation::complete(&mut conn, &job);
                send_or_warn(reply, result, "complete_session_consolidation");
            }
            WriteCmd::FailSessionConsolidation {
                job,
                error,
                retry_at,
                reply,
            } => {
                let result = crate::session_consolidation::fail(&mut conn, &job, &error, retry_at);
                send_or_warn(reply, result, "fail_session_consolidation");
            }
            WriteCmd::ReleaseSessionConsolidation { job, reply } => {
                let result = crate::session_consolidation::release(&mut conn, &job);
                send_or_warn(reply, result, "release_session_consolidation");
            }
            WriteCmd::ReconcileSessionConsolidationCompleted { session_id, reply } => {
                let result =
                    crate::session_consolidation::reconcile_session_consolidation_completed(
                        &mut conn, session_id,
                    );
                send_or_warn(reply, result, "reconcile_session_consolidation_completed");
            }
            WriteCmd::InsertHandoff { handoff, reply } => {
                let result = ops::insert_handoff(&mut conn, &handoff);
                send_or_warn(reply, result, "insert_handoff");
            }
            WriteCmd::CheckpointSessionHandoff { handoff, reply } => {
                let result = ops::checkpoint_session_handoff(&mut conn, &handoff);
                send_or_warn(reply, result, "checkpoint_session_handoff");
            }
            WriteCmd::AcceptHandoff { acceptance, reply } => {
                let result = ops::accept_handoff(&mut conn, &acceptance);
                send_or_warn(reply, result, "accept_handoff");
            }
            WriteCmd::ExpireOpenHandoffs {
                workspace_id,
                project_id,
                owner_filter,
                older_than_us,
                author_id,
                reply,
            } => {
                let result = ops::expire_open_handoffs(
                    &mut conn,
                    &workspace_id,
                    &project_id,
                    &owner_filter,
                    older_than_us,
                    author_id,
                );
                send_or_warn(reply, result, "expire_open_handoffs");
            }
            WriteCmd::RecordEmbedFailure {
                page_id,
                outcome,
                detail,
                reply,
            } => {
                let result = ops::record_embed_failure(&conn, &page_id, outcome, detail.as_deref());
                send_or_warn(reply, result, "record_embed_failure");
            }
            WriteCmd::CancelHandoff {
                handoff_id,
                workspace_id,
                project_id,
                owner_filter,
                reply,
            } => {
                let result = ops::cancel_handoff(
                    &mut conn,
                    &handoff_id,
                    &workspace_id,
                    &project_id,
                    &owner_filter,
                );
                send_or_warn(reply, result, "cancel_handoff");
            }
            WriteCmd::InsertMessage { message, reply } => {
                let result = ops::insert_message(&mut conn, &message);
                send_or_warn(reply, result, "insert_message");
            }
            WriteCmd::PopMessage {
                claim,
                specific_id,
                reply,
            } => {
                let result = ops::pop_message(&mut conn, &claim, specific_id);
                send_or_warn(reply, result, "pop_message");
            }
            WriteCmd::BeginMessageEdit {
                to_workspace_id,
                to_project_id,
                message_id,
                reply,
            } => {
                let result = ops::begin_message_edit(
                    &mut conn,
                    &to_workspace_id,
                    &to_project_id,
                    message_id,
                );
                send_or_warn(reply, result, "begin_message_edit");
            }
            WriteCmd::FinishMessageEdit {
                to_workspace_id,
                to_project_id,
                message_id,
                replacement,
                reply,
            } => {
                let result = ops::finish_message_edit(
                    &mut conn,
                    &to_workspace_id,
                    &to_project_id,
                    message_id,
                    replacement
                        .as_ref()
                        .map(|(subject, body)| (subject.as_deref(), body.as_str())),
                );
                send_or_warn(reply, result, "finish_message_edit");
            }
            WriteCmd::CancelMessages {
                from_workspace_id,
                from_project_id,
                specific_id,
                reply,
            } => {
                let result = ops::cancel_messages(
                    &mut conn,
                    &from_workspace_id,
                    &from_project_id,
                    specific_id,
                );
                send_or_warn(reply, result, "cancel_messages");
            }
            WriteCmd::Reorg {
                workspace_id,
                plan,
                reply,
            } => {
                let result = ops::reorg_sessions(&mut conn, &workspace_id, &plan);
                send_or_warn(reply, result, "reorg_sessions");
            }
            WriteCmd::RecordPageFeedback {
                workspace_id,
                project_id,
                path,
                kind,
                reason,
                author_id,
                params,
                reply,
            } => {
                let result = ops::record_page_feedback(
                    &mut conn,
                    workspace_id,
                    project_id,
                    &path,
                    kind,
                    reason.as_deref(),
                    author_id,
                    &params,
                );
                send_or_warn(reply, result, "record_page_feedback");
            }
            WriteCmd::BumpAccess {
                page_ids,
                actor,
                reply,
            } => {
                let result =
                    ops::bump_access_for_pages_for_actor(&mut conn, &page_ids, actor.as_ref());
                send_or_warn(reply, result, "bump_access_for_pages");
            }
            WriteCmd::BumpClientActivity { entries, reply } => {
                let result = ops::bump_client_activity(&mut conn, &entries);
                send_or_warn(reply, result, "bump_client_activity");
            }
            WriteCmd::SoftDeleteForDecayIfLatest {
                workspace_id,
                project_id,
                path,
                expected_latest_id,
                reply,
            } => {
                let result = ops::soft_delete_for_decay_if_latest(
                    &mut conn,
                    workspace_id,
                    project_id,
                    &path,
                    expected_latest_id,
                );
                send_or_warn(reply, result, "soft_delete_for_decay_if_latest");
            }
            WriteCmd::SoftDeleteForReconcileIfLatest {
                workspace_id,
                project_id,
                path,
                expected_latest_id,
                reply,
            } => {
                let result = ops::soft_delete_for_reconcile_if_latest(
                    &mut conn,
                    workspace_id,
                    project_id,
                    &path,
                    expected_latest_id,
                );
                send_or_warn(reply, result, "soft_delete_for_reconcile_if_latest");
            }
            WriteCmd::HardDeleteDecayedPageChain {
                workspace_id,
                project_id,
                path,
                tombstone_id,
                expected_latest_id,
                cutoff_us,
                reply,
            } => {
                let result = ops::hard_delete_decayed_page_chain(
                    &mut conn,
                    workspace_id,
                    project_id,
                    &path,
                    tombstone_id,
                    expected_latest_id,
                    cutoff_us,
                );
                send_or_warn(reply, result, "hard_delete_decayed_page_chain");
            }
            WriteCmd::PruneConsolidatedObservations {
                workspace_id,
                project_id,
                cutoff_us,
                batch,
                reply,
            } => {
                let result = ops::prune_consolidated_observations(
                    &mut conn,
                    workspace_id,
                    project_id,
                    cutoff_us,
                    batch,
                );
                send_or_warn(reply, result, "prune_consolidated_observations");
            }
            WriteCmd::HealCatchAllRepoPaths { home, reply } => {
                let result = ops::heal_catch_all_repo_paths(&mut conn, home.as_deref());
                send_or_warn(reply, result, "heal_catch_all_repo_paths");
            }
            WriteCmd::StoreEmbedding {
                page_id,
                vector_bytes,
                provider,
                model,
                dim,
                reply,
            } => {
                let result = ops::store_embedding(
                    &mut conn,
                    &page_id,
                    &vector_bytes,
                    &provider,
                    &model,
                    dim,
                );
                send_or_warn(reply, result, "store_embedding");
            }
            WriteCmd::StoreEmbeddingBatch { embeddings, reply } => {
                let result = ops::store_embeddings(&mut conn, &embeddings);
                send_or_warn(reply, result, "store_embeddings");
            }
            WriteCmd::StoreAbstractEmbeddingBatch { embeddings, reply } => {
                let result = ops::store_abstract_embeddings(&mut conn, &embeddings);
                send_or_warn(reply, result, "store_abstract_embeddings");
            }
            WriteCmd::DeleteAbstractEmbedding { page_id, reply } => {
                let result = ops::delete_abstract_embedding(&mut conn, &page_id);
                send_or_warn(reply, result, "delete_abstract_embedding");
            }
            WriteCmd::DeleteStalePageEmbeddings {
                workspace_id,
                project_id,
                provider,
                model,
                dim,
                reply,
            } => {
                let result = ops::delete_stale_page_embeddings(
                    &mut conn,
                    &workspace_id,
                    project_id.as_ref(),
                    &provider,
                    &model,
                    dim,
                );
                send_or_warn(reply, result, "delete_stale_page_embeddings");
            }
            WriteCmd::PurgeProject {
                workspace_id,
                project_id,
                label,
                author_id,
                force,
                compaction,
                mode,
                reply,
            } => {
                let result = ops::purge_project(
                    &mut conn,
                    &workspace_id,
                    &project_id,
                    &label,
                    author_id,
                    force,
                    compaction,
                    mode,
                );
                send_or_warn(reply, result, "purge_project");
            }
            WriteCmd::PurgeSession {
                workspace_id,
                project_id,
                session_id,
                author_id,
                compaction,
                mode,
                owner,
                reply,
            } => {
                let result = ops::purge_session_with_owner(
                    &mut conn,
                    workspace_id,
                    project_id,
                    session_id,
                    author_id,
                    compaction,
                    mode,
                    owner.as_ref(),
                );
                send_or_warn(reply, result, "purge_session");
            }
            WriteCmd::Close { reply } => {
                ops::truncate_wal_best_effort(&conn, "shutdown");
                // Close before replying, so the caller's return means the
                // connection is released.
                drop(conn);
                send_or_warn(reply, (), "close");
                // Same drain as `Shutdown`: callers that already hold a
                // permit see `WriterClosed` instead of waiting forever.
                rx.close();
                while rx.blocking_recv().is_some() {}
                break;
            }
            #[cfg(test)]
            WriteCmd::JournalSizeLimit { reply } => {
                let result = conn
                    .query_row("PRAGMA journal_size_limit", [], |row| row.get(0))
                    .map_err(StoreError::from);
                send_or_warn(reply, result, "journal_size_limit");
            }
            WriteCmd::Compact { reply } => {
                let result = ops::compact(&mut conn);
                send_or_warn(reply, result, "compact");
            }
            WriteCmd::ReclaimLedgerVersions {
                dry_run,
                drop_latest,
                compaction,
                reply,
            } => {
                let result =
                    ops::reclaim_ledger_versions(&mut conn, dry_run, drop_latest, compaction);
                send_or_warn(reply, result, "reclaim_ledger_versions");
            }
            WriteCmd::DeleteWorkspace {
                workspace_id,
                force,
                compaction,
                mode,
                reply,
            } => {
                let result =
                    ops::delete_workspace(&mut conn, &workspace_id, force, compaction, mode);
                send_or_warn(reply, result, "delete_workspace");
            }
            WriteCmd::RenameWorkspace {
                workspace_id,
                new_name,
                reply,
            } => {
                let result = ops::rename_workspace(&mut conn, &workspace_id, &new_name);
                send_or_warn(reply, result, "rename_workspace");
            }
            WriteCmd::MoveProjectWorkspace {
                project_id,
                from_workspace,
                to_workspace,
                reply,
            } => {
                let result = ops::move_project_workspace(
                    &mut conn,
                    &project_id,
                    &from_workspace,
                    &to_workspace,
                );
                send_or_warn(reply, result, "move_project_workspace");
            }
            WriteCmd::MergeProject {
                workspace_id,
                source_project,
                target_project,
                pages,
                commit,
                reply,
            } => {
                let result = ops::merge_project(
                    &mut conn,
                    workspace_id,
                    source_project,
                    target_project,
                    &pages,
                    commit,
                );
                send_or_warn(reply, result, "merge_project");
            }
            WriteCmd::MoveSession {
                session_id,
                target_workspace,
                target_project,
                pages,
                author_id,
                commit,
                reply,
            } => {
                let result = ops::move_session(
                    &mut conn,
                    session_id,
                    target_workspace,
                    target_project,
                    pages,
                    author_id,
                    commit,
                );
                send_or_warn(reply, result, "move_session");
            }
            WriteCmd::RepairSessionTimes {
                workspace_id,
                project_id,
                candidates,
                now_us,
                author_id,
                commit,
                reply,
            } => {
                let result = ops::repair_session_times(
                    &mut conn,
                    workspace_id,
                    project_id,
                    &candidates,
                    now_us,
                    author_id,
                    commit,
                );
                send_or_warn(reply, result, "repair_session_times");
            }
            WriteCmd::RenameProject {
                workspace_id,
                project_id,
                new_name,
                author_id,
                reply,
            } => {
                let result = ops::rename_project(
                    &mut conn,
                    &workspace_id,
                    &project_id,
                    &new_name,
                    author_id,
                );
                send_or_warn(reply, result, "rename_project");
            }
            WriteCmd::OkfMigrateLatestPages { reply } => {
                let result = ops::okf_migrate_latest_pages(&mut conn);
                send_or_warn(reply, result, "okf_migrate_latest_pages");
            }
            WriteCmd::RepairDateOnlyStaleAfter { reply } => {
                let result = ops::repair_date_only_stale_after(&mut conn);
                send_or_warn(reply, result, "repair_date_only_stale_after");
            }
            WriteCmd::OkfNonconformantCount { reply } => {
                let result = ops::okf_nonconformant_latest_pages(&conn);
                send_or_warn(reply, result, "okf_nonconformant_count");
            }
            WriteCmd::MarkExperiencePassRun {
                workspace_id,
                project_id,
                reply,
            } => {
                let result = crate::auto_improve::mark_experience_pass_run(
                    &mut conn,
                    workspace_id,
                    project_id,
                );
                send_or_warn(reply, result, "mark_experience_pass_run");
            }
            WriteCmd::InsertWikiMigration {
                name,
                applied_at,
                reply,
            } => {
                let result = ops::insert_wiki_migration(&mut conn, &name, applied_at);
                send_or_warn(reply, result, "insert_wiki_migration");
            }
            WriteCmd::BootstrapRoot {
                username,
                name,
                email,
                password_hash,
                reply,
            } => {
                let result = users::bootstrap_root(
                    &mut conn,
                    &username,
                    name.as_deref(),
                    email.as_deref(),
                    &password_hash,
                );
                send_or_warn(reply, result, "bootstrap_root");
            }
            WriteCmd::RecoverRoot {
                username,
                name,
                email,
                password_hash,
                reply,
            } => {
                let result = users::recover_root(
                    &mut conn,
                    &username,
                    name.as_deref(),
                    email.as_deref(),
                    &password_hash,
                );
                send_or_warn(reply, result, "recover_root");
            }
            WriteCmd::GrantMemory {
                user_id,
                repository_id,
                role,
                granted_by,
                reply,
            } => {
                let result = crate::grants::grant(
                    &conn,
                    user_id,
                    repository_id,
                    role,
                    granted_by,
                    jiff::Timestamp::now().as_microsecond(),
                );
                send_or_warn(reply, result, "grant_memory");
            }
            WriteCmd::RevokeMemory {
                user_id,
                repository_id,
                revoked_by,
                reply,
            } => {
                let result = crate::grants::revoke(
                    &conn,
                    user_id,
                    repository_id,
                    revoked_by,
                    jiff::Timestamp::now().as_microsecond(),
                );
                send_or_warn(reply, result, "revoke_memory");
            }
            WriteCmd::CreateHumanUser {
                new_user,
                role,
                password_hash,
                must_change_password,
                reply,
            } => {
                let result = users::insert_human_user(
                    &conn,
                    &new_user,
                    role,
                    password_hash.as_deref(),
                    must_change_password,
                );
                send_or_warn(reply, result, "create_human_user");
            }
            WriteCmd::ResetHumanPassword {
                user_id,
                password_hash,
                must_change_password,
                reply,
            } => {
                let result = users::reset_human_password(
                    &mut conn,
                    user_id,
                    &password_hash,
                    must_change_password,
                );
                send_or_warn(reply, result, "reset_human_password");
            }
            WriteCmd::SetUserDisabled {
                user_id,
                disabled,
                reply,
            } => {
                let result = users::set_user_disabled(&mut conn, user_id, disabled);
                send_or_warn(reply, result, "set_user_disabled");
            }
            WriteCmd::PatchUser {
                user_id,
                name,
                email,
                role,
                reply,
            } => {
                let result = users::patch_user(&mut conn, user_id, name, email, role);
                send_or_warn(reply, result, "patch_user");
            }
            WriteCmd::ChangePassword {
                user_id,
                expected_password_hash,
                new_password_hash,
                session_id,
                new_session_hash,
                new_csrf_hash,
                reply,
            } => {
                let result = users::change_password(
                    &mut conn,
                    user_id,
                    &expected_password_hash,
                    &new_password_hash,
                    session_id,
                    &new_session_hash,
                    &new_csrf_hash,
                );
                send_or_warn(reply, result, "change_password");
            }
            WriteCmd::IssueWebSession {
                user_id,
                expected_password_hash,
                expected_role,
                expected_must_change,
                session_hash,
                csrf_hash,
                reply,
            } => {
                let result = users::issue_web_session(
                    &mut conn,
                    user_id,
                    &expected_password_hash,
                    expected_role,
                    expected_must_change,
                    &session_hash,
                    &csrf_hash,
                );
                send_or_warn(reply, result, "issue_web_session");
            }
            WriteCmd::RevokeWebSession {
                session_hash,
                reply,
            } => {
                let result = web_sessions::revoke_session_by_hash(&conn, &session_hash);
                send_or_warn(reply, result, "revoke_web_session");
            }
            WriteCmd::TouchWebSession {
                session_id,
                last_used_at,
                reply,
            } => {
                let result = web_sessions::touch_web_session(&conn, session_id, last_used_at);
                send_or_warn(reply, result, "touch_web_session");
            }
            WriteCmd::CreateApiCredential {
                id,
                user_id,
                label,
                token_hash,
                preview,
                max_active,
                reply,
            } => {
                let at_limit = match max_active {
                    Some(max) => api_credentials::count_active_api_credentials_for_user(
                        &conn,
                        user_id,
                        jiff::Timestamp::now().as_microsecond(),
                    )
                    .map(|active| (active >= max).then_some(max)),
                    None => Ok(None),
                };
                let result = match at_limit {
                    Ok(Some(max)) => Err(StoreError::InvalidState(format!(
                        "active API key limit reached ({max}); revoke a key before creating another"
                    ))),
                    Ok(None) => api_credentials::insert_api_credential(
                        &conn,
                        id,
                        user_id,
                        &label,
                        &token_hash,
                        preview.as_deref(),
                    ),
                    Err(e) => Err(e),
                };
                send_or_warn(reply, result, "create_api_credential");
            }
            WriteCmd::RotateApiCredential {
                id,
                new_token_hash,
                preview,
                reply,
            } => {
                let result = api_credentials::rotate_api_credential(
                    &conn,
                    id,
                    &new_token_hash,
                    preview.as_deref(),
                );
                send_or_warn(reply, result, "rotate_api_credential");
            }
            WriteCmd::RevokeApiCredential { id, reply } => {
                let result = api_credentials::revoke_api_credential(&conn, id);
                send_or_warn(reply, result, "revoke_api_credential");
            }
            WriteCmd::TouchApiCredential { id, reply } => {
                let result = api_credentials::touch_api_credential(&conn, id);
                send_or_warn(reply, result, "touch_api_credential");
            }
            WriteCmd::BindApiCredentialPepperVerifier { verifier, reply } => {
                let result = api_credentials::bind_api_credential_pepper_verifier(&conn, &verifier);
                send_or_warn(reply, result, "bind_api_credential_pepper_verifier");
            }
            WriteCmd::TouchUserLastSeen { user_id, reply } => {
                let result = users::touch_user_last_seen(&conn, user_id);
                send_or_warn(reply, result, "touch_user_last_seen");
            }
            WriteCmd::StageAutoImproveRun { input, reply } => {
                let result = crate::auto_improve::stage_run(&mut conn, &input);
                send_or_warn(reply, result, "stage_auto_improve_run");
            }
            WriteCmd::StageAutoImproveRunForOwner {
                input,
                owner,
                reply,
            } => {
                let result =
                    crate::auto_improve::stage_run_for_owner(&mut conn, &input, owner.as_ref());
                send_or_warn(reply, result, "stage_auto_improve_run_for_owner");
            }
            WriteCmd::RejectAutoImproveProposal { input, reply } => {
                let result = crate::auto_improve::reject_proposal(&mut conn, &input);
                send_or_warn(reply, result, "reject_auto_improve_proposal");
            }
            WriteCmd::FailAutoImproveProposal { input, reply } => {
                let result = crate::auto_improve::fail_proposal(&mut conn, &input);
                send_or_warn(reply, result, "fail_auto_improve_proposal");
            }
            WriteCmd::ApproveAutoImproveProposal { input, reply } => {
                let result = crate::auto_improve::approve_proposal(&mut conn, &input);
                send_or_warn(reply, result, "approve_auto_improve_proposal");
            }
            WriteCmd::EnsureAutoImproveSchedulerState {
                workspace_id,
                project_id,
                reply,
            } => {
                let result = crate::auto_improve::ensure_scheduler_state(
                    &mut conn,
                    workspace_id,
                    project_id,
                );
                send_or_warn(reply, result, "ensure_auto_improve_scheduler_state");
            }
            WriteCmd::ClaimAutoImproveSchedulerSession {
                workspace_id,
                project_id,
                session_id,
                ended_at,
                reply,
            } => {
                let result = crate::auto_improve::claim_scheduler_session(
                    &mut conn,
                    workspace_id,
                    project_id,
                    session_id,
                    ended_at,
                );
                send_or_warn(reply, result, "claim_auto_improve_scheduler_session");
            }
            WriteCmd::RecordAutoImproveClaimFailure {
                workspace_id,
                project_id,
                session_id,
                error,
                reply,
            } => {
                let result = crate::auto_improve::record_claim_failure(
                    &conn,
                    workspace_id,
                    project_id,
                    session_id,
                    &error,
                );
                send_or_warn(reply, result, "record_auto_improve_claim_failure");
            }
            WriteCmd::RecordMaintenanceJobSuccess { job, reply } => {
                let result = crate::maintenance::record_success(&conn, job);
                send_or_warn(reply, result, "record_maintenance_job_success");
            }
            WriteCmd::PrepareWorkstreamRun {
                input,
                owner_user,
                force_unlock,
                reply,
            } => {
                let result = crate::workstream::prepare_run(
                    &mut conn,
                    &input,
                    owner_user.as_deref(),
                    force_unlock,
                );
                send_or_warn(reply, result, "prepare_workstream_run");
            }
            WriteCmd::HeartbeatManagedRun { run_id, reply } => {
                let result = crate::workstream::heartbeat(&mut conn, run_id);
                send_or_warn(reply, result, "heartbeat_managed_run");
            }
            WriteCmd::CancelManagedRun { run_id, reply } => {
                let result = crate::workstream::cancel_run(&mut conn, run_id);
                send_or_warn(reply, result, "cancel_managed_run");
            }
            WriteCmd::LinkManagedRunSession {
                run_id,
                agent,
                native_session_id,
                reply,
            } => {
                let result = crate::workstream::link_native_session(
                    &mut conn,
                    run_id,
                    agent,
                    &native_session_id,
                );
                send_or_warn(reply, result, "link_managed_run_session");
            }
            WriteCmd::LinkOrAdoptManagedRunSession { input, reply } => {
                let result = crate::workstream::link_or_adopt_native_session(&mut conn, &input);
                send_or_warn(reply, result, "link_or_adopt_managed_run_session");
            }
            WriteCmd::LinkManagedRunSessionInScope { input, reply } => {
                let result = crate::workstream::link_native_session_in_scope(&mut conn, &input);
                send_or_warn(reply, result, "link_managed_run_session_in_scope");
            }
            WriteCmd::AcceptManagedRunContext { run_id, reply } => {
                let result = crate::workstream::accept_context(&mut conn, run_id);
                send_or_warn(reply, result, "accept_managed_run_context");
            }
            WriteCmd::AcceptStartupContext {
                handoff,
                managed_run_id,
                receiving_session,
                busy_since,
                reply,
            } => {
                let result = (|| {
                    let tx = conn.transaction()?;
                    if let Some(session) = &receiving_session {
                        let matching_acceptance = handoff.as_ref().is_some_and(|acceptance| {
                            acceptance.accepting_session == Some(session.id)
                                && acceptance.workspace_id == session.workspace_id
                                && acceptance.project_id == session.project_id
                                && acceptance.accepting_agent == session.agent_kind
                        });
                        if !matching_acceptance {
                            return Err(StoreError::InvalidState(
                                "startup receiver session does not match its handoff claim".into(),
                            ));
                        }
                        ops::begin_session_in_transaction(&tx, session)?;
                    }
                    let managed_context_accepted = match managed_run_id {
                        Some(run_id) => {
                            crate::workstream::claim_context_in_transaction(&tx, run_id)?
                        }
                        None => false,
                    };
                    if managed_run_id.is_some() && !managed_context_accepted {
                        return Ok(StartupContextAcceptance::default());
                    }
                    let handoff_accepted = match handoff {
                        Some(acceptance) => ops::accept_handoff_in_transaction(
                            &tx,
                            &acceptance,
                            Some(busy_since.as_microsecond()),
                        )?,
                        None => false,
                    };
                    tx.commit()?;
                    Ok(StartupContextAcceptance {
                        handoff_accepted,
                        managed_context_accepted,
                    })
                })();
                send_or_warn(reply, result, "accept_startup_context");
            }
            WriteCmd::FinishWorkstreamRun {
                authority,
                input,
                recover_expired,
                reply,
            } => {
                let result = if recover_expired {
                    crate::workstream::recover_run(&mut conn, &authority, &input)
                } else {
                    crate::workstream::finish_run(&mut conn, &authority, &input)
                };
                send_or_warn(reply, result, "finish_workstream_run");
            }
            WriteCmd::RenameWorkstream { input, reply } => {
                let result = crate::workstream::rename(&mut conn, &input);
                send_or_warn(reply, result, "rename_workstream");
            }
        }
    }
    tracing::debug!("writer thread exiting cleanly");
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Store;
    use ai_memory_core::{NewPage, PagePath, Tier};
    use std::time::Duration;
    use tempfile::TempDir;

    fn sample_page(ws: WorkspaceId, proj: ProjectId, path: &str, body: &str) -> NewPage {
        NewPage {
            workspace_id: ws,
            project_id: proj,
            path: PagePath::new(path).unwrap(),
            title: "test".into(),
            body: body.into(),
            tier: Tier::Semantic,
            frontmatter_json: serde_json::json!({}),
            pinned: false,
            links: Vec::new(),
            author_id: None,
            expires_at: None,
            entities: Vec::new(),
            evidence: Vec::new(),
        }
    }

    /// Enqueue a workspace creation without awaiting the reply, returning
    /// the oneshot receiver so the caller decides when to collect it.
    async fn enqueue_workspace(
        writer: &WriterHandle,
        name: &str,
    ) -> oneshot::Receiver<StoreResult<WorkspaceId>> {
        let (tx, rx) = oneshot::channel();
        writer
            .inner
            .tx
            .as_ref()
            .unwrap()
            .send(WriteCmd::GetOrCreateWorkspace {
                name: name.to_owned(),
                reply: tx,
            })
            .await
            .expect("writer channel closed while enqueueing");
        rx
    }

    /// Commands enqueued on the bounded channel run on the writer thread in
    /// FIFO order: insertion rowids must match enqueue order exactly.
    #[tokio::test]
    async fn executes_commands_in_fifo_order() {
        let tmp = TempDir::new().unwrap();
        let store = Store::open(tmp.path()).unwrap();

        let mut pending = Vec::new();
        for i in 0..8 {
            pending.push(enqueue_workspace(&store.writer, &format!("fifo-{i:02}")).await);
        }
        for rx in pending {
            rx.await.unwrap().unwrap();
        }

        let conn = Connection::open(store.db_path()).unwrap();
        let mut stmt = conn
            .prepare("SELECT name FROM workspaces WHERE name LIKE 'fifo-%' ORDER BY rowid")
            .unwrap();
        let names: Vec<String> = stmt
            .query_map([], |row| row.get(0))
            .unwrap()
            .collect::<Result<_, _>>()
            .unwrap();
        let expected: Vec<String> = (0..8).map(|i| format!("fifo-{i:02}")).collect();
        assert_eq!(
            names, expected,
            "single writer thread must apply commands in enqueue order"
        );
    }

    /// A command whose SQL fails returns the error on *its* oneshot only;
    /// the actor keeps processing — the next command succeeds.
    #[tokio::test]
    async fn sql_error_reaches_caller_without_killing_actor() {
        let tmp = TempDir::new().unwrap();
        let store = Store::open(tmp.path()).unwrap();
        let ws = store
            .writer
            .get_or_create_workspace("default")
            .await
            .unwrap();
        let proj = store
            .writer
            .get_or_create_project(ws, "app", None)
            .await
            .unwrap();

        // FK violation: no project row exists for this id.
        let err = store
            .writer
            .upsert_page(sample_page(ws, ProjectId::new(), "notes/bogus.md", "x"))
            .await
            .unwrap_err();
        assert!(
            matches!(err, StoreError::Sqlite(_)),
            "expected the raw SQL failure to reach the caller, got {err:?}"
        );

        // The actor survived: a well-formed write lands afterwards.
        store
            .writer
            .upsert_page(sample_page(ws, proj, "notes/fine.md", "ok"))
            .await
            .unwrap();
        let conn = Connection::open(store.db_path()).unwrap();
        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM pages", [], |row| row.get(0))
            .unwrap();
        assert_eq!(count, 1, "only the post-error write may be present");
    }

    /// A batch command is one transaction: a failure part-way through rolls
    /// back the pages that already succeeded inside the same batch.
    #[tokio::test]
    async fn batch_upsert_rolls_back_on_mid_batch_failure() {
        let tmp = TempDir::new().unwrap();
        let store = Store::open(tmp.path()).unwrap();
        let ws = store
            .writer
            .get_or_create_workspace("default")
            .await
            .unwrap();
        let proj = store
            .writer
            .get_or_create_project(ws, "app", None)
            .await
            .unwrap();

        let pages = vec![
            sample_page(ws, proj, "notes/good.md", "good"),
            // Second page references a project that does not exist.
            sample_page(ws, ProjectId::new(), "notes/bad.md", "bad"),
        ];
        let err = store.writer.upsert_pages_batch(pages).await.unwrap_err();
        assert!(
            matches!(err, StoreError::Sqlite(_)),
            "expected FK failure from the batch, got {err:?}"
        );

        let conn = Connection::open(store.db_path()).unwrap();
        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM pages", [], |row| row.get(0))
            .unwrap();
        assert_eq!(
            count, 0,
            "mid-batch failure must roll back the earlier page too"
        );

        // Actor is still alive after the rolled-back batch.
        store
            .writer
            .upsert_page(sample_page(ws, proj, "notes/after.md", "after"))
            .await
            .unwrap();
    }

    /// Dropping the last handle queues `Shutdown` behind the pending
    /// commands and joins the thread: every already-enqueued command is
    /// answered, and the join returning proves the thread exited (no hang).
    #[tokio::test]
    async fn drop_completes_pending_commands_and_joins_thread() {
        let tmp = TempDir::new().unwrap();
        let store = Store::open(tmp.path()).unwrap();
        let writer = store.writer.clone();
        let db_path = store.db_path().to_owned();
        drop(store);

        let mut pending = Vec::new();
        for i in 0..8 {
            pending.push(enqueue_workspace(&writer, &format!("drain-{i:02}")).await);
        }
        // Joins the writer thread inside `Drop for WriterInner`; returns
        // only after the queue (including Shutdown) was drained.
        drop(writer);

        for rx in pending {
            let id = tokio::time::timeout(Duration::from_secs(10), rx)
                .await
                .expect("pending command was not answered before the writer stopped")
                .expect("reply oneshot dropped")
                .unwrap();
            let conn = Connection::open(&db_path).unwrap();
            let count: i64 = conn
                .query_row(
                    "SELECT COUNT(*) FROM workspaces WHERE id = ?1",
                    [id.as_bytes()],
                    |row| row.get(0),
                )
                .unwrap();
            assert_eq!(count, 1, "pending command must have committed");
        }
    }

    #[test]
    fn drop_with_a_full_queue_completes_pending_commands_and_joins() {
        let tmp = TempDir::new().unwrap();
        let store = Store::open(tmp.path()).unwrap();
        let mut writer = store.writer.clone();
        let db_path = store.db_path().to_owned();
        drop(store);

        let (entered_tx, entered_rx) = std::sync::mpsc::channel();
        let (resume_tx, resume_rx) = std::sync::mpsc::channel();
        let (reply, blocker) = oneshot::channel();
        let blocked =
            writer
                .inner
                .tx
                .as_ref()
                .unwrap()
                .try_send(WriteCmd::EndIdleSessionsPreStamp {
                    candidates: vec![IdleEndCandidate {
                        session_id: SessionId::new(),
                        workspace_id: WorkspaceId::new(),
                        project_id: ProjectId::new(),
                        agent_kind: AgentKind::Codex,
                        action: ops::IdleEndAction::LifecycleOnly {
                            now_us: 0,
                            last_activity_us: 0,
                        },
                    }],
                    enqueue_consolidation: false,
                    pre_stamp: Box::new(move |_| {
                        entered_tx.send(()).unwrap();
                        resume_rx.recv().unwrap();
                    }),
                    reply,
                });
        assert!(blocked.is_ok());
        entered_rx.recv_timeout(Duration::from_secs(5)).unwrap();

        let mut pending = Vec::new();
        let capacity = writer.queue_depth().1;
        for i in 0..capacity {
            let (reply, rx) = oneshot::channel();
            assert!(
                writer
                    .inner
                    .tx
                    .as_ref()
                    .unwrap()
                    .try_send(WriteCmd::GetOrCreateWorkspace {
                        name: format!("full-drain-{i}"),
                        reply,
                    })
                    .is_ok()
            );
            pending.push(rx);
        }
        assert_eq!(writer.queue_depth(), (capacity, capacity));
        let rescue = writer.inner.tx.as_ref().unwrap().downgrade();
        let (joining_tx, joining_rx) = std::sync::mpsc::channel();
        Arc::get_mut(&mut writer.inner).unwrap().before_join = Some(Box::new(move || {
            joining_tx.send(()).unwrap();
        }));
        let (done_tx, done_rx) = std::sync::mpsc::channel();
        let dropper = thread::spawn(move || {
            drop(writer);
            let _ = done_tx.send(());
        });
        // The writer cannot consume a queued command until Drop has attempted
        // shutdown against the full queue. No scheduling sleeps are needed.
        joining_rx.recv_timeout(Duration::from_secs(5)).unwrap();
        resume_tx.send(()).unwrap();
        let completed = done_rx.recv_timeout(Duration::from_secs(5)).is_ok();
        if !completed {
            // Rescue the old deadlock before failing, so a regression never
            // leaves the test suite waiting on a stuck writer thread.
            if let Some(sender) = rescue.upgrade() {
                let _ = sender.try_send(WriteCmd::Shutdown);
            }
            assert!(done_rx.recv_timeout(Duration::from_secs(5)).is_ok());
        }
        dropper.join().unwrap();
        blocker.blocking_recv().unwrap().unwrap();
        for rx in pending {
            rx.blocking_recv().unwrap().unwrap();
        }
        let conn = Connection::open(db_path).unwrap();
        let committed: usize = conn
            .query_row(
                "SELECT COUNT(*) FROM workspaces WHERE name LIKE 'full-drain-%'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(committed, capacity, "accepted commands must all commit");
        assert!(completed, "dropping a full writer queue must finish");
    }

    /// The dry run and the real move both go through the actor; only the
    /// latter changes the session row a reader sees.
    #[tokio::test]
    async fn move_session_dry_run_then_commit_through_writer() {
        let tmp = TempDir::new().unwrap();
        let store = Store::open(tmp.path()).unwrap();
        let ws = store
            .writer
            .get_or_create_workspace("default")
            .await
            .unwrap();
        let src = store
            .writer
            .get_or_create_project(ws, "src", None)
            .await
            .unwrap();
        let dst = store
            .writer
            .get_or_create_project(ws, "dst", None)
            .await
            .unwrap();
        let sid = SessionId::new();
        store
            .writer
            .begin_session(NewSession {
                occurred_at: None,
                id: sid,
                workspace_id: ws,
                project_id: src,
                agent_kind: AgentKind::Codex,
                cwd: None,
                actor_user: None,
            })
            .await
            .unwrap();

        let dry = store
            .writer
            .move_session(sid, ws, dst, PagesMode::Move, None, false)
            .await
            .unwrap();
        assert!(dry.session_moved);
        assert_eq!(
            store.reader.session_project_ids(sid).await.unwrap(),
            Some((ws, src)),
            "dry run must roll back"
        );

        let moved = store
            .writer
            .move_session(sid, ws, dst, PagesMode::Move, None, true)
            .await
            .unwrap();
        assert!(moved.session_moved);
        assert_eq!(
            store.reader.session_project_ids(sid).await.unwrap(),
            Some((ws, dst))
        );
    }

    /// Commands racing the shutdown never hang: a send that holds a channel
    /// permit when the actor stops must still be dropped, so its caller gets
    /// a reply (a result or `WriterClosed`) instead of waiting forever.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn commands_racing_shutdown_always_get_a_reply() {
        for round in 0..20 {
            let tmp = TempDir::new().unwrap();
            let store = Store::open(tmp.path()).unwrap();
            let writer = store.writer.clone();
            drop(store);
            let callers: Vec<_> = (0..64)
                .map(|i| {
                    let writer = writer.clone();
                    tokio::spawn(async move {
                        writer
                            .get_or_create_workspace(&format!("ws-{round}-{i}"))
                            .await
                    })
                })
                .collect();
            writer
                .inner
                .tx
                .as_ref()
                .unwrap()
                .send(WriteCmd::Shutdown)
                .await
                .expect("writer channel closed before Shutdown");
            for caller in callers {
                let reply = tokio::time::timeout(std::time::Duration::from_secs(10), caller)
                    .await
                    .expect("a command racing shutdown hung instead of replying")
                    .expect("caller task panicked");
                assert!(
                    matches!(reply, Ok(_) | Err(StoreError::WriterClosed)),
                    "unexpected reply: {reply:?}"
                );
            }
        }
    }

    /// Once the actor has stopped, calls fail fast with
    /// [`StoreError::WriterClosed`] instead of hanging on a dead channel.
    #[tokio::test]
    async fn commands_after_shutdown_return_writer_closed() {
        let tmp = TempDir::new().unwrap();
        let store = Store::open(tmp.path()).unwrap();
        let writer = store.writer.clone();
        drop(store);

        writer
            .inner
            .tx
            .as_ref()
            .unwrap()
            .send(WriteCmd::Shutdown)
            .await
            .expect("writer channel closed before Shutdown");

        // FIFO guarantees Shutdown is processed first; whether the send
        // itself fails or the reply oneshot is dropped, the caller sees
        // WriterClosed either way.
        let err = writer
            .get_or_create_workspace("too-late")
            .await
            .unwrap_err();
        assert!(
            matches!(err, StoreError::WriterClosed),
            "expected WriterClosed, got {err:?}"
        );
    }
}