Skip to content

A full-featured download manager.

51.7 KB
Raw Blame
import { createHash, randomUUID } from 'node:crypto'
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import type { Worker } from 'node:worker_threads'
import type { SupportedLocale } from '@shared/constants/locales'
import { AppError, ErrorCode } from '@shared/errors'
import type { PluginManifest } from '@shared/types/plugin'
import type { FfmpegDetection } from '../capabilities/ffmpeg-detect'
import type { CapabilityHost } from '../capabilities/interface'
import type { GrantsManager } from '../grants/grants-manager'
import { ffmpegSatisfies } from '../install/ffmpeg-semver'
import { readMoextEntry } from '../install/moext-reader'
import { loadOfficialPackage } from '../install/official-package'
import { resolveInsidePluginDir } from '../manifest/path-safety'
import type { OperationExecution } from '../operations/operation-files'
import type { PluginRegistry } from '../plugin-registry'
import type { PluginSecurityService } from '../security/security-service'
import type { PluginStateStore } from '../state/plugin-state-store'
import { verifyBuiltinSignature } from '../update/signature'
import type { HookName } from './bridge-protocol'
import { CapabilityBridge, type HookContextArgs } from './capability-bridge'
import {
  type PluginCallChain,
  PluginLane,
  type PluginLaneState,
} from './plugin-lane'

/**
 * Per-plugin activity metadata returned by `PluginHost.activeMeta()`.
 * Used by `ActivationDispatcher.runEviction()` to pick LRU / tier candidates.
 */
export interface ActiveMeta {
  id: string
  lastActivityAt: number
  /** Milliseconds since the plugin last handled a hook or was activated. */
  idleMs: number
  /**
   * The "highest" role band the plugin contributes to.
   * Priority (least critical = evicted first): audit < enrich < post-process
   * < resolve < pre-resolve.
   * A plugin with no hooks (commands-only) falls into 'audit'.
   */
  evictionTier: 'audit' | 'enrich' | 'post-process' | 'resolve' | 'pre-resolve'
  queuedEntries?: number
  runningEntries?: number
}

/**
 * Active plugin descriptor exposed to Plan C orchestration code. Includes the
 * manifest (needed for eligibility + role lookup) and the bridge/worker pair
 * (needed for hook invocation and the abort backstop).
 */
export interface ActivePluginInfo {
  id: string
  manifest: PluginManifest
  bridge: CapabilityBridge
  worker: Worker
}

export interface PluginPolicyLease {
  generation: number
  signal: AbortSignal
  release(): void
}

export type PluginUnavailableReason =
  | 'disabled'
  | 'uninstalled'
  | 'quarantined'
  | 'security_revoked'

export type PluginUnavailableHandler = (
  pluginId: string,
  reason: PluginUnavailableReason,
  at: number
) => Promise<number>

export interface PluginHostOptions {
  security?: PluginSecurityService
  onSecurityChanged?: () => void
  registry: PluginRegistry
  stateStore: PluginStateStore
  capabilityHost: CapabilityHost
  workerScriptPath: string
  maxActivePlugins?: number
  idleDisposeMs?: number
  activationTimeoutMs?: number
  /** Budget in ms for worker-side onDeactivate handlers. Default 2000. */
  deactivateBudgetMs?: number
  appVersion: string
  runtime: 'electron' | 'server'
  hostLanguage: SupportedLocale
  /**
   * Spec §I30 — optional grants manager. When provided, the host resolves
   * `effectivePermissions = required ∪ (optional ∩ granted)` before each
   * activation and passes it to the bridge for runtime gating. Absent →
   * bridge falls back to "all declared permissions" (no gating). Wired in
   * production from main/server; tests can omit.
   */
  pluginGrants?: GrantsManager
  /**
   * Optional ffmpeg detector. When provided the host probes ffmpeg at
   * activation time and enforces `engines.ffmpeg` range requirements.
   * Absent → no ffmpeg gate (all plugins pass regardless of manifest range).
   */
  ffmpegDetect?: () => Promise<FfmpegDetection>
  /** Injectable bundle-source reader; defaults to `readFile(path, 'utf8')`. */
  readBundleSource?: (bundlePath: string) => Promise<string>
  /**
   * Injectable for tests; defaults to the pinned build-time keys. Mirrors
   * `PluginRegistryOptions.signingPubkeys` — the host re-verifies
   * bundle.moext against the SAME trust root the registry used at scan
   * time (2026-07-18 design §4) before trusting its code at activation.
   */
  signingPubkeys?: ReadonlyArray<string>
}

interface Active {
  bridge: CapabilityBridge
  manifest: PluginManifest
  ready: boolean
  /** Rejects host-side waiters when the policy barrier must force teardown. */
  admissionAbort: AbortController
  lastActivityAt: number
  activeTimerCount: number
  registrations: Array<{ kind: 'hook' | 'command'; key: string }>
  /** Shared teardown promise so fatal/deactivate races cannot dispose twice. */
  teardown?: Promise<void>
  /** A failed dispose() must retry the worker termination backstop directly. */
  disposeNeedsBackstop?: boolean
  /**
   * Snapshot taken at activation time. `true` when the plugin does not
   * declare ffmpeg at all (vacuously satisfied), or when detection met the
   * declared `engines.ffmpeg` range. `false` only when the plugin declares
   * `optionalPermissions: ['ffmpeg']` and detection was missing or below
   * range (required+miss always throws before this field is stored).
   */
  ffmpegAdvertised: boolean
  policyGeneration: number
}

interface ActivationAttempt {
  epoch: number
  errorRecorded: boolean
  cancelled: boolean
  cancellation: Promise<never>
  cancel(reason?: Error): void
  promise: Promise<void>
}

/**
 * Default soft cap on concurrently-active plugins, shared by PluginHost and
 * ActivationDispatcher so their independent defaults can't silently diverge.
 */
export const DEFAULT_MAX_ACTIVE_PLUGINS = 32

