Skip to content

Fastest and only macOS Dictation app with on-device STT and custom trained AI enhancement model. Windows, iOS testflight! Android, Linux waitlist open! A local Wispr Flow alternative. Follow https://x.com/fluidvoiceapp for more

148 KB
Raw Blame
@preconcurrency import AVFoundation
import CoreMedia
import CryptoKit
import Foundation

@MainActor
protocol MeetingProcessingControlling: AnyObject {
    func process(
        session: MeetingSession,
        sessionDirectory: URL,
        progress: @escaping @MainActor (MeetingProcessingStage) -> Void
    ) async throws -> MeetingProcessingResult
}

actor MeetingProcessingSerializationGate {
    static let shared = MeetingProcessingSerializationGate()

    private var isLeased = false
    private var waiters: [(id: UUID, continuation: CheckedContinuation<Void, Error>)] = []
    private var cancelledWaiterIDs: Set<UUID> = []
    /// Pending = created but not parked: lets cancelWaiter tell "not yet registered" (tombstone)
    /// from "already resumed by release()" (no-op), so tombstones can't accumulate forever.
    private var pendingWaiterIDs: Set<UUID> = []

    func acquire() async throws {
        try Task.checkCancellation()
        if !self.isLeased {
            self.isLeased = true
            return
        }
        let id = UUID()
        self.pendingWaiterIDs.insert(id)
        try await withTaskCancellationHandler {
            try await withCheckedThrowingContinuation { continuation in
                self.register(id: id, continuation: continuation)
            }
        } onCancel: {
            Task { await self.cancelWaiter(id) }
        }
    }

    func release() {
        guard !self.waiters.isEmpty else {
            self.isLeased = false
            return
        }
        self.waiters.removeFirst().continuation.resume()
    }

    private func register(id: UUID, continuation: CheckedContinuation<Void, Error>) {
        self.pendingWaiterIDs.remove(id)
        if self.cancelledWaiterIDs.remove(id) != nil {
            continuation.resume(throwing: CancellationError())
            return
        }
        self.waiters.append((id, continuation))
    }

    private func cancelWaiter(_ id: UUID) {
        if let index = self.waiters.firstIndex(where: { $0.id == id }) {
            self.waiters.remove(at: index).continuation.resume(throwing: CancellationError())
        } else if self.pendingWaiterIDs.contains(id) {
            self.cancelledWaiterIDs.insert(id)
        }
    }
}

/// Keeps only one normalized centroid per session speaker. Matching is
/// conservative and one-to-one within each writer chunk to avoid false merges.
nonisolated struct MeetingSpeakerEmbeddingIndex {
    nonisolated struct Prototype: Equatable {
        var speakerID: SessionSpeakerID
        var embedding: [Float]
        var observationCount: Int
        var averageQuality: Float
    }

    let maximumCosineDistance: Float
    let ambiguityMargin: Float
    private(set) var prototypes: [SessionSpeakerID: Prototype] = [:]

    init(maximumCosineDistance: Float = 0.35, ambiguityMargin: Float = 0.08) {
        self.maximumCosineDistance = maximumCosineDistance
        self.ambiguityMargin = ambiguityMargin
    }

    func bestMatch(
        for embedding: [Float],
        excluding excludedSpeakerIDs: Set<SessionSpeakerID> = []
    ) -> SessionSpeakerID? {
        guard let normalized = Self.normalized(embedding) else { return nil }
        let candidates = self.prototypes.values.compactMap { prototype -> (SessionSpeakerID, Float)? in
            guard !excludedSpeakerIDs.contains(prototype.speakerID),
                  prototype.embedding.count == normalized.count,
                  let distance = Self.cosineDistance(normalized, prototype.embedding)
            else { return nil }
            return (prototype.speakerID, distance)
        }.sorted {
            if $0.1 == $1.1 { return $0.0.uuidString < $1.0.uuidString }
            return $0.1 < $1.1
        }
        guard let closest = candidates.first,
              closest.1 <= self.maximumCosineDistance
        else { return nil }
        if candidates.count > 1, candidates[1].1 - closest.1 < self.ambiguityMargin {
            return nil
        }
        return closest.0
    }

    mutating func observe(
        speakerID: SessionSpeakerID,
        embedding: [Float],
        quality: Float
    ) {
        guard let normalized = Self.normalized(embedding) else { return }
        guard let existing = self.prototypes[speakerID],
              existing.embedding.count == normalized.count
        else {
            self.prototypes[speakerID] = Prototype(
                speakerID: speakerID,
                embedding: normalized,
                observationCount: 1,
                averageQuality: max(0, min(1, quality))
            )
            return
        }

        let nextCount = existing.observationCount + 1
        let retainedCount = min(existing.observationCount, 31)
        let divisor = Float(retainedCount + 1)
        let combined = zip(existing.embedding, normalized).map {
            ($0 * Float(retainedCount) + $1) / divisor
        }
        guard let updatedEmbedding = Self.normalized(combined) else { return }
        let boundedQuality = max(0, min(1, quality))
        let averageQuality = (
            existing.averageQuality * Float(existing.observationCount) + boundedQuality
        ) / Float(nextCount)
        self.prototypes[speakerID] = Prototype(
            speakerID: speakerID,
            embedding: updatedEmbedding,
            observationCount: nextCount,
            averageQuality: averageQuality
        )
    }

    mutating func replace(prototype: Prototype) {
        self.prototypes[prototype.speakerID] = prototype
    }

    func prototype(for speakerID: SessionSpeakerID) -> Prototype? {
        self.prototypes[speakerID]
    }

    var speakerIDs: Set<SessionSpeakerID> {
        Set(self.prototypes.keys)
    }

    static func cosineDistance(_ lhs: [Float], _ rhs: [Float]) -> Float? {
        guard lhs.count == rhs.count, !lhs.isEmpty else { return nil }
        var dot: Float = 0
        var lhsNorm: Float = 0
        var rhsNorm: Float = 0
        for (left, right) in zip(lhs, rhs) {
            guard left.isFinite, right.isFinite else { return nil }
            dot += left * right
            lhsNorm += left * left
            rhsNorm += right * right
        }
        guard lhsNorm > 0, rhsNorm > 0 else { return nil }
        return 1 - max(-1, min(1, dot / sqrt(lhsNorm * rhsNorm)))
    }

    // swiftlint:disable:next discouraged_optional_collection
    private static func normalized(_ embedding: [Float]) -> [Float]? {
        guard let distance = cosineDistance(embedding, embedding), distance.isFinite else { return nil }
        let magnitude = sqrt(embedding.reduce(Float.zero) { $0 + $1 * $1 })
        guard magnitude > 0, magnitude.isFinite else { return nil }
        return embedding.map { $0 / magnitude }
    }
}

/// Deterministically joins per-chunk diarizer labels into session identities.
///
/// This is deliberately a pure value type. It has no knowledge of transcription or capture
/// state, and it never uses observation order as an identity signal. Quality is a diarizer
/// quality metric, not a probability; it is used with speech duration only for the explicit
/// eligibility gates below.
nonisolated struct MeetingGlobalSpeakerStitcher {
    nonisolated struct Observation: Equatable {
        let key: String
        let chunkKey: String
        let trackKind: MeetingAudioTrackKind
        let localLabel: String
        let embedding: [Float]
        let quality: Float
        let effectiveSpeechDuration: TimeInterval
    }

    nonisolated struct Prototype: Equatable {
        let speakerID: SessionSpeakerID
        let embedding: [Float]
        let observationCount: Int
        let averageQuality: Float
        let effectiveSpeechDuration: TimeInterval
        let containsReliableCore: Bool
    }

    nonisolated struct Result: Equatable {
        let speakerIDByObservationKey: [String: SessionSpeakerID]
        let prototypes: [SessionSpeakerID: Prototype]
    }

    /// These thresholds are intentionally named and injectable so behavior can be pinned by tests.
    struct Configuration: Equatable {
        var coreMaximumDistance: Float = 0.35
        var deferredMaximumDistance: Float = 0.25
        var deferredAmbiguityMargin: Float = 0.10
        var coreMinimumQuality: Float = 0.65
        var coreMinimumDuration: TimeInterval = 1.0
        var coreMaximumPairwiseDistance: Float = 0.35
        var bootstrapMinimumQuality: Float = 0.45
        var bootstrapMinimumDuration: TimeInterval = 2.0
        var prototypeUpdateMaximumDistance: Float = 0.12
        // These can be lower than the core gates because the much tighter distance gate above
        // supplies the additional evidence required to update an established prototype.
        var prototypeUpdateMinimumQuality: Float = 0.55
        var prototypeUpdateMinimumDuration: TimeInterval = 0.5
    }

    let configuration: Configuration

    init(configuration: Configuration = Configuration()) {
        self.configuration = configuration
    }

    func stitch(_ observations: [Observation]) -> Result {
        var assignments: [String: SessionSpeakerID] = [:]
        var prototypes: [SessionSpeakerID: Prototype] = [:]

        for trackKind in MeetingAudioTrackKind.allCases {
            let trackObservations = observations
                .filter { $0.trackKind == trackKind }
                .sorted(by: Self.observationPrecedes)
            guard !trackObservations.isEmpty else { continue }

            var clusters: [Cluster] = []
            for observation in trackObservations where self.isReliableCore(observation) {
                guard let normalized = Self.normalized(observation.embedding) else { continue }
                clusters.append(Cluster(observation: observation, embedding: normalized))
            }

            // Avoid a hard regression to "Unknown" when a quiet track has no strict core at all.
            // Bootstrap only from longer, valid observations; once any strict core exists this
            // relaxed path is disabled for the entire track.
            if clusters.isEmpty {
                for observation in trackObservations where self.isBootstrapCore(observation) {
                    guard let normalized = Self.normalized(observation.embedding) else { continue }
                    clusters.append(Cluster(observation: observation, embedding: normalized))
                }
            }

            // Merge reliable cores only. The closest eligible pair is selected with stable
            // tie-breaks, and a cluster merge is rejected if it would violate cannot-link.
            while let pair = self.closestMergeablePair(in: clusters) {
                let right = clusters.remove(at: pair.right)
                let left = clusters.remove(at: pair.left)
                clusters.append(Self.merged(left, right))
                clusters.sort { $0.identityKey < $1.identityKey }
            }

            for index in clusters.indices {
                for observation in clusters[index].observations {
                    assignments[observation.key] = clusters[index].speakerID
                }
            }

            // Deferred observations can attach to cores, never to another deferred observation.
            // A failed attachment gets its own deterministic identity and is not added as a core.
            let coreObservationKeys = Set(clusters.flatMap { $0.observations.map(\.key) })
            for observation in trackObservations where !coreObservationKeys.contains(observation.key) {
                guard let normalized = Self.normalized(observation.embedding) else {
                    let singleton = Self.singletonCluster(for: observation)
                    assignments[observation.key] = singleton.speakerID
                    prototypes[singleton.speakerID] = singleton.prototype()
                    continue
                }

                let candidates = clusters.indices.compactMap { index -> (index: Int, distance: Float)? in
                    let cluster = clusters[index]
                    guard self.canLink(observation, to: cluster),
                          let distance = MeetingSpeakerEmbeddingIndex.cosineDistance(normalized, cluster.embedding)
                    else { return nil }
                    return (index, distance)
                }.sorted {
                    if $0.distance == $1.distance {
                        return clusters[$0.index].identityKey < clusters[$1.index].identityKey
                    }
                    return $0.distance < $1.distance
                }

                guard let closest = candidates.first,
                      closest.distance <= self.configuration.deferredMaximumDistance,
                      candidates.dropFirst().first.map({ $0.distance - closest.distance >= self.configuration.deferredAmbiguityMargin }) ?? true
                else {
                    let singleton = Self.singletonCluster(for: observation)
                    assignments[observation.key] = singleton.speakerID
                    prototypes[singleton.speakerID] = singleton.prototype()
                    continue
                }

                let clusterIndex = closest.index
                let clusterID = clusters[clusterIndex].speakerID
                assignments[observation.key] = clusterID
                // Cannot-link membership is independent from whether this observation is trusted
                // enough to move the speaker prototype.
                clusters[clusterIndex].recordConstraint(observation)
                if closest.distance <= self.configuration.prototypeUpdateMaximumDistance,
                   self.isEligibleForPrototypeUpdate(observation)
                {
                    clusters[clusterIndex].add(observation: observation, embedding: normalized)
                }
            }

            for cluster in clusters {
                prototypes[cluster.speakerID] = cluster.prototype()
            }
        }

        return Result(
            speakerIDByObservationKey: assignments,
            prototypes: prototypes
        )
    }

    private struct Cluster {
        var speakerID: SessionSpeakerID
        var identityKey: String
        var observations: [Observation]
        var constrainedLabelsByChunk: [String: Set<String>]
        var embedding: [Float]
        var containsReliableCore: Bool

        init(observation: Observation, embedding: [Float]) {
            self.speakerID = MeetingGlobalSpeakerStitcher.stableUUID(trackKind: observation.trackKind, key: observation.key)
            self.identityKey = observation.key
            self.observations = [observation]
            self.constrainedLabelsByChunk = [observation.chunkKey: [observation.localLabel]]
            self.embedding = embedding
            self.containsReliableCore = true
        }

        mutating func add(observation: Observation, embedding: [Float]) {
            let count = Float(self.observations.count)
            let combined = zip(self.embedding, embedding).map { ($0 * count + $1) / (count + 1) }
            self.embedding = MeetingGlobalSpeakerStitcher.normalized(combined) ?? self.embedding
            self.observations.append(observation)
        }

        mutating func recordConstraint(_ observation: Observation) {
            self.constrainedLabelsByChunk[observation.chunkKey, default: []].insert(observation.localLabel)
        }

        func prototype() -> Prototype {
            Prototype(
                speakerID: self.speakerID,
                embedding: self.embedding,
                observationCount: self.observations.count,
                averageQuality: self.observations.reduce(Float.zero) { $0 + $1.quality } / Float(self.observations.count),
                effectiveSpeechDuration: self.observations.reduce(0) { $0 + max(0, $1.effectiveSpeechDuration) },
                containsReliableCore: self.containsReliableCore
            )
        }
    }

    private func isReliableCore(_ observation: Observation) -> Bool {
        guard Self.normalized(observation.embedding) != nil else { return false }
        return observation.quality >= self.configuration.coreMinimumQuality
            && observation.effectiveSpeechDuration >= self.configuration.coreMinimumDuration
    }

    private func isBootstrapCore(_ observation: Observation) -> Bool {
        guard Self.normalized(observation.embedding) != nil else { return false }
        return observation.quality >= self.configuration.bootstrapMinimumQuality
            && observation.effectiveSpeechDuration >= self.configuration.bootstrapMinimumDuration
    }

    private func isEligibleForPrototypeUpdate(_ observation: Observation) -> Bool {
        observation.quality >= self.configuration.prototypeUpdateMinimumQuality
            && observation.effectiveSpeechDuration >= self.configuration.prototypeUpdateMinimumDuration
    }

    private func canLink(_ observation: Observation, to cluster: Cluster) -> Bool {
        guard let labels = cluster.constrainedLabelsByChunk[observation.chunkKey] else { return true }
        return labels.allSatisfy { $0 == observation.localLabel }
    }

    private func closestMergeablePair(in clusters: [Cluster]) -> (left: Int, right: Int)? {
        var best: (left: Int, right: Int, distance: Float)?
        for left in clusters.indices {
            for right in clusters.indices where right > left {
                guard !clusters[left].observations.contains(where: { first in
                    clusters[right].observations.contains { second in
                        first.chunkKey == second.chunkKey && first.localLabel != second.localLabel
                    }
                }),
                    self.coreClustersRespectDiameter(clusters[left], clusters[right]),
                    let distance = MeetingSpeakerEmbeddingIndex.cosineDistance(
                        clusters[left].embedding, clusters[right].embedding
                    ),
                    distance <= self.configuration.coreMaximumDistance
                else { continue }
                let candidate = (left, right, distance)
                if best.map({ distance < $0.distance
                        || (distance == $0.distance && Self.pairPrecedes(candidate, $0, clusters: clusters)) }) ?? true
                {
                    best = candidate
                }
            }
        }
        return best.map { ($0.left, $0.right) }
    }

    private func coreClustersRespectDiameter(_ left: Cluster, _ right: Cluster) -> Bool {
        left.observations.allSatisfy { first in
            right.observations.allSatisfy { second in
                guard let distance = MeetingSpeakerEmbeddingIndex.cosineDistance(first.embedding, second.embedding) else {
                    return false
                }
                return distance <= self.configuration.coreMaximumPairwiseDistance
            }
        }
    }

    private static func pairPrecedes(
        _ lhs: (Int, Int, Float),
        _ rhs: (left: Int, right: Int, distance: Float),
        clusters: [Cluster]
    ) -> Bool {
        let leftKey = clusters[lhs.0].identityKey + "\u{0}" + clusters[lhs.1].identityKey
        let rightKey = clusters[rhs.left].identityKey + "\u{0}" + clusters[rhs.right].identityKey
        return leftKey < rightKey
    }

    private static func merged(_ left: Cluster, _ right: Cluster) -> Cluster {
        let ordered = (left.observations + right.observations).sorted(by: Self.observationPrecedes)
        var merged = Cluster(observation: ordered[0], embedding: left.identityKey <= right.identityKey ? left.embedding : right.embedding)
        merged.speakerID = MeetingGlobalSpeakerStitcher.stableUUID(trackKind: ordered[0].trackKind, key: ordered[0].key)
        merged.identityKey = ordered[0].key
        merged.observations = []
        merged.constrainedLabelsByChunk = left.constrainedLabelsByChunk
        for (chunkKey, labels) in right.constrainedLabelsByChunk {
            merged.constrainedLabelsByChunk[chunkKey, default: []].formUnion(labels)
        }
        merged.containsReliableCore = left.containsReliableCore || right.containsReliableCore
        for observation in ordered {
            guard let normalized = normalized(observation.embedding) else { continue }
            if merged.observations.isEmpty {
                merged.embedding = normalized
            }
            merged.add(observation: observation, embedding: normalized)
        }
        return merged
    }

    private static func singletonCluster(for observation: Observation) -> Cluster {
        let embedding = Self.normalized(observation.embedding) ?? []
        var cluster = Cluster(observation: observation, embedding: embedding)
        cluster.containsReliableCore = false
        return cluster
    }

    private static func observationPrecedes(_ lhs: Observation, _ rhs: Observation) -> Bool {
        let left = [lhs.key, lhs.chunkKey, lhs.localLabel, lhs.trackKind.rawValue].joined(separator: "\u{0}")
        let right = [rhs.key, rhs.chunkKey, rhs.localLabel, rhs.trackKind.rawValue].joined(separator: "\u{0}")
        return left < right
    }

    // nil represents unavailable or invalid evidence, distinct from a valid empty collection.
    // swiftlint:disable:next discouraged_optional_collection
    private static func normalized(_ embedding: [Float]) -> [Float]? {
        guard let distance = MeetingSpeakerEmbeddingIndex.cosineDistance(embedding, embedding), distance.isFinite else { return nil }
        let magnitude = sqrt(embedding.reduce(Float.zero) { $0 + $1 * $1 })
        guard magnitude > 0, magnitude.isFinite else { return nil }
        return embedding.map { $0 / magnitude }
    }

    private static func stableUUID(trackKind: MeetingAudioTrackKind, key: String) -> UUID {
        var bytes = Array(SHA256.hash(data: Data("global-speaker:\(trackKind.rawValue):\(key)".utf8)).prefix(16))
        bytes[6] = (bytes[6] & 0x0f) | 0x50
        bytes[8] = (bytes[8] & 0x3f) | 0x80
        return UUID(uuid: (
            bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
            bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]
        ))
    }
}

