Skip to content

AI, fully local on your computer.

58.7 KB
Raw Blame
import { guardedHandleFor } from './guarded-handle'
import { IPC } from '../../shared/ipc'
import type { AppContext } from '../services/context'
import {
  PlaintextNotAllowedError,
  VaultBusyError,
  VaultDamagedError,
  VaultDescriptorMissingError,
  VaultDescriptorUnreadableError,
  VaultMissingError,
  VaultOpenFailedError,
  VaultRecoveryBlockedError,
  WorkspaceExistsError,
  WrongPasswordError,
  isVaultNewerError,
  workspaceAdmitsWork,
  type WorkingCopyLossCause
} from '../services/workspace-vault'
import { prepareFirstBenchmark, scheduleFirstBenchmark } from './registerBenchmarkIpc'
import { maybeAutoStartActiveModel } from './registerModelIpc'
import { healEngineLoadState } from '../services/engine-health'
import { maybeStartLocalApi } from '../services/local-api/lifecycle'
import { startKnowledgePackSession } from '../services/zim/session'
import { inFlightStreams, awaitInFlightStreamsSettled } from './inflight'
import { endedEarlyAbortReason } from '../services/chat/ended-early'
import { applyUiLanguageSetting, tMain } from '../services/i18n'
import { isWorkspaceNewerError } from '../services/db'
import { getSettings } from '../services/settings'
import { purgeResidentVectors } from '../services/embeddings'
import { log, attachVaultKey, detachVaultKey, usesPlaintextLog, rekeyVaultLog } from '../services/logging'
import { failureForLog } from '../services/failure-for-log'
import { perfMark, perfMs } from '../services/perf'
import {
  MIN_PASSWORD_LENGTH,
  type WorkspaceActionResult,
  type WorkspaceMode,
  type WorkspaceStateInfo
} from '../../shared/types'

// IPC for the encrypted-workspace lock/unlock lifecycle (spec §7.9).
// A wrong password or a policy refusal is a NORMAL result (`{ ok: false, reason }`),
// not a thrown error, so the unlock gate can re-prompt cleanly.

/** Settings just became readable (unlock/create) → re-resolve the main-side UI
 *  language from the real `uiLanguage` setting. Best-effort: a settings read must
 *  never break an unlock. */
function refreshUiLanguage(ctx: AppContext): void {
  try {
    applyUiLanguageSetting(getSettings(ctx.db).uiLanguage)
  } catch {
    /* keep the current (OS-locale) language */
  }
}

/**
 * Point the diagnostics log at the now-resolved workspace. Encrypted → adopt the live vault
 * key so `app.log.enc` is encrypted at rest under the same key as the DB. Plaintext_dev →
 * switch to the plain `app.log` (no key exists). Best-effort: a logging hiccup must never
 * break an unlock/create.
 */
function attachLogKey(ctx: AppContext): void {
  try {
    const key = ctx.workspace.encryptionKey()
    if (key) attachVaultKey(key)
    else usesPlaintextLog()
  } catch {
    /* logging is best-effort */
  }
}

/** What was lost, per cause, for the app.log line the unlock writes after a loss (#875, #892; English, content-free:
 *  app.log is for support, not translated). The audit event carries the cause itself. `unclean-full` says what the start
 *  measured, not the cause it suggests: a power cut on a drive that full reads the same. */
const LOSS_LOG_TEXT: Record<WorkingCopyLossCause, string> = {
  lock: 'the working file was gone or no longer a database',
  startup: 'the working file was no longer a database',
  unclean: 'the app ended without locking the workspace',
  'unclean-full':
    'the app ended without locking the workspace, and at the next start the free space on the drive was below the ' +
    'size of the workspace',
  recovery: 'the recovery copy a failed lock left was no longer a database'
}

/** Upper bound on how long the lock handler waits for a cancelled doc-task to unwind (TA-1). */
const LOCK_TASK_SETTLE_TIMEOUT_MS = 5_000

/**
 * Await the currently-running doc-task's abort-unwind, bounded by a timeout so a wedged handler
 * cannot hang "Lock now" (TA-1 H2). The manager persists/shreds its transient synchronously
 * during the unwind while `ctx.db` is open, so this runs before the DB closes. Best-effort.
 */
async function awaitActiveDocTaskSettled(ctx: AppContext): Promise<void> {
  let settle: Promise<void> | undefined
  try {
    settle = ctx.docTasks?.awaitActiveTaskSettled?.()
  } catch (err) {
    log.error('Error awaiting doc-task settle on lock', failureForLog(err))
    return
  }
  if (!settle) return
  let timer: ReturnType<typeof setTimeout> | undefined
  const timeout = new Promise<void>((resolve) => {
    timer = setTimeout(resolve, LOCK_TASK_SETTLE_TIMEOUT_MS)
    timer.unref()
  })
  try {
    await Promise.race([settle.catch(() => undefined), timeout])
  } finally {
    if (timer) clearTimeout(timer)
  }
}

/**
 * #606: await the skill runs cancelled at the start of the teardown within the same bound, so each
 * records its cancel in `skill_runs` while `ctx.db` is open — after the lock the write failed and a
 * cancelled run read "This could not be saved". A run parked in a save dialog that was already open
 * does not settle (an abort cannot close the dialog); the lock proceeds at the bound. Best-effort.
 */
async function awaitSkillRunsSettled(ctx: AppContext): Promise<void> {
  try {
    const settled = await (ctx.skillRuns?.awaitSettled(LOCK_TASK_SETTLE_TIMEOUT_MS) ?? true)
    if (!settled) log.warn('Lock: a skill run was still running at the settle bound')
  } catch (err) {
    log.error('Error settling skill runs on lock', failureForLog(err))
  }
}

/**
 * Await the aborted plaintext operations (preview / re-index / import prepare / dictation /
 * export) within the same bound as the doc-task settle, then shred whatever transient is still
 * registered — a parser that cannot cancel (pdfjs, mammoth) is bounded by this sweep, not by
 * its signal (#237). Runs while `ctx.db` is open, before the vault re-encrypts. Best-effort.
 */
async function settleAndSweepPlaintextOps(ctx: AppContext): Promise<void> {
  const ops = ctx.plaintextOps
  if (!ops) return
  try {
    const settled = await ops.awaitSettled(LOCK_TASK_SETTLE_TIMEOUT_MS)
    if (!settled) {
      log.warn('Lock: plaintext operations still running at the settle bound — sweeping', {
        live: ops.size()
      })
    }
    const swept = ops.sweepRegistered()
    if (swept > 0) log.info('Lock: swept registered plaintext transients', { swept })
  } catch (err) {
    log.error('Error settling plaintext operations on lock', failureForLog(err))
  }
}