export class PluginHost {
  private readonly active = new Map<string, Active>()
  private readonly lanes = new Map<string, PluginLane>()
  private readonly policyBarriers = new Set<string>()
  private readonly policyBarrierTails = new Map<string, Promise<unknown>>()
  private readonly policyLeases = new Map<string, Set<AbortController>>()
  // Per-plugin activation/deactivation state. The epoch invalidates every
  // await continuation from an older activation, while `quiescing` is a
  // synchronous tombstone that prevents a replacement worker from starting
  // until teardown has fully completed.
  private readonly activating = new Map<string, ActivationAttempt>()
  private readonly deactivating = new Map<string, Promise<void>>()
  private readonly activationEpochs = new Map<string, number>()
  private readonly quiescing = new Set<string>()
  private readonly artifactQuiescingTasks = new Set<string>()
  private pluginUnavailableHandler: PluginUnavailableHandler | undefined
  private readonly maxActivePlugins: number
  private readonly idleDisposeMs: number
  private readonly activationTimeoutMs: number
  private readonly deactivateBudgetMs: number
  private idleTimer?: NodeJS.Timeout
  private unsubscribeLocale: () => void = () => {}
  private shuttingDown = false
  private unsubscribeSecurity: () => void = () => {}
  private readonly securityStops = new Map<string, Promise<void>>()

  constructor(private readonly opts: PluginHostOptions) {
    this.maxActivePlugins = opts.maxActivePlugins ?? DEFAULT_MAX_ACTIVE_PLUGINS
    // Spec §7 L2149 — Plugin Active → 5 min no hook/capability/timer activity
    // → dispose VM → Inactive. Shells may inject an operations override.
    this.idleDisposeMs = opts.idleDisposeMs ?? 5 * 60_000
    this.activationTimeoutMs = opts.activationTimeoutMs ?? 5_000
    this.deactivateBudgetMs = opts.deactivateBudgetMs ?? 2_000
    this.idleTimer = setInterval(() => this.sweepIdle(), 30_000)
    this.idleTimer.unref?.()
    this.unsubscribeLocale = this.opts.capabilityHost.onLocaleChange((lang) => {
      this.broadcastLocaleChange(lang)
    })
    this.unsubscribeSecurity =
      opts.security?.subscribe(() => this.enforceSecurityPolicy()) ?? (() => {})
  }

  private broadcastLocaleChange(_lang: string): void {
    for (const [pluginId, active] of this.active) {
      if (this.quiescing.has(pluginId)) continue
      try {
        const snap = this.opts.capabilityHost.i18nSnapshot(pluginId)
        active.bridge.postLocaleChange(
          snap.language,
          snap.dir,
          snap.currentDict
        )
      } catch (error) {
        // A terminated/broken worker must not prevent other active plugins
        // from receiving the same committed locale snapshot.
        try {
          this.opts.capabilityHost
            .createLog(pluginId)
            .warn('plugin locale broadcast failed', {
              error: error instanceof Error ? error.message : String(error),
            })
        } catch {
          // Logging is best-effort at this isolation boundary.
        }
      }
    }
  }

  isActive(pluginId: string): boolean {
    return this.activeForUse(pluginId) !== undefined
  }

  /**
   * True only when no worker, bridge, activation continuation, or teardown
   * remains for the plugin. Installer commit/uninstall use this stronger
   * postcondition instead of treating an early `active.delete()` as stopped.
   */
  isQuiescent(pluginId: string): boolean {
    return (
      !this.active.has(pluginId) &&
      !this.activating.has(pluginId) &&
      !this.deactivating.has(pluginId) &&
      !this.quiescing.has(pluginId) &&
      this.laneFor(pluginId).isDrained()
    )
  }

  /**
   * Whether the plugin's ffmpeg surface advertises as available. Reflects
   * the snapshot taken at activate time. Returns undefined when the plugin
   * is not active.
   */
  getFfmpegAdvertised(pluginId: string): boolean | undefined {
    return this.activeForUse(pluginId)?.ffmpegAdvertised
  }

  activeIds(): string[] {
    return [...this.active.keys()].filter(
      (id) => this.activeForUse(id) !== undefined
    )
  }

  /**
   * Invoke a command handler registered inside `pluginId`'s VM. Plan D's
   * `CrossPluginInvoker` calls this after all safeguards pass — every
   * trust gate (declared/public/throttle/rate/size/schema) is enforced
   * upstream, so the host's job here is purely to drive the round-trip
   * over the bridge. Any error thrown by the worker handler surfaces
   * as a rejection that `CrossPluginInvoker` then wraps as
   * `plugin.command.handler_threw` (callee stack never reaches caller).
   */
  invokeCommand(
    pluginId: string,
    commandId: string,
    args: unknown,
    options: {
      callChain?: PluginCallChain
      operation?: OperationExecution
    } = {}
  ): Promise<unknown> {
    return this.laneFor(pluginId).run(
      () => {
        const a = this.activeForUse(pluginId)
        if (!a) {
          throw new AppError(
            ErrorCode.PluginRuntimeFault,
            'plugin.command.not_available'
          )
        }
        a.lastActivityAt = Date.now()
        if (options.operation) {
          const context = {
            ...options.operation,
            signal: AbortSignal.any([
              options.operation.signal,
              a.admissionAbort.signal,
            ]),
          }
          return a.bridge
            .callOperation(commandId, args, context)
            .finally(() => this.teardownActive(pluginId, a, true))
        }

        return raceWithAdmissionAbort(
          a.bridge.callPlugin(commandId, args),
          a.admissionAbort.signal,
          pluginId
        )
      },
      { callChain: options.callChain }
    )
  }