nonisolated enum MeetingTurnSelection {
    /// Drops empty-text turns; nil when all were empty (caller falls back to whole-chunk).
    static func keepingNonEmpty<T>(
        _ turns: [(index: Int, turn: T, text: String)]
        // nil represents unavailable or invalid evidence, distinct from a valid empty collection.
        // swiftlint:disable:next discouraged_optional_collection
    ) -> [(index: Int, turn: T, text: String)]? {
        let nonEmpty = turns.filter { !$0.text.isEmpty }
        return nonEmpty.isEmpty ? nil : nonEmpty
    }
}

/// Separates near-field speech (the user, inches from a personal mic) from far-field sound the same
/// mic also hears — a TV across the room, the laptop speakers. Both are real speech, so a VAD passes
/// both; only level separates them. Measured on a real session: user 0.0287 RMS (-30.8 dBFS) against
/// room audio at 0.0023 (-52.4 dBFS).
///
/// The reference is the track's own loud end rather than an absolute dBFS value, so the rule travels
/// across microphones and gain settings. It degrades safely: when a track holds nothing but distant
/// audio the reference anchors on that audio and nothing is gated.
nonisolated enum MeetingNearFieldGate {
    /// Far enough below the user's own voice to clear room audio, with room to spare for their
    /// quieter moments — the measured gap is 22 dB.
    static let rejectionDepthDB: Double = 15
    /// Nothing this quiet is intelligible near-field speech on any hardware; a backstop for tracks
    /// whose loud end is itself noise.
    static let absoluteFloorRMS: Double = 0.0015
    /// Below this the reference is not a reliable picture of how loud the user gets.
    static let minimumReferenceSeconds: TimeInterval = 3

    /// Duration-weighted 75th percentile of turn loudness: robust to a handful of loud transients
    /// without being dragged down by long stretches of quiet.
    static func referenceRMS(turns: [(rms: Double, duration: TimeInterval)]) -> Double? {
        let usable = turns.filter { $0.rms > 0 && $0.duration > 0 }
        guard usable.reduce(0, { $0 + $1.duration }) >= Self.minimumReferenceSeconds else { return nil }
        let sorted = usable.sorted { $0.rms < $1.rms }
        let total = sorted.reduce(0) { $0 + $1.duration }
        var accumulated: TimeInterval = 0
        for entry in sorted {
            accumulated += entry.duration
            if accumulated >= total * 0.75 { return entry.rms }
        }
        return sorted.last?.rms
    }

    static func isNearField(rms: Double, reference: Double?) -> Bool {
        guard rms >= self.absoluteFloorRMS else { return false }
        guard let reference, reference > 0 else { return true }
        return rms >= reference * pow(10, -Self.rejectionDepthDB / 20)
    }
}

nonisolated enum MeetingLocalSpeakerEvidenceSelector {
    static func candidate(
        evidenceDurationByCluster: [SessionSpeakerID: TimeInterval],
        prototypeSpeakerIDs: Set<SessionSpeakerID>
    ) -> SessionSpeakerID? {
        let ranked = evidenceDurationByCluster
            .filter { $0.value >= 1 && prototypeSpeakerIDs.contains($0.key) }
            .sorted {
                if $0.value == $1.value { return $0.key.uuidString < $1.key.uuidString }
                return $0.value > $1.value
            }
        guard let strongest = ranked.first else { return nil }
        guard ranked.count > 1 else { return strongest.key }
        let runnerUpDuration = ranked[1].value
        guard strongest.value >= max(runnerUpDuration * 1.75, runnerUpDuration + 2) else {
            return nil
        }
        return strongest.key
    }
}

@MainActor
private final class MeetingProviderLanguagePin {
    private enum Desired {
        case none
        case apple(String)
        case cohere(SettingsStore.CohereLanguage)
        case nemotron(SettingsStore.NemotronLanguage)
    }

    private enum Restoration {
        case none
        case apple(String)
        case cohere(SettingsStore.CohereLanguage)
        case nemotron(SettingsStore.NemotronLanguage)
    }

    let languageCode: String
    private let settings: SettingsStore
    private let desired: Desired
    private let restoration: Restoration

    init?(languageCode: String, model: SettingsStore.SpeechModel, settings: SettingsStore) {
        guard let route = VoiceEngineLanguageCatalog.routes(
            forLanguageID: languageCode,
            availableModels: [model]
        ).first else { return nil }
        self.languageCode = route.language.id
        self.settings = settings
        switch route.binding {
        case .automatic, .whisper:
            self.desired = .none
            self.restoration = .none
        case let .appleSpeech(localeIdentifier):
            self.desired = .apple(localeIdentifier)
            self.restoration = .apple(settings.selectedAppleSpeechLocaleIdentifier)
        case let .cohere(language):
            self.desired = .cohere(language)
            self.restoration = .cohere(settings.selectedCohereLanguage)
        case let .nemotron(language):
            self.desired = .nemotron(language)
            self.restoration = .nemotron(settings.selectedNemotronLanguage)
        }
        self.apply()
    }

    func apply() {
        switch self.desired {
        case .none: break
        case let .apple(identifier): self.settings.selectedAppleSpeechLocaleIdentifier = identifier
        case let .cohere(language): self.settings.selectedCohereLanguage = language
        case let .nemotron(language): self.settings.selectedNemotronLanguage = language
        }
    }

    func restore() {
        switch self.restoration {
        case .none:
            break
        case let .apple(identifier):
            self.settings.selectedAppleSpeechLocaleIdentifier = identifier
        case let .cohere(language):
            self.settings.selectedCohereLanguage = language
        case let .nemotron(language):
            self.settings.selectedNemotronLanguage = language
        }
    }
}

@MainActor
// Keep this existing processing state machine intact during integration.
// swiftlint:disable:next type_body_length
final class MeetingProcessingPipeline: MeetingProcessingControlling {
    /// Bump whenever classification rules change so a resumed run can't mix rules mid-session.
    /// Era-awareness did NOT bump this: the mic pass re-runs every time, and multi-era tracks cannot predate this build.
    /// Version 15: retain unfiltered microphone speech when echo filtering is unavailable.
    nonisolated static let pipelineVersion = 15
    /// Per-turn engines starve on short turns, and an all-empty chunk collapses to unlabeled.
    static let perTurnTurnMergeGapSeconds = 5.0

    /// Gap alone produced ~59s turns, too coarse to attribute. Bound the length as well.
    static let meetingTurnMaxSeconds = 30.0

    nonisolated static func turnMergeGapSeconds(supportsWordTimings: Bool) -> TimeInterval {
        supportsWordTimings ? self.meetingTurnMergeGapSeconds : self.perTurnTurnMergeGapSeconds
    }

    /// Claiming the whole chunk marks every concurrent mic turn as overlapping remote, erasing
    /// the clean-speech evidence that identifies "You".
    nonisolated static func isEmptyTurnFallback(_ error: Error) -> Bool {
        if case LabeledPassError.emptyTurn = error { return true }
        return false
    }

    /// On speakers nearly everything overlaps, so overlap cannot identify the mic's owner.
    /// What can: speech that is not the far end coming back.
    nonisolated static func localSpeakerEvidence(
        // Keep this existing grouped state result intact during integration.
        // swiftlint:disable:next large_tuple
        from turns: [(
            clusterID: SessionSpeakerID, start: TimeInterval, end: TimeInterval,
            overlapsRemote: Bool, echoScored: Bool, isEcho: Bool
        )]
    ) -> [SessionSpeakerID: TimeInterval] {
        var supporting: [SessionSpeakerID: TimeInterval] = [:]
        var echoed: [SessionSpeakerID: TimeInterval] = [:]
        for turn in turns {
            let duration = max(0, turn.end - turn.start)
            if turn.isEcho {
                echoed[turn.clusterID, default: 0] += duration
                continue
            }
            guard !turn.overlapsRemote || turn.echoScored else { continue }
            supporting[turn.clusterID, default: 0] += duration
        }
        return supporting.filter { $0.value > (echoed[$0.key] ?? 0) }
    }

    /// Reads `isLikelyEcho` (text-only), never `effectiveEcho`: signal evidence must not
    /// influence which cluster gets elected "You".
    nonisolated static func selectLocalCluster(
        from turns: [StagedMicrophoneTurn],
        prototypeSpeakerIDs: Set<SessionSpeakerID>
    ) -> SessionSpeakerID? {
        MeetingLocalSpeakerEvidenceSelector.candidate(
            evidenceDurationByCluster: self.localSpeakerEvidence(
                from: turns.map {
                    (
                        clusterID: $0.clusterID, start: $0.start, end: $0.end,
                        overlapsRemote: $0.overlapsRemote, echoScored: $0.echoScored,
                        isEcho: $0.isLikelyEcho
                    )
                }
            ),
            prototypeSpeakerIDs: prototypeSpeakerIDs
        )
    }

    nonisolated static func trustedMicrophoneObservationKeys(
        from turns: [StagedMicrophoneTurn]
    ) -> Set<String> {
        Set(turns.compactMap { turn in
            turn.isLikelyEcho ? nil : turn.diarizationObservationKey
        })
    }

    /// Why "You" was or was not elected. Without this the only visible symptom is an entire
    /// microphone track collapsing to "Microphone / Unknown", which has several distinct causes.
    nonisolated static func logLocalSpeakerElection(
        turns: [StagedMicrophoneTurn],
        prototypeSpeakerIDs: Set<SessionSpeakerID>,
        index: MeetingSpeakerEmbeddingIndex?,
        role: MeetingMicrophoneRole,
        elected: SessionSpeakerID?,
        captureMethod: MeetingAudioTrackCaptureMethod?,
        // `unscoredOverlap` pins to 0.0s under VPIO; this carries the widening delta instead.
        widenedIndices: Set<Int> = [],
        // nil represents unavailable or invalid evidence, distinct from a valid empty collection.
        // swiftlint:disable:next discouraged_optional_collection
        captureEras: [MeetingCaptureEra]? = nil
    ) {
        let widenedSeconds = widenedIndices.reduce(0.0) { total, offset in
            guard turns.indices.contains(offset) else { return total }
            return total + max(0, turns[offset].end - turns[offset].start)
        }
        var supporting: [SessionSpeakerID: TimeInterval] = [:]
        var echoed: [SessionSpeakerID: TimeInterval] = [:]
        var skipped: [SessionSpeakerID: TimeInterval] = [:]
        for turn in turns {
            let duration = max(0, turn.end - turn.start)
            if turn.isLikelyEcho {
                echoed[turn.clusterID, default: 0] += duration
            } else if turn.overlapsRemote, !turn.echoScored {
                skipped[turn.clusterID, default: 0] += duration
            } else {
                supporting[turn.clusterID, default: 0] += duration
            }
        }
        let clusters = Set(supporting.keys).union(echoed.keys).union(skipped.keys)
        let rows = clusters
            .map { id -> String in
                let s = supporting[id] ?? 0, e = echoed[id] ?? 0, k = skipped[id] ?? 0
                let proto = prototypeSpeakerIDs.contains(id) ? "yes" : "NO"
                return String(
                    format: "%@ supporting=%.1fs echoed=%.1fs unscoredOverlap=%.1fs prototype=%@ netEvidence=%@",
                    id.uuidString.prefix(8).description,
                    s,
                    e,
                    k,
                    proto,
                    s > e ? "counts" : "DROPPED"
                )
            }
            .sorted()
        // Pairwise prototype distance across the clusters that survived the echo filter: two
        // fragments of one voice are what blocks the winner-margin rule from electing "You".
        var distances: [String] = []
        if let index {
            let survivors = clusters.filter { (supporting[$0] ?? 0) > (echoed[$0] ?? 0) }.sorted {
                $0.uuidString < $1.uuidString
            }
            for (offset, left) in survivors.enumerated() {
                for right in survivors.dropFirst(offset + 1) {
                    guard let a = index.prototypes[left]?.embedding,
                          let b = index.prototypes[right]?.embedding,
                          let distance = MeetingSpeakerEmbeddingIndex.cosineDistance(a, b)
                    else { continue }
                    distances.append(String(
                        format: "%@↔%@ cosineDistance=%.3f (mergeThreshold=%.2f) %@",
                        left.uuidString.prefix(8).description,
                        right.uuidString.prefix(8).description,
                        distance,
                        index.maximumCosineDistance,
                        distance <= index.maximumCosineDistance ? "SAME VOICE" : "different"
                    ))
                }
            }
        }
        let captureMethodDescription = captureMethod.map(String.init(describing:)) ?? "nil"
        let eraDescription = captureEras.map { eras in
            ", eras=[" + eras.map { String(format: "%@@%.1fs", String(describing: $0.method), $0.startSeconds) }.joined(separator: ", ") + "]"
        } ?? ""
        DebugLogger.shared.info(
            "Local speaker election (role=\(role), captureMethod=\(captureMethodDescription)\(eraDescription), "
                + "elected=\(elected?.uuidString.prefix(8).description ?? "none"), "
                + "widened=\(widenedIndices.count)/\(String(format: "%.1f", widenedSeconds))s):\n  "
                + rows.joined(separator: "\n  ")
                + (distances.isEmpty ? "" : "\n  " + distances.joined(separator: "\n  ")),
            source: "MeetingProcessingPipeline"
        )
    }