/**
 * The knowledge-pack twin of the step above (#301, findings H4/M4). Await the aborted ZIM
 * operations within the SAME 5 s bound, shred whatever `library.<n>.xml` / `meta-<n>/library.xml`
 * an operation that could not cancel still tracks, then run the dedicated `zim-transient/`
 * cleanup. Runs while `ctx.db` is open and AFTER `zim.suspend()` took the sidecar down, so
 * nothing is publishing into that directory any more.
 *
 * Failure policy (plan §9.17 (b)): the LOCK PROCEEDS. A file still tracked by a live operation
 * at the bound is shredded under it (its child is settled or unconfirmed by then); a file
 * belonging to a child that could NOT be confirmed dead is kept — a possibly-live process may
 * still write it — reported, and removed once that child is seen to exit, or by the next app
 * start (#713). The log then says "NOT
 * confirmed", never "complete", and carries counts only: no pack title, no path.
 */
async function settleAndCleanZimTransients(ctx: AppContext): Promise<void> {
  const ops = ctx.zimOps
  const zim = ctx.zim
  if (!ops && !zim) return
  try {
    if (ops) {
      const settled = await ops.awaitSettled(LOCK_TASK_SETTLE_TIMEOUT_MS)
      if (!settled) {
        log.warn('Lock: knowledge-pack operations still running at the settle bound — sweeping', {
          live: ops.size()
        })
      }
      const swept = ops.sweepRegistered()
      if (swept > 0) log.info('Lock: swept registered knowledge-pack transients', { swept })
    }
    const report = zim?.cleanupTransients('lock')
    if (!report) return
    if (report.confirmed) log.info('Lock: ZIM transients cleaned')
    else
      log.warn('Lock: ZIM cleanup NOT confirmed', {
        kept: report.kept,
        unknownEntries: report.unknownEntries,
        unsettledOps: report.unsettledOps,
        unconfirmedChildren: report.unconfirmedChildren
      })
  } catch (err) {
    log.error('Error settling knowledge-pack operations on lock', failureForLog(err))
  }
}

/**
 * #876 review round 2: log each site that judged a workspace file by its SQLite header because the probe could not read
 * its structure for a reason that is not damage (the file was then treated as before the probe existed). Which site and
 * SQLite's code only; the controller keeps them until a handler that can log (a lock, an unlock, a password change).
 */
function logProbeFallbacks(ctx: AppContext): void {
  for (const note of ctx.workspace.takeProbeFallbacks?.() ?? []) {
    log.warn('A workspace file was judged by its SQLite header: the structural check could not run', note)
  }
}

/**
 * #973 (a log line, no audit type, as #911's): what the last unlock did with a staged copy of the database that no rekey
 * journal listed: removed it, because it does not open under this workspace's key (a create cut short by a crash left
 * it, or it came from another workspace), or (#1027) because the workspace file opens under that key too and so holds
 * the newer data, or left it as it is, because it could not be read, or not removed yet. Logged on the
 * unlock's success and failure paths alike (review round 2 F4). Fixed words only: no path, no file name.
 * #1001: then, in one more line, what it did with the staged document and image copies no journal listed: how many it
 * removed (no newer copy of their stored document: another key or file, or the stored copy is already current) and left
 * (they could be neither read nor swapped in or removed;
 * the next unlock checks them again), with the count it swapped in, and (review round 2) how many it set aside: a staged
 * copy that could not be moved into place while its old copy could not be moved back either, which the next start
 * finishes. Counts only. Nothing when it removed, left and set aside none.
 */
function logStageOutcome(ctx: AppContext): void {
  // #1014: the rekey journal entries the recoveries left as they were (outside the workspace, and not a stored copy the
  // database lists, or not a stage at all; round 3: and the folders left in place; round 4: and the entries a stat that
  // proves nothing left unchecked, which wait; a password change's count waits for this line), once, as a count: no
  // path, no name.
  const refused = ctx.workspace.takeJournalRefusals?.() ?? 0
  if (refused > 0) {
    log.warn(
      "Workspace unlock: left as they are the password-change journal's entries it cannot vouch for or act on yet (#1014)",
      { refused }
    )
  }
  const outcome = ctx.workspace.takeStageOutcome?.()
  if (outcome === 'removed') {
    log.info("Workspace unlock: removed a staged copy that does not open under this workspace's key (#973)")
  } else if (outcome === 'superseded') {
    log.info('Workspace unlock: removed a staged copy of the database that is older than the workspace file (#1027)')
  } else if (outcome === 'left') {
    // Code review CR1-5: true of both kinds: one the unlock could not read (#973), and one it read and judged older than
    // the workspace file but could not delete yet (#1027).
    log.warn('Workspace unlock: left a staged copy of the database as it is: it could not be read, or not removed yet (#973, #1027)')
  }
  const sidecars = ctx.workspace.takeSidecarStageOutcome?.()
  if (!sidecars) return
  const counts = {
    removed: sidecars.removed,
    left: sidecars.left,
    setAside: sidecars.setAside,
    rolledForward: sidecars.rolledForward
  }
  if (sidecars.setAside > 0) {
    log.warn(
      'Workspace unlock: could not move staged document or image copies into place, nor their old copies back; the next start removes the old copies and puts the staged ones in their place (#1001)',
      counts
    )
  } else if (sidecars.left > 0) {
    log.warn(
      'Workspace unlock: left staged document or image copies that could not be checked or swapped in; the next unlock checks them again (#1001)',
      counts
    )
  } else if (sidecars.removed > 0) {
    log.info(
      'Workspace unlock: removed staged document or image copies that were no newer copy of their stored document (another key, another file, or the stored copy is already current) (#1001)',
      counts
    )
  }
}

/** What the app passes beside the context (#1002), so the shared `AppContext` type stays as it is. */
export interface WorkspaceIpcHooks {
  /** Called once at the end of each unlock or first-run create that opened the workspace and ran its post-unlock steps;
   *  never for one that failed or was refused (a step after the open included), nor for an unlock that found it already
   *  open. `index.ts` binds the quit closure's `onWorkspaceUnlocked`. */
  onUnlocked?: () => void
}