  async activate(
    pluginId: string,
    options: { waitForDeactivation?: boolean } = {}
  ): Promise<void> {
    this.opts.registry.assertSecurityAllowed?.(pluginId)
    if (this.shuttingDown) {
      throw new AppError(
        ErrorCode.PluginRuntimeFault,
        'plugin.activation.host_shutting_down'
      )
    }
    // A policy barrier is authoritative: demand activation must never turn a
    // grant change, disable, upgrade, or uninstall into an implicit reopen.
    if (this.policyBarriers.has(pluginId)) {
      throw new AppError(
        ErrorCode.PluginRuntimeFault,
        `plugin.runtime.admission_closed: ${pluginId}`
      )
    }
    const deactivation = this.deactivating.get(pluginId)
    if (deactivation && options.waitForDeactivation) {
      await deactivation
      return this.activate(pluginId, options)
    }
    // Check the tombstone before `active`: the old worker remains owned by
    // `active` until dispose() completes, but must not be considered a valid
    // idempotent activation while teardown is underway.
    if (this.quiescing.has(pluginId)) {
      throw this.activationSupersededError(pluginId)
    }
    this.laneFor(pluginId).reopen()
    const inFlight = this.activating.get(pluginId)
    if (inFlight) return inFlight.promise
    const existing = this.active.get(pluginId)
    if (existing) {
      if (existing.policyGeneration !== this.policyGenerationFor(pluginId)) {
        await this.deactivate(pluginId)
        return this.activate(pluginId)
      }
      existing.lastActivityAt = Date.now()
      return
    }
    // Coalesce concurrent activations. `active` is only populated after the
    // awaits in doActivate (ffmpeg detect, bundle read, permission
    // resolution), so two overlapping calls would otherwise both pass the
    // guard above, both spawn a worker, and the second active.set() would
    // orphan the first bridge. Share one in-flight promise keyed by pluginId.
    const epoch = (this.activationEpochs.get(pluginId) ?? 0) + 1
    this.activationEpochs.set(pluginId, epoch)
    let rejectCancellation!: (error: Error) => void
    const cancellation = new Promise<never>((_resolve, reject) => {
      rejectCancellation = reject
    })
    // The cancellation promise is raced at every async boundary. Keep a
    // handler attached even between those boundaries to avoid an unhandled
    // rejection when deactivate() wins immediately.
    void cancellation.catch(() => undefined)
    const attempt: ActivationAttempt = {
      epoch,
      errorRecorded: false,
      cancelled: false,
      cancellation,
      cancel: (reason = this.activationSupersededError(pluginId)) => {
        if (attempt.cancelled) return
        attempt.cancelled = true
        rejectCancellation(reason)
      },
      promise: Promise.resolve(),
    }
    // Start in a microtask so the attempt and its real promise are both
    // published before registry/capability test doubles can re-enter us.
    const promise = Promise.resolve()
      .then(() => this.doActivate(pluginId, attempt))
      .catch((error: unknown) => {
        if (
          !attempt.errorRecorded &&
          this.isActivationCurrent(pluginId, attempt) &&
          !this.shuttingDown &&
          this.opts.registry.get(pluginId)?.state.enabled &&
          !this.opts.registry.securityDecision?.(pluginId)
        ) {
          const message = error instanceof Error ? error.message : String(error)
          this.recordError(
            pluginId,
            `plugin.runtime.activation_failed: ${message}`
          )
          this.opts.registry.refreshState(pluginId)
        }
        throw error
      })
      .finally(() => {
        if (this.activating.get(pluginId) === attempt) {
          this.activating.delete(pluginId)
        }
      })
    attempt.promise = promise
    this.activating.set(pluginId, attempt)
    return promise
  }

  /** Probe dependencies, then publish enabled state only if admission stayed current. */
  async enable(pluginId: string): Promise<void> {
    const checkPolicy = this.capturePolicyCheck(pluginId)
    const indexed = this.opts.registry.get(pluginId)
    if (!indexed) {
      throw new AppError(
        ErrorCode.PluginManifestInvalid,
        `unknown plugin: ${pluginId}`
      )
    }
    if (this.shuttingDown) throw laneAdmissionClosed(pluginId)
    await this.checkRuntimeRequirements(indexed.manifest)
    checkPolicy()
    if (this.shuttingDown) throw laneAdmissionClosed(pluginId)
    // No await between the final policy check and publishing enabled state.
    // A disable, upgrade, uninstall or grant change supersedes the old probe.
    if (!this.opts.stateStore.get(pluginId)?.enabled) {
      this.opts.stateStore.setEnabled(pluginId, true)
      this.opts.registry.refreshState(pluginId)
    }
  }

  private async checkRuntimeRequirements(
    manifest: PluginManifest
  ): Promise<boolean> {
    const required = manifest.permissions.includes('ffmpeg')
    const optional = manifest.optionalPermissions?.includes('ffmpeg')
    if ((!required && !optional) || !this.opts.ffmpegDetect) return true
    let detection: FfmpegDetection = { available: false }
    try {
      detection = await this.opts.ffmpegDetect()
    } catch {
      // A probe failure is an unavailable runtime dependency, not a bad package.
    }
    const satisfied =
      detection.available &&
      ffmpegSatisfies(detection.version ?? '', manifest.engines.ffmpeg ?? null)
    if (required && !satisfied) {
      throw new AppError(
        ErrorCode.PluginCapabilityUnavailable,
        detection.available
          ? 'plugin.runtime.ffmpegIncompatible'
          : 'plugin.runtime.ffmpegUnavailable'
      )
    }
    return satisfied
  }