    /// Drops turns the microphone only heard at a distance. They are not echo — a TV or another
    /// room never matches the far end's words — so nothing downstream can catch them, and left in
    /// they form a rival cluster that outweighs the user and blocks the "You" election entirely.
    /// Gates each turn against its own era's reference (VPIO runs hotter via AGC).
    nonisolated static func rejectingFarField(
        _ turns: [StagedMicrophoneTurn],
        eras: [MeetingCaptureEra]
    ) -> [StagedMicrophoneTurn] {
        guard !turns.isEmpty else { return turns }
        var indicesByEra: [Int: [Int]] = [:]
        for (offset, turn) in turns.enumerated() {
            indicesByEra[Self.eraIndex(containing: turn.start, eras: eras), default: []].append(offset)
        }
        var rejectedOffsets = Set<Int>()
        for (eraIndex, offsets) in indicesByEra {
            let eraTurns = offsets.map { turns[$0] }
            let measured = eraTurns.filter { $0.rms > 0 }
            guard !measured.isEmpty else { continue }
            let reference = MeetingNearFieldGate.referenceRMS(
                turns: measured.map { (rms: $0.rms, duration: max(0, $0.end - $0.start)) }
            )
            var eraRejectedSeconds: TimeInterval = 0
            for offset in offsets {
                let turn = turns[offset]
                guard turn.rms > 0, !MeetingNearFieldGate.isNearField(rms: turn.rms, reference: reference) else { continue }
                rejectedOffsets.insert(offset)
                eraRejectedSeconds += max(0, turn.end - turn.start)
            }
            guard eraRejectedSeconds > 0 else { continue }
            DebugLogger.shared.info(
                String(
                    format: "Near-field gate: era %d dropped %.1fs of %d microphone turns below reference %.5f RMS − %.0f dB",
                    eraIndex,
                    eraRejectedSeconds,
                    eraTurns.count,
                    reference ?? 0,
                    MeetingNearFieldGate.rejectionDepthDB
                ),
                source: "MeetingProcessingPipeline"
            )
        }
        guard !rejectedOffsets.isEmpty else { return turns }
        return turns.enumerated().filter { !rejectedOffsets.contains($0.offset) }.map(\.element)
    }

    /// Reads the chunk once and measures each turn's RMS. Failure degrades to zeros, which the gate
    /// treats as unmeasured rather than as silence.
    nonisolated static func turnLoudness(
        fileURL: URL,
        turns: [(start: TimeInterval, end: TimeInterval)]
    ) -> [Double] {
        guard let samples = try? readSamples(fileURL: fileURL, startSeconds: 0, endSeconds: nil),
              !samples.isEmpty
        else { return Array(repeating: 0, count: turns.count) }
        let sampleRate = 16_000.0
        return turns.map { turn in
            let first = max(0, Int(turn.start * sampleRate))
            let last = min(samples.count, Int(turn.end * sampleRate))
            guard last > first else { return 0 }
            let sum = samples[first..<last].reduce(0.0) { $0 + Double($1) * Double($1) }
            return (sum / Double(last - first)).squareRoot()
        }
    }

    nonisolated static func remoteFallbackIntervals(
        diarizedTurns: [(start: TimeInterval, end: TimeInterval)],
        chunkOffset: TimeInterval,
        chunkDuration: TimeInterval
    ) -> [(start: TimeInterval, end: TimeInterval)] {
        guard !diarizedTurns.isEmpty else {
            return [(start: chunkOffset, end: chunkOffset + chunkDuration)]
        }
        return diarizedTurns.map { (start: chunkOffset + $0.start, end: chunkOffset + $0.end) }
    }

    /// Conversational pauses run to a few seconds; 1.0s fragmented turns and starved the ASR.
    static let meetingTurnMergeGapSeconds = 3.0

    private enum LabeledPassError: Error {
        case emptyTurn
    }

    private struct TimelineInterval {
        var start: TimeInterval
        var end: TimeInterval
    }

    /// Internal (not private) so tests can exercise `effectiveEcho` and local-speaker selection
    /// directly against the pure helpers below.
    struct StagedMicrophoneTurn {
        var chunkID: MeetingAudioChunkID
        var index: Int
        var clusterID: SessionSpeakerID
        var clusterLabel: String
        var diarizationObservationKey: String? = nil
        var start: TimeInterval
        var end: TimeInterval
        /// Original capture clock coordinates. Echo-protection era boundaries live in this domain;
        /// display/merge timestamps above may be de-drifted.
        var rawStart: TimeInterval? = nil
        var rawEnd: TimeInterval? = nil
        var text: String
        var overlapsRemote: Bool
        /// Loudness of this turn's microphone audio, for the near-field gate. Zero when unmeasured.
        var rms: Double = 0
        /// Text-only, from `MeetingEchoDetector`. `localSpeakerEvidence` must keep reading this
        /// field, never `effectiveEcho` — signal evidence must not influence local-speaker
        /// election, or a misclassification could elect the far-end cluster as "You".
        var isLikelyEcho = false
        /// False when nothing scoreable overlapped: absence of a verdict is not evidence.
        var echoScored = false
        var signalVerdict: TurnEchoVerdict = .unknown
        /// What the UI and exporter hide. Text and signal each get to say "echo", because they fail
        /// independently: ASR garbles bleed differently from the far end's own transcript, defeating
        /// text matching, while the signal reads it plainly (measured median 0.91 explained). Either
        /// one is then vetoed by a low-explanation run under the historical compatibility rule.
        /// That run does not prove genuine local speech. Stage A preserves this behavior;
        /// the separately calibrated shadow policy must not influence it.
        ///
        /// `isLikelyEcho` stays text-only and remains the sole input to the local-speaker election —
        /// signal evidence must never reach it, or a misclassification could elect the far-end
        /// cluster as "You" through the 1.75x winner rule.
        var effectiveEcho: Bool {
            self.signalVerdict.legacyEffectiveEcho(textEcho: self.isLikelyEcho)
        }
    }

    private struct PendingDiarizedTurn {
        let observation: MeetingGlobalSpeakerStitcher.Observation
        let trackID: MeetingAudioTrackID
        let chunkID: MeetingAudioChunkID
        let index: Int
        let start: TimeInterval
        let end: TimeInterval
        let text: String
    }

    // MARK: - Echo signal veto

    nonisolated struct ReferenceSpan: Equatable {
        var chunk: MeetingAudioChunk
        var localRange: Range<TimeInterval>
        var outputOffset: TimeInterval
    }

    /// Session time -> each app chunk's own decoded coordinates, keyed off `presentationStart`.
    /// The two writers rotate independently and diverge permanently after a discontinuity on
    /// either track, so app chunk N never lines up with mic chunk N.
    nonisolated static func referenceSpans(
        micSessionRange: (start: TimeInterval, end: TimeInterval),
        appChunks: [MeetingAudioChunk],
        origin: TimeInterval
    ) -> [ReferenceSpan] {
        appChunks.compactMap { chunk in
            let chunkStart = chunk.presentationStart.seconds - origin
            let chunkEnd = chunk.presentationEnd.seconds - origin
            let overlapStart = max(chunkStart, micSessionRange.start)
            let overlapEnd = min(chunkEnd, micSessionRange.end)
            guard overlapEnd > overlapStart else { return nil }
            return ReferenceSpan(
                chunk: chunk,
                localRange: (overlapStart - chunkStart)..<(overlapEnd - chunkStart),
                outputOffset: overlapStart - micSessionRange.start
            )
        }
    }

    /// Concatenates the decoded slices for a mic chunk's time range, zero-filling any gap
    /// (missing chunk, failed chunk, or a hole between chunks). Zero-fill is self-masking: a
    /// zero-filled block has no reference energy, so the scorer's own floor already forces
    /// those frames to NaN — no separate validity mask is needed.
    nonisolated static func gatherReferenceAudio(
        micSessionRange: (start: TimeInterval, end: TimeInterval),
        appChunks: [MeetingAudioChunk],
        origin: TimeInterval,
        sessionDirectory: URL,
        sampleRate: Double
    ) -> [Float] {
        let totalSamples = max(0, Int(((micSessionRange.end - micSessionRange.start) * sampleRate).rounded()))
        guard totalSamples > 0 else { return [] }
        var output = [Float](repeating: 0, count: totalSamples)
        for span in Self.referenceSpans(micSessionRange: micSessionRange, appChunks: appChunks, origin: origin) {
            guard let samples = try? Self.readSamples(
                fileURL: span.chunk.fileURL(relativeTo: sessionDirectory),
                startSeconds: span.localRange.lowerBound,
                endSeconds: span.localRange.upperBound
            ) else { continue }
            let outStart = Int((span.outputOffset * sampleRate).rounded())
            for (offset, sample) in samples.enumerated() {
                let index = outStart + offset
                guard index >= 0, index < output.count else { break }
                output[index] = sample
            }
        }
        return output
    }

    /// Guard interval around each recorded discontinuity on either track, excluded from both
    /// delay estimation and scoring so a clock jump isn't read as correlated (or decorrelated) audio.
    nonisolated static func discontinuityGuardIntervals(
        micChunk: MeetingAudioChunk,
        overlappingAppChunks: [MeetingAudioChunk],
        origin: TimeInterval,
        guardSeconds: TimeInterval
    ) -> [(start: TimeInterval, end: TimeInterval)] {
        (micChunk.discontinuities + overlappingAppChunks.flatMap(\.discontinuities)).compactMap { discontinuity in
            guard let presentationTime = discontinuity.presentationTime else { return nil }
            let time = presentationTime.seconds - origin
            return (time - guardSeconds, time + guardSeconds)
        }
    }

    nonisolated static func zeroingGuardedSamples(
        _ samples: [Float],
        chunkOffset: TimeInterval,
        sampleRate: Double,
        guardIntervals: [(start: TimeInterval, end: TimeInterval)]
    ) -> [Float] {
        guard !guardIntervals.isEmpty else { return samples }
        var result = samples
        for interval in guardIntervals {
            let startIndex = max(0, Int(((interval.start - chunkOffset) * sampleRate).rounded()))
            let endIndex = min(samples.count, Int(((interval.end - chunkOffset) * sampleRate).rounded()))
            guard startIndex < endIndex else { continue }
            for index in startIndex..<endIndex {
                result[index] = 0
            }
        }
        return result
    }

    /// Post-hoc NaN mask rather than zeroing the scorer's inputs: zeroing would corrupt the
    /// block-level fit for the valid frames sharing a block with a guarded one.
    nonisolated static func maskingGuardedFrames(
        _ scores: EchoFrameScores,
        chunkOffset: TimeInterval,
        sampleRate: Double,
        guardIntervals: [(start: TimeInterval, end: TimeInterval)]
    ) -> EchoFrameScores {
        guard !guardIntervals.isEmpty else { return scores }
        let frameSeconds = Double(MeetingEchoSignalScorer.frameLength) / sampleRate
        var fractions = scores.fractions
        for index in fractions.indices {
            let frameStart = chunkOffset + Double(index) * scores.hopSeconds
            let frameEnd = frameStart + frameSeconds
            if guardIntervals.contains(where: { max($0.start, frameStart) < min($0.end, frameEnd) }) {
                fractions[index] = .nan
            }
        }
        return EchoFrameScores(fractions: fractions, hopSeconds: scores.hopSeconds)
    }

    /// Frames whose window overlaps the turn's span; the result is contiguous because frame
    /// time is monotonic in index.
    nonisolated static func turnVerdict(
        _ scores: EchoFrameScores,
        chunkOffset: TimeInterval,
        turnStart: TimeInterval,
        turnEnd: TimeInterval,
        sampleRate: Double
    ) -> (verdict: TurnEchoVerdict, scoreableSeconds: TimeInterval) {
        let frameSeconds = Double(MeetingEchoSignalScorer.frameLength) / sampleRate
        let overlapping = scores.fractions.indices.filter { index in
            let frameStart = chunkOffset + Double(index) * scores.hopSeconds
            let frameEnd = frameStart + frameSeconds
            return frameEnd > turnStart && frameStart < turnEnd
        }
        guard !overlapping.isEmpty else { return (.unknown, 0) }
        let subset = EchoFrameScores(fractions: overlapping.map { scores.fractions[$0] }, hopSeconds: scores.hopSeconds)
        let result = MeetingEchoSignalScorer.verdict(subset)
        Self.logTurnFrameStats(subset, turnStart: turnStart, turnEnd: turnEnd, verdict: result)
        let scoreableCount = subset.fractions.filter { !$0.isNaN }.count
        return (result, Double(scoreableCount) * subset.hopSeconds)
    }

    /// Frame-level picture behind a turn's verdict. The rescue rule uses an absolute low-run
    /// threshold, so long turns need their run length read as a share of the turn, not in seconds.
    nonisolated static func logTurnFrameStats(
        _ scores: EchoFrameScores,
        turnStart: TimeInterval,
        turnEnd: TimeInterval,
        verdict: TurnEchoVerdict
    ) {
        let scoreable = scores.fractions.filter { !$0.isNaN }
        guard !scoreable.isEmpty else { return }
        let sorted = scoreable.sorted()
        let median = sorted[sorted.count / 2]
        var longestLowRun = 0
        var currentRun = 0
        for value in scores.fractions {
            if !value.isNaN, value < MeetingEchoSignalScorer.lowExplanationFractionThreshold {
                currentRun += 1
                longestLowRun = max(longestLowRun, currentRun)
            } else if !value.isNaN {
                currentRun = 0
            }
        }
        let turnSeconds = max(0.001, turnEnd - turnStart)
        let lowRunSeconds = Double(longestLowRun) * scores.hopSeconds
        DebugLogger.shared.info(
            String(
                format: "[echoframes] turn=[%.1f-%.1f] %.1fs median=%.2f scoreable=%.0f%% lowRun=%.2fs (%.1f%% of turn) verdict=%@",
                turnStart,
                turnEnd,
                turnSeconds,
                median,
                100 * Double(scoreable.count) / Double(scores.fractions.count),
                lowRunSeconds,
                100 * lowRunSeconds / turnSeconds,
                String(describing: verdict)
            ),
            source: "MeetingProcessingPipeline"
        )
    }

    /// A capture epoch ends at any discontinuity on either track; a rolling delay consensus must
    /// never survive one — measured drift (~6.4 ppm, ~23ms/hour) makes a stale offset wrong on
    /// the far side of a jump.
    nonisolated static func epochBoundaries(
        micChunks: [MeetingAudioChunk],
        appChunks: [MeetingAudioChunk],
        origin: TimeInterval
    ) -> [TimeInterval] {
        (micChunks + appChunks).flatMap { chunk in
            chunk.discontinuities.compactMap { $0.presentationTime.map { $0.seconds - origin } }
        }.sorted()
    }

    private struct EchoDelayEpochState {
        var boundaries: [TimeInterval]
        var boundaryIndex = 0
        var acceptedDelays: [TimeInterval] = []

        mutating func advance(toChunkEnd chunkEnd: TimeInterval) {
            while self.boundaryIndex < self.boundaries.count, self.boundaries[self.boundaryIndex] <= chunkEnd {
                self.acceptedDelays.removeAll()
                self.boundaryIndex += 1
            }
        }
    }

    /// No confident per-chunk estimate and no consensus yet (e.g. the first chunks of a quiet
    /// meeting) leaves the verdict `.unknown` for that chunk — acceptable, since `.unknown`
    /// never vetoes.
    nonisolated static func resolvedDelay(
        estimate: DelayEstimate?,
        acceptedDelaysInEpoch: [TimeInterval]
    ) -> TimeInterval? {
        if let estimate, estimate.confidence >= MeetingEchoSignalScorer.minimumDelayConfidence {
            return estimate.seconds
        }
        guard !acceptedDelaysInEpoch.isEmpty else { return nil }
        return MeetingEchoSignalScorer.median(acceptedDelaysInEpoch)
    }

    nonisolated struct EchoScoringOutcome {
        var verdicts: [Int: TurnEchoVerdict]
        var acceptedDelaySeconds: TimeInterval?
        /// From the scorer's non-NaN frames — never fabricated from turn duration.
        var scoreableSecondsByTurn: [Int: TimeInterval] = [:]
        var delayConfidence: Double? = nil
    }