export function registerWorkspaceIpc(ctx: AppContext, hooks: WorkspaceIpcHooks = {}): void {
  const ipcHandle = guardedHandleFor(ctx)
  ipcHandle(IPC.getWorkspaceState, (): WorkspaceStateInfo => ctx.workspace.getState())

  ipcHandle(IPC.unlockWorkspace, (_e, password: string): WorkspaceActionResult => {
    // The renderer is the untrusted boundary in Electron (M-S2): args are TS-typed but
    // arrive unvalidated. A non-string password would throw deep in the vault; reject it
    // here as a clean wrong-password result instead.
    if (typeof password !== 'string') {
      return { ok: false, reason: 'wrong_password', message: tMain('main.workspace.wrongPassword') }
    }
    // #858: an unlock on a workspace that is already open verifies nothing: the controller returns
    // early, deliberately, so an unlock landing mid-teardown cannot re-open the admission window
    // (AUD-02). Answer with the state and stop. Running the post-unlock steps here would record a
    // `workspace_unlocked` audit event for a password nobody checked, fold the persisted
    // diagnostics log into a buffer that already holds it (duplicating it), and restart the model,
    // the local API and the knowledge-pack session.
    if (ctx.workspace.isUnlocked()) return { ok: true, state: ctx.workspace.getState() }
    try {
      const unlockT0 = performance.now()
      const state = ctx.workspace.unlock(password)
      perfMark('unlock_done', { totalMs: perfMs(unlockT0) })
      // #936 review SF-2: no quit is under way while someone unlocks, or creates the workspace (#955 item 4: the create
      // seam below releases it too; the close guard holds the document-task queue only inside its save or behind its
      // window-modal dialog), so a quit hold still set here is stale (a quit cancelled outside the guard): clear it, so
      // it can never block this session's document tasks.
      ctx.docTasks?.releaseQueueHold()
      // The vault key is live now — adopt it for the diagnostics log so it is encrypted at
      // rest like the DB, and fold in this session's pre-unlock buffer + any prior history.
      attachLogKey(ctx)
      log.info('Workspace unlocked')
      // #911 (owner decision D5: a log line, no audit type): the start found `.enc` missing and kept the only copy, and
      // this unlock encrypted it again. Content-free; it is the one trace that something removed the file.
      if (ctx.workspace.takeRestoredMissingEnc?.()) {
        log.warn('The encrypted workspace file was missing; the copy the last session left was encrypted again')
      }
      logStageOutcome(ctx)
      logProbeFallbacks(ctx)
      // Audit: writing this also flushes events buffered while locked —
      // which is how the unlock_failed events below ever reach the log. NEVER the
      // password, in any branch.
      ctx.audit?.('workspace_unlocked', 'Workspace unlocked')
      // #985 (review round 3 F3; a log line, no audit type): this unlock opened `.enc` beside a copy of the workspace a
      // newer HilbertRaum wrote and that `.enc` is newer than (a spent leftover). It stays on the drive unencrypted until
      // a later failed lock's salvage replaces it or a newer build's unlock shreds it. Fixed words only.
      if (ctx.workspace.takeNewerRecoveryLeft?.()) {
        log.warn('Workspace unlock: left an older, unencrypted copy of the workspace that a newer HilbertRaum wrote (#985)')
      }
      // #875: the last session's changes were lost: the previous lock finished at the last saved state
      // (often at quit, with no lock screen to say so and no log that outlived it), the start swept the
      // working file (or, #892, the session the app ended without locking: a power cut, a pulled drive, a
      // kill, a quit on a full drive, which leaves no log at all), or this unlock discarded a broken recovery
      // copy. Now there is a database and a log key to record it in, once. Content-free: which loss (`cause`)
      // and, for a recorded one, when.
      const lost = ctx.workspace.takeWorkingCopyLost?.() ?? null
      if (lost) {
        const meta = { cause: lost.cause, ...(lost.lostAt ? { lostAt: lost.lostAt } : {}) }
        const what = LOSS_LOG_TEXT[lost.cause]
        log.warn(`The changes since the last saved state were lost: ${what}`, meta)
        ctx.audit?.('workspace_working_copy_lost', 'Changes since the last saved state were lost', meta)
      }
      // Settings are readable now — main-side emissions follow the user's language.
      refreshUiLanguage(ctx)
      // The first-run / moved-drive benchmark and the model auto-start, in the P7 order (PR #303
      // audit L1, owner decision G5; the same sequence as the plaintext startup in main/index.ts):
      // the CHEAP preparation first — a known computer's result restored, the history seeded, the
      // GPU probe refreshed, synchronously — then the selected model's runtime back up in the
      // background, then the benchmark's MEASUREMENT scheduled behind that start's settlement so
      // its drive probe never contends with the weight hash + load and its speed leg sees the
      // runtime. The handler never awaits the scheduler.
      // #530: first heal what an engine load refusal wrote before the fix (a compatibility-mode
      // flag that blamed the GPU, raw loader lines on failed documents) — the auto-start reads it.
      healEngineLoadState(ctx)
      const firstBenchmark = prepareFirstBenchmark(ctx)
      // #380: the auto-start waits for the session's probe (≈1 s idle; resolved at once with no
      // binary), so the ladder finds a settled device list instead of racing the weight upload
      // for the driver. `maybeAutoStartActiveModel` re-checks admission and `startModelRuntime`
      // the epoch, so a lock landing inside that ≈1 s is handled exactly as before.
      const autoStarted = firstBenchmark.probed.then(() => maybeAutoStartActiveModel(ctx))
      void scheduleFirstBenchmark(ctx, firstBenchmark, autoStarted)
      // Post-unlock seam for the local API (policy ∧ setting gated; D3/D7).
      maybeStartLocalApi(ctx)
      // Knowledge packs (#301, finding L7; owner ruling D3): clean this workspace's ZIM
      // transients and reconcile the drive folder ONCE per session — scheduled, never on the
      // unlock's critical path (a 30 s manager spawn must not sit between the password and
      // the workspace).
      startKnowledgePackSession(ctx)
      // #1002: last, once every post-unlock step went through: after a session-end lock that left the app running, the
      // quit closure returns to a normal session (it changes nothing in any other state). Never on the early return
      // above, nor when the unlock or a step after it failed (the catch below): the closure then stays as it was, and a
      // quit locks again and exits.
      hooks.onUnlocked?.()
      return { ok: true, state }
    } catch (err) {
      logStageOutcome(ctx) // #973 (review round 2 F4): a staged copy removed before a later step failed
      // instanceof PLUS the name: the production rollup bundle can contain a second,
      // tree-shaken copy of workspace-vault (module-id quirk), and the class thrown by
      // the vault is then not the class this file imported — instanceof alone made the
      // friendly wrong-password message unreachable in the built app (vitest runs
      // unbundled and never sees this).
      if (err instanceof WrongPasswordError || (err instanceof Error && err.name === 'WrongPasswordError')) {
        ctx.audit?.('workspace_unlock_failed', 'Workspace unlock failed (wrong password)')
        // §7 voice: describe the problem and the next step, no jargon. Localized at
        // emission (D-L5) — ephemeral, never persisted; English value unchanged.
        return {
          ok: false,
          reason: 'wrong_password',
          message: tMain('main.workspace.wrongPassword')
        }
      }
      // #208: the password VERIFIED but `.enc` did not decrypt to an openable database (or, #860 V5b,
      // failed its GCM tag: only changed bytes can, once the password verified).
      // This must never wear the wrong-password/openFailed copy: the reporter's vault was
      // destroyed and three releases' worth of "check your password" pointed them at the
      // troubleshooting step (create a new workspace) that would have erased the evidence.
      // instanceof PLUS the name — same bundle-duplication quirk as WrongPasswordError.
      if (err instanceof VaultDamagedError || (err instanceof Error && err.name === 'VaultDamagedError')) {
        // Which damage (#860 V5b: a failed authentication, or #208: not a database) goes to the log only.
        log.error('Workspace unlock failed: vault damaged (password verified, data unreadable)', {
          damage: (err as VaultDamagedError).damage
        })
        ctx.audit?.('workspace_unlock_failed', 'Workspace unlock failed (vault damaged)')
        return {
          ok: false,
          reason: 'vault_damaged',
          message: tMain('main.workspace.vaultDamaged')
        }
      }
      // #844: the password verified and SQLite found a database, but opening it could not finish
      // (an upgrade step: a full drive, an I/O error, a bug in a new step). The open does not rewrite
      // `.enc` (only a `.recovery` roll-forward before it can, with a fresher snapshot), so this
      // must not wear the damaged copy and send the user looking for a backup. The log gets
      // the error's `failure` (the cause's kind and SQLite's fixed description): the error never
      // holds the cause's message, which a backfill can fill with stored text.
      // instanceof PLUS the name — the bundle-duplication quirk again.
      if (err instanceof VaultOpenFailedError || (err instanceof Error && err.name === 'VaultOpenFailedError')) {
        log.error(
          'Workspace unlock failed: the database could not finish opening (password verified)',
          (err as VaultOpenFailedError).failure
        )
        ctx.audit?.('workspace_unlock_failed', 'Workspace unlock failed (could not finish opening)')
        return {
          ok: false,
          reason: 'vault_open_failed',
          message: tMain('main.workspace.vaultOpenFailed')
        }
      }
      // #911: the password verified, but the encrypted workspace file is missing and no copy was left to restore it
      // from. Before, this was a raw ENOENT that read "Could not open the workspace." on every try. The copy warns
      // against a new workspace, which would replace the data key the stored documents need. The log line names no
      // path. instanceof PLUS the name: the bundle-duplication quirk again.
      if (err instanceof VaultMissingError || (err instanceof Error && err.name === 'VaultMissingError')) {
        log.error('Workspace unlock failed: the encrypted workspace file is missing (password verified)')
        // #911 (D3, SF-2): the unlock shredded a kept copy whose structure was damaged. Content-free, no path.
        if ((err as VaultMissingError).keptCopyDiscarded) {
          log.warn('Workspace unlock: a kept copy that could not be restored was removed')
        }
        ctx.audit?.('workspace_unlock_failed', 'Workspace unlock failed (encrypted file missing)')
        return {
          ok: false,
          reason: 'vault_missing',
          message: tMain('main.workspace.vaultMissing')
        }
      }
      // #807 (C-S2): the encrypted workspace file is there, but its descriptor (`config/workspace.json`, which holds
      // the wrapped key) is missing or unreadable, so no password can open it; refused before the password was checked.
      // Before, this was a plain English error that read "Could not open the workspace." on every try. The copy names
      // the file and warns against a new workspace. The log line names no path. instanceof PLUS the name, as above.
      if (
        err instanceof VaultDescriptorMissingError ||
        (err instanceof Error && err.name === 'VaultDescriptorMissingError')
      ) {
        log.error('Workspace unlock failed: the workspace descriptor is missing or unreadable (encrypted file present)')
        ctx.audit?.('workspace_unlock_failed', 'Workspace unlock failed (descriptor missing)')
        return {
          ok: false,
          reason: 'vault_descriptor_missing',
          message: tMain('main.workspace.descriptorMissing')
        }
      }
      // #955 item 1: `config/workspace.json` is on the drive but cannot be read, and the encrypted workspace file is not
      // beside it, so no password can open anything here. Before, a plain English error that read "Could not open the
      // workspace." on every try. Its own copy says not to delete the key file (a file damaged by an edit can often be
      // repaired; #974: a byte-order mark alone no longer makes it unreadable) and never that no data is left: a
      // `.recovery`, an `.enc.new` or stored documents may still be on the drive. The log line names no path. instanceof PLUS the name, as above.
      if (
        err instanceof VaultDescriptorUnreadableError ||
        (err instanceof Error && err.name === 'VaultDescriptorUnreadableError')
      ) {
        log.error('Workspace unlock failed: the workspace descriptor is unreadable and no encrypted file is beside it')
        ctx.audit?.('workspace_unlock_failed', 'Workspace unlock failed (descriptor unreadable)')
        return {
          ok: false,
          reason: 'vault_descriptor_unreadable',
          message: tMain('main.workspace.descriptorUnreadable')
        }
      }
      // #242: the startup salvage is blocked — another program holds the recovery file the
      // last session's newest data must be moved onto, so opening now would decrypt the
      // stale snapshot over it. Its own reason + copy (close the holder, retry; nothing is
      // lost). instanceof PLUS the name — the bundle-duplication quirk again.
      if (
        err instanceof VaultRecoveryBlockedError ||
        (err instanceof Error && err.name === 'VaultRecoveryBlockedError')
      ) {
        // #911 widened what blocks: also a stat of `.enc` that fails other than ENOENT, and a `-wal` the start's replay
        // could not empty while `.enc` is missing (a full drive, another program reading the file). #1015: and a
        // password change's staged file the recovery could not put in place, with that file error's code (no path).
        const code = (err as VaultRecoveryBlockedError).code ?? null
        log.warn(
          'Workspace unlock refused: the startup recovery is blocked (a held recovery file, a workspace file it ' +
            "could not read or replay, or a password change's staged file it could not put in place)",
          code === null ? undefined : { code }
        )
        ctx.audit?.('workspace_unlock_failed', 'Workspace unlock refused (recovery blocked)')
        return {
          ok: false,
          reason: 'vault_recovery_blocked',
          message: tMain('main.workspace.recoveryBlocked')
        }
      }
      // #845: the vault's own format (its descriptor, KDF, `.enc` frame or rekey journal) was written
      // by a NEWER build: refused before the password was checked and before anything was written. The
      // same reason + copy as #247 (update the app; nothing was changed), with a log line naming the
      // artifact and the version found. Name-based like the arms above (bundle-duplication quirk).
      if (isVaultNewerError(err)) {
        log.warn('Workspace unlock refused: the vault format was written by a newer build', {
          what: err.what,
          found: err.found
        })
        ctx.audit?.('workspace_unlock_failed', 'Workspace unlock refused (newer workspace)')
        return { ok: false, reason: 'workspace_newer', message: tMain('main.workspace.newer') }
      }
      // #247: the password verified but the database was written by a NEWER build. Its own
      // reason + copy (update the app); the vault is untouched and nothing was written.
      if (isWorkspaceNewerError(err)) {
        log.warn('Workspace unlock refused: the database was written by a newer build', {
          found: err.found,
          supported: err.supported
        })
        ctx.audit?.('workspace_unlock_failed', 'Workspace unlock refused (newer workspace)')
        return { ok: false, reason: 'workspace_newer', message: tMain('main.workspace.newer') }
      }
      // #956: a file error (a roll-forward or a rekey recovery that cannot write) logs its code and system call, never
      // its message, which names the drive's paths; any other error keeps its message (`failureForLog`).
      log.error('Workspace unlock failed', failureForLog(err))
      ctx.audit?.('workspace_unlock_failed', 'Workspace unlock failed')
      return { ok: false, reason: 'error', message: tMain('main.workspace.openFailed') }
    }
  })

  ipcHandle(
    IPC.createWorkspace,
    (_e, password: string, mode: WorkspaceMode): WorkspaceActionResult => {
      // M-S2: validate the renderer-supplied shapes FIRST. `password.length` used to be
      // read OUTSIDE the try/catch, so a non-string password was an unhandled TypeError
      // at the IPC boundary instead of a clean refusal. `mode` must be a known enum too.
      if (mode !== 'encrypted' && mode !== 'plaintext_dev') {
        return { ok: false, reason: 'error', message: tMain('main.workspace.createFailed') }
      }
      if (typeof password !== 'string') {
        return {
          ok: false,
          reason: 'refused',
          message: tMain('main.workspace.passwordTooShort', { min: MIN_PASSWORD_LENGTH })
        }
      }
      if (mode === 'encrypted' && password.length < MIN_PASSWORD_LENGTH) {
        return {
          ok: false,
          reason: 'refused',
          message: tMain('main.workspace.passwordTooShort', { min: MIN_PASSWORD_LENGTH })
        }
      }
      try {
        const state = ctx.workspace.create(password, mode)
        // #936 review SF-2, #955 item 4: like an unlock, a create is no moment of a quit (the close guard holds the
        // document-task queue only inside its save or behind its window-modal dialog, and `create` runs synchronously on
        // the main thread), so a quit hold still set here is stale (a quit called off outside the guard): clear it, so
        // it can never block this session's document tasks.
        ctx.docTasks?.releaseQueueHold()
        // Encrypted: adopt the fresh vault key for the log. Plaintext_dev: switch the log to
        // the plain file (`attachLogKey` dispatches on the workspace mode).
        attachLogKey(ctx)
        log.info('Workspace created', { mode })
        ctx.audit?.('workspace_created', 'Workspace created', { mode })
        // Settings are readable now — main-side emissions follow the user's language.
        refreshUiLanguage(ctx)
        // The same P7 sequence as unlock (above): a fresh workspace has never been benchmarked
        // and has no active model yet — the auto-start is a no-op then and the measurement runs
        // at once — but a re-created vault that restored settings gets the full order.
        healEngineLoadState(ctx) // #530: the same heal as the unlock seam above
        const firstBenchmark = prepareFirstBenchmark(ctx)
        // #380: the auto-start waits for the session's probe, as on the unlock seam above.
        const autoStarted = firstBenchmark.probed.then(() => maybeAutoStartActiveModel(ctx))
        void scheduleFirstBenchmark(ctx, firstBenchmark, autoStarted)
        // Third post-unlock seam (create runs the same sequence as unlock): a re-created
        // vault that restored `localApiEnabled: true` starts the endpoint here.
        maybeStartLocalApi(ctx)
        // …and the third knowledge-pack session seam (#301, D3): a re-created vault may sit on
        // a drive that already holds archives, so this session reconciles them too.
        startKnowledgePackSession(ctx)
        // #1002: a first-run create opened the workspace too, so the quit closure hears of it as of an unlock, last
        // (it changes nothing unless a session-end lock left the app running). Never for a refused or failed create.
        hooks.onUnlocked?.()
        return { ok: true, state }
      } catch (err) {
        // #247: the database already on disk (a plaintext workspace, or the file a create
        // would open) was written by a NEWER build — refused before any write.
        if (isWorkspaceNewerError(err)) {
          log.warn('Workspace create refused: the database on disk was written by a newer build', {
            found: err.found,
            supported: err.supported
          })
          return { ok: false, reason: 'workspace_newer', message: tMain('main.workspace.newer') }
        }
        // #807: the two expected refusals are typed, each with its own reason, which the gate renders in its own
        // language (D-17). A workspace is already on the drive: a new one would replace the user's data with an empty
        // vault. instanceof PLUS the name, the bundle-duplication quirk (see the unlock catch).
        // Review V F-3: a key file that appeared under the create form but cannot be read, with no `.enc` beside it:
        // the unlock's own refusal (an unlock form would answer it on every try), with the same copy. The log line
        // names no path.
        if (
          err instanceof VaultDescriptorUnreadableError ||
          (err instanceof Error && err.name === 'VaultDescriptorUnreadableError')
        ) {
          log.warn('Workspace create refused: the workspace descriptor is unreadable and no encrypted file is beside it')
          return {
            ok: false,
            reason: 'vault_descriptor_unreadable',
            message: tMain('main.workspace.descriptorUnreadable')
          }
        }
        if (err instanceof WorkspaceExistsError || (err instanceof Error && err.name === 'WorkspaceExistsError')) {
          log.warn('Workspace create refused: a workspace already exists on the drive')
          return { ok: false, reason: 'workspace_exists', message: tMain('main.workspace.exists') }
        }
        // A workspace without a password, which the policy or the build does not allow (the gate offers the switch only
        // when it is allowed, so only a direct call gets here).
        if (
          err instanceof PlaintextNotAllowedError ||
          (err instanceof Error && err.name === 'PlaintextNotAllowedError')
        ) {
          log.warn('Workspace create refused: a workspace without a password is not allowed')
          return { ok: false, reason: 'plaintext_not_allowed', message: tMain('main.workspace.plaintextNotAllowed') }
        }
        // Anything else failed the create (#807, C S-1: a Node file error such as an `EPERM … rename` while an
        // antivirus holds the new file used to match the old `/not permitted|already exists/` wording and reach the
        // gate raw, with absolute paths, and unlogged). The log line names no path: a file error logs its code and
        // system call only; any other error keeps its message (#844's open failure adds what failed, its `failure`).
        log.error('Workspace create failed', failureForLog(err))
        return { ok: false, reason: 'error', message: tMain('main.workspace.createFailed') }
      }
    }
  )

  // Change the vault password. Runs UNLOCKED only; a wrong current password
  // is a NORMAL failure result audited in the existing unlock-failure class (never a
  // new event, never the password). On a legacy v1 vault the first change runs the
  // one-time journaled migration to the v2 envelope — it can take a while on a big
  // document corpus, so the renderer shows honest progress copy while this resolves.
  ipcHandle(
    IPC.changeWorkspacePassword,
    (_e, currentPassword: string, nextPassword: string): WorkspaceActionResult => {
      // M-S2: a non-string current password would throw in the vault verifier — treat it
      // as a wrong-current-password result (the new-password shape is validated below).
      if (typeof currentPassword !== 'string') {
        return { ok: false, reason: 'wrong_password', message: tMain('main.workspace.wrongCurrentPassword') }
      }
      if (typeof nextPassword !== 'string' || nextPassword.length < MIN_PASSWORD_LENGTH) {
        return {
          ok: false,
          reason: 'refused',
          message: tMain('main.workspace.newPasswordTooShort', { min: MIN_PASSWORD_LENGTH })
        }
      }
      // Also refused once a LOCK is under way (AUD-02): a change re-wraps the descriptor and (on
      // a v1 vault) re-encrypts every `.enc` sidecar, which must never interleave with the lock's
      // own re-encrypt of the working DB. The bare `isUnlocked()` did not express that — the DB
      // stays open for the whole lock teardown.
      if (!workspaceAdmitsWork(ctx.workspace)) {
        return {
          ok: false,
          reason: 'refused',
          message: tMain('main.workspace.unlockBeforeChange')
        }
      }
      try {
        const state = ctx.workspace.changePassword(currentPassword, nextPassword)
        // A v1→v2 migration swaps in a NEW data key and zeroes the old one (v2 keeps the same
        // key). Re-seal the diagnostics log under the now-current key, carrying the in-memory
        // buffer across unchanged — `rekeyVaultLog` deliberately does NOT re-load from disk,
        // which would discard history under a rotated key or double it under an unchanged one.
        const key = ctx.workspace.encryptionKey()
        if (key) rekeyVaultLog(key)
        log.info('Workspace password changed') // never the passwords, in any branch
        // #1027: the change committed, but another program held its staged database, so it could not be moved into
        // place: the open workspace was saved as the workspace file instead (`saved`), or the next lock saves it (review
        // F5: the words follow `saved`). The code is the last error the swap pass met, which need not be the database's
        // own (code review CR1-4: another file's step may have failed after it), so it is logged as that. The code only,
        // never the message (which names the drive's paths).
        const swap = ctx.workspace.takeDatabaseSwapFailure?.()
        if (swap) {
          log.warn(
            swap.saved
              ? 'Workspace password changed: the staged database could not be moved into place, so the open workspace was saved as the workspace file instead (#1027)'
              : 'Workspace password changed: the staged database could not be moved into place, and the open workspace could not be saved yet; the next lock saves it (#1027)',
            { swapLastErrorCode: swap.code, saved: swap.saved }
          )
        }
        logProbeFallbacks(ctx)
        // Audit: id-free, content-free, success only.
        ctx.audit?.('workspace_password_changed', 'Workspace password changed')
        return { ok: true, state }
      } catch (err) {
        // The change did not commit, so the vault still holds the ORIGINAL key and the log was
        // never detached — nothing to re-adopt; it keeps writing under the unchanged key.
        // instanceof PLUS the name — same bundle-duplication quirk as unlockWorkspace.
        if (err instanceof WrongPasswordError || (err instanceof Error && err.name === 'WrongPasswordError')) {
          ctx.audit?.('workspace_unlock_failed', 'Workspace password change failed (wrong current password)')
          return {
            ok: false,
            reason: 'wrong_password',
            message: tMain('main.workspace.wrongCurrentPassword')
          }
        }
        // Document work holds the vault: the vault's own `tMain` text (#807: in main's language, like every refusal
        // on the open workspace's Settings card).
        if (err instanceof VaultBusyError || (err instanceof Error && err.name === 'VaultBusyError')) {
          return { ok: false, reason: 'refused', message: err.message }
        }
        // Everything else, including the #845 refusals (the descriptor on disk is a newer build's, or no
        // longer the one this session unlocked; nothing was written), reads "change failed, your current
        // password still works": true, and the gate's "update the app to open it" would be wrong on an
        // open workspace. #956: a file error (the descriptor's temp, a document sidecar or a stored copy the rekey
        // stages) logs its code and system call, never its message, which names the path; any other error keeps its
        // message (`failureForLog`).
        log.error('Workspace password change failed', failureForLog(err))
        logProbeFallbacks(ctx)
        return {
          ok: false,
          reason: 'error',
          message: tMain('main.workspace.changeFailed')
        }
      }
    }
  )

  ipcHandle(IPC.lockWorkspace, async (): Promise<WorkspaceStateInfo> => {
    // AUD-02 — arm the lock latch FIRST, before any await. Everything below this line is an
    // awaited teardown that can take seconds (sidecar suspends, stream settles, the doc-task
    // settle), and an async ipcMain handler yields the main thread at every one of those awaits,
    // so a `startDocTask`/`translateStart`/`imageAnalyze`/`importDocuments` arriving in that
    // window is dispatched normally. Until this latch existed, every admission guard was a bare
    // `isUnlocked()` — true until the very last statement of this handler — so such a call was
    // ADMITTED and immediately pumped, and because the suspends below are deliberately
    // NON-latching (the sidecars must come back lazily after the next unlock) it lazily
    // RESPAWNED the multi-GB child this teardown had just killed, with document/image-derived
    // text in its KV cache, outliving the lock. The renderer likewise stays mounted until this
    // invoke RESOLVES, so the refusal is what the user's next click gets either way.
    ctx.workspace.beginLock()
    try {
      return await runLockTeardown(ctx)
    } catch (err) {
      // AUD-02 — the SINGLE disarm point for every failure path out of the teardown, including
      // the CODE-1a failed re-encrypt below and any throw from a teardown boundary. Arming a
      // latch before multi-second work introduces a failure mode the pre-latch code did not
      // have: a throw between `beginLock()` and `lock()` would leave the workspace UNLOCKED
      // (DB open, key live) with the latch armed, and `unlock()` cannot clear it — it early-
      // returns on an already-unlocked controller before it can start a new session. Every
      // content surface would then refuse for the rest of the session with no user-visible
      // explanation and no recovery short of a relaunch. Reachability is low today (all seven
      // teardown boundaries are async, so their failures arrive as rejections `allSettled`
      // swallows), but one non-async boundary added later would reintroduce it, so the
      // structure — not the current call list — is what guarantees the disarm.
      // The condition is deliberate: disarm only while the workspace is genuinely still open.
      // A lock that already closed the DB must KEEP the latch (`isUnlocked()` reports locked by
      // then, and the next unlock clears it).
      if (ctx.workspace.isUnlocked()) {
        ctx.workspace.cancelLock()
        // #344: the teardown above stopped every sidecar BEFORE the vault re-encrypted, and a
        // failed lock never reaches the post-unlock seam that brings the two EAGER ones back —
        // the workspace stays open, but the chat runtime is stopped (`runtime.stop()`; Chat then
        // shows "No model is running" until the user re-starts it on the AI Model screen) and an
        // opted-in local API is down (`localApi.stop()`, "restarted only by the post-unlock
        // seam"). Everything else the teardown suspended comes back lazily on its next use
        // (embedder, reranker, transcriber, OCR, translator, vision, kiwix-serve — the #301
        // P3b/P5 non-latching pattern), so nothing more needs re-arming. Re-run exactly the two
        // post-unlock restarts, AFTER the disarm (both check `workspaceAdmitsWork()` first) and
        // fire-and-forget, so the handler still rejects at once with the friendly copy below.
        // No new session, no epoch bump, no benchmark scheduling: a failed lock is not an unlock.
        maybeStartLocalApi(ctx)
        void maybeAutoStartActiveModel(ctx)
      }
      throw err
    }
  })
}