  private async doActivate(
    pluginId: string,
    attempt: ActivationAttempt
  ): Promise<void> {
    this.assertActivationCurrent(pluginId, attempt)
    const indexed = this.opts.registry.get(pluginId)
    if (!indexed) {
      throw new AppError(
        ErrorCode.PluginManifestInvalid,
        `unknown plugin: ${pluginId}`
      )
    }
    if (!indexed.state.enabled) {
      throw new AppError(
        ErrorCode.PluginRuntimeFault,
        `plugin ${pluginId} is disabled`
      )
    }
    await this.awaitActivation(
      pluginId,
      attempt,
      this.opts.registry.recordSecurityAdmission?.(pluginId) ??
        Promise.resolve()
    )
    const policyGeneration = this.policyGenerationFor(pluginId)
    if (this.active.size >= this.maxActivePlugins) {
      throw new AppError(
        ErrorCode.PluginActivationCapExceeded,
        `active plugin cap (${this.maxActivePlugins}) reached`
      )
    }

    let ffmpegAdvertised: boolean
    try {
      ffmpegAdvertised = await this.awaitActivation(
        pluginId,
        attempt,
        this.checkRuntimeRequirements(indexed.manifest)
      )
    } catch (error) {
      if (
        error instanceof AppError &&
        error.code === ErrorCode.PluginCapabilityUnavailable
      ) {
        this.recordError(pluginId, error.message)
        this.opts.registry.refreshState(pluginId)
      }
      throw error
    }

    // manifest.main is only length-validated by the schema; contain it to the
    // plugin's own dir so "../../x" can't make us read+eval a file elsewhere.
    // Kept unconditionally (including the overlay path below) — cheap and
    // harmless even when the overlay's actual source of truth is
    // bundle.moext, not this on-disk path.
    const bundlePath = resolveInsidePluginDir(
      indexed.rootDir,
      indexed.manifest.main
    )
    if (!bundlePath) {
      throw new AppError(
        ErrorCode.PluginManifestInvalid,
        `plugin.manifest.main_escapes_dir: ${indexed.manifest.main}`
      )
    }

    let bundleSource: string
    if (indexed.official) {
      const archive = await this.awaitActivation(
        pluginId,
        attempt,
        loadOfficialPackage(
          indexed.rootDir,
          indexed.official,
          this.opts.signingPubkeys
        )
      )
      const entryBytes = await this.awaitActivation(
        pluginId,
        attempt,
        readMoextEntry(archive.bytes, indexed.manifest.main)
      )
      if (!entryBytes) {
        throw new AppError(
          ErrorCode.PluginManifestInvalid,
          'plugin.install.official_signature_invalid'
        )
      }
      this.assertExecutableDigest(
        pluginId,
        indexed.executableDigest,
        entryBytes
      )
      bundleSource = entryBytes.toString('utf8')
    } else if (indexed.overlay) {
      // Firefox packed-XPI model (2026-07-18 design §4): a builtin
      // hot-update overlay's EXECUTED CODE comes from the signature-verified
      // bundle.moext, never the separately-tamperable extracted tree — an
      // attacker who can write userData keeps the signed bundle but tampers
      // the tree would otherwise get unverified code run with builtin
      // privilege. Re-verify on every activation; nothing here is cached
      // across the signature check performed at scan time.
      const moextBytes = await this.awaitActivation(
        pluginId,
        attempt,
        readFile(path.join(indexed.rootDir, 'bundle.moext'))
      )
      if (
        !verifyBuiltinSignature(
          moextBytes,
          indexed.overlay.signature,
          this.opts.signingPubkeys
        )
      ) {
        this.recordError(pluginId, 'plugin.update.builtin_bad_signature')
        this.opts.registry.refreshState(pluginId)
        throw new AppError(
          ErrorCode.PluginManifestInvalid,
          'plugin.update.builtin_bad_signature'
        )
      }
      const entryBytes = await this.awaitActivation(
        pluginId,
        attempt,
        readMoextEntry(moextBytes, indexed.manifest.main)
      )
      if (!entryBytes) {
        this.recordError(pluginId, 'plugin.update.builtin_bundle_entry_missing')
        this.opts.registry.refreshState(pluginId)
        throw new AppError(
          ErrorCode.PluginManifestInvalid,
          'plugin.update.builtin_bundle_entry_missing'
        )
      }
      this.assertExecutableDigest(
        pluginId,
        indexed.executableDigest,
        entryBytes
      )
      bundleSource = entryBytes.toString('utf8')
    } else {
      const readBundleSource =
        this.opts.readBundleSource ?? ((file) => readFile(file, 'utf8'))
      bundleSource = await this.awaitActivation(
        pluginId,
        attempt,
        readBundleSource(bundlePath)
      )
      this.assertExecutableDigest(
        pluginId,
        indexed.executableDigest,
        Buffer.from(bundleSource, 'utf8')
      )
    }

    let resolveReady: () => void
    let rejectReady: (e: Error) => void
    const ready = new Promise<void>((resolve, reject) => {
      resolveReady = resolve
      rejectReady = reject
    })

    const effectivePermissions = this.opts.pluginGrants
      ? await this.awaitActivation(
          pluginId,
          attempt,
          this.opts.pluginGrants.effectivePermissionsFor(pluginId)
        )
      : undefined

    this.assertActivationCurrent(pluginId, attempt)
    if (this.policyGenerationFor(pluginId) !== policyGeneration) {
      throw new AppError(
        ErrorCode.PluginRuntimeFault,
        `plugin.activation.policy_changed: ${pluginId}`
      )
    }
    let bridge: CapabilityBridge | undefined
    bridge = new CapabilityBridge(
      {
        pluginId,
        manifest: indexed.manifest,
        bundleSource,
        capabilityHost: this.opts.capabilityHost,
        workerScriptPath: this.opts.workerScriptPath,
        heapMB: indexed.manifest.requestedHeapMB ?? 32,
        appVersion: this.opts.appVersion,
        runtime: this.opts.runtime,
        hostLanguage: this.opts.hostLanguage,
        permissionGeneration: policyGeneration,
        effectivePermissions,
      },
      {
        onReady: () => {
          const current = this.active.get(pluginId)
          if (
            !bridge ||
            !this.isActivationCurrent(pluginId, attempt) ||
            current?.bridge !== bridge
          ) {
            return
          }
          const registeredHooks = new Set(
            current.registrations
              .filter((entry) => entry.kind === 'hook')
              .map((entry) => entry.key)
          )
          const missingHooks = Object.keys(
            indexed.manifest.contributes.hooks ?? {}
          ).filter((hook) => !registeredHooks.has(hook))
          if (missingHooks.length > 0) {
            const error = new AppError(
              ErrorCode.PluginRuntimeFault,
              `plugin.hook.not_registered: ${missingHooks.join(',')}`
            )
            this.recordError(pluginId, error.message)
            this.opts.registry.refreshState(pluginId)
            rejectReady(error)
            return
          }
          current.ready = true
          this.opts.stateStore.markActivated(pluginId, Date.now())
          this.opts.registry.refreshState(pluginId)
          resolveReady()
        },
        onRegister: (kind, key) => {
          const current = this.active.get(pluginId)
          if (
            bridge &&
            current?.bridge === bridge &&
            !this.quiescing.has(pluginId)
          ) {
            current.registrations.push({ kind, key })
          }
        },
        onFatal: (code, message) => {
          if (
            !bridge ||
            this.active.get(pluginId)?.bridge !== bridge ||
            this.quiescing.has(pluginId)
          ) {
            return
          }
          const startupFailure =
            !this.active.get(pluginId)?.ready &&
            [
              'plugin.runtime.worker_crashed',
              'plugin.runtime.worker_exited',
              'plugin.runtime.boot_failed',
            ].includes(code)
          this.recordError(
            pluginId,
            `${startupFailure ? 'plugin.runtime.worker_start_failed' : code}: ${message}`
          )
          this.opts.registry.refreshState(pluginId)
          const error = new AppError(ErrorCode.PluginRuntimeFault, message)
          rejectReady(error)
          // Teardown cancels activation synchronously. Preserve the worker
          // failure even if cancellation wins the nested readiness race.
          attempt.cancel(error)
          void this.deactivate(pluginId).catch(() => undefined)
        },
      }
    )
    this.assertActivationCurrent(pluginId, attempt)
    this.active.set(pluginId, {
      bridge,
      manifest: indexed.manifest,
      ready: false,
      admissionAbort: new AbortController(),
      lastActivityAt: Date.now(),
      activeTimerCount: 0,
      registrations: [],
      ffmpegAdvertised,
      policyGeneration,
    })
    const worker = bridge.getWorker()
    worker.on('message', (message: unknown) => {
      if (!isTimerActivityMessage(message)) return
      const current = this.active.get(pluginId)
      if (current?.bridge !== bridge) return
      current.activeTimerCount = message.activeCount
      current.lastActivityAt = Date.now()
    })
    worker.once('exit', () => {
      const current = this.active.get(pluginId)
      if (current?.bridge !== bridge) return
      current.activeTimerCount = 0
      current.lastActivityAt = Date.now()
    })

    const timeoutMs = this.activationTimeoutMs
    let timeoutHandle: NodeJS.Timeout | undefined
    const timeoutP = new Promise<never>((_resolve, reject) => {
      timeoutHandle = setTimeout(() => {
        reject(
          new AppError(
            ErrorCode.PluginActivationTimeout,
            `plugin ${pluginId} did not become ready within ${timeoutMs} ms`
          )
        )
      }, timeoutMs)
      timeoutHandle.unref?.()
    })

    try {
      await this.awaitActivation(
        pluginId,
        attempt,
        Promise.race([ready, timeoutP])
      )
    } catch (e) {
      const current = this.active.get(pluginId)
      if (bridge && current?.bridge === bridge) {
        await this.teardownActive(pluginId, current)
      } else if (bridge) {
        await bridge.dispose()
      }
      throw e
    } finally {
      if (timeoutHandle) clearTimeout(timeoutHandle)
    }
  }