    // Every failure here (missing/corrupt reference audio, decode errors, bad timing math, ...)
    // degrades to `.unknown` rather than propagating: a sick application-audio track must never
    // take down an otherwise-healthy microphone chunk.
    // Keep the existing capture/processing contract explicit during integration.
    // swiftlint:disable:next function_parameter_count
    nonisolated static func computeEchoVerdicts(
        micChunk: MeetingAudioChunk,
        micChunkURL: URL,
        chunkOffset: TimeInterval,
        chunkDuration: TimeInterval,
        turns: [(index: Int, start: TimeInterval, end: TimeInterval)],
        applicationTrack: MeetingAudioTrack,
        origin: TimeInterval,
        sessionDirectory: URL,
        acceptedDelaysInEpoch: [TimeInterval]
    ) throws -> EchoScoringOutcome {
        let sampleRate = 16_000.0
        let micSamples = try Self.readSamples(fileURL: micChunkURL, startSeconds: 0, endSeconds: nil)
        guard !micSamples.isEmpty else { return EchoScoringOutcome(verdicts: [:], acceptedDelaySeconds: nil) }

        let micSessionRange = (start: chunkOffset, end: chunkOffset + chunkDuration)
        let referenceSamples = Self.gatherReferenceAudio(
            micSessionRange: micSessionRange,
            appChunks: applicationTrack.chunks,
            origin: origin,
            sessionDirectory: sessionDirectory,
            sampleRate: sampleRate
        )

        let overlappingAppChunks = applicationTrack.chunks.filter { appChunk in
            let start = appChunk.presentationStart.seconds - origin
            let end = appChunk.presentationEnd.seconds - origin
            return end > micSessionRange.start && start < micSessionRange.end
        }
        let guardIntervals = Self.discontinuityGuardIntervals(
            micChunk: micChunk,
            overlappingAppChunks: overlappingAppChunks,
            origin: origin,
            guardSeconds: MeetingEchoSignalScorer.blockSeconds
        )

        let guardedMic = Self.zeroingGuardedSamples(micSamples, chunkOffset: chunkOffset, sampleRate: sampleRate, guardIntervals: guardIntervals)
        let guardedReference = Self.zeroingGuardedSamples(referenceSamples, chunkOffset: chunkOffset, sampleRate: sampleRate, guardIntervals: guardIntervals)
        let estimate = MeetingEchoSignalScorer.estimateDelay(
            mic: guardedMic, reference: guardedReference, sampleRate: sampleRate, maxLagSeconds: 0.5
        )
        guard let delaySeconds = Self.resolvedDelay(estimate: estimate, acceptedDelaysInEpoch: acceptedDelaysInEpoch) else {
            return EchoScoringOutcome(verdicts: [:], acceptedDelaySeconds: nil)
        }
        let acceptedDelaySeconds = (estimate?.confidence ?? 0) >= MeetingEchoSignalScorer.minimumDelayConfidence
            ? estimate?.seconds
            : nil

        let rawScores = MeetingEchoSignalScorer.explainedFractions(
            mic: micSamples, reference: referenceSamples, sampleRate: sampleRate, delaySeconds: delaySeconds
        )
        let scores = Self.maskingGuardedFrames(rawScores, chunkOffset: chunkOffset, sampleRate: sampleRate, guardIntervals: guardIntervals)

        var verdicts: [Int: TurnEchoVerdict] = [:]
        var scoreableSecondsByTurn: [Int: TimeInterval] = [:]
        for turn in turns {
            let scoring = Self.turnVerdict(
                scores, chunkOffset: chunkOffset, turnStart: turn.start, turnEnd: turn.end, sampleRate: sampleRate
            )
            verdicts[turn.index] = scoring.verdict
            scoreableSecondsByTurn[turn.index] = scoring.scoreableSeconds
        }
        return EchoScoringOutcome(
            verdicts: verdicts,
            acceptedDelaySeconds: acceptedDelaySeconds,
            scoreableSecondsByTurn: scoreableSecondsByTurn,
            delayConfidence: estimate?.confidence
        )
    }

    private struct Accumulator {
        var speakers: [MeetingSessionSpeaker] = []
        var segments: [MeetingTranscriptSegment] = []
        var speakerIDByKey: [String: SessionSpeakerID] = [:]
        var embeddingIndexByTrack: [MeetingAudioTrackKind: MeetingSpeakerEmbeddingIndex] = [:]
        var nextRemoteSpeaker = 1
        var nextMicrophoneSpeaker = 1

        mutating func speaker(
            key: String,
            displayName: @autoclosure () -> String,
            trackKind: MeetingAudioTrackKind,
            isLocalUser: Bool,
            clusterID: String?
        ) -> SessionSpeakerID {
            if let existing = self.speakerIDByKey[key] { return existing }
            let id = MeetingProcessingPipeline.stableUUID("speaker:\(key)")
            self.speakerIDByKey[key] = id
            self.speakers.append(MeetingSessionSpeaker(
                id: id,
                displayName: displayName(),
                diarizationClusterID: clusterID,
                trackKind: trackKind,
                isLocalUser: isLocalUser,
                identityCandidates: []
            ))
            return id
        }

        mutating func applyGlobalStitch(
            _ result: MeetingGlobalSpeakerStitcher.Result,
            trackKind: MeetingAudioTrackKind
        ) {
            var index = MeetingSpeakerEmbeddingIndex()
            for prototype in result.prototypes.values.sorted(by: { $0.speakerID.uuidString < $1.speakerID.uuidString }) {
                guard prototype.containsReliableCore, !prototype.embedding.isEmpty else { continue }
                index.replace(prototype: MeetingSpeakerEmbeddingIndex.Prototype(
                    speakerID: prototype.speakerID,
                    embedding: prototype.embedding,
                    observationCount: prototype.observationCount,
                    averageQuality: prototype.averageQuality
                ))
            }
            self.embeddingIndexByTrack[trackKind] = index
        }

        mutating func addResolvedSpeaker(
            id: SessionSpeakerID,
            key: String,
            displayName: String,
            clusterID: String?,
            trackKind: MeetingAudioTrackKind,
            isLocalUser: Bool
        ) {
            let prototype = self.embeddingIndexByTrack[trackKind]?.prototype(for: id)
            if let existingIndex = self.speakers.firstIndex(where: { $0.id == id }) {
                self.speakers[existingIndex].diarizationEmbedding = prototype?.embedding
                self.speakers[existingIndex].diarizationEmbeddingObservationCount = prototype?.observationCount
                self.speakers[existingIndex].diarizationQuality = prototype?.averageQuality
                return
            }
            self.speakerIDByKey[key] = id
            self.speakers.append(MeetingSessionSpeaker(
                id: id,
                displayName: displayName,
                diarizationClusterID: clusterID,
                diarizationEmbedding: prototype?.embedding,
                diarizationEmbeddingObservationCount: prototype?.observationCount,
                diarizationQuality: prototype?.averageQuality,
                trackKind: trackKind,
                isLocalUser: isLocalUser,
                identityCandidates: []
            ))
        }
    }

    private struct ProcessingContext {
        let origin: TimeInterval
        let sessionDirectory: URL
        let provider: any TranscriptionProvider
        let languageCode: String
        let asrService: ASRService
        let languagePin: MeetingProviderLanguagePin
    }

    private let managesModelResidency: Bool
    private let asrServiceProvider: @MainActor () -> ASRService
    private let serializationGate: MeetingProcessingSerializationGate
    private let backendRegistry: MeetingTranscriptionBackendRegistry
    private let backendIDProvider: @MainActor (String) -> MeetingBackendID
    private let preferredASRModelProvider: @MainActor () -> SettingsStore.SpeechModel
    /// Canonical path only: observes chunk files for the analysis manifest. `nil` uses the real
    /// filesystem observer; tests inject fixture observations instead of writing audio.
    private let chunkObserver: (any MeetingChunkAudioObserving)?
    /// Canonical path only: an explicitly injected per-unit echo provider. Without an injection,
    /// only the Parakeet+Nemotron backend gets its Stage E text/time provider; every other
    /// canonical backend remains fail-closed until it wires its own evidence source.
    private let echoVerdictProvider: (any MeetingUnitEchoVerdictProviding)?
    /// Canonical path only: builds the composite backend's runtime for the frozen request. Tests
    /// inject a fake here; production wires ASRService and the Nemotron model locator.
    private let meetingRuntimeFactory: MeetingParakeetNemotronRuntimeFactory
    /// Parakeet+Nemotron path only: makes the diarization model available before planning, which
    /// requires it installed. Production downloads it here when the background download has not
    /// finished; tests inject nothing and supply the model themselves.
    private let prepareDiarizationModel: @MainActor () async throws -> Void
    /// Test seam: runs after the canonical sidecar is written and read-back verified, before the
    /// final cancellation check, so "cancelled after sidecar" is deterministically exercisable.
    private let canonicalSidecarVerifiedProbe: (MeetingResultSidecarReference) -> Void

    init(
        asrServiceProvider: @escaping @MainActor () -> ASRService,
        managesModelResidency: Bool = true,
        serializationGate: MeetingProcessingSerializationGate = .shared,
        backendRegistry: MeetingTranscriptionBackendRegistry? = nil,
        backendID: MeetingBackendID? = nil,
        backendIDProvider: (@MainActor () -> MeetingBackendID)? = nil,
        chunkObserver: (any MeetingChunkAudioObserving)? = nil,
        echoVerdictProvider: (any MeetingUnitEchoVerdictProviding)? = nil,
        meetingRuntimeFactory: MeetingParakeetNemotronRuntimeFactory? = nil,
        prepareDiarizationModel: @escaping @MainActor () async throws -> Void = {},
        canonicalSidecarVerifiedProbe: ((MeetingResultSidecarReference) -> Void)? = nil,
        preferredASRModelProvider: @escaping @MainActor () -> SettingsStore.SpeechModel = { SettingsStore.shared.selectedSpeechModel }
    ) {
        self.asrServiceProvider = asrServiceProvider
        self.preferredASRModelProvider = preferredASRModelProvider
        self.managesModelResidency = managesModelResidency
        self.serializationGate = serializationGate
        self.chunkObserver = chunkObserver
        self.echoVerdictProvider = echoVerdictProvider
        self.meetingRuntimeFactory = meetingRuntimeFactory ?? { [asrServiceProvider] _ in
            MeetingParakeetNemotronRuntime(
                asrServiceProvider: asrServiceProvider,
                modelLocator: MeetingNemotronModelLocator()
            )
        }
        self.prepareDiarizationModel = prepareDiarizationModel
        self.canonicalSidecarVerifiedProbe = canonicalSidecarVerifiedProbe ?? { _ in }
        let resolvedRegistry = backendRegistry ?? MeetingTranscriptionBackendRegistry.makeDefault()
        self.backendRegistry = resolvedRegistry
        // Resolution order, most specific first: an explicitly pinned ID never changes underneath
        // the caller; then an injected provider; then an injected registry's own default; and only
        // otherwise the user preference. An unknown selection is rejected in `process`, never
        // quietly replaced.
        if let backendID {
            self.backendIDProvider = { _ in backendID }
        } else if let backendIDProvider {
            self.backendIDProvider = { _ in backendIDProvider() }
        } else if let backendRegistry {
            let registryDefault = backendRegistry.defaultBackendID
            self.backendIDProvider = { _ in registryDefault }
        } else {
            self.backendIDProvider = { languageCode in
                let saved = SettingsStore.shared.meetingTranscriptionBackendID
                // Preserve English rollback settings; non-English recordings need the current backend.
                return saved == .legacyCompatibility && languageCode != "en" ? .productionDefault : saved
            }
        }
    }

    func process(
        session: MeetingSession,
        sessionDirectory: URL,
        progress: @escaping @MainActor (MeetingProcessingStage) -> Void
    ) async throws -> MeetingProcessingResult {
        guard VoiceEngineLanguageCatalog.parakeetV3LanguageIDs.contains(session.languageCode) else {
            throw MeetingProcessingError.unsupportedLanguage
        }
        guard session.audioTracks.contains(where: { !$0.chunks.isEmpty }) else {
            throw MeetingProcessingError.noRecoverableAudio
        }

        // The selection is read exactly once, here, and every later decision in this attempt uses
        // the local copy. Re-reading the preference after an await could split one attempt across
        // two backends — planning under one, failing the legacy callback against another.
        let backendID = self.backendIDProvider(session.languageCode)
        DebugLogger.shared.info(
            "Meeting final processing selected backend=\(backendID.rawValue)",
            source: "MeetingProcessingPipeline"
        )

        // Resolving and planning the backend happens before the serialization lease and before any
        // model readiness work, so an unknown selection or an incompatible session fails without
        // loading anything.
        //
        // The request is frozen first, so the host capability handed to the factory can be bound to
        // this exact value.
        let request = MeetingBackendRequest(
            attemptID: Self.resolvedAttemptID(session: session),
            session: session,
            sessionDirectory: sessionDirectory,
            configuration: MeetingFinalProcessingConfiguration(
                preferredASRModel: backendID == .parakeetNemotron ? self.preferredASRModelProvider() : nil,
                languageCode: session.languageCode
            )
        )
        let backend = try self.backendRegistry.makeBackend(
            id: backendID,
            context: MeetingBackendHostContext(
                legacyExecutor: { [self] callbackRequest, progress in
                    // The legacy path reads the session's own audio and writes its checkpoint. A
                    // backend calling back with anything but the frozen request — a different session
                    // snapshot, directory, attempt or configuration — is asking to transcribe audio
                    // this call never authorized. Compared whole, not spot-checked.
                    guard callbackRequest == request else {
                        throw MeetingBackendError.legacyExecutorRequestMismatch(backend: backendID)
                    }
                    return try await self.processWithLease(
                        session: request.session,
                        sessionDirectory: request.sessionDirectory,
                        attemptID: request.attemptID,
                        progress: progress
                    )
                },
                parakeetNemotronRuntimeFactory: { [self] callbackRequest in
                    // Same binding rule as the legacy executor: the runtime is created for the
                    // frozen request only, so the composite backend can never aim ASR/model
                    // capabilities at a session this attempt was not given.
                    guard callbackRequest == request else {
                        throw MeetingBackendError.hostCapabilityRequestMismatch(backend: backendID)
                    }
                    return try self.meetingRuntimeFactory(callbackRequest)
                }
            )
        )
        if backendID == .parakeetNemotron {
            try await self.prepareDiarizationModel()
        }
        let plan = try backend.plan(request)
        if let defect = plan.agreementDefect(with: request, descriptor: backend.descriptor) {
            throw MeetingBackendError.planDisagreesWithRequest(backend: backendID, defect: defect)
        }

        try await self.serializationGate.acquire()
        let result: MeetingProcessingResult
        do {
            // Cancellation that landed while this attempt waited for the lease must not start model
            // work: the lease can be held for a long time, and the caller has already moved on.
            try Task.checkCancellation()
            let summaryProvider = MeetingPostProcessingRegistry.shared.provider
            let execute: () async throws -> MeetingProcessingResult = {
                var processed: MeetingProcessingResult
                switch plan.resultContract {
                case .legacyResult:
                    let legacyWork: () async throws -> MeetingProcessingResult = {
                        let outcome = try await backend.execute(plan: plan, manifest: nil, progress: progress)
                        try Task.checkCancellation()
                        guard case let .legacyCompatibility(value) = outcome else {
                            throw MeetingBackendError.outcomeContractMismatch(backend: backendID, declared: .legacyResult)
                        }
                        return value
                    }
                    if self.managesModelResidency {
                        let service = self.asrServiceProvider()
                        do {
                            processed = try await MeetingModelResidencyCoordinator.shared.withLegacySpeechModel(
                                modelID: SettingsStore.shared.selectedSpeechModel.id, work: legacyWork
                            )
                        } catch {
                            await Task { try? await service.meetingResidencyParticipant().suspend() }.value
                            throw error
                        }
                        try await service.meetingResidencyParticipant().suspend()
                    } else {
                        processed = try await legacyWork()
                    }
                case .canonicalEvidence:
                    processed = try await self.processCanonicalAttempt(plan: plan, backend: backend, progress: progress)
                }
                if self.managesModelResidency, summaryProvider != nil {
                    processed.postProcessing = await MeetingPostProcessingRegistry.shared.process(
                        sessionID: session.id,
                        language: session.languageCode,
                        result: processed,
                        directory: sessionDirectory,
                        provider: summaryProvider
                    )
                }
                return processed
            }
            if self.managesModelResidency {
                result = try await self.asrServiceProvider().withMeetingModelResidency(
                    attemptID: request.attemptID, acceptsCompletedCancellation: { $0.postProcessing != nil }, work: execute
                )
            } else {
                result = try await execute()
            }
        } catch {
            await self.serializationGate.release()
            throw error
        }
        // Exactly one release on every path: the throwing paths above, this one otherwise.
        await self.serializationGate.release()
        return result
    }