/**
 * The "Lock now" teardown, extracted so the lock handler is a bare
 * `beginLock()` → `try { … } catch { disarm }` frame: the latch's disarm-on-any-failure
 * guarantee is then structural rather than a property of which boundaries happen to be async.
 * Runs with the latch ARMED and the DB still OPEN — every step below deliberately depends on
 * that (partial replies persist, transients shred, vectors purge, the audit event writes),
 * which is why `requireDb()`/`ctx.db` is NOT latched.
 */
async function runLockTeardown(ctx: AppContext): Promise<WorkspaceStateInfo> {
  // "Lock now" must leave nothing user-derived running: a llama-server sidecar keeps
  // recent prompts in its in-memory KV cache (the reranker additionally saw recent
  // questions + chunk text), so ALL sidecars are stopped BEFORE the vault re-encrypts.
  // In-flight generations are aborted first (their partial replies persist while the
  // DB is still open); the E5 embedder + reranker restart lazily on next use, and the
  // chat runtime comes back via the unlock auto-start. #612: the reason records the cause, so a
  // partial is saved marked "Reply stopped", a question with no answer yet "Not answered", and a
  // re-ask keeps its previous complete answer — a lock is not a verdict on the answer.
  const lockReason = endedEarlyAbortReason('lock')
  for (const controller of inFlightStreams.values()) controller.abort(lockReason)
  // A multi-minute deep-index (tree) build is NOT in inFlightStreams (doc tasks never
  // are), so it must be aborted explicitly or it would keep calling chatStream/getDb()
  // while the vault re-encrypts (plan §4.1 M9). Aborts the build's controller AND rejects
  // any parked arbiter reacquire; the tree is left `building` for reconcileStuckTrees.
  ctx.docTasks?.abortActiveBuild()
  // And ALL doc tasks (TG-3 → TA-1 H2): a running TRANSLATION no longer dies with the chat
  // runtime below — left running, its next window would lazily RESPAWN the suspended
  // TranslateGemma sidecar with document plaintext while the vault re-encrypts. Cancel the
  // running task (cancel persists nothing; a running summary/compare gets a clean `cancelled`
  // too instead of failing against the stopped chat runtime) AND flush the QUEUE. The old
  // `cancelDocTask()` cancelled only the ACTIVE task, and the safety claim that "still-queued
  // tasks fail friendly at dequeue (`getDb()` throws while locked)" was FALSE during THIS
  // handler: the DB stays OPEN while we await the sidecar suspends below, so when the cancelled
  // task settled `pump()` would dequeue the next queued translation INTO the lock window —
  // decrypting document text to a `.parse` transient and cold-starting a fresh ~10 GB sidecar
  // that outlives the lock. `cancelAllDocTasks()` closes that window; no permanent latch (the
  // manager is usable again after unlock).
  ctx.docTasks?.cancelAllDocTasks()
  // #606: and every skill run, before the sidecars stop below. A redaction or document-edit run whose
  // model request died with the sidecar took its FAILURE path, because its own signal was untouched:
  // redaction fell back to the rule-based floor and opened its save dialog over the lock screen (seen
  // in the real app), and an edit ended "could not be completed". Cancelled first, the killed request
  // reads as the cancel it is and nothing is written. Every run, whatever its tool — an extraction
  // decrypts document text too. Its settle is awaited below, beside the doc task's.
  try {
    ctx.skillRuns?.cancelAll()
  } catch {
    /* best-effort */
  }
  // #606: and the benchmark's speed leg, which streams on the same model. Cancelled, it ends as an
  // abort instead of on the killed socket; nothing is persisted (`runBenchmarkAndPersist`).
  try {
    ctx.cancelBenchmark?.()
  } catch {
    /* best-effort */
  }
  // And the active TRANSLATE-VIEW job (TG-4): abort it BEFORE the translator suspend below —
  // left running, its next window would call translate() and lazily RESPAWN the just-suspended
  // ~10 GB sidecar with the source text while the vault re-encrypts. stop() also purges the job
  // map so the transient source/translation text does not linger past the lock (vision parity).
  void ctx.translateJobs?.stop()
  // #237: abort every plaintext operation in flight (a preview, re-index, import prepare,
  // dictation or export decrypting to / reading a `.parse*` transient) NOW, so it has the whole
  // teardown to unwind; its settle is awaited (bounded) and its transients swept below, after
  // the doc-task settle. In-memory; best-effort.
  try {
    ctx.plaintextOps?.abortAll()
  } catch {
    /* best-effort */
  }
  // #301 (H4): and every knowledge-pack operation — an ask's arm, an article read, a parked
  // native-picker wait, a running reconciliation. Its OWN try: two registries sharing one
  // `catch` would make whichever runs second silently optional. The signals fire now, so each
  // operation has the whole teardown to unwind before the bounded settle below; a picker that
  // resolves after this stays refused for good (the op signal never un-aborts), which is why
  // the picker wait is an operation and not merely an epoch check.
  try {
    ctx.zimOps?.abortAll()
  } catch {
    /* best-effort */
  }
  // The local API dies FIRST (local-api wave, D7): its stop() aborts active + queued
  // external streams and closes every socket, so no outside caller can reach the model
  // (or hold a stream open) while the sidecars below are torn down and the vault
  // re-encrypts. Restarted only by the post-unlock seam. Idempotent, non-latching —
  // and best-effort like every sibling boundary: a throw here must never block the
  // security action (the lock proceeds; the listener still dies with lock's stops).
  try {
    await (ctx.localApi?.stop() ?? Promise.resolve())
  } catch {
    /* best-effort — the lock must proceed */
  }
  // `suspend()` (not `stop()`): the sidecars must come back lazily
  // after unlock — `stop()` latches permanently for the will-quit path and used to
  // leave every post-lock/unlock embed failing with "Embedder is stopped".
  await Promise.allSettled([
    ctx.runtime.stop(),
    ctx.embedder.suspend?.() ?? ctx.embedder.stop?.() ?? Promise.resolve(),
    ctx.reranker?.suspend?.() ?? Promise.resolve(),
    // Kill any in-flight whisper-cli child (it is reading decrypted audio;
    // the failing parse marks that document `failed`, and processDocument's finally
    // shreds the decrypted transient). Per-file CLI — next use just respawns.
    ctx.transcriber?.suspend?.() ?? Promise.resolve(),
    // BE-5 (ocr-audit 2026-07-18): terminate the warm tesseract WASM worker — an idle worker
    // holds decoded page bytes in main-process RAM, so it too must die before the vault
    // re-encrypts. `suspend()` (not `stop()`): the engine is held on ctx for the session, so it
    // must come back lazily on the next recognition after unlock — stop() latches permanently.
    ctx.ocrEngine?.suspend() ?? Promise.resolve(),
    // The vision sidecar keeps the decoded image + its prompt in the llama-server KV cache,
    // so it too must die before the vault re-encrypts. `stop()` aborts any in-flight analyze
    // and kills the child; the orchestrator rebuilds a fresh runtime (cold start) on the next
    // analyze, so this needs no `suspend()`/latch distinction (the runtime instance is discarded).
    ctx.vision?.stop() ?? Promise.resolve(),
    // The kiwix-serve sidecar (#301, finding M4) holds open handles on every enabled archive
    // and a live loopback port serving the user's whole library, so it dies here with the
    // others. `suspend()` (not `stop()`): bounded by the server's own SIGTERM → 2 s → SIGKILL
    // → 3 s per child and deliberately NON-LATCHING — a failed lock must admit a new ask at
    // once, so there is no flag that only an unlock could clear. It also aborts the shared
    // start, so every waiter rejects instead of consuming a publication from the old session.
    ctx.zim?.suspend() ?? Promise.resolve(),
    // The TranslateGemma sidecar (TG wave) keeps recent source/translation text in its KV cache,
    // so it too must die before the vault re-encrypts. `suspend()` (not `stop()`): the runtime
    // instance is held on ctx for the session (unlike vision's rebuilt-per-analyze runtime), so
    // it must come back lazily on the next translate() after unlock — stop() latches permanently.
    ctx.translator?.suspend?.() ?? ctx.translator?.stop?.() ?? Promise.resolve()
  ])
  // R1 (full-audit-2026-06-30, Phase C) — deterministically await each aborted stream's
  // SETTLE (its partial-reply persistence) before the DB closes. The aborts above unwind each
  // generation as an ABORT, so `generateAssistantMessage` persists the partial via
  // `appendMessage` while `ctx.db` is open — but that runs in the stream's OWN promise, which
  // this handler never awaited; previously it relied on `runtime.stop()` outrunning the
  // abort-unwind (for an already-exited/mock sidecar `stop()` can resolve first → the partial
  // is dropped, or `appendMessage` throws against the now-closed DB → an unhandled rejection).
  // Awaiting the settle here makes persist-before-close the ORDERING, not a race. Placed after
  // the sidecar stop so a generation that ignores its abort signal is still unwound by the
  // dead sidecar (no teardown stall). Best-effort (`allSettled`) and BOUNDED (full-audit
  // 2026-07-12 REL-4: 5 s ceiling inside `awaitInFlightStreamsSettled`, mirroring the
  // doc-task settle below) so a wedged settle can never hang "Lock now".
  await awaitInFlightStreamsSettled()
  // TA-1 H2: also await the cancelled doc-task's abort-unwind (its materialize/shred runs
  // synchronously while ctx.db is open) before purge/lock close the DB — bounded so a wedged
  // handler can't hang the lock. Mirrors the in-flight-stream settle await above. #606: the
  // cancelled skill runs settle in the same window (a categorize run ends when its doc task does).
  await Promise.all([awaitActiveDocTaskSettled(ctx), awaitSkillRunsSettled(ctx)])
  // #237: then the plaintext operations aborted above — settle within the same bound, and shred
  // whatever `.parse*` transient a parser that cannot cancel still holds. Only registered paths
  // are touched, never a stored copy.
  await settleAndSweepPlaintextOps(ctx)
  // #301 (H4/M4): the same for the knowledge-pack operations — settle within the same bound,
  // shred what a build or a registration that could not cancel still tracks, then remove the
  // workspace's `zim-transient/` contents. The library XML names every enabled pack's title and
  // absolute path in plaintext, so it must be gone before the vault re-encrypts. Best-effort by
  // construction: the lock never fails or hangs because of a pack.
  await settleAndCleanZimTransients(ctx)
  // RAG-6 (Wave P4) — SECURITY purge: drop the resident decoded-vector cache from main-process
  // RAM. The vectors are derived from chunk text, so like the sidecars' in-memory recent text
  // they must not linger after the vault re-encrypts. The staleness signature does NOT cover
  // this (the table is unchanged on lock), so this explicit purge is a hard requirement. Done
  // while `ctx.db` is still open (before `lock()` makes it unreachable). The next search after
  // unlock rebuilds the cache from the re-opened DB.
  purgeResidentVectors(ctx.db)
  // Recorded BEFORE the vault closes — afterwards the DB is unreachable. (If the lock
  // below FAILS, the follow-up `workspace_lock_failed` event corrects the record.)
  ctx.audit?.('workspace_locked', 'Workspace locked')
  // Flush the encrypted diagnostics log while the key is still live, then drop it —
  // lock() zeroes the key, after which the log can no longer be persisted. The next
  // unlock re-attaches and continues the same `app.log.enc`.
  detachVaultKey()
  let state: WorkspaceStateInfo
  try {
    state = ctx.workspace.lock()
  } catch (err) {
    // full-audit 2026-07-11 CODE-1a — the re-encrypt failed (realistically ENOSPC:
    // during lock the plaintext DB + old `.enc` + new `.enc.tmp` coexist, so each lock
    // needs ~DB-size free space). The controller has restored itself to a consistently
    // UNLOCKED state (plaintext DB re-opened, key kept for the retry), so re-adopt the
    // vault key for the diagnostics log and surface friendly copy — §7 voice, localized
    // at emission (D-L5), never the raw error. The renderer keeps the workspace open;
    // the user frees space and taps "Lock now" again.
    //
    // AUD-02: the lock latch is disarmed by the handler's outer catch, not here — the workspace
    // is genuinely open again after this recovery, so leaving it armed would refuse every content
    // surface for the rest of the session with nothing to explain it. One disarm point covers
    // this path and any other throw out of the teardown.
    attachLogKey(ctx)
    // #956: `VaultLockError` is content-free; what caused it (`ENOSPC`, `EPERM`, …) rides along as its `failure`
    // (S-5: before, the line named no cause at all). No path, no message of the cause.
    log.error('Workspace lock failed — workspace stays unlocked', failureForLog(err))
    logProbeFallbacks(ctx)
    ctx.audit?.('workspace_lock_failed', 'Workspace lock failed (workspace stays unlocked)')
    throw new Error(tMain('main.workspace.lockFailed'))
  }
  // #855: the working file was gone or no longer a database, so the lock finished at the last good
  // `.enc` and the workspace is LOCKED (key zeroed, no handle). Not a failure: the latch stays
  // armed and nothing restarts, as after any lock; the lock screen shows the notice. There is no
  // database to audit it in now: the controller keeps the notice until the next unlock (and a
  // marker carries it across a quit, #875), and that unlock records `workspace_working_copy_lost`.
  // This line is buffered like any line logged while locked; it persists if the user unlocks in
  // this session.
  if (state.lockNotice === 'working_copy_lost') {
    log.warn('Workspace locked at its last saved state: the working file was gone or no longer a database')
  }
  logProbeFallbacks(ctx)
  log.info('Workspace locked (sidecars stopped)')
  return state
}