  async deactivate(pluginId: string): Promise<void> {
    const existing = this.deactivating.get(pluginId)
    if (existing) return existing

    // Close guest admission before any asynchronous drain/teardown work.
    this.laneFor(pluginId).close()
    // Establish the tombstone and supersede the activation synchronously,
    // before yielding to any continuation that could publish a bridge.
    this.quiescing.add(pluginId)
    this.activationEpochs.set(
      pluginId,
      (this.activationEpochs.get(pluginId) ?? 0) + 1
    )
    const attempt = this.activating.get(pluginId)
    attempt?.cancel()

    const promise = Promise.resolve()
      .then(() => this.doDeactivate(pluginId, attempt))
      .finally(() => {
        if (this.deactivating.get(pluginId) === promise) {
          this.deactivating.delete(pluginId)
          this.quiescing.delete(pluginId)
        }
        if (!this.shuttingDown && !this.policyBarriers.has(pluginId)) {
          this.laneFor(pluginId).reopen()
        }
      })
    this.deactivating.set(pluginId, promise)
    return promise
  }

  private async doDeactivate(
    pluginId: string,
    attempt: ActivationAttempt | undefined
  ): Promise<void> {
    // The attempt rejects when cancellation wins. Its catch path owns cleanup
    // for any bridge it managed to create, so wait for that path before
    // checking the stable active entry below.
    await attempt?.promise.catch(() => undefined)
    const active = this.active.get(pluginId)
    if (!active) return
    if (this.opts.registry.securityDecision?.(pluginId)) {
      active.admissionAbort.abort()
      await this.teardownActive(pluginId, active, true)
      await this.laneFor(pluginId).drain()
      return
    }
    const lane = this.laneFor(pluginId)
    const drained = await lane.drainWithin(this.deactivateBudgetMs)
    if (!drained) {
      active.admissionAbort.abort()
      lane.cancelQueued()
      await lane.drain()
    }
    await this.teardownActive(pluginId, active, !drained)
  }

  private teardownActive(
    pluginId: string,
    active: Active,
    forced = false
  ): Promise<void> {
    if (active.teardown) return active.teardown
    let teardown!: Promise<void>
    teardown = this.performTeardown(pluginId, active, forced).catch((error) => {
      // A rejected teardown must not be cached forever. Keep the active entry
      // owned by the host and let a later deactivate/upgrade retry termination.
      if (active.teardown === teardown) active.teardown = undefined
      throw error
    })
    active.teardown = teardown
    return teardown
  }

  private async performTeardown(
    pluginId: string,
    active: Active,
    forced: boolean
  ): Promise<void> {
    // A revoked guest must not run its own cleanup or issue more capabilities.
    if (forced) await this.disposeActiveBridge(pluginId, active, true)
    // 1. Run worker-side deactivate handlers (budget enforced by bridge).
    if (!forced) {
      try {
        await active.bridge.runDeactivate(this.deactivateBudgetMs)
      } catch (e) {
        this.opts.capabilityHost
          .createLog(pluginId)
          .warn('worker deactivate failed', {
            error: (e as Error).message,
            code: (e as Error & { code?: string }).code,
          })
      }
    }

    // 2. Run host-side deactivate handlers (LifecycleCapabilityHost registry).
    // Guard: lifecycle may be absent in minimal test stubs.
    if (this.opts.capabilityHost.lifecycle) {
      try {
        await this.opts.capabilityHost.lifecycle.runDeactivate(pluginId)
      } catch (e) {
        this.opts.capabilityHost
          .createLog(pluginId)
          .warn('host deactivate failed', {
            error: (e as Error).message,
            code: (e as Error & { code?: string }).code,
          })
      }
    }

    // 3. Tear down bridge and mark inactive. CapabilityBridge marks itself
    // disposed before awaiting Worker.terminate(), so a rejected dispose()
    // cannot itself be retried; terminate the worker directly as a backstop.
    await this.disposeActiveBridge(pluginId, active)
    if (this.active.get(pluginId) === active) {
      this.active.delete(pluginId)
    }
    this.opts.stateStore.setStatus(pluginId, 'inactive')
    this.opts.registry.refreshState(pluginId)
  }

  private async disposeActiveBridge(
    pluginId: string,
    active: Active,
    force = false
  ): Promise<void> {
    if (!active.disposeNeedsBackstop) {
      try {
        await active.bridge.dispose(force)
        return
      } catch (error) {
        active.disposeNeedsBackstop = true
        this.opts.capabilityHost
          .createLog(pluginId)
          .warn('worker bridge dispose failed; terminating worker directly', {
            error: (error as Error).message,
            code: (error as Error & { code?: string }).code,
          })
      }
    }

    try {
      await active.bridge.getWorker().terminate()
      active.disposeNeedsBackstop = false
    } catch (error) {
      this.opts.capabilityHost
        .createLog(pluginId)
        .warn('worker terminate backstop failed', {
          error: (error as Error).message,
          code: (error as Error & { code?: string }).code,
        })
      throw error
    }
  }

  private async awaitActivation<T>(
    pluginId: string,
    attempt: ActivationAttempt,
    operation: PromiseLike<T>
  ): Promise<T> {
    const value = await Promise.race([
      Promise.resolve(operation),
      attempt.cancellation,
    ])
    this.assertActivationCurrent(pluginId, attempt)
    return value
  }