    /// The canonical Stage C2b2 path, run under the same serialization and cancellation ownership
    /// as the legacy path: manifest from the frozen plan, backend execution against it, product
    /// echo verdicts, assembly, and a written-then-read-back-verified result sidecar. Cancellation
    /// is checked between every non-cooperative boundary, and a cancelled attempt publishes
    /// nothing — it returns no result and references no sidecar.
    private func processCanonicalAttempt(
        plan: MeetingBackendPlan,
        backend: any MeetingTranscriptionBackend,
        progress: @escaping @MainActor (MeetingProcessingStage) -> Void
    ) async throws -> MeetingProcessingResult {
        let request = plan.request
        let observer = self.chunkObserver ?? MeetingChunkAudioObserver(
            sessionDirectory: request.sessionDirectory
        )
        // Chunk observation hashes and decodes real files; keep it off the main actor. The
        // selected backend's real analysis rate is recorded on the manifest when it has one.
        let analysisSampleRate = backend.descriptor.analysisSampleRate
        let manifestTask = Task.detached(priority: .userInitiated) {
            try MeetingAnalysisManifestBuilder(
                plan: plan,
                observer: observer,
                analysisSampleRate: analysisSampleRate
            ).build()
        }
        let manifest = try await withTaskCancellationHandler {
            try await manifestTask.value
        } onCancel: {
            manifestTask.cancel()
        }
        try Task.checkCancellation()

        let outcome = try await backend.execute(plan: plan, manifest: manifest, progress: progress)
        try Task.checkCancellation()
        guard case let .canonicalEvidence(bundle) = outcome else {
            throw MeetingBackendError.outcomeContractMismatch(
                backend: plan.backendID, declared: .canonicalEvidence
            )
        }

        let echoProvider: any MeetingUnitEchoVerdictProviding = self.echoVerdictProvider
            ?? (plan.backendID == .parakeetNemotron
                ? MeetingTextOverlapEchoVerdictProvider()
                : MeetingFailClosedEchoVerdictProvider())
        let echoVerdicts = try await echoProvider.echoVerdicts(
            for: bundle.evidence,
            manifest: manifest,
            plan: plan
        )
        try Task.checkCancellation()

        progress(.finalizing)
        let assemblyInput = MeetingAssemblyInput(
            plan: plan,
            manifest: manifest,
            evidence: bundle.evidence,
            coverageReceipts: bundle.coverageReceipts,
            echoVerdicts: echoVerdicts
        )
        let assemblyTask = Task.detached(priority: .userInitiated) {
            try MeetingTranscriptAssembler().assemble(assemblyInput)
        }
        let assembly = try await withTaskCancellationHandler {
            try await assemblyTask.value
        } onCancel: {
            assemblyTask.cancel()
        }
        try Task.checkCancellation()

        let sidecar = assembly.sidecar
        let attemptID = plan.attemptID
        let backendID = plan.backendID
        let sessionDirectory = request.sessionDirectory
        let reference = try await Task.detached(priority: .userInitiated) {
            let store = MeetingResultSidecarStore(sessionDirectory: sessionDirectory)
            let written = try store.write(sidecar)
            // The write already read-back verifies; this second read is the publication gate:
            // the reference returned below is proven against the attempt's lineage on disk.
            _ = try store.read(
                expectedAttemptID: attemptID,
                expectedBackendID: backendID,
                reference: written
            )
            return written
        }.value
        self.canonicalSidecarVerifiedProbe(reference)
        try Task.checkCancellation()

        progress(.completed)
        return Self.canonicalResult(from: assembly, plan: plan, sidecarReference: reference)
    }

    /// Turns the validated assembly into the normal result. Attempt identity comes from the
    /// frozen request — the still-open attempt is reused, never renumbered; lineage fields record
    /// the actual backend and the immutable configuration snapshot, nothing is synthesized.
    nonisolated static func canonicalResult(
        from assembly: MeetingAssemblyResult,
        plan: MeetingBackendPlan,
        sidecarReference: MeetingResultSidecarReference
    ) -> MeetingProcessingResult {
        let request = plan.request
        var attempt = request.session.processingAttempts
            .last(where: { $0.completedAt == nil && $0.id == plan.attemptID })
            ?? MeetingProcessingAttempt(
                id: plan.attemptID,
                startedAt: Date(),
                completedAt: nil,
                stage: .pending,
                pipelineVersion: request.configuration.pipelineVersion,
                asrProvider: nil,
                asrModel: nil,
                languageCode: request.configuration.languageCode,
                diarizationModel: nil,
                lastCompletedTrackID: nil,
                errorCode: nil
            )
        attempt.stage = .completed
        attempt.completedAt = Date()
        attempt.pipelineVersion = request.configuration.pipelineVersion
        attempt.asrProvider = plan.backendID.rawValue
        attempt.asrModel = request.configuration.asrModel
        attempt.languageCode = request.configuration.languageCode
        attempt.diarizationModel = request.configuration.diarizationFingerprint
        attempt.backendID = plan.backendID.rawValue
        attempt.backendVersion = plan.backendVersion

        let segments = Self.mergeCanonicalSegments(assembly.segments).map { segment in
            var updated = segment
            if !assembly.isComplete { updated.completeness = .incompleteTrack }
            return updated
        }

        return MeetingProcessingResult(
            speakers: assembly.speakers,
            segments: segments,
            attempt: attempt,
            // Canonical skips remain typed coverage gaps. Unlike the legacy unreadable-chunk
            // list, they must not mark readable source chunks failed and erase them from retries.
            skippedChunkIDs: [],
            coverageGaps: assembly.coverageGaps.map(Self.productCoverageGap),
            resultSidecarReference: sidecarReference,
            isComplete: assembly.isComplete
        )
    }

    private nonisolated struct CanonicalSegmentMergeKey: Hashable {
        let trackID: MeetingAudioTrackID
        let speakerID: SessionSpeakerID?
        let overlap: String
        let status: String
        let completeness: String
        let isLikelyEcho: Bool?
        let attributionState: String?
    }

    /// Backend-versioned canonical turn policy: how far apart two same-key segments on the
    /// same track may sit and still count as one continuous turn.
    nonisolated static let canonicalTurnMergeGapSeconds: TimeInterval = 3
    /// Backend-versioned canonical turn policy: the longest a merged turn may span before a
    /// new turn starts even with a matching key and no gap.
    nonisolated static let canonicalTurnMaximumDurationSeconds: TimeInterval = 30

    private nonisolated static func canonicalSegmentMergeKey(
        _ segment: MeetingTranscriptSegment
    ) -> CanonicalSegmentMergeKey {
        CanonicalSegmentMergeKey(
            trackID: segment.sourceTrackID,
            speakerID: segment.speakerID,
            overlap: segment.overlap.rawValue,
            status: segment.status.rawValue,
            completeness: segment.completeness.rawValue,
            isLikelyEcho: segment.isLikelyEcho,
            attributionState: (segment.attributionState ?? (segment.speakerID != nil ? .assigned : .unassigned)).rawValue
        )
    }

    /// Product policy: unresolved text belongs to the preceding visible speaker. Keep the
    /// original word evidence in the sidecar; only the published transcript inherits a label.
    /// An opening Unknown stays unresolved until there is a preceding speaker to inherit.
    nonisolated static func inheritPreviousSpeaker(
        _ segments: [MeetingTranscriptSegment]
    ) -> [MeetingTranscriptSegment] {
        let ordered = segments.enumerated().sorted {
            ($0.element.start, $0.element.end, $0.element.sourceTrackID.uuidString, $0.offset)
                < ($1.element.start, $1.element.end, $1.element.sourceTrackID.uuidString, $1.offset)
        }.map(\.element)
        var previousSpeakerID: SessionSpeakerID?
        return ordered.map { segment in
            guard !segment.isEcho else { return segment }
            var updated = segment
            let unresolved = segment.speakerID == nil
                || segment.attributionState == .unassigned
                || segment.attributionState == .overlappingSpeakers
                || segment.attributionState == .timingUncertain
            if unresolved {
                if let previousSpeakerID {
                    updated.speakerID = previousSpeakerID
                    updated.attributionState = .assigned
                    updated.overlap = .none
                }
            } else {
                previousSpeakerID = segment.speakerID
            }
            return updated
        }
    }

    /// Canonical evidence remains word-granular in the sidecar, but product session JSON and UI
    /// rows stay turn-granular. Folds each track chronologically and merges only a segment with
    /// the immediately preceding turn on that same track — never across an intervening
    /// different-key segment — so A → B → A stays three turns instead of collapsing the two A
    /// segments around B. A merge additionally requires an identical full attribution/state key
    /// and the named gap/duration turn bounds.
    nonisolated static func mergeCanonicalSegments(
        _ segments: [MeetingTranscriptSegment],
        maximumGapSeconds: TimeInterval = MeetingProcessingPipeline.canonicalTurnMergeGapSeconds,
        maximumDurationSeconds: TimeInterval = MeetingProcessingPipeline.canonicalTurnMaximumDurationSeconds
    ) -> [MeetingTranscriptSegment] {
        let byTrack = Dictionary(grouping: Self.inheritPreviousSpeaker(segments), by: \.sourceTrackID)
        var merged: [MeetingTranscriptSegment] = []
        for (_, members) in byTrack {
            let ordered = members.enumerated().sorted {
                ($0.element.start, $0.element.end, $0.offset) < ($1.element.start, $1.element.end, $1.offset)
            }.map(\.element)
            guard var current = ordered.first else { continue }
            var currentKey = Self.canonicalSegmentMergeKey(current)
            var memberIDs = [current.id]
            for next in ordered.dropFirst() {
                let nextKey = Self.canonicalSegmentMergeKey(next)
                let gap = next.start.seconds - current.end.seconds
                let combinedDuration = max(current.end.seconds, next.end.seconds) - current.start.seconds
                if nextKey == currentKey, gap <= maximumGapSeconds, combinedDuration <= maximumDurationSeconds {
                    current.end = Self.mediaTime(max(current.end.seconds, next.end.seconds))
                    current.text = Self.joinTranscriptText(current.text, next.text)
                    memberIDs.append(next.id)
                    current.id = Self.stableUUID(
                        "canonical-merged:" + memberIDs.map(\.uuidString).joined(separator: ":")
                    )
                } else {
                    merged.append(current)
                    current = next
                    currentKey = nextKey
                    memberIDs = [next.id]
                }
            }
            merged.append(current)
        }
        return merged.enumerated().sorted {
            ($0.element.start, $0.element.end, $0.element.sourceTrackID.uuidString, $0.offset)
                < ($1.element.start, $1.element.end, $1.element.sourceTrackID.uuidString, $1.offset)
        }.map(\.element)
    }

    private nonisolated static func joinTranscriptText(_ left: String, _ right: String) -> String {
        guard let first = right.first else { return left }
        if let scalar = first.unicodeScalars.first, CharacterSet.punctuationCharacters.contains(scalar) {
            return left + right
        }
        return left + " " + right
    }

    /// Assembly reasons become product reasons one-to-one; only the pre-existing
    /// `unprotectedMicrophone` label is reused, and only for its exact existing meaning —
    /// an excluded capture era. Nothing else is relabelled as unprotected.
    nonisolated static func productCoverageGapReason(
        for reason: MeetingAssemblyCoverageGapReason
    ) -> MeetingTranscriptCoverageGapReason {
        switch reason {
        case .inadmissibleCaptureEra: return .inadmissibleCaptureEra
        case .missingOrUnreadableAudio: return .missingOrUnreadableAudio
        case .processingFailed: return .processingFailed
        case .skipped: return .processingSkipped
        case .providerTruncated: return .providerTruncated
        case .excludedUnitIncompleteCoverage: return .excludedUnitIncompleteCoverage
        }
    }

    nonisolated static func productCoverageGap(
        _ gap: MeetingAssemblyCoverageGap
    ) -> MeetingTranscriptCoverageGap {
        MeetingTranscriptCoverageGap(
            trackID: gap.trackID,
            start: gap.start,
            end: gap.end,
            reason: self.productCoverageGapReason(for: gap.reason)
        )
    }

    /// Unchanged legacy rule: reuse the open attempt's ID when retrying, otherwise start a new one.
    private static func resolvedAttemptID(session: MeetingSession) -> UUID {
        session.processingAttempts.last(where: { $0.completedAt == nil })?.id ?? UUID()
    }

    private func processWithLease(
        session: MeetingSession,
        sessionDirectory: URL,
        attemptID: UUID,
        progress: @escaping @MainActor (MeetingProcessingStage) -> Void
    ) async throws -> MeetingProcessingResult {
        let asrService = self.asrServiceProvider()
        guard !asrService.isRunning else { throw MeetingProcessingError.dictationActive }

        let selectedModel = SettingsStore.shared.selectedSpeechModel
        guard let languagePin = MeetingProviderLanguagePin(
            languageCode: session.languageCode,
            model: selectedModel,
            settings: .shared
        ) else {
            throw MeetingProcessingError.providerDoesNotSupportLanguage(session.languageCode)
        }
        defer { languagePin.restore() }

        progress(.saving)
        try await asrService.ensureAsrReady()
        let provider = asrService.fileTranscriptionProvider
        guard provider.isReady else { throw MeetingProcessingError.modelUnavailable }

        var attempt = MeetingProcessingAttempt(
            id: attemptID,
            startedAt: Date(),
            completedAt: nil,
            stage: .identifyingSpeakers,
            pipelineVersion: Self.pipelineVersion,
            asrProvider: provider.name,
            asrModel: selectedModel.rawValue,
            languageCode: languagePin.languageCode,
            diarizationModel: SpeakerDiarizationService.isSupported
                ? MeetingProcessingCheckpoint.currentDiarizationFingerprint
                : nil,
            lastCompletedTrackID: nil,
            errorCode: nil
        )
        progress(.identifyingSpeakers)

        let origin = session.audioTracks
            .flatMap(\.chunks)
            .map(\.presentationStart.seconds)
            .min() ?? 0
        var accumulator = Accumulator()
        var remoteSpeech: [TimelineInterval] = []
        let expectedFingerprints = MeetingProcessingCheckpoint.fingerprints(for: session.audioTracks)

        let context = ProcessingContext(
            origin: origin,
            sessionDirectory: sessionDirectory,
            provider: provider,
            languageCode: languagePin.languageCode,
            asrService: asrService,
            languagePin: languagePin
        )

        var applicationSkippedChunkIDs: [MeetingAudioChunkID] = []
        var resumedFromCheckpoint = false
        if let applicationTrack = session.audioTracks.first(where: { $0.kind == .applicationAudio }) {
            if let checkpoint = Self.loadCheckpoint(sessionDirectory: sessionDirectory),
               checkpoint.isValid(
                   session: session,
                   pipelineVersion: Self.pipelineVersion,
                   provider: provider.name,
                   model: selectedModel.rawValue,
                   language: languagePin.languageCode,
                   completedTrackID: applicationTrack.id,
                   expectedFingerprints: expectedFingerprints
               )
            {
                accumulator.speakers = checkpoint.speakers
                accumulator.segments = checkpoint.segments
                accumulator.speakerIDByKey = checkpoint.speakerIDByKey
                accumulator.nextRemoteSpeaker = checkpoint.nextRemoteSpeaker
                accumulator.nextMicrophoneSpeaker = checkpoint.nextMicrophoneSpeaker
                remoteSpeech = checkpoint.remoteSpeech.map { TimelineInterval(start: $0.start, end: $0.end) }
                attempt.lastCompletedTrackID = checkpoint.completedTrackID
                resumedFromCheckpoint = true
                DebugLogger.shared.log(
                    "Meeting processing resuming from checkpoint after application track",
                    source: "MeetingProcessingPipeline"
                )
            } else {
                Self.deleteCheckpoint(sessionDirectory: sessionDirectory)
            }

            if !resumedFromCheckpoint {
                try await self.processApplicationTrack(
                    applicationTrack,
                    context: context,
                    accumulator: &accumulator,
                    remoteSpeech: &remoteSpeech,
                    skippedChunkIDs: &applicationSkippedChunkIDs
                )
                attempt.lastCompletedTrackID = applicationTrack.id
                if applicationSkippedChunkIDs.isEmpty {
                    Self.writeCheckpoint(
                        MeetingProcessingCheckpoint(
                            version: MeetingProcessingCheckpoint.currentVersion,
                            sessionID: session.id,
                            pipelineVersion: Self.pipelineVersion,
                            asrProvider: provider.name,
                            asrModel: selectedModel.rawValue,
                            languageCode: languagePin.languageCode,
                            diarizationFingerprint: MeetingProcessingCheckpoint.currentDiarizationFingerprint,
                            completedTrackID: applicationTrack.id,
                            trackFingerprints: expectedFingerprints,
                            speakers: accumulator.speakers,
                            segments: accumulator.segments,
                            remoteSpeech: remoteSpeech.map { MeetingProcessingCheckpoint.SpeechInterval(start: $0.start, end: $0.end) },
                            speakerIDByKey: accumulator.speakerIDByKey,
                            nextRemoteSpeaker: accumulator.nextRemoteSpeaker,
                            nextMicrophoneSpeaker: accumulator.nextMicrophoneSpeaker
                        ),
                        sessionDirectory: sessionDirectory
                    )
                }
            }
        }

        progress(.transcribing)
        var microphoneSkippedChunkIDs: [MeetingAudioChunkID] = []
        var coverageGaps: [MeetingTranscriptCoverageGap] = []
        if let microphoneTrack = session.audioTracks.first(where: { $0.kind == .microphone }) {
            if session.mode == .onlineCall {
                coverageGaps = Self.microphoneCoverageGaps(
                    track: microphoneTrack,
                    origin: context.origin
                )
            }
            try await self.processMicrophoneTrack(
                microphoneTrack,
                session: session,
                context: context,
                remoteSpeech: remoteSpeech,
                accumulator: &accumulator,
                skippedChunkIDs: &microphoneSkippedChunkIDs
            )
            attempt.lastCompletedTrackID = microphoneTrack.id
        }

        let skippedChunkIDs = applicationSkippedChunkIDs + microphoneSkippedChunkIDs
        let totalFinalizedChunkCount = session.audioTracks.reduce(0) {
            $0 + $1.chunks.filter { $0.finalizationState == .finalized }.count
        }
        guard skippedChunkIDs.count < totalFinalizedChunkCount else {
            throw MeetingProcessingError.noRecoverableAudio
        }

        progress(.finalizing)
        accumulator.segments.sort {
            if $0.start == $1.start { return $0.sourceTrackID.uuidString < $1.sourceTrackID.uuidString }
            return $0.start < $1.start
        }
        guard !accumulator.segments.isEmpty else { throw MeetingProcessingError.noSpeech }
        attempt.stage = .completed
        attempt.completedAt = Date()
        progress(.completed)
        return MeetingProcessingResult(
            speakers: accumulator.speakers,
            segments: accumulator.segments,
            attempt: attempt,
            skippedChunkIDs: skippedChunkIDs,
            coverageGaps: coverageGaps
        )
    }

    private static let checkpointEncoder: JSONEncoder = {
        let encoder = JSONEncoder()
        encoder.dateEncodingStrategy = .iso8601
        return encoder
    }()

    private static let checkpointDecoder: JSONDecoder = {
        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .iso8601
        return decoder
    }()

    private static func checkpointURL(sessionDirectory: URL) -> URL {
        sessionDirectory.appendingPathComponent("checkpoint.json", isDirectory: false)
    }

    private static func loadCheckpoint(sessionDirectory: URL) -> MeetingProcessingCheckpoint? {
        guard let data = try? Data(contentsOf: checkpointURL(sessionDirectory: sessionDirectory)) else { return nil }
        return try? Self.checkpointDecoder.decode(MeetingProcessingCheckpoint.self, from: data)
    }

    private static func writeCheckpoint(_ checkpoint: MeetingProcessingCheckpoint, sessionDirectory: URL) {
        let url = Self.checkpointURL(sessionDirectory: sessionDirectory)
        do {
            let data = try Self.checkpointEncoder.encode(checkpoint)
            try data.write(to: url, options: .atomic)
            try FileManager.default.setAttributes(
                [.posixPermissions: NSNumber(value: Int16(0o600))],
                ofItemAtPath: url.path
            )
        } catch {
            DebugLogger.shared.warning("Meeting checkpoint write failed: \(error)", source: "MeetingProcessingPipeline")
        }
    }

    private static func deleteCheckpoint(sessionDirectory: URL) {
        try? FileManager.default.removeItem(at: self.checkpointURL(sessionDirectory: sessionDirectory))
    }

    private func processApplicationTrack(
        _ track: MeetingAudioTrack,
        context: ProcessingContext,
        accumulator: inout Accumulator,
        remoteSpeech: inout [TimelineInterval],
        skippedChunkIDs: inout [MeetingAudioChunkID]
    ) async throws {
        let diarizer = SpeakerDiarizationService()
        var pendingTurns: [PendingDiarizedTurn] = []
        for chunk in track.chunks where chunk.finalizationState == .finalized {
            // Snapshot so a mid-chunk partial mutation (e.g. some turns transcribed before an
            // unreadable read) never leaks into the accumulated result for a skipped chunk.
            let accumulatorSnapshot = accumulator
            let remoteSpeechSnapshot = remoteSpeech
            let pendingTurnsSnapshot = pendingTurns
            do {
                try await self.processApplicationChunk(
                    chunk,
                    track: track,
                    diarizer: diarizer,
                    context: context,
                    accumulator: &accumulator,
                    remoteSpeech: &remoteSpeech,
                    pendingTurns: &pendingTurns
                )
            } catch {
                if error is CancellationError { throw error }
                guard case MeetingProcessingError.audioUnreadable = error else { throw error }
                accumulator = accumulatorSnapshot
                remoteSpeech = remoteSpeechSnapshot
                pendingTurns = pendingTurnsSnapshot
                skippedChunkIDs.append(chunk.id)
            }
        }
        self.finishApplicationTrack(track, pendingTurns: pendingTurns, accumulator: &accumulator)
    }

    private func finishApplicationTrack(
        _ track: MeetingAudioTrack,
        pendingTurns: [PendingDiarizedTurn],
        accumulator: inout Accumulator
    ) {
        guard !pendingTurns.isEmpty else { return }
        var observationsByKey: [String: MeetingGlobalSpeakerStitcher.Observation] = [:]
        for pending in pendingTurns {
            observationsByKey[pending.observation.key] = pending.observation
        }
        let result = MeetingGlobalSpeakerStitcher().stitch(observationsByKey.values.sorted { $0.key < $1.key })
        accumulator.applyGlobalStitch(result, trackKind: .applicationAudio)

        let orderedTurns = pendingTurns.sorted {
            if $0.start == $1.start { return $0.observation.key < $1.observation.key }
            return $0.start < $1.start
        }
        var emittedSpeakerIDs = Set<SessionSpeakerID>()
        for pending in orderedTurns {
            guard let speakerID = result.speakerIDByObservationKey[pending.observation.key] else {
                DebugLogger.shared.warning(
                    "Meeting speaker stitch omitted application observation \(pending.observation.key); preserving text as unattributed",
                    source: "MeetingProcessingPipeline"
                )
                let fallbackSpeakerID = accumulator.speaker(
                    key: "meeting-audio",
                    displayName: "Meeting Audio",
                    trackKind: .applicationAudio,
                    isLocalUser: false,
                    clusterID: nil
                )
                accumulator.segments.append(Self.segment(
                    key: "remote:\(pending.chunkID.uuidString):\(pending.index)",
                    trackID: track.id,
                    speakerID: fallbackSpeakerID,
                    start: pending.start,
                    end: pending.end,
                    text: pending.text,
                    overlap: .none
                ))
                continue
            }
            if emittedSpeakerIDs.insert(speakerID).inserted {
                let firstLabel = orderedTurns.first {
                    result.speakerIDByObservationKey[$0.observation.key] == speakerID
                }?.observation.localLabel
                accumulator.addResolvedSpeaker(
                    id: speakerID,
                    key: "remote-cluster:\(speakerID.uuidString)",
                    displayName: "Speaker \(accumulator.nextRemoteSpeaker)",
                    clusterID: firstLabel,
                    trackKind: .applicationAudio,
                    isLocalUser: false
                )
                accumulator.nextRemoteSpeaker += 1
            }
            accumulator.segments.append(Self.segment(
                key: "remote:\(pending.chunkID.uuidString):\(pending.index)",
                trackID: track.id,
                speakerID: speakerID,
                start: pending.start,
                end: pending.end,
                text: pending.text,
                overlap: .none
            ))
        }
    }

    private func processApplicationChunk(
        _ chunk: MeetingAudioChunk,
        track: MeetingAudioTrack,
        diarizer: SpeakerDiarizationService,
        context: ProcessingContext,
        accumulator: inout Accumulator,
        remoteSpeech: inout [TimelineInterval],
        pendingTurns: inout [PendingDiarizedTurn]
    ) async throws {
        let url = chunk.fileURL(relativeTo: context.sessionDirectory)
        let chunkOffset = chunk.presentationStart.seconds - context.origin
        // Preflight readability once, provider-independent, so a garbage file is skipped
        // uniformly instead of only surfacing via a post-transcription duration read.
        let chunkDuration = try await Task.detached(priority: .userInitiated) {
            try Self.audioDuration(url)
        }.value
        var diarizedSpans: [(start: TimeInterval, end: TimeInterval)] = []
        if SpeakerDiarizationService.isSupported {
            do {
                let diarization = try await diarizer.diarizeWithProfiles(
                    fileURL: url,
                    maxGapSeconds: Self.turnMergeGapSeconds(supportsWordTimings: context.provider.supportsWordTimings),
                    maxTurnSeconds: Self.meetingTurnMaxSeconds
                )
                let turns = diarization.turns
                diarizedSpans = turns.map { (start: $0.startSeconds, end: $0.endSeconds) }
                if !turns.isEmpty {
                    let allTurns = try await self.transcribeTurns(turns, chunkID: chunk.id, trackKind: .applicationAudio, fileURL: url, context: context)
                    guard let transcribedTurns = MeetingTurnSelection.keepingNonEmpty(allTurns) else {
                        throw LabeledPassError.emptyTurn
                    }
                    if transcribedTurns.count < allTurns.count {
                        DebugLogger.shared.log(
                            "Meeting remote transcription chunk \(chunk.id): skipped \(allTurns.count - transcribedTurns.count) of \(allTurns.count) silent turns",
                            source: "MeetingProcessingPipeline"
                        )
                    }
                    // Filtered turns only: a silent turn must not mark a mic turn overlapsRemote.
                    remoteSpeech.append(contentsOf: transcribedTurns.map { _, turn, _ in
                        TimelineInterval(
                            start: chunkOffset + turn.startSeconds,
                            end: chunkOffset + turn.endSeconds
                        )
                    })
                    let observationsByLabel: [String: MeetingGlobalSpeakerStitcher.Observation] = Dictionary(
                        uniqueKeysWithValues: Set(transcribedTurns.map { $0.turn.speakerLabel }).sorted().map { label in
                            let profile = diarization.profilesByLabel[label]
                            return (label, MeetingGlobalSpeakerStitcher.Observation(
                                key: "application:\(chunk.id.uuidString):\(label)",
                                chunkKey: chunk.id.uuidString,
                                trackKind: .applicationAudio,
                                localLabel: label,
                                embedding: profile?.embedding ?? [],
                                quality: profile?.averageQuality ?? 0,
                                effectiveSpeechDuration: transcribedTurns
                                    .filter { $0.turn.speakerLabel == label }
                                    .reduce(0) { $0 + max(0, $1.turn.durationSeconds) }
                            ))
                        }
                    )
                    for (index, turn, text) in transcribedTurns {
                        let absoluteStart = chunkOffset + turn.startSeconds
                        let absoluteEnd = chunkOffset + turn.endSeconds
                        guard let observation = observationsByLabel[turn.speakerLabel] else { continue }
                        pendingTurns.append(PendingDiarizedTurn(
                            observation: observation,
                            trackID: track.id,
                            chunkID: chunk.id,
                            index: index,
                            start: absoluteStart,
                            end: absoluteEnd,
                            text: text
                        ))
                    }
                    return
                }
            } catch {
                if error is CancellationError { throw error }
                if case MeetingProcessingError.audioUnreadable = error { throw error }
                let reason = Self.isEmptyTurnFallback(error) ? "every turn transcribed empty" : "diarization failed"
                DebugLogger.shared.warning(
                    "Meeting remote chunk \(chunk.id) fell back to an unlabeled transcript (\(reason)): \(error)",
                    source: "MeetingProcessingPipeline"
                )
            }
        }
        if let fallback = try await self.transcribeWholeChunk(
            url,
            provider: context.provider,
            languageCode: context.languageCode,
            asrService: context.asrService,
            languagePin: context.languagePin
        ) {
            let key = "meeting-audio"
            let speakerID = accumulator.speaker(
                key: key,
                displayName: "Meeting audio",
                trackKind: .applicationAudio,
                isLocalUser: false,
                clusterID: nil
            )
            remoteSpeech.append(contentsOf: Self.remoteFallbackIntervals(
                diarizedTurns: diarizedSpans,
                chunkOffset: chunkOffset,
                chunkDuration: chunkDuration
            ).map { TimelineInterval(start: $0.start, end: $0.end) })
            accumulator.segments.append(Self.segment(
                key: "remote-fallback:\(chunk.id.uuidString)",
                trackID: track.id,
                speakerID: speakerID,
                start: chunkOffset,
                end: chunkOffset + chunkDuration,
                text: fallback,
                overlap: .none
            ))
        }
    }

    private func processMicrophoneTrack(
        _ track: MeetingAudioTrack,
        session: MeetingSession,
        context: ProcessingContext,
        remoteSpeech: [TimelineInterval],
        accumulator: inout Accumulator,
        skippedChunkIDs: inout [MeetingAudioChunkID]
    ) async throws {
        let diarizer = SpeakerDiarizationService()
        let applicationTrack = session.audioTracks.first(where: { $0.kind == .applicationAudio })
        var epochState = EchoDelayEpochState(
            boundaries: Self.epochBoundaries(
                micChunks: track.chunks,
                appChunks: applicationTrack?.chunks ?? [],
                origin: context.origin
            )
        )
        var stagedTurns: [StagedMicrophoneTurn] = []
        var pendingTurns: [PendingDiarizedTurn] = []
        var echoMonitor = EchoMonitorAccumulator()
        let eras = Self.microphoneEras(for: track, origin: context.origin)
        // Era 0 has no writer-boundary anchor, so de-drift anchors it at the track's own first PTS.
        let era0AnchorRelative = (track.chunks.map(\.presentationStart.seconds).min() ?? context.origin) - context.origin
        for chunk in track.chunks where chunk.finalizationState == .finalized {
            let accumulatorSnapshot = accumulator
            let stagedTurnsSnapshot = stagedTurns
            let pendingTurnsSnapshot = pendingTurns
            let epochStateSnapshot = epochState
            let echoMonitorSnapshot = echoMonitor
            do {
                try await self.processMicrophoneChunk(
                    chunk,
                    track: track,
                    requiresEchoProtection: session.mode == .onlineCall,
                    eras: eras,
                    era0AnchorRelative: era0AnchorRelative,
                    diarizer: diarizer,
                    context: context,
                    remoteSpeech: remoteSpeech,
                    applicationTrack: applicationTrack,
                    epochState: &epochState,
                    echoMonitor: &echoMonitor,
                    accumulator: &accumulator,
                    stagedTurns: &stagedTurns,
                    pendingTurns: &pendingTurns
                )
            } catch {
                if error is CancellationError { throw error }
                guard case MeetingProcessingError.audioUnreadable = error else { throw error }
                accumulator = accumulatorSnapshot
                stagedTurns = stagedTurnsSnapshot
                pendingTurns = pendingTurnsSnapshot
                epochState = epochStateSnapshot
                echoMonitor = echoMonitorSnapshot
                skippedChunkIDs.append(chunk.id)
            }
        }

        let admittedTurns = session.mode == .onlineCall
            ? stagedTurns.filter {
                Self.microphoneIntervalIsAdmitted(
                    start: $0.rawStart ?? $0.start,
                    end: $0.rawEnd ?? $0.end,
                    eras: eras
                )
            }
            : stagedTurns
        if admittedTurns.count != stagedTurns.count {
            DebugLogger.shared.warning(
                "Meeting microphone admission excluded \(stagedTurns.count - admittedTurns.count) turn(s) intersecting unprotected capture eras.",
                source: "MeetingProcessingPipeline"
            )
        }
        stagedTurns = admittedTurns

        // Echo evidence remains the only semantic filter before prototype construction. Relative
        // loudness is not ownership: a quieter person on the microphone side is still legitimate.
        let profileEligibleTurns = stagedTurns
        let preclassified = Self.classifyMicrophoneTurns(
            profileEligibleTurns,
            eras: eras,
            applicationTrackID: applicationTrack?.id,
            segments: accumulator.segments,
            fallbackSpeakerID: accumulator.speakerIDByKey["meeting-audio"]
        )
        stagedTurns = preclassified.turns
        let trustedObservationKeys = Self.trustedMicrophoneObservationKeys(from: stagedTurns)
        var observationsByKey: [String: MeetingGlobalSpeakerStitcher.Observation] = [:]
        for pending in pendingTurns where trustedObservationKeys.contains(pending.observation.key) {
            observationsByKey[pending.observation.key] = pending.observation
        }
        let stitchResult = MeetingGlobalSpeakerStitcher().stitch(observationsByKey.values.sorted { $0.key < $1.key })
        accumulator.applyGlobalStitch(stitchResult, trackKind: .microphone)
        for index in stagedTurns.indices {
            if let observationKey = stagedTurns[index].diarizationObservationKey,
               let speakerID = stitchResult.speakerIDByObservationKey[observationKey]
            {
                stagedTurns[index].clusterID = speakerID
            } else if let observationKey = stagedTurns[index].diarizationObservationKey {
                DebugLogger.shared.warning(
                    "Meeting speaker stitch omitted microphone observation \(observationKey); keeping it outside trusted prototypes",
                    source: "MeetingProcessingPipeline"
                )
            }
        }

        self.finishMicrophoneTrack(
            track,
            session: session,
            origin: context.origin,
            stagedTurns: stagedTurns,
            echoMonitor: echoMonitor,
            applicationTrackHadSpeech: !remoteSpeech.isEmpty,
            accumulator: &accumulator
        )
    }