  private isActivationCurrent(
    pluginId: string,
    attempt: ActivationAttempt
  ): boolean {
    return (
      !attempt.cancelled &&
      !this.quiescing.has(pluginId) &&
      this.activationEpochs.get(pluginId) === attempt.epoch &&
      this.activating.get(pluginId) === attempt
    )
  }

  private assertActivationCurrent(
    pluginId: string,
    attempt: ActivationAttempt
  ): void {
    this.opts.registry.assertSecurityAllowed?.(pluginId)
    if (!this.isActivationCurrent(pluginId, attempt)) {
      throw this.activationSupersededError(pluginId)
    }
  }

  private activationSupersededError(pluginId: string): AppError {
    return new AppError(
      ErrorCode.PluginRuntimeFault,
      `plugin.activation.superseded: ${pluginId}`
    )
  }

  private recordError(pluginId: string, message: string): void {
    const attempt = this.activating.get(pluginId)
    if (attempt) attempt.errorRecorded = true
    this.opts.stateStore.recordError(pluginId, message)
    this.opts.capabilityHost
      .createLog(pluginId)
      .error(message, { source: 'host' })
  }

  private assertExecutableDigest(
    pluginId: string,
    expected: string | undefined,
    bytes: Uint8Array
  ): void {
    const actual = createHash('sha256').update(bytes).digest('hex')
    if (!expected || actual !== expected) {
      this.recordError(pluginId, 'plugin.runtime.executable_identity_changed')
      this.opts.registry.refreshState(pluginId)
      throw new AppError(
        ErrorCode.PluginRuntimeFault,
        'plugin.runtime.executable_identity_changed'
      )
    }
  }

  /**
   * Plan C — list every currently active plugin with the descriptors the
   * HookOrchestrator needs (manifest for eligibility/role, bridge for hook
   * invocation, worker for the abort backstop).
   */
  allActive(): ActivePluginInfo[] {
    const out: ActivePluginInfo[] = []
    for (const [id, a] of this.active.entries()) {
      if (this.activeForUse(id) !== a) continue
      out.push({
        id,
        manifest: a.manifest,
        bridge: a.bridge,
        worker: a.bridge.getWorker(),
      })
    }
    return out
  }

  /**
   * Plan C T14 — per-plugin activity metadata used by ActivationDispatcher
   * eviction. A plugin with no hooks (commands only) derives tier 'audit' —
   * the least-critical role and therefore the first-to-evict bucket.
   */
  activeMeta(): ActiveMeta[] {
    const now = Date.now()
    return [...this.active.entries()]
      .filter(([id, active]) => this.activeForUse(id) === active)
      .map(([id, a]) => ({
        id,
        lastActivityAt: a.lastActivityAt,
        idleMs: now - a.lastActivityAt,
        evictionTier: deriveEvictionTier(a.manifest),
        queuedEntries: this.laneFor(id).state().queued,
        runningEntries: this.laneFor(id).state().running,
      }))
  }

  /** Plan C — bridge accessor used by HookOrchestrator and tests. */
  bridgeFor(pluginId: string): CapabilityBridge | undefined {
    return this.activeForUse(pluginId)?.bridge
  }

  /** Worker access for lifecycle diagnostics. */
  workerFor(pluginId: string): Worker | undefined {
    return this.active.get(pluginId)?.bridge.getWorker()
  }

  /**
   * Plan C — invoke a hook in the named plugin's worker. Wraps
   * `bridge.callHook` and refreshes the per-plugin `lastActivityAt` so the
   * idle sweeper does not evict the plugin mid-chain. The caller (orchestrator)
   * is responsible for setting hook context on the bridge first.
   *
   * Throws (via the returned promise) when the plugin is not active, when the
   * worker reports an error, or when the supplied AbortSignal fires.
   */
  async invokeHook(
    pluginId: string,
    hook: HookName,
    args: {
      taskId: string
      signal: AbortSignal
      timeoutMs: number
      ctxPayload?: Record<string, unknown>
      metadataSnapshot?: Record<string, unknown>
      invocationId?: string
      permissionGeneration?: number
      context: HookContextArgs
    }
  ): Promise<void> {
    if (this.artifactQuiescingTasks.has(args.taskId)) {
      throw new AppError(
        ErrorCode.PluginRuntimeFault,
        `task artifact ${args.taskId} is quiesced`
      )
    }
    await this.laneFor(pluginId).run(
      async (chain) => {
        if (this.artifactQuiescingTasks.has(args.taskId)) {
          throw new AppError(
            ErrorCode.PluginRuntimeFault,
            `task artifact ${args.taskId} is quiesced`
          )
        }
        const a = this.activeForUse(pluginId)
        if (!a) {
          throw new AppError(
            ErrorCode.PluginRuntimeFault,
            `plugin ${pluginId} is not active`
          )
        }
        a.lastActivityAt = Date.now()
        if (args.context.taskId !== args.taskId) {
          throw new AppError(
            ErrorCode.PluginRuntimeFault,
            'plugin.hook.context_task_mismatch'
          )
        }
        const invocationSignal = linkAbortSignals([
          args.signal,
          a.admissionAbort.signal,
        ])
        a.bridge.setHookContext(args.context)
        try {
          return await a.bridge.callHook(
            hook,
            args.taskId,
            invocationSignal.signal,
            args.timeoutMs,
            args.ctxPayload,
            args.metadataSnapshot,
            {
              invocationId: args.invocationId ?? randomUUID(),
              callChainId: chain.id,
              permissionGeneration:
                args.permissionGeneration ?? a.policyGeneration,
            }
          )
        } finally {
          invocationSignal.dispose()
          a.bridge.clearHookContext()
        }
      },
      { signal: args.signal }
    )
  }

  laneState(pluginId: string): PluginLaneState {
    return this.laneFor(pluginId).state()
  }

  drainPlugin(pluginId: string): Promise<void> {
    return this.laneFor(pluginId).drain()
  }

  /** Close task-scoped Hook admission and drain every active bridge writer. */
  async quiesceArtifactWriters(taskId: string): Promise<() => Promise<void>> {
    if (this.artifactQuiescingTasks.has(taskId)) {
      throw new Error(`task artifact ${taskId} is already quiesced`)
    }
    this.artifactQuiescingTasks.add(taskId)
    try {
      await Promise.all(
        [...this.active.values()].map((entry) =>
          entry.bridge.quiesceTaskWriters(taskId)
        )
      )
    } catch (error) {
      this.artifactQuiescingTasks.delete(taskId)
      throw error
    }
    return async () => {
      this.artifactQuiescingTasks.delete(taskId)
    }
  }

  isPolicyMutationPending(pluginId: string): boolean {
    return this.policyBarriers.has(pluginId)
  }