    // Keep the existing capture/processing contract explicit during integration.
    // swiftlint:disable:next function_parameter_count
    private func processMicrophoneChunk(
        _ chunk: MeetingAudioChunk,
        track: MeetingAudioTrack,
        requiresEchoProtection: Bool,
        eras: [MeetingCaptureEra],
        era0AnchorRelative: TimeInterval,
        diarizer: SpeakerDiarizationService,
        context: ProcessingContext,
        remoteSpeech: [TimelineInterval],
        applicationTrack: MeetingAudioTrack?,
        epochState: inout EchoDelayEpochState,
        echoMonitor: inout EchoMonitorAccumulator,
        accumulator: inout Accumulator,
        stagedTurns: inout [StagedMicrophoneTurn],
        pendingTurns: inout [PendingDiarizedTurn]
    ) async throws {
        let url = chunk.fileURL(relativeTo: context.sessionDirectory)
        let chunkOffset = chunk.presentationStart.seconds - context.origin
        let chunkDuration = try await Task.detached(priority: .userInitiated) {
            try Self.audioDuration(url)
        }.value
        epochState.advance(toChunkEnd: chunkOffset + chunkDuration)
        if SpeakerDiarizationService.isSupported {
            do {
                let diarization = try await diarizer.diarizeWithProfiles(
                    fileURL: url,
                    maxGapSeconds: Self.turnMergeGapSeconds(supportsWordTimings: context.provider.supportsWordTimings),
                    maxTurnSeconds: Self.meetingTurnMaxSeconds
                )
                let turns = diarization.turns
                if !turns.isEmpty {
                    let allTurns = try await self.transcribeTurns(turns, chunkID: chunk.id, trackKind: .microphone, fileURL: url, context: context)
                    guard let transcribedTurns = MeetingTurnSelection.keepingNonEmpty(allTurns) else {
                        throw LabeledPassError.emptyTurn
                    }
                    if transcribedTurns.count < allTurns.count {
                        DebugLogger.shared.log(
                            "Meeting microphone transcription chunk \(chunk.id): skipped \(allTurns.count - transcribedTurns.count) of \(allTurns.count) silent turns",
                            source: "MeetingProcessingPipeline"
                        )
                    }
                    let observationsByLabel: [String: MeetingGlobalSpeakerStitcher.Observation] = Dictionary(
                        uniqueKeysWithValues: Set(transcribedTurns.map { $0.turn.speakerLabel }).sorted().map { label in
                            let profile = diarization.profilesByLabel[label]
                            return (label, MeetingGlobalSpeakerStitcher.Observation(
                                key: "microphone:\(chunk.id.uuidString):\(label)",
                                chunkKey: chunk.id.uuidString,
                                trackKind: .microphone,
                                localLabel: label,
                                embedding: profile?.embedding ?? [],
                                quality: profile?.averageQuality ?? 0,
                                effectiveSpeechDuration: transcribedTurns
                                    .filter { $0.turn.speakerLabel == label }
                                    .reduce(0) { $0 + max(0, $1.turn.durationSeconds) }
                            ))
                        }
                    )
                    for (index, turn, text) in transcribedTurns {
                        guard let observation = observationsByLabel[turn.speakerLabel] else { continue }
                        pendingTurns.append(PendingDiarizedTurn(
                            observation: observation,
                            trackID: track.id,
                            chunkID: chunk.id,
                            index: index,
                            start: 0,
                            end: 0,
                            text: text
                        ))
                    }

                    var signalVerdictByIndex: [Int: TurnEchoVerdict] = [:]
                    if let applicationTrack {
                        let turnRanges = transcribedTurns.map {
                            (index: $0.index, start: chunkOffset + $0.turn.startSeconds, end: chunkOffset + $0.turn.endSeconds)
                        }
                        let acceptedDelaysInEpoch = epochState.acceptedDelays
                        do {
                            let outcome = try await Task.detached(priority: .userInitiated) {
                                try Self.computeEchoVerdicts(
                                    micChunk: chunk,
                                    micChunkURL: url,
                                    chunkOffset: chunkOffset,
                                    chunkDuration: chunkDuration,
                                    turns: turnRanges,
                                    applicationTrack: applicationTrack,
                                    origin: context.origin,
                                    sessionDirectory: context.sessionDirectory,
                                    acceptedDelaysInEpoch: acceptedDelaysInEpoch
                                )
                            }.value
                            signalVerdictByIndex = outcome.verdicts
                            if let acceptedDelaySeconds = outcome.acceptedDelaySeconds {
                                epochState.acceptedDelays.append(acceptedDelaySeconds)
                            }
                            echoMonitor.scoredChunkCount += 1
                            echoMonitor.scoreableSeconds += outcome.scoreableSecondsByTurn.values.reduce(0, +)
                            if outcome.acceptedDelaySeconds != nil { echoMonitor.lockedChunkCount += 1 }
                            if let confidence = outcome.delayConfidence {
                                echoMonitor.bestDelayConfidence = max(echoMonitor.bestDelayConfidence, confidence)
                            }
                        } catch {
                            if error is CancellationError { throw error }
                            DebugLogger.shared.warning(
                                "Meeting echo signal scoring chunk \(chunk.id) failed; leaving turns unscored: \(error)",
                                source: "MeetingProcessingPipeline"
                            )
                        }
                    }

                    let turnLoudness = Self.turnLoudness(
                        fileURL: url,
                        turns: transcribedTurns.map { (start: $0.turn.startSeconds, end: $0.turn.endSeconds) }
                    )
                    for (offset, element) in transcribedTurns.enumerated() {
                        let (index, turn, text) = element
                        // De-drift applies ONLY here — echo verdicts below keep consuming raw chunkOffset.
                        let rawStart = chunkOffset + turn.startSeconds
                        let turnEraIndex = Self.eraIndex(containing: rawStart, eras: eras)
                        var turnEra = eras[turnEraIndex]
                        // Era 0's containment boundary is a sentinel, not a real anchor.
                        if turnEraIndex == 0 { turnEra.startSeconds = era0AnchorRelative }
                        let turnEraEnd = Self.eraEndRelative(afterIndex: turnEraIndex, eras: eras)
                        let start = MeetingMicrophoneDeDrift.correct(
                            rawStart, era: turnEra, eraEndRelative: turnEraEnd
                        )
                        let end = MeetingMicrophoneDeDrift.correct(
                            chunkOffset + turn.endSeconds, era: turnEra, eraEndRelative: turnEraEnd
                        )
                        let overlapsRemote = remoteSpeech.contains {
                            min(end, $0.end) - max(start, $0.start) > 0.15
                        }
                        let observationKey = "microphone:\(chunk.id.uuidString):\(turn.speakerLabel)"
                        stagedTurns.append(StagedMicrophoneTurn(
                            chunkID: chunk.id,
                            index: index,
                            clusterID: Self.stableUUID("pending-microphone:\(observationKey)"),
                            clusterLabel: turn.speakerLabel,
                            diarizationObservationKey: observationKey,
                            start: start,
                            end: end,
                            rawStart: rawStart,
                            rawEnd: chunkOffset + turn.endSeconds,
                            text: text,
                            overlapsRemote: overlapsRemote,
                            rms: turnLoudness.indices.contains(offset) ? turnLoudness[offset] : 0,
                            signalVerdict: signalVerdictByIndex[index] ?? .unknown
                        ))
                    }
                    return
                }
            } catch {
                if error is CancellationError { throw error }
                if case MeetingProcessingError.audioUnreadable = error { throw error }
                // Diarization worked and every turn still came back empty: the microphone holds no
                // intelligible speech here. Re-transcribing the whole chunk only coaxes the
                // recognizer into hallucinating over near-silence, and that text lands unattributed
                // and unscoreable — measured at 0.31 text containment and no signal verdict at all.
                if Self.isEmptyTurnFallback(error) {
                    DebugLogger.shared.warning(
                        "Meeting microphone chunk \(chunk.id): no intelligible speech, emitting nothing",
                        source: "MeetingProcessingPipeline"
                    )
                    return
                }
                DebugLogger.shared.warning(
                    "Meeting microphone chunk \(chunk.id) fell back to an unlabeled transcript (diarization failed): \(error)",
                    source: "MeetingProcessingPipeline"
                )
            }
        }
        if let fallback = try await self.transcribeWholeChunk(
            url,
            provider: context.provider,
            languageCode: context.languageCode,
            asrService: context.asrService,
            languagePin: context.languagePin
        ) {
            let duration = chunkDuration
            guard !requiresEchoProtection || Self.microphoneIntervalIsAdmitted(
                start: chunkOffset, end: chunkOffset + duration, eras: eras
            ) else {
                DebugLogger.shared.warning(
                    "Meeting microphone fallback transcript excluded because its chunk intersects an unprotected capture era.",
                    source: "MeetingProcessingPipeline"
                )
                return
            }
            let speakerID = accumulator.speaker(
                key: "microphone-unknown",
                displayName: "Microphone / Unknown",
                trackKind: .microphone,
                isLocalUser: false,
                clusterID: nil
            )
            accumulator.segments.append(Self.segment(
                key: "microphone-fallback:\(chunk.id.uuidString)",
                trackID: track.id,
                speakerID: speakerID,
                start: chunkOffset,
                end: chunkOffset + duration,
                text: fallback,
                overlap: .ambiguous
            ))
        }
    }

    /// The only place in the mic batch path allowed to read `track.captureMethod` directly.
    /// `captureEras[].startSeconds` is raw PTS, converted here to origin-relative; era 0 is pinned to `-infinity`.
    nonisolated static func microphoneEras(for track: MeetingAudioTrack, origin: TimeInterval) -> [MeetingCaptureEra] {
        guard let rawEras = track.captureEras, !rawEras.isEmpty else {
            let legacyMethod = track.captureMethod ?? .avCaptureSession
            return [MeetingCaptureEra(
                method: legacyMethod,
                deviceUID: nil,
                deviceName: nil,
                roleAtElection: .unknown,
                // A missing era array is a pre-v9 recording. Grandfather its previous eligibility
                // while preserving that its route protection was never positively observed.
                echoProtection: legacyMethod == .voiceProcessing ? .voiceProcessed : .legacyUnclassified,
                startSeconds: -.infinity,
                settledConfig: track.voiceProcessingConfig,
                clockDrift: track.clockDrift
            )]
        }
        return rawEras.enumerated().map { index, era in
            var converted = era
            converted.startSeconds = index == 0 ? -.infinity : era.startSeconds - origin
            return converted
        }
    }

    nonisolated static func eraIndex(containing turnStart: TimeInterval, eras: [MeetingCaptureEra]) -> Int {
        var index = 0
        for (offset, era) in eras.enumerated() where era.startSeconds <= turnStart {
            index = offset
        }
        return index
    }

    nonisolated static func eraEndRelative(afterIndex index: Int, eras: [MeetingCaptureEra]) -> TimeInterval? {
        eras.indices.contains(index + 1) ? eras[index + 1].startSeconds : nil
    }

    /// A diarized turn is indivisible at this stage. Any overlap with an unprotected era rejects
    /// the complete turn; assigning solely from its start would leak audio across a splice.
    nonisolated static func microphoneIntervalIsAdmitted(
        start: TimeInterval,
        end: TimeInterval,
        eras: [MeetingCaptureEra]
    ) -> Bool {
        guard end > start, !eras.isEmpty else { return false }
        for index in eras.indices {
            let eraStart = eras[index].startSeconds
            let eraEnd = Self.eraEndRelative(afterIndex: index, eras: eras) ?? .infinity
            guard min(end, eraEnd) > max(start, eraStart) else { continue }
            if !eras[index].echoProtection.admitsTranscript { return false }
        }
        return true
    }

    nonisolated static func microphoneCoverageGaps(
        track: MeetingAudioTrack,
        origin: TimeInterval
    ) -> [MeetingTranscriptCoverageGap] {
        guard let first = track.chunks.map(\.presentationStart.seconds).min(),
              let last = track.chunks.map(\.presentationEnd.seconds).max(),
              last > first
        else { return [] }
        let trackStart = first - origin
        let trackEnd = last - origin
        let eras = Self.microphoneEras(for: track, origin: origin)
        return eras.indices.compactMap { index in
            guard !eras[index].echoProtection.admitsTranscript else { return nil }
            let start = max(trackStart, eras[index].startSeconds)
            let end = min(trackEnd, Self.eraEndRelative(afterIndex: index, eras: eras) ?? trackEnd)
            guard end > start else { return nil }
            return MeetingTranscriptCoverageGap(
                trackID: track.id,
                start: start,
                end: end,
                reason: .unprotectedMicrophone
            )
        }
    }

    nonisolated static func classifyMicrophoneTurns(
        _ turns: [StagedMicrophoneTurn],
        eras: [MeetingCaptureEra],
        applicationTrackID: MeetingAudioTrackID?,
        segments: [MeetingTranscriptSegment],
        fallbackSpeakerID: SessionSpeakerID?
    ) -> (turns: [StagedMicrophoneTurn], widenedIndices: Set<Int>) {
        var classified = turns
        var detectorExamined = Set<Int>()
        if let applicationTrackID {
            for index in classified.indices where classified[index].overlapsRemote {
                let turn = classified[index]
                let remoteText = Self.echoCandidateText(
                    segments: segments,
                    speakerIDToExclude: fallbackSpeakerID,
                    applicationTrackID: applicationTrackID,
                    window: (turn.start, turn.end)
                )
                guard !remoteText.isEmpty else { continue }
                classified[index].echoScored = true
                classified[index].isLikelyEcho = MeetingEchoDetector.isLikelyEcho(
                    micText: turn.text,
                    remoteText: remoteText
                )
                detectorExamined.insert(index)
            }
        }
        var widenedIndices = Set<Int>()
        for index in classified.indices {
            let era = eras[Self.eraIndex(containing: classified[index].start, eras: eras)]
            guard era.method == .voiceProcessing else { continue }
            if !detectorExamined.contains(index) {
                widenedIndices.insert(index)
            }
            classified[index].echoScored = true
        }
        return (classified, widenedIndices)
    }

    struct EchoMonitorAccumulator {
        var scoreableSeconds: TimeInterval = 0
        var scoredChunkCount = 0
        var lockedChunkCount = 0
        var bestDelayConfidence: Double = 0
    }

    /// Telemetry, not mitigation — the (retained) signal veto is the mitigation.
    nonisolated static func logEchoMonitorSummary(
        turns: [StagedMicrophoneTurn],
        monitor: EchoMonitorAccumulator,
        applicationTrackHadSpeech: Bool
    ) {
        var breakdown: [TurnEchoVerdict: (count: Int, seconds: TimeInterval)] = [:]
        for turn in turns {
            var entry = breakdown[turn.signalVerdict] ?? (0, 0)
            entry.count += 1
            entry.seconds += max(0, turn.end - turn.start)
            breakdown[turn.signalVerdict] = entry
        }
        let verdictDescription = [TurnEchoVerdict.echo, .residualNotExplained, .unknown].map { verdict -> String in
            let entry = breakdown[verdict] ?? (0, 0)
            return String(format: "%@=%d/%.1fs", String(describing: verdict), entry.count, entry.seconds)
        }.joined(separator: " ")
        DebugLogger.shared.info(
            String(
                format: "Echo scorer monitor: verdicts[%@] scoreableSeconds=%.1f delayLock=%d/%d bestConfidence=%.2f",
                verdictDescription,
                monitor.scoreableSeconds,
                monitor.lockedChunkCount,
                monitor.scoredChunkCount,
                monitor.bestDelayConfidence
            ),
            source: "MeetingProcessingPipeline"
        )
        guard applicationTrackHadSpeech, monitor.scoreableSeconds <= 0.001 else { return }
        DebugLogger.shared.warning(
            "Echo scorer monitor: coverage ~0 while the application track carried speech — the scorer is blind, which is not proof the mic is clean.",
            source: "MeetingProcessingPipeline"
        )
    }