  isSecurityRestricted(pluginId: string): boolean {
    return !!this.opts.registry.securityDecision?.(pluginId)
  }

  /** A returned hook result remains subject to revocation until committed. */
  capturePolicyCheck(pluginId: string): () => void {
    const generation = this.policyGenerationFor(pluginId)
    const check = () => {
      this.opts.registry.assertSecurityAllowed?.(pluginId)
      if (
        this.policyBarriers.has(pluginId) ||
        this.policyGenerationFor(pluginId) !== generation
      ) {
        throw laneAdmissionClosed(pluginId)
      }
    }
    check()
    return check
  }

  /**
   * Registers an invocation-scoped policy lease. Policy mutation aborts every
   * registered lease before waiting for the plugin lane or worker teardown.
   */
  acquirePolicyLease(
    pluginId: string,
    expectedGeneration: number
  ): PluginPolicyLease {
    this.opts.registry.assertSecurityAllowed?.(pluginId)
    if (
      this.policyBarriers.has(pluginId) ||
      this.policyGenerationFor(pluginId) !== expectedGeneration
    ) {
      throw laneAdmissionClosed(pluginId)
    }
    const controller = new AbortController()
    const leases = this.policyLeases.get(pluginId) ?? new Set<AbortController>()
    leases.add(controller)
    this.policyLeases.set(pluginId, leases)
    let released = false
    return {
      generation: expectedGeneration,
      signal: controller.signal,
      release: () => {
        if (released) return
        released = true
        leases.delete(controller)
        if (leases.size === 0) this.policyLeases.delete(pluginId)
      },
    }
  }

  /**
   * Exclusive live-policy mutation barrier. Admission closes synchronously,
   * the old worker and its operations drain (or are terminated at budget),
   * then the new policy is published and receives a fresh generation.
   */
  applyPolicyMutation<T>(
    pluginId: string,
    publish: () => Promise<T> | T
  ): Promise<T> {
    this.laneFor(pluginId).close()
    this.policyBarriers.add(pluginId)
    this.abortPolicyAdmission(pluginId)
    const previous = this.policyBarrierTails.get(pluginId) ?? Promise.resolve()
    const operation = previous
      .catch(() => undefined)
      .then(async () => {
        const generationBefore = this.policyGenerationFor(pluginId)
        await this.deactivate(pluginId)
        const result = await publish()
        if (this.policyGenerationFor(pluginId) === generationBefore) {
          this.opts.registry.bumpPolicyGeneration(pluginId)
        }
        return result
      })
    this.policyBarrierTails.set(pluginId, operation)
    void operation.then(
      () => this.clearPolicyBarrierTail(pluginId, operation),
      () => this.clearPolicyBarrierTail(pluginId, operation)
    )
    return operation
  }

  /**
   * Bind durable post-delivery retention after the runtime repository exists.
   * Installer mutations may call `pluginUnavailable()` from inside their
   * existing policy barrier; `disable()` does so automatically.
   */
  bindPluginUnavailable(handler: PluginUnavailableHandler): void {
    this.pluginUnavailableHandler = handler
  }

  pluginUnavailable(
    pluginId: string,
    reason: PluginUnavailableReason,
    at = Date.now()
  ): Promise<number> {
    return (
      this.pluginUnavailableHandler?.(pluginId, reason, at) ??
      Promise.resolve(0)
    )
  }

  /**
   * Plan C — permanently disable a plugin (e.g. circuit breaker tripped).
   * Records the reason via the state store, marks the plugin disabled, and
   * tears down the active VM if one is running. Idempotent: calling on an
   * already-disabled plugin is a no-op besides updating `lastError`.
   */
  async disable(
    pluginId: string,
    reason: string,
    unavailableReason: Extract<
      PluginUnavailableReason,
      'disabled' | 'quarantined'
    > = 'disabled',
    options: { recordError?: boolean } = {}
  ): Promise<void> {
    await this.applyPolicyMutation(pluginId, async () => {
      // Admission is closed, live capability leases are aborted, and the old
      // worker is drained. Publish reversible state before terminalizing
      // durable deliveries, and roll it back if terminalization fails.
      const previousState = this.opts.stateStore.get(pluginId)
      this.opts.stateStore.setEnabled(pluginId, false)
      if (options.recordError !== false) {
        this.recordError(pluginId, reason)
      }
      this.opts.registry.refreshState(pluginId)
      try {
        await this.pluginUnavailable(pluginId, unavailableReason)
      } catch (error) {
        if (previousState) {
          this.opts.stateStore.upsert({
            ...previousState,
            status:
              previousState.status === 'active'
                ? 'inactive'
                : previousState.status,
          })
        }
        this.opts.registry.refreshState(pluginId)
        throw error
      }
    })
    this.opts.stateStore.setStatus(pluginId, 'disabled')
    this.opts.registry.refreshState(pluginId)
  }

  private operationsShutdown?: () => Promise<void>
  bindOperationsShutdown(shutdown: () => Promise<void>) {
    this.operationsShutdown = shutdown
  }
  async shutdown(): Promise<void> {
    await this.operationsShutdown?.()
    this.shuttingDown = true
    this.unsubscribeSecurity()
    await this.opts.security?.stop()
    this.unsubscribeLocale()
    if (this.idleTimer) clearInterval(this.idleTimer)
    const pluginIds = new Set([
      ...this.active.keys(),
      ...this.activating.keys(),
      ...this.deactivating.keys(),
    ])
    await Promise.all([...pluginIds].map((id) => this.deactivate(id)))
    await this.opts.capabilityHost.flush()
    await this.opts.capabilityHost.closeLogs?.()
  }

  private sweepIdle(): void {
    const now = Date.now()
    for (const [id, a] of this.active.entries()) {
      if (this.quiescing.has(id)) continue
      if (
        now - a.lastActivityAt >= this.idleDisposeMs &&
        this.laneFor(id).isDrained() &&
        !a.bridge.hasInFlightOperations() &&
        a.activeTimerCount === 0 &&
        (this.policyLeases.get(id)?.size ?? 0) === 0
      ) {
        void this.deactivate(id)
      }
    }
  }

  /**
   * Exposed for unit tests so they can drive idle disposal without waiting
   * for the 30s timer interval.
   */
  __sweepIdleForTest(): void {
    this.sweepIdle()
  }

  /** Test helper: idle threshold accessor. */
  get idleDisposeMsForTest(): number {
    return this.idleDisposeMs
  }

  private activeForUse(pluginId: string): Active | undefined {
    if (this.opts.registry.securityDecision?.(pluginId)) return undefined
    if (this.quiescing.has(pluginId) || this.policyBarriers.has(pluginId)) {
      return undefined
    }
    const active = this.active.get(pluginId)
    if (!active?.ready) return undefined
    if (active.policyGeneration !== this.policyGenerationFor(pluginId)) {
      return undefined
    }
    return active
  }

  private laneFor(pluginId: string): PluginLane {
    let lane = this.lanes.get(pluginId)
    if (!lane) {
      lane = new PluginLane(pluginId)
      this.lanes.set(pluginId, lane)
    }
    return lane
  }

  private policyGenerationFor(pluginId: string): number {
    return this.opts.registry.policyGenerationFor(pluginId)
  }

  private abortPolicyAdmission(pluginId: string): void {
    this.active.get(pluginId)?.admissionAbort.abort()
    for (const controller of this.policyLeases.get(pluginId) ?? []) {
      controller.abort()
    }
    this.laneFor(pluginId).cancelQueued()
  }

  private clearPolicyBarrierTail(
    pluginId: string,
    operation: Promise<unknown>
  ): void {
    if (this.policyBarrierTails.get(pluginId) === operation) {
      this.policyBarrierTails.delete(pluginId)
      this.policyBarriers.delete(pluginId)
      if (!this.shuttingDown) this.laneFor(pluginId).reopen()
    }
  }

  /** Called on signed-policy refresh; closes all affected lanes before awaiting IO. */
  enforceSecurityPolicy(): Promise<void> {
    const operations: Promise<void>[] = []
    for (const plugin of this.opts.registry.list()) {
      if (!plugin.security || plugin.security.reason === 'pending') continue
      const existing = this.securityStops.get(plugin.id)
      if (existing) {
        operations.push(existing)
        continue
      }
      this.opts.registry.bumpPolicyGeneration(plugin.id)
      this.laneFor(plugin.id).close()
      this.abortPolicyAdmission(plugin.id)
      const active = this.active.get(plugin.id)
      const termination = active
        ? this.disposeActiveBridge(plugin.id, active, true)
        : Promise.resolve()
      void termination.catch(() => undefined)
      const operation = this.applyPolicyMutation(plugin.id, async () => {
        await termination
        // An installer may have already replaced the affected identity while
        // this mutation waited for its lane. Never terminalize its fixed successor.
        const decision = this.opts.registry.securityDecision(plugin.id)
        if (decision && decision.advisoryIds.length > 0) {
          await this.pluginUnavailable(plugin.id, 'security_revoked')
        }
      }).finally(() => {
        this.securityStops.delete(plugin.id)
        this.opts.onSecurityChanged?.()
      })
      this.securityStops.set(plugin.id, operation)
      operations.push(operation)
    }
    this.opts.onSecurityChanged?.()
    return Promise.all(operations).then(() => undefined)
  }

  notifySecurityWake(): void {
    this.opts.security?.notifyWake()
  }

  refreshSecurityPolicy(force = false): Promise<void> {
    return this.opts.security?.refresh(force) ?? Promise.resolve()
  }
}

function isTimerActivityMessage(
  message: unknown
): message is { type: 'timer_activity'; activeCount: number } {
  if (!message || typeof message !== 'object') return false
  const candidate = message as { type?: unknown; activeCount?: unknown }
  return (
    candidate.type === 'timer_activity' &&
    typeof candidate.activeCount === 'number' &&
    Number.isSafeInteger(candidate.activeCount) &&
    candidate.activeCount >= 0 &&
    candidate.activeCount <= 100
  )
}

function raceWithAdmissionAbort<T>(
  operation: Promise<T>,
  signal: AbortSignal,
  pluginId: string
): Promise<T> {
  if (signal.aborted) return Promise.reject(laneAdmissionClosed(pluginId))
  return new Promise<T>((resolve, reject) => {
    let settled = false
    const detach = () => signal.removeEventListener('abort', onAbort)
    const onAbort = () => {
      if (settled) return
      settled = true
      detach()
      reject(laneAdmissionClosed(pluginId))
    }
    signal.addEventListener('abort', onAbort, { once: true })
    operation.then(
      (value) => {
        if (settled) return
        settled = true
        detach()
        resolve(value)
      },
      (error) => {
        if (settled) return
        settled = true
        detach()
        reject(error)
      }
    )
  })
}

function laneAdmissionClosed(pluginId: string): AppError {
  return new AppError(
    ErrorCode.PluginRuntimeFault,
    `plugin.runtime.admission_closed: ${pluginId}`
  )
}

function linkAbortSignals(signals: readonly AbortSignal[]): {
  signal: AbortSignal
  dispose(): void
} {
  const controller = new AbortController()
  const listeners: Array<{
    signal: AbortSignal
    listener: () => void
  }> = []
  const dispose = () => {
    for (const entry of listeners) {
      entry.signal.removeEventListener('abort', entry.listener)
    }
    listeners.length = 0
  }
  for (const signal of signals) {
    if (signal.aborted) {
      controller.abort(signal.reason)
      break
    }
    const listener = () => controller.abort(signal.reason)
    listeners.push({ signal, listener })
    signal.addEventListener('abort', listener, { once: true })
  }
  return { signal: controller.signal, dispose }
}

export function parsePluginIdleDisposeMs(
  raw: string | undefined
): number | undefined {
  if (!raw) return undefined
  const n = Number.parseInt(raw, 10)
  return Number.isFinite(n) && n > 0 ? n : undefined
}

/**
 * Return the "highest" (most critical) role band contributed by the manifest.
 * Priority order (least critical first): audit, enrich, post-process, resolve,
 * pre-resolve. A plugin contributing multiple hooks at different tiers is
 * assigned the tier of its most critical hook so it is protected from eviction
 * at a tier below that threshold.
 *
 * Plugins with no hooks (commands-only) return 'audit' — the least critical
 * tier and therefore the first eviction bucket. T15 will replace this with
 * real in-flight tracking once TaskManager wires the orchestrator.
 */
export function deriveEvictionTier(
  manifest: PluginManifest
): ActiveMeta['evictionTier'] {
  const hooks = manifest.contributes.hooks ?? {}
  const roles = new Set<string>()
  for (const h of Object.values(hooks)) {
    roles.add(h.role ?? 'enrich')
  }
  if (roles.has('pre-resolve')) return 'pre-resolve'
  if (roles.has('resolve')) return 'resolve'
  if (roles.has('post-process')) return 'post-process'
  if (roles.has('enrich')) return 'enrich'
  return 'audit'
}