    private func finishMicrophoneTrack(
        _ track: MeetingAudioTrack,
        session: MeetingSession,
        origin: TimeInterval,
        stagedTurns allStagedTurns: [StagedMicrophoneTurn],
        echoMonitor: EchoMonitorAccumulator,
        applicationTrackHadSpeech: Bool,
        accumulator: inout Accumulator
    ) {
        let eras = Self.microphoneEras(for: track, origin: origin)
        // Personal-mic turns were already near-field filtered before profile stitching. Applying
        // the relative loudness gate again would recompute its reference from a narrower set and
        // could reject a turn that passed the original, correctly calibrated gate.
        let stagedTurns = allStagedTurns

        if session.mode == .inRoom {
            for turn in stagedTurns {
                let isNewSpeaker = !accumulator.speakers.contains { $0.id == turn.clusterID }
                if isNewSpeaker {
                    let displayName = "Room Speaker \(accumulator.nextMicrophoneSpeaker)"
                    accumulator.nextMicrophoneSpeaker += 1
                    accumulator.addResolvedSpeaker(
                        id: turn.clusterID,
                        key: "room-cluster:\(turn.clusterID.uuidString)",
                        displayName: displayName,
                        clusterID: turn.clusterLabel,
                        trackKind: .microphone,
                        isLocalUser: false
                    )
                } else {
                    accumulator.addResolvedSpeaker(
                        id: turn.clusterID,
                        key: "room-cluster:\(turn.clusterID.uuidString)",
                        displayName: "Room Speaker",
                        clusterID: turn.clusterLabel,
                        trackKind: .microphone,
                        isLocalUser: false
                    )
                }
                accumulator.segments.append(Self.segment(
                    key: "microphone:\(turn.chunkID.uuidString):\(turn.index)",
                    trackID: track.id,
                    speakerID: turn.clusterID,
                    start: turn.start,
                    end: turn.end,
                    text: turn.text,
                    overlap: .none
                ))
            }
            return
        }

        let applicationTrackID = session.audioTracks.first(where: { $0.kind == .applicationAudio })?.id
        // The 60s remote whole-chunk fallback is too coarse to score against; exclude its speaker.
        let fallbackSpeakerID = accumulator.speakerIDByKey["meeting-audio"]
        let (classifiedTurns, widenedIndices) = Self.classifyMicrophoneTurns(
            stagedTurns,
            eras: eras,
            applicationTrackID: applicationTrackID,
            segments: accumulator.segments,
            fallbackSpeakerID: fallbackSpeakerID
        )

        let prototypeSpeakerIDs = accumulator.embeddingIndexByTrack[.microphone]?.speakerIDs ?? []
        _ = widenedIndices // retained as echo-classification diagnostics; no ownership election
        Self.logEchoMonitorSummary(
            turns: classifiedTurns,
            monitor: echoMonitor,
            applicationTrackHadSpeech: applicationTrackHadSpeech
        )
        let unknownSpeakerID = accumulator.speaker(
            key: "microphone-unknown",
            displayName: "Microphone / Unknown",
            trackKind: .microphone,
            isLocalUser: false,
            clusterID: nil
        )
        // Clean non-local clusters keep their diarization identity as nameable speakers; only
        // echo-demoted turns stay in the anonymous bucket (bleed must not become a "person").
        var micSpeakerOrdinalByCluster: [SessionSpeakerID: Int] = [:]
        for turn in classifiedTurns {
            let speakerID: SessionSpeakerID
            if !turn.effectiveEcho, prototypeSpeakerIDs.contains(turn.clusterID) {
                if micSpeakerOrdinalByCluster[turn.clusterID] == nil {
                    let ordinal = micSpeakerOrdinalByCluster.count + 1
                    micSpeakerOrdinalByCluster[turn.clusterID] = ordinal
                    accumulator.addResolvedSpeaker(
                        id: turn.clusterID,
                        key: "microphone-speaker:\(turn.clusterID.uuidString)",
                        displayName: "Microphone Speaker \(ordinal)",
                        clusterID: turn.clusterLabel,
                        trackKind: .microphone,
                        isLocalUser: false
                    )
                }
                speakerID = turn.clusterID
            } else {
                speakerID = unknownSpeakerID
            }
            accumulator.segments.append(Self.segment(
                key: "microphone:\(turn.chunkID.uuidString):\(turn.index)",
                trackID: track.id,
                speakerID: speakerID,
                start: turn.start,
                end: turn.end,
                text: turn.text,
                overlap: turn.overlapsRemote ? .overlapsOtherTrack : .none,
                isLikelyEcho: turn.effectiveEcho
            ))
        }
    }

    /// Each word lands in at most one turn: max overlap wins, ties to the lower index.
    nonisolated static func assignWords(
        _ words: [ASRWordTiming],
        toTurns turns: [(index: Int, start: TimeInterval, end: TimeInterval)],
        nearestTolerance: TimeInterval = 0.5
    ) -> (byTurn: [Int: String], unassigned: Int) {
        var accumulated: [Int: [String]] = [:]
        var unassignedCount = 0

        for word in words {
            // Half-open [start, end): a boundary instant scores 0 on both sides, never doubles.
            let overlaps = turns.map { turn in
                (index: turn.index, overlap: max(0, min(word.end, turn.end) - max(word.start, turn.start)))
            }
            if let maxOverlap = overlaps.map(\.overlap).max(), maxOverlap > 0,
               let winner = overlaps.filter({ $0.overlap == maxOverlap }).min(by: { $0.index < $1.index })
            {
                accumulated[winner.index, default: []].append(word.text)
                continue
            }

            let distances = turns.map { turn -> (index: Int, distance: TimeInterval) in
                let distance: TimeInterval
                if word.end <= turn.start {
                    distance = turn.start - word.end
                } else if word.start >= turn.end {
                    distance = word.start - turn.end
                } else {
                    distance = 0
                }
                return (turn.index, distance)
            }
            if let nearest = distances.min(by: { $0.distance < $1.distance || ($0.distance == $1.distance && $0.index < $1.index) }),
               nearest.distance <= nearestTolerance
            {
                accumulated[nearest.index, default: []].append(word.text)
            } else {
                unassignedCount += 1
            }
        }

        return (accumulated.mapValues { $0.joined(separator: " ") }, unassignedCount)
    }

    /// Above this share of unplaceable words the timings are not trustworthy enough to keep.
    static let maxUnassignedWordFraction = 0.25

    /// Words outside every turn attach to the nearest turn within this window. Zero on the
    /// microphone, where bleed would otherwise be credited to the user as their own words.
    nonisolated static func wordAttachmentTolerance(for trackKind: MeetingAudioTrackKind) -> TimeInterval {
        trackKind == .microphone ? 0 : 0.5
    }

    /// The chunk-level catch classifies on these; swallowing one would mislabel the chunk.
    nonisolated static func alignmentErrorMustPropagate(_ error: Error) -> Bool {
        if error is CancellationError { return true }
        if case MeetingProcessingError.audioUnreadable = error { return true }
        return false
    }

    nonisolated static func tooManyWordsUnassigned(unassigned: Int, totalWords: Int) -> Bool {
        totalWords > 0 && Double(unassigned) > Double(totalWords) * self.maxUnassignedWordFraction
    }

    private func transcribeTurnsWordAligned(
        _ turns: [SpeakerDiarizationService.SpeakerTurn],
        chunkID: MeetingAudioChunkID,
        trackKind: MeetingAudioTrackKind,
        fileURL: URL,
        context: ProcessingContext
        // nil represents unavailable or invalid evidence, distinct from a valid empty collection.
        // swiftlint:disable:next discouraged_optional_collection
    ) async throws -> [(index: Int, turn: SpeakerDiarizationService.SpeakerTurn, text: String)]? {
        let samples = try await Task.detached(priority: .userInitiated) {
            try Self.readSamples(fileURL: fileURL, startSeconds: 0, endSeconds: nil)
        }.value
        guard samples.count >= 16_000 else { return nil }

        context.languagePin.apply()
        let outcome = try await context.asrService.transcribeMeetingSamplesWithTimings(
            samples,
            provider: context.provider
        )
        guard !outcome.words.isEmpty else { return nil }

        let assignment = Self.assignWords(
            outcome.words,
            toTurns: turns.enumerated().map { (index: $0.offset, start: $0.element.startSeconds, end: $0.element.endSeconds) },
            nearestTolerance: Self.wordAttachmentTolerance(for: trackKind)
        )
        guard !Self.tooManyWordsUnassigned(unassigned: assignment.unassigned, totalWords: outcome.words.count) else {
            DebugLogger.shared.warning(
                "Meeting word alignment chunk \(chunkID): \(assignment.unassigned)/\(outcome.words.count) words unassigned, falling back to per-turn",
                source: "MeetingProcessingPipeline"
            )
            return nil
        }
        if assignment.unassigned > 0 {
            DebugLogger.shared.warning(
                "Meeting word alignment chunk \(chunkID): dropped \(assignment.unassigned) of \(outcome.words.count) unplaceable word(s)",
                source: "MeetingProcessingPipeline"
            )
        }
        return turns.enumerated().map { index, turn in
            (index, turn, assignment.byTurn[index] ?? "")
        }
    }

    private func transcribeTurns(
        _ turns: [SpeakerDiarizationService.SpeakerTurn],
        chunkID: MeetingAudioChunkID,
        trackKind: MeetingAudioTrackKind,
        fileURL: URL,
        context: ProcessingContext
    ) async throws -> [(index: Int, turn: SpeakerDiarizationService.SpeakerTurn, text: String)] {
        if !context.provider.supportsWordTimings {
            DebugLogger.shared.log(
                "Meeting chunk \(chunkID): provider \(context.provider.name) exposes no word timings; transcribing per turn",
                source: "MeetingProcessingPipeline"
            )
        } else {
            do {
                if let aligned = try await self.transcribeTurnsWordAligned(
                    turns,
                    chunkID: chunkID,
                    trackKind: trackKind,
                    fileURL: fileURL,
                    context: context
                ) {
                    return aligned
                }
            } catch {
                if Self.alignmentErrorMustPropagate(error) { throw error }
                DebugLogger.shared.warning(
                    "Meeting word alignment chunk \(chunkID) failed; falling back to per-turn: \(error)",
                    source: "MeetingProcessingPipeline"
                )
            }
        }
        var allTurns: [(index: Int, turn: SpeakerDiarizationService.SpeakerTurn, text: String)] = []
        for (index, turn) in turns.enumerated() {
            let text = try await self.transcribeTurn(
                turn,
                fileURL: fileURL,
                provider: context.provider,
                languageCode: context.languageCode,
                asrService: context.asrService,
                languagePin: context.languagePin
            )
            allTurns.append((index, turn, text))
        }
        return allTurns
    }

    private func transcribeTurn(
        _ turn: SpeakerDiarizationService.SpeakerTurn,
        fileURL: URL,
        provider: any TranscriptionProvider,
        languageCode: String,
        asrService: ASRService,
        languagePin: MeetingProviderLanguagePin
    ) async throws -> String {
        var samples = try await Task.detached(priority: .userInitiated) {
            try Self.readSamples(
                fileURL: fileURL,
                startSeconds: turn.startSeconds,
                endSeconds: turn.endSeconds
            )
        }.value
        let minimumSamples = 17_600
        if samples.count < minimumSamples {
            samples.append(contentsOf: repeatElement(0, count: minimumSamples - samples.count))
        }
        let result = try await self.transcribeSamples(
            samples,
            provider: provider,
            languageCode: languageCode,
            asrService: asrService,
            languagePin: languagePin
        )
        return result.text.trimmingCharacters(in: .whitespacesAndNewlines)
    }

    private func transcribeWholeChunk(
        _ fileURL: URL,
        provider: any TranscriptionProvider,
        languageCode: String,
        asrService: ASRService,
        languagePin: MeetingProviderLanguagePin
    ) async throws -> String? {
        let result: ASRTranscriptionResult
        if provider.prefersNativeFileTranscription {
            languagePin.apply()
            result = try await asrService.transcribeMeetingFile(at: fileURL, provider: provider)
        } else {
            let samples = try await Task.detached(priority: .userInitiated) {
                try Self.readSamples(fileURL: fileURL, startSeconds: 0, endSeconds: nil)
            }.value
            guard samples.count >= 16_000 else { return nil }
            result = try await self.transcribeSamples(
                samples,
                provider: provider,
                languageCode: languageCode,
                asrService: asrService,
                languagePin: languagePin
            )
        }
        let text = result.text.trimmingCharacters(in: .whitespacesAndNewlines)
        return text.isEmpty ? nil : text
    }

    private func transcribeSamples(
        _ samples: [Float],
        provider: any TranscriptionProvider,
        languageCode: String,
        asrService: ASRService,
        languagePin: MeetingProviderLanguagePin
    ) async throws -> ASRTranscriptionResult {
        languagePin.apply()
        return try await asrService.transcribeMeetingSamples(
            samples,
            provider: provider,
            languageCode: languageCode
        )
    }

    /// Internal (not private) so tests can exercise unreadable-file classification directly.
    nonisolated static func readSamples(
        fileURL: URL,
        startSeconds: TimeInterval,
        endSeconds: TimeInterval?
    ) throws -> [Float] {
        let audioFile: AVAudioFile
        do {
            audioFile = try AVAudioFile(forReading: fileURL)
        } catch {
            throw MeetingProcessingError.audioUnreadable
        }
        let sampleRate = audioFile.processingFormat.sampleRate
        guard sampleRate > 0 else { throw MeetingProcessingError.audioUnreadable }
        let fileDuration = Double(audioFile.length) / sampleRate
        let start = max(0, min(startSeconds, fileDuration))
        let end = max(start, min(endSeconds ?? fileDuration, fileDuration))
        let startFrame = AVAudioFramePosition((start * sampleRate).rounded(.down))
        let frameCount = AVAudioFrameCount(((end - start) * sampleRate).rounded(.up))
        guard frameCount > 0,
              let buffer = AVAudioPCMBuffer(
                  pcmFormat: audioFile.processingFormat,
                  frameCapacity: frameCount
              )
        else { return [] }
        audioFile.framePosition = startFrame
        do {
            try audioFile.read(into: buffer, frameCount: frameCount)
        } catch {
            throw MeetingProcessingError.audioUnreadable
        }
        return try AudioBufferConverter.monoSamples(from: buffer, targetSampleRate: 16_000)
    }

    private nonisolated static func audioDuration(_ url: URL) throws -> TimeInterval {
        let file: AVAudioFile
        do {
            file = try AVAudioFile(forReading: url)
        } catch {
            throw MeetingProcessingError.audioUnreadable
        }
        guard file.processingFormat.sampleRate > 0 else { throw MeetingProcessingError.audioUnreadable }
        return Double(file.length) / file.processingFormat.sampleRate
    }

    /// Overlapping application-track text, minus the coarse whole-chunk fallback speaker.
    nonisolated static func echoCandidateText(
        segments: [MeetingTranscriptSegment],
        speakerIDToExclude: SessionSpeakerID?,
        applicationTrackID: MeetingAudioTrackID,
        window: (start: TimeInterval, end: TimeInterval)
    ) -> String {
        segments
            .filter { segment in
                segment.sourceTrackID == applicationTrackID
                    && (speakerIDToExclude == nil || segment.speakerID != speakerIDToExclude)
                    && min(window.end, segment.end.seconds) - max(window.start, segment.start.seconds) > 0.15
            }
            .map(\.text)
            .joined(separator: " ")
    }

    private static func segment(
        key: String,
        trackID: MeetingAudioTrackID,
        speakerID: SessionSpeakerID?,
        start: TimeInterval,
        end: TimeInterval,
        text: String,
        overlap: MeetingTranscriptOverlap,
        isLikelyEcho: Bool = false
    ) -> MeetingTranscriptSegment {
        MeetingTranscriptSegment(
            id: self.stableUUID("segment:\(key)"),
            start: self.mediaTime(start),
            end: self.mediaTime(max(start, end)),
            sourceTrackID: trackID,
            speakerID: speakerID,
            text: text,
            revision: 0,
            status: .final,
            overlap: overlap,
            completeness: .complete,
            isLikelyEcho: isLikelyEcho
        )
    }

    private nonisolated static func mediaTime(_ seconds: TimeInterval) -> MeetingMediaTime {
        MeetingMediaTime(value: Int64((max(0, seconds) * 1000).rounded()), timescale: 1000)
    }

    private nonisolated static func stableUUID(_ key: String) -> UUID {
        var bytes = Array(SHA256.hash(data: Data(key.utf8)).prefix(16))
        bytes[6] = (bytes[6] & 0x0f) | 0x50
        bytes[8] = (bytes[8] & 0x3f) | 0x80
        return UUID(uuid: (
            bytes[0], bytes[1], bytes[2], bytes[3],
            bytes[4], bytes[5], bytes[6], bytes[7],
            bytes[8], bytes[9], bytes[10], bytes[11],
            bytes[12], bytes[13], bytes[14], bytes[15]
        ))
    }
}

nonisolated enum MeetingProcessingError: LocalizedError {
    case unsupportedLanguage
    case noRecoverableAudio
    case dictationActive
    case modelUnavailable
    case providerDoesNotSupportLanguage(String)
    case audioUnreadable
    case noSpeech

    var errorDescription: String? {
        switch self {
        case .unsupportedLanguage:
            return "Choose a supported meeting language from Recording settings."
        case .noRecoverableAudio:
            return "No finalized meeting audio is available to transcribe."
        case .dictationActive:
            return "Finish the active dictation before transcribing this meeting."
        case .modelUnavailable:
            return "The selected speech model is not ready."
        case let .providerDoesNotSupportLanguage(languageCode):
            return "The selected speech model cannot transcribe meeting language \(languageCode)."
        case .audioUnreadable:
            return "A finalized meeting audio chunk could not be read."
        case .noSpeech:
            return "No speech was detected in the saved meeting audio."
        }
    }
}