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
feat(meetings): wire PCM-first Parakeet Nemotron backend
argus-vault06044161a28c
diff --git a/.gitignore b/.gitignoreindex 1ca829cb..1f07ccfd 100644--- a/.gitignore+++ b/.gitignore@@ -210,6 +210,9 @@ create_dmg_only.sh# Scratch directoryscratch/+# Maintained local dependency workspaces (patches are exported separately)+.local-dependencies/+assets/.swiftpm/scripts/diff --git a/Fluid.xcodeproj/project.pbxproj b/Fluid.xcodeproj/project.pbxprojindex d76e033e..8fb305b7 100644--- a/Fluid.xcodeproj/project.pbxproj+++ b/Fluid.xcodeproj/project.pbxproj@@ -34,6 +34,16 @@F1BD00000000000000000002 /* StripThinkingTagsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1BD00000000000000000001 /* StripThinkingTagsTests.swift */; };D1A600000000000000000204 /* MeetingWindowSelectorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1A600000000000000000203 /* MeetingWindowSelectorTests.swift */; };D1A600000000000000000206 /* MeetingRecoveryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1A600000000000000000205 /* MeetingRecoveryTests.swift */; };+ BE0A00000000000000000002 /* MeetingTranscriptionBackendTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE0A00000000000000000001 /* MeetingTranscriptionBackendTests.swift */; };+ C1A000000000000000000002 /* MeetingResultSidecarTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A000000000000000000001 /* MeetingResultSidecarTests.swift */; };+ C2A000000000000000000002 /* MeetingAnalysisManifestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2A000000000000000000001 /* MeetingAnalysisManifestTests.swift */; };+ C2B100000000000000000002 /* MeetingTranscriptAssemblerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2B100000000000000000001 /* MeetingTranscriptAssemblerTests.swift */; };+ C2B200000000000000000002 /* MeetingCanonicalPipelineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2B200000000000000000001 /* MeetingCanonicalPipelineTests.swift */; };+ E3A000000000000000000002 /* MeetingParakeetNemotronBackendTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3A000000000000000000001 /* MeetingParakeetNemotronBackendTests.swift */; };+ E3A000000000000000000012 /* MeetingTextOverlapEchoVerdictProviderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3A000000000000000000011 /* MeetingTextOverlapEchoVerdictProviderTests.swift */; };+ E3A000000000000000000022 /* MeetingEpochAudioMaterializerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3A000000000000000000021 /* MeetingEpochAudioMaterializerTests.swift */; };+ E3A000000000000000000032 /* MeetingNemotronModelLocatorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3A000000000000000000031 /* MeetingNemotronModelLocatorTests.swift */; };+ E3A000000000000000000042 /* MeetingNemotronRealModelSmokeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3A000000000000000000041 /* MeetingNemotronRealModelSmokeTests.swift */; };AD7A00000000000000000002 /* MeetingAutoDetectorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD7A00000000000000000001 /* MeetingAutoDetectorTests.swift */; };A7D000000000000000000002 /* AudioTopologyDiagnosticsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7D000000000000000000001 /* AudioTopologyDiagnosticsTests.swift */; };7E57C8BE6F444F6A9AC9FCB0 /* MeetingEchoSignalScorerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4AD7433B35340CEB85EA268 /* MeetingEchoSignalScorerTests.swift */; };@@ -70,6 +80,11 @@CD120000000000000000000002 /* MeetingReferenceAttributionContractsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD120000000000000000000001 /* MeetingReferenceAttributionContractsTests.swift */; };E5EC000000000000000000B2 /* MeetingVoiceProcessingProbeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5EC000000000000000000B1 /* MeetingVoiceProcessingProbeTests.swift */; };E5EC000000000000000000C2 /* MeetingSCKPairedDiagnosticsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5EC000000000000000000C1 /* MeetingSCKPairedDiagnosticsTests.swift */; };+ F1A000000000000000000002 /* MeetingAudioChunkSinkTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1A000000000000000000001 /* MeetingAudioChunkSinkTests.swift */; };+ F1A000000000000000000004 /* MeetingAudioAssetCompatibilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1A000000000000000000003 /* MeetingAudioAssetCompatibilityTests.swift */; };+ F1A000000000000000000006 /* MeetingAudioChunkLedgerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1A000000000000000000005 /* MeetingAudioChunkLedgerTests.swift */; };+ F1A000000000000000000008 /* MeetingAudioChunkLedgerRecoveryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1A000000000000000000007 /* MeetingAudioChunkLedgerRecoveryTests.swift */; };+ F1A00000000000000000000A /* MeetingPCMStoragePolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1A000000000000000000009 /* MeetingPCMStoragePolicyTests.swift */; };E5EC000000000000000000D2 /* MeetingSCKPairedHardwareTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5EC000000000000000000D1 /* MeetingSCKPairedHardwareTests.swift */; };803000000000000000000003 /* MediaRemoteAdapter in Frameworks */ = {isa = PBXBuildFile; productRef = 803000000000000000000004 /* MediaRemoteAdapter */; };B51800000000000000000002 /* SpokenSendTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B51800000000000000000001 /* SpokenSendTests.swift */; };@@ -146,6 +161,16 @@F1BD00000000000000000001 /* StripThinkingTagsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StripThinkingTagsTests.swift; sourceTree = "<group>"; };D1A600000000000000000203 /* MeetingWindowSelectorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingWindowSelectorTests.swift; sourceTree = "<group>"; };D1A600000000000000000205 /* MeetingRecoveryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingRecoveryTests.swift; sourceTree = "<group>"; };+ BE0A00000000000000000001 /* MeetingTranscriptionBackendTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingTranscriptionBackendTests.swift; sourceTree = "<group>"; };+ C1A000000000000000000001 /* MeetingResultSidecarTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingResultSidecarTests.swift; sourceTree = "<group>"; };+ C2A000000000000000000001 /* MeetingAnalysisManifestTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingAnalysisManifestTests.swift; sourceTree = "<group>"; };+ C2B100000000000000000001 /* MeetingTranscriptAssemblerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingTranscriptAssemblerTests.swift; sourceTree = "<group>"; };+ C2B200000000000000000001 /* MeetingCanonicalPipelineTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingCanonicalPipelineTests.swift; sourceTree = "<group>"; };+ E3A000000000000000000001 /* MeetingParakeetNemotronBackendTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingParakeetNemotronBackendTests.swift; sourceTree = "<group>"; };+ E3A000000000000000000011 /* MeetingTextOverlapEchoVerdictProviderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingTextOverlapEchoVerdictProviderTests.swift; sourceTree = "<group>"; };+ E3A000000000000000000021 /* MeetingEpochAudioMaterializerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingEpochAudioMaterializerTests.swift; sourceTree = "<group>"; };+ E3A000000000000000000031 /* MeetingNemotronModelLocatorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingNemotronModelLocatorTests.swift; sourceTree = "<group>"; };+ E3A000000000000000000041 /* MeetingNemotronRealModelSmokeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingNemotronRealModelSmokeTests.swift; sourceTree = "<group>"; };AD7A00000000000000000001 /* MeetingAutoDetectorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingAutoDetectorTests.swift; sourceTree = "<group>"; };A7D000000000000000000001 /* AudioTopologyDiagnosticsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioTopologyDiagnosticsTests.swift; sourceTree = "<group>"; };B4AD7433B35340CEB85EA268 /* MeetingEchoSignalScorerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingEchoSignalScorerTests.swift; sourceTree = "<group>"; };@@ -194,6 +219,11 @@CD120000000000000000000001 /* MeetingReferenceAttributionContractsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingReferenceAttributionContractsTests.swift; sourceTree = "<group>"; };E5EC000000000000000000B1 /* MeetingVoiceProcessingProbeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingVoiceProcessingProbeTests.swift; sourceTree = "<group>"; };E5EC000000000000000000C1 /* MeetingSCKPairedDiagnosticsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingSCKPairedDiagnosticsTests.swift; sourceTree = "<group>"; };+ F1A000000000000000000001 /* MeetingAudioChunkSinkTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingAudioChunkSinkTests.swift; sourceTree = "<group>"; };+ F1A000000000000000000003 /* MeetingAudioAssetCompatibilityTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingAudioAssetCompatibilityTests.swift; sourceTree = "<group>"; };+ F1A000000000000000000005 /* MeetingAudioChunkLedgerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingAudioChunkLedgerTests.swift; sourceTree = "<group>"; };+ F1A000000000000000000007 /* MeetingAudioChunkLedgerRecoveryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingAudioChunkLedgerRecoveryTests.swift; sourceTree = "<group>"; };+ F1A000000000000000000009 /* MeetingPCMStoragePolicyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingPCMStoragePolicyTests.swift; sourceTree = "<group>"; };E5EC000000000000000000D1 /* MeetingSCKPairedHardwareTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingSCKPairedHardwareTests.swift; sourceTree = "<group>"; };7CDB0A2A2F3C4D5600FB7CAD /* AudioFixtureLoader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioFixtureLoader.swift; sourceTree = "<group>"; };7CDB0A2B2F3C4D5600FB7CAD /* dictation_fixture.wav */ = {isa = PBXFileReference; lastKnownFileType = audio.wav; path = dictation_fixture.wav; sourceTree = "<group>"; };@@ -332,6 +362,16 @@F1BD00000000000000000001 /* StripThinkingTagsTests.swift */,D1A600000000000000000203 /* MeetingWindowSelectorTests.swift */,D1A600000000000000000205 /* MeetingRecoveryTests.swift */,+ BE0A00000000000000000001 /* MeetingTranscriptionBackendTests.swift */,+ C1A000000000000000000001 /* MeetingResultSidecarTests.swift */,+ C2A000000000000000000001 /* MeetingAnalysisManifestTests.swift */,+ C2B100000000000000000001 /* MeetingTranscriptAssemblerTests.swift */,+ C2B200000000000000000001 /* MeetingCanonicalPipelineTests.swift */,+ E3A000000000000000000001 /* MeetingParakeetNemotronBackendTests.swift */,+ E3A000000000000000000011 /* MeetingTextOverlapEchoVerdictProviderTests.swift */,+ E3A000000000000000000021 /* MeetingEpochAudioMaterializerTests.swift */,+ E3A000000000000000000031 /* MeetingNemotronModelLocatorTests.swift */,+ E3A000000000000000000041 /* MeetingNemotronRealModelSmokeTests.swift */,AD7A00000000000000000001 /* MeetingAutoDetectorTests.swift */,A7D000000000000000000001 /* AudioTopologyDiagnosticsTests.swift */,B4AD7433B35340CEB85EA268 /* MeetingEchoSignalScorerTests.swift */,@@ -373,6 +413,11 @@CD120000000000000000000001 /* MeetingReferenceAttributionContractsTests.swift */,E5EC000000000000000000B1 /* MeetingVoiceProcessingProbeTests.swift */,E5EC000000000000000000C1 /* MeetingSCKPairedDiagnosticsTests.swift */,+ F1A000000000000000000001 /* MeetingAudioChunkSinkTests.swift */,+ F1A000000000000000000003 /* MeetingAudioAssetCompatibilityTests.swift */,+ F1A000000000000000000005 /* MeetingAudioChunkLedgerTests.swift */,+ F1A000000000000000000007 /* MeetingAudioChunkLedgerRecoveryTests.swift */,+ F1A000000000000000000009 /* MeetingPCMStoragePolicyTests.swift */,E5EC000000000000000000D1 /* MeetingSCKPairedHardwareTests.swift */,);path = FluidDictationIntegrationTests;@@ -564,7 +609,7 @@minimizedProjectReferenceProxies = 1;packageReferences = (AEC300000000000000000001 /* XCLocalSwiftPackageReference "WebRTCAudioProcessing" */,- 7C078DA32E3B386A00FB7CAC /* XCRemoteSwiftPackageReference "FluidAudio" */,+ 7C078DA32E3B386A00FB7CAC /* XCLocalSwiftPackageReference "FluidAudio" */,7CE006BB2E80EBE600DDCCD6 /* XCRemoteSwiftPackageReference "AppUpdater" */,7C3697872ED70F9C005874CE /* XCRemoteSwiftPackageReference "DynamicNotchKit" */,7C9A71002F58B00000FB7CAF /* XCRemoteSwiftPackageReference "transcribe-cpp-swift" */,@@ -664,6 +709,16 @@F1BD00000000000000000002 /* StripThinkingTagsTests.swift in Sources */,D1A600000000000000000204 /* MeetingWindowSelectorTests.swift in Sources */,D1A600000000000000000206 /* MeetingRecoveryTests.swift in Sources */,+ BE0A00000000000000000002 /* MeetingTranscriptionBackendTests.swift in Sources */,+ C1A000000000000000000002 /* MeetingResultSidecarTests.swift in Sources */,+ C2A000000000000000000002 /* MeetingAnalysisManifestTests.swift in Sources */,+ C2B100000000000000000002 /* MeetingTranscriptAssemblerTests.swift in Sources */,+ C2B200000000000000000002 /* MeetingCanonicalPipelineTests.swift in Sources */,+ E3A000000000000000000002 /* MeetingParakeetNemotronBackendTests.swift in Sources */,+ E3A000000000000000000012 /* MeetingTextOverlapEchoVerdictProviderTests.swift in Sources */,+ E3A000000000000000000022 /* MeetingEpochAudioMaterializerTests.swift in Sources */,+ E3A000000000000000000032 /* MeetingNemotronModelLocatorTests.swift in Sources */,+ E3A000000000000000000042 /* MeetingNemotronRealModelSmokeTests.swift in Sources */,AD7A00000000000000000002 /* MeetingAutoDetectorTests.swift in Sources */,A7D000000000000000000002 /* AudioTopologyDiagnosticsTests.swift in Sources */,7E57C8BE6F444F6A9AC9FCB0 /* MeetingEchoSignalScorerTests.swift in Sources */,@@ -704,6 +759,11 @@CD120000000000000000000002 /* MeetingReferenceAttributionContractsTests.swift in Sources */,E5EC000000000000000000B2 /* MeetingVoiceProcessingProbeTests.swift in Sources */,E5EC000000000000000000C2 /* MeetingSCKPairedDiagnosticsTests.swift in Sources */,+ F1A000000000000000000002 /* MeetingAudioChunkSinkTests.swift in Sources */,+ F1A000000000000000000004 /* MeetingAudioAssetCompatibilityTests.swift in Sources */,+ F1A000000000000000000006 /* MeetingAudioChunkLedgerTests.swift in Sources */,+ F1A000000000000000000008 /* MeetingAudioChunkLedgerRecoveryTests.swift in Sources */,+ F1A00000000000000000000A /* MeetingPCMStoragePolicyTests.swift in Sources */,E5EC000000000000000000D2 /* MeetingSCKPairedHardwareTests.swift in Sources */,);runOnlyForDeploymentPostprocessing = 0;@@ -1208,6 +1268,10 @@/* End XCConfigurationList section *//* Begin XCLocalSwiftPackageReference section */+ 7C078DA32E3B386A00FB7CAC /* XCLocalSwiftPackageReference "FluidAudio" */ = {+ isa = XCLocalSwiftPackageReference;+ relativePath = ".local-dependencies/FluidAudio";+ };AEC300000000000000000001 /* XCLocalSwiftPackageReference "WebRTCAudioProcessing" */ = {isa = XCLocalSwiftPackageReference;relativePath = Vendor/WebRTCAudioProcessing;@@ -1215,14 +1279,6 @@/* End XCLocalSwiftPackageReference section *//* Begin XCRemoteSwiftPackageReference section */- 7C078DA32E3B386A00FB7CAC /* XCRemoteSwiftPackageReference "FluidAudio" */ = {- isa = XCRemoteSwiftPackageReference;- repositoryURL = "https://github.com/altic-dev/FluidAudio.git";- requirement = {- kind = revision;- revision = 3fd63887eef1dc25edea8263ce4b44aa854d898b;- };- };7C3697872ED70F9C005874CE /* XCRemoteSwiftPackageReference "DynamicNotchKit" */ = {isa = XCRemoteSwiftPackageReference;repositoryURL = "https://github.com/altic-dev/DynamicNotchKit.git";@@ -1273,7 +1329,7 @@};7C078DA42E3B386A00FB7CAC /* FluidAudio */ = {isa = XCSwiftPackageProductDependency;- package = 7C078DA32E3B386A00FB7CAC /* XCRemoteSwiftPackageReference "FluidAudio" */;+ package = 7C078DA32E3B386A00FB7CAC /* XCLocalSwiftPackageReference "FluidAudio" */;productName = FluidAudio;};7C3697882ED70F9C005874CE /* DynamicNotchKit */ = {diff --git a/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolvedindex 5a9aa57b..06206eb3 100644--- a/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved+++ b/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved@@ -1,5 +1,5 @@{- "originHash" : "f7ad30d968aec3ed22705eb42b7b2c993f57c298942da95e0e9f00806ac08045",+ "originHash" : "7e15eb82903b33220d1d3bc1ab79f9433d1bd5a1dca1fab72e6aa726ec7b8325","pins" : [{"identity" : "appupdater",@@ -28,14 +28,6 @@"version" : "1.3.0"}},- {- "identity" : "fluidaudio",- "kind" : "remoteSourceControl",- "location" : "https://github.com/altic-dev/FluidAudio.git",- "state" : {- "revision" : "3fd63887eef1dc25edea8263ce4b44aa854d898b"- }- },{"identity" : "foundation","kind" : "remoteSourceControl",diff --git a/MEETING_PCM_FIRST_IMPLEMENTATION_PLAN.md b/MEETING_PCM_FIRST_IMPLEMENTATION_PLAN.mdnew file mode 100644index 00000000..c6856455--- /dev/null+++ b/MEETING_PCM_FIRST_IMPLEMENTATION_PLAN.md@@ -0,0 +1,511 @@+# FluidVoice PCM-First Meeting Audio Implementation Plan++Status: reviewed; PCM capture and analysis wired for pre-production testing; AAC archive/retention unfinished+Scope: meeting capture, canonical Parakeet + Nemotron processing, durable publication, and post-publication AAC archive+Non-goals: model-quality benchmarking, changing live-caption ASR, weakening attribution safety gates, or retranscribing historical AAC with a guessed delay++## 1. Outcome and hard invariants++For every new-format meeting, PCM is the only authoritative capture and analysis source. FluidVoice+does not create AAC until the canonical transcript and speaker evidence have been durably published.++The required ordering is:++```text+capture separate PCM tracks+ -> finalize and validate PCM chunks+ -> build measured analysis timeline+ -> Nemotron diarization+ -> Parakeet transcription+ -> assemble and durably publish sidecar + session+ -> create and verify AAC archive+ -> retain or evict PCM according to explicit policy+```++Load-bearing invariants:++1. Application and microphone audio remain separate tracks and clock/speaker namespaces.+2. With software AEC active, the authoritative microphone sample is the output committed by+ `MeetingAECOutputCommitter.commitProcessed`. Raw, bypass and warm-up audio remain explicit+ unprotected eras; no pre-AEC copy enters the protected analysis asset.+3. `MeetingAudioChunkWriter` remains the sole ordering, producer-epoch, canonical-retiming,+ format-boundary, gap, splice, and sequenced-metadata authority. A new PCM sink replaces the AAC+ storage behavior; a second competing timeline is forbidden.+4. A model-visible span is backed by a finalized, confined, hash-verified PCM asset and exact frame+ accounting. Every accepted interval becomes durable audio or a typed failure/gap.+5. Linear PCM priming is `notApplicable(linearPCM)` only after the sink's written frames and the+ finalized container's decoded frames agree. It is never inferred from the `.caf` extension.+6. Clock residual, admission, echo, coverage and ambiguity gates remain fail-closed.+7. Nemotron and Parakeet consume the same immutable per-epoch analysis materialization and sample+ mapping. Track-local or epoch-local speaker slots are never equated automatically.+8. Transcript publication does not depend on AAC compression succeeding.+9. AAC is a playback/archive derivative and is never an analysis fallback for new-format sessions.+10. Unknown or partially migrated state preserves PCM and refuses destructive cleanup.++## 2. Durable data model++### 2.1 Versioned assets, not filename inference++Add an explicit, Codable audio-asset schema. Do not infer semantics from `.caf` or `.m4a`.++```swift+enum MeetingAudioAssetRole: String, Codable {+ case captureAnalysis+ case playbackArchive+}++enum MeetingAudioEncoding: String, Codable {+ case linearPCMFloat32CAFV1+ case aacLCM4AV1+ case legacyAACUnknownPrimingV1+}++enum MeetingAudioAssetPresence: String, Codable {+ case partial+ case ready+ case evicted+ case failed+}++struct MeetingAudioAsset: Codable, Equatable, Sendable {+ var role: MeetingAudioAssetRole+ var encoding: MeetingAudioEncoding+ var presence: MeetingAudioAssetPresence+ var relativeFilePath: String+ var byteCount: Int64+ var sha256: String?+ var sampleRate: Double?+ var channelCount: Int?+ var frameCount: Int64?+ var sourceAssetSHA256: String?+}+```++`MeetingAudioChunk` retains immutable identity, sequence, presentation bounds and discontinuities,+and owns:++- one authoritative `captureAnalysisAsset` for new PCM sessions;+- an optional `playbackArchiveAsset` created after transcript publication;+- an explicit `audioSchemaVersion` / capture era.++Existing fields decode through a compatibility initializer into+`legacyAACUnknownPrimingV1`; unavailable historical frame facts remain `nil` and are legal only for+that encoding. Unknown enum values or contradictory combinations fail validation; they do not+silently become PCM or a ready archive. The first schema phase adds optional fields but continues to+encode the byte-identical legacy shape. Writing the new schema begins only at the PCM activation+boundary, with an explicit one-way `audioSchemaVersion`; older binaries are not claimed to read new+PCM sessions. Rollback after activation means disabling new PCM session creation in the new binary,+not installing an old binary over already-created PCM sessions.++The result sidecar snapshots immutable PCM provenance (asset digest, frame facts and mapping) so an+eventual PCM eviction never rewrites evidence already used to publish the transcript.++### 2.2 Session and chunk state++Do not duplicate the session processing state on every chunk. Use:++- existing session processing attempt/stage for capture and transcript publication;+- per-asset `partial`, `ready`, `evicted`, or `failed` presence;+- optional ready/staged AAC asset;+- a session-level archive job state: `notEligible`, `pending`, `running`, `completed`, or `failed`.++AAC becomes eligible only when the saved session references a read-verified canonical sidecar and a+completed Parakeet + Nemotron attempt.++### 2.3 Admission-to-durability ledger++`enqueue` success is not durability. Add a writer-owned append ledger:++- before a new chunk accepts its first sample, durably publish a chunk intent containing chunk ID,+ sequence, canonical start PTS, producer epoch, source format, and partial path;+- on the serialized writer queue, each accepted sample advances expected frames/PTS in memory;+- successful PCM writes advance written frames;+- periodic durable checkpoints and finalization record the written frame prefix and last PTS;+- finalization succeeds only when expected frames equal written frames and the decoded finalized CAF+ reports the same frame count;+- queue overflow, sink failure, invalid/retired samples and crash recovery become typed gaps or a+ failed chunk. A partial is never promoted merely because bytes exist.++No filesystem work occurs on the real-time callback. On crash, the durable chunk intent plus the last+checkpoint conservatively classifies the uncommitted tail as unavailable; initial recovery may+discard the entire partial chunk rather than fabricate a usable prefix.++## 3. Capture architecture++### 3.1 Timeline controller and sink boundary++Extract a sink protocol beneath `MeetingAudioChunkWriter` without moving its ordering logic:++```swift+protocol MeetingAudioChunkSink {+ func begin(...canonicalFormatAndTimeline...) throws+ func append(_ retimedBuffer: CMSampleBuffer) throws -> MeetingPCMAppendReceipt+ func finalize() async -> MeetingPCMFinalization+ func cancel()+}+```++The production new-format sink uses direct `AudioFileWritePackets` with an explicit native-rate,+native-channel Float32 CAF ASBD. The P1a prototype rejected `ExtAudioFileWrite` because it has no+written-frame out parameter and therefore cannot support truthful per-append receipts. Direct packet+writes report their accepted packet count and finalization independently verifies format, packets,+bytes and hashes. `AVAssetWriter`, `ExtAudioFileWrite`, and `AVAudioFile` writing are not used for+authoritative analysis PCM. The legacy AAC sink remains compiled only as an explicit+rollback/migration path; the new production default never falls back to it automatically.++`MeetingPCMAppendReceipt` reports exact frames accepted and written. The writer updates canonical+end PTS from the accepted frame duration, not an unrelated encoder result. Any mismatch fails the+chunk and records coverage loss.++### 3.2 PCM representation++- Application track: preserve accepted ScreenCaptureKit native sample rate and channel layout.+- AEC-active microphone: preserve the 48 kHz mono post-AEC output already synthesized by+ `MeetingAECPCMAdapter` and committed by `commitProcessed`.+- Non-AEC microphone: preserve the admitted producer format; do not add another resampler.+- Store Float32 LPCM as the authoritative reprocessing representation. This preserves the current+ ScreenCaptureKit/AEC sample domain and avoids irreversible clipping or two competing conversion+ rules. Non-finite samples fail the append rather than entering evidence. A future Int16 storage+ optimization requires its own measured-equivalence decision and is outside this migration.+- Remove the AAC-era two-channel clamp from PCM capture. Downmix belongs to analysis.++The prototype validates direct `AudioFile` packet writes by proving exact frame writes, container+finalization, channel-layout preservation and bounded queue latency. Descriptor-relative path+hardening and a forced-process crash harness remain mandatory before production wiring.++### 3.3 Chunk boundaries and gaps++Preserve the existing 60-second rotation, producer-epoch/backward-clock reset, format change,+explicit splice, and greater-than-0.5-second gap rules. A sink error closes the current chunk as+failed and opens no replacement until the writer has recorded the lost interval/era transition.++Files use same-volume staging and atomic rename:++```text+tracks/<kind>/000123.partial.caf+tracks/<kind>/000123.caf+```++Both paths are session-confined, non-symlink, mode 0600; parent directories are 0700. Orphans are+defined narrowly: a staged file whose chunk ID has no ledger intent, or whose intent already names a+different ready asset hash. Ambiguous files are retained.++## 4. Analysis architecture++### 4.1 Observer and timing certainty++Extend `MeetingChunkAudioObserver` to validate the explicit asset encoding and compare:++- stored byte count and SHA-256;+- declared and decoded sample rate/channel count;+- written, stored and decoded frame count;+- PTS duration versus `frameCount / sampleRate` within the existing residual bound;+- capture era and discontinuity scope.++Introduce `MeetingCodecPriming.notApplicable(.linearPCM)`. The certainty rule accepts this as known+only after all PCM invariants pass. Legacy AAC remains `.unknown(.decoderDidNotReport)` unless a+separate, fixture-proven packet-table implementation lands later.++### 4.2 Stateful epoch materialization++Replace per-span `AudioBufferConverter.monoSamples` calls with one converter state per exact key:++```text+(track ID, epoch generation, capture/AEC era, source sample format, channel layout)+```++A key change drains the old converter, attributes its tail to the old side, records the boundary, and+creates a new converter. Gaps are not bridged with invented samples. Materialization returns exact+input/output ranges for every span and validates total output frames.++The existing model-isolation order runs all Nemotron work before the Parakeet lease. Avoid retaining+unbounded `[Float]` buffers by adding a session-confined immutable epoch-materialization store:++- materialize each epoch exactly once to a hashed 16 kHz mono Float32 working asset plus span map;+- Nemotron and Parakeet reopen the same bytes in their separate phases;+- keep at most one decoded epoch buffer resident at a time;+- the working asset is derived and regenerable from authoritative PCM, so partials are never+ recovered as evidence and are deleted after successful publication or on proven orphan cleanup.++This store counts toward disk preflight. If implementation proves deterministic rematerialization is+bit-identical and cheaper, it may replace the store only with a regression test comparing hashes+across both backend phases and bounding memory.++### 4.3 Backend and evidence++Keep one fresh Nemotron state per analysis epoch and drain/unload it before acquiring prepared+Parakeet ASR. Both phases bind their units/activity to the same epoch materialization digest and span+map. Evidence validation rejects mismatched digests.++Attempt lineage records:++- Parakeet model/version and fixed meeting configuration;+- Nemotron model manifest SHA-256, entry metadata SHA-256, geometry/config version, thresholds and+ supported slot count;+- PCM capture schema, materialization schema and backend version.++Remove the legacy `FluidAudio-offline-v1` diarization fingerprint from canonical attempts.++## 5. Publication and post-publication AAC++### 5.1 Publication transaction++The current canonical ordering remains:++1. assemble evidence using fail-closed admission/timing/echo/coverage rules;+2. write, fsync and read-verify immutable result sidecar;+3. atomically save session transcript, speakers, completeness, attempt lineage and sidecar reference;+4. mark the archive job eligible.++No AAC work starts before step 3 succeeds.++### 5.2 Archive job++For each ready PCM chunk:++1. transcode to a unique same-volume staged `.m4a`;+2. verify encoding, decodability, channel/rate expectations, nonzero duration and bounded duration+ difference; hash the result;+3. persist the ready archive asset bound to the source PCM digest;+4. atomically activate it for playback/export;+5. keep PCM until retention policy permits eviction.++Compression failure changes only archive-job state. It never rolls back or invalidates the published+transcript. Playback/export either reads ready PCM or shows an explicit "preparing recording" state;+it never guesses a file representation.++### 5.3 PCM retention and eviction++Do not delete PCM immediately after AAC activation. Default PCM retention follows the recoverable+audio/reprocessing window. A future user setting may shorten or extend it. Disk-pressure eviction is+oldest-first and allowed only when:++- transcript and sidecar are durably published and verify;+- every archive asset is ready and verifies;+- no chunk/span is timing-uncertain, failed, or pending recovery;+- no processing/archive lease is active.++Eviction persists `.evicted` plus timestamp/reason before unlinking through a recoverable staged+deletion. After eviction, reprocessing reports authoritative PCM unavailable and never analyzes AAC.++## 6. Storage and recovery++Replace the flat 512 MB preflight with a calculation based on planned/default maximum duration,+active track formats, Float32 PCM bytes per frame, epoch working-set allowance, AAC staging and+reserve. At 48 kHz, stereo application plus mono microphone Float32 is about 2.1 GB/hour before the+derived epoch working set and AAC staging; the calculation uses actual active formats rather than a+flat estimate.+Re-evaluate during capture. Low space closes/fails the active chunk, records a typed event and stops+capture without naming a partial file finalized.++Startup reconciliation handles:++- intent without ready PCM: fail or conservatively quarantine partial, record missing interval;+- ready PCM without completed transcript: offer/restart canonical processing;+- published transcript with pending/failed archive: retry compression;+- staged AAC without activation: verify against job intent or retain;+- active AAC plus retained PCM: resume retention policy;+- evicted PCM: preserve provenance and disable reprocessing;+- historical AAC-only session: legacy decode and fail-closed timing semantics.++Recovery never updates byte counts from arbitrary filesystem contents and never promotes a partial+solely by extension or size.++## 7. Phased implementation and rollback boundaries++### Phase P1a — Direct AudioFile Float32 sink contract (implemented; harness only)++- Add an injectable sink protocol with an explicit threading contract: real-time producers enqueue;+ the existing serial writer queue owns canonical timing and performs sink I/O.+- Implement a harness-only native-rate/native-channel Float32 CAF sink using packet-counted+ `AudioFileWritePackets`; canonical storage is interleaved and planar input is packed without+ changing sample values or channel order.+- Prove append receipts report written frames, finalized decode counts match, formats/layout survive,+ files are confined and permission-tight, and partials never appear finalized.+- Exercise real `CMSampleBuffer` fixtures and forced process termination of a standalone harness.+- Make no persisted-model, capture-engine, priming, fingerprint, playback or production-wiring change.++Current verification: 6 focused sink tests and the 219-test combined compatibility, recovery and+canonical meeting selection pass with zero failures. Exact interleaved/planar frames, PTS receipts, layout, packet counts, hashes,+permissions, stale partials, zero-frame/cancel and no-overwrite behavior are covered. The subprocess+crash harness and descriptor-relative TOCTOU hardening are explicitly deferred and prohibit+production wiring until complete.+Rollback: delete unreferenced sink/harness code.++### Phase P0a — Additive compatibility types and golden wire tests (implemented)++- Add optional asset/capture-era types and tolerant compatibility decoding while continuing to emit+ the existing wire representation.+- Define legal missing legacy facts explicitly; do not hash or probe files during decode.+- Add old-session/index/track/backup decode and byte-shape encode goldens, including unknown future+ enum values that quarantine only the affected asset.+- Add no new persisted priming case and no lineage change yet.++Current verification: optional fields omit themselves from legacy chunk JSON, legacy chunk/session+round-trips pass, future raw values survive and quarantine only their asset, valid PCM/legacy assets+round-trip, and incomplete ready PCM is rejected by pure metadata validation. The combined sink,+compatibility, recovery and canonical backend selection passed 219 tests with zero failures. Current+app behavior and serialized output remain unchanged; an old-binary compatibility claim is limited to+this omit-empty phase only.+Rollback: remove optional unused types.++### Phase P0b — Recovery and ledger foundation (implemented; default behavior still AAC)++- Replace `reconcileChunkFile` size rewriting with hash/frame-aware, fail-closed reconciliation for+ new assets while preserving the explicit legacy compatibility rule.+- Add writer-queue chunk intent and durable checkpoint records. Define checkpoint cadence and fsync:+ chunk intent before first sink append, checkpoint at bounded one-second audio intervals or chunk+ closure, and fsync at intent/checkpoint/finalization boundaries off the real-time callback.+- Recovery discards/quarantines an uncommitted partial chunk and records its whole intended interval+ unavailable; it does not attempt prefix salvage in v1.+- Assign these rules explicit store/recovery tests. Keep production capture AAC.++Current verification: ledger intent and terminal records are immutable/idempotent, checkpoints are+chunk-bound and monotonic, ready terminals require complete written frames, and reads do not create+ledger directories. New-asset reconciliation requires verified authoritative PCM and quarantines a+broken optional archive without invalidating that PCM; partial/escaping assets never promote. The+combined foundation, compatibility, recovery and canonical backend selection passed 224 tests with+zero failures. Arbitrary file size never overwrites trusted new-asset metadata; legacy meeting+recovery behavior remains regression-tested.+Rollback: new ledger records are optional and ignored while no PCM session exists.++### Phase P2/P3 — Complete PCM path (wired for pre-production testing)++Capture and analysis were activated together so PCM recordings are never stranded. At the user's+explicit pre-production direction, new meetings now select this path directly rather than hiding it+behind a default-off setting.++- Wire the Float32 PCM sink for a session-scoped, default-off capture-format selection.+- Wire application samples and the correct post-AEC/raw era-specific microphone paths.+- Activate the new audio schema for flagged sessions only; add `notApplicable(linearPCM)` in their+ new-version manifests while legacy output remains unchanged.+- Add dynamic storage preflight and mid-session stop before any PCM capture can start.+- Make recovery, temporary playback and export understand ready PCM.+- Implement PCM observer/builder, boundary-keyed stateful conversion and the immutable epoch working+ store; bind both backend phases to its digest.+- Refuse archive/legacy AAC assets in the new analysis path.++Current verification: new capture writes Float32 CAF only, persists schema-2 authoritative PCM and+ledger records, the observer marks verified PCM priming not applicable, materialization is stateful+across compatible spans, and both models reuse the same bounded PCM epoch cache. Storage preflight+and history reveal are PCM-aware. The combined wired selection passed 290 tests with zero failures+and one opt-in real-model skip. Legacy AAC sessions still decode and remain timing-uncertain.++Real-field startup RCA found that `CMFormatDescriptionEqual` in the writer and raw layout-byte+comparison in the sink disagreed for semantically identical 48 kHz mono buffers whose metadata moved+between nil, Mono and DiscreteInOrder representations. A shared `MeetingPCMFormatContract` now owns+both decisions: safe mono/stereo representations canonicalize, custom layouts remain byte-distinct,+and planar/interleaved payloads remain topology-validated before canonical packing. Real+CMSampleBuffer regressions cover nil→Mono→nil→Discrete mono with one exact chunk and zero+writer failures; genuine mono→stereo changes rotate once. The expanded PCM/AEC/canonical selection+passes 328 tests with zero failures and one opt-in model skip.+Rollback for future sessions requires a new-binary capture switch or code rollback; existing PCM+sessions must remain on a binary that understands schema 2.++Remaining before release: replace the bounded in-memory epoch cache with the planned immutable disk+working store, add descriptor-relative path operations and subprocess crash injection, and complete+post-publication AAC activation/recovery.++### Phase P4 — PCM-first publication activation++- Flip new meetings atomically to the already-complete PCM capture+analysis path.+- Persist new audio schema and real Parakeet/Nemotron/capture/materialization fingerprints.+- Explicitly invalidate only incompatible in-progress checkpoints; completed historical attempts+ remain completed and are never relabeled or automatically rerun.+- Keep PCM unconditionally; do not enable AAC archive or eviction in this phase.++Exit: a production-like matrix—not one fixture—publishes assigned speakers across chunk, AEC era,+format, gap and producer-epoch boundaries; defaults create no AAC; recovery and disk gates pass.+Rollback: disable new session creation in the new binary, retain PCM, and keep existing PCM sessions+readable/retryable. Rolling back to an older binary is unsupported for PCM sessions.++### Phase P5 — Post-publication AAC and representation-aware UI/export++- Add a sidecar-style per-session archive job: same-volume staged file, verification, ready asset+ record, atomic session save, and retry. A second global journal is unnecessary.+- Make playback/export use PCM before archive activation and AAC afterward; show pending/failure.+- Add startup reconciliation for every stage. Never delete PCM in this phase.++Exit: no AAC exists before session publication; every crash point preserves a valid transcript and+recoverable PCM; archive failure is non-destructive.+Rollback: disable archive jobs and continue retaining/playing PCM.++### Phase P6 — PCM retention and eviction++- Add configurable retention and conservative oldest-first eviction.+- Update `deleteAudioFiles`, `audioDeletedAt`, recovery predicates and observer/materializer refusal so+ deleting PCM while retaining AAC cannot make AAC an analysis source.+- Add metrics without audio content.++Exit: deletion is impossible for uncertain/failed/active sessions; an evicted session retains+provenance and explicitly disables reprocessing.+Rollback: disable eviction and retain PCM.++No phase combines the schema activation, default capture flip, archive activation and deletion+policy. P2/P3 cannot ship independently; P4 is the one-way audio-schema activation boundary.++## 8. Release-blocking verification matrix++### Capture and durability++- New-format meeting has no `.m4a`/AAC asset before durable transcript publication.+- App and mic remain separate; AEC-active disk mic matches `commitProcessed`, not raw SCK mic.+- Float32 capture preserves finite source samples and native channel layout; NaN/infinity fail the+ append, and no Int16 clipping/quantization is introduced.+- Queue full, sink failure, short write and crash between intent/append/checkpoint/final rename leave+ every interval as verified PCM or typed unavailable coverage; partials are never promoted.+- Producer epoch, backward clock, format/layout change, splice, 60-second rotation and >0.5-second+ gap preserve exact chunk order and mapping.++### Analysis and attribution++- Written/declared/decoded PCM frames match; mismatch stays timing-uncertain.+- Residual remains within bound for continuous fixtures and fails closed when injected outside it.+- Converter key change drains/restarts at epoch, era, format or layout boundary; drained tail belongs+ to the prior side.+- Nemotron and Parakeet evidence references the identical materialization digest and span map.+- Two-speaker application audio publishes two speaker IDs across a chunk boundary.+- App/mic slot labels do not merge; overlap/ambiguity and AEC admission remain conservative.+- Historical AAC-only fixture remains timing-uncertain without guessed priming.++### Publication, compression and recovery++- Crash after sidecar but before session save leaves no falsely published transcript and is+ reconcilable.+- Crash after transcript save but before AAC creates a readable transcript with ready PCM.+- Crash during AAC stage/rename/manifest activation retains either the prior PCM state or a verified+ active archive, never neither.+- Compression failure keeps transcript valid and PCM retryable.+- Playback/export use PCM before AAC activation and AAC afterward without changing transcript time.+- PCM eviction is refused for uncertain, failed, unpublished or leased sessions.+- Low-space start refusal and mid-session exhaustion preserve prior finalized chunks and emit an+ actionable failure.+- Canonical attempt contains Parakeet identity, Nemotron digest/config and PCM/materialization schema;+ it never reports the legacy diarizer fingerprint.++## 9. Closed design decisions from adversarial review++Grok 4.6 and Claude Opus independently accepted PCM-first capture but rejected the original phase+sequence. This revision closes their load-bearing questions:++1. The ledger performs no synchronous callback I/O. Intent/checkpoints run on the serialized writer+ queue; recovery quarantines the whole uncommitted partial chunk in v1.+2. `ExtAudioFileWrite` was rejected because it cannot report a written-frame count. The accepted+ harness uses direct `AudioFileWritePackets` and verifies packet/frame/byte counts on reopen.+3. Float32 CAF is authoritative. Int16 optimization is deferred because it irreversibly clips or+ quantizes the current Float32 ScreenCaptureKit/AEC domain.+4. An immutable epoch working store is required because the current runtime drains Nemotron before+ acquiring Parakeet and cannot hold unbounded meeting audio in memory. Rematerialization is not an+ implementation option in this migration.+5. AAC activation reuses the sidecar pattern: staged same-volume asset, verification, immutable+ archive record and atomic session save. It does not add a second global journal.+6. PCM eviction is a separate final phase. The observer/materializer accept only the capture-analysis+ role, and reprocessing becomes explicitly unavailable after PCM eviction; AAC is never substituted.+7. Removed as over-engineering: six states duplicated per chunk, production dual-write validation,+ capture-time resampling, immediate PCM deletion, a rematerialization fork, and fingerprint changes+ in a no-behavior phase.++Review disposition: both reviewers' phase and recovery objections are accepted. On source format,+Grok preferred Float32 and Opus considered Int16 adequate with clip metrics; the parent chooses+Float32 because correctness and future reprocessing are the stated priority, while dynamic disk gates+make its cost explicit. The implementation must not reopen this choice without a separate decision.diff --git a/MEETING_TRANSCRIPTION_BACKEND_ARCHITECTURE_PLAN.md b/MEETING_TRANSCRIPTION_BACKEND_ARCHITECTURE_PLAN.mdnew file mode 100644index 00000000..01f7bad7--- /dev/null+++ b/MEETING_TRANSCRIPTION_BACKEND_ARCHITECTURE_PLAN.md@@ -0,0 +1,843 @@+# Meeting Transcription Backend Architecture and Rollout Plan++Execution source of truth: [Meeting transcription implementation plan](MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md).+That shorter companion supersedes conflicting details here about model thresholds, microphone+admission, preemption, automatic fallback, result persistence and model delivery. This document+retains the earlier design rationale and historical review discussion.++Status: reviewed design proposal++Date: 2026-09-12++First-release default: local Parakeet TDT v2 ASR + Nemotron-3 diarization++Future candidates: Meta Muse Voice Transcribe, Google Chirp, and other local or hosted backends++## 1. Decision summary++FluidVoice should introduce a meeting-specific backend abstraction above the existing dictation+`TranscriptionProvider` protocol.++The product-level operation is one request and one result:++```text+MeetingProcessingCoordinator+ -> MeetingTranscriptionBackend+ -> canonical evidence+ -> MeetingTranscriptAssembler+ -> MeetingProcessingResult+```++The first backend is a composed local implementation:++```text+ParakeetNemotronMeetingBackend+ Parakeet TDT v2 -> timestamped words+ Nemotron-3 Sortformer -> speaker activity spans+ local aligner -> speaker-attributed words and turns+```++Future unified services such as Muse or Google Chirp implement the same backend contract but may+produce diarized text in one provider call. Their adapters still normalize into the same canonical+evidence and pass through the same FluidVoice assembler and safety policy.++Do not extend the general dictation `TranscriptionProvider` with diarization, upload, speaker, or+meeting-persistence concepts. Dictation and meeting transcription have different lifecycles,+privacy boundaries, inputs, outputs, and recovery requirements.++## 2. Product requirements++### First release++- The default meeting backend is `local.parakeet-tdt-v2+nemotron3-fp16`. Development targets the+ preview model contract now; the artifact is replaced and pinned to the production Nemotron release+ before FluidVoice ships.+- Parakeet remains responsible for speech-to-text.+- Nemotron remains responsible for speaker activity only.+- Live captions continue using the existing live-caption path and simple You/Them presentation.+- Final diarization runs after durable meeting audio has stopped.+- Existing application and microphone tracks remain separate evidence sources.+- First release performs no automatic cross-era speaker reconciliation. Era-local speakers remain+ distinct; users can reconcile them through the existing explicit speaker-merge workflow.+- Online-call final processing may refine the simple live You/Them labels. At most one verified+ microphone speaker becomes You; other microphone speakers remain Unknown. In-room processing does+ not infer You automatically.+- Processing remains local, except for any unrelated user-selected AI enhancement that already has+ its own explicit policy.+- The current offline-clustering/cosine implementation remains a hidden local rollback backend until+ Nemotron quality and reliability gates pass.++### Later releases++- Users may select an installed/configured meeting backend independently of their dictation model.+- Hosted backends must require explicit disclosure and consent before any meeting audio leaves the+ Mac.+- Adding a backend must not require changing `MeetingSession`, transcript persistence, export, or UI+ rendering merely because the provider uses a different native response format.+- Backend selection changes apply only to new processing attempts. They never mutate an active or+ resumable attempt.++### Non-goals++- Fusing Parakeet and Nemotron into one CoreML graph.+- Making the meeting backend also control dictation.+- Implementing Muse or Google in the first release.+- Automatically switching from local processing to a hosted service.+- Inferring real names from voiceprints or carrying speaker identity between meetings.+- Treating an expected speaker count as ground truth in product behavior.++## 3. Current-state constraints++The design must account for these properties of the current tree:++- `TranscriptionProvider` is an ASR-oriented protocol and returns text plus optional word timings.+- `MeetingProcessingPipeline` directly obtains `ASRService.fileTranscriptionProvider` and constructs+ `SpeakerDiarizationService` itself.+- `SpeakerDiarizationService` directly owns FluidAudio's `OfflineDiarizerManager`.+- The current meeting pipeline diarizes each durability chunk independently, then uses embeddings and+ cosine-based global stitching.+- `MeetingFinalProcessingConfiguration` has an ASR model and diarization fingerprint but no stable+ meeting-backend identity.+- `MeetingASRPreparationOwner` is a tested but currently unwired ASR-only ownership seam. Do not build+ a second preparation lifecycle beside it; either generalize it or deliberately replace it.+- The processing checkpoint is written after the application-audio pass and is valid only for an+ exact pipeline/model/configuration fingerprint.+- Online-call sessions contain separate application-audio and microphone tracks with capture-era,+ echo-protection, coverage, and provenance rules.+- `MeetingTranscriptSegment` has one optional `speakerID` plus an overlap classification. It cannot+ persist one word as belonging to multiple speakers without a versioned schema change.++## 4. Layered architecture++### 4.1 MeetingProcessingCoordinator++Responsibilities:++- Snapshot the selected backend and all configuration exactly once at attempt creation.+- Hold the exclusive audio/model activity lease.+- Resolve a backend through the registry.+- Validate request compatibility before loading models or uploading audio.+- Own cancellation, retry, fallback authorization, and progress delivery.+- Invoke the backend and then the product-owned assembler.+- Persist attempt lineage and checkpoints.++The coordinator must not interpret model-native tensors, provider speaker tags, or API payloads.++### 4.2 MeetingTranscriptionBackend++This is the product extension point. A backend may be composed or unified, local or hosted.++Conceptual contract:++```text+identity and descriptor+plan(request) -> validated immutable execution plan+prepare(plan, progress)+transcribe(plan, progress) -> MeetingTranscriptionEvidence+```++Requirements:++- `Sendable` ownership with one operation per prepared instance.+- Cooperative Swift task cancellation.+- Receive an immutable `MeetingRuntimeEnvironment` containing every setting, credential handle,+ model path, clock policy, and product dependency the operation may use.+- No implicit access to `SettingsStore.shared` after planning. DEBUG/contract tests install a guard+ that fails if meeting processing reads the singleton during an active attempt.+- No mutation of session persistence.+- No direct creation of product `SessionSpeakerID` values.+- No direct emission of UI events.+- Cleanup on success, error, and cancellation.++The planning call is important. A collection of capability booleans is not enough to decide whether+a particular meeting, language, duration, topology, and privacy policy can be processed. Planning+must either return a complete immutable plan or a typed incompatibility before side effects begin.++### 4.3 MeetingTranscriptionBackendRegistry++The registry maps stable string-backed IDs to factories and descriptors.++Use a string-backed value type rather than a closed persisted enum so a removed or unavailable future+backend can be decoded safely. Unknown IDs resolve to an explicit unavailable state; they must not+silently select a cloud service. A migration may select the local default for a new attempt only.++First-release registrations:++- `local.parakeet-tdt-v2+nemotron3-fp16`+- `local.parakeet-tdt-v2+offline-diarizer-v1` (hidden rollback)++Future registrations may include:++- `meta.muse-voice-transcribe`+- `google.chirp-3`++Do not add unavailable future providers to the shipping picker. Prove extensibility with fixture+backends and contract tests instead of disabled marketing UI.++### 4.4 Backend descriptor and capabilities++The first-release descriptor includes only fields consumed by planning or selection:++- stable backend ID, display name, implementation version, and vendor;+- execution boundary: local or hosted;+- supported languages and language-selection mode;+- accepted input topologies: separate tracks, interleaved multichannel, or composed mono;+- supported meeting modes: online call, in-room, or both;+- maximum duration and speaker capacity, when known;+- timing granularity: utterance, word, or frame; `none` is incompatible with meeting processing;+- one of the valid evidence profiles defined below;+- model/download readiness and required local bytes;+- credential and network requirements.++Hosted retention, region, remote-job, and billing metadata are added with the first real hosted+backend in Phase 6 rather than speculated into the first-release contract.++Capabilities describe facts. The backend's `plan` method decides compatibility and produces a typed+reason when a request cannot be served.++Normal product requests never contain an exact expected speaker count. A provider may receive a+declared capacity as a maximum hint, never attendance truth. Planning rejects an API that requires a+known exact count the product cannot honestly supply.++### 4.5 Canonical evidence++All backends return `MeetingTranscriptionEvidence`, not `MeetingProcessingResult`. Version 1 accepts+two closed evidence profiles:++- `activityPlusWords`: separate timed words plus speaker-activity spans, used by the composed local+ backend. The backend runs the shared aligner and returns final diarized words.+- `diarizedWords`: final words or utterances already carrying run-local speaker tags, used by a+ unified provider. Online-call planning accepts this profile only with separate source-track+ provenance.++Anything else is a typed planning incompatibility. The assembler validates and maps final+attribution; it does not run a second aligner.++Version 1 evidence is final-only. Streaming partials, retractions, delayed speaker tags, and endpoint+revisions remain adapter-internal until the adapter can emit a committed final snapshot. A future+incremental evidence protocol requires its own versioned design; fixture tests must not pretend the+single-return contract proves it.++The canonical evidence model contains:++- a versioned evidence schema and backend lineage;+- one or more analysis streams;+- timed words, or at minimum timed utterances;+- speaker-activity spans when required by the evidence profile;+- backend-local anonymous speaker tokens scoped by run, analysis stream, track, and era;+- zero, one, or multiple active speaker tokens over an activity interval;+- timing precision and confidence semantics;+- a closed disposition for every input word/utterance: emitted, echo-suppressed,+ inadmissible-capture-era, coverage-gap, outside-activity, ambiguous-unassigned,+ provider-truncated, overlap-flattened, or speaker-tag-timeout;+- explicit backend coverage claims over the admissible analysis-manifest intervals;+- source-track and analysis-time mapping references;+- non-secret provider/model/configuration provenance.++Provider speaker labels such as `speaker_0`, `Speaker A`, or Google's numeric tags are scoped to one+backend run. They are not names, not cross-track identities, and not directly persisted as stable+session speaker IDs.++### 4.6 MeetingTranscriptAssembler++The assembler is owned by FluidVoice and is shared by every backend.++Responsibilities:++- Validate all evidence bounds, ordering, finiteness, and source mappings.+- Reconcile evidence against the analysis manifest: every admissible manifest interval must be+ covered by evidence or a typed gap. Backend self-reported gaps are not authoritative. Any+ unaccounted interval is a hard validation failure.+- Convert analysis time to the canonical meeting presentation timeline.+- Apply capture-era admission, AEC provenance, coverage-gap, and echo-safety rules.+- Be the sole owner that mints deterministic `SessionSpeakerID` values from attempt, track, era, and+ backend-token scope. Backends never mint product IDs.+- Apply online-call track semantics: application audio is remote evidence; microphone evidence is+ eligible for You/Unknown only after the existing safety checks.+- Suppress cross-track echo duplicates using the existing clock-compensated signal/text evidence.+ The microphone copy receives a typed `echoSuppressed` disposition; the application-track copy is+ never removed by this rule. Unknown AEC/protection state is fail-closed: the microphone word may+ remain Unknown but can never become You.+- Preserve canonical overlap evidence. Because the v1 persisted segment has one `speakerID`, choose+ at most one primary speaker per word, mark unresolved overlap as ambiguous, and retain the word in+ an explicit unassigned ledger. Do not duplicate it. True multi-owner word persistence is a later+ versioned schema change.+- Produce the existing `MeetingSessionSpeaker`, `MeetingTranscriptSegment`, coverage, and attempt+ structures.+- Reconcile a final word ledger on the presentation timeline so every backend word is emitted once or+ carries exactly one explicit non-emission reason. Per-stream backend conservation is necessary but+ insufficient.+- Convert provider truncation or uncovered admissible audio into explicit coverage gaps and an+ incomplete transcript state. Export remains possible only with a visible incompleteness marker;+ truncation never looks like successful complete processing.++No hosted backend may bypass this layer merely because it returns a polished transcript.++## 5. Canonical time and input topology++### 5.1 Analysis manifest++Before model work begins, FluidVoice builds an immutable `MeetingAnalysisManifest` from finalized+audio chunks.++It records mappings among:++```text+source-file local time <-> analysis-stream time <-> meeting presentation time+```++Each span records the source track, chunk, capture era, valid interval, discontinuity, protection+state, and checksum. Its time transform is piecewise affine and records host-clock anchor, rate+ratio, offset, sample-rate-conversion ratio, codec delay/priming, whether analysis time removes gaps,+and measured fit residual. A span whose residual exceeds the configured bound is `timingUncertain`;+its words remain explicit and ambiguous rather than receiving a confident speaker assignment.+Missing, corrupt, unfinalized, or inadmissible ranges remain explicit gaps.++Every evidence interval must round-trip through source, analysis, and presentation time within one+declared model frame and resolve to exactly one source track. Model time is never inferred from AAC+frame counts or durability-file boundaries.++Durability chunks are never presumed diarization boundaries.++### 5.2 Topology rules++- The local backend receives separate application and microphone analysis streams.+- In-room mode normally has only the microphone stream.+- Online-call hosted backends must accept separate per-track inputs with output provenance for every+ word/utterance. Planning rejects a backend that requires a mono mix or cannot preserve track+ provenance. Mixing would make AEC admission, You/Unknown, and cross-track echo suppression+ unverifiable.+- Composed mono is permitted only for a single-track in-room meeting. Multichannel online-call+ support is deferred until a real provider can return verifiable channel provenance; it requires a+ versioned topology-specific safety design rather than a descriptor flag alone.+- Composition, when permitted by the topology rules, is a product-owned, fingerprinted transform. A provider adapter may not+ invent a mixdown silently.+- Speaker tokens from separately processed streams are never equated by label or slot number.+- Temporary upload artifacts use protected storage and are deleted on all terminal paths and by+ next-launch stale-artifact cleanup.++## 6. Default local backend design++### 6.1 Execution strategy++`ParakeetNemotronMeetingBackend` is one application-level implementation with two model stages.++Recommended order until concurrent memory use is measured:++1. Build and validate the analysis manifest.+2. Prepare Nemotron.+3. Diarize each contiguous capture era statefully across its durability chunks.+4. Persist/checkpoint canonical speaker-activity evidence.+5. Release Nemotron resources.+6. Prepare Parakeet TDT v2.+7. Transcribe each readable source chunk once with word timings.+8. Align words to speaker activity.+9. Return canonical evidence to the assembler.++Loading both models simultaneously is not a requirement of the composite abstraction. Prefer bounded+memory and dictation preemption over nominal parallelism until measurements justify concurrency.+Time-to-final-transcript is also an acceptance gate. If sequential execution misses its latency+budget on the minimum supported Mac, reopen this choice using measured peak RSS and latency together.++### 6.2 Nemotron host++Implement the model host in the pinned FluidAudio fork, reusing its Sortformer pipeline while giving+Nemotron a distinct configuration/variant.++Required model contract:++- eight speaker slots;+- 16 kHz mono host audio;+- 128-bin NeMo-compatible log-mel features with dither disabled;+- 264-entry speaker cache;+- offline profile geometry from the converted model;+- exact FIFO-to-cache promotion behavior from the NeMo reference;+- output names `spkcache_fifo_chunk_preds`, `chunk_pre_encode_embs`, and+ `chunk_pre_encode_lengths`;+- predictions are already sigmoid probabilities;+- reference activity threshold defaults to 0.25, not FluidAudio's current Sortformer default of 0.5;+ it is immutable and fingerprinted for a run, with no per-track tuning or hysteresis in v1.++Do not apply sigmoid twice. Do not merge Nemotron slots post hoc. Do not treat pre-encoder embeddings+as speaker-identity embeddings; the local validation found them unsuitable for that purpose.++One Nemotron state spans all contiguous chunks in one track/era. Reset only at a declared analysis+boundary, not every 60-second file. The backend emits only run-local tokens. The assembler derives+product IDs from attempt, source track, era, and token.++V1 always splits speakers across eras. It performs no automatic reconciliation because label equality+is meaningless and the available pre-encoder representation is not a speaker identity embedding.+The existing user-driven merge/alias operation is the only cross-era reconciliation and must remain+idempotent across retry. If the model reuses a slot for a later voice or exhausts all eight slots,+mark a quality/coverage failure; never silently present the two voices as one identity.++### 6.3 Parakeet host++- Pin Parakeet TDT v2 independently of the user's dictation selection.+- Request model-native word timings once per readable source chunk.+- Preserve vocabulary and pronunciation policy only when the immutable meeting configuration enables+ them.+- Never re-read mutable global language/model settings mid-run.+- Unload or yield resources according to the shared audio/model arbiter.++### 6.4 Word-speaker alignment++Use half-open intervals and deterministic rules:++- Prefer the speaker with the greatest temporal intersection with the word.+- A unique active speaker receives the word.+- If multiple speakers overlap materially and no unique winner exists, preserve explicit ambiguity;+ do not duplicate the word into two transcripts.+- A word outside all activity may attach only within a track-specific measured tolerance.+- Microphone tolerance remains zero unless evaluation proves another value safe.+- Every word is assigned once or counted with a typed reason.+- Alignment belongs to the `activityPlusWords` backend path. The assembler validates the resulting+ final attribution and word ledger but does not align a second time.+- Provider text must not be re-transcribed per diarizer turn unless the word-timing path is technically+ unavailable and the configured fallback explicitly permits it.++### 6.5 Speaker limit++Nemotron has eight output slots. The backend descriptor declares that hard ceiling. Saturation or+unrepresentable speaker evidence produces a quality/coverage warning, not a silent ninth-to-eighth+merge. The system must not run the legacy backend merely to choose whichever result reports more+speakers; fallback is for typed technical failure, not quality arbitration. An echo-only slot does+not become a persisted speaker after suppression, but it still consumed raw model capacity and must+not be excluded from saturation detection.++## 7. Future unified hosted backends++### 7.1 Meta Muse adapter++Muse may return streaming text, speaker tags, and endpoint tokens from one model. For this final-only+v1 contract, its adapter buffers/reconciles provider revisions internally and maps only committed+output:++- emitted text/timing into canonical words or utterances;+- speaker tags into run-local anonymous speaker tokens;+- endpoint tokens into turn boundaries;+- missing precision or confidence into explicit capability metadata.++If a word never receives its delayed tag, the adapter returns it as unassigned with+`speakerTagTimeout`. Incremental UI delivery is a separate future protocol rather than a mutation of+checkpointed final evidence.++Muse remains subject to the same input mapping, product assembler, persistence, and privacy rules.+Its unified output does not make it a `TranscriptionProvider` for meetings.++### 7.2 Google Chirp adapter++Chirp batch diarization may return timestamped words with numeric speaker tags. Its adapter maps those+directly into canonical diarized words. Streaming transcription support does not imply streaming+diarization support; the descriptor and planner represent those capabilities independently.++### 7.3 Hosted-provider invariants++- No implicit local-to-cloud fallback.+- Explicit setup disclosure plus a per-meeting preflight of what audio is uploaded, where it is+ processed, expected cost, and provider retention controls. Processing shows a persistent upload/+ remote-processing indicator.+- API credentials live only in Keychain.+- No credential, signed URL, raw response, or provider job token in analytics or exported sessions.+- Remote job identifiers, if resumability requires them, are stored in a protected coordinator-owned,+ device-local envelope and never treated as transcript provenance. They are excluded from backup,+ export, analytics, and crash logs and are wiped on restore to another device or without matching+ credentials.+- Retry is idempotent where the provider supports it; otherwise the UI warns before creating a second+ billable job.+- Cancellation stops local work, requests remote cancellation when supported, and clearly reports+ when a provider may continue processing.++## 8. Selection and settings++Add a meeting-specific setting; do not reuse `selectedSpeechModel`.++```text+meetingTranscriptionBackendID = local.parakeet-tdt-v2+nemotron3-fp16+```++Persistence rules:++- Store only the stable backend ID in `UserDefaults` through `SettingsStore`.+- Store hosted-provider credentials through `KeychainService`.+- Include the meeting-backend selection in backup/restore, but never credentials.+- Distinguish a missing key from an unknown value: missing means use the local default for a new+ attempt; unknown remains inspectable and unavailable. An existing checkpoint may never resume+ under a substituted backend.+- Existing fingerprint-compatible checkpoints without a backend ID migrate only to+ `local.parakeet-tdt-v2+offline-diarizer-v1`. They never migrate to Nemotron or cloud. Older builds+ ignore the new preference and reject newer checkpoint versions rather than attempting downgrade+ resume.+- Call `objectWillChange.send()` when the future picker needs to react.++UI placement:++- Future picker belongs in Meeting Tools, not Voice Engine, because it controls final meeting+ processing rather than general dictation.+- First release may keep the setting internal while only one public backend is ready.+- Hosted choices display Local/Cloud, language coverage, speaker/timing capabilities, credential+ status, and an upload disclosure before activation.+- A backend is selectable only when registered and supported; do not ship disabled Muse/Google cards.+- Before recording, preflight the selected backend's registration, platform support, local model+ readiness or downloadable size, credentials, consent, and meeting-mode compatibility. Do not wait+ until the post-meeting attempt to reveal a missing credential or unavailable model.+- State clearly that the meeting backend is independent of the dictation model; selecting a different+ dictation engine does not alter final-meeting Parakeet policy.++## 9. Preparation, progress, and resource ownership++Generalize or replace `MeetingASRPreparationOwner` with a single+`MeetingTranscriptionPreparationOwner` that owns the selected backend's entire preparation lifecycle.+Do not retain two overlapping owners.++The owner holds:++- activity lease and attempt ID;+- immutable backend ID and execution-plan fingerprint;+- one preparation task;+- prepared backend instance;+- cancellation/drain task;+- progress relay.++First-release generic progress stages include:++- validating input;+- preparing/downloading components;+- identifying speakers;+- transcribing;+- finalizing.++Hosted upload/waiting states are added with the first hosted adapter in Phase 6. Alignment remains a+backend detail under `activityPlusWords`; it may be exposed as non-persisted detail without forcing a+generic enum case.++Provider-specific progress remains backend metadata and does not become a required UI enum case.++The coordinator is the single lease owner; the serialization gate, preparation owner, and model+stages operate under that lease rather than acting as independent authorities. A backend may not load+large local models while active dictation owns the lease. Document the allowed loaded-model set for+each stage. Cancellation must join the current uninterruptible model call, unload/drain the prepared+instance, and only then release ownership.++If dictation starts during a long final pass, the meeting backend yields at the next bounded chunk,+checkpoints durable work, drains models, releases the lease, and resumes only after reacquiring it.+The cancellation/preemption budget is no more than one model inference chunk plus drain overhead;+tests set a numeric wall-clock target on the minimum supported Mac.++## 10. Provenance, checkpointing, and fallback++### 10.1 Immutable run fingerprint++Every attempt records:++- requested backend ID, actual backend ID, and backend implementation version;+- one processing-contract version covering canonical evidence, assembler, safety policy, and+ persisted result semantics;+- ASR model/revision and options;+- diarizer model SHA, profile, threshold, and mel-front-end version;+- FluidAudio revision;+- analysis-manifest hash and source chunk hashes;+- language and input topology;+- input-topology policy.++Chunk SHA-256 values are computed once during durable chunk finalization and referenced here; attempt+creation must not re-read and hash hours of audio.++Any difference invalidates the checkpoint. User setting changes never rewrite an in-flight+fingerprint.++### 10.2 Checkpoints++The checkpoint is a map keyed by `(actualBackendID, trackID, eraID, stage)`, not one global+`completedStage`. Prefer canonical stage outputs over serialized provider-native objects:++- analysis manifest complete;+- speaker activity complete per track/era;+- ASR words complete per source chunk;+- product assembly complete.++V1 does not persist Nemotron cache/FIFO state because it contains acoustic representations covered by+the no-embedding persistence policy. A crash mid-era reruns Nemotron from the start of that era; this+worst-case cost is measured and disclosed in the resource gate. Alignment is deterministic and+recomputable from durable activity plus words, so it is not a separate durable checkpoint.++Corrupt or incompatible checkpoints are discarded fail-closed and processing restarts from a safe+boundary. Hosted remote-job state, when later supported, uses the separate device-local envelope in+§7.3 rather than canonical evidence.++### 10.3 Fallback policy++Fallback is an explicit policy owned by the coordinator:++- local Nemotron may fall back to the hidden local legacy backend only for model checksum, model+ load/initialization, or typed inference-incompatibility failures. Cancellation, timeout, resource+ exhaustion/OOM, empty diarization, saturation, and quality metrics are not allowlisted;+- fully drain the failed instance under the lease, delete its checkpoint subtree, and then start the+ fallback as a new attempt with a new actual-backend fingerprint;+- persist a bounded fallback-attempt counter so crash/resume cannot loop indefinitely;+- record both requested and actual backend plus the failure code;+- never fall back from local to cloud;+- never select a result by speaker count, transcript content, confidence, or apparent quality;+- never mix evidence from two backends in one final result unless a future version defines and+ validates such a composition explicitly.+- If fallback or a fingerprint-invalidating retry renumbers speakers, never attach existing+ user-assigned names by ordinal/provider token. Preserve them only through an explicit verified+ mapping; otherwise invalidate the association with a visible notice.++## 11. Security, privacy, and model-release readiness++- Keep application and microphone audio separate for online-call processing. Only a single-track+ in-room plan may compose audio under the v1 topology rules.+- Preserve all capture-era and echo-admission checks after every provider response.+- Treat provider output and model metadata as untrusted data: validate sizes, times, text lengths, and+ identifiers before persistence.+- Do not persist speaker embeddings in session JSON, exports, analytics, logs, or crash reports.+- Real participant names require user assignment; backend labels stay anonymous.+- Hosted audio use requires explicit consent and accurate retention/region disclosures.++Release assumption: FluidVoice will ship alongside the production Nemotron release. The preview+checkpoint is used only to implement and validate the model contract. Before FluidVoice ships,+replace it with the production artifact, pin its immutable identity/hash, rerun conversion and parity+gates, and verify that geometry, preprocessing, thresholds, and output semantics have not changed.++Official references checked 2026-09-12:++- NVIDIA model: https://huggingface.co/nvidia/Nemotron-3-Diarization-preview+- Meta Muse Voice Transcribe: https://research.meta.ai/blog/introducing-muse-voice-transcribe+- Google Chirp 3: https://docs.cloud.google.com/speech-to-text/v2/docs/chirp-model++## 12. Test architecture++### 12.1 Backend contract suite++Every backend, including future fixture-only adapters, must pass reusable tests for:++- planning and typed capability rejection;+- immutable configuration after planning;+- canonical time bounds and half-open intervals;+- deterministic token scoping and output ordering;+- overlap, ambiguity, missing timing, and partial coverage;+- cancellation and cleanup at each suspension point;+- malformed/oversized provider output rejection;+- checkpoint fingerprint and resume behavior;+- no settings reads after attempt creation;+- no UI, persistence, or analytics writes from the adapter;+- declared input topology matching actual access.++Create two fixture adapters for the two final evidence profiles:++- `activityPlusWords`, wrapping the current local pipeline shape;+- final `diarizedWords`, representing only the committed output shape of a future unified provider.++These prove that the evidence model and assembler can express well-formed final output. They do not+prove hosted extensibility for authentication, upload, polling, revisions, rate limits, billing,+regions, retention, or cancellation. Those are tested with the first real hosted adapter in Phase 6.++### 12.2 Default-backend tests++- Swift-vs-NeMo mel parity on committed redistributable synthetic audio.+- CoreML-vs-reference cold and warm state parity.+- No second sigmoid; activity threshold fixed at 0.25 in the run fingerprint.+- Stable slot across a 60-second durability boundary.+- Correct reset at a declared era boundary.+- Piecewise clock-rate drift, gap-stripped and gap-preserving model time, AAC priming, SRC ratios,+ corrupt chunks, and unfinalized chunks. An impulse at a known presentation time must round-trip+ through Nemotron activity and Parakeet words within one model frame.+- One, two, overlapping, short-interjection, and eight-speaker fixtures.+- Explicit behavior when all eight slots are active or saturated.+- Parakeet word conservation, speaker alignment, and final disposition-ledger reconciliation against+ the analysis manifest.+- Online-call application/microphone isolation, at-most-one You, fail-closed AEC coverage, and a+ remote utterance present as measured residual echo on the microphone track: one final app copy,+ typed suppression of the mic copy, and no phantom speaker.+- Multi-era sessions always split automatic identities; an explicit user merge is idempotent and+ survives retry.+- Fallback cannot start before failed-backend drain and checkpoint deletion complete; retry cannot+ loop fallback or attach old names by speaker ordinal.+- Cancellation latency, peak RSS, model unload, and dictation preemption on long meetings.+- Local retry produces identical text, token ordering, speaker IDs, and reason codes; numeric spans+ match within one declared model frame rather than requiring bit-identical floating-point output.++### 12.3 Evaluation gates++Before default rollout:++- labelled DER/JER with overlap-aware reporting;+- cpWER or speaker-attributed WER;+- merge/split counts and short-speaker recall;+- word conservation and boundary error;+- held-out sessions not used for threshold tuning;+- 8-, 30-, 60-, and 120-minute memory/cancellation measurements;+- time to final transcript on the minimum supported Mac no greater than+ `max(60 seconds, 0.10 * audio duration)`, with this target frozen before evaluation;+- no regression in plain Parakeet WER, capture safety, or dictation responsiveness.++Parity with the PyTorch reference is necessary but is not an accuracy measurement.++## 13. Implementation phases++All architecture and preview-contract work may proceed immediately. The production artifact swap and+full revalidation must complete before Phase 5 ships.++### Phase 0: model-release and dependency gates++1. Implement against the preview model contract without treating the preview artifact as final.+2. Track the production Nemotron release and replace the preview artifact when published.+3. Pin the exact FluidAudio revision and production model hashes.+4. Rerun conversion, mel, output, drift, and end-to-end parity against the production checkpoint.+5. Freeze a labelled development and held-out evaluation manifest.++Exit for shipping: the production checkpoint is pinned and all reproducible parity/baseline inputs+pass.++### Phase 1: canonical contracts, no behavior change++1. Add backend ID, descriptor, planning result, analysis manifest, canonical evidence, and typed errors.+2. Add the registry, an `activityPlusWords` fixture, and one final `diarizedWords` fixture.+3. Extract the product assembler boundary around existing finalization and safety rules.+4. Add backend contract tests for both final evidence profiles; explicitly reject incremental or+ provenance-free online-call evidence.+5. Keep the existing pipeline as the only production backend.++Exit: the current transcript is byte-equivalent through the new boundary, the evidence schema is+versioned, both valid final profiles validate, and invalid profiles fail closed. This does not claim+that a future provider SDK is already integrated.++### Phase 2: preparation ownership and immutable configuration++1. Add backend ID/configuration to `MeetingFinalProcessingConfiguration`.+2. Stop reading `SettingsStore.shared.selectedSpeechModel` inside an active run.+3. Generalize `MeetingASRPreparationOwner` into the sole backend preparation owner.+4. Wire progress, cancellation, activity lease, and model draining through production.+5. Version attempt lineage and checkpoints.+6. Migrate legacy checkpoints without a backend ID only to the hidden legacy backend; add+ missing-versus-unknown settings tests and recording-time readiness preflight.++Exit: a run is fully determined by its initial snapshot and cannot race settings or dictation model+changes.++### Phase 3: Nemotron host in FluidAudio++1. Add the eight-speaker Nemotron Sortformer variant/configuration.+2. Add exact output-name handling and state geometry.+3. Verify the native mel front end against NeMo.+4. Add cold/warm and multi-chunk parity tests.+5. Add bounded streaming file ingestion and cancellation points.+6. Keep all Nemotron-specific fields out of generic canonical evidence.++Exit: one synthetic and one labelled file match reference behavior within declared tolerances.++### Phase 4: composed local backend++1. Build stateful per-track/per-era Nemotron processing across durability chunks.+2. Produce canonical overlapping speaker activity.+3. Run pinned Parakeet TDT v2 word-timed ASR once per source chunk.+4. Align words and preserve all unassigned/ambiguous outcomes.+5. Pass evidence through the shared assembler and existing echo-safety policy.+6. Add manifest-level coverage reconciliation, cross-track echo suppression, era-local speaker IDs,+ the final word disposition ledger, and stage checkpoint maps.+7. Add deterministic retry, fallback-drain, and user-name invalidation tests.++Exit: complete local meeting transcripts pass functional, safety, and resource gates.++### Phase 5: default rollout++1. Register Parakeet+Nemotron as the default meeting backend.+2. Keep the legacy local backend hidden and allow only typed technical fallback.+3. Persist requested/actual backend lineage and surface fallback in diagnostics.+4. Run retained-meeting replay and held-out evaluation.+5. Remove the fallback only after stability and quality gates are met.++Exit: first-release local default uses the production Nemotron artifact and is stable, deterministic,+and recoverable.++### Phase 6: future hosted providers++For each provider separately:++1. Confirm current API, regions, pricing, limits, retention, and diarization/timing capabilities.+2. Implement one adapter and run the shared contract suite.+3. Add Keychain credentials and explicit audio-upload consent.+4. Add provider-specific idempotency, cancellation, and billing tests.+5. Register and expose the provider only when complete.+6. Add hosted descriptor metadata and, only if required by that provider, design a separate versioned+ incremental evidence protocol for partials/retractions. Do not retrofit revisions into v1 finals.++Do not change canonical persistence or product safety policy merely to accommodate a provider SDK.++## 14. Expected code areas++New meeting-specific files, names subject to implementation review:++- `MeetingTranscriptionBackend.swift`+- `MeetingTranscriptionBackendRegistry.swift`+- `MeetingTranscriptionEvidence.swift`+- `MeetingAnalysisManifest.swift`+- `MeetingTranscriptAssembler.swift`+- `ParakeetNemotronMeetingBackend.swift`+- `LegacyLocalMeetingBackend.swift`+- `MeetingTranscriptionPreparationOwner.swift`++Existing areas expected to change:++- `MeetingProcessingPipeline.swift`+- `MeetingProcessingConfiguration.swift`+- `MeetingModels.swift`+- `MeetingASRPreparationOwner.swift` (generalize or remove)+- `SpeakerDiarizationService.swift` (legacy adapter or replacement)+- `ASRService.swift` only at the narrow provider/model ownership boundary+- `SettingsStore.swift` and backup payloads+- Meeting Tools settings UI in a later provider release+- FluidAudio Sortformer model/configuration/inference/timeline files++## 15. Acceptance criteria++The architecture is ready when:++1. Parakeet+Nemotron is one selectable meeting backend while remaining two internally testable model+ components.+2. Dictation model selection cannot alter an active or future meeting backend unintentionally.+3. Well-formed final `activityPlusWords` and `diarizedWords` fixtures normalize without changing+ session persistence; the claim does not extend to a future provider's transport lifecycle.+4. Every backend word appears exactly once in the final presentation-time ledger as emitted or with+ one closed non-emission reason.+5. Provider labels never become cross-track or cross-meeting identities.+6. The topology-specific safety matrix is enforced: online-call processing retains separate track+ provenance, verified-AEC coverage is required for You, and cross-track echo duplicates are+ suppressed with explicit accounting.+7. Checkpoints reject any backend/model/configuration/input mismatch.+8. No local-to-cloud transition occurs without explicit user selection and consent.+9. Cancellation drains models/jobs and leaves no stale scratch or ownership state.+10. The production Nemotron artifact is pinned and passes conversion parity, labelled quality, and+ long-meeting resource gates.+11. Every admissible analysis-manifest interval is covered by evidence or a typed gap; unaccounted+ audio is a hard failure.+12. Cross-era speakers split by default and can only be reconciled by an explicit idempotent user+ merge in v1.++## 16. Adversarial review disposition++The draft was reviewed independently and read-only by Grok 4.6 and Claude Opus on 2026-09-12. Both+reviewers agreed that the coordinator/backend/canonical-evidence/assembler separation, meeting-only+backend contract, immutable planning, string-backed IDs, no implicit cloud fallback, sequential local+model loading, and production-artifact ship gate are sound.++Accepted changes from both reviews:++- prohibited online-call mixdown without recoverable per-track provenance;+- made coverage conservation start from the analysis manifest and end in a final word ledger;+- added cross-track echo-duplicate suppression and fail-closed AEC handling;+- made v1 cross-era identity explicitly split with user-only reconciliation;+- added piecewise clock-rate/offset/SRC/codec-delay mappings and uncertainty handling;+- constrained v1 evidence to two final-only profiles and deferred streaming revisions;+- made the assembler the sole product speaker-ID owner;+- replaced one global checkpoint stage with a backend/track/era/stage map;+- made fallback a fully drained new attempt with a closed allowlist and loop prevention;+- added recording-time readiness preflight, missing-vs-unknown setting migration, and device-local+ remote-job state;+- scoped fixtures to evidence-shape validation rather than claiming complete future-provider proof;+- added numeric latency/cancellation gates and tolerance-based local determinism.++One recommendation was deliberately tightened rather than copied: echo-only Nemotron slots do not+become product speakers after suppression, but they still consumed one of the model's eight raw slots+and therefore remain part of saturation detection.diff --git a/MEETING_TRANSCRIPTION_BRANCH_CODE_REVIEW_2026-09-14.md b/MEETING_TRANSCRIPTION_BRANCH_CODE_REVIEW_2026-09-14.mdnew file mode 100644index 00000000..dc5ff7b8--- /dev/null+++ b/MEETING_TRANSCRIPTION_BRANCH_CODE_REVIEW_2026-09-14.md@@ -0,0 +1,245 @@+# Meeting Transcription Branch Code Review++Date: 2026-09-14+Branch: `meeting/prd-capture-amendments`+Scope: committed diff against `origin/main` plus current tracked and untracked meeting-transcription work.++## Status++The branch is not merge-ready. The application target builds, but clean-checkout reproducibility,+audio durability, long-meeting processing, capability-aware backend selection, and the integration+test target need fixes before release.++No source changes were made during this review.++## P0 — Reproducibility blocker++### Ignored local FluidAudio dependency breaks clean builds++- `Package.swift:14-19` selects `.local-dependencies/FluidAudio`.+- `Fluid.xcodeproj/project.pbxproj:1252-1255` selects the same local package.+- `.gitignore:213-214` excludes the directory, and it contains no tracked files.+- A clean checkout or CI runner cannot resolve the dependency.++Strategic fix: publish the maintained FluidAudio changes and restore an immutable remote revision+and resolved pin before merging.++## P1 — Correctness and release risks++### Chunk ledger has no recovery consumer++- `MeetingAudioChunkWriter.swift:578-609` writes intent before an active chunk is represented in+ `track.json`.+- `MeetingSessionStore.swift:224-237` restores only chunks already listed in `track.json`.+- No production recovery path enumerates `chunk-ledger` records.+- A crash can orphan and omit up to the current 60-second chunk per track.++Strategic fix: reconcile ledger intent/checkpoint/terminal records and partial/final CAF files at+startup, with kill-point tests for every durability boundary.++### Ledger failure deletes authoritative PCM++- `MeetingAudioChunkWriter.swift:653-669` deletes an already finalized, verified, hashed and synced+ CAF if the terminal ledger write fails.+- A metadata/fsync/full-disk failure becomes irreversible loss of otherwise valid audio.++Strategic fix: quarantine the CAF in the session directory and repair or report it during recovery;+never delete the only capture-analysis asset because its metadata publication failed.++### Long two-track meetings exceed the backend cache++- `MeetingEpochAudioMaterializer.swift:90-94` defines a 64M-sample limit and claims it supports a+ one-hour two-track meeting.+- `MeetingParakeetNemotronBackend.swift:128-149` retains all materialized epochs across both tracks.+- Two one-hour 16 kHz analysis tracks contain 115.2M samples, crossing the cap after roughly+ 33–35 minutes of continuous online-call audio.+- Native slices, converted buffers and cached materializations also create large transient memory+ amplification.++Strategic fix: use bounded streaming or an immutable disk-backed materialization cache with+eviction between phases. Keep a per-window safety cap rather than a per-attempt full-meeting cap.++### Historical retry races the retention sweep++- `MeetingSessionCoordinator.swift:632-669` loads a historical session and awaits an audio lease+ before reserving or adopting it.+- `MeetingSessionCoordinator.swift:1063-1067` treats every non-active session as safe to sweep.+- An expired retry target can have its manifest cleared and audio removed while retry is suspended.++Strategic fix: reserve the session ID before the first suspension, make retention respect the+reservation, and revalidate the persisted session and files after lease acquisition.++### Capture-start deadline can still hang++- `MeetingCaptureEngine.swift:3842-3850` wraps the start sequence in a ten-second deadline.+- `MeetingCaptureEngine.swift:5966-5978` implements it with `withThrowingTaskGroup`.+- Exiting a structured task group cancels but still awaits a child that ignores cancellation.+- The deadline therefore cannot bound a wedged AVFoundation/ScreenCaptureKit operation.++Strategic fix: supervise the lifecycle operation behind an ownership fence, return the public+deadline independently, and join or quarantine the stale operation during controlled teardown.++### Diarization failure suppresses otherwise valid transcription++- `MeetingParakeetNemotronBackend.swift:237-266` excludes every Nemotron-failed epoch from the+ Parakeet ASR loop.+- A transient diarization failure therefore removes speech rather than merely losing attribution.++Strategic fix: run ASR for every materializable epoch and publish text with an unassigned speaker+plus explicit diarization-degraded evidence.++### Default backend is not architecture/capability aware++- `MeetingTranscriptionBackend.swift:19-24` makes Parakeet + Nemotron the unconditional default.+- `MeetingProductionParakeetNemotronRuntime.swift:175-198` always throws on non-arm64.+- `MeetingTranscriptionView.swift:1761-1765` nevertheless promises a plain transcript on Intel.++Strategic fix: choose the default from a capability policy, retaining the legacy implementation on+Intel or other unsupported configurations, and present truthful UI.++### Meeting backend readiness checks the wrong models++- `MeetingTranscriptionView.swift:1053-1059` derives readiness from the selected dictation model.+- It does not verify fixed Parakeet TDT v2 or the Nemotron artifact.+- `MeetingTranscriptionView.swift:2007-2009` opens Voice Engine, which cannot install Nemotron.+- The Nemotron installer/preparation step is intentionally timed with the Nemotron release, but+ backend-specific readiness must ship with it.++Strategic fix: expose one backend readiness/preparation contract covering architecture, Parakeet,+Nemotron, storage and actionable installation progress.++### Integration test target does not compile++- `MeetingTranscriptionBackendTests.swift:424` calls the now-throwing+ `BackupService.makeBackupDocument()` without `try`.+- `xcodebuild ... build-for-testing` fails at this line, so the meeting tests are not a valid gate.++Strategic fix: repair the test and make the clean dependency setup plus integration test build a+required branch check.++## P2 — Resilience, observability and incomplete architecture++### Post-transcription compression is not implemented++- `MeetingAudioChunkWriter.swift:729-741` always writes `playbackArchiveAsset: nil`.+- No AAC/archive producer exists.+- `MeetingAudioPresentation.swift:5-17` falls back to PCM indefinitely.+- PCM is currently retained at full size or deleted by retention; it is never replaced by a+ verified compressed archive after transcription and diarization.++Strategic fix: after the canonical sidecar and completed session are durably published, create and+verify the archive, atomically publish its asset metadata, and only then remove authoritative PCM.++### Persisted diarization identity is wrong++- `MeetingProcessingConfiguration.swift:39-47` defaults to the legacy diarization fingerprint.+- `MeetingModels.swift:1255-1259` identifies `FluidAudio-offline-v1` and community defaults.+- `MeetingProductionParakeetNemotronRuntime.swift:126-132` actually runs Nemotron using literal+ parameters `300`, `3`, and `0.25`.+- `MeetingProcessingPipeline.swift:1597-1601` persists the legacy fingerprint for the new backend.++Strategic fix: define a composite-specific fingerprint containing the FluidAudio revision, model+artifact/content digest and named Nemotron configuration constants.++### Model recheck does not authenticate weight content++- `MeetingNemotronModelLocator.swift:21-23,187-198` fingerprints model entries using path, size and+ modification time; only `Manifest.json` content is hashed.+- A same-size weight replacement with restored timestamps can pass recheck.++Strategic fix: validate weights against an installation-time or shipped expected content digest.++### History and retention scans repeatedly hash all PCM++- `MeetingSessionStore.swift:100-136` deep-reconciles every loaded session before filtering.+- `MeetingSessionStore.swift:342-387` streams SHA-256 over every ready PCM asset.+- Launch recovery and periodic retention sweeps can reread gigabytes of completed history.++Strategic fix: filter using the lightweight session manifest first, cache validated file identity,+and deep-verify only recovery/processing targets or files whose metadata changed.++### Failed attempts lose backend lineage++- `MeetingSessionCoordinator.swift:1546-1558` records only an error code when planning, readiness or+ runtime fails.+- `MeetingSessionCoordinator.swift:1924-1937` derives unstable-looking domain/code strings from+ `NSError` instead of stable backend failure tokens.++Strategic fix: persist backend ID, backend version and configuration fingerprint before planning,+and map failures to stable typed reason codes.++### Sidecar can be orphaned after cancellation++- `MeetingProcessingPipeline.swift:1550-1563` writes and verifies a result sidecar before its final+ cancellation check.+- Cancellation can leave that sidecar unreferenced by `session.json`.+- The stronger reviewer claim that this permanently poisons retries was rejected: coordinator+ retry closes the old attempt and creates a fresh attempt ID.++Strategic fix: journal/adopt verified sidecars during recovery or garbage-collect unreferenced+attempt artifacts safely.++### Real-model smoke test does not prove useful output++- `MeetingNemotronRealModelSmokeTests.swift:21-29` supplies sine tones rather than speech.+- `MeetingNemotronRealModelSmokeTests.swift:89-119` permits zero speaker activity and adds synthetic+ `smokeCompleted` entries to the failure map.++Strategic fix: retain this structural smoke test, but add an opt-in end-to-end speech fixture that+requires bounded non-empty diarization and real Parakeet output through release-style model paths.++## P3 — Cleanup and debt++- No active `Run in parallel` user setting or dormant parallel-processing flag was found.+ Nemotron and Parakeet are deliberately sequential to avoid simultaneous model residency. The+ resource bug is retained materialization, not an accidentally disabled parallel toggle.+- `MeetingLiveCaptionsConfiguration` in `MeetingProcessingConfiguration.swift:75-115` has no+ production consumer and contains an unresolved `main` model revision.+- Four final-processing feature booleans in `MeetingProcessingConfiguration.swift:32-35` are never+ populated by production and are rejected when enabled, despite appearing in fingerprints.+- Playback-archive schema/UI selection exists without an archive producer.+- Roughly 5,000+ lines of completed DEBUG-only meeting probes/autoruns remain connected to app+ startup. Move them to a diagnostics executable/test target when evidence collection is complete.+- Direct AEC3 is release-enabled as requested, but `MeetingCaptureEngine.swift:2696-2706` still calls+ it pre-production and retains the environment kill-switch TODO; the reason at lines 3055-3060+ still says `DEBUG direct AEC3`. Remove the escape hatch and stale labels after stability testing.+- The `chunk-ledger` directory remains after audio deletion because `deleteAudioFiles` removes+ `tracks/` and `checkpoint.json` only. It contains timing/path metadata rather than audio, but+ retention semantics should explicitly delete or retain it.++## External adversarial review++- Claude Opus agreed that the local dependency, non-compiling tests, destructive ledger failure,+ missing ledger recovery, retry/sweep race, unsupported default and ASR/diarization coupling are+ release blockers.+- Grok 4.6 agreed with the core findings and emphasized the broader systemic issue: several+ independent deletion authorities act on one authoritative PCM copy without one session-level+ lifecycle authority.+- Kimi K3 independently inspected the dependency and PCM/ledger paths and agreed with the central+ durability and default-backend findings.+- Kimi's claims that atomic writes, format versioning, checksums and disk-space admission were+ wholly absent were rejected after source verification; those mechanisms do exist.+- Phi was unavailable in both the configured router and installed OpenCode model catalog. No Phi+ review was fabricated.++## Validation performed++- `git diff --check`: passed.+- Unsigned Debug application build: passed.+- Integration `build-for-testing`: failed at `MeetingTranscriptionBackendTests.swift:424`.+- Signed test execution was unavailable because the current keychain lacks the configured Mac+ Development private key; this was kept separate from source findings.+- `swift test` is not the project test route and fails on the pre-existing SwiftPM executable source+ path mismatch (`Sources/FluidVoice` versus `Sources/Fluid`).++## Recommended repair order++1. Restore a reproducible pinned FluidAudio dependency and repair the test-target compile error.+2. Make PCM non-destructive: retain/quarantine on ledger failure and implement ledger recovery.+3. Fix retry/sweep ownership and the capture deadline.+4. Replace whole-attempt in-memory materialization with bounded/disk-backed processing.+5. Decouple Parakeet ASR success from Nemotron attribution success.+6. Add capability-aware default selection and backend-specific model readiness.+7. Add verified post-processing archive compression.+8. Correct fingerprints, failure lineage and recovery observability.+9. Remove or isolate completed diagnostics, inert configuration and stale labels.diff --git a/MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md b/MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.mdnew file mode 100644index 00000000..5778d28a--- /dev/null+++ b/MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md@@ -0,0 +1,449 @@+# Meeting transcription: implementation plan++Status: the canonical backend foundation, FluidAudio Nemotron runtime, and local Parakeet+Nemotron+composite backend are implemented and tested. Release dependency/model delivery and rollout remain.+Default: Parakeet TDT v2 + Nemotron diarization. Live captions retain Parakeet realtime.+Scope: local meeting backend now; Muse/Google adapters and cloud UI later.++This is the execution companion to `MEETING_TRANSCRIPTION_BACKEND_ARCHITECTURE_PLAN.md`.+Where the earlier design differs, the decisions here take precedence. It replaces speculative+requirements with explicit milestones. Shipping is scheduled with the production Nemotron release;+pin and revalidate that artifact at release time.++## 1. Reuse the existing abstractions++`MeetingProcessingControlling.process` remains the entry point used by `MeetingSessionCoordinator`.+`MeetingProcessingPipeline` remains the workflow owner. Do not add another coordinator with the same+responsibilities. `TranscriptionProvider` remains the ASR component interface.++Add `MeetingTranscriptionBackend` beneath the existing pipeline. It computes timed text and anonymous+speaker assignments. The local implementation composes Parakeet and a stateful Nemotron session;+future unified providers can return their own assignments through the same final-result contract.++The pipeline owns selection, activity ownership, input mapping, checkpoints and final publication.+The extracted `MeetingTranscriptAssembler` owns capture admission, existing echo policy, product+speaker IDs and conversion to `MeetingProcessingResult`. The session coordinator continues to save+the final session. Backends cannot bypass product policy or write session JSON.++```text+MeetingSessionCoordinator -> MeetingProcessingPipeline+ -> selected MeetingTranscriptionBackend+ local: TranscriptionProvider(Parakeet) + Nemotron session + aligner+ future: unified provider adapter+ -> MeetingTranscriptAssembler -> MeetingProcessingResult -> coordinator save+```++## 2. Minimal contract and ownership++Names below are proposed interfaces, not existing implementations.++- `MeetingBackendID`: stable string-backed identity; registry of compiled factories, not dynamic plugins.+- `MeetingBackendDescriptor`: identity/version, platform/languages, local or hosted execution,+ supported final-output precision, track topology and known model limits.+- `MeetingBackendRequest`: immutable attempt ID, configuration snapshot, manifest and access to its+ validated audio spans. No global settings or arbitrary session-directory access in the new backend.+- `plan(request)`: validates compatibility and returns an immutable plan before model work.+- `execute(plan, resume, stageSink, progress)`: returns final evidence. `stageSink` is an injected+ asynchronous checkpoint writer owned by the pipeline; it validates attempt generation and hashes,+ atomically persists a stage, and acknowledges completion. Backends never write checkpoints directly.+- Each backend instance owns and drains its executors and models before returning or throwing.+ Final evidence may reference protected immutable stage files rather than copy an entire meeting+ into memory. Execute must await `stageSink` acknowledgements for every referenced stage before+ returning. References are temporary assembly inputs, never pointers in the durable result sidecar.+ Their lifetime ends only after the self-contained result sidecar and session are saved or the+ attempt is cleaned up.++Progress is advisory and bounded; a checkpoint acknowledgement is a separate durable operation.+The pipeline rejects late stage callbacks from a cancelled/superseded generation. Final publication+requires the complete acknowledged stage set and a current generation. Cancellation waits for+in-flight writes/inference, retains acknowledged canonical stages, discards unacknowledged data,+and then releases ownership. Explicit cancellation never publishes a result or starts fallback.++The final-output contract has timed text units (word or utterance), each with a stable source ID,+analysis-span references, precision, anonymous speaker assignment or ambiguity, and provenance.+Speaker activity is optional evidence; no synthetic word times or fake confidence are created for a+provider that only returns utterances. The local aligner runs once inside the local backend. The+assembler does not reassign provider words by rerunning a diarizer.++V1 is final-only. Future adapters may reconcile streaming revisions internally; live incremental+speaker captions will require a separate contract. Two fixture adapters exercise local aligned words+and already-diarized utterances. They prove result compatibility, not future API/network behavior.++## 3. Input, safety and identity rules++Build a source manifest from finalized chunks, with source-file offsets, valid decoded samples,+source PTS, track identity, protection metadata, discontinuities and existing content hashes.+Maintain explicit source -> analysis -> presentation mappings; apply existing VPIO clock correction+once, not again after alignment. Account for actual decoder priming and resampling behavior rather+than guessing a universal AAC delay. Unknown clock-fit data is recorded as unknown, not fabricated.++Keep app and mic streams separate in online calls. Reject future plans that require mixing them and+lose track attribution. A word may reference multiple adjacent files on the same track, but never+bridge a missing/inadmissible span. Split untimed utterance boundaries only with real timing evidence;+otherwise reject the whole affected utterance with a coverage reason.++Use one diarizer state across contiguous admissible durability files. Define a separate+`analysisEpochID`: start a new epoch for missing/unreadable audio, a real clock discontinuity,+microphone-device replacement or an inadmissible microphone interval. Apply the capture admission+mask before feeding Nemotron; unsafe audio must not update its speaker cache. V1 drains and resets+after such a hole rather than assuming skip-frame state remains valid. Metadata changes alone do+not reset an epoch if input remains continuous and admissible. Retain gaps in presentation mapping.+V1 does not automatically merge identities across epochs. Label continuity is a model property to+evaluate, never proof of identity.++Preserve the existing mode-specific admission contract: admitted headphones/acoustically closed,+VPIO-protected and attested AEC3 eras remain usable. For new online-call unsafe microphone intervals,+exclude text from normal transcript/export and record `inadmissibleCaptureEra`; calling it Unknown+does not make it admissible. Retain legacy-era behavior only through the existing explicit legacy+compatibility policy. In-room mic audio does not require echo protection.++Apply the current signal/text echo policy after time mapping. Matching text alone cannot prove echo:+include fixtures where the local person genuinely repeats the remote person. Suppressed mic copies+get a disposition; app copies remain. Residual echo detected after ASR may already have affected+Nemotron state; do not claim that postprocessing can undo it. Exclude echo-only tokens from product+speaker/identity evidence and evaluate future assignment quality on residual-echo fixtures. AEC+protection indicates audio safety, not who owns the voice.++Only the assembler creates product speaker IDs, scoped to attempt, track, analysis epoch and token.+No cross-track equality by slot, no use of Nemotron pre-encoder features as speaker embeddings.+The new backend identifies at most one You only with explicit product identity evidence, such as a+user assignment; otherwise anonymous mic speakers remain available with Unknown identity. Do not+copy the legacy prototype-dependent You election with empty/fabricated embeddings. Keep legacy+election unchanged in the legacy adapter and make this deliberate new-backend behavior visible.++The eight-slot model cannot reliably announce a ninth unseen voice or slot reuse. Display its limit,+test more-than-eight-speaker fixtures, and report measurable slot occupancy as a warning only.+Do not claim guaranteed overflow detection or automatically merge/switch engines based on count.++## 4. Coverage, result persistence and retry++The pipeline maintains receipts per requested input span: processed (including no speech), failed,+skipped or inadmissible. The assembler compares these receipts with the manifest independently of+returned text. This detects missing work; it cannot prove an ASR model recognized every spoken word.+Every recognized text-unit ID has exactly one final disposition: emitted, ambiguous-unassigned,+outside-activity, echo-suppressed, inadmissible, or rejected for invalid timing. Backend truncation+also creates a span-level coverage gap; no invented word represents missing audio.++Persist a versioned result sidecar containing the disposition ledger, ambiguity candidates and+coverage receipts. Session JSON stores its schema/hash/reference and the normal transcript segments.+Ambiguous admitted text renders once as an unassigned segment, so it remains visible in normal+transcript/export. Excluded unsafe/echo text is not resurrected by sidecar export. New fields decode+optionally for old sessions. Sidecar retention/deletion follows its session, not scratch cleanup.++Disposition precedence: validate timing/provenance first and quarantine invalid units from normal+output (no interval arithmetic on invalid bounds); for valid units use inadmissible-capture-era,+then echo-suppressed, outside-activity, ambiguous-unassigned, then emitted. If an indivisible unit+touches an excluded interval, exclude that whole unit and record its admissible portion as incomplete+coverage. Split only with real timing evidence. The same rule applies to words and coarse utterances.+In-room mode bypasses online-call echo admission. Test mixed-safe/unsafe and ambiguous-plus-echo+utterances so ambiguity cannot override exclusion.++Use attempt-scoped checkpoint maps with activity per track/analysis epoch and ASR text per chunk.+Store canonical results, not Nemotron cache embeddings. Mid-epoch interruption therefore replays+that epoch from its beginning, while finished epochs and ASR chunks can resume. Do not promise+arbitrary mid-epoch resume or small replay cost.++The assembler materializes a self-contained sidecar from acknowledged stages, streams it to bounded+storage, and verifies its checksum before the coordinator saves the session reference. No final+sidecar points at disposable stage files. Keep checkpoints until that session save succeeds.+Stage/result writes are atomic and checksummed. On crash, resolve staged/unreferenced files using+the attempt journal; source recordings and the last saved transcript are never overwritten by a+partial attempt. Final publication verifies the attempt is still current, preventing late completions.++Fingerprint actual backend/version, all local model hashes, effective preprocessing/postprocessing,+language, mapping and admission policy, source content hashes, and processing-contract version.+Use stored hashes for identity and verify content when reading; a stored digest alone does not prove+the file is still intact. Retry using acknowledged immutable activity evidence preserves its IDs and+explicit aliases. If an unfinished epoch must be replayed, allocate a new epoch-evidence generation+and invalidate that epoch's speaker tokens/aliases with a visible notice. Include evidence generation+in speaker keys; resumed ASR text-unit IDs can remain stable. Recomputed slots never inherit aliases+just because an ordinal or attempt ID repeats.+Reprocessing with changed settings/backend gets a new attempt; retain old user corrections with the+old result and never transfer them by speaker ordinal. Old checkpoints resume only if their actual+ASR configuration and full fingerprint are representable; otherwise restart explicitly.++V1 legacy backend is a manual rollback/development choice. Automatic runtime fallback is deferred:+it adds checkpoint and identity races without helping the first integration. A failed attempt keeps+recoverable audio and reports a typed failure. No automatic local-to-cloud path exists.++## 5. Model delivery and FluidAudio work++The DMG contains runtime code and a pinned manifest; download weights separately before processing.+FluidVoice owns model readiness, download progress, cache lifetime and atomic installation. FluidAudio+accepts a validated local model URL and owns inference/preprocessing/session state. It does not own+FluidVoice settings, downloads or UI.++Download/readiness is a separate user-visible preparation step before `plan` succeeds. The plan+contains handles to validated pinned artifacts; `execute` performs no downloads. Recheck artifacts+when opening them, and report missing/changed artifacts as a readiness error. For the first local+backend use the existing meeting Parakeet v2 English policy with vocabulary boosting, pronunciation+matching, dictionary rewriting and unified-final features disabled; reject unsupported requested+options explicitly. Multilingual or enhancement options need later model/evaluation support.++Develop in a maintained FluidAudio checkout/branch, never Xcode DerivedData. Pin the resulting commit+in both Xcode and Swift package configuration. Generalize speaker geometry without altering existing+four-speaker Sortformer defaults, or add a dedicated Nemotron host where differences warrant it.+The compiled public API must expose begin/process/finish/reset and explicit state ownership; generic+`processComplete(file:)` resetting for each file cannot implement this workflow.++Before host implementation, inspect the actual CoreML artifact and NVIDIA reference to freeze input+dtypes/shapes, cache geometry, valid-region slicing, activation semantics, left/right contexts,+mel stride and output temporal resolution (including any high-resolution head). The local README+and validation notes disagree on several details. `pred_score_threshold=0.25` in a cache/parity script+does not establish the product activity onset/offset threshold. Freeze both separately from reference+inference configuration and labelled evaluation. Verify the graph already returns probabilities.++Download manifest includes immutable revision, hashes, archive byte limits, supported OS/architecture,+model contract and preprocessing version. Prefer a validated `.mlpackage` compiled locally into a+versioned `.mlmodelc` cache initially; use precompiled distribution only after target OS/architecture+compatibility tests pass. Protect archive extraction against traversal/symlinks and excessive expansion.+Retain the old known-good version until validation and atomic activation complete. Model downloads+are network operations; meeting inference remains local after installation.++## 6. Reviewable implementation sequence++| Change | Deliverable / primary files | Exit condition |+|---|---|---|+| A. Contracts and legacy wrapper | Backend/registry types; existing `MeetingProcessingControlling` and `MeetingProcessingPipeline`; wrap `SpeakerDiarizationService` | Existing golden transcripts, IDs, echo decisions and retry behavior preserved; final-word and utterance fixtures accepted; malformed evidence rejected |+| B. Immutable meeting selection and ownership | `MeetingProcessingConfiguration`, `MeetingASRPreparationOwner`, narrow `ASRService` factory, `SettingsStore`, meeting readiness UI | Dedicated setting independent of dictation; attempt snapshots immutable; cancellation drains; missing/unknown IDs and old settings migrate explicitly |+| C. Timeline and durable evidence | Analysis manifest, assembler, result sidecar, `MeetingModels`, coordinator save/retry/export | Gaps, priming and rate mapping tested; word ledger persisted; crash between sidecar/session save recovers; old sessions decode; unsafe mic text excluded |+| D. FluidAudio Nemotron host | Maintained fork Sortformer/Nemotron runtime and reference fixture tests | Actual artifact contract pinned; mel and cold/warm multichunk parity pass; original Sortformer regression tests pass |+| E. Composite backend and downloader | `ParakeetNemotronMeetingBackend`, local model manifest/download integration | One Nemotron state per analysis epoch; unload then dedicated Parakeet ASR; word alignment; separate tracks and epoch retry verified |+| F. Default and release validation | Meeting backend default, production checkpoint pin, meeting model readiness | Held-out speaker/word quality and resource gates pass; app packages runtime only; installed model works offline |++A precedes B and C. D may proceed independently after the model-contract audit. E depends on B/C/D;+F depends on E and production-artifact revalidation. Preserve general dictation and standalone file+transcription behavior. Keep the first extraction small; required result-schema changes belong in C,+not the output-equivalent A refactor. Each change has its own review and focused regression checks.++B migration table: an absent preference resolves to the legacy wrapper through A–E and to the local+composite only in F. An explicit supported choice is honored; unknown/unavailable IDs remain+unavailable and never silently choose a backend. During A–E the composite is an explicit development+choice. F alone changes the default for new attempts; existing attempts retain their snapshot.+Preserve the actual selected ASR on legacy checkpoints where representable, otherwise restart with+an explicit notice rather than relabeling old results as Parakeet v2.++C makes the manifest the only new source-to-presentation mapper. Remove the corresponding legacy+de-drift application when switching that adapter to mapped evidence; never apply both. A may wrap+the existing final times as an explicit temporary compatibility path. Regression tests at C verify+unchanged timestamps/echo windows for that legacy path, not only A's initial goldens.++D/E isolation exits: two test sessions cannot share mutable diarizer state; preparation/drain leaves+dictation/file-transcription executors untouched; at most one local meeting model is resident in the+measured loaded-set sequence; missing weights fail at readiness with no download during inference.++The coordinator retains the existing exclusive meeting activity policy for v1. Requests to start+dictation during final processing remain blocked with the existing UI behavior. Do not implement+preemption in this refactor: automatic pause/unload/resume needs a separate product decision and+would otherwise repeatedly replay long Nemotron epochs. Own dedicated meeting model instances;+reuse cached weight files, not mutable dictation executors. Loaded-set sequence is none -> Nemotron+-> drained -> Parakeet -> drained. Preparation may validate both artifacts without loading both.++## 7. Acceptance and future extension++- Golden legacy outputs and file/dictation tests pass after extraction; new behavior tested separately.+- Reference audio features and CoreML predictions match declared tolerances over cold/warm/long runs.+ Digital impulse fixtures test the audio mapper only; annotated speech tests ASR/diarizer timing.+- Speaker continuity across 60-second boundaries, actual discontinuities, headphones transitions,+ eight and more-than-eight speakers, short interjections, overlapping/repeated speech are evaluated.+- Every planned span has a receipt, every recognized text unit a disposition, and unassigned admitted+ text remains visible. Test silent spans, missing results, corrupt audio and provider truncation.+- Cancellation is checked between bounded model calls; stale completions cannot save a result or+ unload a newer operation. Measure wall-clock drain and replay cost, including mid-epoch cancellation.+- Test 8/30/60/120-minute sessions on the named minimum supported Apple Silicon Mac. Before F,+ record hardware and freeze numeric p95 time-to-transcript, peak RSS, cancellation and disk budgets+ from baseline measurements. Do not claim a guessed 10x speedup as a verified product requirement.+- Held-out DER, speaker-attributed WER, merge/split counts and short-speaker recall must beat the+ selected legacy baseline targets established before tuning; plain ASR WER must not regress.+ Speaker count agreement alone and conversion parity alone are insufficient quality gates.++Later Muse/Google adapters implement the same final evidence contract using separate inputs for+online calls. Recheck actual APIs and support timed utterances when word precision is unavailable.+Keep backend selection separate from dictation; v1 shows local model readiness, later releases add+a provider picker plus credentials/consent. Cloud transfer, auth refresh, idempotency, regional+processing, deletion and incremental captions remain future adapter work with dedicated tests.++## 8. Review record++The longer architecture draft previously received direct Grok 4.6 and Claude Opus reviews.+This companion received a fresh orchestrate `standard` review served by Grok 4.6 (143.8 seconds).+The reviewer assessed the full inline plan and reported five P1 and three P2 findings. Its verdict+applied to the pre-revision draft, not the corrected document.++| Finding | Disposition |+|---|---|+| P1: durable sidecar might retain disposable stage references | Accepted: self-contained sidecar, checksum verification, session save before stage cleanup |+| P1: backend could return before asynchronous stage acknowledgements | Accepted: execute/publication require full acknowledged stage set; late generations rejected |+| P1: coarse words/utterances lack exclusion precedence | Accepted with correction: validate bounds before interval rules, then conservative whole-unit disposition; no fabricated word timing |+| P1: excluded mic audio can contaminate speaker state | Accepted for known admission gaps: mask before inference and reset epoch; post-ASR echo cannot retrospectively be removed from model state and remains an evaluation risk |+| P1: default might change before rollout gates | Accepted: absent preference stays legacy through A–E; F is the only default switch; unknown values stay unavailable |+| P2: legacy and manifest could both correct timestamps | Accepted: one mapping owner and timestamp goldens at C |+| P2: epoch replay might attach old aliases to new slots | Accepted: epoch-evidence generation invalidates replayed tokens; immutable completed evidence retains aliases |+| P2: model isolation and downloads lack testable exits | Accepted: dedicated state, measured resident model set and zero execute-time downloads |++The router's tree-change flag was true because the main agent updated the architecture-document+header while review ran. Final repository checks showed no tracked source changes. The requested+review was plan-only. A reviewed plan is not an implementation or an end-to-end validation result.++## 9. Implementation progress — 2026-09-12++Completed implementation slice:++- Stage A: production pipeline dispatches through an injectable backend registry. Legacy algorithms+ remain available through an explicit compatibility/rollback backend.+- Canonical word/utterance evidence and structural validation are present. Registered canonical+ fixture backends now pass through C2 assembly/publication; the production registry remains+ legacy-only. No fake model output or fabricated timestamps.+- Registry identity, request/plan scope and legacy callback binding are checked before execution.+- Cancellation before execution and after a non-cooperative backend returns suppresses publication;+ tests prove that the serialization lease is released for the next attempt.+- B1: a dedicated persisted meeting-backend preference is resolved once per processing attempt.+ Missing settings choose the named production default; unknown IDs remain unknown. Injected registries and explicit+ overrides retain precedence. Tests prove a setting change cannot switch an executing attempt.+- B2a: `ASRService.withPreparedMeetingASR` now owns fixed Parakeet-v2 preparation under the exact+ meeting activity lease, retires dictation providers without deleting disk caches, serializes+ meeting inference on a dedicated executor, defers handback lease release until drain, and joins+ an owned scope body during termination. Parent- or shutdown-driven cancellation suppresses a+ non-cooperative body's late success. Dictation readiness/download entry points reject while the+ meeting claim is active. The meeting backend preference is included in backup/restore; missing+ legacy backup values migrate to the phase default and unknown IDs round-trip unchanged.+- C1: canonical backend evidence has an explicit fail-closed Codable schema. A separate versioned,+ self-contained result sidecar defines the closed text-unit disposition ledger and span coverage+ receipts without scratch references. Its session-confined store publishes a 0600 same-directory+ temporary file atomically, makes each attempt's stable sidecar immutable (byte-identical retries+ join; conflicts fail), hashes and reads back the payload, and verifies reference format, byte+ count, checksum, attempt and backend on every read. It is intentionally not referenced by+ `MeetingSession` or accepted by the pipeline until the manifest/assembler publication transaction+ exists. Structural tests cover schema/enum failures, ledger conservation, ambiguity, timing+ quarantine, source/epoch bounds, tampering, path/symlink escape and overwrite conflicts.+- C2a: a versioned analysis manifest, frozen-plan projection, real chunk observation boundary and+ builder now map each planned `(track, chunk)` into an exact cover of admissible spans and typed+ gaps. The observer confines paths, rejects symlinks, rechecks bytes/SHA-256 and reads actual+ AVFoundation format/frame facts; codec priming remains explicitly unknown when the decoder does+ not report it. The builder preserves separate app/mic analysis streams, splits within chunks at+ capture-era and discontinuity boundaries, applies the existing era-local de-drift transform once,+ resets diarizer epochs only for recorded causes, and represents short decoded audio with a backed+ prefix plus an explicit trailing gap. Canonical online-mic admission is positive-proof only;+ in-room mic and application audio follow their distinct rules. This contract remains unwired.+- C2b1: canonical evidence now uses exact analysis-span references and per-track analysis time. The+ pure shared assembler reconciles span receipts independently of text, rejects text that overlaps+ failed/skipped/truncated work, applies echo/activity/ambiguity precedence, maps through the+ manifest once, mints attempt+track+epoch+generation-scoped speaker IDs, and produces deterministic+ segments plus a complete disposition ledger. Invalid/non-finite evidence is durably quarantined;+ sidecar ordering and disposition reasons are canonical and fail closed.+- C2b2: backend plans freeze a legacy-versus-canonical result contract. Canonical execution receives+ the product-owned manifest, obtains echo decisions from a separate fail-closed product provider,+ assembles off the main actor, writes/fsyncs/read-verifies an immutable sidecar containing the full+ manifest, and returns its reference only after cancellation checks. The coordinator saves that+ reference, transcript, lineage and durable completeness together before checkpoint deletion; a+ failed save restores the previously published transcript/reference and leaves the new sidecar+ unreferenced. Legacy execution builds no manifest, requests no echo evidence and writes no+ sidecar. It remains the default/rollback backend.+- D runtime host: the independent FluidAudio branch now adds eight-speaker configuration, strict+ CoreML shape/dtype validation, Float16 decoding, caller compute configuration, local model loading,+ an immutable model-family mel contract, NeMo-valid frame counting, complete-file core-tail+ processing, and guarded FIFO/speaker-cache progression. Source/test changes are preserved in+ `tools/patches/fluidaudio-nemotron-compatibility.patch`.+- E local composite: `MeetingParakeetNemotronBackend` is registered as a selectable canonical+ backend. It materializes verified 16 kHz epoch audio, runs fresh Nemotron state per track/epoch,+ drains Nemotron before one attempt-wide prepared Parakeet scope, maps both model timelines through+ actual resampled span ranges, emits exact receipts/evidence, performs causal word-context echo+ filtering, and publishes turn-sized product segments while retaining word evidence in the sidecar.+ Model lookup supports an injected path, a development environment override and a versioned local+ cache; no hosting URL is guessed and weights are not bundled.++Verification:++- App: 135 selected backend, recovery, global-speaker-stitching and coordinator tests passed in the+ Stage A/B1 pass. A later focused B2a run passed 52 backend/preparation/scope tests, including+ non-cooperative preparation/body cancellation, termination join, deferred lease release, fixed+ provider policy and backup migration.+- App after C1 review fixes: 72 selected sidecar, backend, preparation and scope tests passed with+ zero failures. The new persistence code adds no Swift actor-isolation warnings; existing project+ warnings remain outside this slice.+- C2a focused manifest + C1 sidecar + backend suite: 50 tests passed with zero failures after parent+ fixes for throwing-map compilation, EOF hashing, partial-decoder coverage and mid-chunk+ discontinuity epoch splitting.+- Final C2 publication/assembler/sidecar/manifest/backend/recovery selection: 181 tests passed with+ zero failures after parent and adversarial-review fixes.+- FluidAudio: the 67-test Sortformer/legacy integration selection passed. The 10-test Nemotron suite+ also passed with the supplied CoreML model loaded and run end-to-end across one fixed window plus+ its final core tail. Model-quality and performance measurement are accepted from the completed+ model-validation work and are not repeated here.+- Dependency patch passes reverse-apply validation against its local checkout.+- Composite integration selections: 228 tests passed, one opt-in real-model test skipped, zero+ failures. The opt-in real-model smoke test separately passed with the supplied `.mlpackage`.+- Grok 4.6 adversarial reviews through orchestrate identified cancellation/request binding and+ model-geometry/overflow gaps. Routed corrections plus parent integration/test fixes address them.+ A final scoped Grok review of selection/cancellation completed successfully (180 seconds) and+ found no remaining actionable regressions in that contract. This does not cover unfinished+ assembly, model-preparation or end-to-end parity work.+- The B2a review dispatch was attempted through orchestrate and direct Grok 4.6; both repeatedly+ exhausted the Grok CLI turn limit after reading the files without returning a verdict or editing+ the tree. Direct Claude fallback was unavailable because its account session limit was exhausted.+ Parent review found and fixed shutdown/body ownership and late-success cancellation gaps, but this+ slice therefore still needs an independent adversarial verdict when either review channel recovers.+- C1 implementation ran through authorized Fireworks Kimi K3 after the configured router exposed+ only Claude implementation tiers. A separate review-only Kimi session found no P0/P1 issues and+ two P2 durability defects: overwriting an already-referenced same-attempt result and publishing+ the stable filename before tightening permissions. Parent fixes make attempt results immutable and+ publish only a permission-tightened temporary file; the same pass also applied the review's+ mapped-read, schema-separation, epoch/chunk and comment corrections. Streaming serialization and+ descriptor-relative TOCTOU hardening remain later C work.+- C2a implementation used the user-authorized orchestrator heavy route. Its MCP response timed out,+ but the underlying Claude worker completed the manifest/observer/builder files; parent review+ supplied the missing tests and fixed four reproduced defects. Adversarial review was dispatched+ through both standard and heavy orchestrator routes without tree edits; the standard route ended+ task-failed after reading, and the heavy worker's verdict was lost when the MCP transport expired.+ A bounded retry was unavailable because both recipients entered cooldown; the later read-only+ Kimi C2a+C2b1 review supplied the missing visible verdict.+- C2b implementation used Fireworks Kimi K3 through OpenCode at the user's direction. Two separate+ read-only Kimi adversarial passes reported no P0s. Accepted findings fixed text emitted from+ non-processed receipt regions, missing epoch-evidence generation, invisible quarantine+ completeness, canonical skips poisoning future plans, failed saves persisting a new result under+ `.failed`, main-actor assembly, unchecked echo targets, non-durable rename, non-self-contained+ span references and misleading coverage event/reason labels. The production priming finding is+ accepted as a release blocker; it is not "fixed" by guessing zero.+ Rejected review claims: moving attempt-ID selection outside the gate cannot reread newer state+ because the input session is a value snapshot; Float32 input validation already existed; fixed+ model dimensions were incorrectly described by one review as mutable.+- D frontend/state implementation was attempted through the orchestrate router, but dispatch was+ rejected because the configured fallback could cross to an unapproved recipient. The scoped work+ proceeded through authorized Kimi K3. A read-only adversarial pass verified the frontend, tail,+ prediction-slicing and cache-cadence contracts; its two P3 hardening findings were fixed. A full+ legacy integration run then exposed and drove the fix for model-family framing isolation.+- E implementation was attempted through the orchestrate standard route, but its automatic Claude+ fallback was rejected by the source-disclosure boundary. Authorized Kimi K3 produced the scoped+ implementation; parent review fixed a cross-module generic witness crash, decoder short reads,+ span-resampling time mapping and artifact binding. A later read-only Kimi adversarial pass found+ no P0s. Accepted findings fixed future-audio echo suppression, word-per-row product publication,+ cancellation checks between materialization/model calls, duplicated activity policy and the+ hash/open/read race. The local dependency override remains a P1 merge blocker until a maintained+ FluidAudio fork revision is published and pinned.++Still open:++- Model delivery: add recording-time readiness UI/preflight and the pinned hosted artifact manifest.+- C3: acknowledged per-stage checkpoint maps, attempt journal/orphan-sidecar reconciliation, bounded+ streaming sidecar serialization and sidecar-aware export/recovery verification.+- D release step: commit the completed FluidAudio runtime work to the maintained fork and pin it.+- E release step: replace the development-only local FluidAudio override with the maintained-fork+ revision in both SwiftPM and Xcode. The current override is intentionally not merge-ready.+- F release remainder: production-artifact identity pin. The default rollout now selects the local+ Parakeet + Nemotron composite. Existing model validation is accepted; no new quality/performance+ benchmark is planned.++The supplied folder contains the CoreML packages, conversion scripts and copied NeMo source needed+to implement the runtime contract. The original `.nemo` and numerical fixtures are not required for+the remaining application integration because the separate model-validation work is accepted. The+The development workspace uses the maintained local FluidAudio checkout. A clean clone cannot use+that ignored path, so the fork commit/revision pin is required before these changes are committed.++The production observer truthfully records `.unknown(.decoderDidNotReport)` when decoder/container+priming is unavailable. The accepted model-validation decision permits the Stage F default switch;+the legacy backend remains registered as an explicit rollback selection.++Execution interruption: the router's heavy implementation entry reported a Claude session limit+resetting at 2:30 p.m. Pacific. Grok implementation calls reported failure; a late B1 preference+patch nevertheless arrived and was reconciled, compiled and tested by the parent. Grok read-only+snapshot reviews did succeed. No commit, push or app reinstall performed.diff --git a/Package.resolved b/Package.resolvedindex d267136b..ec5c8120 100644--- a/Package.resolved+++ b/Package.resolved@@ -27,14 +27,6 @@"version" : "1.4.1"}},- {- "identity" : "fluidaudio",- "kind" : "remoteSourceControl",- "location" : "https://github.com/altic-dev/FluidAudio.git",- "state" : {- "revision" : "3fd63887eef1dc25edea8263ce4b44aa854d898b"- }- },{"identity" : "foundation","kind" : "remoteSourceControl",diff --git a/Package.swift b/Package.swiftindex a6302752..9579fe84 100644--- a/Package.swift+++ b/Package.swift@@ -11,12 +11,12 @@ let package = Package(dependencies: [.package(path: "Vendor/WebRTCAudioProcessing"),.package(url: "https://github.com/mxcl/AppUpdater.git", from: "1.0.0"),- // Diarization evaluation and checkpoints depend on exact clustering behavior.- // Keep this immutable and update it only with a reviewed before/after evaluation.- .package(- url: "https://github.com/altic-dev/FluidAudio.git",- revision: "3fd63887eef1dc25edea8263ce4b44aa854d898b"- ),+ // INTERIM local override (Stage D/E development): the Nemotron runtime work exists only+ // in this checkout. Before release this MUST be replaced by a maintained-fork+ // commit/revision pin (see MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md, "D release+ // step"). Diarization evaluation and checkpoints depend on exact clustering behavior;+ // the fork pin stays immutable and changes only with a reviewed before/after evaluation.+ .package(path: ".local-dependencies/FluidAudio"),.package(url: "https://github.com/mxcl/PromiseKit", from: "6.0.0"),.package(url: "https://github.com/altic-dev/DynamicNotchKit.git", branch: "main"),.package(url: "https://github.com/altic-dev/transcribe-cpp-swift.git", exact: "0.1.2"),diff --git a/Sources/Fluid/Persistence/BackupService.swift b/Sources/Fluid/Persistence/BackupService.swiftindex 0fe5f1f9..555f3c1f 100644--- a/Sources/Fluid/Persistence/BackupService.swift+++ b/Sources/Fluid/Persistence/BackupService.swift@@ -21,6 +21,8 @@ struct SettingsBackupPayload: Codable, Equatable {let selectedCohereLanguage: SettingsStore.CohereLanguagelet selectedNemotronLanguage: SettingsStore.NemotronLanguage?let selectedAppleSpeechLocaleIdentifier: String?+ /// Stable final-meeting backend ID. Optional so backups from before backend selection decode.+ let meetingTranscriptionBackendID: String?let hotkeyShortcut: HotkeyShortcut// Older backup files only contain hotkeyShortcut; nil restores that legacy single shortcut.// swiftlint:disable:next discouraged_optional_collectiondiff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swiftindex 57eef338..081cde59 100644--- a/Sources/Fluid/Persistence/SettingsStore.swift+++ b/Sources/Fluid/Persistence/SettingsStore.swift@@ -1954,6 +1954,24 @@ final class SettingsStore: ObservableObject {}}+ /// Which meeting transcription backend final processing should use.+ ///+ /// An absent preference resolves to the current production default. A stored value is handed+ /// through verbatim, including an ID this build does not know: the pipeline rejects an unknown+ /// selection loudly rather than quietly transcribing with a different backend than the one+ /// that was chosen. An explicit legacy selection therefore remains a reliable rollback switch.+ var meetingTranscriptionBackendID: MeetingBackendID {+ get {+ guard let raw = self.defaults.string(forKey: Keys.meetingTranscriptionBackendID)+ else { return .productionDefault }+ return MeetingBackendID(rawValue: raw)+ }+ set {+ objectWillChange.send()+ self.defaults.set(newValue.rawValue, forKey: Keys.meetingTranscriptionBackendID)+ }+ }+/// Tier 1 native (Zoom/Teams/Webex) meeting auto-detection (default: ON).var meetingAutoDetectEnabled: Bool {get {@@ -3329,6 +3347,7 @@ final class SettingsStore: ObservableObject {selectedCohereLanguage: self.selectedCohereLanguage,selectedNemotronLanguage: self.selectedNemotronLanguage,selectedAppleSpeechLocaleIdentifier: self.selectedAppleSpeechLocaleIdentifier,+ meetingTranscriptionBackendID: self.meetingTranscriptionBackendID.rawValue,hotkeyShortcut: self.hotkeyShortcut,primaryDictationShortcuts: self.primaryDictationShortcuts,promptModeHotkeyShortcut: self.promptModeHotkeyShortcut,@@ -3461,6 +3480,11 @@ final class SettingsStore: ObservableObject {if let selectedAppleSpeechLocaleIdentifier = payload.selectedAppleSpeechLocaleIdentifier {self.selectedAppleSpeechLocaleIdentifier = selectedAppleSpeechLocaleIdentifier}+ // A backup predating this setting represents an absent selection, which resolves to the+ // current phase's local default. Unknown stored IDs remain intact and visibly unavailable.+ self.meetingTranscriptionBackendID = payload.meetingTranscriptionBackendID.map {+ MeetingBackendID(rawValue: $0)+ } ?? .productionDefaultself.primaryDictationShortcuts = payload.primaryDictationShortcuts ?? [payload.hotkeyShortcut]self.promptModeHotkeyShortcut = payload.promptModeHotkeyShortcutself.promptModeShortcutEnabled = payload.promptModeShortcutEnabled@@ -5504,6 +5528,7 @@ private extension SettingsStore {static let preferredOutputDeviceUID = "PreferredOutputDeviceUID"static let meetingRecordingDefaults = "MeetingRecordingDefaults"static let meetingAudioRetentionPolicy = "MeetingAudioRetentionPolicy"+ static let meetingTranscriptionBackendID = "MeetingTranscriptionBackendID"static let meetingAutoDetectEnabled = "MeetingAutoDetectEnabled"static let meetingAutoDetectBrowserEnabled = "MeetingAutoDetectBrowserEnabled"static let microphoneSelectionMode = "MicrophoneSelectionMode"diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swiftindex b2ccd615..cfa238a7 100644--- a/Sources/Fluid/Services/ASRService.swift+++ b/Sources/Fluid/Services/ASRService.swift@@ -621,6 +621,20 @@ final class ASRService: ObservableObject {private var deferredMeetingRouteRecoveryReason: String?private var deferredMeetingRouteRecoveryRequiresPrewarm = falseprivate var deferredMeetingRouteRecoveryReconcilesInput = false+ private struct MeetingASRScope {+ let id: UUID+ let lease: ASRActivityLease+ var cancelBody: (() -> Void)?+ var awaitBodyCompletion: (() async -> Void)?+ }++ private var meetingASRPreparationOwner: MeetingASRPreparationOwner?+ private var activeMeetingASRScope: MeetingASRScope?+ private var deferredMeetingActivityLeaseRelease: ASRActivityLease?+#if DEBUG+ /// Test seam replacing the lazily wired production owner so scope tests use fake providers.+ var meetingASRPreparationOwnerForTesting: MeetingASRPreparationOwner?+#endifvar isRunningOrStarting: Bool {self.isRunning || self.isStarting}@@ -637,6 +651,11 @@ final class ASRService: ObservableObject {func releaseExclusiveActivity(_ lease: ASRActivityLease) {guard self.activeActivityLease == lease else { return }+ if self.isMeetingASRClaimBlocking(lease: lease) {+ // The exact lease is released by the scope's joined drain, never mid-scope.+ self.deferredMeetingActivityLeaseRelease = lease+ return+ }#if DEBUGAudioTopologyDiagnostics.record(.phaseBegin, owner: .asrActivityLease, queueRole: .mainControl, phase: .activityLease)defer { AudioTopologyDiagnostics.record(.phaseEnd, owner: .asrActivityLease, queueRole: .mainControl, phase: .activityLease) }@@ -1014,6 +1033,22 @@ final class ASRService: ObservableObject {_ = await downloadTask?.resultawait self.providerResetDrain?.task.valueself.streamingWorkState.invalidateProvider()+ // The scope body is independently owned because a future backend may suspend+ // outside the CoreML executor. Termination must join that work before releasing+ // its provider claim or the meeting activity lease.+ if let scope = self.activeMeetingASRScope {+ scope.cancelBody?()+ if let awaitBodyCompletion = scope.awaitBodyCompletion {+ await awaitBodyCompletion()+ }+ }+ if let meetingOwner = self.activeMeetingASRPreparationOwner,+ let claimToken = meetingOwner.currentClaimToken,+ meetingOwner.isClaimed || meetingOwner.isDraining {+ await meetingOwner.release(claimToken)+ }+ await self.meetingTranscriptionExecutor.cancelAndAwaitPending()+ self.flushDeferredMeetingLeaseReleaseIfReady()await self.transcriptionExecutor.cancelAndAwaitPending()self.fluidAudioProvider = nil@@ -1200,6 +1235,9 @@ final class ASRService: ObservableObject {source: AnalyticsModelDownloadSource = .settings,progressHandler: ((Double) -> Void)?) async throws {+ if self.isMeetingASRPreparationClaimed {+ throw MeetingASRPreparationError.preparationInProgress+ }guard self.modelDownloadTask == nil, self.ensureReadyTask == nil else {throw NSError(domain: "ASRService",@@ -1877,6 +1915,8 @@ final class ASRService: ObservableObject {private var benchmarkCompletedStreamingChunks: Int = 0private var benchmarkLastChunkSampleCount: Int = 0private let transcriptionExecutor = TranscriptionExecutor() // Serializes all CoreML access+ /// Scoped meeting ASR work; drained independently of the shared legacy executor.+ private let meetingTranscriptionExecutor = TranscriptionExecutor()private var providerResetDrain: (id: UUID, task: Task<Void, Never>)?private var engineConfigurationChangeObserver: NSObjectProtocol?private let audioEngineRetirementDrain = AudioEngineRetirementDrain()@@ -3702,6 +3742,202 @@ final class ASRService: ObservableObject {return (ASRTranscriptionResult(text: cleanedText, confidence: result.confidence), estimatedSamples)}+ // MARK: - Scoped Meeting ASR Preparation++ private var activeMeetingASRPreparationOwner: MeetingASRPreparationOwner? {+ #if DEBUG+ if let injected = self.meetingASRPreparationOwnerForTesting { return injected }+ #endif+ return self.meetingASRPreparationOwner+ }++ private var isMeetingASRPreparationClaimed: Bool {+ guard let owner = self.activeMeetingASRPreparationOwner else { return false }+ return owner.isClaimed || owner.isDraining+ }++ private func meetingASROwner() -> MeetingASRPreparationOwner {+ #if DEBUG+ if let injected = self.meetingASRPreparationOwnerForTesting { return injected }+ #endif+ if let existing = self.meetingASRPreparationOwner { return existing }+ let owner = MeetingASRPreparationOwner(+ isActiveLease: { [weak self] lease in+ self?.activeActivityLease == lease+ },+ isUserDownloadInProgress: { [weak self] in+ self?.hasActiveModelDownload ?? false+ },+ retireDictationResources: { [weak self] lease in+ guard let self else { throw CancellationError() }+ try await self.retireDictationASRResourcesForMeeting(lease: lease)+ },+ makeProvider: { configuration in+ // Fixed Parakeet TDT v2 English policy; never reads selectedSpeechModel.+ try FluidAudioProvider(meetingConfiguration: configuration)+ },+ prepareProvider: { provider, _, progress in+ try await provider.prepare(progressHandler: progress)+ },+ drainExecutor: { [weak self] _ in+ await self?.meetingTranscriptionExecutor.cancelAndAwaitPending()+ }+ )+ self.meetingASRPreparationOwner = owner+ return owner+ }++ /// Drops cached dictation providers and drains the legacy executor for a claimed meeting+ /// preparation. On-disk model caches are never deleted.+ func retireDictationASRResourcesForMeeting(lease: ASRActivityLease) async throws {+ guard self.activeActivityLease == lease, lease.activity == .meeting else {+ throw CancellationError()+ }+ guard !self.hasActiveModelDownload else {+ throw MeetingASRPreparationError.userModelDownloadInProgress+ }++ if let retiringTask = self.ensureReadyTask {+ self.isCancellingModelPreparation = true+ retiringTask.cancel()+ _ = await retiringTask.result+ }+ await self.transcriptionExecutor.cancelAndAwaitPending()++ guard self.activeActivityLease == lease else { throw CancellationError() }+ self.fluidAudioProvider = nil+ self.parakeetRealtimeProvider = nil+ self.externalCoreMLProvider = nil+ self.nemotronProviders.removeAll()+ self.whisperProvider = nil+ self.appleSpeechProvider = nil+ self._appleSpeechAnalyzerProvider = nil+ self.isAsrReady = false+ }++ private func isMeetingASRClaimBlocking(lease: ASRActivityLease) -> Bool {+ guard lease.activity == .meeting else { return false }+ if let scope = self.activeMeetingASRScope, scope.lease == lease { return true }+ if let owner = self.activeMeetingASRPreparationOwner,+ owner.currentClaimToken?.lease == lease,+ owner.isClaimed || owner.isDraining {+ return true+ }+ return false+ }++ private func executorForMeetingTranscription() -> TranscriptionExecutor {+ if self.activeMeetingASRScope != nil || self.isMeetingASRPreparationClaimed {+ return self.meetingTranscriptionExecutor+ }+ return self.transcriptionExecutor+ }++ /// Runs `body` with the dedicated fixed-configuration meeting ASR provider. Requires the+ /// active meeting lease; one scope at a time. Release/drain is awaited on success, error,+ /// and cancellation before the scope clears and any deferred lease release flushes.+ @discardableResult+ func withPreparedMeetingASR<Result>(+ attemptID: UUID,+ configuration: MeetingFinalProcessingConfiguration,+ body: @escaping (any TranscriptionProvider) async throws -> Result+ ) async throws -> Result {+ try Task.checkCancellation()+ guard let lease = self.activeActivityLease, lease.activity == .meeting else {+ throw MeetingASRPreparationError.invalidActivityLease+ }+ guard self.activeMeetingASRScope == nil else {+ throw MeetingASRPreparationError.preparationInProgress+ }+ let scopeID = UUID()+ self.activeMeetingASRScope = MeetingASRScope(+ id: scopeID,+ lease: lease,+ cancelBody: nil,+ awaitBodyCompletion: nil+ )++ let owner = self.meetingASROwner()+ let provider: any TranscriptionProvider+ do {+ provider = try await owner.prepare(lease: lease, attemptID: attemptID, configuration: configuration)+ } catch {+ // The owner already drained the failed preparation.+ self.finishMeetingASRScope(scopeID: scopeID)+ throw error+ }+ guard self.activeActivityLease == lease,+ let token = owner.currentClaimToken, token.lease == lease+ else {+ if let token = owner.currentClaimToken { await owner.release(token) }+ self.finishMeetingASRScope(scopeID: scopeID)+ throw CancellationError()+ }++ do {+ let bodyTask = Task { @MainActor in+ try await body(provider)+ }+ guard self.activeMeetingASRScope?.id == scopeID else {+ bodyTask.cancel()+ _ = await bodyTask.result+ throw CancellationError()+ }+ self.activeMeetingASRScope?.cancelBody = {+ bodyTask.cancel()+ }+ self.activeMeetingASRScope?.awaitBodyCompletion = {+ _ = await bodyTask.result+ }+ let result = try await withTaskCancellationHandler {+ try await bodyTask.value+ } onCancel: {+ bodyTask.cancel()+ }+ // A provider/model call may not observe cooperative cancellation until it+ // returns. Never publish that late success after the enclosing attempt was+ // cancelled; teardown still runs below before cancellation escapes.+ if bodyTask.isCancelled { throw CancellationError() }+ try Task.checkCancellation()+ await owner.release(token)+ self.finishMeetingASRScope(scopeID: scopeID)+ return result+ } catch {+ await owner.release(token)+ self.finishMeetingASRScope(scopeID: scopeID)+ throw error+ }+ }++ private func finishMeetingASRScope(scopeID: UUID) {+ if self.activeMeetingASRScope?.id == scopeID {+ self.activeMeetingASRScope = nil+ }+ self.flushDeferredMeetingLeaseReleaseIfReady()+ }++ private func flushDeferredMeetingLeaseReleaseIfReady() {+ guard let lease = self.deferredMeetingActivityLeaseRelease,+ !self.isMeetingASRClaimBlocking(lease: lease)+ else { return }+ self.deferredMeetingActivityLeaseRelease = nil+ guard self.activeActivityLease == lease else { return }+ let reason = self.deferredMeetingRouteRecoveryReason+ let requiresPrewarm = self.deferredMeetingRouteRecoveryRequiresPrewarm+ let reconcilesInput = self.deferredMeetingRouteRecoveryReconcilesInput+ self.deferredMeetingRouteRecoveryReason = nil+ self.deferredMeetingRouteRecoveryRequiresPrewarm = false+ self.deferredMeetingRouteRecoveryReconcilesInput = false+ self.releaseExclusiveActivity(lease)+ if requiresPrewarm || reason != nil {+ self.scheduleAudioRouteRecovery(+ reason: reason ?? "meeting audio handback",+ requiresIdlePrewarm: requiresPrewarm,+ reconcilesInputSelection: reconcilesInput+ )+ }+ }+func transcribeMeetingSamples(_ samples: [Float],provider: any TranscriptionProvider,@@ -3710,7 +3946,7 @@ final class ASRService: ObservableObject {guard self.activeExclusiveActivity == .meeting else {throw ASRActivityError.activityInProgress(self.activeExclusiveActivity ?? .meeting)}- return try await self.transcriptionExecutor.run { [provider] in+ return try await self.executorForMeetingTranscription().run { [provider] inif let whisperProvider = provider as? WhisperProvider {return try await whisperProvider.transcribe(samples, languageCode: languageCode)}@@ -3725,7 +3961,7 @@ final class ASRService: ObservableObject {guard self.activeExclusiveActivity == .meeting else {throw ASRActivityError.activityInProgress(self.activeExclusiveActivity ?? .meeting)}- return try await self.transcriptionExecutor.run { [provider] in+ return try await self.executorForMeetingTranscription().run { [provider] intry await provider.transcribeWithWordTimings(samples)}}@@ -3737,7 +3973,7 @@ final class ASRService: ObservableObject {guard self.activeExclusiveActivity == .meeting else {throw ASRActivityError.activityInProgress(self.activeExclusiveActivity ?? .meeting)}- return try await self.transcriptionExecutor.run { [provider] in+ return try await self.executorForMeetingTranscription().run { [provider] intry await provider.transcribeFile(at: fileURL)}}@@ -5543,6 +5779,10 @@ final class ASRService: ObservableObject {self.providerResetDrain = nil}}+ // Unclaimed behavior is unchanged; a claimed scope blocks re-seeding retired caches.+ if self.isMeetingASRPreparationClaimed {+ throw MeetingASRPreparationError.preparationInProgress+ }let provider = self.transcriptionProviderlet model = SettingsStore.shared.selectedSpeechModellet providerKey = "\(model.id):\(type(of: provider)):\(provider.name)"diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingAnalysisManifest.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingAnalysisManifest.swiftnew file mode 100644index 00000000..a700f242--- /dev/null+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingAnalysisManifest.swift@@ -0,0 +1,1969 @@+import Foundation++// Stage C2a of `MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md` (§3, §4) and+// `MEETING_TRANSCRIPTION_BACKEND_ARCHITECTURE_PLAN.md` §5.1: the immutable analysis manifest.+//+// The manifest is the single source-to-analysis-to-presentation mapper for the new backend. It is+// built from a frozen `MeetingBackendPlan` before any model work, and every fact in it is either+// copied from that frozen request or *actually observed* on disk. Nothing here guesses: a universal+// AAC priming delay is never assumed, an unmeasured clock fit stays unknown, and audio that could+// not be read, verified or admitted becomes an explicit typed gap instead of silence that looks+// like coverage.+//+// A planned chunk is represented by one or more non-overlapping *pieces* whose recorded+// presentation intervals union to exactly the chunk's recorded interval. A capture-era boundary+// inside a chunk therefore splits it: the safe part stays an analysable span and the unsafe part+// becomes an inadmissible gap. Nothing is discarded wholesale, and nothing unsafe is laundered.+//+// This slice contains the types, the canonical admission rule, the observation boundary, the+// builder and the fail-closed validator. It writes nothing durable, creates no product speaker ID+// and applies no echo policy — those are later Stage C work.++nonisolated enum MeetingAnalysisManifestSchema {+ static let currentVersion = 1++ /// Affine round-trip slack. The manifest computes each piece's transform exactly, so this only+ /// absorbs floating-point error — it is not a licence to disagree with the mapping.+ static let mappingToleranceSeconds: Double = 1e-6++ /// Default bound for the measured decoded-length-versus-recorded-PTS fit residual. A span whose+ /// residual exceeds its bound is `timingUncertain` (architecture plan §5.1).+ static let defaultResidualBoundSeconds: Double = 0.050++ /// Two consecutive planned chunks whose recorded intervals are farther apart than this are not+ /// contiguous, and the later one begins a new analysis epoch.+ static let chunkContiguityToleranceSeconds: Double = 0.001+}++// MARK: - Intervals++/// Half-open seconds interval. Every interval in the manifest is finite and strictly positive;+/// there is no "empty interval means unknown" encoding anywhere in this file.+nonisolated struct MeetingAnalysisInterval: Codable, Equatable {+ let start: TimeInterval+ let end: TimeInterval++ var duration: TimeInterval {+ self.end - self.start+ }++ var isValid: Bool {+ MeetingEvidenceInterval.isValid(start: self.start, end: self.end)+ }++ func contains(+ _ other: Self,+ toleranceSeconds: Double = MeetingAnalysisManifestSchema.mappingToleranceSeconds+ ) -> Bool {+ other.start >= self.start - toleranceSeconds && other.end <= self.end + toleranceSeconds+ }+}++// MARK: - Codec priming++nonisolated enum MeetingCodecPrimingUnknownReason: String, Codable, CaseIterable {+ /// The decoder exposed no priming/trim information for this file. The common case for the+ /// AAC chunks FluidVoice writes: `AVAudioFile` reports a decoded length, not an encoder delay.+ case decoderDidNotReport+ /// The observation deliberately did not inspect priming.+ case notInspected+}++/// Codec delay/priming as an explicit known-or-unknown value. There is no third state, and+/// `unknown` is never silently treated as zero frames.+nonisolated enum MeetingCodecPriming: Codable, Equatable {+ /// Only for a value a decoder actually reported. A measured zero is a real measurement.+ case measuredFrames(Int)+ case unknown(MeetingCodecPrimingUnknownReason)+ /// Linear PCM has no codec delay. This is deliberately distinct from a measured AAC value:+ /// it records that priming is not applicable to the authoritative capture asset.+ case notApplicable(MeetingAudioEncoding)++ var measuredFrames: Int? {+ switch self {+ case let .measuredFrames(frames): return frames+ case .unknown, .notApplicable: return nil+ }+ }++ var isKnown: Bool {+ switch self {+ case .measuredFrames: return true+ case .notApplicable(.linearPCMFloat32CAFV1): return true+ case .unknown, .notApplicable: return false+ }+ }+}++// Keep the synthesized legacy shape (`{"unknown":"..."}` / `{"measuredFrames":N}`)+// readable while adding the explicit PCM representation. New writes use the same keyed shape.+nonisolated extension MeetingCodecPriming {+ private enum CodingKeys: String, CodingKey { case measuredFrames, unknown, notApplicable }+ private enum AssociatedValueKeys: String, CodingKey { case _0 }++ init(from decoder: Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ if container.contains(.measuredFrames) {+ if let value = try? container.nestedContainer(keyedBy: AssociatedValueKeys.self, forKey: .measuredFrames) {+ self = .measuredFrames(try value.decode(Int.self, forKey: ._0))+ } else {+ // Be liberal for any interim build that emitted a direct scalar.+ self = .measuredFrames(try container.decode(Int.self, forKey: .measuredFrames))+ }+ } else if container.contains(.unknown) {+ if let value = try? container.nestedContainer(keyedBy: AssociatedValueKeys.self, forKey: .unknown) {+ self = .unknown(try value.decode(MeetingCodecPrimingUnknownReason.self, forKey: ._0))+ } else {+ self = .unknown(try container.decode(MeetingCodecPrimingUnknownReason.self, forKey: .unknown))+ }+ } else if container.contains(.notApplicable) {+ if let value = try? container.nestedContainer(keyedBy: AssociatedValueKeys.self, forKey: .notApplicable) {+ self = .notApplicable(try value.decode(MeetingAudioEncoding.self, forKey: ._0))+ } else {+ self = .notApplicable(try container.decode(MeetingAudioEncoding.self, forKey: .notApplicable))+ }+ } else {+ throw DecodingError.dataCorruptedError(+ forKey: .measuredFrames,+ in: container,+ debugDescription: "Invalid codec priming representation."+ )+ }+ }++ func encode(to encoder: Encoder) throws {+ var container = encoder.container(keyedBy: CodingKeys.self)+ switch self {+ case let .measuredFrames(value):+ var nested = container.nestedContainer(keyedBy: AssociatedValueKeys.self, forKey: .measuredFrames)+ try nested.encode(value, forKey: ._0)+ case let .unknown(value):+ var nested = container.nestedContainer(keyedBy: AssociatedValueKeys.self, forKey: .unknown)+ try nested.encode(value, forKey: ._0)+ case let .notApplicable(value):+ var nested = container.nestedContainer(keyedBy: AssociatedValueKeys.self, forKey: .notApplicable)+ try nested.encode(value, forKey: ._0)+ }+ }+}++// MARK: - Observed audio facts++/// What a decoder actually reported for one chunk file. None of these values are derived from the+/// recorded session manifest, from AAC frame arithmetic or from the chunk's nominal duration.+nonisolated struct MeetingChunkDecodedFacts: Codable, Equatable {+ let sampleRate: Double+ let channelCount: Int+ let frameCount: Int64+ /// `frameCount / sampleRate` as observed. Recorded rather than recomputed downstream so a+ /// reader never has to reconstruct it from a different rate.+ let durationSeconds: Double+ let codecPriming: MeetingCodecPriming+ /// Free-form description of the decoder's processing format, for provenance only.+ let processingFormatDescription: String++ /// Seconds of measured codec priming. `nil` when priming was never measured — never zero.+ var primingSeconds: Double? {+ guard let frames = self.codecPriming.measuredFrames, self.sampleRate > 0 else { return nil }+ return Double(frames) / self.sampleRate+ }++ /// Decoded seconds that are not codec priming.+ var usableDurationSeconds: Double {+ self.durationSeconds - (self.primingSeconds ?? 0)+ }+}++/// Identity of the bytes that were actually present when the manifest was built. A stored digest+/// alone does not prove the file is still intact, so the observation re-verifies both.+nonisolated struct MeetingChunkObservedAudio: Codable, Equatable {+ let byteCount: Int64+ let sha256: String+ let decoded: MeetingChunkDecodedFacts+}++// MARK: - Capture era identity++/// The capture era a piece's audio belongs to, after persisted mixed-domain era starts have been+/// normalized through the existing pipeline semantics (`microphoneEras(for:origin:)`).+nonisolated struct MeetingCaptureEraIdentity: Codable, Equatable {+ let index: Int+ /// The recorded capture method. `nil` only for an application-audio track whose session+ /// manifest never recorded one — an absent fact, not an assumed `screenCaptureKit`.+ let method: MeetingAudioTrackCaptureMethod?+ let deviceUID: String?+ let deviceName: String?+ /// Origin-relative era start. `nil` is the first era, which the pipeline pins open at the+ /// beginning of the track (`-infinity`); the manifest never stores a non-finite bound.+ let normalizedStartSeconds: Double?+ /// Microphone echo protection as recorded. `nil` for application audio, where the concept does+ /// not apply — deliberately not `unprotected`, which would assert something false.+ let echoProtection: MeetingMicrophoneEchoProtection?+ let aecProvenance: MeetingAECProvenance?+ /// The era's own recorded clock-drift fit, the sole input to this manifest's de-drift decision.+ let clockDrift: MeetingClockDriftRecord?++ /// Era equality for epoch purposes: the facts that change what the microphone input *is*.+ /// Display name, elected role, settled configuration and drift records are metadata; a change+ /// in them alone does not split an epoch (implementation plan §3).+ func isSameInput(as other: Self) -> Bool {+ self.method == other.method+ && self.deviceUID == other.deviceUID+ && self.echoProtection == other.echoProtection+ }+}++/// Normalization of a track's persisted capture eras, and the de-drift decision derived from them.+/// Microphone eras go through the existing pipeline helper so the manifest cannot disagree with the+/// legacy path about which era an interval belongs to.+nonisolated enum MeetingAnalysisCaptureEras {+ /// Origin-relative era starts. Index 0 is `-infinity`: the pipeline pins the first era open at+ /// the beginning of the track. An application-audio track has exactly one open era.+ static func normalizedStarts(for track: MeetingAudioTrack, origin: Double) -> [Double] {+ switch track.kind {+ case .applicationAudio:+ return [-.infinity]+ case .microphone:+ return MeetingProcessingPipeline.microphoneEras(for: track, origin: origin).map(\.startSeconds)+ }+ }++ static func identities(for track: MeetingAudioTrack, origin: Double) -> [MeetingCaptureEraIdentity] {+ switch track.kind {+ case .applicationAudio:+ // Application audio carries no microphone era metadata at all; recording anything but+ // the track's own capture method here would be invention.+ return [MeetingCaptureEraIdentity(+ index: 0,+ method: track.captureMethod,+ deviceUID: nil,+ deviceName: nil,+ normalizedStartSeconds: nil,+ echoProtection: nil,+ aecProvenance: nil,+ clockDrift: nil+ )]+ case .microphone:+ return MeetingProcessingPipeline.microphoneEras(for: track, origin: origin)+ .enumerated()+ .map { index, era in+ MeetingCaptureEraIdentity(+ index: index,+ method: era.method,+ deviceUID: era.deviceUID,+ deviceName: era.deviceName,+ normalizedStartSeconds: era.startSeconds.isFinite ? era.startSeconds : nil,+ echoProtection: era.echoProtection,+ aecProvenance: era.aecProvenance,+ clockDrift: era.clockDrift+ )+ }+ }+ }++ /// Index of the era containing `presentationSeconds`, using the pipeline's own rule.+ static func index(containing presentationSeconds: Double, starts: [Double]) -> Int {+ var index = 0+ for (offset, start) in starts.enumerated() where start <= presentationSeconds {+ index = offset+ }+ return index+ }++ static func endSeconds(afterIndex index: Int, starts: [Double]) -> Double {+ starts.indices.contains(index + 1) ? starts[index + 1] : .infinity+ }++ /// The anchor the existing de-drift correction pivots around. Era 0's containment boundary is a+ /// `-infinity` sentinel, so it anchors at the track's own first recorded PTS — exactly what+ /// `MeetingProcessingPipeline` computes as `era0AnchorRelative`.+ static func anchorSeconds(+ for identity: MeetingCaptureEraIdentity,+ track: MeetingAudioTrack,+ origin: Double+ ) -> Double {+ if let start = identity.normalizedStartSeconds { return start }+ return (track.chunks.map(\.presentationStart.seconds).min() ?? origin) - origin+ }++ /// The affine rate `MeetingMicrophoneDeDrift.correct` would apply inside this era, or `nil`+ /// when that helper would decline. The guards are the existing ones, not new policy.+ static func deDriftFactor(for identity: MeetingCaptureEraIdentity) -> Double? {+ guard identity.method == .voiceProcessing,+ let drift = identity.clockDrift,+ drift.eligible,+ drift.elapsedValidHostSeconds > 0+ else { return nil }+ let fraction = drift.cumulativeAbsorbedSeconds / drift.elapsedValidHostSeconds+ guard abs(drift.cumulativeAbsorbedSeconds) > MeetingMicrophoneDeDrift.materialityThresholdSeconds,+ abs(fraction) * 1_000_000 < MeetingMicrophoneDeDrift.maxAbsolutePPM,+ (1 + fraction).isFinite,+ 1 + fraction > 0+ else { return nil }+ return 1 + fraction+ }++ /// The de-drift application this manifest owns for one era. Exactly one of these values is+ /// representable per span, which is what makes a second correction downstream a contradiction.+ static func deDrift(+ for identity: MeetingCaptureEraIdentity,+ anchorSeconds: Double+ ) -> MeetingDeDriftApplication {+ if let factor = deDriftFactor(for: identity) {+ return .appliedOnce(factor: factor, eraStartSeconds: anchorSeconds)+ }+ if identity.method == .voiceProcessing, identity.clockDrift != nil {+ return .ineligible(.driftRecordDeclined)+ }+ return .notApplicable+ }+}++// MARK: - Canonical admission++nonisolated enum MeetingCanonicalAdmissionDecision: String, Codable, CaseIterable {+ case admissible+ case inadmissible+}++/// Why the canonical backend may or may not use a piece's audio. Rationales are separate tokens per+/// protection state so an inadmissible interval can never be reported as a generic "unknown".+nonisolated enum MeetingCanonicalAdmissionRationale: String, Codable, CaseIterable {+ /// Application audio carries no microphone echo-protection requirement at all.+ case applicationAudio+ /// In-room microphone audio does not require echo protection (implementation plan §3).+ case inRoomMicrophone+ case onlineMicrophoneVoiceProcessed+ case onlineMicrophoneAcousticallyClosed+ case onlineMicrophoneSoftwareEchoCancelled+ case onlineMicrophoneUnprotected+ /// Legacy-era audio stays usable only through the existing explicit legacy compatibility+ /// policy. The canonical backend has no such policy, so it is inadmissible here.+ case onlineMicrophoneLegacyUnclassified+ /// A microphone piece arrived with no recorded protection state at all.+ case onlineMicrophoneProtectionMissing++ var decision: MeetingCanonicalAdmissionDecision {+ switch self {+ case .applicationAudio,+ .inRoomMicrophone,+ .onlineMicrophoneVoiceProcessed,+ .onlineMicrophoneAcousticallyClosed,+ .onlineMicrophoneSoftwareEchoCancelled:+ return .admissible+ case .onlineMicrophoneUnprotected,+ .onlineMicrophoneLegacyUnclassified,+ .onlineMicrophoneProtectionMissing:+ return .inadmissible+ }+ }+}++/// The canonical-backend admission rule, fail-closed and total. It is deliberately stricter than+/// `MeetingMicrophoneEchoProtection.admitsTranscript`, which still admits `legacyUnclassified` for+/// the legacy adapter. Keeping both visible is the point: this slice must not relabel legacy audio+/// as positively verified.+nonisolated enum MeetingCanonicalAdmission {+ static func rationale(+ captureMode: MeetingCaptureMode,+ trackKind: MeetingAudioTrackKind,+ echoProtection: MeetingMicrophoneEchoProtection?+ ) -> MeetingCanonicalAdmissionRationale {+ guard trackKind == .microphone else { return .applicationAudio }+ if captureMode == .inRoom { return .inRoomMicrophone }+ switch echoProtection {+ case .voiceProcessed: return .onlineMicrophoneVoiceProcessed+ case .acousticallyClosed: return .onlineMicrophoneAcousticallyClosed+ case .softwareEchoCancelled: return .onlineMicrophoneSoftwareEchoCancelled+ case .unprotected: return .onlineMicrophoneUnprotected+ case .legacyUnclassified: return .onlineMicrophoneLegacyUnclassified+ case .none: return .onlineMicrophoneProtectionMissing+ }+ }+}++/// Admission provenance for one span or inadmissible gap: the decision, the rule that produced it+/// and the inputs that rule read.+nonisolated struct MeetingSpanAdmission: Codable, Equatable {+ let decision: MeetingCanonicalAdmissionDecision+ let rationale: MeetingCanonicalAdmissionRationale+ let captureMode: MeetingCaptureMode+ let trackKind: MeetingAudioTrackKind+ let echoProtection: MeetingMicrophoneEchoProtection?++ init(+ captureMode: MeetingCaptureMode,+ trackKind: MeetingAudioTrackKind,+ echoProtection: MeetingMicrophoneEchoProtection?+ ) {+ let rationale = MeetingCanonicalAdmission.rationale(+ captureMode: captureMode,+ trackKind: trackKind,+ echoProtection: echoProtection+ )+ self.decision = rationale.decision+ self.rationale = rationale+ self.captureMode = captureMode+ self.trackKind = trackKind+ self.echoProtection = echoProtection+ }+}++// MARK: - Timing++nonisolated enum MeetingSpanTimingCertainty: String, Codable, CaseIterable {+ case certain+ /// The measured fit residual is missing or out of bounds, or the codec priming this span's+ /// offset depends on was never measured. The architecture plan requires such a span's words to+ /// stay explicit and ambiguous rather than confidently assigned.+ case timingUncertain+}++/// Whether the existing microphone de-drift correction was applied to this span, and with what+/// factor. The manifest is the only owner of that correction for the new backend, so exactly one+/// application is representable and a second one downstream would be a visible contradiction.+nonisolated enum MeetingDeDriftApplication: Codable, Equatable {+ /// No drift correction is defined for this input (application audio, or a non-VPIO era).+ case notApplicable+ /// A drift record exists but the existing eligibility/materiality rules declined it.+ case ineligible(MeetingDeDriftIneligibilityReason)+ /// Applied exactly once, here. `factor` is the existing `1 + cumulative/elapsed` rate.+ case appliedOnce(factor: Double, eraStartSeconds: Double)++ var appliedFactor: Double? {+ switch self {+ case let .appliedOnce(factor, _): return factor+ case .notApplicable, .ineligible: return nil+ }+ }+}++nonisolated enum MeetingDeDriftIneligibilityReason: String, Codable, CaseIterable {+ /// The era's own `MeetingClockDriftRecord` is absent, ineligible or immaterial.+ case driftRecordDeclined+}++/// Piecewise-affine analysis-to-presentation transform for one span, plus the evidence behind it.+/// `presentation(a) = a * rateRatio + offsetSeconds` over the span's analysis interval.+nonisolated struct MeetingAnalysisTimeTransform: Codable, Equatable {+ /// The owning track's recorded host-clock anchor. Copied from the frozen request, never+ /// recomputed and never derived from file timestamps.+ let hostClockAnchor: UInt64+ let rateRatio: Double+ let offsetSeconds: Double+ /// Observed decoded rate ÷ the backend's analysis rate. `nil` when the analysis rate is not+ /// known to this build — unknown, not 1.+ let sampleRateConversionRatio: Double?+ /// Seconds of codec priming removed from analysis time. Non-`nil` only when priming was truly+ /// measured; an unknown priming never becomes a silent zero-second compensation.+ let codecPrimingCompensationSeconds: Double?+ /// Analysis time is per track, gap-removed and monotonic; presentation time retains the gaps.+ let analysisRemovesGaps: Bool++ func presentationTime(forAnalysisTime analysisTime: TimeInterval) -> TimeInterval {+ analysisTime * self.rateRatio + self.offsetSeconds+ }+}++nonisolated struct MeetingSpanTimingMetadata: Codable, Equatable {+ let certainty: MeetingSpanTimingCertainty+ /// Measured residual between the mapped decoded length of this span's chunk and that chunk's+ /// recorded presentation duration. `nil` means no fit was measured — explicitly unknown,+ /// never zero.+ let fitResidualSeconds: Double?+ let residualBoundSeconds: Double+ let deDrift: MeetingDeDriftApplication++ /// The only certainty rule: a measured residual inside the bound *and* a measured codec+ /// priming. An unknown priming leaves the span's offset uncertain by an unmeasured encoder+ /// delay, which is exactly the universal-AAC-delay guess the plan forbids.+ static func certainty(+ fitResidualSeconds: Double?,+ residualBoundSeconds: Double,+ codecPriming: MeetingCodecPriming+ ) -> MeetingSpanTimingCertainty {+ guard codecPriming.isKnown,+ let fitResidualSeconds,+ fitResidualSeconds.isFinite,+ abs(fitResidualSeconds) <= residualBoundSeconds+ else { return .timingUncertain }+ return .certain+ }+}++// MARK: - Discontinuity++nonisolated struct MeetingSpanDiscontinuityBoundary: Codable, Equatable {+ let kind: MeetingInterruptionKind+ /// Origin-relative seconds. `nil` when the recorded discontinuity carried no presentation+ /// time; the boundary is still reported, with its position unknown.+ let presentationSeconds: Double?+ let gapSeconds: Double?+ let detail: String?+}++nonisolated struct MeetingSpanDiscontinuityFacts: Codable, Equatable {+ /// Discontinuities recorded on this piece's chunk, copied from the session manifest. Every+ /// piece of a chunk carries the same copy; only the chunk's first piece may use them as an+ /// epoch boundary, because that is where the chunk actually begins.+ let boundaries: [MeetingSpanDiscontinuityBoundary]+ /// The previous planned chunk on this track ends before this one starts by more than the+ /// contiguity tolerance.+ let precededByChunkTimeGap: Bool+ /// Measured size of that gap. `nil` when there is no preceding planned chunk.+ let precedingGapSeconds: Double?++ static let contiguous = Self(+ boundaries: [],+ precededByChunkTimeGap: false,+ precedingGapSeconds: nil+ )++ /// Copies a chunk's recorded discontinuities into origin-relative form.+ static func make(+ chunk: MeetingAudioChunk,+ previousChunk: MeetingAudioChunk?,+ origin: Double+ ) -> Self {+ let precedingGap = previousChunk.map {+ (chunk.presentationStart.seconds - origin) - ($0.presentationEnd.seconds - origin)+ }+ return Self(+ boundaries: chunk.discontinuities.map { discontinuity in+ MeetingSpanDiscontinuityBoundary(+ kind: discontinuity.kind,+ presentationSeconds: discontinuity.presentationTime.map { $0.seconds - origin },+ gapSeconds: discontinuity.gapSeconds,+ detail: discontinuity.detail+ )+ },+ precededByChunkTimeGap: (precedingGap ?? 0)+ > MeetingAnalysisManifestSchema.chunkContiguityToleranceSeconds,+ precedingGapSeconds: precedingGap+ )+ }+}++// MARK: - Chunk identity++/// Everything about a planned chunk that the manifest must agree with the frozen request on. A+/// piece that mis-states any of it is refused: it would describe a different file.+nonisolated struct MeetingAnalysisChunkIdentity: Codable, Equatable, Hashable {+ let trackID: MeetingAudioTrackID+ let chunkID: MeetingAudioChunkID+ let sequence: Int+ /// Session-directory-relative, exactly as recorded.+ let relativeFilePath: String+ let storedByteCount: Int64+ let storedSHA256: String++ /// The authoritative bytes used for analysis. For legacy chunks these equal the stored chunk+ /// fields; for an activated PCM-first chunk they point at the ready capture-analysis asset.+ let analysisEncoding: MeetingAudioEncoding?++ init(trackID: MeetingAudioTrackID, chunk: MeetingAudioChunk) {+ self.trackID = trackID+ self.chunkID = chunk.id+ self.sequence = chunk.sequence+ if let asset = chunk.captureAnalysisAsset,+ asset.presence == .ready,+ asset.role == .captureAnalysis,+ asset.encoding == .linearPCMFloat32CAFV1 {+ self.relativeFilePath = asset.relativeFilePath+ self.storedByteCount = asset.byteCount+ self.storedSHA256 = asset.sha256 ?? ""+ self.analysisEncoding = asset.encoding+ } else {+ self.relativeFilePath = chunk.relativeFilePath+ self.storedByteCount = chunk.byteCount+ self.storedSHA256 = chunk.sha256+ // A schema-bearing chunk without a ready PCM asset is never allowed to silently+ // fall back to AAC. Keep a legacy chunk (which has no schema) distinguishable from a+ // malformed PCM-first chunk so the materializer can refuse the latter.+ self.analysisEncoding = chunk.audioSchemaVersion == nil+ ? nil+ : .legacyAACUnknownPrimingV1+ }+ }++ var key: MeetingAnalysisChunkKey {+ MeetingAnalysisChunkKey(trackID: self.trackID, chunkID: self.chunkID)+ }+}++/// Chunk scope is keyed by track *and* chunk. A chunk UUID alone is not a scope key: two tracks may+/// legally carry the same identifier in a hand-built or corrupted manifest, and coverage accounting+/// keyed only by UUID would let one track's span satisfy another track's planned chunk.+nonisolated struct MeetingAnalysisChunkKey: Hashable, CustomStringConvertible {+ let trackID: MeetingAudioTrackID+ let chunkID: MeetingAudioChunkID++ var description: String {+ "\(self.trackID.uuidString)/\(self.chunkID.uuidString)"+ }+}++// MARK: - Spans, gaps and epochs++nonisolated enum MeetingAnalysisEpochResetReason: String, Codable, CaseIterable {+ case trackStart+ case missingOrUnreadableAudio+ case chunkDiscontinuity+ case microphoneDeviceChanged+ case inadmissibleCaptureEra+}++nonisolated struct MeetingAnalysisEpochRecord: Codable, Equatable, Identifiable {+ let id: MeetingAnalysisEpochID+ let resetReason: MeetingAnalysisEpochResetReason+ /// Spans in analysis order. An epoch with no spans is not representable: it would describe+ /// model state that never existed.+ let spanIDs: [String]+ let analysisInterval: MeetingAnalysisInterval+}++/// Why a piece of a planned chunk has no validated analysis span. Every reason is a fact the+/// builder established — a file it could not find, bytes that changed, a decoder that refused, or+/// audio the canonical admission rule rejects.+nonisolated enum MeetingAnalysisGapReason: String, Codable, CaseIterable {+ case chunkFileMissing+ /// The chunk path left the session directory, or a path component was a symlink.+ case chunkPathRejected+ case chunkByteCountChanged+ case chunkHashChanged+ case chunkUnreadable+ /// Zero stored bytes, or zero decoded frames.+ case chunkEmpty+ /// A decoder reported a non-positive sample rate, so no duration can be derived from it.+ case chunkSampleRateUnusable+ case chunkAnalysisAssetInvalid+ /// Defensive: a chunk that is not finalized is not planned work.+ case chunkNotFinalized+ /// The chunk's recorded presentation bounds are not a positive interval, so it maps nowhere.+ case chunkHasNoRecordedInterval+ /// The decoder returned less audio than the chunk's recorded interval claims, so this trailing+ /// piece has no samples behind it at all.+ case decodedAudioExhausted+ case inadmissibleCaptureEra++ var epochResetReason: MeetingAnalysisEpochResetReason {+ switch self {+ case .inadmissibleCaptureEra:+ return .inadmissibleCaptureEra+ case .chunkFileMissing,+ .chunkPathRejected,+ .chunkByteCountChanged,+ .chunkHashChanged,+ .chunkUnreadable,+ .chunkEmpty,+ .chunkSampleRateUnusable,+ .chunkAnalysisAssetInvalid,+ .chunkNotFinalized,+ .chunkHasNoRecordedInterval,+ .decodedAudioExhausted:+ return .missingOrUnreadableAudio+ }+ }++ /// Only an admission refusal carries admission provenance; everything else would be asserting a+ /// protection judgement it never made.+ var carriesAdmission: Bool {+ self == .inadmissibleCaptureEra+ }+}++nonisolated struct MeetingAnalysisGap: Codable, Equatable, Identifiable {+ let id: String+ let chunk: MeetingAnalysisChunkIdentity+ /// Position of this piece inside its chunk's cover, from 0.+ let pieceIndex: Int+ let reason: MeetingAnalysisGapReason+ /// This piece's slice of the chunk's recorded, origin-relative presentation interval. `nil`+ /// only when the chunk's own recorded bounds are not a positive interval — the validator+ /// re-checks that against the frozen request.+ let recordedInterval: MeetingAnalysisInterval?+ /// Present exactly for `inadmissibleCaptureEra`, carrying the era that excluded this piece.+ let captureEra: MeetingCaptureEraIdentity?+ /// Present exactly for `inadmissibleCaptureEra`, carrying the rule inputs that excluded it.+ let admission: MeetingSpanAdmission?+ let detail: String?++ var trackID: MeetingAudioTrackID {+ self.chunk.trackID+ }++ var chunkID: MeetingAudioChunkID {+ self.chunk.chunkID+ }++ /// Stable across rebuilds of the same attempt: derived from identity and piece position, not+ /// from iteration order.+ static func stableID(attemptID: UUID, chunk: MeetingAnalysisChunkIdentity, pieceIndex: Int) -> String {+ "gap:\(attemptID.uuidString):\(chunk.trackID.uuidString):\(chunk.chunkID.uuidString):\(pieceIndex)"+ }+}++/// One validated, admissible, actually-decoded piece of one planned chunk.+nonisolated struct MeetingAnalysisSpan: Codable, Equatable, Identifiable {+ let id: String+ let chunk: MeetingAnalysisChunkIdentity+ /// Position of this piece inside its chunk's cover, from 0.+ let pieceIndex: Int+ let trackKind: MeetingAudioTrackKind+ let analysisEpochID: MeetingAnalysisEpochID+ /// This piece's slice of the chunk's recorded, origin-relative presentation interval. Coverage+ /// accounting is done in this domain, so drift correction can never create or destroy coverage.+ let recordedInterval: MeetingAnalysisInterval+ /// Valid region inside the source file, in seconds from that file's own start.+ let sourceLocalInterval: MeetingAnalysisInterval+ /// Position in the track's gap-removed analysis stream.+ let analysisInterval: MeetingAnalysisInterval+ /// Position in meeting presentation time, origin-relative, after de-drift.+ let presentationInterval: MeetingAnalysisInterval+ let presentationMapping: MeetingAnalysisTimeTransform+ let captureEra: MeetingCaptureEraIdentity+ let admission: MeetingSpanAdmission+ /// Byte count, digest and decoded format as actually observed on disk.+ let observed: MeetingChunkObservedAudio+ let discontinuity: MeetingSpanDiscontinuityFacts+ let timing: MeetingSpanTimingMetadata++ var trackID: MeetingAudioTrackID {+ self.chunk.trackID+ }++ var chunkID: MeetingAudioChunkID {+ self.chunk.chunkID+ }++ var storedByteCount: Int64 {+ self.chunk.storedByteCount+ }++ var storedSHA256: String {+ self.chunk.storedSHA256+ }++ /// Stable across rebuilds of the same attempt: derived from identity and piece position, not+ /// from iteration order.+ static func stableID(attemptID: UUID, chunk: MeetingAnalysisChunkIdentity, pieceIndex: Int) -> String {+ "span:\(attemptID.uuidString):\(chunk.trackID.uuidString):\(chunk.chunkID.uuidString):\(pieceIndex)"+ }+}++/// One piece of a planned chunk's cover, in chunk order. Spans and gaps are stored separately so a+/// reader never has to filter, but coverage and epoch rules see a single ordered sequence.+nonisolated enum MeetingAnalysisPiece: Equatable {+ case span(MeetingAnalysisSpan)+ case gap(MeetingAnalysisGap)++ var chunk: MeetingAnalysisChunkIdentity {+ switch self {+ case let .span(span): return span.chunk+ case let .gap(gap): return gap.chunk+ }+ }++ var pieceIndex: Int {+ switch self {+ case let .span(span): return span.pieceIndex+ case let .gap(gap): return gap.pieceIndex+ }+ }++ var recordedInterval: MeetingAnalysisInterval? {+ switch self {+ case let .span(span): return span.recordedInterval+ case let .gap(gap): return gap.recordedInterval+ }+ }++ var id: String {+ switch self {+ case let .span(span): return span.id+ case let .gap(gap): return gap.id+ }+ }+}++nonisolated struct MeetingAnalysisTrackManifest: Codable, Equatable, Identifiable {+ let id: MeetingAudioTrackID+ let kind: MeetingAudioTrackKind+ /// Analysis order, which is also (chunk sequence, piece index) order.+ let spans: [MeetingAnalysisSpan]+ /// (chunk sequence, piece index) order.+ let gaps: [MeetingAnalysisGap]+ let epochs: [MeetingAnalysisEpochRecord]++ /// Explicit inadmissible coverage, as the plan requires it to be visible rather than implied+ /// by absence.+ var inadmissibleGaps: [MeetingAnalysisGap] {+ self.gaps.filter { $0.reason == .inadmissibleCaptureEra }+ }++ /// Every piece of every planned chunk in one ordered sequence.+ var orderedPieces: [MeetingAnalysisPiece] {+ let pieces = self.spans.map(MeetingAnalysisPiece.span) + self.gaps.map(MeetingAnalysisPiece.gap)+ return pieces.sorted { left, right in+ if left.chunk.sequence != right.chunk.sequence {+ return left.chunk.sequence < right.chunk.sequence+ }+ return left.pieceIndex < right.pieceIndex+ }+ }+}++// MARK: - Manifest++nonisolated struct MeetingAnalysisManifest: Equatable {+ let schemaVersion: Int+ let backendID: MeetingBackendID+ let backendVersion: String+ let attemptID: UUID+ let sessionID: MeetingSessionID+ let captureMode: MeetingCaptureMode+ /// The presentation origin every interval here is relative to, computed with the existing+ /// pipeline semantics (the minimum chunk presentation start across the session's tracks).+ let presentationOriginSeconds: Double+ /// Analysis sample rate the spans were mapped for. `nil` when this build does not know it;+ /// the composite backend supplies its real resampler rate in Stage E.+ let analysisSampleRate: Double?+ /// The single residual bound every span in this manifest was judged against.+ let residualBoundSeconds: Double+ /// One entry per planned track, including a planned track with no finalized chunks.+ let tracks: [MeetingAnalysisTrackManifest]++ init(+ backendID: MeetingBackendID,+ backendVersion: String,+ attemptID: UUID,+ sessionID: MeetingSessionID,+ captureMode: MeetingCaptureMode,+ presentationOriginSeconds: Double,+ analysisSampleRate: Double?,+ residualBoundSeconds: Double = MeetingAnalysisManifestSchema.defaultResidualBoundSeconds,+ tracks: [MeetingAnalysisTrackManifest]+ ) {+ self.schemaVersion = MeetingAnalysisManifestSchema.currentVersion+ self.backendID = backendID+ self.backendVersion = backendVersion+ self.attemptID = attemptID+ self.sessionID = sessionID+ self.captureMode = captureMode+ self.presentationOriginSeconds = presentationOriginSeconds+ self.analysisSampleRate = analysisSampleRate+ self.residualBoundSeconds = residualBoundSeconds+ self.tracks = tracks+ }++ func track(_ trackID: MeetingAudioTrackID) -> MeetingAnalysisTrackManifest? {+ self.tracks.first(where: { $0.id == trackID })+ }++ var allSpans: [MeetingAnalysisSpan] {+ self.tracks.flatMap(\.spans)+ }++ var allGaps: [MeetingAnalysisGap] {+ self.tracks.flatMap(\.gaps)+ }++ /// The presentation origin the existing pipeline would use for this session: the minimum+ /// recorded chunk start across every track. Not just planned chunks — the legacy path folds in+ /// provisional ones too, and disagreeing would shift every timestamp the product shows.+ static func presentationOrigin(of session: MeetingSession) -> Double {+ session.audioTracks+ .flatMap(\.chunks)+ .map(\.presentationStart.seconds)+ .min() ?? 0+ }+}++nonisolated extension MeetingAnalysisManifest: Codable {+ private enum CodingKeys: String, CodingKey {+ case schemaVersion+ case backendID+ case backendVersion+ case attemptID+ case sessionID+ case captureMode+ case presentationOriginSeconds+ case analysisSampleRate+ case residualBoundSeconds+ case tracks+ }++ init(from decoder: Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ let version = try container.decode(Int.self, forKey: .schemaVersion)+ guard version == MeetingAnalysisManifestSchema.currentVersion else {+ throw DecodingError.dataCorruptedError(+ forKey: .schemaVersion,+ in: container,+ debugDescription: "Unsupported meeting analysis manifest schema version \(version)."+ )+ }+ try self.init(+ backendID: container.decode(MeetingBackendID.self, forKey: .backendID),+ backendVersion: container.decode(String.self, forKey: .backendVersion),+ attemptID: container.decode(UUID.self, forKey: .attemptID),+ sessionID: container.decode(MeetingSessionID.self, forKey: .sessionID),+ captureMode: container.decode(MeetingCaptureMode.self, forKey: .captureMode),+ presentationOriginSeconds: container.decode(Double.self, forKey: .presentationOriginSeconds),+ analysisSampleRate: container.decodeIfPresent(Double.self, forKey: .analysisSampleRate),+ residualBoundSeconds: container.decode(Double.self, forKey: .residualBoundSeconds),+ tracks: container.decode([MeetingAnalysisTrackManifest].self, forKey: .tracks)+ )+ }++ func encode(to encoder: Encoder) throws {+ var container = encoder.container(keyedBy: CodingKeys.self)+ try container.encode(self.schemaVersion, forKey: .schemaVersion)+ try container.encode(self.backendID, forKey: .backendID)+ try container.encode(self.backendVersion, forKey: .backendVersion)+ try container.encode(self.attemptID, forKey: .attemptID)+ try container.encode(self.sessionID, forKey: .sessionID)+ try container.encode(self.captureMode, forKey: .captureMode)+ try container.encode(self.presentationOriginSeconds, forKey: .presentationOriginSeconds)+ try container.encodeIfPresent(self.analysisSampleRate, forKey: .analysisSampleRate)+ try container.encode(self.residualBoundSeconds, forKey: .residualBoundSeconds)+ try container.encode(self.tracks, forKey: .tracks)+ }+}++// MARK: - Errors++nonisolated enum MeetingAnalysisManifestError: LocalizedError, Equatable {+ case unsupportedSchemaVersion(Int)+ case backendMismatch(expected: MeetingBackendID, actual: MeetingBackendID)+ case backendVersionMismatch(expected: String, actual: String)+ case attemptMismatch(expected: UUID, actual: UUID)+ case sessionMismatch(expected: MeetingSessionID, actual: MeetingSessionID)+ case captureModeMismatch(expected: MeetingCaptureMode, actual: MeetingCaptureMode)+ case presentationOriginMismatch(expected: Double, actual: Double)+ case invalidAnalysisSampleRate+ case invalidResidualBound+ case duplicateTrack(MeetingAudioTrackID)+ case trackOutOfScope(MeetingAudioTrackID)+ case trackKindMismatch(MeetingAudioTrackID)+ case missingPlannedTrack(MeetingAudioTrackID)+ case unstableSpanID(expected: String, actual: String)+ case duplicateSpanID(String)+ case unstableGapID(expected: String, actual: String)+ case duplicateGapID(String)+ case pieceOrderInvalid(trackID: MeetingAudioTrackID)+ case chunkOutOfScope(MeetingAnalysisChunkKey)+ case chunkIdentityDisagreesWithPlan(MeetingAnalysisChunkKey)+ case plannedChunkUncovered(MeetingAnalysisChunkKey)+ case chunkPieceIndicesInvalid(MeetingAnalysisChunkKey)+ case chunkPieceCoverageInvalid(MeetingAnalysisChunkKey)+ case spanTrackCrossing(spanID: String)+ case gapTrackCrossing(gapID: String)+ case invalidRecordedInterval(pieceID: String)+ case recordedIntervalCrossesCaptureEra(pieceID: String)+ case invalidSourceLocalInterval(spanID: String)+ case invalidAnalysisInterval(spanID: String)+ case invalidPresentationInterval(spanID: String)+ case observedIdentityDisagreesWithStored(spanID: String)+ case invalidDecodedFacts(spanID: String)+ case decodedDurationInconsistent(spanID: String)+ case primingFramesExceedDecodedFrames(spanID: String)+ case sourceLocalIntervalDisagreesWithRecordedPiece(spanID: String)+ case analysisDurationDisagreesWithSource(spanID: String)+ case analysisTimeNotGapRemoved(trackID: MeetingAudioTrackID)+ case invalidTransform(spanID: String)+ case transformDisagreesWithIntervals(spanID: String)+ case hostClockAnchorMismatch(spanID: String)+ case primingCompensationMismatch(spanID: String)+ case sampleRateConversionRatioMismatch(spanID: String)+ case analysisMustRemoveGaps(spanID: String)+ case captureEraDisagreesWithPlan(pieceID: String)+ case admissionRuleMismatch(spanID: String)+ case inadmissibleSpan(spanID: String)+ case discontinuityDisagreesWithPlan(spanID: String)+ case residualDisagreesWithObservation(spanID: String)+ case invalidTimingCertainty(spanID: String)+ case spanResidualBoundMismatch(spanID: String)+ case deDriftDisagreesWithPlan(spanID: String)+ case driftFactorDisagreesWithTransform(spanID: String)+ case presentationMappingDisagreesWithPlan(spanID: String)+ case gapReasonInconsistent(gapID: String)+ case gapAdmissionInconsistent(gapID: String)+ case spanEpochTrackCrossing(spanID: String)+ case invalidEpochOrdinal(spanID: String)+ case invalidEpochGeneration(MeetingAnalysisEpochID)+ case unknownSpanEpoch(spanID: String)+ case duplicateEpoch(MeetingAnalysisEpochID)+ case epochTrackCrossing(MeetingAnalysisEpochID)+ case nonContiguousEpochOrdinals(trackID: MeetingAudioTrackID)+ case emptyEpoch(MeetingAnalysisEpochID)+ case epochSpanMembershipMismatch(MeetingAnalysisEpochID)+ case epochIntervalMismatch(MeetingAnalysisEpochID)+ case invalidEpochResetReason(MeetingAnalysisEpochID)+ case unjustifiedEpochBoundary(spanID: String)+ case missingEpochBoundary(spanID: String)+ case nonMonotonicAnalysisTime(trackID: MeetingAudioTrackID)+ case nonMonotonicPresentationTime(trackID: MeetingAudioTrackID)++ var errorDescription: String? {+ switch self {+ case let .unsupportedSchemaVersion(version):+ return "Unsupported meeting analysis manifest schema version \(version)."+ case let .backendMismatch(expected, actual):+ return "Analysis manifest names backend \"\(actual)\" but the plan selected \"\(expected)\"."+ case let .backendVersionMismatch(expected, actual):+ return "Analysis manifest names backend version \"\(actual)\"; the plan froze \"\(expected)\"."+ case let .attemptMismatch(expected, actual):+ return "Analysis manifest carries attempt \(actual) but the plan is attempt \(expected)."+ case let .sessionMismatch(expected, actual):+ return "Analysis manifest carries session \(actual) but the plan is session \(expected)."+ case let .captureModeMismatch(expected, actual):+ return "Analysis manifest declares \(actual.rawValue) capture; the session is \(expected.rawValue)."+ case let .presentationOriginMismatch(expected, actual):+ return "Analysis manifest uses presentation origin \(actual); the frozen session's is \(expected)."+ case .invalidAnalysisSampleRate:+ return "Analysis manifest declares a non-finite or non-positive analysis sample rate."+ case .invalidResidualBound:+ return "Analysis manifest declares a non-finite or non-positive residual bound."+ case let .duplicateTrack(trackID):+ return "Analysis manifest lists track \(trackID) more than once."+ case let .trackOutOfScope(trackID):+ return "Analysis manifest covers track \(trackID), which was never planned."+ case let .trackKindMismatch(trackID):+ return "Analysis manifest declares the wrong kind for track \(trackID)."+ case let .missingPlannedTrack(trackID):+ return "Analysis manifest omits planned track \(trackID)."+ case let .unstableSpanID(expected, actual):+ return "Analysis span identifier \"\(actual)\" is not its stable identity \"\(expected)\"."+ case let .duplicateSpanID(id):+ return "Analysis span identifier \"\(id)\" appears more than once."+ case let .unstableGapID(expected, actual):+ return "Analysis gap identifier \"\(actual)\" is not its stable identity \"\(expected)\"."+ case let .duplicateGapID(id):+ return "Analysis gap identifier \"\(id)\" appears more than once."+ case let .pieceOrderInvalid(trackID):+ return "Track \(trackID) lists spans or gaps out of chunk-sequence order."+ case let .chunkOutOfScope(key):+ return "Analysis manifest references chunk \(key), which was not planned."+ case let .chunkIdentityDisagreesWithPlan(key):+ return "Analysis manifest states a sequence, path, byte count or digest for chunk "+ + "\(key) that the frozen request does not."+ case let .plannedChunkUncovered(key):+ return "Planned chunk \(key) has neither an analysis span nor a gap."+ case let .chunkPieceIndicesInvalid(key):+ return "Planned chunk \(key) has duplicate or non-contiguous piece indices."+ case let .chunkPieceCoverageInvalid(key):+ return "Planned chunk \(key)'s pieces do not exactly cover its recorded interval."+ case let .spanTrackCrossing(spanID):+ return "Analysis span \"\(spanID)\" is filed under a different track than it names."+ case let .gapTrackCrossing(gapID):+ return "Analysis gap \"\(gapID)\" is filed under a different track than it names."+ case let .invalidRecordedInterval(pieceID):+ return "Analysis piece \"\(pieceID)\" has a non-finite or non-positive recorded interval."+ case let .recordedIntervalCrossesCaptureEra(pieceID):+ return "Analysis piece \"\(pieceID)\" spans more than one capture era."+ case let .invalidSourceLocalInterval(spanID):+ return "Analysis span \"\(spanID)\" has a non-finite or non-positive source interval."+ case let .invalidAnalysisInterval(spanID):+ return "Analysis span \"\(spanID)\" has a non-finite or non-positive analysis interval."+ case let .invalidPresentationInterval(spanID):+ return "Analysis span \"\(spanID)\" has a non-finite or non-positive presentation interval."+ case let .observedIdentityDisagreesWithStored(spanID):+ return "Analysis span \"\(spanID)\" records observed bytes that differ from the stored manifest."+ case let .invalidDecodedFacts(spanID):+ return "Analysis span \"\(spanID)\" has non-positive decoded rate, channels, frames or duration."+ case let .decodedDurationInconsistent(spanID):+ return "Analysis span \"\(spanID)\" records a decoded duration that is not frames ÷ sample rate."+ case let .primingFramesExceedDecodedFrames(spanID):+ return "Analysis span \"\(spanID)\" reports more priming frames than decoded frames."+ case let .sourceLocalIntervalDisagreesWithRecordedPiece(spanID):+ return "Analysis span \"\(spanID)\" reads a source region its recorded piece does not map to."+ case let .analysisDurationDisagreesWithSource(spanID):+ return "Analysis span \"\(spanID)\" has an analysis duration unequal to its valid source duration."+ case let .analysisTimeNotGapRemoved(trackID):+ return "Track \(trackID)'s analysis stream is not the gap-removed concatenation of its spans."+ case let .invalidTransform(spanID):+ return "Analysis span \"\(spanID)\" has a non-finite or non-positive time transform."+ case let .transformDisagreesWithIntervals(spanID):+ return "Analysis span \"\(spanID)\" does not round-trip between analysis and presentation time."+ case let .hostClockAnchorMismatch(spanID):+ return "Analysis span \"\(spanID)\" records a host-clock anchor its track never had."+ case let .primingCompensationMismatch(spanID):+ return "Analysis span \"\(spanID)\" compensates priming that was not measured, or by the wrong amount."+ case let .sampleRateConversionRatioMismatch(spanID):+ return "Analysis span \"\(spanID)\" records a sample-rate conversion ratio its rates do not give."+ case let .analysisMustRemoveGaps(spanID):+ return "Analysis span \"\(spanID)\" declares an analysis stream that retains gaps."+ case let .captureEraDisagreesWithPlan(pieceID):+ return "Analysis piece \"\(pieceID)\" records a capture era the frozen session does not have."+ case let .admissionRuleMismatch(spanID):+ return "Analysis span \"\(spanID)\" records an admission decision the canonical rule did not make."+ case let .inadmissibleSpan(spanID):+ return "Analysis span \"\(spanID)\" is inadmissible; inadmissible audio must be a gap."+ case let .discontinuityDisagreesWithPlan(spanID):+ return "Analysis span \"\(spanID)\" records discontinuities its chunk does not."+ case let .residualDisagreesWithObservation(spanID):+ return "Analysis span \"\(spanID)\" records a fit residual its observed audio does not give."+ case let .invalidTimingCertainty(spanID):+ return "Analysis span \"\(spanID)\" declares a timing certainty its evidence does not support."+ case let .spanResidualBoundMismatch(spanID):+ return "Analysis span \"\(spanID)\" uses a residual bound other than the manifest's."+ case let .deDriftDisagreesWithPlan(spanID):+ return "Analysis span \"\(spanID)\" records a de-drift decision its capture era does not give."+ case let .driftFactorDisagreesWithTransform(spanID):+ return "Analysis span \"\(spanID)\" records a drift factor its transform does not use."+ case let .presentationMappingDisagreesWithPlan(spanID):+ return "Analysis span \"\(spanID)\" maps to a presentation interval its recorded piece does not."+ case let .gapReasonInconsistent(gapID):+ return "Analysis gap \"\(gapID)\" has a reason inconsistent with the interval it covers."+ case let .gapAdmissionInconsistent(gapID):+ return "Analysis gap \"\(gapID)\" has admission provenance inconsistent with its reason."+ case let .spanEpochTrackCrossing(spanID):+ return "Analysis span \"\(spanID)\" uses an analysis epoch from another track."+ case let .invalidEpochOrdinal(spanID):+ return "Analysis span \"\(spanID)\" uses a negative analysis epoch ordinal."+ case let .invalidEpochGeneration(epochID):+ return "Analysis epoch \(epochID) uses a negative evidence generation."+ case let .unknownSpanEpoch(spanID):+ return "Analysis span \"\(spanID)\" references an epoch the manifest does not record."+ case let .duplicateEpoch(epochID):+ return "Analysis epoch \(epochID) is recorded more than once."+ case let .epochTrackCrossing(epochID):+ return "Analysis epoch \(epochID) is filed under another track."+ case let .nonContiguousEpochOrdinals(trackID):+ return "Track \(trackID) has non-contiguous analysis epoch ordinals."+ case let .emptyEpoch(epochID):+ return "Analysis epoch \(epochID) contains no spans."+ case let .epochSpanMembershipMismatch(epochID):+ return "Analysis epoch \(epochID) lists spans other than the ones assigned to it."+ case let .epochIntervalMismatch(epochID):+ return "Analysis epoch \(epochID) declares an interval its spans do not cover."+ case let .invalidEpochResetReason(epochID):+ return "Analysis epoch \(epochID) declares a reset reason its position cannot have."+ case let .unjustifiedEpochBoundary(spanID):+ return "Analysis span \"\(spanID)\" starts a new epoch with no gap, discontinuity or device change before it."+ case let .missingEpochBoundary(spanID):+ return "Analysis span \"\(spanID)\" continues an epoch across a gap, discontinuity or device change."+ case let .nonMonotonicAnalysisTime(trackID):+ return "Track \(trackID) has overlapping or out-of-order analysis intervals."+ case let .nonMonotonicPresentationTime(trackID):+ return "Track \(trackID) has overlapping or out-of-order presentation intervals."+ }+ }+}++// MARK: - Plan projection++/// Everything the validator and the builder both need to read out of the frozen plan, derived once+/// and read-only. Both sides go through this so the manifest is checked against the *request*, not+/// against whatever the builder happened to remember.+nonisolated struct MeetingAnalysisPlanProjection {+ let origin: Double+ let tracksByID: [MeetingAudioTrackID: MeetingAudioTrack]+ let chunksByKey: [MeetingAnalysisChunkKey: MeetingAudioChunk]+ /// Planned chunks per track, in recorded sequence order.+ let plannedChunksByTrack: [MeetingAudioTrackID: [MeetingAudioChunk]]+ let eraIdentitiesByTrack: [MeetingAudioTrackID: [MeetingCaptureEraIdentity]]+ let eraStartsByTrack: [MeetingAudioTrackID: [Double]]++ init(plan: MeetingBackendPlan) {+ let session = plan.request.session+ let origin = MeetingAnalysisManifest.presentationOrigin(of: session)+ self.origin = origin++ var tracksByID: [MeetingAudioTrackID: MeetingAudioTrack] = [:]+ var chunksByKey: [MeetingAnalysisChunkKey: MeetingAudioChunk] = [:]+ var plannedChunksByTrack: [MeetingAudioTrackID: [MeetingAudioChunk]] = [:]+ var eraIdentitiesByTrack: [MeetingAudioTrackID: [MeetingCaptureEraIdentity]] = [:]+ var eraStartsByTrack: [MeetingAudioTrackID: [Double]] = [:]++ for track in session.audioTracks {+ tracksByID[track.id] = track+ guard let plannedIDs = plan.chunkIDsByTrackID[track.id] else { continue }+ let planned = track.chunks+ .filter { plannedIDs.contains($0.id) }+ .sorted { $0.sequence < $1.sequence }+ plannedChunksByTrack[track.id] = planned+ for chunk in planned {+ chunksByKey[MeetingAnalysisChunkKey(trackID: track.id, chunkID: chunk.id)] = chunk+ }+ eraIdentitiesByTrack[track.id] = MeetingAnalysisCaptureEras.identities(for: track, origin: origin)+ eraStartsByTrack[track.id] = MeetingAnalysisCaptureEras.normalizedStarts(for: track, origin: origin)+ }++ self.tracksByID = tracksByID+ self.chunksByKey = chunksByKey+ self.plannedChunksByTrack = plannedChunksByTrack+ self.eraIdentitiesByTrack = eraIdentitiesByTrack+ self.eraStartsByTrack = eraStartsByTrack+ }++ /// Origin-relative recorded presentation interval of a planned chunk. `nil` when the recorded+ /// bounds are not a positive interval — the only case where a piece may omit its interval.+ func recordedInterval(of chunk: MeetingAudioChunk) -> MeetingAnalysisInterval? {+ let interval = MeetingAnalysisInterval(+ start: chunk.presentationStart.seconds - self.origin,+ end: chunk.presentationEnd.seconds - self.origin+ )+ return interval.isValid ? interval : nil+ }++ func eraIdentity(forTrack trackID: MeetingAudioTrackID, containing seconds: Double) -> MeetingCaptureEraIdentity? {+ guard let starts = self.eraStartsByTrack[trackID],+ let identities = self.eraIdentitiesByTrack[trackID],+ !identities.isEmpty+ else { return nil }+ let index = MeetingAnalysisCaptureEras.index(containing: seconds, starts: starts)+ return identities.indices.contains(index) ? identities[index] : nil+ }++ func eraEndSeconds(forTrack trackID: MeetingAudioTrackID, index: Int) -> Double {+ guard let starts = self.eraStartsByTrack[trackID] else { return .infinity }+ return MeetingAnalysisCaptureEras.endSeconds(afterIndex: index, starts: starts)+ }++ func anchorSeconds(forTrack trackID: MeetingAudioTrackID, era: MeetingCaptureEraIdentity) -> Double {+ guard let track = self.tracksByID[trackID] else { return 0 }+ return MeetingAnalysisCaptureEras.anchorSeconds(for: era, track: track, origin: self.origin)+ }+}++// MARK: - Validation++nonisolated extension MeetingAnalysisManifest {+ /// Fail-closed structural validation against the frozen plan. Everything it proves is a+ /// property of the manifest measured against the request the host froze: identity and scope+ /// agreement, chunk identity, exactly-once piece coverage of every planned chunk's recorded+ /// interval, finite positive bounds, source/analysis/presentation round-trip, the capture eras+ /// the session actually recorded, copied discontinuities, measured residuals, the canonical+ /// admission rule, exactly one de-drift application, and epoch resets that something really+ /// caused.+ ///+ /// It cannot prove the audio was transcribed, that a decoder's priming report is correct, or+ /// that an admissible era really was acoustically safe. Those are not structural facts.+ @discardableResult+ func validated(against plan: MeetingBackendPlan) throws -> Self {+ let projection = MeetingAnalysisPlanProjection(plan: plan)+ try self.validateHeader(plan: plan, projection: projection)++ var seenTrackIDs = Set<MeetingAudioTrackID>()+ var seenSpanIDs = Set<String>()+ var seenGapIDs = Set<String>()++ for track in self.tracks {+ guard seenTrackIDs.insert(track.id).inserted else {+ throw MeetingAnalysisManifestError.duplicateTrack(track.id)+ }+ guard let plannedKind = plan.trackKindsByID[track.id] else {+ throw MeetingAnalysisManifestError.trackOutOfScope(track.id)+ }+ guard plannedKind == track.kind else {+ throw MeetingAnalysisManifestError.trackKindMismatch(track.id)+ }++ for span in track.spans {+ guard seenSpanIDs.insert(span.id).inserted else {+ throw MeetingAnalysisManifestError.duplicateSpanID(span.id)+ }+ try self.validateSpan(span, track: track, projection: projection)+ }+ for gap in track.gaps {+ guard seenGapIDs.insert(gap.id).inserted else {+ throw MeetingAnalysisManifestError.duplicateGapID(gap.id)+ }+ try self.validateGap(gap, track: track, projection: projection)+ }++ try self.validatePieceCoverage(of: track, projection: projection)+ try self.validateEpochRecords(of: track)+ try self.validateAnalysisTimeline(of: track)+ try self.validateEpochBoundaries(of: track)+ }++ for trackID in plan.trackKindsByID.keys where !seenTrackIDs.contains(trackID) {+ throw MeetingAnalysisManifestError.missingPlannedTrack(trackID)+ }+ return self+ }++ private func validateHeader(+ plan: MeetingBackendPlan,+ projection: MeetingAnalysisPlanProjection+ ) throws {+ guard self.schemaVersion == MeetingAnalysisManifestSchema.currentVersion else {+ throw MeetingAnalysisManifestError.unsupportedSchemaVersion(self.schemaVersion)+ }+ guard self.backendID == plan.backendID else {+ throw MeetingAnalysisManifestError.backendMismatch(+ expected: plan.backendID, actual: self.backendID+ )+ }+ guard self.backendVersion == plan.backendVersion else {+ throw MeetingAnalysisManifestError.backendVersionMismatch(+ expected: plan.backendVersion, actual: self.backendVersion+ )+ }+ guard self.attemptID == plan.attemptID else {+ throw MeetingAnalysisManifestError.attemptMismatch(+ expected: plan.attemptID, actual: self.attemptID+ )+ }+ guard self.sessionID == plan.request.session.id else {+ throw MeetingAnalysisManifestError.sessionMismatch(+ expected: plan.request.session.id, actual: self.sessionID+ )+ }+ guard self.captureMode == plan.request.session.mode else {+ throw MeetingAnalysisManifestError.captureModeMismatch(+ expected: plan.request.session.mode, actual: self.captureMode+ )+ }+ // The origin is not a free parameter: every interval here is relative to it, so a manifest+ // that picks its own would silently move every timestamp the product shows.+ guard self.presentationOriginSeconds.isFinite,+ self.presentationOriginSeconds == projection.origin+ else {+ throw MeetingAnalysisManifestError.presentationOriginMismatch(+ expected: projection.origin, actual: self.presentationOriginSeconds+ )+ }+ if let analysisSampleRate = self.analysisSampleRate {+ guard analysisSampleRate.isFinite, analysisSampleRate > 0 else {+ throw MeetingAnalysisManifestError.invalidAnalysisSampleRate+ }+ }+ guard self.residualBoundSeconds.isFinite, self.residualBoundSeconds > 0 else {+ throw MeetingAnalysisManifestError.invalidResidualBound+ }+ }++ // MARK: Spans++ private func validateSpan(+ _ span: MeetingAnalysisSpan,+ track: MeetingAnalysisTrackManifest,+ projection: MeetingAnalysisPlanProjection+ ) throws {+ let tolerance = MeetingAnalysisManifestSchema.mappingToleranceSeconds+ guard span.chunk.trackID == track.id, span.trackKind == track.kind else {+ throw MeetingAnalysisManifestError.spanTrackCrossing(spanID: span.id)+ }+ let expectedID = MeetingAnalysisSpan.stableID(+ attemptID: self.attemptID, chunk: span.chunk, pieceIndex: span.pieceIndex+ )+ guard span.id == expectedID else {+ throw MeetingAnalysisManifestError.unstableSpanID(expected: expectedID, actual: span.id)+ }+ let (chunk, recordedChunkInterval) = try self.plannedChunk(for: span.chunk, projection: projection)+ guard let recordedChunkInterval else {+ // A chunk with no positive recorded interval can only be a gap.+ throw MeetingAnalysisManifestError.invalidRecordedInterval(pieceID: span.id)+ }+ guard span.recordedInterval.isValid,+ recordedChunkInterval.contains(span.recordedInterval)+ else {+ throw MeetingAnalysisManifestError.invalidRecordedInterval(pieceID: span.id)+ }+ guard span.sourceLocalInterval.isValid else {+ throw MeetingAnalysisManifestError.invalidSourceLocalInterval(spanID: span.id)+ }+ guard span.analysisInterval.isValid else {+ throw MeetingAnalysisManifestError.invalidAnalysisInterval(spanID: span.id)+ }+ guard span.presentationInterval.isValid else {+ throw MeetingAnalysisManifestError.invalidPresentationInterval(spanID: span.id)+ }++ // Observed identity must match the frozen request's stored identity exactly. The stored+ // digest is already bound to the plan by `plannedChunk(for:projection:)` above.+ guard span.observed.byteCount == span.chunk.storedByteCount,+ span.observed.sha256 == span.chunk.storedSHA256+ else {+ throw MeetingAnalysisManifestError.observedIdentityDisagreesWithStored(spanID: span.id)+ }++ let decoded = span.observed.decoded+ guard decoded.sampleRate.isFinite, decoded.sampleRate > 0,+ decoded.channelCount > 0,+ decoded.frameCount > 0,+ decoded.durationSeconds.isFinite, decoded.durationSeconds > 0+ else {+ throw MeetingAnalysisManifestError.invalidDecodedFacts(spanID: span.id)+ }+ guard abs(decoded.durationSeconds - Double(decoded.frameCount) / decoded.sampleRate) <= tolerance else {+ throw MeetingAnalysisManifestError.decodedDurationInconsistent(spanID: span.id)+ }+ if let primingFrames = decoded.codecPriming.measuredFrames {+ guard primingFrames >= 0, Int64(primingFrames) < decoded.frameCount else {+ throw MeetingAnalysisManifestError.primingFramesExceedDecodedFrames(spanID: span.id)+ }+ }++ let era = try self.validatedEra(+ of: span.captureEra,+ pieceID: span.id,+ recordedInterval: span.recordedInterval,+ track: track,+ projection: projection+ )+ let admission = MeetingSpanAdmission(+ captureMode: self.captureMode,+ trackKind: span.trackKind,+ echoProtection: era.echoProtection+ )+ guard span.admission == admission else {+ throw MeetingAnalysisManifestError.admissionRuleMismatch(spanID: span.id)+ }+ guard span.admission.decision == .admissible else {+ throw MeetingAnalysisManifestError.inadmissibleSpan(spanID: span.id)+ }++ try self.validateSourceMapping(span, chunkInterval: recordedChunkInterval)+ try self.validateTransform(span, era: era, track: track, projection: projection)+ try self.validateTiming(span, chunkInterval: recordedChunkInterval, era: era, projection: projection)++ let expectedDiscontinuity = MeetingSpanDiscontinuityFacts.make(+ chunk: chunk,+ previousChunk: self.previousPlannedChunk(before: chunk, track: track.id, projection: projection),+ origin: projection.origin+ )+ guard span.discontinuity == expectedDiscontinuity else {+ throw MeetingAnalysisManifestError.discontinuityDisagreesWithPlan(spanID: span.id)+ }++ guard span.analysisEpochID.trackID == track.id else {+ throw MeetingAnalysisManifestError.spanEpochTrackCrossing(spanID: span.id)+ }+ guard span.analysisEpochID.ordinal >= 0 else {+ throw MeetingAnalysisManifestError.invalidEpochOrdinal(spanID: span.id)+ }+ guard span.analysisEpochID.generation >= 0 else {+ throw MeetingAnalysisManifestError.invalidEpochGeneration(span.analysisEpochID)+ }+ guard track.epochs.contains(where: { $0.id == span.analysisEpochID }) else {+ throw MeetingAnalysisManifestError.unknownSpanEpoch(spanID: span.id)+ }+ }++ /// The valid source region is the recorded piece translated into file-local time, past any+ /// measured priming, truncated only where the decoder actually ran out of audio.+ private func validateSourceMapping(+ _ span: MeetingAnalysisSpan,+ chunkInterval: MeetingAnalysisInterval+ ) throws {+ let tolerance = MeetingAnalysisManifestSchema.mappingToleranceSeconds+ let decoded = span.observed.decoded+ let priming = decoded.primingSeconds ?? 0+ let expectedStart = priming + (span.recordedInterval.start - chunkInterval.start)+ let expectedEnd = min(+ priming + (span.recordedInterval.end - chunkInterval.start),+ decoded.durationSeconds+ )+ guard abs(span.sourceLocalInterval.start - expectedStart) <= tolerance,+ abs(span.sourceLocalInterval.end - expectedEnd) <= tolerance+ else {+ throw MeetingAnalysisManifestError.sourceLocalIntervalDisagreesWithRecordedPiece(spanID: span.id)+ }+ // No fabricated samples: the valid source region must be inside audio a decoder reported.+ guard span.sourceLocalInterval.end <= decoded.durationSeconds + tolerance else {+ throw MeetingAnalysisManifestError.sourceLocalIntervalDisagreesWithRecordedPiece(spanID: span.id)+ }+ // Analysis time is the concatenation of valid source regions, so its duration is theirs.+ guard abs(span.analysisInterval.duration - span.sourceLocalInterval.duration) <= tolerance else {+ throw MeetingAnalysisManifestError.analysisDurationDisagreesWithSource(spanID: span.id)+ }+ }++ private func validateTransform(+ _ span: MeetingAnalysisSpan,+ era: MeetingCaptureEraIdentity,+ track: MeetingAnalysisTrackManifest,+ projection: MeetingAnalysisPlanProjection+ ) throws {+ let tolerance = MeetingAnalysisManifestSchema.mappingToleranceSeconds+ let transform = span.presentationMapping+ guard transform.rateRatio.isFinite, transform.rateRatio > 0,+ transform.offsetSeconds.isFinite+ else {+ throw MeetingAnalysisManifestError.invalidTransform(spanID: span.id)+ }+ guard transform.analysisRemovesGaps else {+ throw MeetingAnalysisManifestError.analysisMustRemoveGaps(spanID: span.id)+ }+ guard let sessionTrack = projection.tracksByID[track.id],+ transform.hostClockAnchor == sessionTrack.timebase.startedHostTime+ else {+ throw MeetingAnalysisManifestError.hostClockAnchorMismatch(spanID: span.id)+ }++ let decoded = span.observed.decoded+ switch (self.analysisSampleRate, transform.sampleRateConversionRatio) {+ case let (.some(analysisRate), .some(ratio)):+ guard ratio.isFinite, ratio > 0,+ abs(ratio - decoded.sampleRate / analysisRate) <= tolerance+ else {+ throw MeetingAnalysisManifestError.sampleRateConversionRatioMismatch(spanID: span.id)+ }+ case (.none, .none):+ break+ case (.some, .none), (.none, .some):+ // An unknown analysis rate has no ratio, and a known one always has exactly one.+ throw MeetingAnalysisManifestError.sampleRateConversionRatioMismatch(spanID: span.id)+ }++ switch (decoded.primingSeconds, transform.codecPrimingCompensationSeconds) {+ case let (.some(measured), .some(compensation)):+ guard compensation.isFinite, abs(compensation - measured) <= tolerance else {+ throw MeetingAnalysisManifestError.primingCompensationMismatch(spanID: span.id)+ }+ case (.none, .none):+ break+ case (.some, .none), (.none, .some):+ // Unknown priming is never a silent zero-second compensation, and measured priming is+ // never silently left uncompensated.+ throw MeetingAnalysisManifestError.primingCompensationMismatch(spanID: span.id)+ }++ // Affine round-trip: the declared transform must actually produce the declared interval.+ let mappedStart = transform.presentationTime(forAnalysisTime: span.analysisInterval.start)+ let mappedEnd = transform.presentationTime(forAnalysisTime: span.analysisInterval.end)+ let affineTolerance = max(+ tolerance,+ tolerance * max(abs(span.analysisInterval.end), 1) * max(transform.rateRatio, 1)+ )+ guard abs(mappedStart - span.presentationInterval.start) <= affineTolerance,+ abs(mappedEnd - span.presentationInterval.end) <= affineTolerance+ else {+ throw MeetingAnalysisManifestError.transformDisagreesWithIntervals(spanID: span.id)+ }++ // And the presentation interval must be where this era's de-drift actually puts the+ // recorded piece — not somewhere a self-consistent but invented transform reaches.+ let anchor = projection.anchorSeconds(forTrack: track.id, era: era)+ let expectedStart = anchor + (span.recordedInterval.start - anchor) * transform.rateRatio+ let expectedEnd = expectedStart + span.analysisInterval.duration * transform.rateRatio+ let slack = max(affineTolerance, tolerance * max(abs(anchor), 1) * max(transform.rateRatio, 1))+ guard abs(span.presentationInterval.start - expectedStart) <= slack,+ abs(span.presentationInterval.end - expectedEnd) <= slack+ else {+ throw MeetingAnalysisManifestError.presentationMappingDisagreesWithPlan(spanID: span.id)+ }+ }++ private func validateTiming(+ _ span: MeetingAnalysisSpan,+ chunkInterval: MeetingAnalysisInterval,+ era: MeetingCaptureEraIdentity,+ projection: MeetingAnalysisPlanProjection+ ) throws {+ let tolerance = MeetingAnalysisManifestSchema.mappingToleranceSeconds+ guard span.timing.residualBoundSeconds == self.residualBoundSeconds else {+ throw MeetingAnalysisManifestError.spanResidualBoundMismatch(spanID: span.id)+ }++ // Exactly one owner of the de-drift correction: the decision must be the one this era's+ // own recorded drift fit produces, and the transform must use exactly that rate.+ let anchor = projection.anchorSeconds(forTrack: span.chunk.trackID, era: era)+ let expectedDeDrift = MeetingAnalysisCaptureEras.deDrift(for: era, anchorSeconds: anchor)+ guard span.timing.deDrift == expectedDeDrift else {+ throw MeetingAnalysisManifestError.deDriftDisagreesWithPlan(spanID: span.id)+ }+ let expectedRate = expectedDeDrift.appliedFactor ?? 1+ guard abs(span.presentationMapping.rateRatio - expectedRate) <= tolerance else {+ throw MeetingAnalysisManifestError.driftFactorDisagreesWithTransform(spanID: span.id)+ }++ // The residual is a measurement, not a declaration: mapped decoded length minus the+ // chunk's recorded presentation duration.+ let decoded = span.observed.decoded+ let expectedResidual = decoded.usableDurationSeconds * expectedRate - chunkInterval.duration+ guard let residual = span.timing.fitResidualSeconds,+ residual.isFinite,+ abs(residual - expectedResidual) <= tolerance+ else {+ throw MeetingAnalysisManifestError.residualDisagreesWithObservation(spanID: span.id)+ }+ let expectedCertainty = MeetingSpanTimingMetadata.certainty(+ fitResidualSeconds: residual,+ residualBoundSeconds: span.timing.residualBoundSeconds,+ codecPriming: decoded.codecPriming+ )+ guard span.timing.certainty == expectedCertainty else {+ throw MeetingAnalysisManifestError.invalidTimingCertainty(spanID: span.id)+ }+ }++ // MARK: Gaps++ private func validateGap(+ _ gap: MeetingAnalysisGap,+ track: MeetingAnalysisTrackManifest,+ projection: MeetingAnalysisPlanProjection+ ) throws {+ guard gap.chunk.trackID == track.id else {+ throw MeetingAnalysisManifestError.gapTrackCrossing(gapID: gap.id)+ }+ let expectedID = MeetingAnalysisGap.stableID(+ attemptID: self.attemptID, chunk: gap.chunk, pieceIndex: gap.pieceIndex+ )+ guard gap.id == expectedID else {+ throw MeetingAnalysisManifestError.unstableGapID(expected: expectedID, actual: gap.id)+ }+ let (_, recordedChunkInterval) = try self.plannedChunk(for: gap.chunk, projection: projection)++ switch (gap.recordedInterval, recordedChunkInterval) {+ case let (.some(interval), .some(chunkInterval)):+ guard interval.isValid, chunkInterval.contains(interval) else {+ throw MeetingAnalysisManifestError.invalidRecordedInterval(pieceID: gap.id)+ }+ guard gap.reason != .chunkHasNoRecordedInterval else {+ throw MeetingAnalysisManifestError.gapReasonInconsistent(gapID: gap.id)+ }+ case (.some, .none):+ throw MeetingAnalysisManifestError.invalidRecordedInterval(pieceID: gap.id)+ case (.none, .some):+ // A positive recorded interval may never be hidden behind a missing piece interval.+ throw MeetingAnalysisManifestError.invalidRecordedInterval(pieceID: gap.id)+ case (.none, .none):+ guard gap.reason == .chunkHasNoRecordedInterval else {+ throw MeetingAnalysisManifestError.gapReasonInconsistent(gapID: gap.id)+ }+ }++ if gap.reason.carriesAdmission {+ guard let interval = gap.recordedInterval,+ let eraIdentity = gap.captureEra+ else {+ throw MeetingAnalysisManifestError.gapAdmissionInconsistent(gapID: gap.id)+ }+ let era = try self.validatedEra(+ of: eraIdentity,+ pieceID: gap.id,+ recordedInterval: interval,+ track: track,+ projection: projection+ )+ let expected = MeetingSpanAdmission(+ captureMode: self.captureMode,+ trackKind: track.kind,+ echoProtection: era.echoProtection+ )+ guard gap.admission == expected, expected.decision == .inadmissible else {+ throw MeetingAnalysisManifestError.gapAdmissionInconsistent(gapID: gap.id)+ }+ } else {+ guard gap.admission == nil, gap.captureEra == nil else {+ throw MeetingAnalysisManifestError.gapAdmissionInconsistent(gapID: gap.id)+ }+ }+ }++ // MARK: Shared piece checks++ private func plannedChunk(+ for identity: MeetingAnalysisChunkIdentity,+ projection: MeetingAnalysisPlanProjection+ ) throws -> (MeetingAudioChunk, MeetingAnalysisInterval?) {+ guard let chunk = projection.chunksByKey[identity.key] else {+ throw MeetingAnalysisManifestError.chunkOutOfScope(identity.key)+ }+ guard identity == MeetingAnalysisChunkIdentity(trackID: identity.trackID, chunk: chunk) else {+ throw MeetingAnalysisManifestError.chunkIdentityDisagreesWithPlan(identity.key)+ }+ return (chunk, projection.recordedInterval(of: chunk))+ }++ /// A piece's era must be the era the frozen session recorded for that interval, and the piece+ /// must lie wholly inside it — that is what makes splitting at era boundaries load-bearing.+ private func validatedEra(+ of identity: MeetingCaptureEraIdentity,+ pieceID: String,+ recordedInterval: MeetingAnalysisInterval,+ track: MeetingAnalysisTrackManifest,+ projection: MeetingAnalysisPlanProjection+ ) throws -> MeetingCaptureEraIdentity {+ let tolerance = MeetingAnalysisManifestSchema.mappingToleranceSeconds+ guard let expected = projection.eraIdentity(+ forTrack: track.id, containing: recordedInterval.start+ ), expected == identity else {+ throw MeetingAnalysisManifestError.captureEraDisagreesWithPlan(pieceID: pieceID)+ }+ let eraEnd = projection.eraEndSeconds(forTrack: track.id, index: identity.index)+ guard recordedInterval.end <= eraEnd + tolerance else {+ throw MeetingAnalysisManifestError.recordedIntervalCrossesCaptureEra(pieceID: pieceID)+ }+ return expected+ }++ private func previousPlannedChunk(+ before chunk: MeetingAudioChunk,+ track trackID: MeetingAudioTrackID,+ projection: MeetingAnalysisPlanProjection+ ) -> MeetingAudioChunk? {+ guard let planned = projection.plannedChunksByTrack[trackID],+ let index = planned.firstIndex(where: { $0.id == chunk.id }),+ index > 0+ else { return nil }+ return planned[index - 1]+ }++ // MARK: Coverage++ /// Exactly-once coverage, in both directions: every planned chunk is covered by pieces that+ /// tile its recorded interval with no hole and no overlap, and nothing outside the plan is+ /// covered at all.+ private func validatePieceCoverage(+ of track: MeetingAnalysisTrackManifest,+ projection: MeetingAnalysisPlanProjection+ ) throws {+ let tolerance = MeetingAnalysisManifestSchema.mappingToleranceSeconds+ let ordered = track.orderedPieces+ guard track.spans.map(\.id) == ordered.compactMap({ piece -> String? in+ if case .span = piece { return piece.id }+ return nil+ }), track.gaps.map(\.id) == ordered.compactMap({ piece -> String? in+ if case .gap = piece { return piece.id }+ return nil+ }) else {+ throw MeetingAnalysisManifestError.pieceOrderInvalid(trackID: track.id)+ }++ var piecesByChunk: [MeetingAnalysisChunkKey: [MeetingAnalysisPiece]] = [:]+ for piece in ordered {+ piecesByChunk[piece.chunk.key, default: []].append(piece)+ }++ let planned = projection.plannedChunksByTrack[track.id] ?? []+ for (key, pieces) in piecesByChunk {+ guard planned.contains(where: { $0.id == key.chunkID }), key.trackID == track.id else {+ throw MeetingAnalysisManifestError.chunkOutOfScope(key)+ }+ guard pieces.map(\.pieceIndex) == Array(0..<pieces.count) else {+ throw MeetingAnalysisManifestError.chunkPieceIndicesInvalid(key)+ }+ }++ for chunk in planned {+ let key = MeetingAnalysisChunkKey(trackID: track.id, chunkID: chunk.id)+ guard let pieces = piecesByChunk[key], !pieces.isEmpty else {+ throw MeetingAnalysisManifestError.plannedChunkUncovered(key)+ }+ guard let recorded = projection.recordedInterval(of: chunk) else {+ // No positive interval to tile: one gap accounts for the whole chunk, and it is the+ // only shape in which a piece may omit its interval.+ guard pieces.count == 1, pieces[0].recordedInterval == nil else {+ throw MeetingAnalysisManifestError.chunkPieceCoverageInvalid(key)+ }+ continue+ }+ var cursor = recorded.start+ for piece in pieces {+ guard let interval = piece.recordedInterval,+ abs(interval.start - cursor) <= tolerance,+ interval.end > interval.start+ else {+ throw MeetingAnalysisManifestError.chunkPieceCoverageInvalid(key)+ }+ cursor = interval.end+ }+ guard abs(cursor - recorded.end) <= tolerance else {+ throw MeetingAnalysisManifestError.chunkPieceCoverageInvalid(key)+ }+ }+ }++ // MARK: Epochs++ private func validateEpochRecords(of track: MeetingAnalysisTrackManifest) throws {+ let tolerance = MeetingAnalysisManifestSchema.mappingToleranceSeconds+ var seenEpochIDs = Set<MeetingAnalysisEpochID>()+ for epoch in track.epochs {+ guard seenEpochIDs.insert(epoch.id).inserted else {+ throw MeetingAnalysisManifestError.duplicateEpoch(epoch.id)+ }+ guard epoch.id.trackID == track.id else {+ throw MeetingAnalysisManifestError.epochTrackCrossing(epoch.id)+ }+ guard epoch.id.generation >= 0 else {+ throw MeetingAnalysisManifestError.invalidEpochGeneration(epoch.id)+ }+ let members = track.spans.filter { $0.analysisEpochID == epoch.id }+ guard !members.isEmpty, !epoch.spanIDs.isEmpty else {+ throw MeetingAnalysisManifestError.emptyEpoch(epoch.id)+ }+ guard members.map(\.id) == epoch.spanIDs else {+ throw MeetingAnalysisManifestError.epochSpanMembershipMismatch(epoch.id)+ }+ guard let first = members.map(\.analysisInterval.start).min(),+ let last = members.map(\.analysisInterval.end).max(),+ abs(epoch.analysisInterval.start - first) <= tolerance,+ abs(epoch.analysisInterval.end - last) <= tolerance,+ epoch.analysisInterval.isValid+ else {+ throw MeetingAnalysisManifestError.epochIntervalMismatch(epoch.id)+ }+ // Only the first epoch may be a plain track start; every later one states what broke.+ if epoch.id.ordinal > 0, epoch.resetReason == .trackStart {+ throw MeetingAnalysisManifestError.invalidEpochResetReason(epoch.id)+ }+ if epoch.id.ordinal == 0, epoch.resetReason != .trackStart {+ throw MeetingAnalysisManifestError.invalidEpochResetReason(epoch.id)+ }+ }+ let ordinals = track.epochs.map(\.id.ordinal)+ guard ordinals == Array(0..<ordinals.count) else {+ throw MeetingAnalysisManifestError.nonContiguousEpochOrdinals(trackID: track.id)+ }+ }++ /// An epoch boundary is a claim that model state could not be carried across it. This walks the+ /// track's pieces and proves the claim both ways: every boundary has a cause, and every cause+ /// produced a boundary.+ private func validateEpochBoundaries(of track: MeetingAnalysisTrackManifest) throws {+ let reasonsByEpoch = Dictionary(+ track.epochs.map { ($0.id, $0.resetReason) },+ uniquingKeysWith: { first, _ in first }+ )+ var previousSpan: MeetingAnalysisSpan?+ var pendingGapReasons: Set<MeetingAnalysisEpochResetReason> = []++ for piece in track.orderedPieces {+ switch piece {+ case let .gap(gap):+ pendingGapReasons.insert(gap.reason.epochResetReason)+ case let .span(span):+ guard let resetReason = reasonsByEpoch[span.analysisEpochID] else {+ throw MeetingAnalysisManifestError.unknownSpanEpoch(spanID: span.id)+ }+ defer {+ pendingGapReasons.removeAll()+ previousSpan = span+ }+ guard let previous = previousSpan else {+ // The first analysable audio on a track always opens epoch 0.+ guard span.analysisEpochID.ordinal == 0, resetReason == .trackStart else {+ throw MeetingAnalysisManifestError.invalidEpochResetReason(span.analysisEpochID)+ }+ continue+ }+ let causes = Self.epochResetCauses(+ previousSpan: previous,+ span: span,+ pendingGapReasons: pendingGapReasons+ )+ if span.analysisEpochID == previous.analysisEpochID {+ guard causes.isEmpty else {+ throw MeetingAnalysisManifestError.missingEpochBoundary(spanID: span.id)+ }+ } else {+ guard span.analysisEpochID.ordinal == previous.analysisEpochID.ordinal + 1 else {+ throw MeetingAnalysisManifestError.invalidEpochOrdinal(spanID: span.id)+ }+ guard !causes.isEmpty else {+ throw MeetingAnalysisManifestError.unjustifiedEpochBoundary(spanID: span.id)+ }+ guard causes.contains(resetReason) else {+ throw MeetingAnalysisManifestError.invalidEpochResetReason(span.analysisEpochID)+ }+ }+ }+ }+ }++ /// Everything that could legitimately break the analysis epoch immediately before `span`.+ /// Empty means the audio ran on continuously and admissibly, so the epoch must continue.+ static func epochResetCauses(+ previousSpan: MeetingAnalysisSpan,+ span: MeetingAnalysisSpan,+ pendingGapReasons: Set<MeetingAnalysisEpochResetReason>+ ) -> Set<MeetingAnalysisEpochResetReason> {+ self.epochResetCauses(+ previousEra: previousSpan.captureEra,+ era: span.captureEra,+ pieceIndex: span.pieceIndex,+ recordedStart: span.recordedInterval.start,+ discontinuity: span.discontinuity,+ pendingGapReasons: pendingGapReasons+ )+ }++ /// The rule itself, in terms the builder can evaluate before it has an epoch to assign.+ /// Metadata-only era changes — display name, elected role, settled configuration, drift record —+ /// deliberately do not appear here: implementation plan §3 keeps the epoch running when the+ /// input itself is unchanged and admissible.+ static func epochResetCauses(+ previousEra: MeetingCaptureEraIdentity,+ era: MeetingCaptureEraIdentity,+ pieceIndex: Int,+ recordedStart: TimeInterval,+ discontinuity: MeetingSpanDiscontinuityFacts,+ pendingGapReasons: Set<MeetingAnalysisEpochResetReason>+ ) -> Set<MeetingAnalysisEpochResetReason> {+ var causes = pendingGapReasons+ if !previousEra.isSameInput(as: era) {+ causes.insert(.microphoneDeviceChanged)+ }+ let tolerance = MeetingAnalysisManifestSchema.mappingToleranceSeconds+ let hasTimedBoundaryHere = discontinuity.boundaries.contains {+ $0.presentationSeconds.map { abs($0 - recordedStart) <= tolerance } ?? false+ }+ let hasUnpositionedBoundaryAtChunkStart = pieceIndex == 0+ && discontinuity.boundaries.contains(where: { $0.presentationSeconds == nil })+ if hasTimedBoundaryHere+ || hasUnpositionedBoundaryAtChunkStart+ || (pieceIndex == 0 && discontinuity.precededByChunkTimeGap)+ {+ causes.insert(.chunkDiscontinuity)+ }+ return causes+ }++ /// Deterministic choice among equally valid causes, so a rebuild of the same attempt produces+ /// the same reset reason. Safety-relevant causes are named ahead of mechanical ones.+ static func preferredEpochResetReason(+ among causes: Set<MeetingAnalysisEpochResetReason>+ ) -> MeetingAnalysisEpochResetReason? {+ [+ .inadmissibleCaptureEra,+ .missingOrUnreadableAudio,+ .microphoneDeviceChanged,+ .chunkDiscontinuity,+ ].first(where: causes.contains)+ }++ // MARK: Timeline++ /// Analysis time is per track: it starts at zero, concatenates its spans with no gaps at all,+ /// and never runs backwards.+ ///+ /// Presentation time keeps the gaps and must stay ordered *within one capture era*. Across an+ /// era boundary the de-drift correction re-anchors, and the existing per-era correction can+ /// legitimately place the end of one era after the recorded start of the next — that is a+ /// property of the recording, not of this manifest, so it is not laundered into an ordering+ /// claim the audio does not support.+ private func validateAnalysisTimeline(of track: MeetingAnalysisTrackManifest) throws {+ let tolerance = MeetingAnalysisManifestSchema.mappingToleranceSeconds+ var expectedAnalysisStart: TimeInterval = 0+ var previous: MeetingAnalysisSpan?+ for span in track.spans {+ guard abs(span.analysisInterval.start - expectedAnalysisStart) <= tolerance else {+ throw MeetingAnalysisManifestError.analysisTimeNotGapRemoved(trackID: track.id)+ }+ if let previous {+ if previous.captureEra.index == span.captureEra.index,+ span.presentationInterval.start < previous.presentationInterval.end - tolerance+ {+ throw MeetingAnalysisManifestError.nonMonotonicPresentationTime(trackID: track.id)+ }+ if span.analysisEpochID.ordinal < previous.analysisEpochID.ordinal {+ throw MeetingAnalysisManifestError.nonMonotonicAnalysisTime(trackID: track.id)+ }+ if span.recordedInterval.start < previous.recordedInterval.end - tolerance {+ throw MeetingAnalysisManifestError.nonMonotonicPresentationTime(trackID: track.id)+ }+ }+ expectedAnalysisStart = span.analysisInterval.end+ previous = span+ }+ }+}diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingAnalysisManifestBuilder.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingAnalysisManifestBuilder.swiftnew file mode 100644index 00000000..392a8142--- /dev/null+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingAnalysisManifestBuilder.swift@@ -0,0 +1,465 @@+import Foundation++// Stage C2a assembler of the analysis manifest. It reads a frozen `MeetingBackendPlan`, observes+// every planned chunk through an injected boundary, and produces the immutable+// `MeetingAnalysisManifest` the rest of Stage C will map evidence through.+//+// What it will not do is as important as what it does:+//+// - it never invents audio: a chunk it cannot find, verify or decode becomes a typed gap;+// - it never mixes application and microphone audio, and never shares analysis time between them;+// - it applies the existing VPIO de-drift correction exactly once, per capture era, and records+// that it did — so a second correction downstream would contradict a stored fact;+// - it splits a chunk at capture-era boundaries instead of judging the whole chunk by one era, so+// the safe part of a chunk stays analysable and only the unsafe part becomes an explicit gap;+// - it returns nothing that does not pass `validated(against:)`, so a bug here surfaces as a+// refusal rather than as a manifest the rest of the stage would trust.+//+// Nothing here writes a file, creates a product speaker ID, or applies echo policy.++nonisolated struct MeetingAnalysisManifestBuilder {+ let plan: MeetingBackendPlan+ let observer: any MeetingChunkAudioObserving+ /// The backend's real resampler rate, when this build knows it. `nil` leaves every span's+ /// sample-rate conversion ratio explicitly unknown rather than implying 1.+ let analysisSampleRate: Double?+ let residualBoundSeconds: Double+ /// Generation overrides supplied by retry/checkpoint orchestration. Completed epochs retain+ /// their generation; a replayed epoch receives a larger one and therefore new speaker IDs.+ let epochGenerations: [MeetingAnalysisEpochGenerationKey: Int]++ init(+ plan: MeetingBackendPlan,+ observer: any MeetingChunkAudioObserving,+ analysisSampleRate: Double? = nil,+ residualBoundSeconds: Double = MeetingAnalysisManifestSchema.defaultResidualBoundSeconds,+ epochGenerations: [MeetingAnalysisEpochGenerationKey: Int] = [:]+ ) {+ self.plan = plan+ self.observer = observer+ self.analysisSampleRate = analysisSampleRate+ self.residualBoundSeconds = residualBoundSeconds+ self.epochGenerations = epochGenerations+ }++ /// Builds and validates. The returned manifest has already been checked against the frozen+ /// plan, so a caller never has to decide whether to trust it.+ func build() throws -> MeetingAnalysisManifest {+ let projection = MeetingAnalysisPlanProjection(plan: self.plan)+ let session = self.plan.request.session+ // Recorded track order, filtered to planned tracks: application and microphone streams stay+ // separate manifests with separate analysis timelines and separate epoch spaces.+ let tracks = try session.audioTracks+ .filter { self.plan.trackKindsByID[$0.id] != nil }+ .map { try self.buildTrack($0, projection: projection) }++ let manifest = MeetingAnalysisManifest(+ backendID: self.plan.backendID,+ backendVersion: self.plan.backendVersion,+ attemptID: self.plan.attemptID,+ sessionID: session.id,+ captureMode: session.mode,+ presentationOriginSeconds: projection.origin,+ analysisSampleRate: self.analysisSampleRate,+ residualBoundSeconds: self.residualBoundSeconds,+ tracks: tracks+ )+ return try manifest.validated(against: self.plan)+ }++ // MARK: - Per-track assembly++ /// Mutable state while walking one track's planned chunks in sequence order.+ private struct TrackAccumulator {+ var spans: [MeetingAnalysisSpan] = []+ var gaps: [MeetingAnalysisGap] = []+ var epochReasons: [MeetingAnalysisEpochID: MeetingAnalysisEpochResetReason] = [:]+ var epochOrder: [MeetingAnalysisEpochID] = []+ var analysisCursor: TimeInterval = 0+ var currentEpochID: MeetingAnalysisEpochID?+ var previousSpan: MeetingAnalysisSpan?+ var pendingGapReasons: Set<MeetingAnalysisEpochResetReason> = []+ }++ private func buildTrack(+ _ track: MeetingAudioTrack,+ projection: MeetingAnalysisPlanProjection+ ) throws -> MeetingAnalysisTrackManifest {+ var accumulator = TrackAccumulator()+ let plannedChunks = projection.plannedChunksByTrack[track.id] ?? []++ for (offset, chunk) in plannedChunks.enumerated() {+ try Task.checkCancellation()+ let identity = MeetingAnalysisChunkIdentity(trackID: track.id, chunk: chunk)+ let discontinuity = MeetingSpanDiscontinuityFacts.make(+ chunk: chunk,+ previousChunk: offset > 0 ? plannedChunks[offset - 1] : nil,+ origin: projection.origin+ )+ self.appendChunk(+ chunk,+ identity: identity,+ discontinuity: discontinuity,+ track: track,+ projection: projection,+ into: &accumulator+ )+ try Task.checkCancellation()+ }++ let epochs = accumulator.epochOrder.map { epochID in+ let members = accumulator.spans.filter { $0.analysisEpochID == epochID }+ return MeetingAnalysisEpochRecord(+ id: epochID,+ resetReason: accumulator.epochReasons[epochID] ?? .trackStart,+ spanIDs: members.map(\.id),+ analysisInterval: MeetingAnalysisInterval(+ start: members.map(\.analysisInterval.start).min() ?? 0,+ end: members.map(\.analysisInterval.end).max() ?? 0+ )+ )+ }+ return MeetingAnalysisTrackManifest(+ id: track.id,+ kind: track.kind,+ spans: accumulator.spans,+ gaps: accumulator.gaps,+ epochs: epochs+ )+ }++ // MARK: - Per-chunk assembly++ private func appendChunk(+ _ chunk: MeetingAudioChunk,+ identity: MeetingAnalysisChunkIdentity,+ discontinuity: MeetingSpanDiscontinuityFacts,+ track: MeetingAudioTrack,+ projection: MeetingAnalysisPlanProjection,+ into accumulator: inout TrackAccumulator+ ) {+ let recorded = projection.recordedInterval(of: chunk)++ guard chunk.finalizationState == .finalized else {+ // Defensive: planning excludes these, so reaching here means the plan and the session+ // disagree. Refusing the audio is the only safe reading.+ self.appendGap(+ identity: identity,+ pieceIndex: 0,+ reason: .chunkNotFinalized,+ recordedInterval: recorded,+ era: nil,+ detail: chunk.finalizationState.rawValue,+ into: &accumulator+ )+ return+ }+ guard let recorded else {+ self.appendGap(+ identity: identity,+ pieceIndex: 0,+ reason: .chunkHasNoRecordedInterval,+ recordedInterval: nil,+ era: nil,+ detail: "Recorded presentation bounds are not a positive interval.",+ into: &accumulator+ )+ return+ }++ let observation = self.observer.observe(chunk: chunk, trackID: track.id)+ guard case let .observed(observed) = observation else {+ guard case let .failed(failure, detail) = observation else { return }+ // One unreadable file is one hole, whatever eras it would have crossed.+ self.appendGap(+ identity: identity,+ pieceIndex: 0,+ reason: failure.gapReason,+ recordedInterval: recorded,+ era: nil,+ detail: detail,+ into: &accumulator+ )+ return+ }++ var nextPieceIndex = 0+ for piece in self.eraPieces(+ of: recorded,+ chunk: chunk,+ track: track,+ projection: projection+ ) {+ nextPieceIndex += self.appendPiece(+ piece,+ pieceIndex: nextPieceIndex,+ identity: identity,+ chunkInterval: recorded,+ observed: observed,+ discontinuity: discontinuity,+ track: track,+ projection: projection,+ into: &accumulator+ )+ }+ }++ /// Splits a chunk's recorded interval at every capture-era start that falls strictly inside it.+ /// The result tiles the interval exactly, so a mid-chunk era change costs only the part of the+ /// chunk that actually belongs to the other era.+ private func eraPieces(+ of recorded: MeetingAnalysisInterval,+ chunk: MeetingAudioChunk,+ track: MeetingAudioTrack,+ projection: MeetingAnalysisPlanProjection+ ) -> [MeetingAnalysisInterval] {+ let tolerance = MeetingAnalysisManifestSchema.mappingToleranceSeconds+ let starts = projection.eraStartsByTrack[track.id] ?? [-.infinity]+ let discontinuityStarts = chunk.discontinuities.compactMap {+ $0.presentationTime.map { $0.seconds - projection.origin }+ }+ let candidates = (starts + discontinuityStarts)+ .filter { $0.isFinite && $0 > recorded.start + tolerance && $0 < recorded.end - tolerance }+ .sorted()+ var inner: [Double] = []+ for candidate in candidates where inner.last.map({ abs($0 - candidate) > tolerance }) ?? true {+ inner.append(candidate)+ }+ let bounds = [recorded.start] + inner + [recorded.end]+ return (0..<(bounds.count - 1)).map {+ MeetingAnalysisInterval(start: bounds[$0], end: bounds[$0 + 1])+ }+ }++ private func appendPiece(+ _ piece: MeetingAnalysisInterval,+ pieceIndex: Int,+ identity: MeetingAnalysisChunkIdentity,+ chunkInterval: MeetingAnalysisInterval,+ observed: MeetingChunkObservedAudio,+ discontinuity: MeetingSpanDiscontinuityFacts,+ track: MeetingAudioTrack,+ projection: MeetingAnalysisPlanProjection,+ into accumulator: inout TrackAccumulator+ ) -> Int {+ let tolerance = MeetingAnalysisManifestSchema.mappingToleranceSeconds+ guard let era = projection.eraIdentity(forTrack: track.id, containing: piece.start) else {+ self.appendGap(+ identity: identity,+ pieceIndex: pieceIndex,+ reason: .chunkUnreadable,+ recordedInterval: piece,+ era: nil,+ detail: "The session records no capture era covering this interval.",+ into: &accumulator+ )+ return 1+ }+ let admission = MeetingSpanAdmission(+ captureMode: self.plan.request.session.mode,+ trackKind: track.kind,+ echoProtection: era.echoProtection+ )+ guard admission.decision == .admissible else {+ self.appendGap(+ identity: identity,+ pieceIndex: pieceIndex,+ reason: .inadmissibleCaptureEra,+ recordedInterval: piece,+ era: era,+ detail: admission.rationale.rawValue,+ into: &accumulator+ )+ return 1+ }++ // Source-local time: the recorded piece translated past any measured priming. If the+ // decoder ends partway through this recorded piece, preserve only the backed prefix as a+ // span and account for the remainder as an explicit gap; never let a shorter source region+ // claim coverage of a longer recorded interval.+ let decoded = observed.decoded+ let priming = decoded.primingSeconds ?? 0+ let availableRecordedEnd = chunkInterval.start + max(0, decoded.durationSeconds - priming)+ let spanRecordedEnd = min(piece.end, availableRecordedEnd)+ let spanPiece = MeetingAnalysisInterval(start: piece.start, end: spanRecordedEnd)+ let sourceStart = priming + (spanPiece.start - chunkInterval.start)+ let sourceEnd = priming + (spanPiece.end - chunkInterval.start)+ guard sourceEnd - sourceStart > tolerance, sourceStart >= 0 else {+ self.appendGap(+ identity: identity,+ pieceIndex: pieceIndex,+ reason: .decodedAudioExhausted,+ recordedInterval: piece,+ era: nil,+ detail: String(+ format: "Decoder reported %.6fs of audio for a piece starting at %.6fs.",+ decoded.durationSeconds,+ sourceStart+ ),+ into: &accumulator+ )+ return 1+ }++ let anchor = projection.anchorSeconds(forTrack: track.id, era: era)+ let deDrift = MeetingAnalysisCaptureEras.deDrift(for: era, anchorSeconds: anchor)+ let rateRatio = deDrift.appliedFactor ?? 1+ let analysisStart = accumulator.analysisCursor+ let analysisDuration = sourceEnd - sourceStart+ let presentationStart = anchor + (spanPiece.start - anchor) * rateRatio+ let presentationEnd = presentationStart + analysisDuration * rateRatio++ // The fit residual is a measurement of this chunk, not a declaration: the decoded audio it+ // really holds, mapped through this era's correction, against the duration the recorder+ // claimed for it.+ let residual = decoded.usableDurationSeconds * rateRatio - chunkInterval.duration+ let timing = MeetingSpanTimingMetadata(+ certainty: MeetingSpanTimingMetadata.certainty(+ fitResidualSeconds: residual,+ residualBoundSeconds: self.residualBoundSeconds,+ codecPriming: decoded.codecPriming+ ),+ fitResidualSeconds: residual,+ residualBoundSeconds: self.residualBoundSeconds,+ deDrift: deDrift+ )++ let epochID = self.epochID(+ for: era,+ pieceIndex: pieceIndex,+ recordedStart: spanPiece.start,+ discontinuity: discontinuity,+ track: track,+ into: &accumulator+ )+ let span = MeetingAnalysisSpan(+ id: MeetingAnalysisSpan.stableID(+ attemptID: self.plan.attemptID, chunk: identity, pieceIndex: pieceIndex+ ),+ chunk: identity,+ pieceIndex: pieceIndex,+ trackKind: track.kind,+ analysisEpochID: epochID,+ recordedInterval: spanPiece,+ sourceLocalInterval: MeetingAnalysisInterval(start: sourceStart, end: sourceEnd),+ analysisInterval: MeetingAnalysisInterval(+ start: analysisStart, end: analysisStart + analysisDuration+ ),+ presentationInterval: MeetingAnalysisInterval(+ start: presentationStart, end: presentationEnd+ ),+ presentationMapping: MeetingAnalysisTimeTransform(+ hostClockAnchor: track.timebase.startedHostTime,+ rateRatio: rateRatio,+ offsetSeconds: presentationStart - analysisStart * rateRatio,+ sampleRateConversionRatio: self.analysisSampleRate.map { decoded.sampleRate / $0 },+ codecPrimingCompensationSeconds: decoded.primingSeconds,+ analysisRemovesGaps: true+ ),+ captureEra: era,+ admission: admission,+ observed: observed,+ discontinuity: discontinuity,+ timing: timing+ )+ accumulator.spans.append(span)+ accumulator.analysisCursor = analysisStart + analysisDuration+ accumulator.previousSpan = span+ accumulator.pendingGapReasons.removeAll()+ guard spanRecordedEnd < piece.end - tolerance else { return 1 }+ self.appendGap(+ identity: identity,+ pieceIndex: pieceIndex + 1,+ reason: .decodedAudioExhausted,+ recordedInterval: MeetingAnalysisInterval(start: spanRecordedEnd, end: piece.end),+ era: nil,+ detail: String(+ format: "Decoder audio ended at recorded time %.6fs before this piece ended at %.6fs.",+ spanRecordedEnd,+ piece.end+ ),+ into: &accumulator+ )+ return 2+ }++ private func appendGap(+ identity: MeetingAnalysisChunkIdentity,+ pieceIndex: Int,+ reason: MeetingAnalysisGapReason,+ recordedInterval: MeetingAnalysisInterval?,+ era: MeetingCaptureEraIdentity?,+ detail: String?,+ into accumulator: inout TrackAccumulator+ ) {+ let carriesAdmission = reason.carriesAdmission+ accumulator.gaps.append(MeetingAnalysisGap(+ id: MeetingAnalysisGap.stableID(+ attemptID: self.plan.attemptID, chunk: identity, pieceIndex: pieceIndex+ ),+ chunk: identity,+ pieceIndex: pieceIndex,+ reason: reason,+ recordedInterval: recordedInterval,+ captureEra: carriesAdmission ? era : nil,+ admission: carriesAdmission ? era.map {+ MeetingSpanAdmission(+ captureMode: self.plan.request.session.mode,+ trackKind: self.plan.trackKindsByID[identity.trackID] ?? .microphone,+ echoProtection: $0.echoProtection+ )+ } : nil,+ detail: detail+ ))+ accumulator.pendingGapReasons.insert(reason.epochResetReason)+ }++ // MARK: - Epochs++ /// A new epoch starts only where something really broke the input: a typed gap, a recorded+ /// chunk discontinuity or time gap, or a change of microphone. Otherwise the epoch continues,+ /// so diarizer state is not thrown away for a metadata edit.+ private func epochID(+ for era: MeetingCaptureEraIdentity,+ pieceIndex: Int,+ recordedStart: TimeInterval,+ discontinuity: MeetingSpanDiscontinuityFacts,+ track: MeetingAudioTrack,+ into accumulator: inout TrackAccumulator+ ) -> MeetingAnalysisEpochID {+ guard let previousSpan = accumulator.previousSpan,+ let currentEpochID = accumulator.currentEpochID+ else {+ let epochID = self.epochID(trackID: track.id, ordinal: 0)+ accumulator.currentEpochID = epochID+ accumulator.epochReasons[epochID] = .trackStart+ accumulator.epochOrder.append(epochID)+ return epochID+ }+ let causes = MeetingAnalysisManifest.epochResetCauses(+ previousEra: previousSpan.captureEra,+ era: era,+ pieceIndex: pieceIndex,+ recordedStart: recordedStart,+ discontinuity: discontinuity,+ pendingGapReasons: accumulator.pendingGapReasons+ )+ guard let reason = MeetingAnalysisManifest.preferredEpochResetReason(among: causes) else {+ return currentEpochID+ }+ let epochID = self.epochID(trackID: track.id, ordinal: currentEpochID.ordinal + 1)+ accumulator.currentEpochID = epochID+ accumulator.epochReasons[epochID] = reason+ accumulator.epochOrder.append(epochID)+ return epochID+ }++ private func epochID(trackID: MeetingAudioTrackID, ordinal: Int) -> MeetingAnalysisEpochID {+ let key = MeetingAnalysisEpochGenerationKey(trackID: trackID, ordinal: ordinal)+ return MeetingAnalysisEpochID(+ trackID: trackID,+ ordinal: ordinal,+ generation: self.epochGenerations[key] ?? 0+ )+ }+}diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingAudioChunkSink.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingAudioChunkSink.swiftnew file mode 100644index 00000000..e752a4f2--- /dev/null+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingAudioChunkSink.swift@@ -0,0 +1,116 @@+import AVFoundation+import CoreMedia+import Foundation++/// PCM-first capture boundary beneath `MeetingAudioChunkWriter`. `MeetingAudioChunkWriter` remains+/// the sole ordering/producer-epoch/canonical+/// retiming/format-boundary/gap/splice authority; a sink only durably persists the exact bytes it+/// is handed.+///+/// One accepted `append` call's durability facts. `framesAccepted` is what the caller's timeline+/// counted for this call; `framesWritten` is what the sink actually persisted for the same call.+/// The sink's packet-writing API reports the count it actually accepted. A conforming sink reports+/// `framesWritten == framesAccepted` on success and throws a poisoning short-write error otherwise.+/// A caller comparing the two fields never needs to infer persistence from producer enqueue.+nonisolated struct MeetingPCMAppendReceipt: Equatable, Sendable {+ var framesAccepted: Int64+ var framesWritten: Int64+ var presentationStart: CMTime+ var presentationDuration: CMTime+}++/// Immutable facts about a successfully finalized, durably published container. Every field is+/// independently re-derived from the finalized file on disk after a fresh read-only reopen — never+/// carried forward from the in-memory append tally — so a caller can trust this value even if the+/// in-process writer state were somehow wrong.+nonisolated struct MeetingPCMFinalization: Equatable, Sendable {+ var relativeFilePath: String+ var byteCount: Int64+ var sha256: String+ var sampleRate: Double+ var channelCount: Int+ var frameCount: Int64+}++nonisolated enum MeetingPCMSinkError: Error, Equatable, Sendable {+ case alreadyBegun+ case notBegun+ case unsupportedClientFormat(String)+ case invalidRelativePath(String)+ case pathEscapesSessionDirectory(String)+ case symlinkComponentRejected(String)+ case finalPathAlreadyExists(String)+ case partialPathAlreadyExists(String)+ case invalidSampleBuffer(String)+ case nonFiniteSample+ case formatMismatch(expected: String, actual: String)+ case invalidPresentationTime+ case shortWrite(expectedFrames: Int64, writtenFrames: Int64)+ case writeFailed(OSStatus)+ case alreadyFinalizedOrCancelled+ case finalizationVerificationFailed(String)+ case underlyingFileError(String)+}++nonisolated extension MeetingPCMSinkError: LocalizedError {+ var errorDescription: String? {+ switch self {+ case let .formatMismatch(expected, actual): return "PCM format mismatch (expected \(expected); received \(actual))."+ case let .unsupportedClientFormat(detail): return "Unsupported PCM format: \(detail)."+ case let .shortWrite(expected, written): return "PCM short write (expected \(expected) frames; wrote \(written))."+ case let .writeFailed(status): return "PCM write failed (OSStatus \(status))."+ case let .invalidSampleBuffer(detail): return "Invalid PCM sample buffer: \(detail)."+ case let .finalizationVerificationFailed(detail): return "PCM finalization verification failed: \(detail)."+ case let .underlyingFileError(detail): return "PCM file error: \(detail)."+ default: return String(describing: self)+ }+ }+}++/// Threading contract (load-bearing, not advisory): real-time audio producers may only enqueue+/// work onto the existing serialized, non-real-time writer queue that already owns canonical+/// ordering/timing (e.g. `MeetingAudioChunkWriter`'s internal dispatch queue). Every method on this+/// protocol — `begin`, `append`, and `cancel` — is called exclusively from that one serialized+/// writer queue, off the real-time audio callback thread. After a chunk is removed from active+/// capture, exclusive ownership may transfer to a finalization queue for `finalize`; no append or+/// cancel may then overlap it. No method here performs internal locking against concurrent callers.+///+/// Producer enqueue is not durability: a real-time producer successfully enqueuing a buffer onto+/// the writer queue says nothing about whether that buffer has reached, or will ever reach, stable+/// storage. `append` returning success only means the sink's underlying container write call+/// completed for that one buffer; it is `finalize()` succeeding — after a full close, reopen and+/// decoded-frame/format re-verification — that is this protocol's only durability boundary. A+/// crash, sink failure, or cancellation at any point before `finalize()` returns success must be+/// treated by the caller as an unfinalized/failed chunk, never as a partially-durable one; this+/// protocol makes no partial-recovery claim.+nonisolated protocol MeetingAudioChunkSink: AnyObject, Sendable {+ /// The owned staging path selected by `begin`, when available. This is recorded in the+ /// durability ledger so recovery can identify the exact partial artifact for this chunk.+ var partialRelativeFilePath: String? { get }++ /// Opens the sink for exactly one chunk at `relativeFilePath`, which must be confined to the+ /// implementation's session directory (non-absolute, no traversal, no symlink component).+ /// `contract` is fixed for the sink's entire lifetime: every subsequent `append` must match its+ /// semantic rate/channel/layout identity. Interleaved and planar Float32 payloads are both+ /// accepted only when their AudioBufferList topology validates. May be called at most once.+ func begin(relativeFilePath: String, format: AVAudioFormat, contract: MeetingPCMFormatContract) throws++ /// Appends one already-retimed, already-canonical, ready Float32 LPCM `CMSampleBuffer`. Only+ /// buffers with finite samples, a valid numeric presentation timestamp, and a format matching+ /// the one passed to `begin` are accepted; everything else throws without touching durable+ /// state. No resampling, channel clamping, or sample-value conversion is performed; a sink may+ /// pack planar channels into canonical interleaved storage without changing order or values.+ func append(_ sampleBuffer: CMSampleBuffer) throws -> MeetingPCMAppendReceipt++ /// Finalizes: closes the underlying container, reopens it read-only, verifies decoded frame+ /// count/sample rate/channel count against the sink's own written totals, then atomically+ /// publishes it at its final (non-`.partial`) path only if every check passes. Any poisoning+ /// write recorded by a prior `append`, or any verification failure here, fails this call and+ /// guarantees the final path is never created.+ func finalize() -> Result<MeetingPCMFinalization, MeetingPCMSinkError>++ /// Abandons the in-progress chunk and removes any partial artifact. After `cancel()` — and+ /// after any unresolved write failure — the final (non-`.partial`) path must never come into+ /// existence for this instance.+ func cancel()+}diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingAudioFilePCMChunkSink.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingAudioFilePCMChunkSink.swiftnew file mode 100644index 00000000..fb962694--- /dev/null+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingAudioFilePCMChunkSink.swift@@ -0,0 +1,295 @@+import AudioToolbox+@preconcurrency import AVFoundation+import CoreMedia+import CryptoKit+import Darwin+import Foundation++/// PCM capture sink. The caller owns serialization on a non-real-time queue. The CAF payload is+/// canonical interleaved native-rate Float32 LPCM; non-interleaved input is only packed at the+/// sink boundary (there is no resampling, channel clamp, or quantization).+///+/// Path validation is lexical plus lstat-based. A descriptor-relative `openat`/`renameat` walk+/// is intentionally deferred: a hostile concurrent rename can still create a path TOCTOU window,+/// so this harness must not be described as a production security boundary. The crash harness+/// that kills a subprocess between each durability point is also a follow-up, not production-ready+/// recovery behavior.+final nonisolated class MeetingAudioFilePCMChunkSink: MeetingAudioChunkSink, @unchecked Sendable {+ private enum State { case idle, open, finalized, cancelled }+ private struct Format {+ let rate: Double+ let channels: UInt32+ let layout: Data?+ let contract: MeetingPCMFormatContract+ }+ private struct Paths { let final: URL; let partial: URL }+ private struct Identity { let dev: dev_t; let ino: ino_t; let size: off_t }+ private let sessionDirectory: URL+ private var state: State = .idle+ private var audioFile: AudioFileID?+ private var paths: Paths?+ private var format: Format?+ private var fileASBD: AudioStreamBasicDescription?+ private var writtenPackets: Int64 = 0+ private var poisoned = false++ var partialRelativeFilePath: String? {+ guard let partial = paths?.partial else { return nil }+ let root = sessionDirectory.path.hasSuffix("/") ? sessionDirectory.path : sessionDirectory.path + "/"+ guard partial.path.hasPrefix(root) else { return nil }+ return String(partial.path.dropFirst(root.count))+ }++ init(sessionDirectory: URL) { self.sessionDirectory = sessionDirectory.standardizedFileURL }++ deinit { if let audioFile { AudioFileClose(audioFile) } }++ func begin(relativeFilePath: String, format: AVAudioFormat) throws {+ let contract: MeetingPCMFormatContract+ do { contract = try MeetingPCMFormatContract(audioFormat: format) }+ catch { throw MeetingPCMSinkError.unsupportedClientFormat(error.localizedDescription) }+ try begin(relativeFilePath: relativeFilePath, format: format, contract: contract)+ }++ func begin(relativeFilePath: String, format: AVAudioFormat, contract: MeetingPCMFormatContract) throws {+ guard state == .idle else { throw MeetingPCMSinkError.alreadyBegun }+ let inputASBD = format.streamDescription.pointee+ let derivedContract: MeetingPCMFormatContract+ do { derivedContract = try MeetingPCMFormatContract(audioFormat: format) }+ catch { throw MeetingPCMSinkError.unsupportedClientFormat(error.localizedDescription) }+ guard derivedContract == contract else {+ throw MeetingPCMSinkError.formatMismatch(expected: contract.description, actual: derivedContract.description)+ }+ let layout = Self.layoutData(format.channelLayout)+ let paths = try resolvePaths(relativeFilePath)+ var asbd = try Self.canonicalASBD(rate: inputASBD.mSampleRate, channels: inputASBD.mChannelsPerFrame)+ var file: AudioFileID?+ let status = AudioFileCreateWithURL(paths.partial as CFURL, kAudioFileCAFType, &asbd, [], &file)+ guard status == noErr, let file else { throw MeetingPCMSinkError.writeFailed(status) }+ guard chmod(paths.partial.path, mode_t(0o600)) == 0 else {+ AudioFileClose(file); try? FileManager.default.removeItem(at: paths.partial)+ throw MeetingPCMSinkError.underlyingFileError("could not set partial permissions")+ }+ if let layout {+ let setStatus = layout.withUnsafeBytes {+ AudioFileSetProperty(file, kAudioFilePropertyChannelLayout, UInt32($0.count), $0.baseAddress!)+ }+ guard setStatus == noErr else {+ AudioFileClose(file); try? FileManager.default.removeItem(at: paths.partial)+ throw MeetingPCMSinkError.writeFailed(setStatus)+ }+ }+ self.audioFile = file+ self.paths = paths+ self.format = Format(rate: inputASBD.mSampleRate, channels: inputASBD.mChannelsPerFrame, layout: layout, contract: contract)+ self.fileASBD = asbd+ self.writtenPackets = 0+ self.poisoned = false+ self.state = .open+ }++ func append(_ sampleBuffer: CMSampleBuffer) throws -> MeetingPCMAppendReceipt {+ guard state == .open, let file = audioFile, let format, let expectedASBD = fileASBD else {+ if state == .idle { throw MeetingPCMSinkError.notBegun }+ throw MeetingPCMSinkError.alreadyFinalizedOrCancelled+ }+ guard !poisoned else { throw MeetingPCMSinkError.finalizationVerificationFailed("sink is poisoned") }+ guard CMSampleBufferIsValid(sampleBuffer), CMSampleBufferDataIsReady(sampleBuffer) else {+ throw MeetingPCMSinkError.invalidSampleBuffer("invalid or unready sample buffer")+ }+ let pts = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)+ guard pts.isValid, pts.isNumeric, !pts.isIndefinite, pts.timescale > 0 else {+ throw MeetingPCMSinkError.invalidPresentationTime+ }+ guard let desc = CMSampleBufferGetFormatDescription(sampleBuffer),+ let incoming = CMAudioFormatDescriptionGetStreamBasicDescription(desc)?.pointee+ else { throw MeetingPCMSinkError.invalidSampleBuffer("missing audio format description") }+ let incomingContract: MeetingPCMFormatContract+ do { incomingContract = try MeetingPCMFormatContract(formatDescription: desc) }+ catch {+ poisoned = true+ closeOpenFile()+ throw MeetingPCMSinkError.unsupportedClientFormat(error.localizedDescription)+ }+ guard incomingContract == format.contract else {+ poisoned = true+ closeOpenFile()+ throw MeetingPCMSinkError.formatMismatch(expected: format.contract.description, actual: incomingContract.description)+ }+ guard incoming.mSampleRate == format.rate,+ incoming.mChannelsPerFrame == format.channels,+ incoming.mBitsPerChannel == 32,+ (incoming.mFormatFlags & kAudioFormatFlagIsFloat) != 0,+ (incoming.mFormatFlags & kAudioFormatFlagIsSignedInteger) == 0+ else {+ poisoned = true+ closeOpenFile()+ throw MeetingPCMSinkError.formatMismatch(expected: format.contract.description, actual: Self.describe(incoming, layout: Self.layoutData(desc)))+ }+ let frames = CMSampleBufferGetNumSamples(sampleBuffer)+ guard frames > 0 else { throw MeetingPCMSinkError.invalidSampleBuffer("zero frames") }+ let list = try AudioList(sampleBuffer: sampleBuffer)+ let packed = try list.interleavedFloat32(frames: frames, channels: Int(format.channels), inputASBD: incoming)+ let expectedBytes = try Self.checkedMultiply(Int64(frames), Int64(expectedASBD.mBytesPerFrame))+ guard Int64(packed.count) == expectedBytes else { throw MeetingPCMSinkError.invalidSampleBuffer("packed size mismatch") }+ var packetCount = try Self.checkedUInt32(Int64(frames))+ let packetOffset = try Self.checkedInt64(writtenPackets)+ let byteCount = try Self.checkedUInt32(Int64(packed.count))+ let status = packed.withUnsafeBytes { bytes in+ AudioFileWritePackets(file, false, byteCount, nil, packetOffset, &packetCount, bytes.baseAddress!)+ }+ let actual = Int64(packetCount)+ guard status == noErr else { poisoned = true; closeOpenFile(); throw MeetingPCMSinkError.writeFailed(status) }+ guard actual == Int64(frames) else { poisoned = true; closeOpenFile(); throw MeetingPCMSinkError.shortWrite(expectedFrames: Int64(frames), writtenFrames: actual) }+ writtenPackets = try Self.checkedAdd(writtenPackets, actual)+ let duration = CMTime(seconds: Double(frames) / format.rate, preferredTimescale: 1_000_000_000)+ return MeetingPCMAppendReceipt(framesAccepted: Int64(frames), framesWritten: actual, presentationStart: pts, presentationDuration: duration)+ }++ func finalize() -> Result<MeetingPCMFinalization, MeetingPCMSinkError> {+ guard state == .open, let paths, let format else { return .failure(state == .idle ? .notBegun : .alreadyFinalizedOrCancelled) }+ guard !poisoned else { removePartialAndClose(); return .failure(.finalizationVerificationFailed("sink is poisoned")) }+ guard writtenPackets > 0 else { removePartialAndClose(); state = .cancelled; return .failure(.finalizationVerificationFailed("CAF contains no written frames")) }+ if let file = audioFile {+ let status = AudioFileClose(file); audioFile = nil+ guard status == noErr else { try? FileManager.default.removeItem(at: paths.partial); state = .cancelled; return .failure(.writeFailed(status)) }+ }+ do {+ let check = try Self.verify(paths.partial, format: format, expectedPackets: writtenPackets)+ let identity = try Self.identity(paths.partial)+ guard !FileManager.default.fileExists(atPath: paths.final.path) else { throw MeetingPCMSinkError.finalPathAlreadyExists(paths.final.path) }+ try Self.fullSync(paths.partial)+ let beforePublish = try Self.identity(paths.partial)+ guard beforePublish.dev == identity.dev, beforePublish.ino == identity.ino, beforePublish.size == identity.size else {+ throw MeetingPCMSinkError.finalizationVerificationFailed("staged file changed before publication")+ }+ guard renameatx_np(AT_FDCWD, paths.partial.path, AT_FDCWD, paths.final.path, UInt32(RENAME_EXCL)) == 0 else {+ if errno == EEXIST { throw MeetingPCMSinkError.finalPathAlreadyExists(paths.final.path) }+ throw MeetingPCMSinkError.underlyingFileError("atomic rename failed: errno \(errno)")+ }+ try Self.syncDirectory(paths.final.deletingLastPathComponent())+ state = .finalized+ return .success(MeetingPCMFinalization(relativeFilePath: try relativePath(paths.final), byteCount: check.bytes, sha256: check.hash,+ sampleRate: check.rate, channelCount: check.channels, frameCount: check.frames))+ } catch let error as MeetingPCMSinkError {+ state = .cancelled; try? FileManager.default.removeItem(at: paths.partial); return .failure(error)+ } catch { state = .cancelled; try? FileManager.default.removeItem(at: paths.partial); return .failure(.underlyingFileError(error.localizedDescription)) }+ }++ func cancel() { guard state == .open || state == .idle else { return }; removePartialAndClose(); state = .cancelled }++ // MARK: Path / format helpers+ private func resolvePaths(_ relative: String) throws -> Paths {+ guard !relative.isEmpty, !relative.hasPrefix("/"), !relative.contains("\\"), relative.hasSuffix(".caf") else { throw MeetingPCMSinkError.invalidRelativePath(relative) }+ let components = relative.split(separator: "/", omittingEmptySubsequences: false).map(String.init)+ guard !components.isEmpty, components.allSatisfy({ !$0.isEmpty && $0 != "." && $0 != ".." }), !components.last!.contains(".partial.") else { throw MeetingPCMSinkError.invalidRelativePath(relative) }+ try Self.rejectSymlink(sessionDirectory)+ var parent = sessionDirectory+ for component in components.dropLast() {+ parent.appendPathComponent(component, isDirectory: true)+ if FileManager.default.fileExists(atPath: parent.path) { try Self.rejectSymlink(parent) }+ else { try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: false, attributes: [.posixPermissions: NSNumber(value: Int16(0o700))]) }+ guard FileManager.default.fileExists(atPath: parent.path, isDirectory: nil) else { throw MeetingPCMSinkError.underlyingFileError("parent does not exist") }+ guard chmod(parent.path, mode_t(0o700)) == 0 else {+ throw MeetingPCMSinkError.underlyingFileError("could not set directory permissions: \(parent.path)")+ }+ }+ let final = parent.appendingPathComponent(components.last!)+ if FileManager.default.fileExists(atPath: final.path) { try Self.rejectSymlink(final); throw MeetingPCMSinkError.finalPathAlreadyExists(relative) }+ let partial = parent.appendingPathComponent(String(components.last!.dropLast(4)) + ".\(UUID().uuidString).partial.caf")+ if FileManager.default.fileExists(atPath: partial.path) { throw MeetingPCMSinkError.partialPathAlreadyExists(partial.path) }+ return Paths(final: final, partial: partial)+ }++ private static func rejectSymlink(_ url: URL) throws {+ var st = stat(); guard lstat(url.path, &st) == 0 else { if errno == ENOENT { return }; throw MeetingPCMSinkError.underlyingFileError("cannot inspect \(url.path)") }+ if (st.st_mode & S_IFMT) == S_IFLNK { throw MeetingPCMSinkError.symlinkComponentRejected(url.path) }+ }++ private static func canonicalASBD(rate: Double, channels: UInt32) throws -> AudioStreamBasicDescription {+ let (bytes, overflow) = channels.multipliedReportingOverflow(by: 4)+ guard !overflow else { throw MeetingPCMSinkError.unsupportedClientFormat("channel byte size overflow") }+ return AudioStreamBasicDescription(mSampleRate: rate, mFormatID: kAudioFormatLinearPCM, mFormatFlags: kAudioFormatFlagsNativeFloatPacked,+ mBytesPerPacket: bytes, mFramesPerPacket: 1, mBytesPerFrame: bytes,+ mChannelsPerFrame: channels, mBitsPerChannel: 32, mReserved: 0)+ }++ // MARK: ABL and checked arithmetic+ private final class AudioList {+ let pointer: UnsafeMutablePointer<AudioBufferList>; let retained: CMBlockBuffer?+ init(sampleBuffer: CMSampleBuffer) throws {+ var size = 0+ let first = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(sampleBuffer, bufferListSizeNeededOut: &size, bufferListOut: nil, bufferListSize: 0, blockBufferAllocator: nil, blockBufferMemoryAllocator: nil, flags: 0, blockBufferOut: nil)+ guard first == noErr, size > 0 else { throw MeetingPCMSinkError.invalidSampleBuffer("ABL size unavailable") }+ pointer = UnsafeMutableRawPointer.allocate(byteCount: size, alignment: MemoryLayout<AudioBufferList>.alignment).assumingMemoryBound(to: AudioBufferList.self)+ var block: CMBlockBuffer?+ let second = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(sampleBuffer, bufferListSizeNeededOut: &size, bufferListOut: pointer, bufferListSize: size, blockBufferAllocator: nil, blockBufferMemoryAllocator: nil, flags: kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment, blockBufferOut: &block)+ guard second == noErr else { pointer.deallocate(); throw MeetingPCMSinkError.invalidSampleBuffer("ABL unavailable") }+ retained = block+ }+ deinit { pointer.deallocate() }+ func interleavedFloat32(frames: Int, channels: Int, inputASBD: AudioStreamBasicDescription) throws -> Data {+ let buffers = UnsafeMutableAudioBufferListPointer(pointer)+ let nonInterleaved = (inputASBD.mFormatFlags & kAudioFormatFlagIsNonInterleaved) != 0+ guard (nonInterleaved ? buffers.count == channels : buffers.count == 1), buffers.allSatisfy({ $0.mData != nil && $0.mNumberChannels == (nonInterleaved ? 1 : UInt32(channels)) }) else { throw MeetingPCMSinkError.invalidSampleBuffer("ABL topology mismatch") }+ let bytesPerChannel = try MeetingAudioFilePCMChunkSink.checkedMultiply(Int64(frames), 4)+ let expectedBytes = try MeetingAudioFilePCMChunkSink.checkedMultiply(bytesPerChannel, nonInterleaved ? 1 : Int64(channels))+ guard buffers.allSatisfy({ Int64($0.mDataByteSize) == expectedBytes }) else { throw MeetingPCMSinkError.invalidSampleBuffer("ABL byte count mismatch") }+ let count = try MeetingAudioFilePCMChunkSink.checkedMultiply(Int64(frames), Int64(channels))+ var output = Data(count: try Int(MeetingAudioFilePCMChunkSink.checkedMultiply(count, 4)))+ output.withUnsafeMutableBytes { out in+ let dst = out.baseAddress!.assumingMemoryBound(to: Float.self)+ if nonInterleaved {+ let src = buffers.map { $0.mData!.assumingMemoryBound(to: Float.self) }+ for frame in 0..<frames { for channel in 0..<channels { dst[frame * channels + channel] = src[channel][frame] } }+ } else {+ let src = buffers[0].mData!.assumingMemoryBound(to: Float.self)+ for i in 0..<Int(count) { dst[i] = src[i] }+ }+ }+ for value in output.withUnsafeBytes({ $0.bindMemory(to: Float.self) }) where !value.isFinite { throw MeetingPCMSinkError.nonFiniteSample }+ return output+ }+ }++ private static func checkedMultiply(_ a: Int64, _ b: Int64) throws -> Int64 { let (v, o) = a.multipliedReportingOverflow(by: b); if o || v < 0 { throw MeetingPCMSinkError.invalidSampleBuffer("integer overflow") }; return v }+ private static func checkedAdd(_ a: Int64, _ b: Int64) throws -> Int64 { let (v, o) = a.addingReportingOverflow(b); if o || v < 0 { throw MeetingPCMSinkError.invalidSampleBuffer("integer overflow") }; return v }+ private static func checkedUInt32(_ value: Int64) throws -> UInt32 { guard value >= 0, value <= Int64(UInt32.max) else { throw MeetingPCMSinkError.invalidSampleBuffer("packet count overflow") }; return UInt32(value) }+ private static func checkedInt64(_ value: Int64) throws -> Int64 { guard value >= 0 else { throw MeetingPCMSinkError.invalidSampleBuffer("negative packet offset") }; return value }++ // MARK: Verification / durability+ private struct Check { let bytes: Int64; let hash: String; let rate: Double; let channels: Int; let frames: Int64 }+ private static func verify(_ url: URL, format: Format, expectedPackets: Int64) throws -> Check {+ var file: AudioFileID?; let open = AudioFileOpenURL(url as CFURL, .readPermission, 0, &file); guard open == noErr, let file else { throw MeetingPCMSinkError.finalizationVerificationFailed("CAF reopen failed") }; defer { AudioFileClose(file) }+ var asbd = AudioStreamBasicDescription(); var size = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)+ let canonical = try Self.canonicalASBD(rate: format.rate, channels: format.channels)+ guard AudioFileGetProperty(file, kAudioFilePropertyDataFormat, &size, &asbd) == noErr,+ asbd.mSampleRate == canonical.mSampleRate,+ asbd.mFormatID == canonical.mFormatID,+ asbd.mFormatFlags == canonical.mFormatFlags,+ asbd.mBytesPerPacket == canonical.mBytesPerPacket,+ asbd.mFramesPerPacket == canonical.mFramesPerPacket,+ asbd.mBytesPerFrame == canonical.mBytesPerFrame,+ asbd.mChannelsPerFrame == canonical.mChannelsPerFrame,+ asbd.mBitsPerChannel == canonical.mBitsPerChannel+ else { throw MeetingPCMSinkError.finalizationVerificationFailed("CAF ASBD mismatch") }+ let layout = try Self.fileLayout(file); guard layout == format.layout else { throw MeetingPCMSinkError.finalizationVerificationFailed("CAF channel layout mismatch") }+ var packets: Int64 = 0; size = UInt32(MemoryLayout<Int64>.size); guard AudioFileGetProperty(file, kAudioFilePropertyAudioDataPacketCount, &size, &packets) == noErr, packets == expectedPackets else { throw MeetingPCMSinkError.finalizationVerificationFailed("CAF packet count mismatch") }+ var bytesCount: Int64 = 0; size = UInt32(MemoryLayout<Int64>.size); guard AudioFileGetProperty(file, kAudioFilePropertyAudioDataByteCount, &size, &bytesCount) == noErr else { throw MeetingPCMSinkError.finalizationVerificationFailed("CAF byte count unavailable") }+ let expectedBytes = try checkedMultiply(packets, Int64(asbd.mBytesPerFrame)); guard bytesCount == expectedBytes else { throw MeetingPCMSinkError.finalizationVerificationFailed("CAF data bytes mismatch") }+ let attrs = try FileManager.default.attributesOfItem(atPath: url.path); let actualSize = (attrs[.size] as? NSNumber)?.int64Value ?? -1; guard actualSize > 0 else { throw MeetingPCMSinkError.finalizationVerificationFailed("CAF is empty") }+ var hasher = SHA256(); let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() }; while true { let data = try handle.read(upToCount: 1 << 20) ?? Data(); if data.isEmpty { break }; hasher.update(data: data) }+ return Check(bytes: actualSize, hash: hasher.finalize().map { String(format: "%02x", $0) }.joined(), rate: asbd.mSampleRate, channels: Int(asbd.mChannelsPerFrame), frames: packets)+ }+ private static func fileLayout(_ file: AudioFileID) throws -> Data? { var size: UInt32 = 0; let query = AudioFileGetPropertyInfo(file, kAudioFilePropertyChannelLayout, &size, nil); guard query == noErr else { return nil }; guard size > 0 else { return nil }; var data = Data(count: Int(size)); let status = data.withUnsafeMutableBytes { AudioFileGetProperty(file, kAudioFilePropertyChannelLayout, &size, $0.baseAddress!) }; guard status == noErr else { throw MeetingPCMSinkError.finalizationVerificationFailed("CAF layout read failed") }; return data }+ private static func identity(_ url: URL) throws -> Identity { var st = stat(); guard lstat(url.path, &st) == 0 else { throw MeetingPCMSinkError.finalizationVerificationFailed("staged file disappeared") }; return Identity(dev: st.st_dev, ino: st.st_ino, size: st.st_size) }+ private static func fullSync(_ url: URL) throws { let fd = open(url.path, O_RDONLY); guard fd >= 0 else { throw MeetingPCMSinkError.underlyingFileError("open for sync failed") }; defer { close(fd) }; guard fcntl(fd, F_FULLFSYNC) == 0 else { throw MeetingPCMSinkError.underlyingFileError("F_FULLFSYNC failed") } }+ private static func syncDirectory(_ url: URL) throws { let fd = open(url.path, O_RDONLY | O_DIRECTORY); guard fd >= 0 else { throw MeetingPCMSinkError.underlyingFileError("open parent for sync failed") }; defer { close(fd) }; guard fsync(fd) == 0 else { throw MeetingPCMSinkError.underlyingFileError("parent fsync failed") } }+ private static func layoutData(_ layout: AVAudioChannelLayout?) -> Data? { MeetingPCMFormatContract.layoutData(layout) }+ private static func layoutData(_ desc: CMFormatDescription) -> Data? { MeetingPCMFormatContract.layoutData(desc) }+ private static func describe(_ format: Format) -> String { "rate=\(format.rate), channels=\(format.channels), layoutBytes=\(format.layout?.count ?? 0)" }+ private static func describe(_ asbd: AudioStreamBasicDescription, layout: Data?) -> String { "rate=\(asbd.mSampleRate), channels=\(asbd.mChannelsPerFrame), flags=\(asbd.mFormatFlags), layoutBytes=\(layout?.count ?? 0)" }+ private func relativePath(_ url: URL) throws -> String { let root = sessionDirectory.path.hasSuffix("/") ? sessionDirectory.path : sessionDirectory.path + "/"; guard url.path.hasPrefix(root) else { throw MeetingPCMSinkError.finalizationVerificationFailed("published path escaped session") }; return String(url.path.dropFirst(root.count)) }+ private func closeOpenFile() { if let file = audioFile { AudioFileClose(file); audioFile = nil } }+ private func removePartialAndClose() { closeOpenFile(); if let partial = paths?.partial { try? FileManager.default.removeItem(at: partial) } }+}diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingBackendEvidence.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingBackendEvidence.swiftnew file mode 100644index 00000000..dbbe36e3--- /dev/null+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingBackendEvidence.swift@@ -0,0 +1,536 @@+import Foundation++// Canonical final-output contract from `MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md` §2: timed+// text units (word *or* utterance), each with a stable source ID, exact analysis-span references,+// precision, an anonymous speaker assignment or an explicit ambiguity, and provenance.+//+// Stage C2b1: a unit's bounds are per-track *analysis* time — the gap-removed stream the manifest+// defines — and its provenance is the exact list of manifest analysis spans its audio came from.+// The assembler maps those bounds to presentation time through the referenced spans, exactly once;+// no presentation timestamps exist here to disagree with that mapping.+//+// Validation is split in two on purpose. `validated(against:)` / `validatedForAssembly` prove+// *scope*: every reference names something the frozen plan and manifest actually contain, so a+// violation is a hard error. Timing and provenance *values* are instead classified by+// `quarantineReason(in:)`: a unit with impossible bounds or unverifiable span coverage is not+// thrown away by preflight but quarantined, so the assembler can record exactly one sidecar+// disposition for every input unit (plan §4).+//+// Nothing here creates product speaker IDs, applies echo or admission policy, or writes anything+// durable — that is the assembler's job. Nothing here invents a timestamp or a confidence value+// either: a backend that returns only utterances stays an utterance backend, and absent confidence+// stays `nil`.++/// Version of the encoded canonical-evidence representation. Decoding is fail-closed: an+/// unknown or absent version is an error, never a guess. Version 2 moves text units from+/// session-relative seconds plus chunk references to analysis-time bounds plus exact span IDs;+/// version-1 payloads are rejected, not reinterpreted.+nonisolated enum MeetingBackendEvidenceSchema {+ static let currentVersion = 2+}++nonisolated enum MeetingEvidenceInterval {+ static func isValid(start: TimeInterval, end: TimeInterval) -> Bool {+ start.isFinite && end.isFinite && start >= 0 && end > start+ }+}++nonisolated enum MeetingTextUnitPrecision: String, Codable {+ case word+ case utterance+}++/// Analysis epoch, scoped to its track. A new epoch starts for missing audio, a real clock+/// discontinuity, a microphone device replacement or an inadmissible microphone interval, so+/// speaker state may never be carried across one. Encoding the track here is what makes the+/// token-scoping check below meaningful.+nonisolated struct MeetingAnalysisEpochID: Hashable, Codable, CustomStringConvertible {+ let trackID: MeetingAudioTrackID+ let ordinal: Int+ /// Changes when this epoch's model evidence is replayed under the same attempt. Product+ /// speaker IDs include it, so recomputed slot labels can never inherit an earlier alias merely+ /// because the track and ordinal stayed the same.+ let generation: Int++ init(trackID: MeetingAudioTrackID, ordinal: Int, generation: Int = 0) {+ self.trackID = trackID+ self.ordinal = ordinal+ self.generation = generation+ }++ var description: String {+ "\(self.trackID.uuidString)#\(self.ordinal)@\(self.generation)"+ }+}++nonisolated struct MeetingAnalysisEpochGenerationKey: Hashable {+ let trackID: MeetingAudioTrackID+ let ordinal: Int+}++/// Anonymous, backend-local speaker slot. Never a `SessionSpeakerID`: only the assembler creates+/// product speaker IDs, and never by slot equality across tracks or epochs.+nonisolated struct MeetingBackendSpeakerToken: Hashable, Codable {+ let analysisEpochID: MeetingAnalysisEpochID+ let label: String+}++nonisolated enum MeetingBackendSpeakerAssignment: Equatable {+ case assigned(MeetingBackendSpeakerToken)+ /// Two or more candidate slots the backend could not separate. Ambiguity is reported, never+ /// resolved by picking one.+ case ambiguous([MeetingBackendSpeakerToken])+ /// The backend produced text but no speaker evidence at all.+ case unassigned++ var tokens: [MeetingBackendSpeakerToken] {+ switch self {+ case let .assigned(token): return [token]+ case let .ambiguous(tokens): return tokens+ case .unassigned: return []+ }+ }+}++nonisolated extension MeetingBackendSpeakerAssignment: Codable {+ /// Stable keyed encoding; the raw-value `Kind` decode already throws on an unknown case,+ /// so a payload can never decode into a speaker assignment the backend never made.+ private enum CodingKeys: String, CodingKey {+ case kind+ case token+ case candidates+ }++ private enum Kind: String, Codable {+ case assigned+ case ambiguous+ case unassigned+ }++ init(from decoder: Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ switch try container.decode(Kind.self, forKey: .kind) {+ case .assigned:+ guard container.contains(.token), !container.contains(.candidates) else {+ throw DecodingError.dataCorruptedError(+ forKey: .kind,+ in: container,+ debugDescription: "An assigned speaker requires exactly one token payload."+ )+ }+ self = try .assigned(container.decode(MeetingBackendSpeakerToken.self, forKey: .token))+ case .ambiguous:+ guard container.contains(.candidates), !container.contains(.token) else {+ throw DecodingError.dataCorruptedError(+ forKey: .kind,+ in: container,+ debugDescription: "An ambiguous speaker requires only a candidates payload."+ )+ }+ self = try .ambiguous(container.decode([MeetingBackendSpeakerToken].self, forKey: .candidates))+ case .unassigned:+ guard !container.contains(.token), !container.contains(.candidates) else {+ throw DecodingError.dataCorruptedError(+ forKey: .kind,+ in: container,+ debugDescription: "An unassigned speaker cannot carry token payloads."+ )+ }+ self = .unassigned+ }+ }++ func encode(to encoder: Encoder) throws {+ var container = encoder.container(keyedBy: CodingKeys.self)+ switch self {+ case let .assigned(token):+ try container.encode(Kind.assigned, forKey: .kind)+ try container.encode(token, forKey: .token)+ case let .ambiguous(tokens):+ try container.encode(Kind.ambiguous, forKey: .kind)+ try container.encode(tokens, forKey: .candidates)+ case .unassigned:+ try container.encode(Kind.unassigned, forKey: .kind)+ }+ }+}++/// One final timed text unit. `analysisStart`/`analysisEnd` are seconds in the unit's track's+/// gap-removed analysis stream — the domain `MeetingAnalysisSpan.analysisInterval` defines — and+/// `analysisSpanIDs` is the exact, contiguous set of manifest spans the unit's audio came from.+nonisolated struct MeetingFinalTextUnit: Equatable, Identifiable {+ /// Stable within an attempt and, for resumed ASR chunks, across retries of that attempt.+ let id: String+ let trackID: MeetingAudioTrackID+ let analysisEpochID: MeetingAnalysisEpochID+ let precision: MeetingTextUnitPrecision+ let text: String+ let analysisStart: TimeInterval+ let analysisEnd: TimeInterval+ let speaker: MeetingBackendSpeakerAssignment+ /// Exact manifest analysis spans backing this unit. Contiguous within the unit's epoch, never+ /// bridging a missing or inadmissible span; validation proves the references exist, and the+ /// quarantine classification proves their union really covers the unit's bounds.+ let analysisSpanIDs: [String]+ /// Whatever the backend actually reported. `nil` when it reports none — never substituted.+ let confidence: Double?++ init(+ id: String,+ trackID: MeetingAudioTrackID,+ analysisEpochID: MeetingAnalysisEpochID,+ precision: MeetingTextUnitPrecision,+ text: String,+ analysisStart: TimeInterval,+ analysisEnd: TimeInterval,+ speaker: MeetingBackendSpeakerAssignment,+ analysisSpanIDs: [String],+ confidence: Double? = nil+ ) {+ self.id = id+ self.trackID = trackID+ self.analysisEpochID = analysisEpochID+ self.precision = precision+ self.text = text+ self.analysisStart = analysisStart+ self.analysisEnd = analysisEnd+ self.speaker = speaker+ self.analysisSpanIDs = analysisSpanIDs+ self.confidence = confidence+ }+}++/// Optional supporting evidence, in the same per-track analysis-time domain as the text units.+/// Its absence is not a defect, and its presence does not by itself assign any text.+nonisolated struct MeetingBackendSpeakerActivity: Equatable {+ let token: MeetingBackendSpeakerToken+ let start: TimeInterval+ let end: TimeInterval+}++nonisolated struct MeetingFinalTranscriptEvidence: Equatable {+ let backendID: MeetingBackendID+ let attemptID: UUID+ let units: [MeetingFinalTextUnit]+ let speakerActivity: [MeetingBackendSpeakerActivity]++ init(+ backendID: MeetingBackendID,+ attemptID: UUID,+ units: [MeetingFinalTextUnit],+ speakerActivity: [MeetingBackendSpeakerActivity] = []+ ) {+ self.backendID = backendID+ self.attemptID = attemptID+ self.units = units+ self.speakerActivity = speakerActivity+ }+}++nonisolated extension MeetingFinalTextUnit: Codable {}+nonisolated extension MeetingBackendSpeakerActivity: Codable {}++nonisolated extension MeetingFinalTranscriptEvidence: Codable {+ private enum CodingKeys: String, CodingKey {+ case schemaVersion+ case backendID+ case attemptID+ case units+ case speakerActivity+ }++ init(from decoder: Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ let version = try container.decode(Int.self, forKey: .schemaVersion)+ guard version == MeetingBackendEvidenceSchema.currentVersion else {+ throw DecodingError.dataCorruptedError(+ forKey: .schemaVersion,+ in: container,+ debugDescription: "Unsupported meeting evidence schema version \(version)."+ )+ }+ try self.init(+ backendID: container.decode(MeetingBackendID.self, forKey: .backendID),+ attemptID: container.decode(UUID.self, forKey: .attemptID),+ units: container.decode([MeetingFinalTextUnit].self, forKey: .units),+ speakerActivity: container.decode([MeetingBackendSpeakerActivity].self, forKey: .speakerActivity)+ )+ }++ func encode(to encoder: Encoder) throws {+ var container = encoder.container(keyedBy: CodingKeys.self)+ try container.encode(MeetingBackendEvidenceSchema.currentVersion, forKey: .schemaVersion)+ try container.encode(self.backendID, forKey: .backendID)+ try container.encode(self.attemptID, forKey: .attemptID)+ try container.encode(self.units, forKey: .units)+ try container.encode(self.speakerActivity, forKey: .speakerActivity)+ }+}++nonisolated enum MeetingBackendEvidenceError: LocalizedError, Equatable {+ case backendMismatch(expected: MeetingBackendID, actual: MeetingBackendID)+ case attemptMismatch(expected: UUID, actual: UUID)+ case emptyUnitID+ case duplicateUnitID(String)+ case emptyText(unitID: String)+ case unsupportedPrecision(unitID: String, precision: MeetingTextUnitPrecision)+ case unknownSourceTrack(unitID: String)+ case missingAnalysisSpans(unitID: String)+ case duplicateAnalysisSpanID(unitID: String)+ case unknownAnalysisSpan(unitID: String)+ case unknownAnalysisEpoch(unitID: String)+ case analysisEpochOutOfScope(unitID: String)+ case invalidAnalysisEpochOrdinal(unitID: String)+ case invalidAnalysisEpochGeneration(unitID: String)+ case speakerTokenOutOfScope(unitID: String)+ case emptySpeakerTokenLabel(unitID: String)+ case invalidAmbiguity(unitID: String)+ case invalidActivityTiming(index: Int)+ case activityTokenOutOfScope(index: Int)+ case activityEpochUnknown(index: Int)+ case invalidActivityEpochOrdinal(index: Int)+ case invalidActivityEpochGeneration(index: Int)+ case emptyActivityTokenLabel(index: Int)+ case activityOutsideEpoch(index: Int)++ var errorDescription: String? {+ switch self {+ case let .backendMismatch(expected, actual):+ return "Evidence came from backend \"\(actual)\" but the plan selected \"\(expected)\"."+ case let .attemptMismatch(expected, actual):+ return "Evidence carries attempt \(actual) but the plan is attempt \(expected)."+ case .emptyUnitID:+ return "A final text unit has an empty identifier."+ case let .duplicateUnitID(id):+ return "Final text unit identifier \"\(id)\" appears more than once."+ case let .emptyText(unitID):+ return "Final text unit \"\(unitID)\" has no text."+ case let .unsupportedPrecision(unitID, precision):+ return "Final text unit \"\(unitID)\" declares \(precision.rawValue) precision, "+ + "which this backend did not declare support for."+ case let .unknownSourceTrack(unitID):+ return "Final text unit \"\(unitID)\" references a track that was not planned."+ case let .missingAnalysisSpans(unitID):+ return "Final text unit \"\(unitID)\" references no analysis span."+ case let .duplicateAnalysisSpanID(unitID):+ return "Final text unit \"\(unitID)\" repeats an analysis span identifier."+ case let .unknownAnalysisSpan(unitID):+ return "Final text unit \"\(unitID)\" references an analysis span the manifest does not record."+ case let .unknownAnalysisEpoch(unitID):+ return "Final text unit \"\(unitID)\" uses an analysis epoch the manifest does not record."+ case let .analysisEpochOutOfScope(unitID):+ return "Final text unit \"\(unitID)\" uses an analysis epoch from another track."+ case let .invalidAnalysisEpochOrdinal(unitID):+ return "Final text unit \"\(unitID)\" uses a negative analysis epoch ordinal."+ case let .invalidAnalysisEpochGeneration(unitID):+ return "Final text unit \"\(unitID)\" uses a negative analysis epoch generation."+ case let .speakerTokenOutOfScope(unitID):+ return "Final text unit \"\(unitID)\" uses a speaker token from another track or epoch."+ case let .emptySpeakerTokenLabel(unitID):+ return "Final text unit \"\(unitID)\" uses an empty speaker-token label."+ case let .invalidAmbiguity(unitID):+ return "Final text unit \"\(unitID)\" reports ambiguity without two distinct candidates."+ case let .invalidActivityTiming(index):+ return "Speaker activity interval \(index) has non-finite or non-positive timing."+ case let .activityTokenOutOfScope(index):+ return "Speaker activity interval \(index) uses a token from an unplanned track."+ case let .activityEpochUnknown(index):+ return "Speaker activity interval \(index) uses an epoch the manifest does not record."+ case let .invalidActivityEpochOrdinal(index):+ return "Speaker activity interval \(index) uses a negative analysis epoch ordinal."+ case let .invalidActivityEpochGeneration(index):+ return "Speaker activity interval \(index) uses a negative analysis epoch generation."+ case let .emptyActivityTokenLabel(index):+ return "Speaker activity interval \(index) uses an empty speaker-token label."+ case let .activityOutsideEpoch(index):+ return "Speaker activity interval \(index) lies outside its analysis epoch."+ }+ }+}++nonisolated extension MeetingFinalTranscriptEvidence {+ /// Scope validation against the frozen plan: identity, uniqueness, declared precisions, and+ /// reference *shape*. A failure here means the evidence talks about something that was never+ /// planned, so it throws. Timing and provenance *values* are deliberately not judged here —+ /// they are quarantined per unit by `quarantineReason(in:)` so assembly can ledger every unit.+ @discardableResult+ func validated(against plan: MeetingBackendPlan) throws -> Self {+ guard self.backendID == plan.backendID else {+ throw MeetingBackendEvidenceError.backendMismatch(expected: plan.backendID, actual: self.backendID)+ }+ guard self.attemptID == plan.attemptID else {+ throw MeetingBackendEvidenceError.attemptMismatch(expected: plan.attemptID, actual: self.attemptID)+ }++ var seenUnitIDs = Set<String>()+ for unit in self.units {+ guard !unit.id.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {+ throw MeetingBackendEvidenceError.emptyUnitID+ }+ guard seenUnitIDs.insert(unit.id).inserted else {+ throw MeetingBackendEvidenceError.duplicateUnitID(unit.id)+ }+ guard !unit.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {+ throw MeetingBackendEvidenceError.emptyText(unitID: unit.id)+ }+ guard plan.declaredFinalPrecisions.contains(unit.precision) else {+ throw MeetingBackendEvidenceError.unsupportedPrecision(unitID: unit.id, precision: unit.precision)+ }+ guard plan.trackKindsByID[unit.trackID] != nil else {+ throw MeetingBackendEvidenceError.unknownSourceTrack(unitID: unit.id)+ }+ guard !unit.analysisSpanIDs.isEmpty else {+ throw MeetingBackendEvidenceError.missingAnalysisSpans(unitID: unit.id)+ }+ guard Set(unit.analysisSpanIDs).count == unit.analysisSpanIDs.count else {+ throw MeetingBackendEvidenceError.duplicateAnalysisSpanID(unitID: unit.id)+ }+ guard unit.analysisEpochID.trackID == unit.trackID else {+ throw MeetingBackendEvidenceError.analysisEpochOutOfScope(unitID: unit.id)+ }+ guard unit.analysisEpochID.ordinal >= 0 else {+ throw MeetingBackendEvidenceError.invalidAnalysisEpochOrdinal(unitID: unit.id)+ }+ guard unit.analysisEpochID.generation >= 0 else {+ throw MeetingBackendEvidenceError.invalidAnalysisEpochGeneration(unitID: unit.id)+ }+ guard unit.speaker.tokens.allSatisfy({ $0.analysisEpochID == unit.analysisEpochID }) else {+ throw MeetingBackendEvidenceError.speakerTokenOutOfScope(unitID: unit.id)+ }+ guard unit.speaker.tokens.allSatisfy({+ !$0.label.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ }) else {+ throw MeetingBackendEvidenceError.emptySpeakerTokenLabel(unitID: unit.id)+ }+ if case let .ambiguous(candidates) = unit.speaker, Set(candidates).count < 2 {+ throw MeetingBackendEvidenceError.invalidAmbiguity(unitID: unit.id)+ }+ }++ for (index, activity) in self.speakerActivity.enumerated() {+ guard MeetingEvidenceInterval.isValid(start: activity.start, end: activity.end) else {+ throw MeetingBackendEvidenceError.invalidActivityTiming(index: index)+ }+ guard plan.trackKindsByID[activity.token.analysisEpochID.trackID] != nil else {+ throw MeetingBackendEvidenceError.activityTokenOutOfScope(index: index)+ }+ guard activity.token.analysisEpochID.ordinal >= 0 else {+ throw MeetingBackendEvidenceError.invalidActivityEpochOrdinal(index: index)+ }+ guard activity.token.analysisEpochID.generation >= 0 else {+ throw MeetingBackendEvidenceError.invalidActivityEpochGeneration(index: index)+ }+ guard !activity.token.label.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {+ throw MeetingBackendEvidenceError.emptyActivityTokenLabel(index: index)+ }+ }++ return self+ }++ /// Assembly scope validation: everything `validated(against:)` proves, plus proof that every+ /// epoch and span the evidence names actually exists in the validated manifest. Anything the+ /// manifest does not record is a scope violation, never a quarantinable timing defect.+ @discardableResult+ func validatedForAssembly(+ against plan: MeetingBackendPlan,+ manifest: MeetingAnalysisManifest+ ) throws -> Self {+ try self.validated(against: plan)+ for unit in self.units {+ guard let track = manifest.track(unit.trackID) else {+ throw MeetingBackendEvidenceError.unknownSourceTrack(unitID: unit.id)+ }+ guard track.epochs.contains(where: { $0.id == unit.analysisEpochID }) else {+ throw MeetingBackendEvidenceError.unknownAnalysisEpoch(unitID: unit.id)+ }+ let spanIDs = Set(track.spans.map(\.id))+ guard unit.analysisSpanIDs.allSatisfy(spanIDs.contains) else {+ throw MeetingBackendEvidenceError.unknownAnalysisSpan(unitID: unit.id)+ }+ }+ for (index, activity) in self.speakerActivity.enumerated() {+ guard let track = manifest.track(activity.token.analysisEpochID.trackID) else {+ throw MeetingBackendEvidenceError.activityTokenOutOfScope(index: index)+ }+ guard let epoch = track.epochs.first(where: {+ $0.id == activity.token.analysisEpochID+ }) else {+ throw MeetingBackendEvidenceError.activityEpochUnknown(index: index)+ }+ let tolerance = MeetingAnalysisManifestSchema.mappingToleranceSeconds+ guard activity.start >= epoch.analysisInterval.start - tolerance,+ activity.end <= epoch.analysisInterval.end + tolerance+ else {+ throw MeetingBackendEvidenceError.activityOutsideEpoch(index: index)+ }+ }+ return self+ }+}++/// Why one input unit can never be mapped or emitted: a timing or provenance *value* defect found+/// after scope validation. These are disposition reasons, not errors — plan §4 quarantines such+/// units from normal output and forbids interval arithmetic on their bounds.+nonisolated enum MeetingUnitQuarantineReason: String, Codable, CaseIterable {+ /// Non-finite, negative or non-positive analysis-time bounds.+ case invalidTiming+ /// Confidence outside 0...1. Absent confidence is never a defect.+ case invalidConfidence+ /// The referenced spans belong to a different analysis epoch than the unit declares.+ case analysisEpochMismatch+ /// The referenced spans are not a contiguous run inside the unit's epoch, so the unit would+ /// bridge a missing or inadmissible span.+ case spansNotContiguousWithinEpoch+ /// The unit's analysis bounds are not covered by the union of the spans it references.+ case spansDoNotCoverUnitInterval+ /// The referenced spans are valid, but their transforms map the unit to non-finite,+ /// negative, or non-positive presentation bounds.+ case presentationMappingInvalid+}++nonisolated extension MeetingFinalTextUnit {+ /// The timing/provenance quarantine classification for this unit, or `nil` when its bounds+ /// and span provenance are sound. Requires scope validation to have passed: unknown span or+ /// epoch references are errors there, never reasons here.+ func quarantineReason(in manifest: MeetingAnalysisManifest) -> MeetingUnitQuarantineReason? {+ guard MeetingEvidenceInterval.isValid(start: self.analysisStart, end: self.analysisEnd) else {+ return .invalidTiming+ }+ if let confidence = self.confidence,+ !confidence.isFinite || confidence < 0 || confidence > 1+ {+ return .invalidConfidence+ }+ guard let track = manifest.track(self.trackID) else { return nil }+ let spansByID = Dictionary(track.spans.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })+ let referenced = self.analysisSpanIDs.compactMap { spansByID[$0] }+ guard referenced.count == self.analysisSpanIDs.count,+ referenced.allSatisfy({ $0.analysisEpochID == self.analysisEpochID })+ else { return .analysisEpochMismatch }++ // The span set must be one contiguous run inside its epoch's analysis-ordered span list:+ // that is what proves the unit never bridges a missing or inadmissible span, since the+ // manifest removes exactly those from analysis time and breaks the epoch across them.+ guard let epoch = track.epochs.first(where: { $0.id == self.analysisEpochID }),+ let firstIndex = epoch.spanIDs.firstIndex(of: self.analysisSpanIDs[0]),+ firstIndex + self.analysisSpanIDs.count <= epoch.spanIDs.count,+ Array(epoch.spanIDs[firstIndex..<(firstIndex + self.analysisSpanIDs.count)]) == self.analysisSpanIDs+ else { return .spansNotContiguousWithinEpoch }++ let tolerance = MeetingAnalysisManifestSchema.mappingToleranceSeconds+ guard self.analysisStart >= referenced[0].analysisInterval.start - tolerance,+ self.analysisStart < referenced[0].analysisInterval.end - tolerance,+ self.analysisEnd <= referenced[referenced.count - 1].analysisInterval.end + tolerance,+ self.analysisEnd > referenced[referenced.count - 1].analysisInterval.start + tolerance+ else { return .spansDoNotCoverUnitInterval }+ let presentationStart = referenced[0].presentationMapping+ .presentationTime(forAnalysisTime: self.analysisStart)+ let presentationEnd = referenced[referenced.count - 1].presentationMapping+ .presentationTime(forAnalysisTime: self.analysisEnd)+ guard MeetingEvidenceInterval.isValid(start: presentationStart, end: presentationEnd) else {+ return .presentationMappingInvalid+ }+ return nil+ }+}diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingChunkAudioObserver.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingChunkAudioObserver.swiftnew file mode 100644index 00000000..6796779f--- /dev/null+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingChunkAudioObserver.swift@@ -0,0 +1,236 @@+import AVFoundation+import CryptoKit+import Foundation++// Stage C2a observation boundary. The analysis manifest may only contain audio facts that were+// *actually observed*, so this is the single place that touches a chunk file: it confines the path+// to the session directory, refuses symlinks, re-verifies the recorded byte count and SHA-256, and+// then asks AVFoundation what the file really contains.+//+// Every failure is a typed value rather than an exception the caller might swallow. The builder+// converts each one into an explicit analysis gap, so unreadable audio becomes visible missing+// coverage instead of silence that looks like it was transcribed.++/// Why one chunk could not become analysable audio. Each maps to exactly one gap reason.+nonisolated enum MeetingChunkObservationFailure: String, Codable, Equatable, CaseIterable {+ case fileMissing+ /// The path escaped the session directory, or a component of it was a symlink.+ case pathRejected+ case byteCountChanged+ case hashChanged+ /// The file exists and verifies, but no decoder would open it.+ case unreadable+ /// Zero bytes on disk, or zero decoded frames.+ case emptyAudio+ /// The decoder reported a non-positive sample rate, so no duration follows from its frames.+ case sampleRateUnusable+ /// A PCM-first chunk advertised an authoritative capture asset that was incomplete or+ /// internally inconsistent. The legacy AAC path is never used as a substitute.+ case analysisAssetInvalid++ var gapReason: MeetingAnalysisGapReason {+ switch self {+ case .fileMissing: return .chunkFileMissing+ case .pathRejected: return .chunkPathRejected+ case .byteCountChanged: return .chunkByteCountChanged+ case .hashChanged: return .chunkHashChanged+ case .unreadable: return .chunkUnreadable+ case .emptyAudio: return .chunkEmpty+ case .sampleRateUnusable: return .chunkSampleRateUnusable+ case .analysisAssetInvalid: return .chunkAnalysisAssetInvalid+ }+ }+}++nonisolated enum MeetingChunkObservationResult: Equatable {+ case observed(MeetingChunkObservedAudio)+ case failed(MeetingChunkObservationFailure, detail: String?)+}++/// The manifest builder's only route to the filesystem. Injectable so the builder can be exercised+/// over synthetic topologies without writing audio, and so the production reader stays one small,+/// auditable implementation.+nonisolated protocol MeetingChunkAudioObserving: Sendable {+ func observe(chunk: MeetingAudioChunk, trackID: MeetingAudioTrackID) -> MeetingChunkObservationResult+}++nonisolated struct MeetingChunkAudioObserver: MeetingChunkAudioObserving {+ let sessionDirectory: URL++ func observe(chunk: MeetingAudioChunk, trackID _: MeetingAudioTrackID) -> MeetingChunkObservationResult {+ let authority: (path: String, byteCount: Int64, sha256: String, asset: MeetingAudioAsset?)+ if chunk.audioSchemaVersion != nil {+ guard let asset = chunk.captureAnalysisAsset,+ asset.presence == .ready,+ asset.role == .captureAnalysis,+ asset.encoding == .linearPCMFloat32CAFV1,+ asset.validationIssues().isEmpty,+ let hash = asset.sha256, !hash.isEmpty+ else {+ return .failed(.analysisAssetInvalid, detail: "A PCM-first chunk has no valid ready linear-PCM capture asset.")+ }+ authority = (asset.relativeFilePath, asset.byteCount, hash, asset)+ } else {+ guard chunk.byteCount > 0, !chunk.sha256.isEmpty else {+ return .failed(.emptyAudio, detail: "The session manifest records no bytes for this chunk.")+ }+ authority = (chunk.relativeFilePath, chunk.byteCount, chunk.sha256, nil)+ }+ guard authority.byteCount > 0, !authority.sha256.isEmpty else {+ return .failed(.emptyAudio, detail: "The session manifest records no bytes for this chunk.")+ }+ let url: URL+ do {+ url = try self.containedURL(relativePath: authority.path)+ } catch {+ return .failed(.pathRejected, detail: authority.path)+ }++ let manager = FileManager.default+ guard let attributes = try? manager.attributesOfItem(atPath: url.path),+ (attributes[.type] as? FileAttributeType) == .typeRegular+ else {+ return .failed(.fileMissing, detail: authority.path)+ }+ let actualByteCount = (attributes[.size] as? NSNumber)?.int64Value ?? -1+ guard actualByteCount >= 0 else {+ return .failed(.fileMissing, detail: authority.path)+ }+ guard actualByteCount > 0 else {+ return .failed(.emptyAudio, detail: "0 bytes on disk.")+ }+ guard actualByteCount == authority.byteCount else {+ return .failed(+ .byteCountChanged,+ detail: "Expected \(authority.byteCount) bytes, found \(actualByteCount)."+ )+ }++ guard let digest = Self.sha256Hex(contentsOf: url) else {+ return .failed(.unreadable, detail: "The chunk could not be read for hashing.")+ }+ guard digest == authority.sha256.lowercased() else {+ return .failed(.hashChanged, detail: "Recorded digest no longer matches the file.")+ }++ return Self.decodedFacts(at: url, byteCount: actualByteCount, sha256: digest, asset: authority.asset)+ }++ /// What a decoder actually reports. Codec priming stays `unknown(.decoderDidNotReport)`:+ /// `AVAudioFile` exposes a decoded frame count, not an encoder delay, and this build has no+ /// verified way to tell whether that frame count already excludes the priming frames. Guessing+ /// either way would either double-trim real speech or shift every word by a delay nobody+ /// measured, which is exactly the universal-AAC-delay assumption the plan forbids.+ private static func decodedFacts(+ at url: URL,+ byteCount: Int64,+ sha256: String,+ asset: MeetingAudioAsset? = nil+ ) -> MeetingChunkObservationResult {+ let file: AVAudioFile+ do {+ file = try AVAudioFile(forReading: url)+ } catch {+ return .failed(.unreadable, detail: error.localizedDescription)+ }+ let format = file.processingFormat+ guard format.sampleRate.isFinite, format.sampleRate > 0 else {+ return .failed(.sampleRateUnusable, detail: "Decoder reported sample rate \(format.sampleRate).")+ }+ guard format.channelCount > 0 else {+ return .failed(.unreadable, detail: "Decoder reported \(format.channelCount) channels.")+ }+ let frameCount = Int64(file.length)+ guard frameCount > 0 else {+ return .failed(.emptyAudio, detail: "Decoder reported 0 frames.")+ }+ if let asset {+ guard asset.encoding == .linearPCMFloat32CAFV1,+ format.commonFormat == .pcmFormatFloat32,+ format.sampleRate == asset.sampleRate,+ Int(format.channelCount) == asset.channelCount,+ frameCount == asset.frameCount+ else {+ return .failed(.analysisAssetInvalid, detail: "PCM capture asset metadata does not match its CAF contents.")+ }+ }+ return .observed(MeetingChunkObservedAudio(+ byteCount: byteCount,+ sha256: sha256,+ decoded: MeetingChunkDecodedFacts(+ sampleRate: format.sampleRate,+ channelCount: Int(format.channelCount),+ frameCount: frameCount,+ durationSeconds: Double(frameCount) / format.sampleRate,+ codecPriming: asset == nil+ ? .unknown(.decoderDidNotReport)+ : .notApplicable(.linearPCMFloat32CAFV1),+ processingFormatDescription: "sampleRate=\(format.sampleRate);channels=\(format.channelCount);"+ + "commonFormat=\(format.commonFormat.rawValue);interleaved=\(format.isInterleaved)"+ )+ ))+ }++ /// Canonicalize the session root once, then require every component the chunk adds to be a+ /// real, non-symlink component underneath it. A pre-existing symlink inside the session+ /// directory is rejected as firmly as one that escapes it: both would make the verified digest+ /// describe a different file than the one a decoder later opens.+ private func containedURL(relativePath: String) throws -> URL {+ try MeetingChunkPathConfinement.containedURL(+ sessionDirectory: self.sessionDirectory,+ relativePath: relativePath+ )+ }++ private static func sha256Hex(contentsOf url: URL) -> String? {+ MeetingChunkPathConfinement.sha256Hex(contentsOf: url)+ }+}++/// The confinement and hashing primitives shared by the chunk observer and the Stage E epoch+/// materializer. Both must agree exactly: a path either is a real, non-symlink file inside the+/// session directory or it is rejected, and the digest is computed the same way in both places.+nonisolated enum MeetingChunkPathConfinement {+ struct PathRejected: Error {}++ static func containedURL(sessionDirectory: URL, relativePath: String) throws -> URL {+ let root = sessionDirectory.standardizedFileURL.resolvingSymlinksInPath()+ let components = relativePath.split(separator: "/", omittingEmptySubsequences: true).map(String.init)+ guard !relativePath.isEmpty,+ !relativePath.hasPrefix("/"),+ !components.isEmpty,+ !components.contains(".."),+ !components.contains(".")+ else { throw PathRejected() }++ let manager = FileManager.default+ var current = root+ for component in components {+ current.appendPathComponent(component, isDirectory: false)+ if let attributes = try? manager.attributesOfItem(atPath: current.path),+ (attributes[.type] as? FileAttributeType) == .typeSymbolicLink+ {+ throw PathRejected()+ }+ }+ let candidate = current.standardizedFileURL+ guard candidate.path.hasPrefix(root.path + "/") else { throw PathRejected() }+ return candidate+ }++ static func sha256Hex(contentsOf url: URL) -> String? {+ guard let handle = try? FileHandle(forReadingFrom: url) else { return nil }+ defer { try? handle.close() }+ var hasher = SHA256()+ while true {+ if Task.isCancelled { return nil }+ do {+ guard let block = try handle.read(upToCount: 1 << 20), !block.isEmpty else { break }+ hasher.update(data: block)+ } catch {+ return nil+ }+ }+ return hasher.finalize().map { String(format: "%02x", $0) }.joined()+ }+}diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingEpochAudioMaterializer.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingEpochAudioMaterializer.swiftnew file mode 100644index 00000000..165f2b57--- /dev/null+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingEpochAudioMaterializer.swift@@ -0,0 +1,371 @@+import AVFoundation+import Foundation++// Stage E of `MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md` (§3): materializing one analysis+// epoch's audio from the validated manifest. Every span re-opens only its confined, verified+// chunk path, slices exactly its `sourceLocalInterval` out of the decoded file, mono-mixes and+// resamples to the 16 kHz analysis stream, and concatenates in analysis order. The returned+// per-span sample ranges are the exact analysis-span mappings the backend's word/activity+// conversion relies on.+//+// Fail-closed on any TOCTOU drift: the file's byte count, SHA-256 and decoded facts must still+// match what the manifest observed, and the slice must be backed by real decoded frames. Nothing+// here guesses priming, invents samples or bridges across spans that are not in the epoch.++/// Sample range of one span inside its epoch's materialized buffer, in analysis order.+nonisolated struct MeetingMaterializedSpanSamples: Equatable, Sendable {+ let spanID: String+ let sampleRange: Range<Int>+}++/// One epoch's 16 kHz mono analysis audio plus its exact span mappings.+nonisolated struct MeetingMaterializedEpoch: Equatable, Sendable {+ let epochID: MeetingAnalysisEpochID+ let samples: [Float]+ let sampleRate: Double+ let spanSamples: [MeetingMaterializedSpanSamples]++ var durationSeconds: Double {+ self.sampleRate > 0 ? Double(self.samples.count) / self.sampleRate : 0+ }+}++nonisolated enum MeetingEpochMaterializationError: LocalizedError, Equatable {+ case unknownSpan(spanID: String)+ case pathRejected(spanID: String)+ case fileMissing(spanID: String)+ case byteCountChanged(spanID: String)+ case hashChanged(spanID: String)+ case unreadable(spanID: String)+ /// The file on disk no longer decodes to what the manifest observed (rate, channels, frames),+ /// or it no longer contains the frames the span's source interval requires. The payload lists+ /// the mismatched facts only, never a localized system string.+ case decodedFactsChanged(spanID: String, detail: String)+ case emptySlice(spanID: String)+ /// Conservative in-memory safety bound for the pre-production PCM working buffer. A durable+ /// disk-backed working store is the production follow-up; this bound keeps the current+ /// immutable in-memory implementation from growing without limit.+ case sampleLimitExceeded(spanID: String, sampleCount: Int)++ var errorDescription: String? {+ switch self {+ case let .unknownSpan(spanID):+ return "Analysis span \"\(spanID)\" is not part of its track manifest."+ case let .pathRejected(spanID):+ return "Analysis span \"\(spanID)\" resolves outside the session directory."+ case let .fileMissing(spanID):+ return "The chunk file for analysis span \"\(spanID)\" is missing."+ case let .byteCountChanged(spanID):+ return "The chunk file for analysis span \"\(spanID)\" changed size since observation."+ case let .hashChanged(spanID):+ return "The chunk file for analysis span \"\(spanID)\" changed content since observation."+ case let .unreadable(spanID):+ return "The chunk file for analysis span \"\(spanID)\" could not be decoded."+ case let .decodedFactsChanged(spanID, detail):+ return "The chunk file for analysis span \"\(spanID)\" no longer decodes to the observed facts (\(detail))."+ case let .emptySlice(spanID):+ return "Analysis span \"\(spanID)\" maps to no decodable audio frames."+ case let .sampleLimitExceeded(spanID, sampleCount):+ return "Analysis span \"\(spanID)\" exceeds the PCM materialization safety limit (\(sampleCount) samples)."+ }+ }++ var isSampleLimitExceeded: Bool {+ if case .sampleLimitExceeded = self { return true }+ return false+ }+}++/// Epoch materialization is backend work, injectable so backend tests exercise orchestration+/// without real audio; the production implementation below is the single file-touching one.+nonisolated protocol MeetingEpochAudioMaterializing: Sendable {+ func materialize(+ epoch: MeetingAnalysisEpochRecord,+ track: MeetingAnalysisTrackManifest,+ manifest: MeetingAnalysisManifest,+ sessionDirectory: URL+ ) async throws -> MeetingMaterializedEpoch+}++nonisolated struct MeetingEpochAudioMaterializer: MeetingEpochAudioMaterializing {+ /// 64M mono Float32 samples is about 256 MiB, enough for a one-hour two-track pre-production+ /// meeting while still preventing an accidental unbounded allocation. Replace with a scoped+ /// immutable disk working store before production retention requirements grow further.+ static let conservativeSampleLimit = 64 * 1024 * 1024+ let sampleRate: Double++ init(sampleRate: Double = 16_000) {+ self.sampleRate = sampleRate+ }++ func materialize(+ epoch: MeetingAnalysisEpochRecord,+ track: MeetingAnalysisTrackManifest,+ manifest _: MeetingAnalysisManifest,+ sessionDirectory: URL+ ) async throws -> MeetingMaterializedEpoch {+ let spansByID = Dictionary(+ track.spans.map { ($0.id, $0) },+ uniquingKeysWith: { first, _ in first }+ )+ // Read all spans first, then convert one contiguous format/era run in one converter call.+ // This is deliberately not a per-span resampler: converter state (including its filter+ // tail) is preserved across chunk boundaries, while a changed era/format/layout forces a+ // clean restart. Epochs contain no gaps, so concatenating only their spans cannot bridge+ // an uncovered interval.+ var sourceSlices: [SourceSlice] = []+ sourceSlices.reserveCapacity(epoch.spanIDs.count)+ for spanID in epoch.spanIDs {+ try Task.checkCancellation()+ guard let span = spansByID[spanID] else {+ throw MeetingEpochMaterializationError.unknownSpan(spanID: spanID)+ }+ sourceSlices.append(try self.readSpanAudio(span, sessionDirectory: sessionDirectory))+ }++ var samples: [Float] = []+ var spanSamples: [MeetingMaterializedSpanSamples] = []+ spanSamples.reserveCapacity(sourceSlices.count)+ var runStart = 0+ while runStart < sourceSlices.count {+ var runEnd = runStart + 1+ while runEnd < sourceSlices.count,+ sourceSlices[runEnd].conversionKey == sourceSlices[runStart].conversionKey {+ runEnd += 1+ }+ let run = Array(sourceSlices[runStart..<runEnd])+ let converted = try self.convert(run)+ guard samples.count + converted.samples.count <= Self.conservativeSampleLimit else {+ throw MeetingEpochMaterializationError.sampleLimitExceeded(+ spanID: run.last?.spanID ?? "unknown",+ sampleCount: samples.count + converted.samples.count+ )+ }+ let outputOffset = samples.count+ samples.append(contentsOf: converted.samples)+ var previousSourceFrames = 0+ for slice in run {+ let sourceEnd = previousSourceFrames + slice.samples.count+ let lower = Int((Double(previousSourceFrames) / slice.sampleRate * self.sampleRate).rounded())+ let upper = Int((Double(sourceEnd) / slice.sampleRate * self.sampleRate).rounded())+ let runLower = min(max(lower, 0), converted.samples.count)+ let runUpper = min(max(upper, runLower), converted.samples.count)+ spanSamples.append(MeetingMaterializedSpanSamples(+ spanID: slice.spanID,+ sampleRange: (outputOffset + runLower)..<(outputOffset + runUpper)+ ))+ previousSourceFrames = sourceEnd+ }+ // The converter's actual frame count is authoritative. Rounding above normally lands+ // exactly on it; pin the final range to the actual end so no converter tail is lost.+ if let last = spanSamples.indices.last {+ let current = spanSamples[last]+ spanSamples[last] = MeetingMaterializedSpanSamples(+ spanID: current.spanID,+ sampleRange: current.sampleRange.lowerBound..<(outputOffset + converted.samples.count)+ )+ }+ runStart = runEnd+ }++ return MeetingMaterializedEpoch(+ epochID: epoch.id,+ samples: samples,+ sampleRate: self.sampleRate,+ spanSamples: spanSamples+ )+ }++ private struct SourceSlice {+ let spanID: String+ let samples: [Float]+ let sampleRate: Double+ let conversionKey: String+ }++ private struct ConvertedRun {+ let samples: [Float]+ }++ private func convert(_ run: [SourceSlice]) throws -> ConvertedRun {+ guard let first = run.first,+ let format = AVAudioFormat(+ commonFormat: .pcmFormatFloat32,+ sampleRate: first.sampleRate,+ channels: 1,+ interleaved: false+ ),+ let buffer = AVAudioPCMBuffer(+ pcmFormat: format,+ frameCapacity: AVAudioFrameCount(run.reduce(0) { $0 + $1.samples.count })+ ) else {+ throw MeetingEpochMaterializationError.emptySlice(spanID: run.first?.spanID ?? "unknown")+ }+ let values = run.flatMap(\.samples)+ buffer.frameLength = AVAudioFrameCount(values.count)+ guard let destination = buffer.floatChannelData?[0] else {+ throw MeetingEpochMaterializationError.emptySlice(spanID: first.spanID)+ }+ values.withUnsafeBufferPointer { source in+ destination.update(from: source.baseAddress!, count: source.count)+ }+ do {+ return ConvertedRun(samples: try AudioBufferConverter.monoSamples(+ from: buffer,+ targetSampleRate: self.sampleRate+ ))+ } catch {+ throw MeetingEpochMaterializationError.unreadable(spanID: first.spanID)+ }+ }++ /// Re-verifies the chunk against the manifest's observation, then decodes exactly the span's+ /// source-local interval and returns native-rate mono samples. Resampling is performed once per+ /// contiguous run by `convert(_:)`, rather than once per span.+ private func readSpanAudio(+ _ span: MeetingAnalysisSpan,+ sessionDirectory: URL+ ) throws -> SourceSlice {+ if let encoding = span.chunk.analysisEncoding, encoding != .linearPCMFloat32CAFV1 {+ throw MeetingEpochMaterializationError.unreadable(spanID: span.id)+ }+ let url: URL+ do {+ url = try MeetingChunkPathConfinement.containedURL(+ sessionDirectory: sessionDirectory,+ relativePath: span.chunk.relativeFilePath+ )+ } catch {+ throw MeetingEpochMaterializationError.pathRejected(spanID: span.id)+ }++ let manager = FileManager.default+ guard let attributes = try? manager.attributesOfItem(atPath: url.path),+ (attributes[.type] as? FileAttributeType) == .typeRegular+ else {+ throw MeetingEpochMaterializationError.fileMissing(spanID: span.id)+ }+ guard (attributes[.size] as? NSNumber)?.int64Value == span.storedByteCount else {+ throw MeetingEpochMaterializationError.byteCountChanged(spanID: span.id)+ }+ guard let digest = MeetingChunkPathConfinement.sha256Hex(contentsOf: url) else {+ try Task.checkCancellation()+ throw MeetingEpochMaterializationError.unreadable(spanID: span.id)+ }+ guard digest == span.storedSHA256.lowercased() else {+ throw MeetingEpochMaterializationError.hashChanged(spanID: span.id)+ }++ let file: AVAudioFile+ do {+ file = try AVAudioFile(forReading: url)+ } catch {+ throw MeetingEpochMaterializationError.unreadable(spanID: span.id)+ }+ let format = file.processingFormat+ let observed = span.observed.decoded+ guard format.sampleRate == observed.sampleRate,+ Int(format.channelCount) == observed.channelCount,+ Int64(file.length) == observed.frameCount+ else {+ let detail = "rate \(format.sampleRate) vs \(observed.sampleRate); channels \(format.channelCount) vs \(observed.channelCount); frames \(file.length) vs \(observed.frameCount)"+ throw MeetingEpochMaterializationError.decodedFactsChanged(spanID: span.id, detail: detail)+ }++ let startFrame = AVAudioFramePosition(+ (span.sourceLocalInterval.start * observed.sampleRate).rounded(.down)+ )+ let endFrame = min(+ AVAudioFramePosition((span.sourceLocalInterval.end * observed.sampleRate).rounded(.up)),+ file.length+ )+ guard endFrame > startFrame else {+ throw MeetingEpochMaterializationError.emptySlice(spanID: span.id)+ }+ let frameCount = AVAudioFrameCount(endFrame - startFrame)+ guard format.commonFormat == .pcmFormatFloat32,+ let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameCount)+ else {+ throw MeetingEpochMaterializationError.unreadable(spanID: span.id)+ }+ file.framePosition = startFrame+ // `AVAudioFile` may return fewer frames than requested even before EOF. Read into fresh+ // buffers and append explicitly; reading repeatedly into the same PCM buffer overwrites+ // its prior contents rather than extending them.+ var framesRead: AVAudioFrameCount = 0+ while framesRead < frameCount {+ try Task.checkCancellation()+ let requested = min(frameCount - framesRead, 32_768)+ guard let part = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: requested) else {+ throw MeetingEpochMaterializationError.unreadable(spanID: span.id)+ }+ do {+ try file.read(into: part, frameCount: requested)+ } catch {+ throw MeetingEpochMaterializationError.unreadable(spanID: span.id)+ }+ guard part.frameLength > 0 else { break }+ let copied = Int(part.frameLength)+ guard let sourceChannels = part.floatChannelData,+ let destinationChannels = buffer.floatChannelData else { break }+ let destinationOffset = Int(framesRead)+ if format.isInterleaved {+ // Interleaved Float32 exposes one channel pointer containing all channels.+ destinationChannels[0].advanced(by: destinationOffset * Int(format.channelCount)).update(+ from: sourceChannels[0], count: copied * Int(format.channelCount)+ )+ } else {+ for channel in 0..<Int(format.channelCount) {+ destinationChannels[channel].advanced(by: destinationOffset).update(+ from: sourceChannels[channel], count: copied+ )+ }+ }+ framesRead += part.frameLength+ }+ buffer.frameLength = framesRead+ guard AVAudioFramePosition(framesRead) == endFrame - startFrame else {+ let detail = "read \(framesRead) frames of \(endFrame - startFrame) required"+ throw MeetingEpochMaterializationError.decodedFactsChanged(spanID: span.id, detail: detail)+ }++ guard let channels = buffer.floatChannelData else {+ throw MeetingEpochMaterializationError.unreadable(spanID: span.id)+ }+ var mono = [Float](repeating: 0, count: Int(buffer.frameLength))+ if format.isInterleaved {+ let source = channels[0]+ let channelCount = Int(format.channelCount)+ for frame in 0..<mono.count {+ var value: Float = 0+ for channel in 0..<channelCount { value += source[frame * channelCount + channel] }+ mono[frame] = value / Float(channelCount)+ }+ } else {+ let channelCount = Int(format.channelCount)+ for frame in 0..<mono.count {+ var value: Float = 0+ for channel in 0..<channelCount { value += channels[channel][frame] }+ mono[frame] = value / Float(channelCount)+ }+ }+ try Task.checkCancellation()+ // Close the hash/open/read race: the path must still name the same bytes after decoding.+ // A replacement or in-place rewrite during the read is therefore refused rather than+ // becoming evidence under the manifest's earlier digest.+ guard MeetingChunkPathConfinement.sha256Hex(contentsOf: url) == span.storedSHA256.lowercased() else {+ try Task.checkCancellation()+ throw MeetingEpochMaterializationError.hashChanged(spanID: span.id)+ }+ let layoutDescription = format.channelLayout.map { layout in+ let ptr = layout.layout.pointee+ return "tag=\(ptr.mChannelLayoutTag);count=\(ptr.mNumberChannelDescriptions)"+ } ?? "none"+ return SourceSlice(+ spanID: span.id,+ samples: mono,+ sampleRate: observed.sampleRate,+ conversionKey: "epoch=\(span.analysisEpochID);era=\(span.captureEra.index);rate=\(observed.sampleRate);channels=\(observed.channelCount);interleaved=\(format.isInterleaved);layout=\(layoutDescription)"+ )+ }+}diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingLegacyCompatibilityBackend.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingLegacyCompatibilityBackend.swiftnew file mode 100644index 00000000..6c86a5d6--- /dev/null+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingLegacyCompatibilityBackend.swift@@ -0,0 +1,64 @@+import Foundation++/// Explicit temporary compatibility path (plan §6: "A may wrap the existing final times as an+/// explicit temporary compatibility path").+///+/// It runs the unchanged in-pipeline workflow — the same `SpeakerDiarizationService` passes, echo+/// policy, near-field gate, "You" election, checkpoint read/write, segment IDs and timestamps — by+/// calling the executor the pipeline injects. It deliberately produces no+/// `MeetingFinalTranscriptEvidence`: mapping the legacy result onto canonical text units requires+/// the analysis manifest and assembler that belong to Stage C, and inventing that mapping now would+/// fabricate per-word timing and provenance the legacy path never computed.+@MainActor+final class MeetingLegacyCompatibilityBackend: MeetingTranscriptionBackend {+ static let descriptor = MeetingBackendDescriptor(+ id: .legacyCompatibility,+ version: "1",+ execution: .local,+ supportedLanguageCodes: ["en"],+ supportedTrackKinds: Set(MeetingAudioTrackKind.allCases),+ // Legacy output is already-merged turn text. It carries no word-level final units, so it+ // must never be read as word precision.+ supportedFinalPrecisions: [.utterance],+ resultContract: .legacyResult,+ knownLimits: [+ "Returns the existing MeetingProcessingResult directly; it emits no canonical final text-unit evidence.",+ "Per-word timings, coverage receipts and a disposition ledger are not produced.",+ "Speaker identity keeps the existing prototype-based local-speaker election unchanged.",+ ]+ )++ var descriptor: MeetingBackendDescriptor {+ Self.descriptor+ }++ private let legacyExecutor: MeetingLegacyBackendExecutor++ init(legacyExecutor: @escaping MeetingLegacyBackendExecutor) {+ self.legacyExecutor = legacyExecutor+ }++ func plan(_ request: MeetingBackendRequest) throws -> MeetingBackendPlan {+ guard self.descriptor.supportedLanguageCodes.contains(request.session.languageCode) else {+ throw MeetingBackendError.unsupportedLanguage(+ backend: self.descriptor.id,+ languageCode: request.session.languageCode+ )+ }+ let plan = MeetingBackendPlan(request: request, descriptor: self.descriptor)+ guard !plan.trackKindsByID.isEmpty else {+ throw MeetingBackendError.unsupportedTrackTopology(backend: self.descriptor.id)+ }+ return plan+ }++ func execute(+ plan: MeetingBackendPlan,+ manifest: MeetingAnalysisManifest?,+ progress: @escaping @MainActor (MeetingProcessingStage) -> Void+ ) async throws -> MeetingBackendOutcome {+ // The legacy contract receives no manifest: the existing in-pipeline workflow keeps its+ // own timing and mapping, and a second mapper would double-apply the de-drift correction.+ try .legacyCompatibility(await self.legacyExecutor(plan.request, progress))+ }+}diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingNemotronModelLocator.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingNemotronModelLocator.swiftnew file mode 100644index 00000000..95f46f39--- /dev/null+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingNemotronModelLocator.swift@@ -0,0 +1,219 @@+import CryptoKit+import Foundation++// Stage E of `MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md` (§5): FluidVoice-side Nemotron model+// readiness. This locator only resolves and validates a local, already-installed model package.+// It never downloads, never guesses a hosting URL and never accepts a symlink — the 190 MB+// weights are delivered by a separate, not-yet-built preparation step, and `execute` performs no+// downloads.+//+// Resolution order: an injected URL (tests), then the development environment override+// `FLUIDVOICE_NEMOTRON_DIARIZATION_MODEL_PATH`, then the versioned FluidVoice cache location.+// `recheck` re-walks the package when it is opened and refuses a missing or changed artifact.++/// A validated local Nemotron model package plus the facts measured while validating it.+nonisolated struct MeetingNemotronModelArtifact: Equatable, Sendable {+ let packageURL: URL+ let totalByteCount: Int64+ let fileCount: Int+ /// SHA-256 of the package's `Manifest.json` — the package's own descriptor of its contents.+ let manifestSHA256: String+ /// Stable digest of every regular entry's relative path, logical size and modification time.+ /// This makes a same-size weight replacement visible without hashing 190 MB on the main actor.+ let entryMetadataSHA256: String+}++nonisolated enum MeetingNemotronModelReadinessError: LocalizedError, Equatable {+ /// Nothing exists at the resolved location.+ case modelNotInstalled(path: String)+ /// The resolved path fails package-structure validation. The payload is a stable diagnostic+ /// token, never a localized system string.+ case invalidModelPackage(reason: String)+ /// The package validated earlier no longer matches what is on disk now.+ case artifactChanged(path: String)++ var errorDescription: String? {+ switch self {+ case let .modelNotInstalled(path):+ return "The Nemotron diarization model is not installed at \(path). "+ + "Meeting model preparation has not run."+ case let .invalidModelPackage(reason):+ return "The Nemotron diarization model package is invalid (\(reason))."+ case let .artifactChanged(path):+ return "The Nemotron diarization model at \(path) changed since it was validated."+ }+ }+}++nonisolated protocol MeetingNemotronModelLocating: Sendable {+ func locate() throws -> MeetingNemotronModelArtifact+ /// Re-validates a previously located artifact before opening it. Any drift is a refusal.+ func recheck(_ artifact: MeetingNemotronModelArtifact) throws -> MeetingNemotronModelArtifact+}++nonisolated struct MeetingNemotronModelLocator: MeetingNemotronModelLocating {+ static let environmentOverrideKey = "FLUIDVOICE_NEMOTRON_DIARIZATION_MODEL_PATH"+ static let cacheVersion = "v1"+ static let packageFileName = "nemotron_diar_fp16.mlpackage"+ private static let maximumFileCount = 64+ private static let maximumTotalByteCount: Int64 = 1_000_000_000++ let injectedURL: URL?+ let environment: [String: String]++ init(+ injectedURL: URL? = nil,+ environment: [String: String] = ProcessInfo.processInfo.environment+ ) {+ self.injectedURL = injectedURL+ self.environment = environment+ }++ /// The versioned FluidVoice cache location used when nothing is injected or overridden.+ static func defaultPackageURL() -> URL {+ let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first+ ?? FileManager.default.homeDirectoryForCurrentUser+ .appendingPathComponent("Library/Application Support", isDirectory: true)+ return base+ .appendingPathComponent("FluidVoice", isDirectory: true)+ .appendingPathComponent("MeetingModels", isDirectory: true)+ .appendingPathComponent("nemotron-3-diarization", isDirectory: true)+ .appendingPathComponent(Self.cacheVersion, isDirectory: true)+ .appendingPathComponent(Self.packageFileName, isDirectory: true)+ }++ func resolvedPackageURL() -> URL {+ if let injectedURL { return injectedURL }+ if let override = self.environment[Self.environmentOverrideKey],+ !override.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ {+ return URL(fileURLWithPath: override)+ }+ return Self.defaultPackageURL()+ }++ func locate() throws -> MeetingNemotronModelArtifact {+ let url = self.resolvedPackageURL().standardizedFileURL+ return try Self.validatePackage(at: url)+ }++ func recheck(_ artifact: MeetingNemotronModelArtifact) throws -> MeetingNemotronModelArtifact {+ let current = try self.locate()+ guard current.packageURL == artifact.packageURL,+ current.totalByteCount == artifact.totalByteCount,+ current.fileCount == artifact.fileCount,+ current.manifestSHA256 == artifact.manifestSHA256,+ current.entryMetadataSHA256 == artifact.entryMetadataSHA256+ else {+ throw MeetingNemotronModelReadinessError.artifactChanged(path: artifact.packageURL.path)+ }+ return current+ }++ /// Structural validation of one package: a real directory (not a symlink) containing a real+ /// `Manifest.json` and at least one `model.mlmodel`, with no symlink anywhere inside it. A+ /// symlinked component would make the measured bytes describe a different file than CoreML+ /// later opens.+ static func validatePackage(at url: URL) throws -> MeetingNemotronModelArtifact {+ let manager = FileManager.default+ guard let attributes = try? manager.attributesOfItem(atPath: url.path),+ let type = attributes[.type] as? FileAttributeType+ else {+ throw MeetingNemotronModelReadinessError.modelNotInstalled(path: url.path)+ }+ guard type == .typeDirectory else {+ if type == .typeSymbolicLink {+ throw MeetingNemotronModelReadinessError.invalidModelPackage(reason: "packageIsSymlink")+ }+ throw MeetingNemotronModelReadinessError.invalidModelPackage(reason: "packageNotDirectory")+ }+ guard url.resolvingSymlinksInPath().standardizedFileURL == url else {+ throw MeetingNemotronModelReadinessError.invalidModelPackage(reason: "packagePathContainsSymlink")+ }++ var totalByteCount: Int64 = 0+ var fileCount = 0+ var hasManifest = false+ var hasModel = false+ var manifestSHA256 = ""+ var entryMetadata: [(path: String, size: Int, modified: TimeInterval)] = []++ guard let enumerator = manager.enumerator(+ at: url,+ includingPropertiesForKeys: [.isRegularFileKey, .isSymbolicLinkKey],+ options: []+ ) else {+ throw MeetingNemotronModelReadinessError.invalidModelPackage(reason: "packageUnreadable")+ }+ for case let entry as URL in enumerator {+ let values = try resourceValues(entry)+ if values.isSymbolicLink == true {+ throw MeetingNemotronModelReadinessError.invalidModelPackage(reason: "packageContainsSymlink")+ }+ guard values.isRegularFile == true else { continue }+ fileCount += 1+ guard fileCount <= Self.maximumFileCount else {+ throw MeetingNemotronModelReadinessError.invalidModelPackage(reason: "packageHasTooManyFiles")+ }+ let logicalSize = values.fileSize ?? 0+ totalByteCount += Int64(logicalSize)+ guard totalByteCount <= Self.maximumTotalByteCount else {+ throw MeetingNemotronModelReadinessError.invalidModelPackage(reason: "packageTooLarge")+ }+ let relativePath = String(entry.path.dropFirst(url.path.count + 1))+ entryMetadata.append((+ path: relativePath,+ size: logicalSize,+ modified: values.contentModificationDate?.timeIntervalSince1970 ?? 0+ ))+ if entry.lastPathComponent == "Manifest.json" {+ hasManifest = true+ manifestSHA256 = try Self.sha256Hex(contentsOf: entry)+ }+ if entry.lastPathComponent == "model.mlmodel" {+ hasModel = true+ }+ }+ guard hasManifest else {+ throw MeetingNemotronModelReadinessError.invalidModelPackage(reason: "manifestMissing")+ }+ guard hasModel else {+ throw MeetingNemotronModelReadinessError.invalidModelPackage(reason: "modelMissing")+ }+ guard fileCount > 0, totalByteCount > 0 else {+ throw MeetingNemotronModelReadinessError.invalidModelPackage(reason: "packageEmpty")+ }++ let metadataBytes = entryMetadata.sorted { $0.path < $1.path }.map {+ "\($0.path)\u{0}\($0.size)\u{0}\($0.modified.bitPattern)\n"+ }.joined()+ let entryMetadataSHA256 = SHA256.hash(data: Data(metadataBytes.utf8))+ .map { String(format: "%02x", $0) }.joined()++ return MeetingNemotronModelArtifact(+ packageURL: url,+ totalByteCount: totalByteCount,+ fileCount: fileCount,+ manifestSHA256: manifestSHA256,+ entryMetadataSHA256: entryMetadataSHA256+ )+ }++ private static func resourceValues(_ url: URL) throws -> URLResourceValues {+ do {+ return try url.resourceValues(forKeys: [+ .isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey, .totalFileAllocatedSizeKey,+ .contentModificationDateKey,+ ])+ } catch {+ throw MeetingNemotronModelReadinessError.invalidModelPackage(reason: "entryUnreadable")+ }+ }++ private static func sha256Hex(contentsOf url: URL) throws -> String {+ guard let data = try? Data(contentsOf: url) else {+ throw MeetingNemotronModelReadinessError.invalidModelPackage(reason: "manifestUnreadable")+ }+ return SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()+ }+}diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingPCMFormatContract.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingPCMFormatContract.swiftnew file mode 100644index 00000000..c020d4dc--- /dev/null+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingPCMFormatContract.swift@@ -0,0 +1,106 @@+@preconcurrency import AVFoundation+import AudioToolbox+import CoreMedia+import Foundation++/// The format identity shared by capture writers and PCM sinks. Channel topology is validated+/// but intentionally excluded from identity: the sink canonicalizes planar input into interleaved+/// CAF, so an interleaved/planar transition with the same semantic layout is one capture epoch.+nonisolated struct MeetingPCMFormatContract: Equatable, Sendable {+ nonisolated enum SemanticLayout: Equatable, Sendable {+ case mono+ case stereo+ case explicit(Data)+ }++ let sampleRate: Double+ let channelCount: Int+ let layout: SemanticLayout++ var description: String {+ let layoutDescription: String+ switch layout {+ case .mono: layoutDescription = "mono"+ case .stereo: layoutDescription = "stereo"+ case let .explicit(bytes): layoutDescription = "explicit(\(bytes.count) bytes)"+ }+ return "lpcm-f32 rate=\(sampleRate) channels=\(channelCount) layout=\(layoutDescription)"+ }++ init(audioFormat: AVAudioFormat) throws {+ try self.init(asbd: audioFormat.streamDescription.pointee, layoutData: Self.layoutData(audioFormat.channelLayout))+ }++ init(formatDescription: CMFormatDescription) throws {+ guard let asbd = CMAudioFormatDescriptionGetStreamBasicDescription(formatDescription)?.pointee else {+ throw MeetingPCMFormatContractError.unsupported("missing LPCM stream description")+ }+ try self.init(asbd: asbd, layoutData: Self.layoutData(formatDescription))+ }++ init(asbd: AudioStreamBasicDescription, layoutData: Data?) throws {+ guard asbd.mFormatID == kAudioFormatLinearPCM,+ asbd.mSampleRate.isFinite, asbd.mSampleRate > 0,+ asbd.mChannelsPerFrame > 0,+ asbd.mBitsPerChannel == 32,+ asbd.mFramesPerPacket == 1,+ asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0,+ asbd.mFormatFlags & kAudioFormatFlagIsSignedInteger == 0+ else { throw MeetingPCMFormatContractError.unsupported("native Float32 LPCM required") }++ let isNonInterleaved = asbd.mFormatFlags & kAudioFormatFlagIsNonInterleaved != 0+ if isNonInterleaved {+ guard asbd.mBytesPerFrame == 4, asbd.mBytesPerPacket == 4 else {+ throw MeetingPCMFormatContractError.unsupported("invalid planar Float32 byte layout")+ }+ } else {+ let expectedBytes = UInt64(asbd.mChannelsPerFrame) * 4+ guard UInt64(asbd.mBytesPerFrame) == expectedBytes,+ UInt64(asbd.mBytesPerPacket) == expectedBytes else {+ throw MeetingPCMFormatContractError.unsupported("invalid interleaved Float32 byte layout")+ }+ }++ self.sampleRate = asbd.mSampleRate+ self.channelCount = Int(asbd.mChannelsPerFrame)+ self.layout = Self.semanticLayout(channelCount: self.channelCount, layoutData: layoutData)+ }++ private static func semanticLayout(channelCount: Int, layoutData: Data?) -> SemanticLayout {+ let tag = layoutData.flatMap { data -> UInt32? in+ guard data.count >= MemoryLayout<UInt32>.size else { return nil }+ return data.withUnsafeBytes { $0.loadUnaligned(as: UInt32.self) }+ }+ if channelCount == 1,+ tag == nil || tag == kAudioChannelLayoutTag_Mono ||+ tag == (kAudioChannelLayoutTag_DiscreteInOrder | UInt32(channelCount)) {+ return .mono+ }+ if channelCount == 2,+ tag == nil || tag == kAudioChannelLayoutTag_Stereo {+ return .stereo+ }+ return .explicit(layoutData ?? Data())+ }++ static func layoutData(_ layout: AVAudioChannelLayout?) -> Data? {+ guard let layout else { return nil }+ let tag = layout.layout.pointee.mChannelLayoutTag+ let count = layout.layout.pointee.mNumberChannelDescriptions+ let headerSize = MemoryLayout<UInt32>.size * 3+ let size = tag != kAudioChannelLayoutTag_UseChannelDescriptions+ ? headerSize+ : headerSize + Int(count) * MemoryLayout<AudioChannelDescription>.stride+ return Data(bytes: layout.layout, count: size)+ }++ static func layoutData(_ desc: CMFormatDescription) -> Data? {+ var size = 0+ guard let ptr = CMAudioFormatDescriptionGetChannelLayout(desc, sizeOut: &size), size > 0 else { return nil }+ return Data(bytes: ptr, count: size)+ }+}++nonisolated enum MeetingPCMFormatContractError: Error, Equatable, Sendable {+ case unsupported(String)+}diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingParakeetNemotronBackend.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingParakeetNemotronBackend.swiftnew file mode 100644index 00000000..7f248f14--- /dev/null+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingParakeetNemotronBackend.swift@@ -0,0 +1,567 @@+import Foundation++// Stage E of `MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md`: the local composite backend.+// Parakeet TDT v2 produces word-timed ASR; Nemotron-3 produces per-epoch speaker activity. The+// backend owns orchestration — per-epoch materialization, unit construction, slot assignment and+// exactly-tiling coverage receipts — while the host-injected runtime owns the two model+// capabilities. It never touches the filesystem outside the frozen request's session directory,+// never merges speaker slots across tracks or epochs, and never invents timing: clamping happens+// only at physical epoch bounds, and text without word timings becomes one epoch-covering+// utterance rather than fabricated words.++@MainActor+final class MeetingParakeetNemotronBackend: MeetingTranscriptionBackend {+ static let descriptor = MeetingBackendDescriptor(+ id: .parakeetNemotron,+ version: "1",+ execution: .local,+ supportedLanguageCodes: ["en"],+ supportedTrackKinds: Set(MeetingAudioTrackKind.allCases),+ supportedFinalPrecisions: [.word, .utterance],+ resultContract: .canonicalEvidence,+ knownLimits: [+ "Nemotron-3 has 8 speaker slots per analysis epoch; a ninth voice is not reliably announced or separated.",+ "Speaker slots are epoch-scoped: no identity is merged across tracks or analysis epochs.",+ "English only; the fixed Parakeet TDT v2 meeting policy rejects other requested options.",+ "When ASR returns text without usable word timings, one utterance covering the epoch is emitted instead of fabricated words.",+ "Local Nemotron model must be installed before planning; execute performs no downloads.",+ ],+ analysisSampleRate: 16_000+ )++ var descriptor: MeetingBackendDescriptor {+ Self.descriptor+ }++ private let runtimeFactory: MeetingParakeetNemotronRuntimeFactory+ private let modelLocator: any MeetingNemotronModelLocating+ private let materializer: any MeetingEpochAudioMaterializing+ private var plannedArtifact: (attemptID: UUID, artifact: MeetingNemotronModelArtifact)?++ init(+ runtimeFactory: @escaping MeetingParakeetNemotronRuntimeFactory,+ modelLocator: any MeetingNemotronModelLocating = MeetingNemotronModelLocator(),+ materializer: any MeetingEpochAudioMaterializing = MeetingEpochAudioMaterializer()+ ) {+ self.runtimeFactory = runtimeFactory+ self.modelLocator = modelLocator+ self.materializer = materializer+ }++ func plan(_ request: MeetingBackendRequest) throws -> MeetingBackendPlan {+ guard self.descriptor.supportedLanguageCodes.contains(request.session.languageCode) else {+ throw MeetingBackendError.unsupportedLanguage(+ backend: self.descriptor.id,+ languageCode: request.session.languageCode+ )+ }+ // The fixed meeting Parakeet v2 policy rejects unsupported requested options explicitly+ // (plan §5): no coercion of another model or feature into this backend.+ _ = try MeetingProviderOptions.resolve(request.configuration)+ // Model readiness is a precondition of planning; execute performs no downloads.+ let artifact = try self.modelLocator.locate()+ let plan = MeetingBackendPlan(request: request, descriptor: self.descriptor)+ guard !plan.trackKindsByID.isEmpty else {+ throw MeetingBackendError.unsupportedTrackTopology(backend: self.descriptor.id)+ }+ self.plannedArtifact = (request.attemptID, artifact)+ return plan+ }++ func execute(+ plan: MeetingBackendPlan,+ manifest: MeetingAnalysisManifest?,+ progress: @escaping @MainActor (MeetingProcessingStage) -> Void+ ) async throws -> MeetingBackendOutcome {+ guard let manifest else {+ throw MeetingBackendError.outcomeContractMismatch(+ backend: self.descriptor.id,+ declared: .canonicalEvidence+ )+ }+ let validatedManifest = try manifest.validated(against: plan)+ guard let plannedArtifact = self.plannedArtifact,+ plannedArtifact.attemptID == plan.attemptID+ else {+ throw MeetingBackendError.planDisagreesWithRequest(+ backend: self.descriptor.id,+ defect: .attemptIdentity+ )+ }+ let artifact = try self.modelLocator.recheck(plannedArtifact.artifact)+ self.plannedArtifact = nil+ // The host hands out the runtime only for the exact frozen request.+ let runtime = try self.runtimeFactory(plan.request)+ let materializer = self.materializer+ let request = plan.request+ let work = Task.detached(priority: .userInitiated) {+ try await Self.runAttempt(+ request: request,+ manifest: validatedManifest,+ runtime: runtime,+ artifact: artifact,+ materializer: materializer,+ progress: progress+ )+ }+ let bundle = try await withTaskCancellationHandler {+ try await work.value+ } onCancel: {+ work.cancel()+ }+ try Task.checkCancellation()+ return .canonicalEvidence(bundle)+ }++ // MARK: - Orchestration (background context)++ /// One epoch's work item: its manifest spans in analysis order.+ private nonisolated struct EpochWork: Sendable {+ let track: MeetingAnalysisTrackManifest+ let epoch: MeetingAnalysisEpochRecord+ let spans: [MeetingAnalysisSpan]+ }++ /// Per-attempt cache for the PCM-first path. The cache is intentionally scoped to this+ /// detached attempt and bounded by the materializer's conservative sample limit; a future+ /// production implementation should replace it with a hashed immutable disk working store.+ private nonisolated final class MaterializationCache: @unchecked Sendable {+ private let lock = NSLock()+ private var values: [MeetingAnalysisEpochID: MeetingMaterializedEpoch] = [:]+ private var totalSampleCount = 0++ func value(for epochID: MeetingAnalysisEpochID) -> MeetingMaterializedEpoch? {+ self.lock.lock(); defer { self.lock.unlock() }+ return self.values[epochID]+ }++ func insert(_ value: MeetingMaterializedEpoch, spanID: String) throws {+ self.lock.lock(); defer { self.lock.unlock() }+ let replacing = self.values[value.epochID]?.samples.count ?? 0+ let proposed = self.totalSampleCount - replacing + value.samples.count+ guard proposed <= MeetingEpochAudioMaterializer.conservativeSampleLimit else {+ throw MeetingEpochMaterializationError.sampleLimitExceeded(+ spanID: spanID,+ sampleCount: proposed+ )+ }+ self.values[value.epochID] = value+ self.totalSampleCount = proposed+ }+ }++ private nonisolated static func runAttempt(+ request: MeetingBackendRequest,+ manifest: MeetingAnalysisManifest,+ runtime: any MeetingParakeetNemotronRunning,+ artifact: MeetingNemotronModelArtifact,+ materializer: any MeetingEpochAudioMaterializing,+ progress: @escaping @MainActor (MeetingProcessingStage) -> Void+ ) async throws -> MeetingCanonicalResultBundle {+ let epochWork: [EpochWork] = manifest.tracks.flatMap { track in+ let spansByID = Dictionary(+ track.spans.map { ($0.id, $0) },+ uniquingKeysWith: { first, _ in first }+ )+ return track.epochs.map { epoch in+ EpochWork(+ track: track,+ epoch: epoch,+ spans: epoch.spanIDs.compactMap { spansByID[$0] }+ )+ }+ }++ let pcmMaterializations = MaterializationCache()++ // Phase A: Nemotron diarization, one fresh state per epoch, then drained.+ await progress(.identifyingSpeakers)+ let phaseA = try await runtime.withNemotronDiarization(artifact: artifact) { factory in+ var result = MeetingNemotronPhaseResult()+ for work in epochWork {+ try Task.checkCancellation()+ let materialized: MeetingMaterializedEpoch+ do {+ materialized = try await Self.materialize(+ work: work,+ manifest: manifest,+ request: request,+ materializer: materializer,+ cache: pcmMaterializations+ )+ } catch let error as CancellationError {+ throw error+ } catch let error as MeetingEpochMaterializationError where error.isSampleLimitExceeded {+ throw error+ } catch {+ result.failures[work.epoch.id] = "epochMaterializationFailed"+ continue+ }+ try Task.checkCancellation()+ do {+ let diarizer = try await factory.makeDiarizer(epoch: work.epoch.id)+ let segments = try await diarizer.diarize(samples: materialized.samples)+ for segment in segments {+ guard let start = Self.analysisTime(+ forMaterializedSeconds: segment.start,+ boundary: .start,+ materialized: materialized,+ spans: work.spans+ ), let end = Self.analysisTime(+ forMaterializedSeconds: segment.end,+ boundary: .end,+ materialized: materialized,+ spans: work.spans+ ) else { continue }+ guard end > start else { continue }+ result.activity.append(MeetingBackendSpeakerActivity(+ token: MeetingBackendSpeakerToken(+ analysisEpochID: work.epoch.id,+ label: "slot-\(segment.slotIndex)"+ ),+ start: start,+ end: end+ ))+ }+ } catch let error as CancellationError {+ throw error+ } catch {+ result.failures[work.epoch.id] = "diarizationFailed"+ continue+ }+ }+ return result+ }+ try Task.checkCancellation()++ // Phase B: Parakeet ASR inside the attempt's single prepared-meeting scope. Epochs that+ // failed phase A are excluded from ASR as well: an epoch is one unit of work.+ await progress(.transcribing)+ let phaseB = try await runtime.withPreparedASR(+ attemptID: request.attemptID,+ configuration: request.configuration+ ) { asr in+ var result = MeetingParakeetPhaseResult()+ for work in epochWork where phaseA.failures[work.epoch.id] == nil {+ try Task.checkCancellation()+ let materialized: MeetingMaterializedEpoch+ do {+ materialized = try await Self.materialize(+ work: work,+ manifest: manifest,+ request: request,+ materializer: materializer,+ cache: pcmMaterializations+ )+ } catch let error as CancellationError {+ throw error+ } catch let error as MeetingEpochMaterializationError where error.isSampleLimitExceeded {+ throw error+ } catch {+ result.failures[work.epoch.id] = "epochMaterializationFailed"+ continue+ }+ try Task.checkCancellation()+ do {+ let output = try await asr.transcribeWithTimings(materialized.samples)+ result.outputs.append(MeetingParakeetEpochOutput(+ epochID: work.epoch.id,+ text: output.result.text,+ words: output.words,+ sampleRate: materialized.sampleRate,+ sampleCount: materialized.samples.count,+ spanSamples: materialized.spanSamples+ ))+ } catch let error as CancellationError {+ throw error+ } catch {+ result.failures[work.epoch.id] = "asrFailed"+ continue+ }+ }+ return result+ }+ try Task.checkCancellation()++ return try self.assembleBundle(+ request: request,+ manifest: manifest,+ epochWork: epochWork,+ phaseA: phaseA,+ phaseB: phaseB+ )+ }++ private nonisolated static func materialize(+ work: EpochWork,+ manifest: MeetingAnalysisManifest,+ request: MeetingBackendRequest,+ materializer: any MeetingEpochAudioMaterializing,+ cache: MaterializationCache+ ) async throws -> MeetingMaterializedEpoch {+ let isPCMFirst = !work.spans.isEmpty && work.spans.allSatisfy {+ $0.chunk.analysisEncoding == .linearPCMFloat32CAFV1+ }+ if isPCMFirst, let cached = cache.value(for: work.epoch.id) {+ return cached+ }+ let materialized = try await materializer.materialize(+ epoch: work.epoch,+ track: work.track,+ manifest: manifest,+ sessionDirectory: request.sessionDirectory+ )+ try Task.checkCancellation()+ guard materialized.samples.count <= MeetingEpochAudioMaterializer.conservativeSampleLimit else {+ throw MeetingEpochMaterializationError.sampleLimitExceeded(+ spanID: work.spans.last?.id ?? "unknown",+ sampleCount: materialized.samples.count+ )+ }+ if isPCMFirst {+ try cache.insert(materialized, spanID: work.spans.last?.id ?? "unknown")+ }+ return materialized+ }++ // MARK: - Units, assignment and receipts++ /// Pure assembly of the final bundle: units from provider word timings clamped only at+ /// physical epoch bounds, slot assignment from overlapping epoch activity, and exactly one+ /// tiling receipt per admissible span. Failed epochs emit no units and mark every span failed;+ /// other epochs continue (plan §4).+ private nonisolated static func assembleBundle(+ request: MeetingBackendRequest,+ manifest: MeetingAnalysisManifest,+ epochWork: [EpochWork],+ phaseA: MeetingNemotronPhaseResult,+ phaseB: MeetingParakeetPhaseResult+ ) throws -> MeetingCanonicalResultBundle {+ let outputsByEpoch = Dictionary(+ phaseB.outputs.map { ($0.epochID, $0) },+ uniquingKeysWith: { first, _ in first }+ )+ let activityByEpoch = Dictionary(grouping: phaseA.activity, by: { $0.token.analysisEpochID })+ var failures = phaseA.failures+ failures.merge(phaseB.failures) { first, _ in first }++ var units: [MeetingFinalTextUnit] = []+ var receipts: [MeetingSpanCoverageReceipt] = []++ for work in epochWork {+ try Task.checkCancellation()+ if let reason = failures[work.epoch.id] {+ for span in work.spans {+ receipts.append(Self.receipt(for: span, status: .failed, reasonCode: reason))+ }+ continue+ }+ for span in work.spans {+ receipts.append(Self.receipt(for: span, status: .processed))+ }+ guard let output = outputsByEpoch[work.epoch.id] else { continue }+ let epochActivity = activityByEpoch[work.epoch.id] ?? []+ units.append(contentsOf: Self.units(+ for: output,+ work: work,+ activity: epochActivity,+ attemptID: request.attemptID+ ))+ }++ return MeetingCanonicalResultBundle(+ evidence: MeetingFinalTranscriptEvidence(+ backendID: .parakeetNemotron,+ attemptID: request.attemptID,+ units: units,+ speakerActivity: phaseA.activity.filter { failures[$0.token.analysisEpochID] == nil }+ ),+ coverageReceipts: receipts+ )+ }++ private nonisolated static func receipt(+ for span: MeetingAnalysisSpan,+ status: MeetingSpanCoverageStatus,+ reasonCode: String? = nil+ ) -> MeetingSpanCoverageReceipt {+ MeetingSpanCoverageReceipt(+ id: "receipt:\(span.id)",+ spanID: span.id,+ analysisStart: span.analysisInterval.start,+ analysisEnd: span.analysisInterval.end,+ status: status,+ reasonCode: reasonCode+ )+ }++ /// Word-timed units for one successful epoch. Provider times are seconds into the epoch's+ /// materialized buffer, so analysis time is the epoch start plus the provider time, clamped+ /// only to the epoch's physical bounds. Words with unusable timings are dropped, never+ /// repaired; text with no usable word timings at all becomes one epoch-covering utterance.+ private nonisolated static func units(+ for output: MeetingParakeetEpochOutput,+ work: EpochWork,+ activity: [MeetingBackendSpeakerActivity],+ attemptID: UUID+ ) -> [MeetingFinalTextUnit] {+ let epochStart = work.epoch.analysisInterval.start+ let physicalEnd = Self.analysisTime(+ forMaterializedSeconds: Double(output.sampleCount) / output.sampleRate,+ boundary: .end,+ sampleRate: output.sampleRate,+ sampleCount: output.sampleCount,+ spanSamples: output.spanSamples,+ spans: work.spans+ ) ?? epochStart+ guard physicalEnd > epochStart else { return [] }++ var wordUnits: [MeetingFinalTextUnit] = []+ let sortedWords = output.words.enumerated()+ .sorted { ($0.element.start, $0.offset) < ($1.element.start, $1.offset) }+ for (index, word) in sortedWords {+ let text = word.text.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !text.isEmpty,+ word.start.isFinite, word.end.isFinite, word.end > word.start+ else { continue }+ guard let start = Self.analysisTime(+ forMaterializedSeconds: word.start,+ boundary: .start,+ sampleRate: output.sampleRate,+ sampleCount: output.sampleCount,+ spanSamples: output.spanSamples,+ spans: work.spans+ ), let end = Self.analysisTime(+ forMaterializedSeconds: word.end,+ boundary: .end,+ sampleRate: output.sampleRate,+ sampleCount: output.sampleCount,+ spanSamples: output.spanSamples,+ spans: work.spans+ ) else { continue }+ guard end > start else { continue }+ guard let spanIDs = Self.intersectingSpanIDs(start: start, end: end, spans: work.spans)+ else { continue }+ wordUnits.append(MeetingFinalTextUnit(+ id: "unit:\(attemptID.uuidString):\(work.epoch.id):\(index)",+ trackID: work.track.id,+ analysisEpochID: work.epoch.id,+ precision: .word,+ text: text,+ analysisStart: start,+ analysisEnd: end,+ speaker: Self.assignment(start: start, end: end, activity: activity),+ analysisSpanIDs: spanIDs,+ confidence: nil+ ))+ }+ if !wordUnits.isEmpty { return wordUnits }++ let text = output.text.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !text.isEmpty else { return [] }+ let spanIDs = work.spans.map(\.id)+ guard !spanIDs.isEmpty else { return [] }+ return [MeetingFinalTextUnit(+ id: "unit:\(attemptID.uuidString):\(work.epoch.id):utterance",+ trackID: work.track.id,+ analysisEpochID: work.epoch.id,+ precision: .utterance,+ text: text,+ analysisStart: epochStart,+ analysisEnd: physicalEnd,+ speaker: Self.assignment(start: epochStart, end: physicalEnd, activity: activity),+ analysisSpanIDs: spanIDs,+ confidence: nil+ )]+ }++ /// The contiguous run of the epoch's spans intersecting the unit's analysis interval.+ /// Contiguity is structural: the epoch's spans tile its analysis interval with no holes.+ private nonisolated static func intersectingSpanIDs(+ start: TimeInterval,+ end: TimeInterval,+ spans: [MeetingAnalysisSpan]+ ) -> [String]? {+ let tolerance = MeetingAnalysisManifestSchema.mappingToleranceSeconds+ let ids = spans.filter {+ min($0.analysisInterval.end, end) - max($0.analysisInterval.start, start) > tolerance+ }.map(\.id)+ return ids.isEmpty ? nil : ids+ }++ private nonisolated enum MaterializedBoundary {+ case start+ case end+ }++ private nonisolated static func analysisTime(+ forMaterializedSeconds seconds: TimeInterval,+ boundary: MaterializedBoundary,+ materialized: MeetingMaterializedEpoch,+ spans: [MeetingAnalysisSpan]+ ) -> TimeInterval? {+ self.analysisTime(+ forMaterializedSeconds: seconds,+ boundary: boundary,+ sampleRate: materialized.sampleRate,+ sampleCount: materialized.samples.count,+ spanSamples: materialized.spanSamples,+ spans: spans+ )+ }++ /// Maps model/provider time through the actual resampled per-span sample ranges. This avoids+ /// accumulating a frame-rounding error at every source-file boundary and then pretending the+ /// concatenated buffer is an exact one-to-one copy of manifest analysis seconds.+ private nonisolated static func analysisTime(+ forMaterializedSeconds seconds: TimeInterval,+ boundary: MaterializedBoundary,+ sampleRate: Double,+ sampleCount: Int,+ spanSamples: [MeetingMaterializedSpanSamples],+ spans: [MeetingAnalysisSpan]+ ) -> TimeInterval? {+ guard seconds.isFinite, sampleRate.isFinite, sampleRate > 0, sampleCount > 0 else { return nil }+ let position = min(max(seconds * sampleRate, 0), Double(sampleCount))+ let probe: Double+ switch boundary {+ case .start:+ probe = min(position, Double(sampleCount).nextDown)+ case .end:+ probe = max(0, position == 0 ? 0 : position.nextDown)+ }+ let mappingsByID = Dictionary(+ spanSamples.map { ($0.spanID, $0.sampleRange) },+ uniquingKeysWith: { first, _ in first }+ )+ let spansByID = Dictionary(spans.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })+ guard let mapping = spanSamples.first(where: {+ Double($0.sampleRange.lowerBound) <= probe && probe < Double($0.sampleRange.upperBound)+ }), let range = mappingsByID[mapping.spanID], let span = spansByID[mapping.spanID], !range.isEmpty+ else { return nil }+ let fraction = min(max(+ (position - Double(range.lowerBound)) / Double(range.count),+ 0+ ), 1)+ return span.analysisInterval.start + fraction * span.analysisInterval.duration+ }++ /// One overlapping slot assigns; two or more are reported ambiguous; none is unassigned.+ private nonisolated static func assignment(+ start: TimeInterval,+ end: TimeInterval,+ activity: [MeetingBackendSpeakerActivity]+ ) -> MeetingBackendSpeakerAssignment {+ let tolerance = MeetingAnalysisManifestSchema.mappingToleranceSeconds+ var tokens = Set<MeetingBackendSpeakerToken>()+ for entry in activity where min(entry.end, end) - max(entry.start, start) > tolerance {+ tokens.insert(entry.token)+ }+ let sorted = tokens.sorted { $0.label < $1.label }+ switch sorted.count {+ case 0: return .unassigned+ case 1: return .assigned(sorted[0])+ default: return .ambiguous(sorted)+ }+ }+}diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingParakeetNemotronRuntime.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingParakeetNemotronRuntime.swiftnew file mode 100644index 00000000..3e6df5f0--- /dev/null+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingParakeetNemotronRuntime.swift@@ -0,0 +1,77 @@+import Foundation++// Stage E of `MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md`: the narrowly scoped runtime+// capability the host injects into the composite backend. The backend owns orchestration —+// epoch order, materialization, unit construction, receipts; the runtime owns exactly two model+// capabilities and nothing else. It cannot see the session store, arbitrary directories or global+// settings: the host binds it to the frozen request before the backend ever runs.+//+// Tests inject a fake implementation of `MeetingParakeetNemotronRunning`; nothing here reads the+// filesystem or touches CoreML by itself.++/// One speaker-active interval from a single Nemotron epoch run, in seconds from that epoch's+/// materialized audio start. Slot indices are Nemotron's own and are meaningful only inside the+/// epoch that produced them.+nonisolated struct MeetingNemotronSpeakerSegment: Equatable, Sendable {+ let slotIndex: Int+ let start: TimeInterval+ let end: TimeInterval+}++/// One fresh Nemotron diarizer state for exactly one analysis epoch.+nonisolated protocol MeetingNemotronDiarizerSession: Sendable {+ /// 16kHz mono epoch audio -> finalized speaker segments. Implementations may block on CoreML+ /// and are always awaited from a background context.+ func diarize(samples: [Float]) async throws -> [MeetingNemotronSpeakerSegment]+}++/// Hands out per-epoch diarizers. Every call must return entirely fresh streaming state; model+/// weights may be shared between instances. Slots never carry across epochs (plan §3).+nonisolated protocol MeetingNemotronDiarizerFactory: Sendable {+ func makeDiarizer(epoch: MeetingAnalysisEpochID) async throws -> any MeetingNemotronDiarizerSession+}++/// The attempt's prepared Parakeet ASR session, valid only inside the meeting preparation scope.+nonisolated protocol MeetingParakeetASRSession: Sendable {+ func transcribeWithTimings(+ _ samples: [Float]+ ) async throws -> (result: ASRTranscriptionResult, words: [ASRWordTiming])+}++nonisolated struct MeetingNemotronPhaseResult: Sendable {+ var activity: [MeetingBackendSpeakerActivity] = []+ var failures: [MeetingAnalysisEpochID: String] = [:]+}++nonisolated struct MeetingParakeetEpochOutput: Sendable {+ let epochID: MeetingAnalysisEpochID+ let text: String+ let words: [ASRWordTiming]+ let sampleRate: Double+ let sampleCount: Int+ let spanSamples: [MeetingMaterializedSpanSamples]+}++nonisolated struct MeetingParakeetPhaseResult: Sendable {+ var outputs: [MeetingParakeetEpochOutput] = []+ var failures: [MeetingAnalysisEpochID: String] = [:]+}++/// The composite backend's runtime, one per attempt. `withNemotronDiarization` is the only owner+/// of Nemotron residency: weights load before the factory is handed out and are released before+/// it returns. `withPreparedASR` wraps the attempt's single `ASRService.withPreparedMeetingASR`+/// scope. The two phases never overlap, so at most one local meeting model is resident at a time+/// (plan §6 D/E isolation). Concrete phase result types are deliberate: a generic scoped-closure+/// witness across the app/test module boundary is not ABI-stable under MainActor-by-default.+protocol MeetingParakeetNemotronRunning: Sendable {+ nonisolated func withNemotronDiarization(+ artifact: MeetingNemotronModelArtifact,+ _ body: @escaping @Sendable (any MeetingNemotronDiarizerFactory) async throws -> MeetingNemotronPhaseResult+ ) async throws -> MeetingNemotronPhaseResult++ nonisolated func withPreparedASR(+ attemptID: UUID,+ configuration: MeetingFinalProcessingConfiguration,+ body: @escaping @Sendable (any MeetingParakeetASRSession) async throws -> MeetingParakeetPhaseResult+ ) async throws -> MeetingParakeetPhaseResult+}diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingProductionParakeetNemotronRuntime.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingProductionParakeetNemotronRuntime.swiftnew file mode 100644index 00000000..e8d50514--- /dev/null+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingProductionParakeetNemotronRuntime.swift@@ -0,0 +1,201 @@+import Foundation++#if arch(arm64)+ import CoreML+ import FluidAudio+#endif++// Stage E of `MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md`: the production runtime behind+// `MeetingParakeetNemotronRunning`. It owns exactly two capabilities for one attempt:+//+// - Nemotron diarization: one shared weight load per attempt, one *fresh* `SortformerDiarizer`+// state per epoch (`initialize(models:)` re-creates streaming state), released before the ASR+// phase begins — the loaded-set sequence is none -> Nemotron -> drained -> Parakeet -> drained.+// - Parakeet ASR: one `ASRService.withPreparedMeetingASR` scope per attempt, with the heavy body+// bounced off the main actor so materialization and inference never block the UI.+//+// Parakeet does ASR only; Nemotron does diarization only. Neither capability sees anything beyond+// the request the host froze.++nonisolated enum MeetingParakeetNemotronRuntimeError: LocalizedError, Equatable {+ case unsupportedArchitecture++ var errorDescription: String? {+ switch self {+ case .unsupportedArchitecture:+ return "The local Parakeet + Nemotron meeting backend requires Apple Silicon."+ }+ }+}++#if arch(arm64)++ /// Shared-weight Nemotron factory: one `SortformerModels` load, fresh streaming state per+ /// epoch. Slots can never merge across epochs because each epoch's diarizer is a new instance.+ private final nonisolated class NemotronDiarizerFactory: MeetingNemotronDiarizerFactory, @unchecked Sendable {+ let config: SortformerConfig+ let models: SortformerModels+ private let lock = NSLock()+ private var created: [SortformerDiarizer] = []++ init(config: SortformerConfig, models: SortformerModels) {+ self.config = config+ self.models = models+ }++ func makeDiarizer(epoch _: MeetingAnalysisEpochID) async throws -> any MeetingNemotronDiarizerSession {+ try Task.checkCancellation()+ let diarizer = SortformerDiarizer(config: self.config)+ diarizer.initialize(models: self.models)+ self.lock.withLock { self.created.append(diarizer) }+ return NemotronDiarizerSession(diarizer: diarizer)+ }++ func cleanup() {+ let diarizers = self.lock.withLock {+ let pending = self.created+ self.created.removeAll()+ return pending+ }+ for diarizer in diarizers {+ diarizer.cleanup()+ }+ }+ }++ private nonisolated struct NemotronDiarizerSession: MeetingNemotronDiarizerSession, @unchecked Sendable {+ // The diarizer is used strictly serially: one epoch, one caller, one call.+ let diarizer: SortformerDiarizer++ func diarize(samples: [Float]) async throws -> [MeetingNemotronSpeakerSegment] {+ try Task.checkCancellation()+ let timeline = try self.diarizer.processComplete(+ samples,+ sourceSampleRate: nil,+ keepingEnrolledSpeakers: false,+ finalizeOnCompletion: true+ )+ try Task.checkCancellation()+ return timeline.speakers+ .sorted { $0.key < $1.key }+ .flatMap { index, speaker in+ speaker.finalizedSegments.compactMap { segment in+ guard segment.isFinalized, segment.endTime > segment.startTime else { return nil }+ return MeetingNemotronSpeakerSegment(+ slotIndex: index,+ start: TimeInterval(segment.startTime),+ end: TimeInterval(segment.endTime)+ )+ }+ }+ }+ }++ /// The prepared Parakeet session. Both references are only ever exercised through ASRService's+ /// own main-actor scope and meeting executor, never from the caller's context directly.+ private nonisolated struct PreparedParakeetASRSession: MeetingParakeetASRSession, @unchecked Sendable {+ let asrService: ASRService+ let provider: any TranscriptionProvider++ func transcribeWithTimings(+ _ samples: [Float]+ ) async throws -> (result: ASRTranscriptionResult, words: [ASRWordTiming]) {+ try await self.asrService.transcribeMeetingSamplesWithTimings(samples, provider: self.provider)+ }+ }++ final nonisolated class MeetingParakeetNemotronRuntime: MeetingParakeetNemotronRunning {+ private let asrServiceProvider: @MainActor () -> ASRService+ private let modelLocator: any MeetingNemotronModelLocating++ init(+ asrServiceProvider: @escaping @MainActor () -> ASRService,+ modelLocator: any MeetingNemotronModelLocating+ ) {+ self.asrServiceProvider = asrServiceProvider+ self.modelLocator = modelLocator+ }++ func withNemotronDiarization(+ artifact: MeetingNemotronModelArtifact,+ _ body: @escaping @Sendable (any MeetingNemotronDiarizerFactory) async throws -> MeetingNemotronPhaseResult+ ) async throws -> MeetingNemotronPhaseResult {+ // Recheck at open time: the artifact located at plan/readiness time is validated again+ // before CoreML touches it (plan §5).+ let artifact = try self.modelLocator.recheck(artifact)+ // Reference Nemotron streaming configuration (conversion script cadence, kept exact by+ // the FluidAudio factory; it validates instead of clamping).+ let config = try SortformerConfig.nemotron(+ spkcacheUpdatePeriod: 300,+ spkcacheSilFramesPerSpk: 3,+ predScoreThreshold: 0.25+ )+ let mlConfiguration = MLModelConfiguration()+ mlConfiguration.computeUnits = .cpuAndGPU+ let models = try await SortformerModels.load(+ config: config,+ mainModelPath: artifact.packageURL,+ configuration: mlConfiguration+ )+ let factory = NemotronDiarizerFactory(config: config, models: models)+ do {+ let result = try await body(factory)+ factory.cleanup()+ return result+ } catch {+ factory.cleanup()+ throw error+ }+ }++ func withPreparedASR(+ attemptID: UUID,+ configuration: MeetingFinalProcessingConfiguration,+ body: @escaping @Sendable (any MeetingParakeetASRSession) async throws -> MeetingParakeetPhaseResult+ ) async throws -> MeetingParakeetPhaseResult {+ let asrService = await self.asrServiceProvider()+ return try await asrService.withPreparedMeetingASR(+ attemptID: attemptID,+ configuration: configuration+ ) { provider in+ let session = PreparedParakeetASRSession(asrService: asrService, provider: provider)+ // ASRService runs this scope body on the main actor; the attempt's epoch loop+ // (materialization + model calls) must not live there. Cancellation of the scope+ // cancels this bridging await, which cancels the detached body.+ let work = Task.detached(priority: .userInitiated) { try await body(session) }+ return try await withTaskCancellationHandler {+ try await work.value+ } onCancel: {+ work.cancel()+ }+ }+ }+ }++#else++ /// Non-Apple-Silicon stub: the FluidAudio runtime stack is arm64-only in this app, so the+ /// capability refuses rather than partially working.+ final nonisolated class MeetingParakeetNemotronRuntime: MeetingParakeetNemotronRunning {+ init(+ asrServiceProvider _: @escaping @MainActor () -> ASRService,+ modelLocator _: any MeetingNemotronModelLocating+ ) {}++ func withNemotronDiarization(+ artifact _: MeetingNemotronModelArtifact,+ _: @escaping @Sendable (any MeetingNemotronDiarizerFactory) async throws -> MeetingNemotronPhaseResult+ ) async throws -> MeetingNemotronPhaseResult {+ throw MeetingParakeetNemotronRuntimeError.unsupportedArchitecture+ }++ func withPreparedASR(+ attemptID _: UUID,+ configuration _: MeetingFinalProcessingConfiguration,+ body _: @escaping @Sendable (any MeetingParakeetASRSession) async throws -> MeetingParakeetPhaseResult+ ) async throws -> MeetingParakeetPhaseResult {+ throw MeetingParakeetNemotronRuntimeError.unsupportedArchitecture+ }+ }++#endifdiff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingResultSidecar.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingResultSidecar.swiftnew file mode 100644index 00000000..5e47e47b--- /dev/null+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingResultSidecar.swift@@ -0,0 +1,465 @@+import Foundation++// Stage C of `MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md` (§4): the versioned, self-contained+// durable result record. It carries backend/attempt lineage, the full final text units, exactly+// one final disposition per unit, and one coverage receipt per admissible analysis span.+//+// Self-contained means values only: no stage-file paths, scratch references or session-directory+// URLs ever appear here, so a retained sidecar can never dangle after checkpoint cleanup.+//+// Schema version 3 (C2b2): text units carry analysis-time bounds plus exact analysis-span IDs,+// coverage receipts are per admissible manifest span, and the complete validated analysis manifest+// is embedded so those IDs and mappings remain self-contained after checkpoint cleanup. Every+// receipt status is a *backend* account of work — processed (including no speech), failed,+// skipped or provider-truncated; inadmissible audio is a manifest gap, not a receipt, because the+// backend never receives it. Text never implies coverage: a span full of words but missing its+// receipt fails reconciliation in the assembler, and a processed receipt with no words is simply+// a span with no speech.++nonisolated enum MeetingResultSidecarSchema {+ static let currentVersion = 3+}++/// The disposition set from plan §4. Raw values are stable contract tokens; decoding is+/// fail-closed through the raw-value enum, so an unknown disposition never becomes visible text.+nonisolated enum MeetingTextUnitFinalDisposition: String, Codable, CaseIterable {+ case emitted+ case ambiguousUnassigned+ case outsideActivity+ case echoSuppressed+ case inadmissible+ /// Timing or provenance quarantine: invalid bounds, or span references that do not provably+ /// cover the unit. The `reasonCode` carries the specific `MeetingUnitQuarantineReason`.+ case rejectedInvalidTiming+}++/// Stable reasons used by non-quarantine dispositions. Quarantine reasons use+/// `MeetingUnitQuarantineReason` directly so arbitrary strings can never authorize exclusion.+nonisolated enum MeetingUnitDispositionReason: String, Codable, CaseIterable {+ case ambiguousSpeaker+ case timingUncertain+ case outsideSpeakerActivity+ case crossTrackEcho+ case inadmissibleCaptureEra+}++nonisolated struct MeetingTextUnitDispositionRecord: Codable, Equatable {+ let unitID: String+ let disposition: MeetingTextUnitFinalDisposition+ /// Diagnostic token only (for example a quarantine or coverage reason); never load-bearing+ /// for inclusion.+ let reasonCode: String?++ init(unitID: String, disposition: MeetingTextUnitFinalDisposition, reasonCode: String? = nil) {+ self.unitID = unitID+ self.disposition = disposition+ self.reasonCode = reasonCode+ }+}++/// Plan §4 span status over one admissible analysis span: processed (including spans with no+/// speech), failed, skipped, or truncated by the provider. A receipt reports that the span was+/// accounted for; it cannot prove the ASR model recognized every spoken word inside it.+nonisolated enum MeetingSpanCoverageStatus: String, Codable, CaseIterable {+ case processed+ case failed+ case skipped+ case providerTruncated+}++/// A backend coverage receipt for one admissible manifest analysis span. Receipts for a span must+/// tile the span's analysis interval exactly once; the assembler reconciles them against the+/// manifest and throws on any missing, duplicate, unknown or out-of-bounds receipt.+nonisolated struct MeetingSpanCoverageReceipt: Codable, Equatable, Identifiable {+ let id: String+ /// The exact `MeetingAnalysisSpan.id` this receipt accounts for.+ let spanID: String+ /// Analysis-time sub-interval of the span, same domain as `MeetingFinalTextUnit` bounds.+ let analysisStart: TimeInterval+ let analysisEnd: TimeInterval+ let status: MeetingSpanCoverageStatus+ /// Diagnostic token only, for example a failure or truncation detail.+ let reasonCode: String?++ init(+ id: String,+ spanID: String,+ analysisStart: TimeInterval,+ analysisEnd: TimeInterval,+ status: MeetingSpanCoverageStatus,+ reasonCode: String? = nil+ ) {+ self.id = id+ self.spanID = spanID+ self.analysisStart = analysisStart+ self.analysisEnd = analysisEnd+ self.status = status+ self.reasonCode = reasonCode+ }+}++nonisolated struct MeetingResultSidecar: Equatable {+ let schemaVersion: Int+ let backendID: MeetingBackendID+ let backendVersion: String+ let attemptID: UUID+ /// The complete validated source→analysis→presentation mapping that gives every span ID in+ /// `units` and `coverageReceipts` durable meaning. It contains values only—no scratch paths—so+ /// the result remains self-contained after checkpoints and stage files are removed.+ let analysisManifest: MeetingAnalysisManifest+ let units: [MeetingFinalTextUnit]+ let dispositions: [MeetingTextUnitDispositionRecord]+ let coverageReceipts: [MeetingSpanCoverageReceipt]++ init(+ backendID: MeetingBackendID,+ backendVersion: String,+ attemptID: UUID,+ analysisManifest: MeetingAnalysisManifest,+ units: [MeetingFinalTextUnit],+ dispositions: [MeetingTextUnitDispositionRecord],+ coverageReceipts: [MeetingSpanCoverageReceipt]+ ) {+ self.schemaVersion = MeetingResultSidecarSchema.currentVersion+ self.backendID = backendID+ self.backendVersion = backendVersion+ self.attemptID = attemptID+ self.analysisManifest = analysisManifest+ self.units = units+ self.dispositions = dispositions+ self.coverageReceipts = coverageReceipts+ }+}++nonisolated extension MeetingResultSidecar: Codable {+ private enum CodingKeys: String, CodingKey {+ case schemaVersion+ case backendID+ case backendVersion+ case attemptID+ case analysisManifest+ case units+ case dispositions+ case coverageReceipts+ }++ init(from decoder: Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ let version = try container.decode(Int.self, forKey: .schemaVersion)+ guard version == MeetingResultSidecarSchema.currentVersion else {+ throw DecodingError.dataCorruptedError(+ forKey: .schemaVersion,+ in: container,+ debugDescription: "Unsupported meeting result sidecar schema version \(version)."+ )+ }+ try self.init(+ backendID: container.decode(MeetingBackendID.self, forKey: .backendID),+ backendVersion: container.decode(String.self, forKey: .backendVersion),+ attemptID: container.decode(UUID.self, forKey: .attemptID),+ analysisManifest: container.decode(MeetingAnalysisManifest.self, forKey: .analysisManifest),+ units: container.decode([MeetingFinalTextUnit].self, forKey: .units),+ dispositions: container.decode([MeetingTextUnitDispositionRecord].self, forKey: .dispositions),+ coverageReceipts: container.decode([MeetingSpanCoverageReceipt].self, forKey: .coverageReceipts)+ )+ }++ func encode(to encoder: Encoder) throws {+ var container = encoder.container(keyedBy: CodingKeys.self)+ try container.encode(self.schemaVersion, forKey: .schemaVersion)+ try container.encode(self.backendID, forKey: .backendID)+ try container.encode(self.backendVersion, forKey: .backendVersion)+ try container.encode(self.attemptID, forKey: .attemptID)+ try container.encode(self.analysisManifest, forKey: .analysisManifest)+ try container.encode(self.units, forKey: .units)+ try container.encode(self.dispositions, forKey: .dispositions)+ try container.encode(self.coverageReceipts, forKey: .coverageReceipts)+ }+}++nonisolated enum MeetingResultSidecarError: LocalizedError, Equatable {+ case emptyBackendID+ case emptyBackendVersion+ case emptyUnitID+ case manifestLineageMismatch+ case unitReferencesUnknownManifestSpan(unitID: String)+ case receiptReferencesUnknownManifestSpan(receiptID: String)+ case duplicateDisposition(unitID: String)+ case missingDisposition(unitID: String)+ case dispositionForUnknownUnit(unitID: String)+ /// An ambiguous-unassigned unit must either carry real ambiguity candidates or name why a+ /// resolved-looking unit is unassigned (for example `timingUncertain`): plan §4 reports+ /// ambiguity, it never invents it and never silently drops it.+ case ambiguousDispositionWithoutCandidates(unitID: String)+ case emittedDispositionWithAmbiguity(unitID: String)+ case duplicateUnitID(String)+ case emptyUnitText(unitID: String)+ case invalidAmbiguity(unitID: String)+ case speakerTokenOutOfScope(unitID: String)+ case emptySpeakerTokenLabel(unitID: String)+ case invalidAnalysisEpochOrdinal(unitID: String)+ case invalidAnalysisEpochGeneration(unitID: String)+ case invalidConfidence(unitID: String)+ case missingUnitAnalysisSpans(unitID: String)+ case duplicateUnitAnalysisSpanID(unitID: String)+ case invalidTimingNotRejected(unitID: String)+ case rejectedInvalidTimingForValidUnit(unitID: String)+ case invalidDispositionReason(unitID: String)+ case emptyCoverageReceiptID+ case duplicateCoverageReceiptID(String)+ case emptyCoverageReceiptSpanID(receiptID: String)+ case invalidCoverageInterval(receiptID: String)++ var errorDescription: String? {+ switch self {+ case .emptyBackendID:+ return "The result sidecar has no backend identifier."+ case .emptyBackendVersion:+ return "The result sidecar has no backend version."+ case .emptyUnitID:+ return "A result sidecar text unit has an empty identifier."+ case .manifestLineageMismatch:+ return "The result sidecar's analysis manifest does not match its backend or attempt lineage."+ case let .unitReferencesUnknownManifestSpan(unitID):+ return "Text unit \"\(unitID)\" references a span absent from the embedded analysis manifest."+ case let .receiptReferencesUnknownManifestSpan(receiptID):+ return "Coverage receipt \"\(receiptID)\" references a span absent from the embedded analysis manifest."+ case let .duplicateUnitID(id):+ return "Text unit identifier \"\(id)\" appears more than once in the sidecar."+ case let .emptyUnitText(unitID):+ return "Text unit \"\(unitID)\" has no text."+ case let .invalidAmbiguity(unitID):+ return "Text unit \"\(unitID)\" does not contain two distinct ambiguity candidates."+ case let .speakerTokenOutOfScope(unitID):+ return "Text unit \"\(unitID)\" carries a speaker token from another track or epoch."+ case let .emptySpeakerTokenLabel(unitID):+ return "Text unit \"\(unitID)\" carries an empty speaker-token label."+ case let .invalidAnalysisEpochOrdinal(unitID):+ return "Text unit \"\(unitID)\" uses a negative analysis epoch ordinal."+ case let .invalidAnalysisEpochGeneration(unitID):+ return "Text unit \"\(unitID)\" uses a negative analysis epoch generation."+ case let .invalidConfidence(unitID):+ return "Text unit \"\(unitID)\" has a confidence outside 0...1."+ case let .missingUnitAnalysisSpans(unitID):+ return "Text unit \"\(unitID)\" references no analysis span."+ case let .duplicateUnitAnalysisSpanID(unitID):+ return "Text unit \"\(unitID)\" repeats an analysis span identifier."+ case let .invalidTimingNotRejected(unitID):+ return "Text unit \"\(unitID)\" has invalid timing without the rejected-invalid-timing disposition."+ case let .rejectedInvalidTimingForValidUnit(unitID):+ return "Text unit \"\(unitID)\" has valid timing but is rejected without a quarantine reason."+ case let .invalidDispositionReason(unitID):+ return "Text unit \"\(unitID)\" has a missing or invalid final-disposition reason."+ case let .duplicateDisposition(unitID):+ return "Text unit \"\(unitID)\" has more than one final disposition."+ case let .missingDisposition(unitID):+ return "Text unit \"\(unitID)\" has no final disposition."+ case let .dispositionForUnknownUnit(unitID):+ return "A final disposition references unknown text unit \"\(unitID)\"."+ case let .ambiguousDispositionWithoutCandidates(unitID):+ return "Text unit \"\(unitID)\" is ambiguous-unassigned without candidates or a reason."+ case let .emittedDispositionWithAmbiguity(unitID):+ return "Text unit \"\(unitID)\" is emitted despite an ambiguous speaker assignment."+ case .emptyCoverageReceiptID:+ return "A coverage receipt has an empty identifier."+ case let .duplicateCoverageReceiptID(id):+ return "Coverage receipt identifier \"\(id)\" appears more than once."+ case let .emptyCoverageReceiptSpanID(receiptID):+ return "Coverage receipt \"\(receiptID)\" names no analysis span."+ case let .invalidCoverageInterval(receiptID):+ return "Coverage receipt \"\(receiptID)\" has non-finite or non-positive bounds."+ }+ }+}++nonisolated extension MeetingResultSidecar {+ /// Structural validation of the ledger invariants from plan §4: every recognized text unit+ /// has exactly one final disposition, dispositions reference only known units, a unit with+ /// unusable bounds is always quarantined (and a quarantined unit with sound bounds names the+ /// provenance reason), and ambiguity is reported, never silently resolved. Value checks that a+ /// quarantined unit cannot pass — timing, confidence — apply only to units the ledger claims+ /// were usable. What this cannot prove without the manifest is span coverage: reconciliation+ /// of units and receipts against the manifest's spans is the assembler's job.+ @discardableResult+ func validated() throws -> Self {+ guard !self.backendID.rawValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {+ throw MeetingResultSidecarError.emptyBackendID+ }+ guard !self.backendVersion.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {+ throw MeetingResultSidecarError.emptyBackendVersion+ }+ guard self.analysisManifest.backendID == self.backendID,+ self.analysisManifest.backendVersion == self.backendVersion,+ self.analysisManifest.attemptID == self.attemptID+ else {+ throw MeetingResultSidecarError.manifestLineageMismatch+ }+ let manifestSpansByID = Dictionary(+ self.analysisManifest.allSpans.map { ($0.id, $0) },+ uniquingKeysWith: { first, _ in first }+ )++ var seenUnitIDs = Set<String>()+ for unit in self.units {+ guard !unit.id.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {+ throw MeetingResultSidecarError.emptyUnitID+ }+ guard seenUnitIDs.insert(unit.id).inserted else {+ throw MeetingResultSidecarError.duplicateUnitID(unit.id)+ }+ guard !unit.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {+ throw MeetingResultSidecarError.emptyUnitText(unitID: unit.id)+ }+ guard !unit.analysisSpanIDs.isEmpty else {+ throw MeetingResultSidecarError.missingUnitAnalysisSpans(unitID: unit.id)+ }+ guard Set(unit.analysisSpanIDs).count == unit.analysisSpanIDs.count else {+ throw MeetingResultSidecarError.duplicateUnitAnalysisSpanID(unitID: unit.id)+ }+ guard unit.analysisSpanIDs.allSatisfy({ spanID in+ guard let span = manifestSpansByID[spanID] else { return false }+ return span.trackID == unit.trackID+ }) else {+ throw MeetingResultSidecarError.unitReferencesUnknownManifestSpan(unitID: unit.id)+ }+ guard unit.analysisEpochID.ordinal >= 0 else {+ throw MeetingResultSidecarError.invalidAnalysisEpochOrdinal(unitID: unit.id)+ }+ guard unit.analysisEpochID.generation >= 0 else {+ throw MeetingResultSidecarError.invalidAnalysisEpochGeneration(unitID: unit.id)+ }+ guard unit.speaker.tokens.allSatisfy({ $0.analysisEpochID == unit.analysisEpochID }) else {+ throw MeetingResultSidecarError.speakerTokenOutOfScope(unitID: unit.id)+ }+ guard unit.speaker.tokens.allSatisfy({+ !$0.label.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ }) else {+ throw MeetingResultSidecarError.emptySpeakerTokenLabel(unitID: unit.id)+ }+ if case let .ambiguous(candidates) = unit.speaker,+ Set(candidates).count < 2+ {+ throw MeetingResultSidecarError.invalidAmbiguity(unitID: unit.id)+ }+ }+ let unitsByID = Dictionary(self.units.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })++ var dispositionedIDs = Set<String>()+ for record in self.dispositions {+ guard dispositionedIDs.insert(record.unitID).inserted else {+ throw MeetingResultSidecarError.duplicateDisposition(unitID: record.unitID)+ }+ guard let unit = unitsByID[record.unitID] else {+ throw MeetingResultSidecarError.dispositionForUnknownUnit(unitID: record.unitID)+ }+ let isAmbiguous: Bool+ if case .ambiguous = unit.speaker { isAmbiguous = true } else { isAmbiguous = false }+ let hasValidTiming = MeetingEvidenceInterval.isValid(+ start: unit.analysisStart, end: unit.analysisEnd+ )+ let hasValidConfidence = unit.confidence.map {+ $0.isFinite && $0 >= 0 && $0 <= 1+ } ?? true+ if record.disposition == .rejectedInvalidTiming {+ guard let reasonCode = record.reasonCode,+ let reason = MeetingUnitQuarantineReason(rawValue: reasonCode)+ else {+ if hasValidTiming {+ throw MeetingResultSidecarError.rejectedInvalidTimingForValidUnit(+ unitID: record.unitID+ )+ }+ throw MeetingResultSidecarError.invalidDispositionReason(unitID: record.unitID)+ }+ let expectedLocallyVisibleReason: MeetingUnitQuarantineReason? = if !hasValidTiming {+ .invalidTiming+ } else if !hasValidConfidence {+ .invalidConfidence+ } else {+ nil+ }+ if let expectedLocallyVisibleReason {+ guard reason == expectedLocallyVisibleReason else {+ throw MeetingResultSidecarError.invalidDispositionReason(unitID: record.unitID)+ }+ } else {+ guard [+ MeetingUnitQuarantineReason.analysisEpochMismatch,+ .spansNotContiguousWithinEpoch,+ .spansDoNotCoverUnitInterval,+ .presentationMappingInvalid,+ ].contains(reason) else {+ throw MeetingResultSidecarError.invalidDispositionReason(unitID: record.unitID)+ }+ }+ } else {+ guard hasValidTiming else {+ throw MeetingResultSidecarError.invalidTimingNotRejected(unitID: record.unitID)+ }+ if !hasValidConfidence {+ throw MeetingResultSidecarError.invalidConfidence(unitID: unit.id)+ }+ }+ switch record.disposition {+ case .ambiguousUnassigned:+ let allowedReason: Bool+ if isAmbiguous {+ allowedReason = record.reasonCode == nil+ || record.reasonCode == MeetingUnitDispositionReason.ambiguousSpeaker.rawValue+ } else {+ allowedReason = record.reasonCode == MeetingUnitDispositionReason.timingUncertain.rawValue+ }+ guard allowedReason else {+ throw MeetingResultSidecarError.ambiguousDispositionWithoutCandidates(unitID: record.unitID)+ }+ case .emitted:+ guard !isAmbiguous else {+ throw MeetingResultSidecarError.emittedDispositionWithAmbiguity(unitID: record.unitID)+ }+ guard record.reasonCode == nil else {+ throw MeetingResultSidecarError.invalidDispositionReason(unitID: record.unitID)+ }+ case .outsideActivity:+ guard record.reasonCode == MeetingUnitDispositionReason.outsideSpeakerActivity.rawValue else {+ throw MeetingResultSidecarError.invalidDispositionReason(unitID: record.unitID)+ }+ case .echoSuppressed:+ guard record.reasonCode == MeetingUnitDispositionReason.crossTrackEcho.rawValue else {+ throw MeetingResultSidecarError.invalidDispositionReason(unitID: record.unitID)+ }+ case .inadmissible:+ guard record.reasonCode == MeetingUnitDispositionReason.inadmissibleCaptureEra.rawValue else {+ throw MeetingResultSidecarError.invalidDispositionReason(unitID: record.unitID)+ }+ case .rejectedInvalidTiming:+ break+ }+ }+ for unit in self.units where !dispositionedIDs.contains(unit.id) {+ throw MeetingResultSidecarError.missingDisposition(unitID: unit.id)+ }++ var seenReceiptIDs = Set<String>()+ for receipt in self.coverageReceipts {+ guard !receipt.id.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {+ throw MeetingResultSidecarError.emptyCoverageReceiptID+ }+ guard seenReceiptIDs.insert(receipt.id).inserted else {+ throw MeetingResultSidecarError.duplicateCoverageReceiptID(receipt.id)+ }+ guard !receipt.spanID.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {+ throw MeetingResultSidecarError.emptyCoverageReceiptSpanID(receiptID: receipt.id)+ }+ guard manifestSpansByID[receipt.spanID] != nil else {+ throw MeetingResultSidecarError.receiptReferencesUnknownManifestSpan(+ receiptID: receipt.id+ )+ }+ guard MeetingEvidenceInterval.isValid(start: receipt.analysisStart, end: receipt.analysisEnd) else {+ throw MeetingResultSidecarError.invalidCoverageInterval(receiptID: receipt.id)+ }+ }++ return self+ }+}diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingResultSidecarStore.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingResultSidecarStore.swiftnew file mode 100644index 00000000..68ee7912--- /dev/null+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingResultSidecarStore.swift@@ -0,0 +1,304 @@+import CryptoKit+import Darwin+import Foundation++// Stage C1 of `MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md` (§4): durable persistence for the+// self-contained result sidecar. Writes are atomic, permission-tightened and read-back-verified+// before a reference is returned; reads re-hash the file and re-check schema, attempt and+// backend identity against that reference. All paths are confined to the session directory —+// the store derives the only legal file name itself, so a reference can never point at scratch+// or checkpoint files, and retention follows the session directory like the plan requires.+//+// The returned reference is what a later Stage C step will embed in the session JSON; no+// `MeetingSession` field exists for it yet, so old sessions are unaffected by this slice.++/// Hash and location of a persisted sidecar. Verification re-hashes file content: a stored+/// digest alone never proves the file is still intact.+nonisolated enum MeetingResultSidecarReferenceSchema {+ static let currentVersion = 1+}++nonisolated struct MeetingResultSidecarReference: Codable, Equatable {+ let formatVersion: Int+ let fileName: String+ let sha256: String+ let byteCount: Int+}++nonisolated enum MeetingResultSidecarStoreError: LocalizedError, Equatable {+ case unsupportedReferenceFormatVersion(found: Int)+ case unexpectedFileName(expected: String, actual: String)+ case pathEscapesSessionDirectory+ case checksumMismatch+ case byteCountMismatch(expected: Int, actual: Int)+ case attemptMismatch(expected: UUID, actual: UUID)+ case backendMismatch(expected: MeetingBackendID, actual: MeetingBackendID)+ case conflictingExistingSidecar(attemptID: UUID)+ case durabilitySyncFailed++ var errorDescription: String? {+ switch self {+ case let .unsupportedReferenceFormatVersion(found):+ return "Meeting result sidecar reference has unsupported format version \(found)."+ case let .unexpectedFileName(expected, actual):+ return "Meeting result sidecar reference names \"\(actual)\"; expected \"\(expected)\"."+ case .pathEscapesSessionDirectory:+ return "Meeting result sidecar path escapes its session directory."+ case .checksumMismatch:+ return "Meeting result sidecar content does not match its recorded SHA-256."+ case let .byteCountMismatch(expected, actual):+ return "Meeting result sidecar is \(actual) bytes; expected \(expected)."+ case let .attemptMismatch(expected, actual):+ return "Meeting result sidecar carries attempt \(actual); expected \(expected)."+ case let .backendMismatch(expected, actual):+ return "Meeting result sidecar carries backend \"\(actual)\"; expected \"\(expected)\"."+ case let .conflictingExistingSidecar(attemptID):+ return "Meeting attempt \(attemptID) already has a different immutable result sidecar."+ case .durabilitySyncFailed:+ return "The meeting result sidecar could not be synchronized to durable storage."+ }+ }+}++nonisolated struct MeetingResultSidecarStore {+ let sessionDirectory: URL++ /// The only file name this store will ever write or read for an attempt.+ static func fileName(for attemptID: UUID) -> String {+ "result-\(attemptID.uuidString).sidecar.json"+ }++ func sidecarURL(for attemptID: UUID) throws -> URL {+ try self.containedURL(fileName: Self.fileName(for: attemptID))+ }++ /// Validates, encodes, atomically writes, then reads back and re-verifies checksum, schema,+ /// attempt and backend before returning the reference a session may durably record.+ @discardableResult+ func write(_ sidecar: MeetingResultSidecar) throws -> MeetingResultSidecarReference {+ try sidecar.validated()++ let encoder = Self.makeEncoder()+ let data = try encoder.encode(sidecar)++ let manager = FileManager.default+ let root = self.sessionDirectory.standardizedFileURL.resolvingSymlinksInPath()+ if !manager.fileExists(atPath: root.path) {+ try manager.createDirectory(+ at: root,+ withIntermediateDirectories: true,+ attributes: [.posixPermissions: NSNumber(value: 0o700)]+ )+ }+ // Tighten existing directories too. A temporary transcript may use the process umask for+ // a few instructions before its own chmod, so the parent must already exclude other users.+ try manager.setAttributes(+ [.posixPermissions: NSNumber(value: 0o700)],+ ofItemAtPath: root.path+ )++ let url = try self.sidecarURL(for: sidecar.attemptID)+ if manager.fileExists(atPath: url.path) {+ return try self.referenceForExistingSidecar(+ sidecar,+ expectedData: data,+ at: url+ )+ }++ let temporaryURL = try self.containedURL(+ fileName: ".\(Self.fileName(for: sidecar.attemptID)).\(UUID().uuidString).tmp"+ )+ defer { try? manager.removeItem(at: temporaryURL) }+ // The unique temporary path prevents partial content from acquiring the stable name.+ // Its enclosing directory is already 0700; chmod it to 0600 before the same-directory+ // move publishes it. A failure before that move leaves no stable transcript file.+ try data.write(to: temporaryURL, options: .withoutOverwriting)+ try manager.setAttributes(+ [.posixPermissions: NSNumber(value: 0o600)],+ ofItemAtPath: temporaryURL.path+ )+ try Self.synchronizeFile(at: temporaryURL)+ do {+ try manager.moveItem(at: temporaryURL, to: url)+ } catch {+ // A racing writer may have won after the existence check. Same bytes are an+ // idempotent join; different bytes may never replace an already-referenceable result.+ let currentURL = try self.sidecarURL(for: sidecar.attemptID)+ if manager.fileExists(atPath: currentURL.path) {+ return try self.referenceForExistingSidecar(+ sidecar,+ expectedData: data,+ at: currentURL+ )+ }+ throw error+ }+ try Self.synchronizeDirectory(at: root)+ return try self.verifiedReference(for: sidecar, expectedData: data, at: url)+ }++ /// Reads and fully re-verifies a sidecar against its recorded reference and the expected+ /// attempt lineage. Anything that fails verification throws; there is no best-effort read.+ func read(+ expectedAttemptID: UUID,+ expectedBackendID: MeetingBackendID,+ reference: MeetingResultSidecarReference+ ) throws -> MeetingResultSidecar {+ guard reference.formatVersion == MeetingResultSidecarReferenceSchema.currentVersion else {+ throw MeetingResultSidecarStoreError.unsupportedReferenceFormatVersion(+ found: reference.formatVersion+ )+ }+ let expectedFileName = Self.fileName(for: expectedAttemptID)+ guard reference.fileName == expectedFileName else {+ throw MeetingResultSidecarStoreError.unexpectedFileName(+ expected: expectedFileName, actual: reference.fileName+ )+ }++ let url = try self.containedURL(fileName: reference.fileName)+ let data = try Data(contentsOf: url)+ guard data.count == reference.byteCount else {+ throw MeetingResultSidecarStoreError.byteCountMismatch(+ expected: reference.byteCount, actual: data.count+ )+ }+ guard Self.sha256Hex(data) == reference.sha256 else {+ throw MeetingResultSidecarStoreError.checksumMismatch+ }++ let sidecar = try Self.makeDecoder().decode(MeetingResultSidecar.self, from: data)+ try sidecar.validated()+ guard sidecar.attemptID == expectedAttemptID else {+ throw MeetingResultSidecarStoreError.attemptMismatch(+ expected: expectedAttemptID, actual: sidecar.attemptID+ )+ }+ guard sidecar.backendID == expectedBackendID else {+ throw MeetingResultSidecarStoreError.backendMismatch(+ expected: expectedBackendID, actual: sidecar.backendID+ )+ }+ return sidecar+ }++ /// Canonicalize symlinks, then require the result itself and its parent to stay at the exact+ /// canonical session-root path. This is intentionally stronger than the legacy chunk-store+ /// prefix check and rejects both internal and escaping pre-existing result-file symlinks.+ private func containedURL(fileName: String) throws -> URL {+ let root = self.sessionDirectory.standardizedFileURL.resolvingSymlinksInPath()+ let unresolvedURL = root.appendingPathComponent(fileName, isDirectory: false).standardizedFileURL+ let resolvedURL = unresolvedURL.resolvingSymlinksInPath()+ guard !fileName.isEmpty,+ unresolvedURL.deletingLastPathComponent() == root,+ resolvedURL.deletingLastPathComponent() == root,+ resolvedURL == unresolvedURL+ else {+ throw MeetingResultSidecarStoreError.pathEscapesSessionDirectory+ }+ return unresolvedURL+ }++ private func referenceForExistingSidecar(+ _ sidecar: MeetingResultSidecar,+ expectedData: Data,+ at url: URL+ ) throws -> MeetingResultSidecarReference {+ let existingData = try Data(contentsOf: url)+ guard existingData == expectedData else {+ throw MeetingResultSidecarStoreError.conflictingExistingSidecar(+ attemptID: sidecar.attemptID+ )+ }+ try FileManager.default.setAttributes(+ [.posixPermissions: NSNumber(value: 0o600)],+ ofItemAtPath: url.path+ )+ try Self.synchronizeFile(at: url)+ try Self.synchronizeDirectory(+ at: self.sessionDirectory.standardizedFileURL.resolvingSymlinksInPath()+ )+ return try self.verifiedReference(for: sidecar, expectedData: expectedData, at: url)+ }++ private func verifiedReference(+ for sidecar: MeetingResultSidecar,+ expectedData: Data,+ at url: URL+ ) throws -> MeetingResultSidecarReference {+ let readBack = try Data(contentsOf: url)+ guard readBack == expectedData else {+ throw MeetingResultSidecarStoreError.checksumMismatch+ }+ let decoded = try Self.makeDecoder().decode(MeetingResultSidecar.self, from: readBack)+ try decoded.validated()+ guard decoded.attemptID == sidecar.attemptID else {+ throw MeetingResultSidecarStoreError.attemptMismatch(+ expected: sidecar.attemptID,+ actual: decoded.attemptID+ )+ }+ guard decoded.backendID == sidecar.backendID else {+ throw MeetingResultSidecarStoreError.backendMismatch(+ expected: sidecar.backendID,+ actual: decoded.backendID+ )+ }+ return MeetingResultSidecarReference(+ formatVersion: MeetingResultSidecarReferenceSchema.currentVersion,+ fileName: Self.fileName(for: sidecar.attemptID),+ sha256: Self.sha256Hex(readBack),+ byteCount: readBack.count+ )+ }++ private static func sha256Hex(_ data: Data) -> String {+ SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()+ }++ /// Quarantined evidence must remain durably ledgerable even when the defect itself is NaN or+ /// infinity. Stable string tokens preserve that raw value without turning it into a valid+ /// timestamp; sidecar validation still requires the rejected-invalid-timing disposition.+ private static func makeEncoder() -> JSONEncoder {+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]+ encoder.nonConformingFloatEncodingStrategy = .convertToString(+ positiveInfinity: "+Infinity",+ negativeInfinity: "-Infinity",+ nan: "NaN"+ )+ return encoder+ }++ private static func makeDecoder() -> JSONDecoder {+ let decoder = JSONDecoder()+ decoder.nonConformingFloatDecodingStrategy = .convertFromString(+ positiveInfinity: "+Infinity",+ negativeInfinity: "-Infinity",+ nan: "NaN"+ )+ return decoder+ }++ private static func synchronizeFile(at url: URL) throws {+ let handle = try FileHandle(forWritingTo: url)+ defer { try? handle.close() }+ do {+ try handle.synchronize()+ } catch {+ throw MeetingResultSidecarStoreError.durabilitySyncFailed+ }+ }++ private static func synchronizeDirectory(at url: URL) throws {+ let descriptor = Darwin.open(url.path, O_RDONLY)+ guard descriptor >= 0 else {+ throw MeetingResultSidecarStoreError.durabilitySyncFailed+ }+ defer { _ = Darwin.close(descriptor) }+ guard Darwin.fsync(descriptor) == 0 else {+ throw MeetingResultSidecarStoreError.durabilitySyncFailed+ }+ }+}diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingTranscriptAssembler.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingTranscriptAssembler.swiftnew file mode 100644index 00000000..f330dffd--- /dev/null+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingTranscriptAssembler.swift@@ -0,0 +1,632 @@+import CryptoKit+import Foundation++nonisolated enum MeetingSpeakerActivityCoverage {+ static func isOutside(+ _ unit: MeetingFinalTextUnit,+ activityByEpoch: [MeetingAnalysisEpochID: [MeetingBackendSpeakerActivity]],+ tolerance: TimeInterval = MeetingAnalysisManifestSchema.mappingToleranceSeconds+ ) -> Bool {+ guard let activity = activityByEpoch[unit.analysisEpochID], !activity.isEmpty else {+ return false+ }+ return !activity.contains {+ min($0.end, unit.analysisEnd) - max($0.start, unit.analysisStart) > tolerance+ }+ }+}++// Stage C2b1 of `MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md` (§4) and+// `MEETING_TRANSCRIPTION_BACKEND_ARCHITECTURE_PLAN.md` §4.6: the pure assembler every backend+// shares. It reads a frozen plan, a validated analysis manifest, final evidence, per-span+// coverage receipts and per-unit echo verdicts, and produces product speakers, transcript+// segments, the durable result sidecar, skipped chunks and product coverage gaps.+//+// It does no I/O, runs no aligner or diarizer, and never identifies You. Every input text unit+// leaves with exactly one disposition, in the plan's precedence order: timing/provenance+// quarantine, inadmissible capture era, echo suppression, outside speaker activity,+// timing/overlap ambiguity, emitted. Every admissible manifest span must be tiled exactly once by+// receipts — a missing, duplicate, unknown or out-of-bounds receipt is a hard typed error, and+// text never implies coverage.++/// Real, per-unit cross-track echo evidence, supplied by the pipeline's existing signal/text+/// analysis. A verdict is a measured fact about one microphone unit, never a guess: in an online+/// call a microphone unit without one fails assembly.+nonisolated enum MeetingUnitEchoVerdict: Equatable {+ /// Evidence found this microphone unit is not a copy of remote (application-track) audio.+ case notEcho+ /// Evidence found this unit duplicates an application-track unit. The application copy is+ /// retained; the microphone copy is ledger-only.+ case echoSuppressed(duplicateOfUnitID: String?)+}++/// Why a presentation-time interval has no transcript coverage.+nonisolated enum MeetingAssemblyCoverageGapReason: String, Codable, CaseIterable {+ case inadmissibleCaptureEra+ case missingOrUnreadableAudio+ case processingFailed+ case skipped+ case providerTruncated+ /// An indivisible unit touched an excluded interval, so its whole text was excluded; this+ /// gap marks the unit's admissible portion as incomplete coverage (plan §4).+ case excludedUnitIncompleteCoverage+}++/// A product-visible coverage gap, in seconds elapsed since the meeting presentation origin (the+/// same meeting-relative domain used by `MeetingTranscriptSegment.start/end`).+nonisolated struct MeetingAssemblyCoverageGap: Equatable {+ let trackID: MeetingAudioTrackID+ let start: TimeInterval+ let end: TimeInterval+ let reason: MeetingAssemblyCoverageGapReason+}++/// Everything the assembler needs, already validated or frozen upstream. `plan` is the frozen+/// backend plan; the assembler re-validates the manifest against it and the evidence against both.+nonisolated struct MeetingAssemblyInput {+ let plan: MeetingBackendPlan+ let manifest: MeetingAnalysisManifest+ let evidence: MeetingFinalTranscriptEvidence+ let coverageReceipts: [MeetingSpanCoverageReceipt]+ /// Echo verdicts keyed by unit ID. Required for every online-call microphone unit that+ /// survives quarantine and admission; never consulted for in-room or application audio.+ let echoVerdicts: [String: MeetingUnitEchoVerdict]++ init(+ plan: MeetingBackendPlan,+ manifest: MeetingAnalysisManifest,+ evidence: MeetingFinalTranscriptEvidence,+ coverageReceipts: [MeetingSpanCoverageReceipt],+ echoVerdicts: [String: MeetingUnitEchoVerdict] = [:]+ ) {+ self.plan = plan+ self.manifest = manifest+ self.evidence = evidence+ self.coverageReceipts = coverageReceipts+ self.echoVerdicts = echoVerdicts+ }+}++nonisolated struct MeetingAssemblyResult: Equatable {+ /// Deterministic product speakers, minted only here, scoped by attempt + track + epoch ++ /// token label. The same label on another track or epoch is a different speaker, always.+ let speakers: [MeetingSessionSpeaker]+ /// Emitted and ambiguous-admitted units, once each, in presentation order. Ambiguous text is+ /// one segment with a nil speaker and `.ambiguous` overlap; excluded units never appear.+ let segments: [MeetingTranscriptSegment]+ /// The complete disposition and coverage ledger, already passing `validated()`.+ let sidecar: MeetingResultSidecar+ /// Planned chunks at least one of whose spans the backend reported as skipped.+ let skippedChunks: [MeetingAnalysisChunkIdentity]+ let coverageGaps: [MeetingAssemblyCoverageGap]+ /// False when any gap exists, so truncation or missing work can never look like a complete+ /// transcript.+ let isComplete: Bool+}++nonisolated enum MeetingAssemblyError: LocalizedError, Equatable {+ case missingCoverageReceipt(spanID: String)+ case duplicateCoverageReceiptID(String)+ case overlappingCoverageReceipts(spanID: String)+ case unknownCoverageReceiptSpan(spanID: String)+ case coverageReceiptOutOfBounds(receiptID: String)+ case invalidCoverageReceiptInterval(receiptID: String)+ case missingEchoVerdict(unitID: String)+ case echoVerdictForUnknownUnit(unitID: String)+ case echoDuplicateTargetUnknown(unitID: String, duplicateID: String)+ case echoDuplicateTargetNotApplicationAudio(unitID: String, duplicateID: String)+ case echoDuplicateTargetNotVisible(unitID: String, duplicateID: String)+ case textContradictsCoverage(+ unitID: String,+ receiptID: String,+ status: MeetingSpanCoverageStatus+ )++ var errorDescription: String? {+ switch self {+ case let .missingCoverageReceipt(spanID):+ return "Admissible analysis span \"\(spanID)\" has no complete coverage receipt."+ case let .duplicateCoverageReceiptID(id):+ return "Coverage receipt identifier \"\(id)\" appears more than once."+ case let .overlappingCoverageReceipts(spanID):+ return "Analysis span \"\(spanID)\" has overlapping coverage receipts."+ case let .unknownCoverageReceiptSpan(spanID):+ return "A coverage receipt references unknown analysis span \"\(spanID)\"."+ case let .coverageReceiptOutOfBounds(receiptID):+ return "Coverage receipt \"\(receiptID)\" lies outside its analysis span's bounds."+ case let .invalidCoverageReceiptInterval(receiptID):+ return "Coverage receipt \"\(receiptID)\" has non-finite or non-positive bounds."+ case let .missingEchoVerdict(unitID):+ return "Online microphone text unit \"\(unitID)\" has no cross-track echo verdict."+ case let .echoVerdictForUnknownUnit(unitID):+ return "An echo verdict references unknown text unit \"\(unitID)\"."+ case let .echoDuplicateTargetUnknown(unitID, duplicateID):+ return "Echo verdict for \"\(unitID)\" names unknown duplicate target \"\(duplicateID)\"."+ case let .echoDuplicateTargetNotApplicationAudio(unitID, duplicateID):+ return "Echo verdict for \"\(unitID)\" names \"\(duplicateID)\", which is not application audio."+ case let .echoDuplicateTargetNotVisible(unitID, duplicateID):+ return "Echo verdict for \"\(unitID)\" names application unit \"\(duplicateID)\", which is not publishable."+ case let .textContradictsCoverage(unitID, receiptID, status):+ return "Text unit \"\(unitID)\" overlaps receipt \"\(receiptID)\" marked \(status.rawValue)."+ }+ }+}++nonisolated struct MeetingTranscriptAssembler {+ private let tolerance = MeetingAnalysisManifestSchema.mappingToleranceSeconds++ init() {}++ func assemble(_ input: MeetingAssemblyInput) throws -> MeetingAssemblyResult {+ try Task.checkCancellation()+ let manifest = try input.manifest.validated(against: input.plan)+ let evidence = try input.evidence.validatedForAssembly(against: input.plan, manifest: manifest)+ let unitIDs = Set(evidence.units.map(\.id))+ let unitsByID = Dictionary(+ evidence.units.map { ($0.id, $0) },+ uniquingKeysWith: { first, _ in first }+ )+ for unitID in input.echoVerdicts.keys where !unitIDs.contains(unitID) {+ throw MeetingAssemblyError.echoVerdictForUnknownUnit(unitID: unitID)+ }++ let receipts = try self.reconcileCoverage(manifest: manifest, receipts: input.coverageReceipts)+ let spansByID = Dictionary(+ manifest.allSpans.map { ($0.id, $0) },+ uniquingKeysWith: { first, _ in first }+ )+ let receiptsBySpanID = Dictionary(grouping: receipts, by: \.spanID)+ let activityByEpoch = Dictionary(grouping: evidence.speakerActivity) { $0.token.analysisEpochID }+ let inadmissibleGapsByTrack = Dictionary(grouping: manifest.allGaps.filter {+ $0.reason == .inadmissibleCaptureEra && $0.recordedInterval != nil+ }) { $0.trackID }++ var dispositions: [MeetingTextUnitDispositionRecord] = []+ var emitted: [(unit: MeetingFinalTextUnit, presentation: MeetingAnalysisInterval)] = []+ var remainderGaps: [MeetingAssemblyCoverageGap] = []++ let canonicalUnits = evidence.units.sorted { $0.id < $1.id }+ for unit in canonicalUnits {+ try Task.checkCancellation()+ if let quarantine = unit.quarantineReason(in: manifest) {+ // No interval arithmetic on quarantined bounds (plan §4).+ dispositions.append(MeetingTextUnitDispositionRecord(+ unitID: unit.id,+ disposition: .rejectedInvalidTiming,+ reasonCode: quarantine.rawValue+ ))+ continue+ }+ let spans = unit.analysisSpanIDs.compactMap { spansByID[$0] }+ let presentation = MeetingAnalysisInterval(+ start: spans[0].presentationMapping.presentationTime(forAnalysisTime: unit.analysisStart),+ end: spans[spans.count - 1].presentationMapping+ .presentationTime(forAnalysisTime: unit.analysisEnd)+ )+ let recorded = MeetingAnalysisInterval(+ start: spans[0].recordedInterval.start+ + (unit.analysisStart - spans[0].analysisInterval.start),+ end: spans[spans.count - 1].recordedInterval.start+ + (unit.analysisEnd - spans[spans.count - 1].analysisInterval.start)+ )+ try self.validateCoverageStatus(+ for: unit,+ spans: spans,+ receiptsBySpanID: receiptsBySpanID+ )++ if self.intersectsInadmissibleGap(+ recorded, gaps: inadmissibleGapsByTrack[unit.trackID] ?? []+ ) {+ dispositions.append(MeetingTextUnitDispositionRecord(+ unitID: unit.id,+ disposition: .inadmissible,+ reasonCode: MeetingUnitDispositionReason.inadmissibleCaptureEra.rawValue+ ))+ remainderGaps.append(contentsOf: self.admissibleRemainderGaps(+ of: recorded,+ excluding: inadmissibleGapsByTrack[unit.trackID] ?? [],+ trackID: unit.trackID+ ))+ continue+ }++ if manifest.captureMode == .onlineCall,+ manifest.track(unit.trackID)?.kind == .microphone+ {+ guard let verdict = input.echoVerdicts[unit.id] else {+ throw MeetingAssemblyError.missingEchoVerdict(unitID: unit.id)+ }+ if case let .echoSuppressed(duplicateOfUnitID) = verdict {+ if let duplicateOfUnitID {+ guard let duplicate = unitsByID[duplicateOfUnitID] else {+ throw MeetingAssemblyError.echoDuplicateTargetUnknown(+ unitID: unit.id,+ duplicateID: duplicateOfUnitID+ )+ }+ guard manifest.track(duplicate.trackID)?.kind == .applicationAudio else {+ throw MeetingAssemblyError.echoDuplicateTargetNotApplicationAudio(+ unitID: unit.id,+ duplicateID: duplicateOfUnitID+ )+ }+ guard duplicate.quarantineReason(in: manifest) == nil,+ !MeetingSpeakerActivityCoverage.isOutside(+ duplicate,+ activityByEpoch: activityByEpoch+ )+ else {+ throw MeetingAssemblyError.echoDuplicateTargetNotVisible(+ unitID: unit.id,+ duplicateID: duplicateOfUnitID+ )+ }+ }+ dispositions.append(MeetingTextUnitDispositionRecord(+ unitID: unit.id,+ disposition: .echoSuppressed,+ reasonCode: MeetingUnitDispositionReason.crossTrackEcho.rawValue+ ))+ continue+ }+ }++ if MeetingSpeakerActivityCoverage.isOutside(unit, activityByEpoch: activityByEpoch) {+ dispositions.append(MeetingTextUnitDispositionRecord(+ unitID: unit.id,+ disposition: .outsideActivity,+ reasonCode: MeetingUnitDispositionReason.outsideSpeakerActivity.rawValue+ ))+ continue+ }++ if case .ambiguous = unit.speaker {+ dispositions.append(MeetingTextUnitDispositionRecord(+ unitID: unit.id,+ disposition: .ambiguousUnassigned,+ reasonCode: MeetingUnitDispositionReason.ambiguousSpeaker.rawValue+ ))+ emitted.append((unit, presentation))+ } else if spans.contains(where: { $0.timing.certainty == .timingUncertain }) {+ dispositions.append(MeetingTextUnitDispositionRecord(+ unitID: unit.id,+ disposition: .ambiguousUnassigned,+ reasonCode: MeetingUnitDispositionReason.timingUncertain.rawValue+ ))+ emitted.append((unit, presentation))+ } else {+ dispositions.append(MeetingTextUnitDispositionRecord(+ unitID: unit.id,+ disposition: .emitted+ ))+ emitted.append((unit, presentation))+ }+ }++ let dispositionByUnitID = Dictionary(+ dispositions.map { ($0.unitID, $0.disposition) },+ uniquingKeysWith: { first, _ in first }+ )+ // Ambiguous-admitted units produce a segment but mint no speaker: their candidates are+ // reported, never resolved into a product identity.+ let speakers = self.makeSpeakers(+ attemptID: manifest.attemptID,+ manifest: manifest,+ emitted: emitted.filter { dispositionByUnitID[$0.unit.id] == .emitted }+ )+ let speakerIDsByToken = Dictionary(+ speakers.map { ($0.token, $0.speaker.id) },+ uniquingKeysWith: { first, _ in first }+ )+ let segments = emitted+ .map { unit, presentation -> MeetingTranscriptSegment in+ let disposition = dispositionByUnitID[unit.id]+ let speakerID: SessionSpeakerID? = {+ guard disposition == .emitted,+ case let .assigned(token) = unit.speaker+ else { return nil }+ return speakerIDsByToken[token]+ }()+ return MeetingTranscriptSegment(+ id: Self.stableUUID("segment:\(manifest.attemptID.uuidString):\(unit.id)"),+ start: Self.mediaTime(presentation.start),+ end: Self.mediaTime(max(presentation.start, presentation.end)),+ sourceTrackID: unit.trackID,+ speakerID: speakerID,+ text: unit.text,+ revision: 0,+ status: .final,+ overlap: disposition == .ambiguousUnassigned ? .ambiguous : .none,+ completeness: .complete,+ isLikelyEcho: nil+ )+ }+ .sorted {+ ($0.start, $0.end, $0.sourceTrackID.uuidString, $0.id.uuidString)+ < ($1.start, $1.end, $1.sourceTrackID.uuidString, $1.id.uuidString)+ }++ let receiptGaps = self.receiptCoverageGaps(+ manifest: manifest, spansByID: spansByID, receipts: receipts+ )+ let manifestGaps = self.manifestCoverageGaps(manifest: manifest)+ let coverageGaps = (receiptGaps + manifestGaps + remainderGaps).sorted {+ ($0.trackID.uuidString, $0.start, $0.end, $0.reason.rawValue)+ < ($1.trackID.uuidString, $1.start, $1.end, $1.reason.rawValue)+ }+ let skippedChunks = self.skippedChunks(spansByID: spansByID, receipts: receipts)++ let sidecar = try MeetingResultSidecar(+ backendID: evidence.backendID,+ backendVersion: input.plan.backendVersion,+ attemptID: evidence.attemptID,+ analysisManifest: manifest,+ units: canonicalUnits,+ dispositions: dispositions,+ coverageReceipts: receipts+ ).validated()++ let hasQuarantinedUnit = dispositions.contains {+ $0.disposition == .rejectedInvalidTiming+ }+ return MeetingAssemblyResult(+ speakers: speakers.map(\.speaker),+ segments: segments,+ sidecar: sidecar,+ skippedChunks: skippedChunks,+ coverageGaps: coverageGaps,+ isComplete: coverageGaps.isEmpty+ && manifest.allGaps.isEmpty+ && !hasQuarantinedUnit+ )+ }++ // MARK: - Coverage reconciliation++ private func validateCoverageStatus(+ for unit: MeetingFinalTextUnit,+ spans: [MeetingAnalysisSpan],+ receiptsBySpanID: [String: [MeetingSpanCoverageReceipt]]+ ) throws {+ for span in spans {+ let coveredStart = max(unit.analysisStart, span.analysisInterval.start)+ let coveredEnd = min(unit.analysisEnd, span.analysisInterval.end)+ guard coveredEnd - coveredStart > self.tolerance else { continue }+ let overlappingReceipts = (receiptsBySpanID[span.id] ?? []).filter {+ min($0.analysisEnd, coveredEnd) - max($0.analysisStart, coveredStart)+ > self.tolerance+ }+ if let contradiction = overlappingReceipts.first(where: { $0.status != .processed }) {+ throw MeetingAssemblyError.textContradictsCoverage(+ unitID: unit.id,+ receiptID: contradiction.id,+ status: contradiction.status+ )+ }+ }+ }++ /// Receipts must tile every admissible span's analysis interval exactly once. The manifest's+ /// own gaps need no receipt — the backend never saw that audio — and a span full of recognized+ /// text but no receipt fails here: text never implies coverage.+ private func reconcileCoverage(+ manifest: MeetingAnalysisManifest,+ receipts: [MeetingSpanCoverageReceipt]+ ) throws -> [MeetingSpanCoverageReceipt] {+ var seenIDs = Set<String>()+ for receipt in receipts {+ try Task.checkCancellation()+ guard seenIDs.insert(receipt.id).inserted else {+ throw MeetingAssemblyError.duplicateCoverageReceiptID(receipt.id)+ }+ }+ let spansByID = Dictionary(+ manifest.allSpans.map { ($0.id, $0) },+ uniquingKeysWith: { first, _ in first }+ )+ var receiptsBySpan: [String: [MeetingSpanCoverageReceipt]] = [:]+ for receipt in receipts {+ guard MeetingEvidenceInterval.isValid(start: receipt.analysisStart, end: receipt.analysisEnd) else {+ throw MeetingAssemblyError.invalidCoverageReceiptInterval(receiptID: receipt.id)+ }+ guard let span = spansByID[receipt.spanID] else {+ throw MeetingAssemblyError.unknownCoverageReceiptSpan(spanID: receipt.spanID)+ }+ guard span.analysisInterval.start - self.tolerance <= receipt.analysisStart,+ receipt.analysisEnd <= span.analysisInterval.end + self.tolerance+ else {+ throw MeetingAssemblyError.coverageReceiptOutOfBounds(receiptID: receipt.id)+ }+ receiptsBySpan[receipt.spanID, default: []].append(receipt)+ }+ for span in manifest.allSpans {+ try Task.checkCancellation()+ guard let spanReceipts = receiptsBySpan[span.id] else {+ throw MeetingAssemblyError.missingCoverageReceipt(spanID: span.id)+ }+ var cursor = span.analysisInterval.start+ for receipt in spanReceipts.sorted(by: { $0.analysisStart < $1.analysisStart }) {+ if receipt.analysisStart < cursor - self.tolerance {+ throw MeetingAssemblyError.overlappingCoverageReceipts(spanID: span.id)+ }+ guard receipt.analysisStart <= cursor + self.tolerance else {+ throw MeetingAssemblyError.missingCoverageReceipt(spanID: span.id)+ }+ cursor = max(cursor, receipt.analysisEnd)+ }+ guard cursor >= span.analysisInterval.end - self.tolerance else {+ throw MeetingAssemblyError.missingCoverageReceipt(spanID: span.id)+ }+ }+ return receipts.sorted {+ ($0.spanID, $0.analysisStart, $0.analysisEnd, $0.status.rawValue, $0.id)+ < ($1.spanID, $1.analysisStart, $1.analysisEnd, $1.status.rawValue, $1.id)+ }+ }++ // MARK: - Admission++ private func intersectsInadmissibleGap(+ _ presentation: MeetingAnalysisInterval,+ gaps: [MeetingAnalysisGap]+ ) -> Bool {+ gaps.contains { gap in+ guard let recorded = gap.recordedInterval else { return false }+ return min(recorded.end, presentation.end) - max(recorded.start, presentation.start)+ > self.tolerance+ }+ }++ /// The admissible portion of a whole-unit exclusion, recorded as incomplete coverage.+ private func admissibleRemainderGaps(+ of presentation: MeetingAnalysisInterval,+ excluding gaps: [MeetingAnalysisGap],+ trackID: MeetingAudioTrackID+ ) -> [MeetingAssemblyCoverageGap] {+ let excluded = gaps.compactMap(\.recordedInterval)+ .filter {+ min($0.end, presentation.end) - max($0.start, presentation.start) > self.tolerance+ }+ .sorted { $0.start < $1.start }+ var pieces: [MeetingAnalysisInterval] = [presentation]+ for interval in excluded {+ pieces = pieces.flatMap { piece -> [MeetingAnalysisInterval] in+ let overlapStart = max(piece.start, interval.start)+ let overlapEnd = min(piece.end, interval.end)+ guard overlapEnd - overlapStart > self.tolerance else { return [piece] }+ var remainder: [MeetingAnalysisInterval] = []+ if overlapStart - piece.start > self.tolerance {+ remainder.append(MeetingAnalysisInterval(start: piece.start, end: overlapStart))+ }+ if piece.end - overlapEnd > self.tolerance {+ remainder.append(MeetingAnalysisInterval(start: overlapEnd, end: piece.end))+ }+ return remainder+ }+ }+ return pieces.map {+ MeetingAssemblyCoverageGap(+ trackID: trackID,+ start: $0.start,+ end: $0.end,+ reason: .excludedUnitIncompleteCoverage+ )+ }+ }++ // MARK: - Gaps and skipped chunks++ private func receiptCoverageGaps(+ manifest: MeetingAnalysisManifest,+ spansByID: [String: MeetingAnalysisSpan],+ receipts: [MeetingSpanCoverageReceipt]+ ) -> [MeetingAssemblyCoverageGap] {+ receipts.compactMap { receipt in+ let reason: MeetingAssemblyCoverageGapReason+ switch receipt.status {+ case .processed: return nil+ case .failed: reason = .processingFailed+ case .skipped: reason = .skipped+ case .providerTruncated: reason = .providerTruncated+ }+ guard let span = spansByID[receipt.spanID] else { return nil }+ let transform = span.presentationMapping+ return MeetingAssemblyCoverageGap(+ trackID: span.trackID,+ start: transform.presentationTime(forAnalysisTime: receipt.analysisStart),+ end: transform.presentationTime(forAnalysisTime: receipt.analysisEnd),+ reason: reason+ )+ }+ }++ /// Manifest gaps are facts the builder established; presentation uses the recorded interval+ /// directly because an unreadable or inadmissible piece has no de-drift correction to apply.+ private func manifestCoverageGaps(+ manifest: MeetingAnalysisManifest+ ) -> [MeetingAssemblyCoverageGap] {+ manifest.allGaps.compactMap { gap in+ guard let recorded = gap.recordedInterval else { return nil }+ return MeetingAssemblyCoverageGap(+ trackID: gap.trackID,+ start: recorded.start,+ end: recorded.end,+ reason: gap.reason == .inadmissibleCaptureEra+ ? .inadmissibleCaptureEra+ : .missingOrUnreadableAudio+ )+ }+ }++ private func skippedChunks(+ spansByID: [String: MeetingAnalysisSpan],+ receipts: [MeetingSpanCoverageReceipt]+ ) -> [MeetingAnalysisChunkIdentity] {+ var seen = Set<MeetingAnalysisChunkIdentity>()+ var skipped: [MeetingAnalysisChunkIdentity] = []+ for receipt in receipts where receipt.status == .skipped {+ guard let span = spansByID[receipt.spanID], seen.insert(span.chunk).inserted else { continue }+ skipped.append(span.chunk)+ }+ return skipped.sorted {+ ($0.trackID.uuidString, $0.sequence, $0.chunkID.uuidString)+ < ($1.trackID.uuidString, $1.sequence, $1.chunkID.uuidString)+ }+ }++ // MARK: - Product speakers and segments++ /// Only the assembler mints product speaker IDs. The key is attempt + track + epoch + token+ /// label, so the same backend label on another track or in another epoch never merges, and a+ /// recomputed epoch never inherits an old speaker. You is never identified here.+ private func makeSpeakers(+ attemptID: UUID,+ manifest: MeetingAnalysisManifest,+ emitted: [(unit: MeetingFinalTextUnit, presentation: MeetingAnalysisInterval)]+ ) -> [(token: MeetingBackendSpeakerToken, speaker: MeetingSessionSpeaker)] {+ var tokens: [MeetingBackendSpeakerToken] = []+ var seen = Set<MeetingBackendSpeakerToken>()+ for (unit, _) in emitted {+ guard case let .assigned(token) = unit.speaker, seen.insert(token).inserted else { continue }+ tokens.append(token)+ }+ tokens.sort {+ ($0.analysisEpochID.trackID.uuidString, $0.analysisEpochID.ordinal, $0.label)+ < ($1.analysisEpochID.trackID.uuidString, $1.analysisEpochID.ordinal, $1.label)+ }+ return tokens.enumerated().map { index, token in+ let normalizedLabel = token.label.precomposedStringWithCanonicalMapping+ let scopedClusterID = "\(token.analysisEpochID):\(normalizedLabel)"+ return (+ token,+ MeetingSessionSpeaker(+ id: Self.stableUUID(+ "speaker:\(attemptID.uuidString):\(scopedClusterID)"+ ),+ displayName: "Speaker \(index + 1)",+ diarizationClusterID: scopedClusterID,+ trackKind: manifest.track(token.analysisEpochID.trackID)?.kind ?? .microphone,+ isLocalUser: false,+ identityCandidates: []+ )+ )+ }+ }++ private 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]+ ))+ }+}diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingTranscriptionBackend.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingTranscriptionBackend.swiftnew file mode 100644index 00000000..f4d27b25--- /dev/null+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingTranscriptionBackend.swift@@ -0,0 +1,315 @@+import Foundation++// Stage A of `MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md`: the contract that sits *beneath*+// the existing pipeline. `MeetingProcessingControlling` and `TranscriptionProvider` are unchanged;+// `MeetingProcessingPipeline` keeps owning selection, checkpoints and final publication and now+// dispatches the transcription work itself through one of these backends.+//+// Stage A deliberately ships only two dispatch shapes: the legacy compatibility wrapper (which+// returns today's `MeetingProcessingResult` unchanged) and validation of the canonical final+// evidence introduced here for Stage C. No unified provider adapter and no assembler exist yet.++/// Stable, string-backed backend identity. Compiled factories only — never a dynamic plugin name.+nonisolated struct MeetingBackendID: RawRepresentable, Hashable, Codable, Sendable, CustomStringConvertible {+ let rawValue: String++ /// Compatibility/rollback backend for sessions that explicitly select the pre-composite path.+ static let legacyCompatibility = MeetingBackendID(rawValue: "legacy-compatibility-v1")++ /// Local Parakeet TDT v2 ASR + Nemotron-3 diarization composite.+ static let parakeetNemotron = MeetingBackendID(rawValue: "local-parakeet-tdt-v2-nemotron-3-v1")++ /// Single source of truth for new meeting-processing attempts. Keep explicit stored selections+ /// untouched; this value applies only when no preference has been recorded.+ static let productionDefault: MeetingBackendID = .parakeetNemotron++ var description: String {+ self.rawValue+ }+}++nonisolated enum MeetingBackendExecutionLocality: String, Codable, Sendable {+ case local+ case hosted+}++/// Which output shape a backend's `execute` returns. This is the dispatch discriminator: the+/// pipeline builds and hands over an analysis manifest only to canonical backends, and accepts+/// only the declared outcome shape back (plan §6, milestones A vs C2b2).+nonisolated enum MeetingBackendResultContract: String, Codable, Sendable {+ /// The unchanged in-pipeline workflow returns today's `MeetingProcessingResult` directly.+ /// It receives no manifest and does no sidecar work.+ case legacyResult+ /// Canonical backends receive the product-owned, validated `MeetingAnalysisManifest` before+ /// execute and return `MeetingCanonicalResultBundle`: final evidence plus per-span receipts.+ case canonicalEvidence+}++/// Identity/version, platform reach, execution locality, supported final precision, track topology+/// and the limits a caller must not assume away.+nonisolated struct MeetingBackendDescriptor: Equatable, Sendable {+ let id: MeetingBackendID+ let version: String+ let execution: MeetingBackendExecutionLocality+ let supportedLanguageCodes: Set<String>+ let supportedTrackKinds: Set<MeetingAudioTrackKind>+ /// Which final text-unit precisions this backend is allowed to emit. A backend that only+ /// produces utterances must not be read as producing words: no synthetic word times exist.+ let supportedFinalPrecisions: Set<MeetingTextUnitPrecision>+ /// The declared output contract. The pipeline enforces it in both directions: a legacy+ /// backend never receives a manifest, and an outcome case other than the declared one is a+ /// typed failure, never a silent reinterpretation.+ let resultContract: MeetingBackendResultContract+ /// Human-readable, non-exhaustive statements of what this backend cannot guarantee.+ let knownLimits: [String]+ /// The backend's real analysis/resample rate, when it has one. The pipeline records it on the+ /// analysis manifest; `nil` leaves sample-rate conversion explicitly unknown (plan §3).+ let analysisSampleRate: Double?++ init(+ id: MeetingBackendID,+ version: String,+ execution: MeetingBackendExecutionLocality,+ supportedLanguageCodes: Set<String>,+ supportedTrackKinds: Set<MeetingAudioTrackKind>,+ supportedFinalPrecisions: Set<MeetingTextUnitPrecision>,+ resultContract: MeetingBackendResultContract,+ knownLimits: [String],+ analysisSampleRate: Double? = nil+ ) {+ self.id = id+ self.version = version+ self.execution = execution+ self.supportedLanguageCodes = supportedLanguageCodes+ self.supportedTrackKinds = supportedTrackKinds+ self.supportedFinalPrecisions = supportedFinalPrecisions+ self.resultContract = resultContract+ self.knownLimits = knownLimits+ self.analysisSampleRate = analysisSampleRate+ }+}++/// Immutable per-attempt input. No global settings reads and no arbitrary session-directory access+/// are granted beyond the recorded session's own directory.+///+/// `Equatable` is load-bearing, not a convenience: the host binds its injected capabilities to one+/// exact request value and compares the whole thing — session snapshot and configuration included —+/// rather than spot-checking a directory or a session identifier.+nonisolated struct MeetingBackendRequest: Equatable, Sendable {+ let attemptID: UUID+ let session: MeetingSession+ let sessionDirectory: URL+ let configuration: MeetingFinalProcessingConfiguration+}++/// Immutable result of `plan(_:)`, produced before any model work. It also carries the scope that+/// returned evidence is validated against: a backend may not report text for a track or chunk that+/// was never planned.+nonisolated struct MeetingBackendPlan: Sendable {+ let backendID: MeetingBackendID+ let backendVersion: String+ let attemptID: UUID+ let request: MeetingBackendRequest+ let trackKindsByID: [MeetingAudioTrackID: MeetingAudioTrackKind]+ let chunkIDsByTrackID: [MeetingAudioTrackID: Set<MeetingAudioChunkID>]+ let declaredFinalPrecisions: Set<MeetingTextUnitPrecision>+ let resultContract: MeetingBackendResultContract++ /// Plans over the session's finalized chunks only; provisional chunks are not planned work.+ init(request: MeetingBackendRequest, descriptor: MeetingBackendDescriptor) {+ let plannedTracks = request.session.audioTracks.filter {+ descriptor.supportedTrackKinds.contains($0.kind)+ }+ self.backendID = descriptor.id+ self.backendVersion = descriptor.version+ self.attemptID = request.attemptID+ self.request = request+ self.trackKindsByID = Dictionary(+ plannedTracks.map { ($0.id, $0.kind) },+ uniquingKeysWith: { first, _ in first }+ )+ self.chunkIDsByTrackID = Dictionary(+ plannedTracks.map { track in+ (track.id, Set(track.chunks.filter { $0.finalizationState == .finalized }.map(\.id)))+ },+ uniquingKeysWith: { first, _ in first }+ )+ self.declaredFinalPrecisions = descriptor.supportedFinalPrecisions+ self.resultContract = descriptor.resultContract+ }++ /// `plan(_:)` is backend code, so what it returns is re-checked against the request the host+ /// froze and the descriptor the host selected — before `execute` runs and before any audio is+ /// read. Identity fields must match exactly; scope may narrow but never widen, so a plan can+ /// never name a track or chunk the caller did not hand in.+ func agreementDefect(+ with request: MeetingBackendRequest,+ descriptor: MeetingBackendDescriptor+ ) -> MeetingBackendPlanDefect? {+ guard self.backendID == descriptor.id else { return .backendIdentity }+ guard self.backendVersion == descriptor.version else { return .backendVersion }+ guard self.attemptID == request.attemptID else { return .attemptIdentity }+ guard self.request == request else { return .request }+ guard self.declaredFinalPrecisions.isSubset(of: descriptor.supportedFinalPrecisions) else {+ return .precisionScope+ }+ guard self.resultContract == descriptor.resultContract else { return .resultContract }++ let sessionTracks = Dictionary(+ request.session.audioTracks.map { ($0.id, $0) },+ uniquingKeysWith: { first, _ in first }+ )+ for (trackID, kind) in self.trackKindsByID {+ guard let track = sessionTracks[trackID],+ track.kind == kind,+ descriptor.supportedTrackKinds.contains(kind)+ else { return .trackScope }+ }+ guard Set(self.chunkIDsByTrackID.keys) == Set(self.trackKindsByID.keys) else {+ return .chunkScope+ }+ for (trackID, chunkIDs) in self.chunkIDsByTrackID {+ guard let track = sessionTracks[trackID] else { return .chunkScope }+ // Provisional chunks are not planned work, so they are not a legal source either.+ let finalized = Set(track.chunks.filter { $0.finalizationState == .finalized }.map(\.id))+ guard chunkIDs.isSubset(of: finalized) else { return .chunkScope }+ }+ return nil+ }+}++/// Which part of a returned plan contradicted the host's request or the selected descriptor.+nonisolated enum MeetingBackendPlanDefect: String, Equatable, Sendable {+ case backendIdentity+ case backendVersion+ case attemptIdentity+ case request+ case trackScope+ case chunkScope+ case precisionScope+ case resultContract+}++/// What a canonical (`canonicalEvidence` contract) backend hands back: the final text evidence+/// plus the per-span coverage receipts the assembler reconciles against the analysis manifest.+/// Receipts are backend self-reports; they are not authoritative until the assembler tiles them+/// against the manifest (plan §4).+nonisolated struct MeetingCanonicalResultBundle: Equatable, Sendable {+ let evidence: MeetingFinalTranscriptEvidence+ let coverageReceipts: [MeetingSpanCoverageReceipt]+}++/// What a backend hands back.+///+/// `legacyCompatibility` is the explicit temporary Stage A path called out by the plan (§6, "A may+/// wrap the existing final times as an explicit temporary compatibility path"). It is not evidence:+/// it is today's already-assembled product result passing through unchanged. `canonicalEvidence`+/// is the canonical contract: the pipeline validates and assembles the bundle through the+/// product-owned `MeetingTranscriptAssembler` and persists its result sidecar before returning.+nonisolated enum MeetingBackendOutcome: Sendable {+ case legacyCompatibility(MeetingProcessingResult)+ case canonicalEvidence(MeetingCanonicalResultBundle)+}++/// Executes the legacy in-pipeline workflow. Owned by `MeetingProcessingPipeline` and injected, so+/// the legacy adapter can run the unchanged algorithm without reimplementing any part of it.+typealias MeetingLegacyBackendExecutor = @MainActor (+ MeetingBackendRequest,+ @escaping @MainActor (MeetingProcessingStage) -> Void+) async throws -> MeetingProcessingResult++/// Creates the composite backend's runtime for one attempt. Owned by `MeetingProcessingPipeline`+/// and bound to the exact frozen request — like the legacy executor, honouring a different request+/// would transcribe audio this call never authorized.+typealias MeetingParakeetNemotronRuntimeFactory = @MainActor (+ MeetingBackendRequest+) throws -> any MeetingParakeetNemotronRunning++/// Host-provided capabilities a registered factory may use. Stage A grants the legacy executor;+/// Stage E adds the composite runtime factory. The default factory throws: a context built without+/// it (tests of the legacy path) must never silently hand out a runtime.+@MainActor+struct MeetingBackendHostContext {+ let legacyExecutor: MeetingLegacyBackendExecutor+ let parakeetNemotronRuntimeFactory: MeetingParakeetNemotronRuntimeFactory++ init(+ legacyExecutor: @escaping MeetingLegacyBackendExecutor,+ parakeetNemotronRuntimeFactory: @escaping MeetingParakeetNemotronRuntimeFactory = { _ in+ throw MeetingBackendError.runtimeUnavailable(backend: .parakeetNemotron)+ }+ ) {+ self.legacyExecutor = legacyExecutor+ self.parakeetNemotronRuntimeFactory = parakeetNemotronRuntimeFactory+ }+}++@MainActor+protocol MeetingTranscriptionBackend: AnyObject {+ var descriptor: MeetingBackendDescriptor { get }++ /// Validates compatibility and freezes an immutable plan. Runs before any model load.+ func plan(_ request: MeetingBackendRequest) throws -> MeetingBackendPlan++ /// `manifest` is the product-owned, already validated analysis manifest built from the frozen+ /// plan, present exactly when the descriptor declares the canonical evidence contract. Legacy+ /// backends always receive `nil` and must run exactly as before.+ func execute(+ plan: MeetingBackendPlan,+ manifest: MeetingAnalysisManifest?,+ progress: @escaping @MainActor (MeetingProcessingStage) -> Void+ ) async throws -> MeetingBackendOutcome+}++nonisolated enum MeetingBackendError: LocalizedError, Equatable, Sendable {+ case unknownBackend(MeetingBackendID)+ /// A registered factory produced a backend whose descriptor claims a different identity than the+ /// one that was requested. Selection would otherwise be a lie: the caller asked for one backend+ /// and a different one would run, carrying its own limits and precisions.+ case backendIdentityMismatch(requested: MeetingBackendID, produced: MeetingBackendID)+ /// A backend invoked the host's legacy executor with a request other than the one the host froze+ /// for this call. Honouring it would transcribe audio this call never authorized.+ case legacyExecutorRequestMismatch(backend: MeetingBackendID)+ /// A backend asked the host for a runtime against a request other than the one the host froze+ /// for this call.+ case hostCapabilityRequestMismatch(backend: MeetingBackendID)+ /// The host context carries no runtime factory for this backend (a test context built only for+ /// the legacy path), so the capability cannot be handed out at all.+ case runtimeUnavailable(backend: MeetingBackendID)+ /// A backend's own plan contradicts the request or the descriptor it was selected under.+ case planDisagreesWithRequest(backend: MeetingBackendID, defect: MeetingBackendPlanDefect)+ case unsupportedLanguage(backend: MeetingBackendID, languageCode: String)+ case unsupportedTrackTopology(backend: MeetingBackendID)+ /// A backend's outcome case contradicts the result contract its descriptor declared — for+ /// example a legacy-contract backend returning canonical evidence. The pipeline never+ /// reinterprets one shape as the other.+ case outcomeContractMismatch(backend: MeetingBackendID, declared: MeetingBackendResultContract)++ var errorDescription: String? {+ switch self {+ case let .unknownBackend(id):+ return "Meeting transcription backend \"\(id.rawValue)\" is not available."+ case let .backendIdentityMismatch(requested, produced):+ return "Meeting backend \"\(requested.rawValue)\" resolved to a backend identifying "+ + "itself as \"\(produced.rawValue)\"."+ case let .legacyExecutorRequestMismatch(backend):+ return "Meeting backend \"\(backend.rawValue)\" asked to process a different recording "+ + "than the one this attempt was given."+ case let .hostCapabilityRequestMismatch(backend):+ return "Meeting backend \"\(backend.rawValue)\" asked for a runtime against a different "+ + "recording than the one this attempt was given."+ case let .runtimeUnavailable(backend):+ return "Meeting backend \"\(backend.rawValue)\" has no runtime available in this context."+ case let .planDisagreesWithRequest(backend, defect):+ return "Meeting backend \"\(backend.rawValue)\" returned a plan that disagrees with "+ + "this attempt (\(defect.rawValue))."+ case let .unsupportedLanguage(backend, languageCode):+ return "Meeting backend \"\(backend.rawValue)\" cannot transcribe language \(languageCode)."+ case let .unsupportedTrackTopology(backend):+ return "Meeting backend \"\(backend.rawValue)\" cannot process this session's audio tracks."+ case let .outcomeContractMismatch(backend, declared):+ return "Meeting backend \"\(backend.rawValue)\" returned an outcome that does not match "+ + "its declared \(declared.rawValue) result contract."+ }+ }+}diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingTranscriptionBackendRegistry.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingTranscriptionBackendRegistry.swiftnew file mode 100644index 00000000..e4a26249--- /dev/null+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingTranscriptionBackendRegistry.swift@@ -0,0 +1,68 @@+import Foundation++/// Registry of compiled backend factories — not a dynamic plugin system. Injectable so tests (and+/// later, development-only composite backends) can register their own without touching the default+/// production wiring.+///+/// Unknown or unregistered identifiers are rejected explicitly. Nothing ever silently substitutes+/// a different backend.+@MainActor+final class MeetingTranscriptionBackendRegistry {+ typealias Factory = @MainActor (MeetingBackendHostContext) -> any MeetingTranscriptionBackend++ private var factories: [MeetingBackendID: Factory] = [:]+ let defaultBackendID: MeetingBackendID++ init(defaultBackendID: MeetingBackendID = .productionDefault) {+ self.defaultBackendID = defaultBackendID+ }++ /// Production registry: the local Parakeet + Nemotron composite plus the explicit legacy+ /// rollback backend. Its default shares the same source of truth as persisted settings.+ static func makeDefault() -> MeetingTranscriptionBackendRegistry {+ let registry = MeetingTranscriptionBackendRegistry()+ registry.register(.legacyCompatibility) { context in+ MeetingLegacyCompatibilityBackend(legacyExecutor: context.legacyExecutor)+ }+ registry.register(.parakeetNemotron) { context in+ MeetingParakeetNemotronBackend(runtimeFactory: context.parakeetNemotronRuntimeFactory)+ }+ return registry+ }++ func register(_ id: MeetingBackendID, factory: @escaping Factory) {+ self.factories[id] = factory+ }++ var registeredBackendIDs: Set<MeetingBackendID> {+ Set(self.factories.keys)+ }++ func contains(_ id: MeetingBackendID) -> Bool {+ self.factories[id] != nil+ }++ /// Throws `MeetingBackendError.unknownBackend` for an identifier that was never registered —+ /// including a default that a caller configured but did not register.+ ///+ /// The requested identifier is also bound to the produced descriptor's identifier: a factory+ /// registered under one key may not hand back a backend that calls itself something else. Every+ /// downstream check — evidence's `backendMismatch`, the descriptor's declared precisions and+ /// limits — is keyed off that identity, so a mismatch here would make selection unverifiable.+ func makeBackend(+ id: MeetingBackendID,+ context: MeetingBackendHostContext+ ) throws -> any MeetingTranscriptionBackend {+ guard let factory = self.factories[id] else {+ throw MeetingBackendError.unknownBackend(id)+ }+ let backend = factory(context)+ guard backend.descriptor.id == id else {+ throw MeetingBackendError.backendIdentityMismatch(+ requested: id,+ produced: backend.descriptor.id+ )+ }+ return backend+ }+}diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingUnitEchoVerdictProvider.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingUnitEchoVerdictProvider.swiftnew file mode 100644index 00000000..66b988a7--- /dev/null+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingUnitEchoVerdictProvider.swift@@ -0,0 +1,148 @@+import Foundation++// Stage C2b2 of `MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md` (§4): the product-owned source of+// per-unit cross-track echo verdicts for canonical assembly. A verdict is a measured fact about+// one microphone text unit, never a guess — in an online call a microphone unit without one fails+// assembly, so this provider is the fail-closed gate between backend evidence and admission.+//+// The pipeline owns when verdicts are requested; the provider owns how they are measured. The+// composite backend's real signal/text scoring lands with Stage E; until then the default+// provider deliberately supplies no verdicts, which makes online microphone text unassemblable+// rather than silently admitted.++nonisolated protocol MeetingUnitEchoVerdictProviding: Sendable {+ /// Verdicts keyed by unit ID. Only online-call microphone units that survive quarantine and+ /// admission require one; application-track and in-room units are never consulted.+ func echoVerdicts(+ for evidence: MeetingFinalTranscriptEvidence,+ manifest: MeetingAnalysisManifest,+ plan: MeetingBackendPlan+ ) async throws -> [String: MeetingUnitEchoVerdict]+}++/// Returns no verdicts. The assembler then refuses every admissible online-call microphone unit+/// with `missingEchoVerdict`, so canonical online output can never be published on absent echo+/// evidence.+nonisolated struct MeetingFailClosedEchoVerdictProvider: MeetingUnitEchoVerdictProviding {+ init() {}++ func echoVerdicts(+ for _: MeetingFinalTranscriptEvidence,+ manifest _: MeetingAnalysisManifest,+ plan _: MeetingBackendPlan+ ) async throws -> [String: MeetingUnitEchoVerdict] {+ [:]+ }+}++/// Stage E deterministic text/time echo evidence. For each online-call microphone unit it+/// compares the unit's text only against *temporally overlapping* application-track units with+/// the existing `MeetingEchoDetector`: a positive detector verdict suppresses the microphone copy+/// (the application copy is retained); anything else is measured `notEcho`. In-room sessions and+/// application units need no verdict and get none.+///+/// This provider creates no text, no timing and no speaker identity: it reads the backend's units+/// and the manifest's mapping only. Quarantined units are never read for interval arithmetic —+/// the assembler never consults their verdicts either.+nonisolated struct MeetingTextOverlapEchoVerdictProvider: MeetingUnitEchoVerdictProviding {+ private let tolerance = MeetingAnalysisManifestSchema.mappingToleranceSeconds+ private let wordContextSeconds: TimeInterval = 2++ init() {}++ func echoVerdicts(+ for evidence: MeetingFinalTranscriptEvidence,+ manifest: MeetingAnalysisManifest,+ plan _: MeetingBackendPlan+ ) async throws -> [String: MeetingUnitEchoVerdict] {+ guard manifest.captureMode == .onlineCall else { return [:] }++ struct PositionedUnit {+ let unit: MeetingFinalTextUnit+ let presentation: MeetingAnalysisInterval+ }++ var microphoneUnits: [PositionedUnit] = []+ var applicationUnits: [PositionedUnit] = []+ let activityByEpoch = Dictionary(grouping: evidence.speakerActivity) { $0.token.analysisEpochID }++ for unit in evidence.units {+ try Task.checkCancellation()+ guard let track = manifest.track(unit.trackID),+ unit.quarantineReason(in: manifest) == nil,+ let firstSpanID = unit.analysisSpanIDs.first,+ let lastSpanID = unit.analysisSpanIDs.last,+ let firstSpan = track.spans.first(where: { $0.id == firstSpanID }),+ let lastSpan = track.spans.first(where: { $0.id == lastSpanID })+ else { continue }+ let presentation = MeetingAnalysisInterval(+ start: firstSpan.presentationMapping.presentationTime(forAnalysisTime: unit.analysisStart),+ end: lastSpan.presentationMapping.presentationTime(forAnalysisTime: unit.analysisEnd)+ )+ guard presentation.isValid else { continue }+ let positioned = PositionedUnit(unit: unit, presentation: presentation)+ switch track.kind {+ case .applicationAudio:+ // An application unit outside its own speaker activity can never become a visible+ // duplicate target, so it is not echo evidence either (the assembler proves this).+ guard !MeetingSpeakerActivityCoverage.isOutside(+ unit,+ activityByEpoch: activityByEpoch+ ) else { continue }+ applicationUnits.append(positioned)+ case .microphone:+ microphoneUnits.append(positioned)+ }+ }++ applicationUnits.sort {+ ($0.presentation.start, $0.presentation.end, $0.unit.id)+ < ($1.presentation.start, $1.presentation.end, $1.unit.id)+ }++ var verdicts: [String: MeetingUnitEchoVerdict] = [:]+ for mic in microphoneUnits {+ try Task.checkCancellation()+ // Canonical evidence normally contains one unit per ASR word. The existing detector+ // deliberately refuses fewer than four words, so classify a short temporal phrase and+ // then apply that verdict only to target words that actually occur in the remote phrase.+ let context = MeetingAnalysisInterval(+ start: max(0, mic.presentation.start - self.wordContextSeconds),+ end: mic.presentation.end + self.wordContextSeconds+ )+ let micContext = microphoneUnits.filter {+ $0.unit.trackID == mic.unit.trackID+ && min($0.presentation.end, context.end)+ - max($0.presentation.start, context.start) > self.tolerance+ }.sorted {+ ($0.presentation.start, $0.presentation.end, $0.unit.id)+ < ($1.presentation.start, $1.presentation.end, $1.unit.id)+ }+ let applicationContext = applicationUnits.filter {+ min($0.presentation.end, context.end)+ - max($0.presentation.start, context.start) > self.tolerance+ }+ let causalMatches = applicationContext.filter {+ $0.presentation.start <= mic.presentation.end + self.tolerance+ }+ let micText = micContext.map(\.unit.text).joined(separator: " ")+ let remoteText = applicationContext.map(\.unit.text).joined(separator: " ")+ let targetWords = Set(MeetingEchoDetector.normalizedWords(mic.unit.text))+ let causalRemoteWords = Set(causalMatches.flatMap {+ MeetingEchoDetector.normalizedWords($0.unit.text)+ })+ guard MeetingEchoDetector.isLikelyEcho(micText: micText, remoteText: remoteText),+ !targetWords.isDisjoint(with: causalRemoteWords)+ else {+ verdicts[mic.unit.id] = .notEcho+ continue+ }+ let duplicate = causalMatches.first {+ !targetWords.isDisjoint(with: Set(MeetingEchoDetector.normalizedWords($0.unit.text)))+ } ?? causalMatches.first+ verdicts[mic.unit.id] = .echoSuppressed(duplicateOfUnitID: duplicate?.unit.id)+ }+ return verdicts+ }++}diff --git a/Sources/Fluid/Services/Meeting/MeetingAudioAsset.swift b/Sources/Fluid/Services/Meeting/MeetingAudioAsset.swiftnew file mode 100644index 00000000..68ede981--- /dev/null+++ b/Sources/Fluid/Services/Meeting/MeetingAudioAsset.swift@@ -0,0 +1,121 @@+import Foundation++/// Additive audio-asset vocabulary. Unknown values are retained verbatim so a future asset can be+/// quarantined without making the containing session undecodable.+nonisolated enum MeetingAudioAssetRole: Equatable, Sendable {+ case captureAnalysis+ case playbackArchive+ case unknown(String)++ var rawValue: String {+ switch self { case .captureAnalysis: return "captureAnalysis"; case .playbackArchive: return "playbackArchive"; case let .unknown(raw): return raw }+ }+ init(rawValue: String) { self = rawValue == "captureAnalysis" ? .captureAnalysis : rawValue == "playbackArchive" ? .playbackArchive : .unknown(rawValue) }+}++nonisolated extension MeetingAudioAssetRole: Codable {+ init(from decoder: Decoder) throws { self.init(rawValue: try decoder.singleValueContainer().decode(String.self)) }+ func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(rawValue) }+}++nonisolated enum MeetingAudioEncoding: Equatable, Hashable, Sendable {+ case linearPCMFloat32CAFV1+ case aacLCM4AV1+ case legacyAACUnknownPrimingV1+ case unknown(String)++ var rawValue: String {+ switch self { case .linearPCMFloat32CAFV1: return "linearPCMFloat32CAFV1"; case .aacLCM4AV1: return "aacLCM4AV1"; case .legacyAACUnknownPrimingV1: return "legacyAACUnknownPrimingV1"; case let .unknown(raw): return raw }+ }+ init(rawValue: String) {+ switch rawValue { case "linearPCMFloat32CAFV1": self = .linearPCMFloat32CAFV1; case "aacLCM4AV1": self = .aacLCM4AV1; case "legacyAACUnknownPrimingV1": self = .legacyAACUnknownPrimingV1; default: self = .unknown(rawValue) }+ }+}++nonisolated extension MeetingAudioEncoding: Codable {+ init(from decoder: Decoder) throws { self.init(rawValue: try decoder.singleValueContainer().decode(String.self)) }+ func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(rawValue) }+}++nonisolated enum MeetingAudioAssetPresence: Equatable, Sendable {+ case partial+ case ready+ case evicted+ case failed+ case unknown(String)++ var rawValue: String {+ switch self { case .partial: return "partial"; case .ready: return "ready"; case .evicted: return "evicted"; case .failed: return "failed"; case let .unknown(raw): return raw }+ }+ init(rawValue: String) {+ switch rawValue { case "partial": self = .partial; case "ready": self = .ready; case "evicted": self = .evicted; case "failed": self = .failed; default: self = .unknown(rawValue) }+ }+}++nonisolated extension MeetingAudioAssetPresence: Codable {+ init(from decoder: Decoder) throws { self.init(rawValue: try decoder.singleValueContainer().decode(String.self)) }+ func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(rawValue) }+}++nonisolated struct MeetingAudioAsset: Codable, Equatable, Sendable {+ var role: MeetingAudioAssetRole+ var encoding: MeetingAudioEncoding+ var presence: MeetingAudioAssetPresence+ var relativeFilePath: String+ var byteCount: Int64+ var sha256: String?+ var sampleRate: Double?+ var channelCount: Int?+ var frameCount: Int64?+ var sourceAssetSHA256: String?++ init(role: MeetingAudioAssetRole, encoding: MeetingAudioEncoding, presence: MeetingAudioAssetPresence,+ relativeFilePath: String, byteCount: Int64, sha256: String? = nil, sampleRate: Double? = nil,+ channelCount: Int? = nil, frameCount: Int64? = nil, sourceAssetSHA256: String? = nil) {+ self.role = role; self.encoding = encoding; self.presence = presence; self.relativeFilePath = relativeFilePath; self.byteCount = byteCount+ self.sha256 = sha256; self.sampleRate = sampleRate; self.channelCount = channelCount; self.frameCount = frameCount; self.sourceAssetSHA256 = sourceAssetSHA256+ }++ /// Pure metadata validation. It performs no path or filesystem access and callers may use the+ /// returned issues to quarantine this asset while continuing to decode its parent session.+ func validationIssues() -> [MeetingAudioAssetValidationIssue] {+ var issues: [MeetingAudioAssetValidationIssue] = []+ if case let .unknown(raw) = role { issues.append(.unknownRole(raw)) }+ if case let .unknown(raw) = encoding { issues.append(.unknownEncoding(raw)) }+ if case let .unknown(raw) = presence { issues.append(.unknownPresence(raw)) }+ guard issues.isEmpty else { return issues }+ if relativeFilePath.isEmpty { issues.append(.emptyRelativeFilePath) }+ if byteCount < 0 { issues.append(.negativeByteCount) }+ switch (role, encoding) {+ case (.captureAnalysis, .linearPCMFloat32CAFV1): break+ case (.playbackArchive, .aacLCM4AV1): break+ case (.playbackArchive, .legacyAACUnknownPrimingV1): break+ case (.captureAnalysis, .aacLCM4AV1), (.captureAnalysis, .legacyAACUnknownPrimingV1): issues.append(.encodingRoleContradiction)+ case (.playbackArchive, .linearPCMFloat32CAFV1): issues.append(.encodingRoleContradiction)+ default: break+ }+ if presence == .ready {+ if byteCount <= 0 { issues.append(.readyAssetMissingBytes) }+ if encoding == .legacyAACUnknownPrimingV1 { return issues }+ if sha256?.isEmpty != false { issues.append(.readyAssetMissingHash) }+ if sampleRate == nil || !(sampleRate?.isFinite ?? false) || (sampleRate ?? 0) <= 0 { issues.append(.readyAssetMissingSampleRate) }+ if channelCount == nil || (channelCount ?? 0) <= 0 { issues.append(.readyAssetMissingChannelCount) }+ if frameCount == nil || (frameCount ?? 0) <= 0 { issues.append(.readyAssetMissingFrameCount) }+ }+ return issues+ }+}++nonisolated enum MeetingAudioAssetValidationIssue: Equatable, Sendable {+ case unknownRole(String)+ case unknownEncoding(String)+ case unknownPresence(String)+ case emptyRelativeFilePath+ case negativeByteCount+ case encodingRoleContradiction+ case readyAssetMissingBytes+ case readyAssetMissingHash+ case readyAssetMissingSampleRate+ case readyAssetMissingChannelCount+ case readyAssetMissingFrameCount+}diff --git a/Sources/Fluid/Services/Meeting/MeetingAudioChunkLedger.swift b/Sources/Fluid/Services/Meeting/MeetingAudioChunkLedger.swiftnew file mode 100644index 00000000..8bcf0edd--- /dev/null+++ b/Sources/Fluid/Services/Meeting/MeetingAudioChunkLedger.swift@@ -0,0 +1,169 @@+import CryptoKit+import Darwin+import Foundation++/// P0b writer-ledger facts. These are intentionally standalone and optional at the session layer:+/// old session JSON never contains them, while the PCM-first writer durably checkpoints each new+/// capture chunk. Legacy AAC sessions continue to decode without these records.+nonisolated struct MeetingAudioChunkLedgerIntent: Codable, Equatable, Sendable {+ var chunkID: MeetingAudioChunkID+ var sequence: Int+ var canonicalStart: MeetingMediaTime+ var producerEpoch: UInt64+ var sourceFormat: MeetingAudioFormat+ var partialRelativeFilePath: String+ var createdAt: Date+}++nonisolated struct MeetingAudioChunkLedgerCheckpoint: Codable, Equatable, Sendable {+ var chunkID: MeetingAudioChunkID+ var expectedFrames: Int64+ var writtenFrames: Int64+ var lastCanonicalPTS: MeetingMediaTime?+ var updatedAt: Date+}++nonisolated enum MeetingAudioChunkLedgerTerminalStatus: Equatable, Sendable {+ case ready+ case failed+ case unknown(String)++ var rawValue: String { switch self { case .ready: return "ready"; case .failed: return "failed"; case let .unknown(raw): return raw } }+ init(rawValue: String) { self = rawValue == "ready" ? .ready : rawValue == "failed" ? .failed : .unknown(rawValue) }+}++nonisolated extension MeetingAudioChunkLedgerTerminalStatus: Codable {+ init(from decoder: Decoder) throws { self.init(rawValue: try decoder.singleValueContainer().decode(String.self)) }+ func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(rawValue) }+}++nonisolated struct MeetingAudioChunkLedgerTerminal: Codable, Equatable, Sendable {+ var chunkID: MeetingAudioChunkID+ var status: MeetingAudioChunkLedgerTerminalStatus+ var updatedAt: Date+ var detail: String?+}++nonisolated enum MeetingAudioChunkLedgerError: Error, Equatable, Sendable {+ case invalidChunkID+ case pathRejected+ case conflictingIntent+ case checkpointRegression+ case incompleteReadyTerminal+ case terminalAlreadyExists+ case durabilityFailure(String)+}++/// A serialized-queue-only ledger store. It does no dispatching or locking itself, and must never+/// be called by a real-time callback. Intent is immutable/no-overwrite; checkpoints are atomic+/// replacements; terminal status is immutable/no-overwrite. Every record is fsynced before its+/// rename and the containing directory is fsynced after publication.+nonisolated final class MeetingAudioChunkLedgerStore: @unchecked Sendable {+ let sessionDirectory: URL+ private let ledgerDirectoryName = "chunk-ledger"++ init(sessionDirectory: URL) { self.sessionDirectory = sessionDirectory.standardizedFileURL }++ func writeIntent(_ intent: MeetingAudioChunkLedgerIntent) throws {+ try validate(intent.partialRelativeFilePath)+ try ensureLedgerDirectory()+ let url = try recordURL(chunkID: intent.chunkID, suffix: "intent")+ try writeImmutable(try encode(intent), to: url, conflict: .conflictingIntent)+ }++ func writeCheckpoint(_ checkpoint: MeetingAudioChunkLedgerCheckpoint, for chunkID: MeetingAudioChunkID) throws {+ guard checkpoint.chunkID == chunkID else { throw MeetingAudioChunkLedgerError.invalidChunkID }+ guard try readIntent(for: chunkID) != nil else {+ throw MeetingAudioChunkLedgerError.durabilityFailure("checkpoint has no intent")+ }+ guard checkpoint.expectedFrames >= 0, checkpoint.writtenFrames >= 0,+ checkpoint.writtenFrames <= checkpoint.expectedFrames+ else {+ throw MeetingAudioChunkLedgerError.durabilityFailure("invalid checkpoint frame totals")+ }+ if let previous = try readCheckpoint(for: chunkID) {+ guard checkpoint.expectedFrames >= previous.expectedFrames,+ checkpoint.writtenFrames >= previous.writtenFrames,+ Self.isNondecreasing(previous.lastCanonicalPTS, checkpoint.lastCanonicalPTS)+ else { throw MeetingAudioChunkLedgerError.checkpointRegression }+ }+ try ensureLedgerDirectory()+ try writeReplacing(try encode(checkpoint), to: try recordURL(chunkID: chunkID, suffix: "checkpoint"))+ }++ func writeTerminal(_ terminal: MeetingAudioChunkLedgerTerminal, for chunkID: MeetingAudioChunkID) throws {+ guard terminal.chunkID == chunkID else { throw MeetingAudioChunkLedgerError.invalidChunkID }+ guard try readIntent(for: chunkID) != nil else {+ throw MeetingAudioChunkLedgerError.durabilityFailure("terminal has no intent")+ }+ if terminal.status == .ready {+ guard let checkpoint = try readCheckpoint(for: chunkID),+ checkpoint.expectedFrames > 0,+ checkpoint.expectedFrames == checkpoint.writtenFrames+ else { throw MeetingAudioChunkLedgerError.incompleteReadyTerminal }+ }+ try ensureLedgerDirectory()+ try writeImmutable(try encode(terminal), to: try recordURL(chunkID: chunkID, suffix: "terminal"), conflict: .terminalAlreadyExists)+ }++ func readIntent(for chunkID: MeetingAudioChunkID) throws -> MeetingAudioChunkLedgerIntent? { try read(MeetingAudioChunkLedgerIntent.self, at: try recordURL(chunkID: chunkID, suffix: "intent")) }+ func readCheckpoint(for chunkID: MeetingAudioChunkID) throws -> MeetingAudioChunkLedgerCheckpoint? { try read(MeetingAudioChunkLedgerCheckpoint.self, at: try recordURL(chunkID: chunkID, suffix: "checkpoint")) }+ func readTerminal(for chunkID: MeetingAudioChunkID) throws -> MeetingAudioChunkLedgerTerminal? { try read(MeetingAudioChunkLedgerTerminal.self, at: try recordURL(chunkID: chunkID, suffix: "terminal")) }++ private func validate(_ relative: String) throws {+ let parts = relative.split(separator: "/", omittingEmptySubsequences: false)+ guard !relative.isEmpty, !relative.hasPrefix("/"), !parts.isEmpty, parts.allSatisfy({ !$0.isEmpty && $0 != "." && $0 != ".." }) else { throw MeetingAudioChunkLedgerError.pathRejected }+ }+ private func recordURL(chunkID: UUID, suffix: String) throws -> URL {+ let directory = sessionDirectory.appendingPathComponent(ledgerDirectoryName, isDirectory: true)+ return directory.appendingPathComponent("\(chunkID.uuidString).\(suffix).json")+ }+ private func ensureLedgerDirectory() throws {+ var rootInfo = stat()+ guard lstat(sessionDirectory.path, &rootInfo) == 0,+ (rootInfo.st_mode & S_IFMT) == S_IFDIR+ else { throw MeetingAudioChunkLedgerError.pathRejected }+ let directory = sessionDirectory.appendingPathComponent(ledgerDirectoryName, isDirectory: true)+ var directoryInfo = stat()+ if lstat(directory.path, &directoryInfo) == 0 {+ guard (directoryInfo.st_mode & S_IFMT) == S_IFDIR else {+ throw MeetingAudioChunkLedgerError.pathRejected+ }+ } else {+ guard errno == ENOENT else { throw MeetingAudioChunkLedgerError.pathRejected }+ try FileManager.default.createDirectory(+ at: directory,+ withIntermediateDirectories: false,+ attributes: [.posixPermissions: NSNumber(value: Int16(0o700))]+ )+ }+ guard chmod(directory.path, mode_t(0o700)) == 0 else {+ throw MeetingAudioChunkLedgerError.durabilityFailure("chmod directory")+ }+ }+ private static func isNondecreasing(_ previous: MeetingMediaTime?, _ next: MeetingMediaTime?) -> Bool {+ guard let previous else { return true }+ guard let next else { return false }+ return next.seconds >= previous.seconds+ }+ private func encode<T: Encodable>(_ value: T) throws -> Data { let encoder = JSONEncoder(); encoder.dateEncodingStrategy = .iso8601; encoder.outputFormatting = [.sortedKeys]; return try encoder.encode(value) }+ private func read<T: Decodable>(_ type: T.Type, at url: URL) throws -> T? { guard FileManager.default.fileExists(atPath: url.path) else { return nil }; let decoder = JSONDecoder(); decoder.dateDecodingStrategy = .iso8601; return try decoder.decode(type, from: Data(contentsOf: url, options: .mappedIfSafe)) }+ private func writeImmutable(_ data: Data, to destination: URL, conflict: MeetingAudioChunkLedgerError) throws {+ if FileManager.default.fileExists(atPath: destination.path) {+ guard (try? Data(contentsOf: destination)) == data else { throw conflict }+ return+ }+ try writeTemp(data, destination: destination, exclusive: true, conflict: conflict)+ }+ private func writeReplacing(_ data: Data, to destination: URL) throws { try writeTemp(data, destination: destination, exclusive: false) }+ private func writeTemp(_ data: Data, destination: URL, exclusive: Bool, conflict: MeetingAudioChunkLedgerError? = nil) throws {+ let temp = destination.deletingLastPathComponent().appendingPathComponent(".\(destination.lastPathComponent).\(UUID().uuidString).tmp")+ try data.write(to: temp, options: [])+ guard chmod(temp.path, mode_t(0o600)) == 0 else { try? FileManager.default.removeItem(at: temp); throw MeetingAudioChunkLedgerError.durabilityFailure("chmod") }+ let fd = open(temp.path, O_RDONLY); guard fd >= 0 else { try? FileManager.default.removeItem(at: temp); throw MeetingAudioChunkLedgerError.durabilityFailure("open") }; defer { close(fd) }+ guard fcntl(fd, F_FULLFSYNC) == 0 else { try? FileManager.default.removeItem(at: temp); throw MeetingAudioChunkLedgerError.durabilityFailure("F_FULLFSYNC") }+ let flags = exclusive ? UInt32(RENAME_EXCL) : 0+ guard renameatx_np(AT_FDCWD, temp.path, AT_FDCWD, destination.path, flags) == 0 else { let e = errno; try? FileManager.default.removeItem(at: temp); if exclusive && e == EEXIST { throw conflict ?? .terminalAlreadyExists }; throw MeetingAudioChunkLedgerError.durabilityFailure("rename errno \(e)") }+ let dirFD = open(destination.deletingLastPathComponent().path, O_RDONLY | O_DIRECTORY); guard dirFD >= 0 else { throw MeetingAudioChunkLedgerError.durabilityFailure("open directory") }; defer { close(dirFD) }; guard fsync(dirFD) == 0 else { throw MeetingAudioChunkLedgerError.durabilityFailure("directory fsync") }+ }+}diff --git a/Sources/Fluid/Services/Meeting/MeetingAudioChunkWriter.swift b/Sources/Fluid/Services/Meeting/MeetingAudioChunkWriter.swiftindex 8213ef67..9c16cbe0 100644--- a/Sources/Fluid/Services/Meeting/MeetingAudioChunkWriter.swift+++ b/Sources/Fluid/Services/Meeting/MeetingAudioChunkWriter.swift@@ -29,19 +29,20 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {}private struct ActiveChunk: @unchecked Sendable {+ var id: MeetingAudioChunkIDvar sequence: Int- var partialURL: URL- var finalURL: URLvar relativeFinalPath: String- var writer: AVAssetWriter- var input: AVAssetWriterInput+ var sink: MeetingAudioChunkSinkvar start: CMTimevar end: CMTimevar discontinuities: [MeetingAudioDiscontinuity]/// Captured at `beginChunk` — `self.track.format` may already be the NEXT chunk's by finalize.var format: MeetingAudioFormatvar sourceFormatDescription: CMFormatDescription+ var formatContract: MeetingPCMFormatContractvar producerEpoch: UInt64+ var framesWritten: Int64+ var lastCheckpointFrames: Int64}private enum FinalizationResult: @unchecked Sendable {@@ -61,6 +62,7 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {private let chunkDuration: TimeIntervalprivate let eventHandler: EventHandlerprivate let encoder: JSONEncoder+ private let ledger: MeetingAudioChunkLedgerStorelet trackID: MeetingAudioTrackID@@ -100,7 +102,10 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {sessionDirectory: URL,chunkDuration: TimeInterval,eventHandler: @escaping EventHandler,- pendingSlotLimit: Int = 24+ // PCM persistence is intentionally synchronous on the serialized writer queue. Keep the+ // queue bounded, but allow roughly 1.3 seconds of capture jitter at a 48 kHz/10 ms tap+ // cadence while the filesystem drains a burst.+ pendingSlotLimit: Int = 128) throws {self.trackID = track.idself.track = track@@ -111,12 +116,13 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {self.manifestURL = self.trackDirectory.appendingPathComponent("track.json")self.chunkDuration = max(60, chunkDuration)self.eventHandler = eventHandler+ self.ledger = MeetingAudioChunkLedgerStore(sessionDirectory: sessionDirectory)self.queue = DispatchQueue(label: "com.fluidvoice.meeting.writer.\(track.kind.rawValue)",qos: .userInitiated)self.finalizationQueue = DispatchQueue(- label: "com.fluidvoice.meeting.writer.\(track.kind.rawValue).finalization",+ label: "com.fluidvoice.meeting.writer.\(track.kind.rawValue).pcm-finalization",qos: .utility)self.pendingSlots = DispatchSemaphore(value: max(0, pendingSlotLimit))@@ -459,28 +465,30 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {discontinuities: boundaryDiscontinuity.map { [$0] } ?? [])} else if let formatDescription = CMSampleBufferGetFormatDescription(sampleBuffer),- !CMFormatDescriptionEqual(formatDescription, otherFormatDescription: self.activeChunk?.sourceFormatDescription)+ let incomingContract = try? MeetingPCMFormatContract(formatDescription: formatDescription),+ incomingContract != self.activeChunk?.formatContract{self.scheduleActiveChunkFinalization()try self.beginChunk(with: sampleBuffer,at: presentationTime,producerEpoch: producerEpoch,- discontinuities: []+ discontinuities: [],+ contract: incomingContract)}guard var activeChunk = self.activeChunk else { return }- guard activeChunk.input.isReadyForMoreMediaData else {- self.recordDroppedSample(detail: "Audio encoder backpressure caused a dropped sample.")- return- }- guard activeChunk.input.append(sampleBuffer) else {- throw MeetingCaptureError.writerFailed(- activeChunk.writer.error?.localizedDescription ?? "The audio encoder rejected a sample."- )+ let receipt = try activeChunk.sink.append(sampleBuffer)+ guard receipt.framesAccepted == receipt.framesWritten,+ receipt.framesAccepted == Int64(CMSampleBufferGetNumSamples(sampleBuffer)) else {+ throw MeetingCaptureError.writerFailed("PCM sink reported a short write.")}activeChunk.end = presentationTime + duration+ activeChunk.framesWritten += receipt.framesWritten+ if activeChunk.framesWritten - activeChunk.lastCheckpointFrames >= Int64((activeChunk.format.sampleRate).rounded()) {+ try self.writeCheckpoint(for: &activeChunk)+ }self.activeChunk = activeChunkself.track.health.status = .healthyself.track.health.lastPresentationTime = Self.mediaTime(presentationTime)@@ -502,13 +510,29 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {self.track.health.detail = nilself.emitHealthIfNeeded()} catch {- self.track.health.status = .degraded- self.track.health.detail = error.localizedDescription- self.eventHandler(.interrupted(- kind: .writerFailure,- trackID: self.track.id,- detail: error.localizedDescription- ))+ // A sink failure poisons the current container. Retire it immediately so the next+ // callback can establish a fresh chunk instead of retrying the same invalid sink and+ // emitting an error storm for every subsequent buffer.+ var retiredChunk = false+ if let failedChunk = self.activeChunk {+ retiredChunk = true+ self.activeChunk = nil+ self.lastFinalizedEnd = failedChunk.end+ failedChunk.sink.cancel()+ self.applyFinalization(.failed(+ Self.failedChunk(from: failedChunk),+ "PCM chunk write failed: \(error.localizedDescription)"+ ))+ }+ if !retiredChunk {+ self.track.health.status = .degraded+ self.track.health.detail = error.localizedDescription+ self.eventHandler(.interrupted(+ kind: .writerFailure,+ trackID: self.track.id,+ detail: error.localizedDescription+ ))+ }}}@@ -516,7 +540,8 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {with sampleBuffer: CMSampleBuffer,at start: CMTime,producerEpoch: UInt64,- discontinuities: [MeetingAudioDiscontinuity]+ discontinuities: [MeetingAudioDiscontinuity],+ contract: MeetingPCMFormatContract? = nil) throws {guard let formatDescription = CMSampleBufferGetFormatDescription(sampleBuffer),let asbd = CMAudioFormatDescriptionGetStreamBasicDescription(formatDescription)?.pointee,@@ -526,74 +551,78 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {throw MeetingCaptureError.unsupportedAudioFormat}- let channelCount = min(2, max(1, Int(asbd.mChannelsPerFrame)))- let bitRate = channelCount == 1 ? 64_000 : 96_000+ let formatContract = try contract ?? MeetingPCMFormatContract(formatDescription: formatDescription)++ guard asbd.mFormatID == kAudioFormatLinearPCM,+ asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0,+ asbd.mBitsPerChannel == 32,+ asbd.mFramesPerPacket == 1+ else { throw MeetingCaptureError.unsupportedAudioFormat }++ let channelCount = Int(asbd.mChannelsPerFrame)let sequence = self.nextChunkSequenceself.nextChunkSequence += 1let stem = String(format: "%06d", sequence)- let partialURL = self.trackDirectory.appendingPathComponent("\(stem).partial.m4a")- let finalURL = self.trackDirectory.appendingPathComponent("\(stem).m4a")- try? FileManager.default.removeItem(at: partialURL)-- let writer = try AVAssetWriter(outputURL: partialURL, fileType: .m4a)- let outputSettings: [String: Any] = [- AVFormatIDKey: kAudioFormatMPEG4AAC,- AVSampleRateKey: asbd.mSampleRate,- AVNumberOfChannelsKey: channelCount,- AVEncoderBitRateKey: bitRate,- ]- let input = AVAssetWriterInput(- mediaType: .audio,- outputSettings: outputSettings,- sourceFormatHint: formatDescription- )- input.expectsMediaDataInRealTime = true- guard writer.canAdd(input) else { throw MeetingCaptureError.unsupportedAudioFormat }- writer.add(input)- guard writer.startWriting() else {- throw MeetingCaptureError.writerFailed(- writer.error?.localizedDescription ?? "The audio writer could not start."- )- }- // `consume` normalizes the sample itself before it reaches AVAssetWriter. Chunk metadata and- // encoded sample timing therefore live on one canonical timeline.- writer.startSession(atSourceTime: start)-let format = MeetingAudioFormat(- codec: "aac-lc",+ codec: "lpcm-f32",sampleRate: asbd.mSampleRate,channelCount: channelCount,- bitRate: bitRate+ bitRate: nil)+ let sink = MeetingAudioFilePCMChunkSink(sessionDirectory: self.sessionDirectory)+ let relativePath = "tracks/\(self.track.kind.rawValue)/\(stem).caf"+ let clientFormat = AVAudioFormat(cmAudioFormatDescription: formatDescription)+ try sink.begin(relativeFilePath: relativePath, format: clientFormat, contract: formatContract)+ let id = UUID()+ do {+ try self.ledger.writeIntent(MeetingAudioChunkLedgerIntent(+ chunkID: id,+ sequence: sequence,+ canonicalStart: Self.mediaTime(start),+ producerEpoch: producerEpoch,+ sourceFormat: format,+ partialRelativeFilePath: sink.partialRelativeFilePath ?? relativePath,+ createdAt: Date()+ ))+ } catch {+ sink.cancel()+ throw error+ }self.track.format = format- let relativePath = finalURL.path.replacingOccurrences(- of: self.sessionDirectory.path + "/",- with: ""- )self.activeChunk = ActiveChunk(+ id: id,sequence: sequence,- partialURL: partialURL,- finalURL: finalURL,relativeFinalPath: relativePath,- writer: writer,- input: input,+ sink: sink,start: start,end: start,discontinuities: discontinuities,format: format,sourceFormatDescription: formatDescription,- producerEpoch: producerEpoch+ formatContract: formatContract,+ producerEpoch: producerEpoch,+ framesWritten: 0,+ lastCheckpointFrames: 0)}private func scheduleActiveChunkFinalization() {- guard let activeChunk = self.activeChunk else { return }+ guard var activeChunk = self.activeChunk else { return }self.activeChunk = nilself.lastFinalizedEnd = activeChunk.end- activeChunk.input.markAsFinished()+ do {+ try self.writeCheckpoint(for: &activeChunk)+ } catch {+ activeChunk.sink.cancel()+ self.applyFinalization(.failed(+ Self.failedChunk(from: activeChunk),+ "PCM chunk checkpoint failed: \(error.localizedDescription)"+ ))+ return+ }guard self.finalizationSlots.wait(timeout: .now()) == .success else {- activeChunk.writer.cancelWriting()+ activeChunk.sink.cancel()self.applyFinalization(.failed(Self.failedChunk(from: activeChunk),"Audio chunk finalization was saturated; the chunk was closed without blocking capture."@@ -602,6 +631,10 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {}self.finalizationGroup.enter()+ // The active chunk has been removed from the writer queue, so ownership of this sink can+ // transfer to the finalization queue with no concurrent append/cancel calls. Reopen, hash+ // and fsync are intentionally off the capture queue: a 60-second Float32 CAF is large+ // enough to overflow the bounded producer queue if finalization blocks it.self.finalizationQueue.async { [self, activeChunk] inlet result = Self.finalize(activeChunk)self.queue.async { [self] in@@ -616,10 +649,37 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {switch result {case let .finalized(chunk, format):self.track.chunks.append(chunk)+ do {+ try self.ledger.writeTerminal(MeetingAudioChunkLedgerTerminal(+ chunkID: chunk.id,+ status: .ready,+ updatedAt: Date(),+ detail: nil+ ), for: chunk.id)+ } catch {+ // A PCM file that finalized without a durable ready terminal is not publishable.+ // Keep the chunk fail-closed and surface the ledger failure to the capture owner.+ try? FileManager.default.removeItem(at: self.sessionDirectory.appendingPathComponent(chunk.relativeFilePath))+ if let index = self.track.chunks.firstIndex(where: { $0.id == chunk.id }) {+ self.track.chunks[index].finalizationState = .failed+ self.track.chunks[index].captureAnalysisAsset?.presence = .failed+ }+ self.track.health.status = .degraded+ self.track.health.detail = "PCM chunk ledger terminal failed: \(error.localizedDescription)"+ self.eventHandler(.interrupted(kind: .writerFailure, trackID: self.track.id, detail: self.track.health.detail ?? "PCM chunk ledger terminal failed."))+ try? self.persistTrackManifest()+ return+ }try? self.persistTrackManifest()self.eventHandler(.chunkFinalized(trackID: self.track.id, chunk: chunk, format: format))case let .failed(chunk, detail):self.track.chunks.append(chunk)+ try? self.ledger.writeTerminal(MeetingAudioChunkLedgerTerminal(+ chunkID: chunk.id,+ status: .failed,+ updatedAt: Date(),+ detail: detail+ ), for: chunk.id)self.track.health.status = .degradedself.track.health.detail = detailtry? self.persistTrackManifest()@@ -653,52 +713,41 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {"Audio chunk timing was not monotonic.")}- let completion = DispatchSemaphore(value: 0)- activeChunk.writer.finishWriting { completion.signal() }- guard completion.wait(timeout: .now() + 4) == .success else {- activeChunk.writer.cancelWriting()- return .failed(- self.failedChunk(from: activeChunk),- "Timed out while finalizing the audio chunk."+ switch activeChunk.sink.finalize() {+ case let .success(finalization):+ let asset = MeetingAudioAsset(+ role: .captureAnalysis,+ encoding: .linearPCMFloat32CAFV1,+ presence: .ready,+ relativeFilePath: finalization.relativeFilePath,+ byteCount: finalization.byteCount,+ sha256: finalization.sha256,+ sampleRate: finalization.sampleRate,+ channelCount: finalization.channelCount,+ frameCount: finalization.frameCount)- }- guard activeChunk.writer.status == .completed else {- return .failed(- self.failedChunk(from: activeChunk),- activeChunk.writer.error?.localizedDescription ?? "The audio chunk could not be finalized."- )- }-- do {- try? FileManager.default.removeItem(at: activeChunk.finalURL)- try FileManager.default.moveItem(at: activeChunk.partialURL, to: activeChunk.finalURL)- try FileManager.default.setAttributes(- [.posixPermissions: NSNumber(value: Int16(0o600))],- ofItemAtPath: activeChunk.finalURL.path- )- let values = try activeChunk.finalURL.resourceValues(forKeys: [.fileSizeKey])- return try .finalized(- MeetingAudioChunk(- id: UUID(),- sequence: activeChunk.sequence,- relativeFilePath: activeChunk.relativeFinalPath,- presentationStart: self.mediaTime(activeChunk.start),- presentationEnd: self.mediaTime(activeChunk.end),- discontinuities: activeChunk.discontinuities,- sha256: self.sha256(of: activeChunk.finalURL),- byteCount: Int64(values.fileSize ?? 0),- finalizationState: .finalized- ),- activeChunk.format- )- } catch {- return .failed(self.failedChunk(from: activeChunk), error.localizedDescription)+ return .finalized(MeetingAudioChunk(+ id: activeChunk.id,+ sequence: activeChunk.sequence,+ relativeFilePath: finalization.relativeFilePath,+ presentationStart: self.mediaTime(activeChunk.start),+ presentationEnd: self.mediaTime(activeChunk.end),+ discontinuities: activeChunk.discontinuities,+ sha256: finalization.sha256,+ byteCount: finalization.byteCount,+ finalizationState: .finalized,+ audioSchemaVersion: 2,+ captureAnalysisAsset: asset,+ playbackArchiveAsset: nil+ ), activeChunk.format)+ case let .failure(error):+ return .failed(self.failedChunk(from: activeChunk), "PCM chunk finalization failed: \(error)")}}private nonisolated static func failedChunk(from activeChunk: ActiveChunk) -> MeetingAudioChunk {MeetingAudioChunk(- id: UUID(),+ id: activeChunk.id,sequence: activeChunk.sequence,relativeFilePath: activeChunk.relativeFinalPath,presentationStart: self.mediaTime(activeChunk.start),@@ -706,10 +755,31 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {discontinuities: activeChunk.discontinuities,sha256: "",byteCount: 0,- finalizationState: .failed+ finalizationState: .failed,+ audioSchemaVersion: 2,+ captureAnalysisAsset: MeetingAudioAsset(+ role: .captureAnalysis,+ encoding: .linearPCMFloat32CAFV1,+ presence: .failed,+ relativeFilePath: activeChunk.relativeFinalPath,+ byteCount: 0+ ),+ playbackArchiveAsset: nil)}+ private func writeCheckpoint(for activeChunk: inout ActiveChunk) throws {+ guard activeChunk.framesWritten > 0 else { return }+ try self.ledger.writeCheckpoint(MeetingAudioChunkLedgerCheckpoint(+ chunkID: activeChunk.id,+ expectedFrames: activeChunk.framesWritten,+ writtenFrames: activeChunk.framesWritten,+ lastCanonicalPTS: Self.mediaTime(activeChunk.end),+ updatedAt: Date()+ ), for: activeChunk.id)+ activeChunk.lastCheckpointFrames = activeChunk.framesWritten+ }+private func recordDroppedSample(detail: String) {self.track.health.status = .degradedself.track.health.droppedSampleCount += 1diff --git a/Sources/Fluid/Services/Meeting/MeetingAutoDetectSignals.swift b/Sources/Fluid/Services/Meeting/MeetingAutoDetectSignals.swiftindex 547c8cc9..d27a59da 100644--- a/Sources/Fluid/Services/Meeting/MeetingAutoDetectSignals.swift+++ b/Sources/Fluid/Services/Meeting/MeetingAutoDetectSignals.swift@@ -853,6 +853,8 @@ nonisolated enum MeetingStorageReadiness {let capacity = try? applicationSupport.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey]).volumeAvailableCapacityForImportantUsageelse { return false }- return capacity >= 512 * 1024 * 1024+ // Auto-detection can arm an online-call capture, so budget for the largest supported+ // topology until the user chooses an explicit in-room mode.+ return capacity >= MeetingPCMStoragePolicy.requiredFreeBytes(trackCount: 2)}}diff --git a/Sources/Fluid/Services/Meeting/MeetingCaptureEngine.swift b/Sources/Fluid/Services/Meeting/MeetingCaptureEngine.swiftindex 906c0eb0..6166aa75 100644--- a/Sources/Fluid/Services/Meeting/MeetingCaptureEngine.swift+++ b/Sources/Fluid/Services/Meeting/MeetingCaptureEngine.swift@@ -53,7 +53,10 @@ actor MeetingCaptureEngine: MeetingCaptureControlling {}self.startingSessionID = session.iddefer { self.startingSessionID = nil }- try Self.preflightStorage(at: sessionDirectory)+ try Self.preflightStorage(+ at: sessionDirectory,+ trackCount: MeetingPCMStoragePolicy.trackCount(for: configuration.mode)+ )try Self.verifyMicrophonePermission()let tracks = Self.makeTracks(session: session, configuration: configuration)@@ -396,9 +399,10 @@ actor MeetingCaptureEngine: MeetingCaptureControlling {})}- private nonisolated static func preflightStorage(at directory: URL) throws {+ private nonisolated static func preflightStorage(at directory: URL, trackCount: Int) throws {let values = try directory.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])- if let capacity = values.volumeAvailableCapacityForImportantUsage, capacity < 512 * 1024 * 1024 {+ let required = MeetingPCMStoragePolicy.requiredFreeBytes(trackCount: trackCount)+ guard let capacity = values.volumeAvailableCapacityForImportantUsage, capacity >= required else {throw MeetingCaptureError.insufficientDiskSpace}}@@ -2495,7 +2499,7 @@ nonisolated enum MeetingCaptureError: LocalizedError {case let .screenCapturePermissionDenied(detail):return "Screen & System Audio permission is required. \(detail)"case .insufficientDiskSpace:- return "At least 512 MB of free space is required to start recording."+ return "Not enough free space is available for PCM meeting capture. Free space for at least a one-hour recording and processing workspace, then try again."case let .captureStartFailed(detail):return "Meeting recording could not start. \(detail)"case let .captureStopFailed(detail, _):diff --git a/Sources/Fluid/Services/Meeting/MeetingMicrophoneCapture.swift b/Sources/Fluid/Services/Meeting/MeetingMicrophoneCapture.swiftindex 882515ee..da5a6225 100644--- a/Sources/Fluid/Services/Meeting/MeetingMicrophoneCapture.swift+++ b/Sources/Fluid/Services/Meeting/MeetingMicrophoneCapture.swift@@ -166,9 +166,18 @@ nonisolated func meetingMicrophoneSynthesizeSampleBuffer(from buffer: AVAudioPCMBuffer,presentationTime: CMTime) -> CMSampleBuffer? {- guard buffer.frameLength > 0, let channelData = buffer.floatChannelData else { return nil }+ guard buffer.frameLength > 0 else { return nil }+ let frameCount = Int(buffer.frameLength)+ let channelCount = Int(buffer.format.channelCount)+ guard channelCount > 0 else { return nil }var asbd = buffer.format.streamDescription.pointee+ // CMSampleBuffer's block buffer below is canonical interleaved LPCM, regardless of whether+ // the tap supplied planar or interleaved AVAudioPCMBuffer storage. Keep the description and+ // payload topology truthful so downstream sinks can validate frame/byte totals.+ asbd.mFormatFlags &= ~kAudioFormatFlagIsNonInterleaved+ asbd.mBytesPerFrame = UInt32(channelCount * MemoryLayout<Float>.size)+ asbd.mBytesPerPacket = asbd.mBytesPerFramevar formatDescription: CMAudioFormatDescription?let formatStatus = CMAudioFormatDescriptionCreate(allocator: kCFAllocatorDefault,@@ -182,8 +191,24 @@ nonisolated func meetingMicrophoneSynthesizeSampleBuffer()guard formatStatus == noErr, let formatDescription else { return nil }- let frameCount = Int(buffer.frameLength)- let byteCount = frameCount * MemoryLayout<Float>.size+ let byteCount = frameCount * channelCount * MemoryLayout<Float>.size+ var interleaved = Data(count: byteCount)+ if buffer.format.isInterleaved {+ guard let source = buffer.audioBufferList.pointee.mBuffers.mData else { return nil }+ interleaved.withUnsafeMutableBytes { destination in+ destination.copyBytes(from: UnsafeRawBufferPointer(start: source, count: byteCount))+ }+ } else {+ guard let channelData = buffer.floatChannelData else { return nil }+ interleaved.withUnsafeMutableBytes { destination in+ let output = destination.baseAddress!.assumingMemoryBound(to: Float.self)+ for frame in 0..<frameCount {+ for channel in 0..<channelCount {+ output[frame * channelCount + channel] = channelData[channel][frame]+ }+ }+ }+ }var blockBuffer: CMBlockBuffer?let blockStatus = CMBlockBufferCreateWithMemoryBlock(@@ -199,12 +224,14 @@ nonisolated func meetingMicrophoneSynthesizeSampleBuffer()guard blockStatus == noErr, let blockBuffer else { return nil }- let copyStatus = CMBlockBufferReplaceDataBytes(- with: channelData[0],- blockBuffer: blockBuffer,- offsetIntoDestination: 0,- dataLength: byteCount- )+ let copyStatus = interleaved.withUnsafeBytes { bytes in+ CMBlockBufferReplaceDataBytes(+ with: bytes.baseAddress!,+ blockBuffer: blockBuffer,+ offsetIntoDestination: 0,+ dataLength: byteCount+ )+ }guard copyStatus == noErr else { return nil }var timing = CMSampleTimingInfo(diff --git a/Sources/Fluid/Services/Meeting/MeetingModels.swift b/Sources/Fluid/Services/Meeting/MeetingModels.swiftindex 7c04e924..d85f5767 100644--- a/Sources/Fluid/Services/Meeting/MeetingModels.swift+++ b/Sources/Fluid/Services/Meeting/MeetingModels.swift@@ -54,6 +54,8 @@ nonisolated enum MeetingInterruptionKind: String, Codable, Sendable {case voiceProcessingDeclinedcase voiceProcessingConfigurationChangedcase voiceProcessingOverload+ /// Final processing completed with typed gaps or quarantined evidence.+ case transcriptCoverageIncomplete}nonisolated enum MeetingFailureDomain: String, Codable, Sendable {@@ -91,6 +93,17 @@ nonisolated enum MeetingTranscriptOverlap: String, Codable, Sendable {nonisolated enum MeetingTranscriptCoverageGapReason: String, Codable, Sendable {case unprotectedMicrophone+ // Canonical-assembly reasons (C2b2). Additive: old sessions keep decoding, and legacy output+ // still only ever reports `unprotectedMicrophone`.+ case missingOrUnreadableAudio+ case processingFailed+ case processingSkipped+ case providerTruncated+ /// An indivisible unit touched an excluded interval; its admissible portion is incomplete.+ case excludedUnitIncompleteCoverage+ /// Canonical admission rejected the capture era because positive echo-protection provenance+ /// was absent or unsafe. Kept distinct from the legacy `unprotectedMicrophone` label.+ case inadmissibleCaptureEra}nonisolated struct MeetingTranscriptCoverageGap: Codable, Equatable, Sendable {@@ -333,6 +346,83 @@ nonisolated struct MeetingAudioChunk: Codable, Identifiable, Equatable, Sendablevar sha256: Stringvar byteCount: Int64var finalizationState: MeetingAudioChunkFinalizationState+ /// P0a additive metadata. Nil is deliberately omitted to preserve the legacy JSON shape.+ /// Once a later activation writes these fields, old-build-read-new compatibility is not+ /// claimed; this P0a slice writes none of them from production capture.+ var audioSchemaVersion: Int? = nil+ var captureAnalysisAsset: MeetingAudioAsset? = nil+ var playbackArchiveAsset: MeetingAudioAsset? = nil++ init(+ id: MeetingAudioChunkID,+ sequence: Int,+ relativeFilePath: String,+ presentationStart: MeetingMediaTime,+ presentationEnd: MeetingMediaTime,+ discontinuities: [MeetingAudioDiscontinuity],+ sha256: String,+ byteCount: Int64,+ finalizationState: MeetingAudioChunkFinalizationState,+ audioSchemaVersion: Int? = nil,+ captureAnalysisAsset: MeetingAudioAsset? = nil,+ playbackArchiveAsset: MeetingAudioAsset? = nil+ ) {+ self.id = id; self.sequence = sequence; self.relativeFilePath = relativeFilePath+ self.presentationStart = presentationStart; self.presentationEnd = presentationEnd+ self.discontinuities = discontinuities; self.sha256 = sha256; self.byteCount = byteCount+ self.finalizationState = finalizationState; self.audioSchemaVersion = audioSchemaVersion+ self.captureAnalysisAsset = captureAnalysisAsset; self.playbackArchiveAsset = playbackArchiveAsset+ }++ private enum CodingKeys: String, CodingKey {+ case id, sequence, relativeFilePath, presentationStart, presentationEnd, discontinuities+ case sha256, byteCount, finalizationState, audioSchemaVersion, captureAnalysisAsset, playbackArchiveAsset+ }++ init(from decoder: Decoder) throws {+ let c = try decoder.container(keyedBy: CodingKeys.self)+ self.id = try c.decode(MeetingAudioChunkID.self, forKey: .id)+ self.sequence = try c.decode(Int.self, forKey: .sequence)+ self.relativeFilePath = try c.decode(String.self, forKey: .relativeFilePath)+ self.presentationStart = try c.decode(MeetingMediaTime.self, forKey: .presentationStart)+ self.presentationEnd = try c.decode(MeetingMediaTime.self, forKey: .presentationEnd)+ self.discontinuities = try c.decode([MeetingAudioDiscontinuity].self, forKey: .discontinuities)+ self.sha256 = try c.decode(String.self, forKey: .sha256)+ self.byteCount = try c.decode(Int64.self, forKey: .byteCount)+ self.finalizationState = try c.decode(MeetingAudioChunkFinalizationState.self, forKey: .finalizationState)+ self.audioSchemaVersion = try c.decodeIfPresent(Int.self, forKey: .audioSchemaVersion)+ self.captureAnalysisAsset = try c.decodeIfPresent(MeetingAudioAsset.self, forKey: .captureAnalysisAsset)+ self.playbackArchiveAsset = try c.decodeIfPresent(MeetingAudioAsset.self, forKey: .playbackArchiveAsset)+ }++ func encode(to encoder: Encoder) throws {+ var c = encoder.container(keyedBy: CodingKeys.self)+ try c.encode(self.id, forKey: .id); try c.encode(self.sequence, forKey: .sequence)+ try c.encode(self.relativeFilePath, forKey: .relativeFilePath)+ try c.encode(self.presentationStart, forKey: .presentationStart); try c.encode(self.presentationEnd, forKey: .presentationEnd)+ try c.encode(self.discontinuities, forKey: .discontinuities); try c.encode(self.sha256, forKey: .sha256)+ try c.encode(self.byteCount, forKey: .byteCount); try c.encode(self.finalizationState, forKey: .finalizationState)+ try c.encodeIfPresent(self.audioSchemaVersion, forKey: .audioSchemaVersion)+ try c.encodeIfPresent(self.captureAnalysisAsset, forKey: .captureAnalysisAsset)+ try c.encodeIfPresent(self.playbackArchiveAsset, forKey: .playbackArchiveAsset)+ }++ func assetValidationIssues() -> [MeetingAudioAssetValidationIssue] {+ var issues: [MeetingAudioAssetValidationIssue] = []+ if let captureAnalysisAsset {+ issues.append(contentsOf: captureAnalysisAsset.validationIssues())+ if captureAnalysisAsset.role != .captureAnalysis {+ issues.append(.encodingRoleContradiction)+ }+ }+ if let playbackArchiveAsset {+ issues.append(contentsOf: playbackArchiveAsset.validationIssues())+ if playbackArchiveAsset.role != .playbackArchive {+ issues.append(.encodingRoleContradiction)+ }+ }+ return issues+ }func fileURL(relativeTo sessionDirectory: URL) -> URL {sessionDirectory.appendingPathComponent(self.relativeFilePath, isDirectory: false)@@ -671,7 +761,16 @@ nonisolated struct MeetingTranscriptSegment: Codable, Identifiable, Equatable, S/// Optional so pre-fix manifests still decode; a non-optional default would `keyNotFound`.var isLikelyEcho: Bool? = nil- var isEcho: Bool { self.isLikelyEcho == true }+ var isEcho: Bool {+ self.isLikelyEcho == true+ }+}++/// Persisted product transcript timestamps are elapsed seconds from the meeting's presentation+/// origin. Optional on `MeetingSession` so legacy sessions and canonical sessions written before+/// the contract was explicit remain decodable and can be handled separately.+nonisolated enum MeetingTranscriptTimeDomain: String, Codable, Sendable {+ case meetingRelative}nonisolated struct MeetingProcessingAttempt: Codable, Identifiable, Equatable, Sendable {@@ -686,6 +785,10 @@ nonisolated struct MeetingProcessingAttempt: Codable, Identifiable, Equatable, Svar diarizationModel: String?var lastCompletedTrackID: MeetingAudioTrackID?var errorCode: String?+ /// Actual backend lineage for canonical attempts. Optional so attempts recorded before the+ /// backend abstraction existed decode unchanged; legacy attempts leave these nil.+ var backendID: String? = nil+ var backendVersion: String? = nil}nonisolated struct MeetingRetentionState: Codable, Equatable, Sendable {@@ -755,6 +858,16 @@ nonisolated struct MeetingSession: Codable, Identifiable, Equatable, Sendable {var transcriptSegments: [MeetingTranscriptSegment]/// Audio intervals intentionally excluded from the transcript. Optional for schema-1 sessions.var transcriptCoverageGaps: [MeetingTranscriptCoverageGap]? = nil+ /// Verified reference to the canonical attempt's durable result sidecar inside this session's+ /// directory. Optional and backward compatible: sessions written before canonical publication+ /// decode `nil`. Retention and deletion follow the session directory itself.+ var resultSidecarReference: MeetingResultSidecarReference? = nil+ /// Canonical transcript completeness. `nil` for older and legacy sessions whose existing+ /// completeness semantics remain unchanged.+ var transcriptIsComplete: Bool? = nil+ /// Explicit for canonical sessions published after the timeline-domain fix. A nil value on a+ /// canonical session with a result sidecar identifies the one-time absolute-host-time migration.+ var transcriptTimeDomain: MeetingTranscriptTimeDomain? = nilvar retention: MeetingRetentionStatevar processingAttempts: [MeetingProcessingAttempt]var updatedAt: Date@@ -1133,6 +1246,10 @@ nonisolated struct MeetingProcessingResult: Sendable {var attempt: MeetingProcessingAttemptvar skippedChunkIDs: [MeetingAudioChunkID] = []var coverageGaps: [MeetingTranscriptCoverageGap] = []+ /// Present only on the canonical path: the sidecar was written and read-back verified before+ /// this result was returned, so the coordinator may persist the reference with the session.+ var resultSidecarReference: MeetingResultSidecarReference? = nil+ var isComplete: Bool = true}/// Resume point written after the application-audio pass so a retry can skip re-diarizing and@@ -1180,9 +1297,12 @@ nonisolated struct MeetingProcessingCheckpoint: Codable, Equatable, Sendable {static func fingerprints(for tracks: [MeetingAudioTrack]) -> [MeetingAudioTrackID: [ChunkFingerprint]] {Dictionary(uniqueKeysWithValues: tracks.map { track in- (track.id, track.chunks- .filter { $0.finalizationState == .finalized && $0.byteCount > 0 }- .map { ChunkFingerprint(id: $0.id, byteCount: $0.byteCount, sha256: $0.sha256) })+ (+ track.id,+ track.chunks+ .filter { $0.finalizationState == .finalized && $0.byteCount > 0 }+ .map { ChunkFingerprint(id: $0.id, byteCount: $0.byteCount, sha256: $0.sha256) }+ )})}diff --git a/Sources/Fluid/Services/Meeting/MeetingPCMStoragePolicy.swift b/Sources/Fluid/Services/Meeting/MeetingPCMStoragePolicy.swiftnew file mode 100644index 00000000..fcd82f28--- /dev/null+++ b/Sources/Fluid/Services/Meeting/MeetingPCMStoragePolicy.swift@@ -0,0 +1,54 @@+import Foundation++/// Storage budget for PCM-first meeting capture.+///+/// Meeting capture keeps the authoritative recording as native Float32 PCM until the+/// transcript is published. This policy deliberately budgets for a normal one-hour+/// meeting plus analysis working space instead of using the old compressed-audio floor.+nonisolated enum MeetingPCMStoragePolicy {+ static let sampleRate: Int64 = 48_000+ static let bytesPerSample: Int64 = 4 // Float32+ static let defaultMeetingDuration: TimeInterval = 60 * 60+ static let safetyMultiplier: Double = 1.25+ static let materializationHeadroomBytes: Int64 = 1 * 1024 * 1024 * 1024+ static let stagingHeadroomBytes: Int64 = 512 * 1024 * 1024++ static func trackCount(for mode: MeetingCaptureMode) -> Int {+ mode == .onlineCall ? 2 : 1+ }++ /// Worst-case PCM bytes per second for the capture topology.+ /// Online calls are application stereo + microphone mono; in-room meetings are microphone+ /// mono. The count is intentionally bounded to the supported topology.+ static func pcmBytesPerSecond(trackCount: Int) -> Int64 {+ let channels = trackCount >= 2 ? 3 : 1+ return sampleRate * bytesPerSample * Int64(channels)+ }++ static func estimatedPCMBytes(+ trackCount: Int,+ duration: TimeInterval = Self.defaultMeetingDuration+ ) -> Int64 {+ guard duration.isFinite, duration > 0 else { return 0 }+ let seconds = Int64(ceil(duration))+ return pcmBytesPerSecond(trackCount: trackCount) * seconds+ }++ /// Free-space floor required before starting a capture. The safety multiplier covers file+ /// headers, short overruns, and timeline duplication; the two fixed reserves cover the+ /// canonical 16 kHz materialization and temporary processing/staging files.+ static func requiredFreeBytes(+ trackCount: Int,+ duration: TimeInterval = Self.defaultMeetingDuration+ ) -> Int64 {+ let pcm = Double(estimatedPCMBytes(trackCount: trackCount, duration: duration))+ let protectedPCM = Int64(ceil(pcm * safetyMultiplier))+ return protectedPCM + materializationHeadroomBytes + stagingHeadroomBytes+ }++ static func requiredFreeSpaceDescription(trackCount: Int) -> String {+ let formatter = ByteCountFormatter()+ formatter.countStyle = .file+ return formatter.string(fromByteCount: requiredFreeBytes(trackCount: trackCount))+ }+}diff --git a/Sources/Fluid/Services/Meeting/MeetingProcessingConfiguration.swift b/Sources/Fluid/Services/Meeting/MeetingProcessingConfiguration.swiftindex 129bafa2..a1e4d0a7 100644--- a/Sources/Fluid/Services/Meeting/MeetingProcessingConfiguration.swift+++ b/Sources/Fluid/Services/Meeting/MeetingProcessingConfiguration.swift@@ -17,15 +17,15 @@ nonisolated enum MeetingConfigFingerprintEncoding {}}-/// Inert value snapshot of meeting post-processing ASR configuration. No runtime path reads this-/// yet; P1 wiring will build it once per run so pipeline actors stop reading `SettingsStore.shared`-/// mid-flight.+/// Immutable value snapshot of meeting post-processing ASR configuration. The pipeline builds it+/// once per attempt and the meeting preparation owner constructs a fixed provider from it, so an+/// active run never follows later dictation-setting changes.nonisolated struct MeetingFinalProcessingConfiguration: Equatable, Sendable {static let defaultASRModel = "parakeet-tdt-v2"static let defaultLanguageCode = "en"/// Mirrors `MeetingProcessingPipeline.pipelineVersion`; that class is `@MainActor`, so a/// MainActor test guards this literal against drift instead of referencing it here.- static let defaultPipelineVersion = 10+ static let defaultPipelineVersion = 11let asrModel: Stringlet languageCode: Stringdiff --git a/Sources/Fluid/Services/Meeting/MeetingProcessingPipeline.swift b/Sources/Fluid/Services/Meeting/MeetingProcessingPipeline.swiftindex ca2d3c03..19e9e369 100644--- a/Sources/Fluid/Services/Meeting/MeetingProcessingPipeline.swift+++ b/Sources/Fluid/Services/Meeting/MeetingProcessingPipeline.swift@@ -18,8 +18,8 @@ actor MeetingProcessingSerializationGate {private var isLeased = falseprivate 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.+ /// 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 {@@ -67,8 +67,8 @@ actor MeetingProcessingSerializationGate {/// 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: Sendable {- nonisolated struct Prototype: Equatable, Sendable {+nonisolated struct MeetingSpeakerEmbeddingIndex {+ nonisolated struct Prototype: Equatable {var speakerID: SessionSpeakerIDvar embedding: [Float]var observationCount: Int@@ -187,8 +187,8 @@ nonisolated struct MeetingSpeakerEmbeddingIndex: Sendable {/// 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: Sendable {- nonisolated struct Observation: Sendable, Equatable {+nonisolated struct MeetingGlobalSpeakerStitcher {+ nonisolated struct Observation: Equatable {let key: Stringlet chunkKey: Stringlet trackKind: MeetingAudioTrackKind@@ -216,7 +216,7 @@ nonisolated struct MeetingGlobalSpeakerStitcher: Sendable {}}- nonisolated struct Prototype: Sendable, Equatable {+ nonisolated struct Prototype: Equatable {let speakerID: SessionSpeakerIDlet embedding: [Float]let observationCount: Int@@ -225,13 +225,13 @@ nonisolated struct MeetingGlobalSpeakerStitcher: Sendable {let containsReliableCore: Bool}- nonisolated struct Result: Sendable, Equatable {+ 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: Sendable, Equatable {+ struct Configuration: Equatable {var coreMaximumDistance: Float = 0.35var deferredMaximumDistance: Float = 0.25var deferredAmbiguityMargin: Float = 0.10@@ -423,11 +423,11 @@ nonisolated struct MeetingGlobalSpeakerStitcher: Sendable {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+ self.coreClustersRespectDiameter(clusters[left], clusters[right]),+ let distance = MeetingSpeakerEmbeddingIndex.cosineDistance(+ clusters[left].embedding, clusters[right].embedding+ ),+ distance <= self.configuration.coreMaximumDistanceelse { continue }let candidate = (left, right, distance)if best == nil || distance < best!.distance@@ -557,7 +557,7 @@ nonisolated enum MeetingNearFieldGate {}static func isNearField(rms: Double, reference: Double?) -> Bool {- guard rms >= Self.absoluteFloorRMS else { return false }+ guard rms >= self.absoluteFloorRMS else { return false }guard let reference, reference > 0 else { return true }return rms >= reference * pow(10, -Self.rejectionDepthDB / 20)}@@ -656,16 +656,15 @@ private final class MeetingProviderLanguagePin {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.- static let pipelineVersion = 10+ static let pipelineVersion = 11/// 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+ supportsWordTimings ? self.meetingTurnMergeGapSeconds : self.perTurnTurnMergeGapSeconds}/// Claiming the whole chunk marks every concurrent mic turn as overlapping remote, erasing@@ -704,7 +703,7 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {prototypeSpeakerIDs: Set<SessionSpeakerID>) -> SessionSpeakerID? {MeetingLocalSpeakerEvidenceSelector.candidate(- evidenceDurationByCluster: Self.localSpeakerEvidence(+ evidenceDurationByCluster: self.localSpeakerEvidence(from: turns.map {(clusterID: $0.clusterID, start: $0.start, end: $0.end,@@ -849,7 +848,7 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {fileURL: URL,turns: [(start: TimeInterval, end: TimeInterval)]) -> [Double] {- guard let samples = try? Self.readSamples(fileURL: fileURL, startSeconds: 0, endSeconds: nil),+ guard let samples = try? readSamples(fileURL: fileURL, startSeconds: 0, endSeconds: nil),!samples.isEmptyelse { return Array(repeating: 0, count: turns.count) }let sampleRate = 16_000.0@@ -1022,7 +1021,9 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {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 }+ for index in startIndex..<endIndex {+ result[index] = 0+ }}return result}@@ -1314,13 +1315,60 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {private let asrServiceProvider: @MainActor () -> ASRServiceprivate let serializationGate: MeetingProcessingSerializationGate+ private let backendRegistry: MeetingTranscriptionBackendRegistry+ private let backendIDProvider: @MainActor () -> MeetingBackendID+ /// 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+ /// 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) -> Voidinit(asrServiceProvider: @escaping @MainActor () -> ASRService,- serializationGate: MeetingProcessingSerializationGate = .shared+ serializationGate: MeetingProcessingSerializationGate = .shared,+ backendRegistry: MeetingTranscriptionBackendRegistry? = nil,+ backendID: MeetingBackendID? = nil,+ backendIDProvider: (@MainActor () -> MeetingBackendID)? = nil,+ chunkObserver: (any MeetingChunkAudioObserving)? = nil,+ echoVerdictProvider: (any MeetingUnitEchoVerdictProviding)? = nil,+ meetingRuntimeFactory: MeetingParakeetNemotronRuntimeFactory? = nil,+ canonicalSidecarVerifiedProbe: ((MeetingResultSidecarReference) -> Void)? = nil) {self.asrServiceProvider = asrServiceProviderself.serializationGate = serializationGate+ self.chunkObserver = chunkObserver+ self.echoVerdictProvider = echoVerdictProvider+ self.meetingRuntimeFactory = meetingRuntimeFactory ?? { [asrServiceProvider] _ in+ MeetingParakeetNemotronRuntime(+ asrServiceProvider: asrServiceProvider,+ modelLocator: MeetingNemotronModelLocator()+ )+ }+ 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 = { backendID }+ } else if let backendIDProvider {+ self.backendIDProvider = backendIDProvider+ } else if let backendRegistry {+ let registryDefault = backendRegistry.defaultBackendID+ self.backendIDProvider = { registryDefault }+ } else {+ self.backendIDProvider = { SettingsStore.shared.meetingTranscriptionBackendID }+ }}func process(@@ -1335,24 +1383,344 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {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()+ 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(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)+ }+ )+ )+ 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: MeetingProcessingResultdo {- let result = try await self.processWithLease(- session: session,- sessionDirectory: sessionDirectory,- progress: progress- )- await self.serializationGate.release()- return result+ // 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()+ switch plan.resultContract {+ case .legacyResult:+ // No manifest is built and no sidecar is written on this path: the legacy+ // workflow keeps its own mapping, checkpoints and byte-identical output.+ let outcome = try await backend.execute(plan: plan, manifest: nil, progress: progress)+ // A backend that does not cooperate with cancellation still must not publish. The+ // caller's generation owns publication and has already been torn down, so a+ // successful result arriving after cancellation is suppressed rather than returned.+ try Task.checkCancellation()+ guard case let .legacyCompatibility(legacyResult) = outcome else {+ throw MeetingBackendError.outcomeContractMismatch(+ backend: backendID, declared: .legacyResult+ )+ }+ result = legacyResult+ case .canonicalEvidence:+ result = try await self.processCanonicalAttempt(+ plan: plan,+ backend: backend,+ progress: progress+ )+ }} 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?+ }++ /// Canonical evidence remains word-granular in the sidecar, but product session JSON and UI+ /// rows stay turn-granular. Merge only segments with identical attribution and state, bounded+ /// by the same 3-second/30-second policy used by aligned legacy meeting turns.+ nonisolated static func mergeCanonicalSegments(+ _ segments: [MeetingTranscriptSegment],+ maximumGapSeconds: TimeInterval = 3,+ maximumDurationSeconds: TimeInterval = 30+ ) -> [MeetingTranscriptSegment] {+ let grouped = Dictionary(grouping: segments) {+ CanonicalSegmentMergeKey(+ trackID: $0.sourceTrackID,+ speakerID: $0.speakerID,+ overlap: $0.overlap.rawValue,+ status: $0.status.rawValue,+ completeness: $0.completeness.rawValue,+ isLikelyEcho: $0.isLikelyEcho+ )+ }+ var merged: [MeetingTranscriptSegment] = []+ for members in grouped.values {+ let ordered = members.sorted {+ ($0.start, $0.end, $0.id.uuidString) < ($1.start, $1.end, $1.id.uuidString)+ }+ guard var current = ordered.first else { continue }+ var memberIDs = [current.id]+ for next in ordered.dropFirst() {+ let gap = next.start.seconds - current.end.seconds+ let combinedDuration = max(current.end.seconds, next.end.seconds) - current.start.seconds+ if 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+ memberIDs = [next.id]+ }+ }+ merged.append(current)+ }+ return merged.sorted {+ ($0.start, $0.end, $0.sourceTrackID.uuidString, $0.id.uuidString)+ < ($1.start, $1.end, $1.sourceTrackID.uuidString, $1.id.uuidString)+ }+ }++ private nonisolated static func joinTranscriptText(_ left: String, _ right: String) -> String {+ guard let first = right.first else { return left }+ if CharacterSet.punctuationCharacters.contains(first.unicodeScalars.first!) {+ 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()@@ -1374,7 +1742,7 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {guard provider.isReady else { throw MeetingProcessingError.modelUnavailable }var attempt = MeetingProcessingAttempt(- id: session.processingAttempts.last(where: { $0.completedAt == nil })?.id ?? UUID(),+ id: attemptID,startedAt: Date(),completedAt: nil,stage: .identifyingSpeakers,@@ -1535,7 +1903,7 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {}private static func loadCheckpoint(sessionDirectory: URL) -> MeetingProcessingCheckpoint? {- guard let data = try? Data(contentsOf: Self.checkpointURL(sessionDirectory: sessionDirectory)) else { return nil }+ guard let data = try? Data(contentsOf: checkpointURL(sessionDirectory: sessionDirectory)) else { return nil }return try? Self.checkpointDecoder.decode(MeetingProcessingCheckpoint.self, from: data)}@@ -1554,7 +1922,7 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {}private static func deleteCheckpoint(sessionDirectory: URL) {- try? FileManager.default.removeItem(at: Self.checkpointURL(sessionDirectory: sessionDirectory))+ try? FileManager.default.removeItem(at: self.checkpointURL(sessionDirectory: sessionDirectory))}private func processApplicationTrack(@@ -1601,7 +1969,9 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {) {guard !pendingTurns.isEmpty else { return }var observationsByKey: [String: MeetingGlobalSpeakerStitcher.Observation] = [:]- for pending in pendingTurns { observationsByKey[pending.observation.key] = pending.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)@@ -2431,7 +2801,7 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {}nonisolated static func tooManyWordsUnassigned(unassigned: Int, totalWords: Int) -> Bool {- totalWords > 0 && Double(unassigned) > Double(totalWords) * Self.maxUnassignedWordFraction+ totalWords > 0 && Double(unassigned) > Double(totalWords) * self.maxUnassignedWordFraction}private func transcribeTurnsWordAligned(@@ -2681,7 +3051,7 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {)}- private static func mediaTime(_ seconds: TimeInterval) -> MeetingMediaTime {+ private nonisolated static func mediaTime(_ seconds: TimeInterval) -> MeetingMediaTime {MeetingMediaTime(value: Int64((max(0, seconds) * 1000).rounded()), timescale: 1000)}diff --git a/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift b/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swiftindex a7c6e891..d9e837b2 100644--- a/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift+++ b/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift@@ -133,36 +133,45 @@ final class MeetingSessionCoordinator: ObservableObject {private var startReservation: UUID? {willSet { if (newValue != nil) != (self.startReservation != nil) { self.objectWillChange.send() } }}+private var liveTranscriptionCoordinator: MeetingLiveTranscriptionCoordinator?private var captureGeneration: UUID?private var operationGeneration: UUID?private var stopTask: Task<MeetingSession, Error>? {willSet { if (newValue == nil) != (self.stopTask == nil) { self.objectWillChange.send() } }}+private var interruptionTask: Task<Void, Never>?private var terminationTask: Task<Void, Never>?private var retryTask: Task<MeetingSession, Error>? {willSet { if (newValue == nil) != (self.retryTask == nil) { self.objectWillChange.send() } }}+private var persistenceTail: Task<Void, Never>?private var persistenceGeneration = 0private var restoreTask: Task<Void, Never>?private var isDeleting = false {willSet { if newValue != self.isDeleting { self.objectWillChange.send() } }}+private var isMutatingSession = false {willSet { if newValue != self.isMutatingSession { self.objectWillChange.send() } }}+private var sweepPending = falseprivate var retentionTimerTask: Task<Void, Never>?private enum TranscriptCorrection {case rename(speakerID: SessionSpeakerID, previousName: String)case reassign(segmentID: MeetingTranscriptSegmentID, previousSpeakerID: SessionSpeakerID?, previousRevision: Int)- case merge(sourceID: SessionSpeakerID, targetID: SessionSpeakerID,- movedSegments: [(id: MeetingTranscriptSegmentID, previousRevision: Int)])+ case merge(+ sourceID: SessionSpeakerID,+ targetID: SessionSpeakerID,+ movedSegments: [(id: MeetingTranscriptSegmentID, previousRevision: Int)]+ )case renameBatch([(speakerID: SessionSpeakerID, previousName: String)])}+private var correctionUndoStacks: [MeetingSessionID: [TranscriptCorrection]] = [:]private static let correctionUndoStackCap = 50@@ -193,7 +202,9 @@ final class MeetingSessionCoordinator: ObservableObject {}}- var hasPendingStart: Bool { self.startReservation != nil }+ var hasPendingStart: Bool {+ self.startReservation != nil+ }/// A recovery offer is not audio ownership. Only matching terminal states may/// be displaced; preparing/stopping and inconsistent states remain blocked.@@ -364,7 +375,8 @@ final class MeetingSessionCoordinator: ObservableObject {guard self.startReservation == reservation,self.activeSession?.id == passiveOffer?.id,!self.hasBlockingActivityTaskExceptStart,- self.canBeginNewRecording, !self.isDeleting, !self.isMutatingSession else {+ self.canBeginNewRecording, !self.isDeleting, !self.isMutatingSession+ else {throw CancellationError()}} catch {@@ -444,7 +456,8 @@ final class MeetingSessionCoordinator: ObservableObject {self.state = .recording(session.id)try await self.store.save(session)guard self.startReservation == reservation,- self.operationGeneration == generation, !Task.isCancelled else {+ self.operationGeneration == generation, !Task.isCancelled+ else {throw CancellationError()}if let resolvingSourceID {@@ -452,12 +465,14 @@ final class MeetingSessionCoordinator: ObservableObject {// Record Again resolution against queued corrections/deletes.await self.flushQueuedPersistence()guard self.startReservation == reservation,- self.operationGeneration == generation, !Task.isCancelled else {+ self.operationGeneration == generation, !Task.isCancelled+ else {throw CancellationError()}if var source = try? await self.store.load(id: resolvingSourceID) {guard self.startReservation == reservation,- self.operationGeneration == generation, !Task.isCancelled else {+ self.operationGeneration == generation, !Task.isCancelled+ else {throw CancellationError()}source.recoveryResolvedAt = Date()@@ -470,7 +485,8 @@ final class MeetingSessionCoordinator: ObservableObject {}}guard self.startReservation == reservation,- self.operationGeneration == generation, !Task.isCancelled else {+ self.operationGeneration == generation, !Task.isCancelled+ else {throw CancellationError()}Task { @MainActor [weak self] in await self?.sweepExpiredAudio() }@@ -727,10 +743,9 @@ final class MeetingSessionCoordinator: ObservableObject {_ snapshot: MeetingSession,configuration: MeetingCaptureConfiguration) async throws -> MeetingSession {- let newSession = try await self.startRecording(- configuration: configuration, passiveOffer: snapshot, resolvingSourceID: snapshot.id- )- return newSession+ return try await self.startRecording(+ configuration: configuration, passiveOffer: snapshot, resolvingSourceID: snapshot.id+ )}private func recordAgainFromHistory(@@ -1064,7 +1079,9 @@ final class MeetingSessionCoordinator: ObservableObject {}/// Exposed for tests only: whether a future-deadline sweep is currently scheduled.- var hasScheduledRetentionSweep: Bool { self.retentionTimerTask != nil }+ var hasScheduledRetentionSweep: Bool {+ self.retentionTimerTask != nil+ }private func scheduleRetentionTimer(nextDeadline: Date?) {self.retentionTimerTask?.cancel()@@ -1418,6 +1435,16 @@ final class MeetingSessionCoordinator: ObservableObject {session.speakers = result.speakerssession.transcriptSegments = result.segmentssession.transcriptCoverageGaps = result.coverageGaps.isEmpty ? nil : result.coverageGaps+ // Canonical attempts carry a sidecar that was already written and read-back verified+ // by the pipeline; legacy attempts leave this nil. The reference only becomes durable+ // with the session save below, and the checkpoint survives until that save succeeds.+ session.resultSidecarReference = result.resultSidecarReference+ session.transcriptIsComplete = result.resultSidecarReference == nil+ ? nil+ : result.isComplete+ if result.resultSidecarReference != nil {+ session.transcriptTimeDomain = .meetingRelative+ }session.processingAttempts.removeAll {$0.completedAt == nil && $0.id != result.attempt.id}@@ -1447,15 +1474,40 @@ final class MeetingSessionCoordinator: ObservableObject {let excludedSeconds = result.coverageGaps.reduce(0.0) { total, gap intotal + max(0, gap.end - gap.start)}+ let allUnprotectedMicrophone = result.coverageGaps.allSatisfy {+ $0.reason == .unprotectedMicrophone+ }+ let allMicrophoneAdmission = result.coverageGaps.allSatisfy {+ $0.reason == .unprotectedMicrophone || $0.reason == .inadmissibleCaptureEra+ }session.events.append(MeetingSessionEvent(id: UUID(),occurredAt: Date(),- kind: .microphoneChanged,+ kind: .transcriptCoverageIncomplete,trackID: result.coverageGaps.first?.trackID,- detail: String(- format: "%.1f seconds of unprotected microphone audio were excluded from the transcript.",- excludedSeconds- )+ detail: allUnprotectedMicrophone+ ? String(+ format: "%.1f seconds of unprotected microphone audio were excluded from the transcript.",+ excludedSeconds+ )+ : allMicrophoneAdmission+ ? String(+ format: "%.1f seconds of microphone audio were excluded because capture admission was not verified.",+ excludedSeconds+ )+ : String(+ format: "%.1f seconds of meeting audio have no transcript coverage.",+ excludedSeconds+ )+ ))+ }+ if !result.isComplete, result.coverageGaps.isEmpty {+ session.events.append(MeetingSessionEvent(+ id: UUID(),+ occurredAt: Date(),+ kind: .transcriptCoverageIncomplete,+ trackID: nil,+ detail: "Some recognized text could not be safely placed on the meeting timeline."))}session.state = .completed@@ -1479,6 +1531,12 @@ final class MeetingSessionCoordinator: ObservableObject {throw error}if error is CancellationError {+ session.speakers = inputSession.speakers+ session.transcriptSegments = inputSession.transcriptSegments+ session.transcriptCoverageGaps = inputSession.transcriptCoverageGaps+ session.resultSidecarReference = inputSession.resultSidecarReference+ session.transcriptIsComplete = inputSession.transcriptIsComplete+ session.transcriptTimeDomain = inputSession.transcriptTimeDomainsession.state = .interruptedsession.updatedAt = Date()await self.flushQueuedPersistence()@@ -1490,6 +1548,15 @@ final class MeetingSessionCoordinator: ObservableObject {throw error}let failure = Self.failure(from: error, domain: .processing, recoverable: true)+ // A failed completed-session save must not durably publish a sidecar or overwrite the+ // last saved transcript under `.failed`. The verified new sidecar remains unreferenced+ // for retry/journal reconciliation.+ session.speakers = inputSession.speakers+ session.transcriptSegments = inputSession.transcriptSegments+ session.transcriptCoverageGaps = inputSession.transcriptCoverageGaps+ session.resultSidecarReference = inputSession.resultSidecarReference+ session.transcriptIsComplete = inputSession.transcriptIsComplete+ session.transcriptTimeDomain = inputSession.transcriptTimeDomainif let lastIndex = session.processingAttempts.indices.last {session.processingAttempts[lastIndex].errorCode = failure.codesession.processingAttempts[lastIndex].completedAt = Date()diff --git a/Sources/Fluid/Services/Meeting/MeetingSessionStore.swift b/Sources/Fluid/Services/Meeting/MeetingSessionStore.swiftindex cedbad12..4f908428 100644--- a/Sources/Fluid/Services/Meeting/MeetingSessionStore.swift+++ b/Sources/Fluid/Services/Meeting/MeetingSessionStore.swift@@ -1,3 +1,5 @@+import CryptoKit+import Darwinimport Foundationnonisolated protocol MeetingSessionStoring: Sendable {@@ -101,10 +103,11 @@ actor MeetingSessionStore: MeetingSessionStoring {guard self.fileSystem.manager.fileExists(atPath: url.path) else { return nil }let session = try self.decodeSession(at: url)let reconciled = try self.reconcileTrackManifests(in: session)- if reconciled != session {- try self.writeSession(reconciled)+ let migrated = self.migrateCanonicalTranscriptTimelineIfNeeded(reconciled)+ if migrated != session {+ try self.writeSession(migrated)}- return reconciled+ return migrated}func loadAll() throws -> [MeetingSession] {@@ -201,6 +204,123 @@ actor MeetingSessionStore: MeetingSessionStoring {return session}+ /// Canonical sessions published before the explicit timeline-domain marker stored product+ /// segment/gap times in absolute host presentation seconds. The immutable sidecar remains in+ /// analysis time and carries the verified presentation origin, so migrate only `session.json`+ /// once and never rewrite the sidecar it references.+ private func migrateCanonicalTranscriptTimelineIfNeeded(+ _ inputSession: MeetingSession+ ) -> MeetingSession {+ guard inputSession.transcriptTimeDomain == nil,+ let reference = inputSession.resultSidecarReference,+ let attempt = inputSession.processingAttempts.last(where: {+ $0.backendID != nil+ && MeetingResultSidecarStore.fileName(for: $0.id) == reference.fileName+ }),+ let backendID = attempt.backendID.map({ MeetingBackendID(rawValue: $0) })+ else { return inputSession }++ let directory = self.sessionDirectoryURL(for: inputSession.id)+ let verifiedOrigin: TimeInterval?+ do {+ let sidecar = try MeetingResultSidecarStore(sessionDirectory: directory).read(+ expectedAttemptID: attempt.id,+ expectedBackendID: backendID,+ reference: reference+ )+ verifiedOrigin = sidecar.analysisManifest.presentationOriginSeconds+ } catch {+ verifiedOrigin = nil+ DebugLogger.shared.warning(+ "Could not verify canonical transcript sidecar while migrating timeline for "+ + "\(inputSession.id): \(error.localizedDescription)",+ source: "MeetingSessionStore"+ )+ }++ let origin = verifiedOrigin ?? inputSession.timebase.firstPresentationTime?.seconds+ guard let origin,+ let migrated = Self.migratingCanonicalTimelineToMeetingRelative(+ inputSession,+ presentationOriginSeconds: origin+ )+ else {+ DebugLogger.shared.warning(+ "Canonical transcript timeline for \(inputSession.id) could not be migrated safely.",+ source: "MeetingSessionStore"+ )+ return inputSession+ }+ DebugLogger.shared.info(+ "Migrated canonical transcript timeline to meeting-relative seconds for \(inputSession.id).",+ source: "MeetingSessionStore"+ )+ return migrated+ }++ /// Pure migration seam used by load-time recovery and tests. A negative result beyond the+ /// rounding tolerance means the supplied origin does not describe this transcript, so refuse+ /// the whole migration instead of partially shifting or guessing.+ nonisolated static func migratingCanonicalTimelineToMeetingRelative(+ _ inputSession: MeetingSession,+ presentationOriginSeconds origin: TimeInterval+ ) -> MeetingSession? {+ guard inputSession.transcriptTimeDomain == nil, origin.isFinite, origin >= 0 else {+ return nil+ }+ let tolerance = MeetingAnalysisManifestSchema.mappingToleranceSeconds+ var migrated = inputSession++ for index in migrated.transcriptSegments.indices {+ let start = migrated.transcriptSegments[index].start.seconds - origin+ let end = migrated.transcriptSegments[index].end.seconds - origin+ guard start.isFinite, end.isFinite,+ start >= -tolerance,+ end + tolerance >= start,+ let shiftedStart = Self.mediaTime(+ seconds: max(0, start),+ timescale: migrated.transcriptSegments[index].start.timescale+ ),+ let shiftedEnd = Self.mediaTime(+ seconds: max(max(0, start), end),+ timescale: migrated.transcriptSegments[index].end.timescale+ )+ else { return nil }+ migrated.transcriptSegments[index].start = shiftedStart+ migrated.transcriptSegments[index].end = shiftedEnd+ }++ if var gaps = migrated.transcriptCoverageGaps {+ for index in gaps.indices {+ let start = gaps[index].start - origin+ let end = gaps[index].end - origin+ guard start.isFinite, end.isFinite,+ start >= -tolerance,+ end + tolerance >= start+ else { return nil }+ gaps[index].start = max(0, start)+ gaps[index].end = max(gaps[index].start, end)+ }+ migrated.transcriptCoverageGaps = gaps+ }++ migrated.transcriptTimeDomain = .meetingRelative+ return migrated+ }++ private nonisolated static func mediaTime(+ seconds: TimeInterval,+ timescale: Int32+ ) -> MeetingMediaTime? {+ guard seconds.isFinite, seconds >= 0, timescale > 0 else { return nil }+ let scaled = seconds * Double(timescale)+ guard scaled.isFinite,+ scaled >= Double(Int64.min),+ scaled <= Double(Int64.max)+ else { return nil }+ return MeetingMediaTime(value: Int64(scaled.rounded()), timescale: timescale)+ }+private func reconcileTrackManifests(in inputSession: MeetingSession) throws -> MeetingSession {var session = inputSession@@ -275,6 +395,12 @@ actor MeetingSessionStore: MeetingSessionStoring {_ inputChunk: MeetingAudioChunk,sessionDirectory: URL) -> MeetingAudioChunk {+ // New asset metadata is an explicit one-way boundary. Never apply the legacy+ // size-repair rule to it: a staged/foreign file must not become trusted merely because it+ // exists. Sessions with no new metadata retain the exact historical AAC behavior below.+ if inputChunk.audioSchemaVersion != nil || inputChunk.captureAnalysisAsset != nil || inputChunk.playbackArchiveAsset != nil {+ return self.reconcileNewAssetChunk(inputChunk, sessionDirectory: sessionDirectory)+ }guard inputChunk.finalizationState == .finalized else { return inputChunk }let fileURL = inputChunk.fileURL(relativeTo: sessionDirectory).standardizedFileURLlet rootPath = sessionDirectory.standardizedFileURL.path + "/"@@ -295,6 +421,90 @@ actor MeetingSessionStore: MeetingSessionStoring {return reconciled}+ private func reconcileNewAssetChunk(+ _ inputChunk: MeetingAudioChunk,+ sessionDirectory: URL+ ) -> MeetingAudioChunk {+ var failed = inputChunk+ func failCapture(_ chunk: inout MeetingAudioChunk) {+ chunk.sha256 = ""+ chunk.byteCount = 0+ chunk.finalizationState = .failed+ if var asset = chunk.captureAnalysisAsset, asset.presence == .ready { asset.presence = .failed; chunk.captureAnalysisAsset = asset }+ }+ guard let capture = inputChunk.captureAnalysisAsset,+ capture.role == .captureAnalysis,+ capture.presence == .ready,+ capture.validationIssues().isEmpty,+ self.assetMatchesDisk(capture, sessionDirectory: sessionDirectory)+ else {+ failCapture(&failed)+ return failed+ }+ var reconciled = inputChunk+ if var archive = reconciled.playbackArchiveAsset,+ archive.presence == .ready,+ (!archive.validationIssues().isEmpty || !self.assetMatchesDisk(archive, sessionDirectory: sessionDirectory))+ {+ // The archive is derived and optional. Quarantine only it; authoritative PCM remains+ // finalized and retryable for a later archive job.+ archive.presence = .failed+ reconciled.playbackArchiveAsset = archive+ }+ reconciled.byteCount = capture.byteCount+ reconciled.sha256 = capture.sha256 ?? ""+ reconciled.finalizationState = .finalized+ return reconciled+ }++ private func assetMatchesDisk(_ asset: MeetingAudioAsset, sessionDirectory: URL) -> Bool {+ guard let url = self.confinedRegularAssetURL(+ relativePath: asset.relativeFilePath,+ sessionDirectory: sessionDirectory+ ), let attributes = try? self.fileSystem.manager.attributesOfItem(atPath: url.path),+ let size = (attributes[.size] as? NSNumber)?.int64Value,+ size == asset.byteCount,+ size > 0,+ let expectedHash = asset.sha256,+ let hash = self.sha256(of: url),+ hash == expectedHash+ else { return false }+ return true+ }++ /// Lexical confinement plus an lstat walk. A descriptor-relative walk is intentionally outside+ /// this additive foundation; concurrent path replacement remains a documented TOCTOU limit.+ private func confinedRegularAssetURL(relativePath: String, sessionDirectory: URL) -> URL? {+ let parts = relativePath.split(separator: "/", omittingEmptySubsequences: false).map(String.init)+ guard !relativePath.isEmpty, !relativePath.hasPrefix("/"), !parts.isEmpty,+ parts.allSatisfy({ !$0.isEmpty && $0 != "." && $0 != ".." }) else { return nil }+ var current = sessionDirectory.standardizedFileURL+ var rootStat = stat()+ guard lstat(current.path, &rootStat) == 0, (rootStat.st_mode & S_IFMT) != S_IFLNK else { return nil }+ for part in parts {+ current.appendPathComponent(part, isDirectory: false)+ var info = stat()+ guard lstat(current.path, &info) == 0, (info.st_mode & S_IFMT) != S_IFLNK else { return nil }+ }+ var final = stat()+ guard lstat(current.path, &final) == 0, (final.st_mode & S_IFMT) == S_IFREG else { return nil }+ return current+ }++ private func sha256(of url: URL) -> String? {+ guard let handle = try? FileHandle(forReadingFrom: url) else { return nil }+ defer { try? handle.close() }+ var digest = SHA256()+ while true {+ let data: Data+ do { data = try handle.read(upToCount: 1 << 20) ?? Data() }+ catch { return nil }+ guard !data.isEmpty else { break }+ digest.update(data: data)+ }+ return digest.finalize().map { String(format: "%02x", $0) }.joined()+ }+private func prepareRootDirectory() throws {if !self.fileSystem.manager.fileExists(atPath: self.rootDirectory.path) {try self.createPrivateDirectory(self.rootDirectory)diff --git a/Sources/Fluid/UI/MeetingAudioPresentation.swift b/Sources/Fluid/UI/MeetingAudioPresentation.swiftnew file mode 100644index 00000000..7acc5fa6--- /dev/null+++ b/Sources/Fluid/UI/MeetingAudioPresentation.swift@@ -0,0 +1,38 @@+import Foundation++/// Resolves the audio representation used by meeting history actions.+///+/// PCM is the authoritative representation during processing. Once a verified archive exists,+/// history actions prefer it; otherwise they use the finalized PCM path recorded on the chunk.+/// This keeps `.caf` capture assets visible without guessing a `.m4a` filename.+nonisolated enum MeetingAudioPresentation {+ static func relativePlaybackPath(for chunk: MeetingAudioChunk) -> String? {+ if let archive = chunk.playbackArchiveAsset, archive.presence == .ready,+ !archive.relativeFilePath.isEmpty+ {+ return archive.relativeFilePath+ }+ guard chunk.finalizationState == .finalized, chunk.byteCount > 0,+ !chunk.relativeFilePath.isEmpty else { return nil }+ return chunk.relativeFilePath+ }++ static func firstPlaybackURL(+ in session: MeetingSession,+ directory: URL,+ fileManager: FileManager = .default+ ) -> URL? {+ for chunk in session.audioTracks+ .flatMap(\.chunks)+ .sorted(by: { $0.sequence < $1.sequence })+ {+ guard let relativePath = relativePlaybackPath(for: chunk) else { continue }+ guard let url = try? MeetingChunkPathConfinement.containedURL(+ sessionDirectory: directory,+ relativePath: relativePath+ ) else { continue }+ if fileManager.fileExists(atPath: url.path) { return url }+ }+ return nil+ }+}diff --git a/Sources/Fluid/UI/MeetingTranscriptionView.swift b/Sources/Fluid/UI/MeetingTranscriptionView.swiftindex 7d50e451..68cc4221 100644--- a/Sources/Fluid/UI/MeetingTranscriptionView.swift+++ b/Sources/Fluid/UI/MeetingTranscriptionView.swift@@ -405,7 +405,8 @@ struct MeetingTranscriptionView: View {} else if self.setupDraft.mode == .onlineCall, !meetingAudioReady {blockingMessage = "Allow Screen & System Audio access, then refresh sources."} else if !self.cachedStorageReady {- blockingMessage = "Free at least 512 MB of storage before recording."+ let trackCount = MeetingPCMStoragePolicy.trackCount(for: self.setupDraft.mode)+ blockingMessage = "Free at least \(MeetingPCMStoragePolicy.requiredFreeSpaceDescription(trackCount: trackCount)) of storage before recording."} else {blockingMessage = nil}@@ -802,11 +803,14 @@ struct MeetingTranscriptionView: View {self.actionErrorMessage = "Captured audio could not be revealed: recording no longer on disk."return}- let firstAudioURL = freshSession.audioTracks- .flatMap(\.chunks)- .first(where: { $0.finalizationState == .finalized && $0.byteCount > 0 })?- .fileURL(relativeTo: directory)- NSWorkspace.shared.activateFileViewerSelecting([firstAudioURL ?? directory])+ guard let firstAudioURL = MeetingAudioPresentation.firstPlaybackURL(+ in: freshSession,+ directory: directory+ ) else {+ self.actionErrorMessage = "Captured audio is still preparing or is no longer available on disk."+ return+ }+ NSWorkspace.shared.activateFileViewerSelecting([firstAudioURL])} catch {self.actionErrorMessage = "Captured audio could not be revealed: \(error.localizedDescription)"}@@ -1052,12 +1056,12 @@ struct MeetingTranscriptionView: View {self.cachedModelReady = self.asrService.isAsrReady ||self.asrService.modelsExistOnDisk ||SettingsStore.shared.selectedSpeechModel.isInstalled- let storage = Self.storageReadiness()+ let storage = Self.storageReadiness(trackCount: MeetingPCMStoragePolicy.trackCount(for: self.setupDraft.mode))self.cachedStorageStatus = storage.statusself.cachedStorageReady = storage.ready}- private static func storageReadiness() -> (status: String, ready: Bool) {+ private static func storageReadiness(trackCount: Int) -> (status: String, ready: Bool) {guard let applicationSupport = FileManager.default.urls(for: .applicationSupportDirectory,in: .userDomainMask@@ -1068,7 +1072,7 @@ struct MeetingTranscriptionView: View {else {return ("Storage availability unavailable", false)}- let requiredBytes: Int64 = 512 * 1024 * 1024+ let requiredBytes = MeetingPCMStoragePolicy.requiredFreeBytes(trackCount: trackCount)let formatter = ByteCountFormatter()formatter.countStyle = .filereturn ("\(formatter.string(fromByteCount: capacity)) available", capacity >= requiredBytes)diff --git a/Tests/FluidDictationIntegrationTests/MeetingASRPreparationOwnerTests.swift b/Tests/FluidDictationIntegrationTests/MeetingASRPreparationOwnerTests.swiftindex 6acb87b4..06c65f40 100644--- a/Tests/FluidDictationIntegrationTests/MeetingASRPreparationOwnerTests.swift+++ b/Tests/FluidDictationIntegrationTests/MeetingASRPreparationOwnerTests.swift@@ -196,6 +196,22 @@ private final class DeallocationProvider: TranscriptionProvider, @unchecked Send}}+/// Bounded observation that never owns or cancels the operation being observed. Tests open+/// their gates and join their task handles after observation, so non-cooperative hooks cannot+/// strand a throwing timeout task-group child.+@MainActor+private func waitUntilCondition(+ timeoutNanoseconds: UInt64 = 5_000_000_000,+ condition: @escaping @MainActor () -> Bool+) async -> Bool {+ let deadline = DispatchTime.now().uptimeNanoseconds + timeoutNanoseconds+ while !condition() {+ if DispatchTime.now().uptimeNanoseconds >= deadline { return false }+ try? await Task.sleep(nanoseconds: 1_000_000)+ }+ return true+}+@MainActorfinal class MeetingASRPreparationOwnerTests: XCTestCase {@MainActor private final class Harness {@@ -284,21 +300,6 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {return secondWaiterEntered}- /// Bounded observation that never owns or cancels the operation being observed. Tests open- /// their gates and join their task handles after observation, so non-cooperative hooks cannot- /// strand a throwing timeout task-group child.- private func waitUntil(- timeoutNanoseconds: UInt64 = 5_000_000_000,- condition: @escaping @MainActor () -> Bool- ) async -> Bool {- let deadline = DispatchTime.now().uptimeNanoseconds + timeoutNanoseconds- while !condition() {- if DispatchTime.now().uptimeNanoseconds >= deadline { return false }- try? await Task.sleep(nanoseconds: 1_000_000)- }- return true- }-func testRejectsInvalidLeaseBeforeAnyMutationOrDependencyCall() async {let harness = self.makeHarness()let lease = self.makeLease()@@ -459,7 +460,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {)return ObjectIdentifier(provider as AnyObject)}- let enteredObserved = await self.waitUntil { entered.opened }+ let enteredObserved = await waitUntilCondition { entered.opened }XCTAssertTrue(enteredObserved)let second = Task { @MainActor in@@ -497,7 +498,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {lease: lease, attemptID: attempt, configuration: configuration)}- let enteredObserved = await self.waitUntil { entered.opened }+ let enteredObserved = await waitUntilCondition { entered.opened }XCTAssertTrue(enteredObserved)let otherLease = self.makeLease()@@ -559,7 +560,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {lease: lease, attemptID: attemptID, configuration: MeetingFinalProcessingConfiguration())}- let enteredObserved = await self.waitUntil { entered.opened }+ let enteredObserved = await waitUntilCondition { entered.opened }XCTAssertTrue(enteredObserved)preparation.cancel()@@ -627,7 +628,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {lease: lease, attemptID: UUID(), configuration: MeetingFinalProcessingConfiguration())}- let observed = await self.waitUntil { harness.retireEntered.opened }+ let observed = await waitUntilCondition { harness.retireEntered.opened }XCTAssertTrue(observed)preparation.cancel()XCTAssertTrue(harness.owner.isClaimed)@@ -652,7 +653,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {lease: lease, attemptID: UUID(), configuration: MeetingFinalProcessingConfiguration())}- let observed = await self.waitUntil { harness.retireEntered.opened }+ let observed = await waitUntilCondition { harness.retireEntered.opened }XCTAssertTrue(observed)harness.registry.deactivateAll()harness.retireGate.open()@@ -697,13 +698,13 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {lease: lease, attemptID: UUID(), configuration: MeetingFinalProcessingConfiguration())}- let enteredObserved = await self.waitUntil { entered.opened }+ let enteredObserved = await waitUntilCondition { entered.opened }XCTAssertTrue(enteredObserved)let token = try XCTUnwrap(harness.owner.currentClaimToken)harness.drainGate.reset()let release = Task { @MainActor in await harness.owner.release(token) }providerGate.open()- let drainObserved = await self.waitUntil { harness.recorder.count(of: "drain") == 1 }+ let drainObserved = await waitUntilCondition { harness.recorder.count(of: "drain") == 1 }XCTAssertTrue(drainObserved)XCTAssertEqual(harness.recorder.count(of: "drain"), 1)harness.drainGate.open()@@ -756,7 +757,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {lease: lease, attemptID: attemptID, configuration: MeetingFinalProcessingConfiguration())}- let enteredObserved = await self.waitUntil { entered.opened }+ let enteredObserved = await waitUntilCondition { entered.opened }XCTAssertTrue(enteredObserved)let second = Task { @MainActor in#if !DEBUG@@ -768,9 +769,9 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {}// Both waiters join the same exact operation; cancellation of one cancels the shared worker.#if DEBUG- let secondObserved = await self.waitUntil { secondWaiterEntered.opened }+ let secondObserved = await waitUntilCondition { secondWaiterEntered.opened }#else- let secondObserved = await self.waitUntil { secondStarted.opened }+ let secondObserved = await waitUntilCondition { secondStarted.opened }#endifXCTAssertTrue(secondObserved)second.cancel()@@ -817,7 +818,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {lease: lease, attemptID: attemptID, configuration: MeetingFinalProcessingConfiguration())}- let enteredObserved = await self.waitUntil { entered.opened }+ let enteredObserved = await waitUntilCondition { entered.opened }XCTAssertTrue(enteredObserved)let second = Task { @MainActor in#if !DEBUG@@ -829,9 +830,9 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {}joinedWaiter = second#if DEBUG- let secondObserved = await self.waitUntil { secondWaiterEntered.opened }+ let secondObserved = await waitUntilCondition { secondWaiterEntered.opened }#else- let secondObserved = await self.waitUntil { secondStarted.opened }+ let secondObserved = await waitUntilCondition { secondStarted.opened }#endifXCTAssertTrue(secondObserved)providerGate.open()@@ -889,7 +890,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {progress: progress)}- let enteredObserved = await self.waitUntil { entered.opened }+ let enteredObserved = await waitUntilCondition { entered.opened }XCTAssertTrue(enteredObserved)let handler = try XCTUnwrap(harness.provider.lastProgressHandler)@@ -917,7 +918,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {let drainEntered = ContinuationGate()harness.drainHook.set { drainEntered.open() }let release = Task { @MainActor in await harness.owner.release(token) }- let drainObserved = await self.waitUntil { drainEntered.opened }+ let drainObserved = await waitUntilCondition { drainEntered.opened }XCTAssertTrue(drainObserved)let staleDuringDrain = self.expectation(description: "no delivery while draining")staleDuringDrain.isInverted = true@@ -965,7 +966,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {progress: { _ in deliveries.record("cancelled") })}- let enteredObserved = await self.waitUntil { entered.opened }+ let enteredObserved = await waitUntilCondition { entered.opened }XCTAssertTrue(enteredObserved)let handler = try XCTUnwrap(harness.provider.lastProgressHandler)preparation.cancel()@@ -999,7 +1000,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {progress: { _ in deliveries.record("invalid") })}- let enteredObserved = await self.waitUntil { entered.opened }+ let enteredObserved = await waitUntilCondition { entered.opened }XCTAssertTrue(enteredObserved)let handler = try XCTUnwrap(harness.provider.lastProgressHandler)harness.registry.deactivateAll()@@ -1034,7 +1035,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {let firstRelease = Task { @MainActor inawait harness.owner.release(token)}- let drainObserved = await self.waitUntil { drainEntered.opened }+ let drainObserved = await waitUntilCondition { drainEntered.opened }XCTAssertTrue(drainObserved)XCTAssertTrue(harness.owner.isClaimed)XCTAssertTrue(harness.owner.isDraining)@@ -1141,7 +1142,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {return false}}- let enteredObserved = await self.waitUntil { providerEntered.opened }+ let enteredObserved = await waitUntilCondition { providerEntered.opened }XCTAssertTrue(enteredObserved)let second = Task { @MainActor in#if !DEBUG@@ -1157,9 +1158,9 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {}}#if DEBUG- let secondObserved = await self.waitUntil { secondWaiterEntered.opened }+ let secondObserved = await waitUntilCondition { secondWaiterEntered.opened }#else- let secondObserved = await self.waitUntil { secondStarted.opened }+ let secondObserved = await waitUntilCondition { secondStarted.opened }#endifXCTAssertTrue(secondObserved)providerGate.open()@@ -1172,3 +1173,502 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {XCTAssertTrue(probe.value)}}++#if DEBUG+private enum ScopeBodyTestError: Error {+ case bodyFailed+}++/// Exercises `ASRService.withPreparedMeetingASR` with the real scope code and the real owner+/// driven by fake dependency closures (injected through the DEBUG owner seam), plus the real+/// production retirement path. No test loads or downloads real ASR models. The seam exists+/// only in DEBUG builds, so the whole suite compiles out of release-config baseline builds.+@MainActor+final class ASRServiceMeetingASRScopeTests: XCTestCase {+ @MainActor private final class Harness {+ let service = ASRService()+ let recorder = OrchestrationRecorder()+ let registry = LeaseRegistry()+ let provider = FakeMeetingTranscriptionProvider()+ let userDownloadInProgress = TestFlag()+ let retireGate = ContinuationGate(open: true)+ let retireEntered = ContinuationGate()+ let drainGate = ContinuationGate(open: true)+ let drainHook = DrainHook()+ let owner: MeetingASRPreparationOwner++ init() {+ let recorder = self.recorder+ let registry = self.registry+ let provider = self.provider+ let userDownloadInProgress = self.userDownloadInProgress+ let retireGate = self.retireGate+ let retireEntered = self.retireEntered+ let drainGate = self.drainGate+ let drainHook = self.drainHook+ self.owner = MeetingASRPreparationOwner(+ isActiveLease: { lease in registry.isActive(lease) },+ isUserDownloadInProgress: { userDownloadInProgress.value },+ retireDictationResources: { _ in+ recorder.record("retire")+ retireEntered.open()+ await retireGate.wait()+ },+ makeProvider: { configuration in+ // The fingerprint proves the scope passes the configuration through untouched.+ recorder.record("factory:\(configuration.identityFingerprint)")+ return provider+ },+ prepareProvider: { preparedProvider, _, progressHandler in+ let identity = preparedProvider as AnyObject === provider+ recorder.record(identity ? "prepare" : "prepare:wrongProvider")+ try await provider.prepare(progressHandler: progressHandler)+ },+ drainExecutor: { _ in+ recorder.record("drain")+ drainHook.fire()+ await drainGate.wait()+ }+ )+ self.service.meetingASRPreparationOwnerForTesting = self.owner+ }++ func openAllGates() {+ self.retireGate.open()+ self.provider.openPrepareGate()+ self.drainGate.open()+ }++ func acquireMeetingLease() throws -> ASRActivityLease {+ let lease = try self.service.acquireExclusiveActivity(.meeting)+ self.registry.activate(lease)+ return lease+ }+ }++ private func makeHarness() -> Harness {+ let harness = Harness()+ self.addTeardownBlock { @MainActor in+ harness.openAllGates()+ if let token = harness.owner.currentClaimToken {+ await harness.owner.release(token)+ }+ }+ return harness+ }++ func testScopeRejectsWithoutActiveMeetingLease() async throws {+ let harness = self.makeHarness()++ do {+ _ = try await harness.service.withPreparedMeetingASR(+ attemptID: UUID(), configuration: MeetingFinalProcessingConfiguration()+ ) { _ in "ran" }+ XCTFail("Expected invalid lease rejection without an active lease")+ } catch let error as MeetingASRPreparationError {+ XCTAssertEqual(error, .invalidActivityLease)+ } catch {+ XCTFail("Expected MeetingASRPreparationError, got \(error)")+ }++ let dictationLease = try harness.service.acquireExclusiveActivity(.dictation)+ do {+ _ = try await harness.service.withPreparedMeetingASR(+ attemptID: UUID(), configuration: MeetingFinalProcessingConfiguration()+ ) { _ in "ran" }+ XCTFail("Expected invalid lease rejection for a dictation lease")+ } catch let error as MeetingASRPreparationError {+ XCTAssertEqual(error, .invalidActivityLease)+ } catch {+ XCTFail("Expected MeetingASRPreparationError, got \(error)")+ }+ harness.service.releaseExclusiveActivity(dictationLease)++ XCTAssertTrue(harness.recorder.events.isEmpty)+ XCTAssertFalse(harness.owner.isClaimed)+ XCTAssertEqual(harness.provider.prepareCalls, 0)+ }++ func testScopeSuccessPassesConfigurationThroughAndDrainsInOrder() async throws {+ let harness = self.makeHarness()+ let lease = try harness.acquireMeetingLease()+ let configuration = MeetingFinalProcessingConfiguration(diarizationFingerprint: "scope-test")++ let result = try await harness.service.withPreparedMeetingASR(+ attemptID: UUID(), configuration: configuration+ ) { provider in+ XCTAssertTrue(provider as AnyObject === harness.provider as AnyObject)+ return 42+ }++ XCTAssertEqual(result, 42)+ XCTAssertEqual(+ harness.recorder.events,+ ["retire", "factory:\(configuration.identityFingerprint)", "prepare", "drain"]+ )+ XCTAssertFalse(harness.owner.isClaimed)+ XCTAssertFalse(harness.owner.isDraining)++ // The scope never releases the caller's lease.+ XCTAssertThrowsError(try harness.service.acquireExclusiveActivity(.dictation)) { error in+ guard let activityError = error as? ASRActivityError,+ case .activityInProgress(.meeting) = activityError+ else {+ return XCTFail("Expected meeting activity to still own the lease, got \(error)")+ }+ }+ harness.service.releaseExclusiveActivity(lease)+ let dictationLease = try harness.service.acquireExclusiveActivity(.dictation)+ harness.service.releaseExclusiveActivity(dictationLease)+ }++ func testScopeBodyErrorDrainsAndRethrowsAndClearsScope() async throws {+ let harness = self.makeHarness()+ _ = try harness.acquireMeetingLease()++ do {+ _ = try await harness.service.withPreparedMeetingASR(+ attemptID: UUID(), configuration: MeetingFinalProcessingConfiguration()+ ) { _ -> Int in+ throw ScopeBodyTestError.bodyFailed+ }+ XCTFail("Expected the body error to propagate")+ } catch ScopeBodyTestError.bodyFailed {+ } catch {+ XCTFail("Expected ScopeBodyTestError, got \(error)")+ }++ XCTAssertEqual(harness.recorder.events.last, "drain")+ XCTAssertFalse(harness.owner.isClaimed)++ // The scope cleared: a fresh scope prepares and runs again.+ let second = try await harness.service.withPreparedMeetingASR(+ attemptID: UUID(), configuration: MeetingFinalProcessingConfiguration()+ ) { _ in "second" }+ XCTAssertEqual(second, "second")+ XCTAssertEqual(harness.provider.prepareCalls, 2)+ XCTAssertEqual(harness.recorder.count(of: "drain"), 2)+ XCTAssertFalse(harness.owner.isClaimed)+ }++ func testScopeRejectsConcurrentCallerWhileBodyRuns() async throws {+ let harness = self.makeHarness()+ _ = try harness.acquireMeetingLease()+ let attemptID = UUID()+ let configuration = MeetingFinalProcessingConfiguration()+ let bodyEntered = ContinuationGate()+ let finishBody = ContinuationGate()++ let first = Task { @MainActor in+ try await harness.service.withPreparedMeetingASR(+ attemptID: attemptID, configuration: configuration+ ) { _ in+ bodyEntered.open()+ await finishBody.wait()+ return "first"+ }+ }+ let enteredObserved = await waitUntilCondition { bodyEntered.opened }+ XCTAssertTrue(enteredObserved)++ // Same attempt and configuration: the scope guard rejects before the owner could join.+ do {+ _ = try await harness.service.withPreparedMeetingASR(+ attemptID: attemptID, configuration: configuration+ ) { _ in "second" }+ XCTFail("Expected concurrent scope rejection")+ } catch let error as MeetingASRPreparationError {+ XCTAssertEqual(error, .preparationInProgress)+ } catch {+ XCTFail("Expected MeetingASRPreparationError, got \(error)")+ }+ XCTAssertEqual(harness.provider.prepareCalls, 1)++ finishBody.open()+ let firstResult = try await first.value+ XCTAssertEqual(firstResult, "first")+ XCTAssertEqual(harness.recorder.count(of: "drain"), 1)+ XCTAssertFalse(harness.owner.isClaimed)+ }++ func testScopeCancellationWithNonCooperativePrepareDrainsBeforeReturning() async throws {+ let harness = self.makeHarness()+ _ = try harness.acquireMeetingLease()+ let providerGate = ContinuationGate()+ let entered = ContinuationGate()+ harness.provider.blockPrepare(on: providerGate)+ harness.provider.onPrepareEntered { entered.open() }++ let scope = Task { @MainActor in+ try await harness.service.withPreparedMeetingASR(+ attemptID: UUID(), configuration: MeetingFinalProcessingConfiguration()+ ) { _ in "unreachable" }+ }+ let enteredObserved = await waitUntilCondition { entered.opened }+ XCTAssertTrue(enteredObserved)++ scope.cancel()+ // The fake prepare ignores cancellation: the claim stays until it returns.+ XCTAssertTrue(harness.owner.isClaimed)+ XCTAssertEqual(harness.recorder.count(of: "drain"), 0)++ providerGate.open()+ do {+ _ = try await scope.value+ XCTFail("Expected cancelled scope to throw")+ } catch is CancellationError {+ } catch {+ XCTFail("Expected CancellationError, got \(error)")+ }+ XCTAssertEqual(harness.recorder.count(of: "retire"), 1)+ XCTAssertEqual(harness.recorder.count(of: "drain"), 1)+ XCTAssertFalse(harness.owner.isClaimed)+ XCTAssertFalse(harness.owner.isDraining)+ }++ func testScopeCancellationDuringNonCooperativeBodySuppressesLateSuccess() async throws {+ let harness = self.makeHarness()+ _ = try harness.acquireMeetingLease()+ let bodyEntered = ContinuationGate()+ let finishBody = ContinuationGate()++ let scope = Task { @MainActor in+ try await harness.service.withPreparedMeetingASR(+ attemptID: UUID(), configuration: MeetingFinalProcessingConfiguration()+ ) { _ in+ bodyEntered.open()+ // Deliberately ignores cancellation until the test releases it.+ await finishBody.wait()+ return "late success"+ }+ }+ let enteredObserved = await waitUntilCondition { bodyEntered.opened }+ XCTAssertTrue(enteredObserved)++ scope.cancel()+ XCTAssertTrue(harness.owner.isClaimed)+ XCTAssertEqual(harness.recorder.count(of: "drain"), 0)++ finishBody.open()+ do {+ _ = try await scope.value+ XCTFail("Expected cancellation to suppress the body's late success")+ } catch is CancellationError {+ } catch {+ XCTFail("Expected CancellationError, got \(error)")+ }++ XCTAssertEqual(harness.recorder.count(of: "drain"), 1)+ XCTAssertFalse(harness.owner.isClaimed)+ XCTAssertFalse(harness.owner.isDraining)+ }++ func testTerminationCancelsAndJoinsNonCooperativeScopeBodyBeforeReleasingClaim() async throws {+ let harness = self.makeHarness()+ _ = try harness.acquireMeetingLease()+ let bodyEntered = ContinuationGate()+ let bodyCancellationObserved = ContinuationGate()+ let finishBody = ContinuationGate()+ let shutdownFinished = TestFlag()++ let scope = Task { @MainActor in+ try await harness.service.withPreparedMeetingASR(+ attemptID: UUID(), configuration: MeetingFinalProcessingConfiguration()+ ) { _ in+ bodyEntered.open()+ return await withTaskCancellationHandler {+ await finishBody.wait()+ return "late success"+ } onCancel: {+ bodyCancellationObserved.open()+ }+ }+ }+ let didEnterBody = await waitUntilCondition { bodyEntered.opened }+ XCTAssertTrue(didEnterBody)++ let shutdown = Task { @MainActor in+ await harness.service.shutdownForTermination()+ shutdownFinished.set(true)+ }+ let didObserveCancellation = await waitUntilCondition { bodyCancellationObserved.opened }+ XCTAssertTrue(didObserveCancellation)++ // Cancellation was delivered, but shutdown remains joined to the deliberately+ // non-cooperative body and cannot clear its model claim early.+ XCTAssertFalse(shutdownFinished.value)+ XCTAssertTrue(harness.owner.isClaimed)++ finishBody.open()+ do {+ _ = try await scope.value+ XCTFail("Expected termination cancellation to suppress late success")+ } catch is CancellationError {+ } catch {+ XCTFail("Expected CancellationError, got \(error)")+ }+ await shutdown.value++ XCTAssertTrue(shutdownFinished.value)+ XCTAssertEqual(harness.recorder.count(of: "drain"), 1)+ XCTAssertFalse(harness.owner.isClaimed)+ XCTAssertFalse(harness.owner.isDraining)+ }++ func testLeaseReleaseRequestedDuringScopeDefersUntilJoinedDrain() async throws {+ let harness = self.makeHarness()+ let lease = try harness.acquireMeetingLease()+ let bodyEntered = ContinuationGate()+ let finishBody = ContinuationGate()++ let scope = Task { @MainActor in+ try await harness.service.withPreparedMeetingASR(+ attemptID: UUID(), configuration: MeetingFinalProcessingConfiguration()+ ) { _ in+ bodyEntered.open()+ await finishBody.wait()+ return "done"+ }+ }+ let enteredObserved = await waitUntilCondition { bodyEntered.opened }+ XCTAssertTrue(enteredObserved)++ // A mid-scope release request (as the meeting handback performs) must not hand+ // ownership to dictation while the scope owns the provider and executor.+ harness.service.releaseExclusiveActivity(lease)+ XCTAssertThrowsError(try harness.service.acquireExclusiveActivity(.dictation)) { error in+ guard let activityError = error as? ASRActivityError,+ case .activityInProgress(.meeting) = activityError+ else {+ return XCTFail("Expected the meeting lease to survive mid-scope, got \(error)")+ }+ }+ XCTAssertTrue(harness.owner.isClaimed)++ finishBody.open()+ let result = try await scope.value+ XCTAssertEqual(result, "done")+ XCTAssertEqual(harness.recorder.count(of: "drain"), 1)++ // After the joined drain the deferred release flushed exactly that lease.+ let dictationLease = try harness.service.acquireExclusiveActivity(.dictation)+ harness.service.releaseExclusiveActivity(dictationLease)+ XCTAssertFalse(harness.owner.isClaimed)+ }++ func testMeetingTranscriptionEntryPointsRunWithinScopeAndUnclaimedLegacyPath() async throws {+ let harness = self.makeHarness()+ _ = try harness.acquireMeetingLease()+ let samples = [Float](repeating: 0, count: 16_000)++ let scopedText = try await harness.service.withPreparedMeetingASR(+ attemptID: UUID(), configuration: MeetingFinalProcessingConfiguration()+ ) { provider in+ try await harness.service.transcribeMeetingSamples(+ samples, provider: provider, languageCode: "en"+ ).text+ }+ XCTAssertEqual(scopedText, "")+ XCTAssertEqual(harness.recorder.count(of: "drain"), 1)++ // Unclaimed legacy meeting transcription still runs without any scope.+ let legacy = try await harness.service.transcribeMeetingSamples(+ samples, provider: harness.provider, languageCode: "en"+ )+ XCTAssertEqual(legacy.text, "")+ }++ func testRetireDictationResourcesRequiresExactLeaseAndDropsCachedProviders() async throws {+ let service = ASRService()+ let settings = SettingsStore.shared+ let originalModel = settings.selectedSpeechModel+ defer { settings.selectedSpeechModel = originalModel }+ settings.selectedSpeechModel = .parakeetTDT++ let lease = try service.acquireExclusiveActivity(.meeting)+ defer { service.releaseExclusiveActivity(lease) }+ let cached = service.fileTranscriptionProvider+ let cachedID = ObjectIdentifier(cached as AnyObject)++ // A stale or foreign meeting lease must not retire anything.+ let foreignLease = ASRActivityLease(id: UUID(), activity: .meeting)+ do {+ try await service.retireDictationASRResourcesForMeeting(lease: foreignLease)+ XCTFail("Expected stale lease rejection")+ } catch is CancellationError {+ } catch {+ XCTFail("Expected CancellationError, got \(error)")+ }+ XCTAssertEqual(ObjectIdentifier(service.fileTranscriptionProvider as AnyObject), cachedID)++ try await service.retireDictationASRResourcesForMeeting(lease: lease)+ XCTAssertFalse(service.isAsrReady)+ let recreated = service.fileTranscriptionProvider+ XCTAssertNotEqual(ObjectIdentifier(recreated as AnyObject), cachedID)+ }++ func testMeetingProviderConstructionIgnoresDictationPreferences() throws {+ let settings = SettingsStore.shared+ let originalModel = settings.selectedSpeechModel+ let originalBoosting = settings.vocabularyBoostingEnabled+ defer {+ settings.selectedSpeechModel = originalModel+ settings.vocabularyBoostingEnabled = originalBoosting+ }+ // Dictation preferences differ from the fixed meeting policy on every axis.+ settings.selectedSpeechModel = .parakeetTDT+ settings.vocabularyBoostingEnabled = true++ let provider = try FluidAudioProvider(meetingConfiguration: MeetingFinalProcessingConfiguration())+ XCTAssertEqual(provider.modelOverride, .parakeetTDTv2)+ #if DEBUG+ let options = provider.effectiveEnhancementOptionsForTesting+ XCTAssertFalse(options.experimentalUnifiedFinalEnabled)+ XCTAssertFalse(options.pronunciationMatchingEnabled)+ XCTAssertTrue(options.customDictionaryEntries.isEmpty)+ #endif+ // Dictation selection is untouched by meeting provider construction.+ XCTAssertEqual(settings.selectedSpeechModel, .parakeetTDT)+ }++ func testDictationReadinessAndDownloadsRejectedWhileScopeClaimed() async throws {+ let harness = self.makeHarness()+ _ = try harness.acquireMeetingLease()+ let bodyEntered = ContinuationGate()+ let finishBody = ContinuationGate()++ let scope = Task { @MainActor in+ try await harness.service.withPreparedMeetingASR(+ attemptID: UUID(), configuration: MeetingFinalProcessingConfiguration()+ ) { _ in+ bodyEntered.open()+ await finishBody.wait()+ return "done"+ }+ }+ let enteredObserved = await waitUntilCondition { bodyEntered.opened }+ XCTAssertTrue(enteredObserved)++ do {+ try await harness.service.ensureAsrReady()+ XCTFail("Expected ensureAsrReady rejection while the scope is claimed")+ } catch let error as MeetingASRPreparationError {+ XCTAssertEqual(error, .preparationInProgress)+ } catch {+ XCTFail("Expected MeetingASRPreparationError, got \(error)")+ }+ do {+ try await harness.service.downloadModel(.whisperBase, progressHandler: nil)+ XCTFail("Expected download rejection while the scope is claimed")+ } catch let error as MeetingASRPreparationError {+ XCTAssertEqual(error, .preparationInProgress)+ } catch {+ XCTFail("Expected MeetingASRPreparationError, got \(error)")+ }++ finishBody.open()+ _ = try await scope.value+ XCTAssertFalse(harness.owner.isClaimed)+ }+}+#endifdiff --git a/Tests/FluidDictationIntegrationTests/MeetingAnalysisManifestTests.swift b/Tests/FluidDictationIntegrationTests/MeetingAnalysisManifestTests.swiftnew file mode 100644index 00000000..aefb0105--- /dev/null+++ b/Tests/FluidDictationIntegrationTests/MeetingAnalysisManifestTests.swift@@ -0,0 +1,610 @@+import AVFoundation+import CryptoKit+@testable import FluidVoice_Debug+import Foundation+import XCTest++private nonisolated struct ManifestFixtureObserver: MeetingChunkAudioObserving {+ let results: [MeetingAnalysisChunkKey: MeetingChunkObservationResult]++ func observe(+ chunk: MeetingAudioChunk,+ trackID: MeetingAudioTrackID+ ) -> MeetingChunkObservationResult {+ self.results[MeetingAnalysisChunkKey(trackID: trackID, chunkID: chunk.id)]+ ?? .failed(.unreadable, detail: "No fixture observation")+ }+}++@MainActor+final class MeetingAnalysisManifestTests: XCTestCase {+ private let backendID = MeetingBackendID(rawValue: "fixture.analysis-manifest")++ private func chunk(+ id: UUID = UUID(),+ sequence: Int,+ start: Double,+ end: Double,+ path: String? = nil,+ discontinuities: [MeetingAudioDiscontinuity] = [],+ sha256: String? = nil,+ byteCount: Int64 = 1024+ ) -> MeetingAudioChunk {+ MeetingAudioChunk(+ id: id,+ sequence: sequence,+ relativeFilePath: path ?? "tracks/chunk-\(sequence).m4a",+ presentationStart: self.mediaTime(start),+ presentationEnd: self.mediaTime(end),+ discontinuities: discontinuities,+ sha256: sha256 ?? String(repeating: String((sequence % 9) + 1), count: 64),+ byteCount: byteCount,+ finalizationState: .finalized+ )+ }++ private func mediaTime(_ seconds: Double) -> MeetingMediaTime {+ MeetingMediaTime(value: Int64((seconds * 1000).rounded()), timescale: 1000)+ }++ private func era(+ protection: MeetingMicrophoneEchoProtection,+ start: Double,+ deviceUID: String = "mic-a",+ method: MeetingAudioTrackCaptureMethod = .voiceProcessing,+ drift: MeetingClockDriftRecord? = nil+ ) -> MeetingCaptureEra {+ MeetingCaptureEra(+ method: method,+ deviceUID: deviceUID,+ deviceName: deviceUID,+ roleAtElection: .unknown,+ echoProtection: protection,+ startSeconds: start,+ clockDrift: drift+ )+ }++ private func track(+ id: UUID = UUID(),+ kind: MeetingAudioTrackKind,+ chunks: [MeetingAudioChunk],+ captureMethod: MeetingAudioTrackCaptureMethod? = nil,+ eras: [MeetingCaptureEra]? = nil,+ hostClock: UInt64 = 42+ ) -> MeetingAudioTrack {+ MeetingAudioTrack(+ id: id,+ kind: kind,+ sourceIdentifier: kind.rawValue,+ sourceDisplayName: kind.rawValue,+ format: nil,+ timebase: MeetingTimebaseMetadata(+ startedHostTime: hostClock,+ machTimebaseNumerator: 1,+ machTimebaseDenominator: 1,+ firstPresentationTime: nil+ ),+ health: .waiting,+ chunks: chunks,+ captureMethod: captureMethod,+ captureEras: eras+ )+ }++ private func plan(+ mode: MeetingCaptureMode,+ tracks: [MeetingAudioTrack]+ ) -> MeetingBackendPlan {+ let application = mode == .onlineCall+ ? MeetingApplicationIdentity(bundleIdentifier: "fixture.app", displayName: "Fixture")+ : nil+ var session = MeetingSession(+ configuration: MeetingCaptureConfiguration(+ mode: mode,+ title: "Manifest fixture",+ application: application,+ microphone: MeetingMicrophoneIdentity(+ captureDeviceID: "mic-a",+ coreAudioUID: "mic-a",+ displayName: "Mic"+ )+ ),+ timebase: MeetingTimebaseMetadata(+ startedHostTime: 1,+ machTimebaseNumerator: 1,+ machTimebaseDenominator: 1,+ firstPresentationTime: nil+ )+ )+ session.audioTracks = tracks+ let request = MeetingBackendRequest(+ attemptID: UUID(),+ session: session,+ sessionDirectory: FileManager.default.temporaryDirectory,+ configuration: MeetingFinalProcessingConfiguration()+ )+ return MeetingBackendPlan(+ request: request,+ descriptor: MeetingBackendDescriptor(+ id: self.backendID,+ version: "c2a-test",+ execution: .local,+ supportedLanguageCodes: ["en"],+ supportedTrackKinds: Set(MeetingAudioTrackKind.allCases),+ supportedFinalPrecisions: [.word],+ resultContract: .canonicalEvidence,+ knownLimits: []+ )+ )+ }++ private func observed(+ _ chunk: MeetingAudioChunk,+ duration: Double,+ sampleRate: Double = 100,+ priming: MeetingCodecPriming = .unknown(.decoderDidNotReport)+ ) -> MeetingChunkObservationResult {+ .observed(MeetingChunkObservedAudio(+ byteCount: chunk.byteCount,+ sha256: chunk.sha256,+ decoded: MeetingChunkDecodedFacts(+ sampleRate: sampleRate,+ channelCount: 1,+ frameCount: Int64((duration * sampleRate).rounded()),+ durationSeconds: duration,+ codecPriming: priming,+ processingFormatDescription: "fixture"+ )+ ))+ }++ private func observer(+ _ entries: [(MeetingAudioTrackID, MeetingAudioChunk, MeetingChunkObservationResult)]+ ) -> ManifestFixtureObserver {+ ManifestFixtureObserver(results: Dictionary(+ uniqueKeysWithValues: entries.map {+ (MeetingAnalysisChunkKey(trackID: $0.0, chunkID: $0.1.id), $0.2)+ }+ ))+ }++ private func replacing(+ _ manifest: MeetingAnalysisManifest,+ origin: Double? = nil,+ tracks: [MeetingAnalysisTrackManifest]? = nil+ ) -> MeetingAnalysisManifest {+ MeetingAnalysisManifest(+ backendID: manifest.backendID,+ backendVersion: manifest.backendVersion,+ attemptID: manifest.attemptID,+ sessionID: manifest.sessionID,+ captureMode: manifest.captureMode,+ presentationOriginSeconds: origin ?? manifest.presentationOriginSeconds,+ analysisSampleRate: manifest.analysisSampleRate,+ residualBoundSeconds: manifest.residualBoundSeconds,+ tracks: tracks ?? manifest.tracks+ )+ }++ func testCodecPrimingLegacyAssociatedValueShapeAndPCMRepresentation() throws {+ let decoder = JSONDecoder()+ let encoder = JSONEncoder()+ let legacyUnknown = try decoder.decode(+ MeetingCodecPriming.self,+ from: Data(#"{"unknown":{"_0":"decoderDidNotReport"}}"#.utf8)+ )+ XCTAssertEqual(legacyUnknown, .unknown(.decoderDidNotReport))+ let legacyMeasured = try decoder.decode(+ MeetingCodecPriming.self,+ from: Data(#"{"measuredFrames":{"_0":0}}"#.utf8)+ )+ XCTAssertEqual(legacyMeasured, .measuredFrames(0))+ let pcm = MeetingCodecPriming.notApplicable(.linearPCMFloat32CAFV1)+ let encoded = try encoder.encode(pcm)+ XCTAssertEqual(+ String(decoding: encoded, as: UTF8.self),+ #"{"notApplicable":{"_0":"linearPCMFloat32CAFV1"}}"#+ )+ XCTAssertEqual(try decoder.decode(MeetingCodecPriming.self, from: encoded), pcm)+ XCTAssertEqual(+ try decoder.decode(MeetingCodecPriming.self, from: encoder.encode(legacyUnknown)),+ legacyUnknown+ )+ }++ func testInRoomChunkBuildsOneAdmissibleUncertainSpan() throws {+ let chunk = self.chunk(sequence: 0, start: 100, end: 110)+ let track = self.track(kind: .microphone, chunks: [chunk], captureMethod: .avCaptureSession)+ let plan = self.plan(mode: .inRoom, tracks: [track])+ let manifest = try MeetingAnalysisManifestBuilder(+ plan: plan,+ observer: self.observer([(track.id, chunk, self.observed(chunk, duration: 10))]),+ analysisSampleRate: 16_000+ ).build()++ XCTAssertEqual(manifest.presentationOriginSeconds, 100)+ let builtTrack = try XCTUnwrap(manifest.track(track.id))+ XCTAssertTrue(builtTrack.gaps.isEmpty)+ let span = try XCTUnwrap(builtTrack.spans.only)+ XCTAssertEqual(span.recordedInterval, MeetingAnalysisInterval(start: 0, end: 10))+ XCTAssertEqual(span.sourceLocalInterval, MeetingAnalysisInterval(start: 0, end: 10))+ XCTAssertEqual(span.analysisInterval, MeetingAnalysisInterval(start: 0, end: 10))+ XCTAssertEqual(span.admission.rationale, .inRoomMicrophone)+ XCTAssertEqual(span.timing.certainty, .timingUncertain)+ XCTAssertNil(span.presentationMapping.codecPrimingCompensationSeconds)+ XCTAssertEqual(span.presentationMapping.sampleRateConversionRatio, 100 / 16_000)+ XCTAssertEqual(builtTrack.epochs.map(\.resetReason), [.trackStart])+ }++ func testOnlineTracksStaySeparateAndMixedMicErasTileChunk() throws {+ let appChunk = self.chunk(sequence: 0, start: 100, end: 110)+ let micChunk = self.chunk(sequence: 0, start: 100, end: 110)+ let app = self.track(kind: .applicationAudio, chunks: [appChunk])+ let mic = self.track(+ kind: .microphone,+ chunks: [micChunk],+ eras: [+ self.era(protection: .voiceProcessed, start: 0),+ self.era(protection: .unprotected, start: 105),+ self.era(protection: .softwareEchoCancelled, start: 108),+ ]+ )+ let plan = self.plan(mode: .onlineCall, tracks: [app, mic])+ let manifest = try MeetingAnalysisManifestBuilder(+ plan: plan,+ observer: self.observer([+ (app.id, appChunk, self.observed(appChunk, duration: 10)),+ (mic.id, micChunk, self.observed(micChunk, duration: 10)),+ ])+ ).build()++ let appManifest = try XCTUnwrap(manifest.track(app.id))+ XCTAssertEqual(appManifest.spans.count, 1)+ XCTAssertTrue(appManifest.gaps.isEmpty)+ XCTAssertEqual(appManifest.spans[0].admission.rationale, .applicationAudio)++ let micManifest = try XCTUnwrap(manifest.track(mic.id))+ XCTAssertEqual(micManifest.spans.map(\.recordedInterval), [+ MeetingAnalysisInterval(start: 0, end: 5),+ MeetingAnalysisInterval(start: 8, end: 10),+ ])+ XCTAssertEqual(micManifest.gaps.compactMap(\.recordedInterval), [+ MeetingAnalysisInterval(start: 5, end: 8),+ ])+ XCTAssertEqual(micManifest.gaps.map(\.reason), [.inadmissibleCaptureEra])+ XCTAssertEqual(micManifest.spans.map(\.analysisInterval), [+ MeetingAnalysisInterval(start: 0, end: 5),+ MeetingAnalysisInterval(start: 5, end: 7),+ ])+ XCTAssertEqual(micManifest.epochs.map(\.resetReason), [.trackStart, .inadmissibleCaptureEra])+ XCTAssertNotEqual(appManifest.spans[0].analysisEpochID.trackID, micManifest.spans[0].analysisEpochID.trackID)+ }++ func testSafeDeviceChangeAndRecordedDiscontinuityResetEpochs() throws {+ let first = self.chunk(sequence: 0, start: 100, end: 105)+ let second = self.chunk(+ sequence: 1,+ start: 105,+ end: 110,+ discontinuities: [MeetingAudioDiscontinuity(+ kind: .microphoneChanged,+ presentationTime: self.mediaTime(105),+ gapSeconds: 0,+ detail: "fixture"+ )]+ )+ let track = self.track(+ kind: .microphone,+ chunks: [first, second],+ eras: [+ self.era(protection: .voiceProcessed, start: 0, deviceUID: "mic-a"),+ self.era(protection: .voiceProcessed, start: 105, deviceUID: "mic-b"),+ ]+ )+ let plan = self.plan(mode: .onlineCall, tracks: [track])+ let manifest = try MeetingAnalysisManifestBuilder(+ plan: plan,+ observer: self.observer([+ (track.id, first, self.observed(first, duration: 5, priming: .measuredFrames(0))),+ (track.id, second, self.observed(second, duration: 5, priming: .measuredFrames(0))),+ ])+ ).build()+ let epochs = try XCTUnwrap(manifest.track(track.id)).epochs+ XCTAssertEqual(epochs.count, 2)+ XCTAssertEqual(epochs[0].resetReason, .trackStart)+ XCTAssertEqual(epochs[1].resetReason, .microphoneDeviceChanged)+ }++ func testMidChunkDiscontinuitySplitsPieceAndResetsEpoch() throws {+ let chunk = self.chunk(+ sequence: 0,+ start: 100,+ end: 110,+ discontinuities: [MeetingAudioDiscontinuity(+ kind: .clockDiscontinuity,+ presentationTime: self.mediaTime(104),+ gapSeconds: nil,+ detail: "mid-chunk"+ )]+ )+ let track = self.track(kind: .microphone, chunks: [chunk], eras: [+ self.era(protection: .voiceProcessed, start: 0),+ ])+ let plan = self.plan(mode: .onlineCall, tracks: [track])+ let manifest = try MeetingAnalysisManifestBuilder(+ plan: plan,+ observer: self.observer([(track.id, chunk, self.observed(chunk, duration: 10))])+ ).build()+ let result = try XCTUnwrap(manifest.track(track.id))+ XCTAssertEqual(result.spans.map(\.recordedInterval), [+ MeetingAnalysisInterval(start: 0, end: 4),+ MeetingAnalysisInterval(start: 4, end: 10),+ ])+ XCTAssertEqual(result.epochs.map(\.resetReason), [.trackStart, .chunkDiscontinuity])+ }++ func testObservationFailuresBecomeTypedGapsAndResetFollowingAudio() throws {+ let first = self.chunk(sequence: 0, start: 0, end: 2)+ let missing = self.chunk(sequence: 1, start: 2, end: 4)+ let third = self.chunk(sequence: 2, start: 4, end: 6)+ let track = self.track(kind: .microphone, chunks: [first, missing, third], eras: [+ self.era(protection: .voiceProcessed, start: 0),+ ])+ let plan = self.plan(mode: .onlineCall, tracks: [track])+ let manifest = try MeetingAnalysisManifestBuilder(+ plan: plan,+ observer: self.observer([+ (track.id, first, self.observed(first, duration: 2)),+ (track.id, missing, .failed(.fileMissing, detail: "gone")),+ (track.id, third, self.observed(third, duration: 2)),+ ])+ ).build()+ let result = try XCTUnwrap(manifest.track(track.id))+ XCTAssertEqual(result.gaps.map(\.reason), [.chunkFileMissing])+ XCTAssertEqual(result.epochs.map(\.resetReason), [.trackStart, .missingOrUnreadableAudio])+ }++ func testShortDecodedAudioProducesBackedSpanAndExplicitTrailingGap() throws {+ let chunk = self.chunk(sequence: 0, start: 10, end: 20)+ let track = self.track(kind: .microphone, chunks: [chunk], eras: [+ self.era(protection: .voiceProcessed, start: 0),+ ])+ let plan = self.plan(mode: .onlineCall, tracks: [track])+ let manifest = try MeetingAnalysisManifestBuilder(+ plan: plan,+ observer: self.observer([(track.id, chunk, self.observed(chunk, duration: 6))])+ ).build()+ let result = try XCTUnwrap(manifest.track(track.id))+ XCTAssertEqual(result.spans.map(\.recordedInterval), [MeetingAnalysisInterval(start: 0, end: 6)])+ XCTAssertEqual(result.gaps.compactMap(\.recordedInterval), [MeetingAnalysisInterval(start: 6, end: 10)])+ XCTAssertEqual(result.gaps.map(\.reason), [.decodedAudioExhausted])+ }++ func testValidatorRejectsOriginChunkIdentityAndCoverageMutations() throws {+ let chunk = self.chunk(sequence: 0, start: 100, end: 110)+ let track = self.track(kind: .microphone, chunks: [chunk])+ let plan = self.plan(mode: .inRoom, tracks: [track])+ let manifest = try MeetingAnalysisManifestBuilder(+ plan: plan,+ observer: self.observer([(track.id, chunk, self.observed(chunk, duration: 10))])+ ).build()++ XCTAssertThrowsError(try self.replacing(manifest, origin: 99).validated(against: plan)) { error in+ guard case .presentationOriginMismatch = error as? MeetingAnalysisManifestError else {+ return XCTFail("Expected presentationOriginMismatch, got \(error)")+ }+ }++ let builtTrack = try XCTUnwrap(manifest.track(track.id))+ let span = try XCTUnwrap(builtTrack.spans.only)+ let changedIdentity = MeetingAnalysisChunkIdentity(+ trackID: span.chunk.trackID,+ chunk: MeetingAudioChunk(+ id: span.chunk.chunkID,+ sequence: span.chunk.sequence,+ relativeFilePath: "different.m4a",+ presentationStart: chunk.presentationStart,+ presentationEnd: chunk.presentationEnd,+ discontinuities: chunk.discontinuities,+ sha256: span.chunk.storedSHA256,+ byteCount: span.chunk.storedByteCount,+ finalizationState: .finalized+ )+ )+ let changedSpan = MeetingAnalysisSpan(+ id: span.id,+ chunk: changedIdentity,+ pieceIndex: span.pieceIndex,+ trackKind: span.trackKind,+ analysisEpochID: span.analysisEpochID,+ recordedInterval: span.recordedInterval,+ sourceLocalInterval: span.sourceLocalInterval,+ analysisInterval: span.analysisInterval,+ presentationInterval: span.presentationInterval,+ presentationMapping: span.presentationMapping,+ captureEra: span.captureEra,+ admission: span.admission,+ observed: span.observed,+ discontinuity: span.discontinuity,+ timing: span.timing+ )+ let changedTrack = MeetingAnalysisTrackManifest(+ id: builtTrack.id,+ kind: builtTrack.kind,+ spans: [changedSpan],+ gaps: builtTrack.gaps,+ epochs: builtTrack.epochs+ )+ XCTAssertThrowsError(try self.replacing(manifest, tracks: [changedTrack]).validated(against: plan)) { error in+ guard case .chunkIdentityDisagreesWithPlan = error as? MeetingAnalysisManifestError else {+ return XCTFail("Expected chunkIdentityDisagreesWithPlan, got \(error)")+ }+ }++ let uncoveredTrack = MeetingAnalysisTrackManifest(+ id: builtTrack.id,+ kind: builtTrack.kind,+ spans: [],+ gaps: [],+ epochs: []+ )+ XCTAssertThrowsError(try self.replacing(manifest, tracks: [uncoveredTrack]).validated(against: plan)) { error in+ guard case .plannedChunkUncovered = error as? MeetingAnalysisManifestError else {+ return XCTFail("Expected plannedChunkUncovered, got \(error)")+ }+ }+ }++ func testProductionObserverRejectsEscapesMutationsAndUnreadableFiles() throws {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("manifest-observer-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ self.addTeardownBlock { try? FileManager.default.removeItem(at: root) }+ let file = root.appendingPathComponent("chunk.bin")+ let bytes = Data("not audio".utf8)+ try bytes.write(to: file)+ let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined()+ let observer = MeetingChunkAudioObserver(sessionDirectory: root)++ let validIdentity = self.chunk(+ sequence: 0,+ start: 0,+ end: 1,+ path: "chunk.bin",+ sha256: digest,+ byteCount: Int64(bytes.count)+ )+ XCTAssertEqualFailure(observer.observe(chunk: validIdentity, trackID: UUID()), .unreadable)++ var changedBytes = validIdentity+ changedBytes.byteCount += 1+ XCTAssertEqualFailure(observer.observe(chunk: changedBytes, trackID: UUID()), .byteCountChanged)++ var changedHash = validIdentity+ changedHash.sha256 = String(repeating: "0", count: 64)+ XCTAssertEqualFailure(observer.observe(chunk: changedHash, trackID: UUID()), .hashChanged)++ var escaping = validIdentity+ escaping.relativeFilePath = "../chunk.bin"+ XCTAssertEqualFailure(observer.observe(chunk: escaping, trackID: UUID()), .pathRejected)++ let outside = FileManager.default.temporaryDirectory+ .appendingPathComponent("manifest-outside-\(UUID().uuidString)")+ try bytes.write(to: outside)+ self.addTeardownBlock { try? FileManager.default.removeItem(at: outside) }+ let link = root.appendingPathComponent("link.bin")+ try FileManager.default.createSymbolicLink(at: link, withDestinationURL: outside)+ var linked = validIdentity+ linked.relativeFilePath = "link.bin"+ XCTAssertEqualFailure(observer.observe(chunk: linked, trackID: UUID()), .pathRejected)+ }++ func testProductionObserverReadsActualAudioAndLeavesPrimingUnknown() throws {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("manifest-audio-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ self.addTeardownBlock { try? FileManager.default.removeItem(at: root) }+ let url = root.appendingPathComponent("chunk.caf")+ let format = try XCTUnwrap(AVAudioFormat(standardFormatWithSampleRate: 16_000, channels: 1))+ do {+ let file = try AVAudioFile(forWriting: url, settings: format.settings)+ let buffer = try XCTUnwrap(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 1600))+ buffer.frameLength = 1600+ try file.write(from: buffer)+ }+ let bytes = try Data(contentsOf: url)+ let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined()+ let chunk = self.chunk(+ sequence: 0,+ start: 0,+ end: 0.1,+ path: "chunk.caf",+ sha256: digest,+ byteCount: Int64(bytes.count)+ )++ let result = MeetingChunkAudioObserver(sessionDirectory: root)+ .observe(chunk: chunk, trackID: UUID())+ guard case let .observed(observed) = result else {+ return XCTFail("Expected observed audio, got \(result)")+ }+ XCTAssertEqual(observed.decoded.sampleRate, 16_000)+ XCTAssertEqual(observed.decoded.frameCount, 1600)+ XCTAssertEqual(observed.decoded.durationSeconds, 0.1, accuracy: 1e-9)+ XCTAssertEqual(observed.decoded.codecPriming, .unknown(.decoderDidNotReport))+ }++ func testProductionObserverUsesReadyPCMAssetAndMarksPrimingNotApplicable() throws {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("manifest-pcm-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ self.addTeardownBlock { try? FileManager.default.removeItem(at: root) }+ let pcmURL = root.appendingPathComponent("analysis/chunk-0.caf")+ try FileManager.default.createDirectory(at: pcmURL.deletingLastPathComponent(), withIntermediateDirectories: true)+ let format = try XCTUnwrap(AVAudioFormat(+ commonFormat: .pcmFormatFloat32,+ sampleRate: 16_000,+ channels: 1,+ interleaved: true+ ))+ let file = try AVAudioFile(forWriting: pcmURL, settings: format.settings,+ commonFormat: .pcmFormatFloat32, interleaved: true)+ let buffer = try XCTUnwrap(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 1600))+ buffer.frameLength = 1600+ try file.write(from: buffer)+ let bytes = try Data(contentsOf: pcmURL)+ let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined()+ let attributes = try FileManager.default.attributesOfItem(atPath: pcmURL.path)+ let asset = MeetingAudioAsset(+ role: .captureAnalysis,+ encoding: .linearPCMFloat32CAFV1,+ presence: .ready,+ relativeFilePath: "analysis/chunk-0.caf",+ byteCount: Int64((attributes[.size] as? NSNumber)?.intValue ?? 0),+ sha256: digest,+ sampleRate: 16_000,+ channelCount: 1,+ frameCount: 1600+ )+ let chunk = MeetingAudioChunk(+ id: UUID(), sequence: 0, relativeFilePath: "archive/chunk-0.m4a",+ presentationStart: self.mediaTime(0), presentationEnd: self.mediaTime(0.1),+ discontinuities: [], sha256: String(repeating: "a", count: 64), byteCount: 1,+ finalizationState: .finalized, audioSchemaVersion: 2,+ captureAnalysisAsset: asset+ )+ let result = MeetingChunkAudioObserver(sessionDirectory: root)+ .observe(chunk: chunk, trackID: UUID())+ guard case let .observed(observed) = result else {+ return XCTFail("Expected verified PCM asset, got \(result)")+ }+ XCTAssertEqual(observed.byteCount, asset.byteCount)+ XCTAssertEqual(observed.sha256, digest)+ XCTAssertEqual(observed.decoded.frameCount, 1600)+ XCTAssertEqual(observed.decoded.codecPriming, .notApplicable(.linearPCMFloat32CAFV1))+ XCTAssertTrue(observed.decoded.codecPriming.isKnown)+ let identity = MeetingAnalysisChunkIdentity(trackID: UUID(), chunk: chunk)+ XCTAssertEqual(identity.relativeFilePath, asset.relativeFilePath)+ XCTAssertEqual(identity.storedByteCount, asset.byteCount)+ XCTAssertEqual(identity.storedSHA256, digest)+ }+}++private extension Collection {+ var only: Element? {+ self.count == 1 ? self.first : nil+ }+}++private func XCTAssertEqualFailure(+ _ result: MeetingChunkObservationResult,+ _ expected: MeetingChunkObservationFailure,+ file: StaticString = #filePath,+ line: UInt = #line+) {+ guard case let .failed(actual, _) = result else {+ return XCTFail("Expected failure \(expected), got \(result)", file: file, line: line)+ }+ XCTAssertEqual(actual, expected, file: file, line: line)+}diff --git a/Tests/FluidDictationIntegrationTests/MeetingAudioAssetCompatibilityTests.swift b/Tests/FluidDictationIntegrationTests/MeetingAudioAssetCompatibilityTests.swiftnew file mode 100644index 00000000..3412fa24--- /dev/null+++ b/Tests/FluidDictationIntegrationTests/MeetingAudioAssetCompatibilityTests.swift@@ -0,0 +1,86 @@+@testable import FluidVoice_Debug+import Foundation+import XCTest++final class MeetingAudioAssetCompatibilityTests: XCTestCase {+ func testLegacyChunkOmitsAllP0aKeysAndRoundTripsFullSession() throws {+ let chunk = MeetingAudioChunk(id: UUID(), sequence: 3, relativeFilePath: "tracks/microphone/3.caf",+ presentationStart: MeetingMediaTime(value: 0, timescale: 1000),+ presentationEnd: MeetingMediaTime(value: 1000, timescale: 1000),+ discontinuities: [], sha256: "legacy", byteCount: 42, finalizationState: .finalized)+ let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys]+ let json = try encoder.encode(chunk)+ let object = try XCTUnwrap(try JSONSerialization.jsonObject(with: json) as? [String: Any])+ XCTAssertEqual(Set(object.keys), Set(["id", "sequence", "relativeFilePath", "presentationStart", "presentationEnd", "discontinuities", "sha256", "byteCount", "finalizationState"]))+ XCTAssertNil(object["audioSchemaVersion"]); XCTAssertNil(object["captureAnalysisAsset"]); XCTAssertNil(object["playbackArchiveAsset"])+ let decodedChunk = try JSONDecoder().decode(MeetingAudioChunk.self, from: json)+ XCTAssertEqual(decodedChunk, chunk)++ let configuration = MeetingCaptureConfiguration(mode: .inRoom, title: "Legacy", microphone: MeetingMicrophoneIdentity(captureDeviceID: "mic", displayName: "Mic"))+ var session = MeetingSession(configuration: configuration, startedAt: Date(timeIntervalSince1970: 1_700_000_000),+ timebase: MeetingTimebaseMetadata(startedHostTime: 1, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil))+ session.audioTracks = [MeetingAudioTrack(id: UUID(), kind: .microphone, sourceIdentifier: "mic", sourceDisplayName: "Mic", format: nil,+ timebase: session.timebase, health: .waiting, chunks: [chunk])]+ let sessionData = try encoder.encode(session)+ XCTAssertEqual(try JSONDecoder().decode(MeetingSession.self, from: sessionData), session)+ }++ func testValidPCMAssetRoundTripsAndLegacyReadyMayOmitFrameFacts() throws {+ let asset = MeetingAudioAsset(role: .captureAnalysis, encoding: .linearPCMFloat32CAFV1, presence: .ready,+ relativeFilePath: "tracks/application/1.caf", byteCount: 128, sha256: String(repeating: "a", count: 64),+ sampleRate: 48_000, channelCount: 2, frameCount: 16)+ let data = try JSONEncoder().encode(asset)+ XCTAssertEqual(try JSONDecoder().decode(MeetingAudioAsset.self, from: data), asset)+ XCTAssertTrue(asset.validationIssues().isEmpty)+ let legacy = MeetingAudioAsset(role: .playbackArchive, encoding: .legacyAACUnknownPrimingV1, presence: .ready,+ relativeFilePath: "audio.m4a", byteCount: 1)+ XCTAssertTrue(legacy.validationIssues().isEmpty)+ }++ func testUnknownRawValuesRoundTripAndQuarantineOnlyThatAsset() throws {+ let json = Data(#"{"role":"futureRole","encoding":"futureEncoding","presence":"futurePresence","relativeFilePath":"future.bin","byteCount":1}"#.utf8)+ let asset = try JSONDecoder().decode(MeetingAudioAsset.self, from: json)+ XCTAssertEqual(asset.role.rawValue, "futureRole"); XCTAssertEqual(asset.encoding.rawValue, "futureEncoding"); XCTAssertEqual(asset.presence.rawValue, "futurePresence")+ XCTAssertEqual(asset.validationIssues(), [.unknownRole("futureRole"), .unknownEncoding("futureEncoding"), .unknownPresence("futurePresence")])+ let reencoded = try JSONDecoder().decode(MeetingAudioAsset.self, from: JSONEncoder().encode(asset))+ XCTAssertEqual(reencoded, asset)++ let validArchive = MeetingAudioAsset(+ role: .playbackArchive,+ encoding: .aacLCM4AV1,+ presence: .ready,+ relativeFilePath: "tracks/application/archive.m4a",+ byteCount: 64,+ sha256: String(repeating: "b", count: 64),+ sampleRate: 48_000,+ channelCount: 2,+ frameCount: 48_000+ )+ let chunk = MeetingAudioChunk(+ id: UUID(),+ sequence: 0,+ relativeFilePath: "tracks/application/legacy.m4a",+ presentationStart: MeetingMediaTime(value: 0, timescale: 1_000),+ presentationEnd: MeetingMediaTime(value: 1_000, timescale: 1_000),+ discontinuities: [],+ sha256: "legacy",+ byteCount: 1,+ finalizationState: .finalized,+ audioSchemaVersion: 2,+ captureAnalysisAsset: asset,+ playbackArchiveAsset: validArchive+ )+ XCTAssertEqual(chunk.captureAnalysisAsset?.validationIssues(), asset.validationIssues())+ XCTAssertTrue(validArchive.validationIssues().isEmpty)+ XCTAssertTrue(chunk.assetValidationIssues().contains(.unknownRole("futureRole")))+ }++ func testReadyPCMAssetWithoutFactsIsInvalidPurelyFromMetadata() {+ let invalid = MeetingAudioAsset(role: .captureAnalysis, encoding: .linearPCMFloat32CAFV1, presence: .ready,+ relativeFilePath: "tracks/application/1.caf", byteCount: 128)+ XCTAssertTrue(invalid.validationIssues().contains(.readyAssetMissingHash))+ XCTAssertTrue(invalid.validationIssues().contains(.readyAssetMissingSampleRate))+ XCTAssertTrue(invalid.validationIssues().contains(.readyAssetMissingChannelCount))+ XCTAssertTrue(invalid.validationIssues().contains(.readyAssetMissingFrameCount))+ }+}diff --git a/Tests/FluidDictationIntegrationTests/MeetingAudioChunkLedgerRecoveryTests.swift b/Tests/FluidDictationIntegrationTests/MeetingAudioChunkLedgerRecoveryTests.swiftnew file mode 100644index 00000000..5b0f2515--- /dev/null+++ b/Tests/FluidDictationIntegrationTests/MeetingAudioChunkLedgerRecoveryTests.swift@@ -0,0 +1,105 @@+@testable import FluidVoice_Debug+import CryptoKit+import Foundation+import XCTest++@MainActor+final class MeetingAudioChunkLedgerRecoveryTests: XCTestCase {+ func testReadyPCMAssetMustMatchConfinedBytesAndHash() async throws {+ let root = try self.makeDirectory(); defer { try? FileManager.default.removeItem(at: root) }+ let sessionID = UUID(); let store = MeetingSessionStore(rootDirectory: root)+ let bytes = Data([1, 2, 3, 4]); let hash = self.hash(bytes)+ let asset = MeetingAudioAsset(role: .captureAnalysis, encoding: .linearPCMFloat32CAFV1, presence: .ready,+ relativeFilePath: "tracks/microphone/pcm.caf", byteCount: Int64(bytes.count), sha256: hash,+ sampleRate: 48_000, channelCount: 1, frameCount: 1)+ let missingArchive = MeetingAudioAsset(+ role: .playbackArchive,+ encoding: .aacLCM4AV1,+ presence: .ready,+ relativeFilePath: "tracks/microphone/archive.m4a",+ byteCount: 4,+ sha256: hash,+ sampleRate: 48_000,+ channelCount: 1,+ frameCount: 1+ )+ let chunk = MeetingAudioChunk(id: UUID(), sequence: 0, relativeFilePath: "legacy.m4a",+ presentationStart: MeetingMediaTime(value: 0, timescale: 1000), presentationEnd: MeetingMediaTime(value: 1, timescale: 1000),+ discontinuities: [], sha256: hash, byteCount: Int64(bytes.count), finalizationState: .finalized,+ audioSchemaVersion: 2, captureAnalysisAsset: asset,+ playbackArchiveAsset: missingArchive)+ var session = MeetingSession(id: sessionID, configuration: MeetingCaptureConfiguration(mode: .inRoom, title: "P0b", microphone: MeetingMicrophoneIdentity(captureDeviceID: "m", displayName: "M")),+ timebase: MeetingTimebaseMetadata(startedHostTime: 0, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil))+ let track = MeetingAudioTrack(id: UUID(), kind: .microphone, sourceIdentifier: "m", sourceDisplayName: "M", format: nil, timebase: session.timebase, health: .waiting, chunks: [chunk])+ session.audioTracks = [track]+ try await store.create(session)+ let directory = try await store.sessionDirectory(for: sessionID)+ let pcmURL = directory.appendingPathComponent(asset.relativeFilePath)+ try FileManager.default.createDirectory(at: pcmURL.deletingLastPathComponent(), withIntermediateDirectories: true)+ try bytes.write(to: pcmURL)+ let trackURL = directory.appendingPathComponent("tracks/microphone/track.json")+ try JSONEncoder().encode(track).write(to: trackURL)+ let loaded = try await store.load(id: sessionID)+ XCTAssertEqual(loaded?.audioTracks.first?.chunks.first?.byteCount, Int64(bytes.count))+ XCTAssertEqual(loaded?.audioTracks.first?.chunks.first?.finalizationState, .finalized)+ XCTAssertEqual(loaded?.audioTracks.first?.chunks.first?.captureAnalysisAsset?.presence, .ready)+ XCTAssertEqual(loaded?.audioTracks.first?.chunks.first?.playbackArchiveAsset?.presence, .failed)+ try Data([9]).write(to: pcmURL)+ let mismatched = try await store.load(id: sessionID)+ XCTAssertEqual(mismatched?.audioTracks.first?.chunks.first?.finalizationState, .failed)+ XCTAssertEqual(mismatched?.audioTracks.first?.chunks.first?.byteCount, 0)+ }++ func testPartialOrEscapingNewAssetIsNeverPromoted() async throws {+ let chunk = MeetingAudioChunk(id: UUID(), sequence: 0, relativeFilePath: "legacy.m4a",+ presentationStart: MeetingMediaTime(value: 0, timescale: 1), presentationEnd: MeetingMediaTime(value: 1, timescale: 1),+ discontinuities: [], sha256: "legacy", byteCount: 1, finalizationState: .writing, audioSchemaVersion: 2,+ captureAnalysisAsset: MeetingAudioAsset(role: .captureAnalysis, encoding: .linearPCMFloat32CAFV1, presence: .partial,+ relativeFilePath: "../outside.partial.caf", byteCount: 0))+ let root = try self.makeDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let sessionID = UUID()+ let store = MeetingSessionStore(rootDirectory: root)+ var session = MeetingSession(+ id: sessionID,+ configuration: MeetingCaptureConfiguration(+ mode: .inRoom,+ title: "P0b partial",+ microphone: MeetingMicrophoneIdentity(captureDeviceID: "m", displayName: "M")+ ),+ timebase: MeetingTimebaseMetadata(+ startedHostTime: 0,+ machTimebaseNumerator: 1,+ machTimebaseDenominator: 1,+ firstPresentationTime: nil+ )+ )+ let track = MeetingAudioTrack(+ id: UUID(),+ kind: .microphone,+ sourceIdentifier: "m",+ sourceDisplayName: "M",+ format: nil,+ timebase: session.timebase,+ health: .waiting,+ chunks: [chunk]+ )+ session.audioTracks = [track]+ try await store.create(session)+ let directory = try await store.sessionDirectory(for: sessionID)+ let trackURL = directory.appendingPathComponent("tracks/microphone/track.json")+ try FileManager.default.createDirectory(+ at: trackURL.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )+ try JSONEncoder().encode(track).write(to: trackURL)++ let loaded = try await store.load(id: sessionID)++ XCTAssertEqual(loaded?.audioTracks.first?.chunks.first?.finalizationState, .failed)+ XCTAssertEqual(loaded?.audioTracks.first?.chunks.first?.captureAnalysisAsset?.presence, .partial)+ }++ private func hash(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() }+ private func makeDirectory() throws -> URL { let url = FileManager.default.temporaryDirectory.appendingPathComponent("FluidVoice-P0b-recovery-\(UUID().uuidString)"); try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false); return url }+}diff --git a/Tests/FluidDictationIntegrationTests/MeetingAudioChunkLedgerTests.swift b/Tests/FluidDictationIntegrationTests/MeetingAudioChunkLedgerTests.swiftnew file mode 100644index 00000000..5b793c10--- /dev/null+++ b/Tests/FluidDictationIntegrationTests/MeetingAudioChunkLedgerTests.swift@@ -0,0 +1,85 @@+@testable import FluidVoice_Debug+import Foundation+import XCTest++final class MeetingAudioChunkLedgerTests: XCTestCase {+ func testIntentCheckpointAndTerminalAreDurableAndRoundTrip() throws {+ let root = try self.makeDirectory()+ let id = UUID()+ let store = MeetingAudioChunkLedgerStore(sessionDirectory: root)+ let intent = MeetingAudioChunkLedgerIntent(chunkID: id, sequence: 4,+ canonicalStart: MeetingMediaTime(value: 125, timescale: 1000), producerEpoch: 9,+ sourceFormat: MeetingAudioFormat(codec: "lpcm-f32", sampleRate: 48_000, channelCount: 2, bitRate: nil),+ partialRelativeFilePath: "tracks/application/4.partial.caf", createdAt: Date(timeIntervalSince1970: 1_700_000_000))+ try store.writeIntent(intent)+ try store.writeCheckpoint(MeetingAudioChunkLedgerCheckpoint(chunkID: id, expectedFrames: 48000, writtenFrames: 24000,+ lastCanonicalPTS: MeetingMediaTime(value: 625, timescale: 1000), updatedAt: intent.createdAt), for: id)+ try store.writeCheckpoint(MeetingAudioChunkLedgerCheckpoint(chunkID: id, expectedFrames: 48000, writtenFrames: 48000,+ lastCanonicalPTS: MeetingMediaTime(value: 1125, timescale: 1000), updatedAt: intent.createdAt), for: id)+ try store.writeTerminal(MeetingAudioChunkLedgerTerminal(chunkID: id, status: .ready, updatedAt: intent.createdAt, detail: nil), for: id)+ XCTAssertEqual(try store.readIntent(for: id), intent)+ XCTAssertEqual(try store.readCheckpoint(for: id)?.writtenFrames, 48000)+ XCTAssertEqual(try store.readTerminal(for: id)?.status, .ready)+ let intentURL = root.appendingPathComponent("chunk-ledger/\(id.uuidString).intent.json")+ let mode = (try FileManager.default.attributesOfItem(atPath: intentURL.path)[.posixPermissions] as? NSNumber)?.intValue+ XCTAssertEqual(mode, Int(0o600))+ }++ func testIntentIsImmutableAndUnknownTerminalStatusSurvivesDecode() throws {+ let root = try self.makeDirectory(); let id = UUID(); let store = MeetingAudioChunkLedgerStore(sessionDirectory: root)+ let intent = MeetingAudioChunkLedgerIntent(chunkID: id, sequence: 1, canonicalStart: MeetingMediaTime(value: 0, timescale: 1), producerEpoch: 0,+ sourceFormat: MeetingAudioFormat(codec: "lpcm-f32", sampleRate: 16_000, channelCount: 1, bitRate: nil), partialRelativeFilePath: "x.partial.caf", createdAt: Date())+ try store.writeIntent(intent)+ XCTAssertNoThrow(try store.writeIntent(intent))+ var changed = intent; changed.sequence = 2+ XCTAssertThrowsError(try store.writeIntent(changed)) { XCTAssertEqual($0 as? MeetingAudioChunkLedgerError, .conflictingIntent) }+ let terminalData = Data("{\"chunkID\":\"\(id.uuidString)\",\"status\":\"futureTerminal\",\"updatedAt\":\"2024-01-01T00:00:00Z\"}".utf8)+ let terminalURL = root.appendingPathComponent("chunk-ledger/\(id.uuidString).terminal.json")+ try terminalData.write(to: terminalURL)+ XCTAssertEqual(try store.readTerminal(for: id)?.status, .unknown("futureTerminal"))+ }++ func testCheckpointCannotRegressAndReadyRequiresCompleteFrames() throws {+ let root = try self.makeDirectory()+ let id = UUID()+ let store = MeetingAudioChunkLedgerStore(sessionDirectory: root)+ let now = Date(timeIntervalSince1970: 1_700_000_000)+ try store.writeIntent(MeetingAudioChunkLedgerIntent(+ chunkID: id,+ sequence: 0,+ canonicalStart: MeetingMediaTime(value: 0, timescale: 1_000),+ producerEpoch: 0,+ sourceFormat: MeetingAudioFormat(codec: "lpcm-f32", sampleRate: 48_000, channelCount: 1, bitRate: nil),+ partialRelativeFilePath: "tracks/microphone/0.partial.caf",+ createdAt: now+ ))+ try store.writeCheckpoint(MeetingAudioChunkLedgerCheckpoint(+ chunkID: id,+ expectedFrames: 48_000,+ writtenFrames: 24_000,+ lastCanonicalPTS: MeetingMediaTime(value: 500, timescale: 1_000),+ updatedAt: now+ ), for: id)+ XCTAssertThrowsError(try store.writeTerminal(+ MeetingAudioChunkLedgerTerminal(chunkID: id, status: .ready, updatedAt: now, detail: nil),+ for: id+ )) {+ XCTAssertEqual($0 as? MeetingAudioChunkLedgerError, .incompleteReadyTerminal)+ }+ XCTAssertThrowsError(try store.writeCheckpoint(MeetingAudioChunkLedgerCheckpoint(+ chunkID: id,+ expectedFrames: 23_000,+ writtenFrames: 23_000,+ lastCanonicalPTS: MeetingMediaTime(value: 400, timescale: 1_000),+ updatedAt: now+ ), for: id)) {+ XCTAssertEqual($0 as? MeetingAudioChunkLedgerError, .checkpointRegression)+ }+ }++ private func makeDirectory() throws -> URL {+ let url = FileManager.default.temporaryDirectory.appendingPathComponent("FluidVoice-P0b-\(UUID().uuidString)")+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false, attributes: [.posixPermissions: NSNumber(value: Int16(0o700))])+ return url+ }+}diff --git a/Tests/FluidDictationIntegrationTests/MeetingAudioChunkSinkTests.swift b/Tests/FluidDictationIntegrationTests/MeetingAudioChunkSinkTests.swiftnew file mode 100644index 00000000..f2b5493f--- /dev/null+++ b/Tests/FluidDictationIntegrationTests/MeetingAudioChunkSinkTests.swift@@ -0,0 +1,318 @@+@testable import FluidVoice_Debug+import AVFoundation+import CoreMedia+import CryptoKit+import Darwin+import Foundation+import XCTest++private final class MeetingPCMFailureCounter: @unchecked Sendable {+ private let lock = NSLock()+ private var count = 0+ func increment() { lock.lock(); count += 1; lock.unlock() }+ func value() -> Int { lock.lock(); defer { lock.unlock() }; return count }+}++/// P1a's sink fixtures intentionally use real ready CMSampleBuffers. These tests stay in the+/// integration target because the sink is an internal harness type, not a package product.+final class MeetingAudioChunkSinkTests: XCTestCase {+ func testWriterAcceptsEquivalentRawMonoLayoutsWithoutRotatingOrFailing() async throws {+ let root = try self.makeDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let track = MeetingAudioTrack(+ id: UUID(), kind: .applicationAudio, sourceIdentifier: "test", sourceDisplayName: "Test",+ format: nil,+ timebase: MeetingTimebaseMetadata(startedHostTime: 0, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil),+ health: .waiting, chunks: []+ )+ let failures = MeetingPCMFailureCounter()+ let writer = try MeetingAudioChunkWriter(track: track, sessionDirectory: root, chunkDuration: 60) { event in+ if case .interrupted(.writerFailure, _, _) = event { failures.increment() }+ }+ let tags: [UInt32?] = [nil, kAudioChannelLayoutTag_Mono, nil, kAudioChannelLayoutTag_DiscreteInOrder | 1]+ for (index, tag) in tags.enumerated() {+ writer.enqueue(try self.makeRawSampleBuffer(channelCount: 1, layoutTag: tag, frameCount: 480, pts: Double(index) * 0.01))+ }+ let result = await writer.stop()+ let chunk = try XCTUnwrap(result.chunks.first)+ XCTAssertEqual(result.chunks.count, 1)+ XCTAssertEqual(chunk.finalizationState, .finalized)+ XCTAssertEqual(chunk.captureAnalysisAsset?.frameCount, 1_920)+ XCTAssertEqual(failures.value(), 0)+ XCTAssertEqual(chunk.discontinuities, [])+ let file = try AVAudioFile(forReading: root.appendingPathComponent(chunk.relativeFilePath), commonFormat: .pcmFormatFloat32, interleaved: true)+ XCTAssertEqual(file.length, 1_920)+ }++ func testWriterRotatesExactlyOnceForGenuineMonoToStereoChange() async throws {+ let root = try self.makeDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let track = MeetingAudioTrack(+ id: UUID(), kind: .applicationAudio, sourceIdentifier: "test", sourceDisplayName: "Test",+ format: nil,+ timebase: MeetingTimebaseMetadata(startedHostTime: 0, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil),+ health: .waiting, chunks: []+ )+ let failures = MeetingPCMFailureCounter()+ let writer = try MeetingAudioChunkWriter(track: track, sessionDirectory: root, chunkDuration: 60) { event in+ if case .interrupted(.writerFailure, _, _) = event { failures.increment() }+ }+ writer.enqueue(try self.makeRawSampleBuffer(channelCount: 1, layoutTag: nil, frameCount: 480, pts: 0))+ writer.enqueue(try self.makeRawSampleBuffer(channelCount: 2, layoutTag: kAudioChannelLayoutTag_Stereo, frameCount: 480, pts: 0.01))+ let result = await writer.stop()+ XCTAssertEqual(result.chunks.count, 2)+ XCTAssertEqual(result.chunks.map { $0.captureAnalysisAsset?.frameCount }, [480, 480])+ XCTAssertEqual(result.chunks.map(\.finalizationState), [.finalized, .finalized])+ XCTAssertEqual(failures.value(), 0)+ }++ func testSinkFormatMismatchErrorUsesNormalizedExpectedAndActualContracts() throws {+ let root = try self.makeDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let sink = MeetingAudioFilePCMChunkSink(sessionDirectory: root)+ let mono = try XCTUnwrap(AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 48_000, channels: 1, interleaved: true))+ try sink.begin(relativeFilePath: "mismatch.caf", format: mono)+ XCTAssertThrowsError(try sink.append(self.makeRawSampleBuffer(channelCount: 2, layoutTag: kAudioChannelLayoutTag_Stereo, frameCount: 2, pts: 0))) { error in+ let message = (error as NSError).localizedDescription+ XCTAssertTrue(message.contains("lpcm-f32 rate=48000.0 channels=1 layout=mono"), message)+ XCTAssertTrue(message.contains("lpcm-f32 rate=48000.0 channels=2 layout=stereo"), message)+ }+ sink.cancel()+ }++ func testPCMFormatContractCanonicalizesEquivalentMonoAndStereoLayouts() throws {+ let monoNil = try XCTUnwrap(AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 48_000, channels: 1, interleaved: true))+ let mono = try XCTUnwrap(AVAudioFormat(+ commonFormat: .pcmFormatFloat32, sampleRate: 48_000, interleaved: true,+ channelLayout: try XCTUnwrap(AVAudioChannelLayout(layoutTag: kAudioChannelLayoutTag_Mono))+ ))+ let discrete0 = try XCTUnwrap(AVAudioFormat(+ commonFormat: .pcmFormatFloat32, sampleRate: 48_000, interleaved: true,+ channelLayout: try XCTUnwrap(AVAudioChannelLayout(layoutTag: kAudioChannelLayoutTag_DiscreteInOrder | 1))+ ))+ let stereoNil = try XCTUnwrap(AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 48_000, channels: 2, interleaved: true))+ let stereo = try XCTUnwrap(AVAudioFormat(+ commonFormat: .pcmFormatFloat32, sampleRate: 48_000, interleaved: true,+ channelLayout: try XCTUnwrap(AVAudioChannelLayout(layoutTag: kAudioChannelLayoutTag_Stereo))+ ))++ XCTAssertEqual(try MeetingPCMFormatContract(audioFormat: monoNil), try MeetingPCMFormatContract(audioFormat: mono))+ XCTAssertEqual(try MeetingPCMFormatContract(audioFormat: mono), try MeetingPCMFormatContract(audioFormat: discrete0))+ XCTAssertEqual(try MeetingPCMFormatContract(audioFormat: stereoNil), try MeetingPCMFormatContract(audioFormat: stereo))+ XCTAssertNotEqual(try MeetingPCMFormatContract(audioFormat: monoNil), try MeetingPCMFormatContract(audioFormat: stereoNil))+ XCTAssertThrowsError(try MeetingPCMFormatContract(audioFormat: try XCTUnwrap(AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: 48_000, channels: 1, interleaved: true))))+ }++ func testMonoAndStereoPreserveFramesPTSAndPublishCAF() async throws {+ for channels in [1, 2] {+ let root = try self.makeDirectory()+ let format = try XCTUnwrap(AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 48_000, channels: AVAudioChannelCount(channels), interleaved: true))+ let samples: [Float] = (0..<(17 * channels)).map { Float($0 + 1) / 100 }+ let buffer = try self.makeSampleBuffer(format: format, interleavedSamples: samples, frameCount: 17, pts: 2.25)+ let sink = MeetingAudioFilePCMChunkSink(sessionDirectory: root)+ try sink.begin(relativeFilePath: "tracks/application/000001.caf", format: format)+ let receipt = try sink.append(buffer)+ XCTAssertEqual(receipt.framesAccepted, 17)+ XCTAssertEqual(receipt.framesWritten, 17)+ XCTAssertEqual(receipt.presentationStart.seconds, 2.25, accuracy: 0.000_001)+ XCTAssertEqual(receipt.presentationDuration.seconds, 17.0 / 48_000.0, accuracy: 0.000_001)+ let result = sink.finalize()+ let finalization = try result.get()+ XCTAssertEqual(finalization.frameCount, 17)+ XCTAssertEqual(finalization.channelCount, channels)+ XCTAssertEqual(finalization.sampleRate, 48_000)+ let finalURL = root.appendingPathComponent("tracks/application/000001.caf")+ let file = try AVAudioFile(+ forReading: finalURL,+ commonFormat: .pcmFormatFloat32,+ interleaved: true+ )+ let readBuffer = try XCTUnwrap(AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: 17))+ try file.read(into: readBuffer)+ let read = Array(UnsafeBufferPointer(start: readBuffer.audioBufferList.pointee.mBuffers.mData!.assumingMemoryBound(to: Float.self), count: samples.count))+ XCTAssertEqual(read, samples)+ let digest = SHA256.hash(data: try Data(contentsOf: finalURL)).map { String(format: "%02x", $0) }.joined()+ XCTAssertEqual(finalization.sha256, digest)+ XCTAssertFalse(FileManager.default.fileExists(atPath: root.appendingPathComponent("tracks/application/000001.partial.caf").path))+ let mode = (try FileManager.default.attributesOfItem(atPath: finalURL.path)[.posixPermissions] as? NSNumber)?.intValue+ XCTAssertEqual(mode, Int(0o600))+ let parentMode = (try FileManager.default.attributesOfItem(atPath: finalURL.deletingLastPathComponent().path)[.posixPermissions] as? NSNumber)?.intValue+ XCTAssertEqual(parentMode, Int(0o700))+ }+ }++ func testRejectsFormatDriftAndNonFiniteWithoutPublishing() async throws {+ let root = try self.makeDirectory()+ let format = try XCTUnwrap(AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 48_000, channels: 1, interleaved: true))+ let otherFormat = try XCTUnwrap(AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 44_100, channels: 1, interleaved: true))+ let sink = MeetingAudioFilePCMChunkSink(sessionDirectory: root)+ try sink.begin(relativeFilePath: "chunk.caf", format: format)+ XCTAssertThrowsError(try sink.append(self.makeSampleBuffer(format: otherFormat, interleavedSamples: [0, 1], frameCount: 2, pts: 0)))+ // A format mismatch poisons the sink and closes its file. Subsequent buffers must not be+ // retried against that instance; the writer retires the chunk and opens a fresh one.+ XCTAssertThrowsError(try sink.append(self.makeSampleBuffer(format: format, interleavedSamples: [0], frameCount: 1, pts: .nan))) { error in+ XCTAssertEqual(error as? MeetingPCMSinkError, .alreadyFinalizedOrCancelled)+ }+ sink.cancel()+ XCTAssertFalse(FileManager.default.fileExists(atPath: root.appendingPathComponent("chunk.caf").path))+ }++ func testConfinementExistingFinalAndStalePartialAreFailClosed() async throws {+ let root = try self.makeDirectory()+ let format = try XCTUnwrap(AVAudioFormat(standardFormatWithSampleRate: 48_000, channels: 1))+ let sink = MeetingAudioFilePCMChunkSink(sessionDirectory: root)+ XCTAssertThrowsError(try sink.begin(relativeFilePath: "../escape.caf", format: format))+ let partial = root.appendingPathComponent("chunk.partial.caf")+ try Data([1, 2, 3]).write(to: partial)+ try sink.begin(relativeFilePath: "chunk.caf", format: format)+ _ = try sink.append(self.makeSampleBuffer(+ format: format,+ interleavedSamples: [0.25],+ frameCount: 1,+ pts: 0+ ))+ let staleFinalization = sink.finalize()+ _ = try staleFinalization.get()+ XCTAssertEqual(try Data(contentsOf: partial), Data([1, 2, 3]), "stale partial must not be promoted or removed")+ try FileManager.default.removeItem(at: root.appendingPathComponent("chunk.caf"))+ try Data([1]).write(to: root.appendingPathComponent("chunk.caf"))+ let existingFinalSink = MeetingAudioFilePCMChunkSink(sessionDirectory: root)+ XCTAssertThrowsError(try existingFinalSink.begin(relativeFilePath: "chunk.caf", format: format)) { error in+ XCTAssertEqual(error as? MeetingPCMSinkError, .finalPathAlreadyExists("chunk.caf"))+ }+ let outside = root.deletingLastPathComponent().appendingPathComponent("FluidVoice-P1a-outside-\(UUID().uuidString)")+ try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: false)+ let link = root.appendingPathComponent("linked")+ try FileManager.default.createSymbolicLink(at: link, withDestinationURL: outside)+ XCTAssertThrowsError(try MeetingAudioFilePCMChunkSink(sessionDirectory: root).begin(relativeFilePath: "linked/escape.caf", format: format)) { error in+ XCTAssertEqual(error as? MeetingPCMSinkError, .symlinkComponentRejected(link.path))+ }+ }++ func testCancelAndFailedFinalizeNeverCreateFinal() async throws {+ let root = try self.makeDirectory()+ let format = try XCTUnwrap(AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 48_000, channels: 1, interleaved: true))+ let sink = MeetingAudioFilePCMChunkSink(sessionDirectory: root)+ try sink.begin(relativeFilePath: "cancel.caf", format: format)+ sink.cancel()+ XCTAssertFalse(FileManager.default.fileExists(atPath: root.appendingPathComponent("cancel.caf").path))+ let failed = sink.finalize()+ XCTAssertEqual(failed, .failure(.alreadyFinalizedOrCancelled))+ }++ func testNonInterleavedStereoIsPackedInChannelOrderAndCountsPackets() async throws {+ let root = try self.makeDirectory()+ let layout = try XCTUnwrap(AVAudioChannelLayout(layoutTag: kAudioChannelLayoutTag_Stereo))+ let format = try XCTUnwrap(AVAudioFormat(+ commonFormat: .pcmFormatFloat32,+ sampleRate: 48_000,+ interleaved: false,+ channelLayout: layout+ ))+ let sink = MeetingAudioFilePCMChunkSink(sessionDirectory: root)+ try sink.begin(relativeFilePath: "noninterleaved.caf", format: format)+ // Planar input: left frames followed by right frames. The file is interleaved L/R.+ let first = try self.makeSampleBuffer(format: format, interleavedSamples: [0.1, 0.2, 0.3, 0.4, 1.1, 1.2, 1.3, 1.4], frameCount: 4, pts: 0)+ let second = try self.makeSampleBuffer(format: format, interleavedSamples: [0.5, 0.6, 1.5, 1.6], frameCount: 2, pts: 4.0 / 48_000.0)+ XCTAssertEqual(try sink.append(first).framesWritten, 4)+ XCTAssertEqual(try sink.append(second).framesWritten, 2)+ let finalization = try sink.finalize().get()+ XCTAssertEqual(finalization.frameCount, 6)+ let file = try AVAudioFile(forReading: root.appendingPathComponent("noninterleaved.caf"), commonFormat: .pcmFormatFloat32, interleaved: true)+ let buffer = try XCTUnwrap(AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: 6))+ try file.read(into: buffer)+ let values = Array(UnsafeBufferPointer(start: buffer.audioBufferList.pointee.mBuffers.mData!.assumingMemoryBound(to: Float.self), count: 12))+ XCTAssertEqual(values, [0.1, 1.1, 0.2, 1.2, 0.3, 1.3, 0.4, 1.4, 0.5, 1.5, 0.6, 1.6])+ }++ func testFinalizeWithoutFramesFailsAndCleansOwnedPartial() async throws {+ let root = try self.makeDirectory()+ let format = try XCTUnwrap(AVAudioFormat(+ commonFormat: .pcmFormatFloat32,+ sampleRate: 48_000,+ channels: 1,+ interleaved: true+ ))+ let sink = MeetingAudioFilePCMChunkSink(sessionDirectory: root)+ try sink.begin(relativeFilePath: "empty.caf", format: format)++ let result = sink.finalize()++ guard case let .failure(.finalizationVerificationFailed(detail)) = result else {+ return XCTFail("Expected an empty-CAF verification failure, got \(result)")+ }+ XCTAssertEqual(detail, "CAF contains no written frames")+ XCTAssertFalse(FileManager.default.fileExists(atPath: root.appendingPathComponent("empty.caf").path))+ let partials = try FileManager.default.contentsOfDirectory(atPath: root.path)+ .filter { $0.contains(".partial.") }+ XCTAssertTrue(partials.isEmpty)+ }++ private func makeDirectory() throws -> URL {+ let url = FileManager.default.temporaryDirectory.appendingPathComponent("FluidVoice-P1a-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false, attributes: [.posixPermissions: NSNumber(value: Int16(0o700))])+ return url+ }++ private func makeRawSampleBuffer(channelCount: Int, layoutTag: UInt32?, frameCount: Int, pts: Double) throws -> CMSampleBuffer {+ let bytesPerFrame = channelCount * MemoryLayout<Float>.size+ var asbd = AudioStreamBasicDescription(+ mSampleRate: 48_000, mFormatID: kAudioFormatLinearPCM, mFormatFlags: kAudioFormatFlagsNativeFloatPacked,+ mBytesPerPacket: UInt32(bytesPerFrame), mFramesPerPacket: 1, mBytesPerFrame: UInt32(bytesPerFrame),+ mChannelsPerFrame: UInt32(channelCount), mBitsPerChannel: 32, mReserved: 0+ )+ var description: CMAudioFormatDescription?+ let layout = layoutTag.flatMap { AVAudioChannelLayout(layoutTag: $0) }+ let layoutStatus: OSStatus+ if let layout, let layoutData = MeetingPCMFormatContract.layoutData(layout) {+ layoutStatus = layoutData.withUnsafeBytes { bytes in+ CMAudioFormatDescriptionCreate(allocator: kCFAllocatorDefault, asbd: &asbd,+ layoutSize: layoutData.count, layout: bytes.baseAddress!.assumingMemoryBound(to: AudioChannelLayout.self),+ magicCookieSize: 0, magicCookie: nil, extensions: nil, formatDescriptionOut: &description)+ }+ } else {+ layoutStatus = CMAudioFormatDescriptionCreate(allocator: kCFAllocatorDefault, asbd: &asbd,+ layoutSize: 0, layout: nil, magicCookieSize: 0, magicCookie: nil, extensions: nil, formatDescriptionOut: &description)+ }+ XCTAssertEqual(layoutStatus, noErr)+ let values = Array(repeating: Float(0.25), count: frameCount * channelCount)+ let bytes = values.withUnsafeBytes { Data($0) }+ var block: CMBlockBuffer?+ XCTAssertEqual(CMBlockBufferCreateWithMemoryBlock(allocator: kCFAllocatorDefault, memoryBlock: nil,+ blockLength: bytes.count, blockAllocator: kCFAllocatorDefault, customBlockSource: nil, offsetToData: 0,+ dataLength: bytes.count, flags: kCMBlockBufferAssureMemoryNowFlag, blockBufferOut: &block), noErr)+ let blockBuffer = try XCTUnwrap(block)+ XCTAssertEqual(bytes.withUnsafeBytes { CMBlockBufferReplaceDataBytes(with: $0.baseAddress!, blockBuffer: blockBuffer, offsetIntoDestination: 0, dataLength: bytes.count) }, noErr)+ var timing = CMSampleTimingInfo(duration: CMTime(value: 1, timescale: 48_000), presentationTimeStamp: CMTime(seconds: pts, preferredTimescale: 48_000), decodeTimeStamp: .invalid)+ var sample: CMSampleBuffer?+ XCTAssertEqual(CMSampleBufferCreateReady(allocator: kCFAllocatorDefault, dataBuffer: blockBuffer, formatDescription: try XCTUnwrap(description), sampleCount: frameCount, sampleTimingEntryCount: 1, sampleTimingArray: &timing, sampleSizeEntryCount: 0, sampleSizeArray: nil, sampleBufferOut: &sample), noErr)+ return try XCTUnwrap(sample)+ }++ private func makeSampleBuffer(format: AVAudioFormat, interleavedSamples: [Float], frameCount: Int, pts: Double) throws -> CMSampleBuffer {+ let bytes = interleavedSamples.withUnsafeBytes { Data($0) }+ var block: CMBlockBuffer?+ var status = CMBlockBufferCreateWithMemoryBlock(allocator: kCFAllocatorDefault, memoryBlock: nil, blockLength: bytes.count,+ blockAllocator: kCFAllocatorDefault, customBlockSource: nil, offsetToData: 0,+ dataLength: bytes.count, flags: 0, blockBufferOut: &block)+ guard status == noErr, let block else { throw NSError(domain: "P1a", code: Int(status)) }+ status = bytes.withUnsafeBytes { ptr in+ CMBlockBufferReplaceDataBytes(with: ptr.baseAddress!, blockBuffer: block, offsetIntoDestination: 0, dataLength: bytes.count)+ }+ guard status == noErr else { throw NSError(domain: "P1a", code: Int(status)) }+ let presentationTimeStamp = pts.isFinite+ ? CMTime(seconds: pts, preferredTimescale: 1_000_000)+ : .invalid+ var timing = CMSampleTimingInfo(+ duration: CMTime(value: 1, timescale: Int32(format.sampleRate)),+ presentationTimeStamp: presentationTimeStamp,+ decodeTimeStamp: .invalid+ )+ var sampleBuffer: CMSampleBuffer?+ status = CMSampleBufferCreateReady(allocator: kCFAllocatorDefault, dataBuffer: block, formatDescription: format.formatDescription, sampleCount: frameCount,+ sampleTimingEntryCount: 1, sampleTimingArray: &timing, sampleSizeEntryCount: 0, sampleSizeArray: nil,+ sampleBufferOut: &sampleBuffer)+ guard status == noErr, let sampleBuffer else { throw NSError(domain: "P1a", code: Int(status)) }+ return sampleBuffer+ }+}diff --git a/Tests/FluidDictationIntegrationTests/MeetingCanonicalPipelineTests.swift b/Tests/FluidDictationIntegrationTests/MeetingCanonicalPipelineTests.swiftnew file mode 100644index 00000000..304d0a5b--- /dev/null+++ b/Tests/FluidDictationIntegrationTests/MeetingCanonicalPipelineTests.swift@@ -0,0 +1,934 @@+import CoreMedia+@testable import FluidVoice_Debug+import Foundation+import XCTest++/// Stage C2b2 of `MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md`: the wired canonical path —+/// manifest built under the pipeline's serialization lease, handed to the backend, assembled with+/// product echo verdicts, persisted as a verified result sidecar, and published by the+/// coordinator only inside the session save that precedes checkpoint removal.+///+/// No fixture writes real audio: the manifest builder's observation boundary is faked per chunk,+/// and fixture backends derive their evidence from the manifest they are handed, so every unit,+/// receipt and span reference is one the validator actually proved.+@MainActor+final class MeetingCanonicalPipelineTests: XCTestCase {+ private static let canonicalBackendID = MeetingBackendID(rawValue: "fixture.canonical-c2b2")++ // MARK: - Fixtures++ private actor Latch {+ private var waiters: [CheckedContinuation<Void, Never>] = []+ private var isOpen = false++ func wait() async {+ if self.isOpen { return }+ await withCheckedContinuation { self.waiters.append($0) }+ }++ func open() {+ self.isOpen = true+ let parked = self.waiters+ self.waiters.removeAll()+ for continuation in parked {+ continuation.resume()+ }+ }+ }++ private struct FixtureObserver: MeetingChunkAudioObserving {+ let results: [MeetingAnalysisChunkKey: MeetingChunkObservationResult]++ func observe(+ chunk: MeetingAudioChunk,+ trackID: MeetingAudioTrackID+ ) -> MeetingChunkObservationResult {+ self.results[MeetingAnalysisChunkKey(trackID: trackID, chunkID: chunk.id)]+ ?? .failed(.unreadable, detail: "no fixture observation")+ }+ }++ private final class RecordingObserver: MeetingChunkAudioObserving, @unchecked Sendable {+ private(set) var callCount = 0++ func observe(+ chunk: MeetingAudioChunk,+ trackID: MeetingAudioTrackID+ ) -> MeetingChunkObservationResult {+ self.callCount += 1+ return .failed(.unreadable, detail: "must not be called on this path")+ }+ }++ private final class FixtureEchoProvider: MeetingUnitEchoVerdictProviding, @unchecked Sendable {+ var verdicts: [String: MeetingUnitEchoVerdict]+ var gate: Latch?+ var onInvoked: (() -> Void)?+ private(set) var callCount = 0++ init(verdicts: [String: MeetingUnitEchoVerdict] = [:]) {+ self.verdicts = verdicts+ }++ func echoVerdicts(+ for _: MeetingFinalTranscriptEvidence,+ manifest _: MeetingAnalysisManifest,+ plan _: MeetingBackendPlan+ ) async throws -> [String: MeetingUnitEchoVerdict] {+ self.callCount += 1+ self.onInvoked?()+ if let gate { await gate.wait() }+ return self.verdicts+ }+ }++ private final class CanonicalFixtureBackend: MeetingTranscriptionBackend {+ let descriptor: MeetingBackendDescriptor+ private let makeBundle: @MainActor (MeetingBackendPlan, MeetingAnalysisManifest) throws -> MeetingCanonicalResultBundle+ var gate: Latch?+ var onEnterExecute: (() -> Void)?+ private(set) var executeCallCount = 0+ private(set) var receivedManifest: MeetingAnalysisManifest??++ init(+ version: String = "c2b2-test",+ makeBundle: @escaping @MainActor (MeetingBackendPlan, MeetingAnalysisManifest) throws -> MeetingCanonicalResultBundle+ ) {+ self.descriptor = MeetingBackendDescriptor(+ id: MeetingCanonicalPipelineTests.canonicalBackendID,+ version: version,+ execution: .local,+ supportedLanguageCodes: ["en"],+ supportedTrackKinds: Set(MeetingAudioTrackKind.allCases),+ supportedFinalPrecisions: [.word],+ resultContract: .canonicalEvidence,+ knownLimits: ["Fixture only; performs no inference."]+ )+ self.makeBundle = makeBundle+ }++ func plan(_ request: MeetingBackendRequest) throws -> MeetingBackendPlan {+ MeetingBackendPlan(request: request, descriptor: self.descriptor)+ }++ func execute(+ plan: MeetingBackendPlan,+ manifest: MeetingAnalysisManifest?,+ progress: @escaping @MainActor (MeetingProcessingStage) -> Void+ ) async throws -> MeetingBackendOutcome {+ self.executeCallCount += 1+ self.receivedManifest = manifest+ self.onEnterExecute?()+ if let gate { await gate.wait() }+ guard let manifest else {+ throw MeetingBackendError.outcomeContractMismatch(+ backend: self.descriptor.id, declared: .canonicalEvidence+ )+ }+ return try .canonicalEvidence(self.makeBundle(plan, manifest))+ }+ }++ private func makeChunk(sequence: Int, start: Double, end: Double) -> MeetingAudioChunk {+ MeetingAudioChunk(+ id: UUID(),+ sequence: sequence,+ relativeFilePath: "tracks/microphone/chunk_\(sequence).caf",+ presentationStart: MeetingMediaTime(value: Int64((start * 1000).rounded()), timescale: 1000),+ presentationEnd: MeetingMediaTime(value: Int64((end * 1000).rounded()), timescale: 1000),+ discontinuities: [],+ sha256: String(repeating: "a", count: 64),+ byteCount: 1024,+ finalizationState: .finalized+ )+ }++ private func makeObserved(+ _ chunk: MeetingAudioChunk,+ duration: Double+ ) -> MeetingChunkObservationResult {+ .observed(MeetingChunkObservedAudio(+ byteCount: chunk.byteCount,+ sha256: chunk.sha256,+ decoded: MeetingChunkDecodedFacts(+ sampleRate: 100,+ channelCount: 1,+ frameCount: Int64((duration * 100).rounded()),+ durationSeconds: duration,+ codecPriming: .measuredFrames(0),+ processingFormatDescription: "fixture"+ )+ ))+ }++ private func makeMicTrack(chunks: [MeetingAudioChunk], eraStart: Double) -> MeetingAudioTrack {+ MeetingAudioTrack(+ id: UUID(),+ kind: .microphone,+ sourceIdentifier: "microphone",+ sourceDisplayName: "microphone",+ format: nil,+ timebase: MeetingTimebaseMetadata(+ startedHostTime: 7,+ machTimebaseNumerator: 1,+ machTimebaseDenominator: 1,+ firstPresentationTime: nil+ ),+ health: .waiting,+ chunks: chunks,+ captureMethod: .voiceProcessing,+ captureEras: [MeetingCaptureEra(+ method: .voiceProcessing,+ deviceUID: "mic-a",+ deviceName: "mic-a",+ roleAtElection: .unknown,+ echoProtection: .voiceProcessed,+ startSeconds: eraStart+ )]+ )+ }++ private func makeSession(+ mode: MeetingCaptureMode,+ tracks: [MeetingAudioTrack],+ openAttempt: Bool = true+ ) -> MeetingSession {+ var session = MeetingSession(+ configuration: MeetingCaptureConfiguration(+ mode: mode,+ title: "Canonical fixture",+ application: mode == .onlineCall+ ? MeetingApplicationIdentity(bundleIdentifier: "fixture.app", displayName: "Fixture")+ : nil,+ microphone: MeetingMicrophoneIdentity(captureDeviceID: "mic-a", displayName: "Mic")+ ),+ timebase: MeetingTimebaseMetadata(+ startedHostTime: 7,+ machTimebaseNumerator: 1,+ machTimebaseDenominator: 1,+ firstPresentationTime: nil+ )+ )+ session.audioTracks = tracks+ if openAttempt {+ session.processingAttempts = [MeetingProcessingAttempt(+ id: UUID(),+ startedAt: Date(timeIntervalSinceNow: -30),+ completedAt: nil,+ stage: .pending,+ pipelineVersion: MeetingProcessingPipeline.pipelineVersion,+ asrProvider: nil,+ asrModel: nil,+ diarizationModel: nil,+ lastCompletedTrackID: nil,+ errorCode: nil+ )]+ }+ return session+ }++ private func makeInRoomFixture() -> (+ session: MeetingSession,+ track: MeetingAudioTrack,+ chunk: MeetingAudioChunk+ ) {+ let chunk = self.makeChunk(sequence: 0, start: 100, end: 110)+ let track = self.makeMicTrack(chunks: [chunk], eraStart: 100)+ return (self.makeSession(mode: .inRoom, tracks: [track]), track, chunk)+ }++ /// Deterministic bundle derived from the manifest the pipeline handed over: one word per+ /// admissible span, one processed receipt tiling each span.+ private func standardBundle(+ plan: MeetingBackendPlan,+ manifest: MeetingAnalysisManifest,+ text: String = "hello"+ ) -> MeetingCanonicalResultBundle {+ let receipts = manifest.allSpans.enumerated().map { index, span in+ MeetingSpanCoverageReceipt(+ id: "receipt-\(index)",+ spanID: span.id,+ analysisStart: span.analysisInterval.start,+ analysisEnd: span.analysisInterval.end,+ status: .processed+ )+ }+ let units = manifest.allSpans.enumerated().map { index, span in+ MeetingFinalTextUnit(+ id: "unit-\(index)",+ trackID: span.trackID,+ analysisEpochID: span.analysisEpochID,+ precision: .word,+ text: text,+ analysisStart: span.analysisInterval.start,+ analysisEnd: span.analysisInterval.end,+ speaker: .assigned(MeetingBackendSpeakerToken(+ analysisEpochID: span.analysisEpochID, label: "slot-0"+ )),+ analysisSpanIDs: [span.id]+ )+ }+ return MeetingCanonicalResultBundle(+ evidence: MeetingFinalTranscriptEvidence(+ backendID: plan.backendID,+ attemptID: plan.attemptID,+ units: units+ ),+ coverageReceipts: receipts+ )+ }++ private func makeCanonicalPipeline(+ backend: CanonicalFixtureBackend,+ observer: any MeetingChunkAudioObserving,+ echoProvider: (any MeetingUnitEchoVerdictProviding)? = nil,+ probe: ((MeetingResultSidecarReference) -> Void)? = nil+ ) -> MeetingProcessingPipeline {+ let registry = MeetingTranscriptionBackendRegistry(defaultBackendID: Self.canonicalBackendID)+ registry.register(Self.canonicalBackendID) { _ in backend }+ return MeetingProcessingPipeline(+ asrServiceProvider: {+ XCTFail("Canonical dispatch must not reach ASR readiness")+ return ASRService()+ },+ serializationGate: MeetingProcessingSerializationGate(),+ backendRegistry: registry,+ backendID: nil,+ chunkObserver: observer,+ echoVerdictProvider: echoProvider,+ canonicalSidecarVerifiedProbe: probe+ )+ }++ private func makeTempSessionDirectory() throws -> URL {+ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("canonical-pipeline-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)+ self.addTeardownBlock { try? FileManager.default.removeItem(at: url) }+ return url+ }++ private func sidecarFiles(in directory: URL) -> [URL] {+ (try? FileManager.default.contentsOfDirectory(+ at: directory,+ includingPropertiesForKeys: nil+ ).filter { $0.lastPathComponent.hasSuffix(".sidecar.json") }) ?? []+ }++ // MARK: - Legacy isolation++ func testLegacyBackendBuildsNoManifestWritesNoSidecarAndReturnsUnchangedResult() async throws {+ let fixture = self.makeInRoomFixture()+ let directory = try self.makeTempSessionDirectory()+ let observer = RecordingObserver()+ let echoProvider = FixtureEchoProvider()+ let expected = MeetingProcessingResult(+ speakers: [],+ segments: [MeetingTranscriptSegment(+ id: UUID(),+ start: MeetingMediaTime(value: 100_000, timescale: 1000),+ end: MeetingMediaTime(value: 101_000, timescale: 1000),+ sourceTrackID: fixture.track.id,+ speakerID: nil,+ text: "legacy",+ revision: 0,+ status: .final,+ overlap: .none,+ completeness: .complete+ )],+ attempt: MeetingProcessingAttempt(+ id: UUID(),+ startedAt: Date(),+ completedAt: Date(),+ stage: .completed,+ pipelineVersion: MeetingProcessingPipeline.pipelineVersion,+ asrProvider: "legacy-fixture",+ asrModel: "legacy-fixture",+ diarizationModel: nil,+ lastCompletedTrackID: nil,+ errorCode: nil+ )+ )++ final class LegacyFixtureBackend: MeetingTranscriptionBackend {+ let descriptor = MeetingBackendDescriptor(+ id: MeetingCanonicalPipelineTests.canonicalBackendID,+ version: "legacy-fixture",+ execution: .local,+ supportedLanguageCodes: ["en"],+ supportedTrackKinds: Set(MeetingAudioTrackKind.allCases),+ supportedFinalPrecisions: [.utterance],+ resultContract: .legacyResult,+ knownLimits: []+ )+ let result: MeetingProcessingResult+ private(set) var receivedManifest: MeetingAnalysisManifest??++ init(result: MeetingProcessingResult) {+ self.result = result+ }++ func plan(_ request: MeetingBackendRequest) throws -> MeetingBackendPlan {+ MeetingBackendPlan(request: request, descriptor: self.descriptor)+ }++ func execute(+ plan: MeetingBackendPlan,+ manifest: MeetingAnalysisManifest?,+ progress: @escaping @MainActor (MeetingProcessingStage) -> Void+ ) async throws -> MeetingBackendOutcome {+ self.receivedManifest = manifest+ return .legacyCompatibility(self.result)+ }+ }+ let backend = LegacyFixtureBackend(result: expected)+ let registry = MeetingTranscriptionBackendRegistry(defaultBackendID: Self.canonicalBackendID)+ registry.register(Self.canonicalBackendID) { _ in backend }+ let pipeline = MeetingProcessingPipeline(+ asrServiceProvider: {+ XCTFail("Legacy fixture must not load ASR")+ return ASRService()+ },+ serializationGate: MeetingProcessingSerializationGate(),+ backendRegistry: registry,+ backendID: nil,+ chunkObserver: observer,+ echoVerdictProvider: echoProvider+ )++ let result = try await pipeline.process(+ session: fixture.session,+ sessionDirectory: directory,+ progress: { _ in }+ )++ XCTAssertEqual(observer.callCount, 0, "the legacy path must not observe chunks for a manifest")+ XCTAssertEqual(echoProvider.callCount, 0, "the legacy path must not request echo verdicts")+ XCTAssertNil(backend.receivedManifest ?? nil, "the legacy backend receives no manifest")+ XCTAssertTrue(self.sidecarFiles(in: directory).isEmpty, "the legacy path writes no sidecar")+ XCTAssertNil(result.resultSidecarReference)+ XCTAssertEqual(result.segments.map(\.text), ["legacy"])+ XCTAssertEqual(result.attempt.id, expected.attempt.id)+ XCTAssertNil(result.attempt.backendID)+ XCTAssertNil(result.attempt.backendVersion)+ }++ // MARK: - Canonical success and retry++ func testCanonicalInRoomSuccessPublishesOnlyAfterVerifiedSidecar() async throws {+ let fixture = self.makeInRoomFixture()+ let directory = try self.makeTempSessionDirectory()+ let openAttemptID = try XCTUnwrap(fixture.session.processingAttempts.last?.id)+ let echoProvider = FixtureEchoProvider()+ let backend = CanonicalFixtureBackend { plan, manifest in+ self.standardBundle(plan: plan, manifest: manifest)+ }+ let pipeline = self.makeCanonicalPipeline(+ backend: backend,+ observer: FixtureObserver(results: [+ MeetingAnalysisChunkKey(trackID: fixture.track.id, chunkID: fixture.chunk.id):+ self.makeObserved(fixture.chunk, duration: 10),+ ]),+ echoProvider: echoProvider+ )++ let result = try await pipeline.process(+ session: fixture.session,+ sessionDirectory: directory,+ progress: { _ in }+ )++ // The backend received the product-owned manifest built from its own frozen plan.+ let manifest = try XCTUnwrap(backend.receivedManifest ?? nil)+ XCTAssertEqual(manifest.attemptID, openAttemptID)+ XCTAssertEqual(manifest.allSpans.count, 1)+ XCTAssertEqual(echoProvider.callCount, 1, "the pipeline obtains verdicts from the provider")++ // The open attempt was reused and finalized with backend/config lineage, not renumbered.+ XCTAssertEqual(result.attempt.id, openAttemptID)+ XCTAssertEqual(result.attempt.startedAt, fixture.session.processingAttempts.last?.startedAt)+ XCTAssertEqual(result.attempt.stage, .completed)+ XCTAssertNotNil(result.attempt.completedAt)+ XCTAssertEqual(result.attempt.backendID, Self.canonicalBackendID.rawValue)+ XCTAssertEqual(result.attempt.backendVersion, "c2b2-test")+ XCTAssertEqual(result.attempt.asrModel, MeetingFinalProcessingConfiguration.defaultASRModel)+ XCTAssertEqual(result.attempt.languageCode, "en")++ XCTAssertEqual(result.segments.count, 1)+ XCTAssertEqual(result.speakers.count, 1)+ XCTAssertFalse(result.speakers[0].isLocalUser)+ XCTAssertTrue(result.coverageGaps.isEmpty)+ XCTAssertTrue(result.skippedChunkIDs.isEmpty)++ // Publication carries a reference whose content verifies on disk right now.+ let reference = try XCTUnwrap(result.resultSidecarReference)+ let sidecar = try MeetingResultSidecarStore(sessionDirectory: directory).read(+ expectedAttemptID: openAttemptID,+ expectedBackendID: Self.canonicalBackendID,+ reference: reference+ )+ XCTAssertEqual(sidecar.units.map(\.id), ["unit-0"])+ XCTAssertEqual(sidecar.dispositions.map(\.disposition), [.emitted])+ XCTAssertEqual(sidecar.coverageReceipts.count, 1)+ XCTAssertEqual(self.sidecarFiles(in: directory).count, 1)+ }++ func testCanonicalByteIdenticalRetryJoinsExistingSidecar() async throws {+ let fixture = self.makeInRoomFixture()+ let directory = try self.makeTempSessionDirectory()+ let observer = FixtureObserver(results: [+ MeetingAnalysisChunkKey(trackID: fixture.track.id, chunkID: fixture.chunk.id):+ self.makeObserved(fixture.chunk, duration: 10),+ ])+ let backend = CanonicalFixtureBackend { plan, manifest in+ self.standardBundle(plan: plan, manifest: manifest)+ }+ let pipeline = self.makeCanonicalPipeline(+ backend: backend, observer: observer+ )++ let first = try await pipeline.process(+ session: fixture.session, sessionDirectory: directory, progress: { _ in }+ )+ let fileURL = try XCTUnwrap(self.sidecarFiles(in: directory).first)+ let firstBytes = try Data(contentsOf: fileURL)++ // Same session value, same still-open attempt: the retry's output is byte-identical, so+ // the store joins the existing immutable sidecar instead of rewriting it.+ let second = try await pipeline.process(+ session: fixture.session, sessionDirectory: directory, progress: { _ in }+ )++ XCTAssertEqual(second.resultSidecarReference, first.resultSidecarReference)+ XCTAssertEqual(self.sidecarFiles(in: directory).count, 1)+ XCTAssertEqual(try Data(contentsOf: fileURL), firstBytes)+ }++ func testCanonicalConflictingSameAttemptOutputPreservesFirstSidecar() async throws {+ let fixture = self.makeInRoomFixture()+ let directory = try self.makeTempSessionDirectory()+ let observer = FixtureObserver(results: [+ MeetingAnalysisChunkKey(trackID: fixture.track.id, chunkID: fixture.chunk.id):+ self.makeObserved(fixture.chunk, duration: 10),+ ])+ let backend = CanonicalFixtureBackend { plan, manifest in+ self.standardBundle(plan: plan, manifest: manifest)+ }+ let pipeline = self.makeCanonicalPipeline(+ backend: backend, observer: observer+ )+ _ = try await pipeline.process(+ session: fixture.session, sessionDirectory: directory, progress: { _ in }+ )+ let fileURL = try XCTUnwrap(self.sidecarFiles(in: directory).first)+ let firstBytes = try Data(contentsOf: fileURL)++ // Same attempt, different output: never overwrite the immutable first result.+ let conflicting = CanonicalFixtureBackend { plan, manifest in+ self.standardBundle(plan: plan, manifest: manifest, text: "changed")+ }+ let conflictPipeline = self.makeCanonicalPipeline(+ backend: conflicting, observer: observer+ )+ do {+ _ = try await conflictPipeline.process(+ session: fixture.session, sessionDirectory: directory, progress: { _ in }+ )+ XCTFail("Divergent output under the same attempt must be a typed conflict")+ } catch {+ let openAttemptID = try XCTUnwrap(fixture.session.processingAttempts.last?.id)+ XCTAssertEqual(+ error as? MeetingResultSidecarStoreError,+ .conflictingExistingSidecar(attemptID: openAttemptID)+ )+ }+ XCTAssertEqual(try Data(contentsOf: fileURL), firstBytes, "the first sidecar is preserved")+ XCTAssertEqual(self.sidecarFiles(in: directory).count, 1)+ }++ // MARK: - Fail-closed echo evidence++ func testCanonicalOnlineMicrophoneWithoutEchoVerdictsFailsWithoutPublication() async throws {+ let chunk = self.makeChunk(sequence: 0, start: 100, end: 110)+ let track = self.makeMicTrack(chunks: [chunk], eraStart: 100)+ let session = self.makeSession(mode: .onlineCall, tracks: [track])+ let directory = try self.makeTempSessionDirectory()+ let backend = CanonicalFixtureBackend { plan, manifest in+ self.standardBundle(plan: plan, manifest: manifest)+ }+ // No provider injected: the default is fail-closed and supplies no verdicts.+ let pipeline = self.makeCanonicalPipeline(+ backend: backend,+ observer: FixtureObserver(results: [+ MeetingAnalysisChunkKey(trackID: track.id, chunkID: chunk.id):+ self.makeObserved(chunk, duration: 10),+ ])+ )++ do {+ _ = try await pipeline.process(+ session: session, sessionDirectory: directory, progress: { _ in }+ )+ XCTFail("Online microphone text without echo evidence must not assemble")+ } catch {+ XCTAssertEqual(+ error as? MeetingAssemblyError,+ .missingEchoVerdict(unitID: "unit-0")+ )+ }+ XCTAssertTrue(+ self.sidecarFiles(in: directory).isEmpty,+ "a failed assembly publishes no sidecar"+ )+ }++ // MARK: - Cancellation boundaries++ func testCancellationAfterBackendReturnSuppressesCanonicalPublication() async throws {+ let fixture = self.makeInRoomFixture()+ let directory = try self.makeTempSessionDirectory()+ let entered = Latch()+ let gate = Latch()+ let backend = CanonicalFixtureBackend { plan, manifest in+ self.standardBundle(plan: plan, manifest: manifest)+ }+ backend.gate = gate+ backend.onEnterExecute = { Task { await entered.open() } }+ let pipeline = self.makeCanonicalPipeline(+ backend: backend,+ observer: FixtureObserver(results: [+ MeetingAnalysisChunkKey(trackID: fixture.track.id, chunkID: fixture.chunk.id):+ self.makeObserved(fixture.chunk, duration: 10),+ ])+ )++ let task = Task {+ try await pipeline.process(+ session: fixture.session, sessionDirectory: directory, progress: { _ in }+ )+ }+ await entered.wait()+ task.cancel()+ await gate.open()+ do {+ _ = try await task.value+ XCTFail("A non-cooperative backend's late success must be suppressed")+ } catch is CancellationError {} catch { XCTFail("Unexpected error: \(error)") }+ XCTAssertTrue(self.sidecarFiles(in: directory).isEmpty)+ }++ func testCancellationAfterEchoVerdictsSuppressesCanonicalPublication() async throws {+ let fixture = self.makeInRoomFixture()+ let directory = try self.makeTempSessionDirectory()+ let entered = Latch()+ let gate = Latch()+ let echoProvider = FixtureEchoProvider()+ echoProvider.gate = gate+ echoProvider.onInvoked = { Task { await entered.open() } }+ let backend = CanonicalFixtureBackend { plan, manifest in+ self.standardBundle(plan: plan, manifest: manifest)+ }+ let pipeline = self.makeCanonicalPipeline(+ backend: backend,+ observer: FixtureObserver(results: [+ MeetingAnalysisChunkKey(trackID: fixture.track.id, chunkID: fixture.chunk.id):+ self.makeObserved(fixture.chunk, duration: 10),+ ]),+ echoProvider: echoProvider+ )++ let task = Task {+ try await pipeline.process(+ session: fixture.session, sessionDirectory: directory, progress: { _ in }+ )+ }+ await entered.wait()+ task.cancel()+ await gate.open()+ do {+ _ = try await task.value+ XCTFail("Cancellation after verdicts must suppress publication")+ } catch is CancellationError {} catch { XCTFail("Unexpected error: \(error)") }+ XCTAssertTrue(self.sidecarFiles(in: directory).isEmpty)+ }++ func testCancellationAfterSidecarWriteSuppressesPublicationAndRetryJoins() async throws {+ let fixture = self.makeInRoomFixture()+ let directory = try self.makeTempSessionDirectory()+ let observer = FixtureObserver(results: [+ MeetingAnalysisChunkKey(trackID: fixture.track.id, chunkID: fixture.chunk.id):+ self.makeObserved(fixture.chunk, duration: 10),+ ])+ let backend = CanonicalFixtureBackend { plan, manifest in+ self.standardBundle(plan: plan, manifest: manifest)+ }+ let cancelBox = CancelBox()+ let pipeline = self.makeCanonicalPipeline(+ backend: backend,+ observer: observer,+ probe: { _ in cancelBox.cancel() }+ )++ let task = Task {+ try await pipeline.process(+ session: fixture.session, sessionDirectory: directory, progress: { _ in }+ )+ }+ cancelBox.cancel = { task.cancel() }+ do {+ _ = try await task.value+ XCTFail("Cancellation after the verified sidecar must suppress publication")+ } catch is CancellationError {} catch { XCTFail("Unexpected error: \(error)") }++ // The verified sidecar stays on disk, unreferenced, and is never deleted silently.+ let fileURL = try XCTUnwrap(self.sidecarFiles(in: directory).first)+ let firstBytes = try Data(contentsOf: fileURL)++ // A byte-identical retry of the same open attempt joins it.+ cancelBox.cancel = {}+ let retry = try await pipeline.process(+ session: fixture.session, sessionDirectory: directory, progress: { _ in }+ )+ XCTAssertNotNil(retry.resultSidecarReference)+ XCTAssertEqual(self.sidecarFiles(in: directory).count, 1)+ XCTAssertEqual(try Data(contentsOf: fileURL), firstBytes)+ }++ // MARK: - Gap reasons and session schema++ func testCoverageGapReasonsMapOneToOneWithoutRelabeling() {+ let expected: [MeetingAssemblyCoverageGapReason: MeetingTranscriptCoverageGapReason] = [+ .inadmissibleCaptureEra: .inadmissibleCaptureEra,+ .missingOrUnreadableAudio: .missingOrUnreadableAudio,+ .processingFailed: .processingFailed,+ .skipped: .processingSkipped,+ .providerTruncated: .providerTruncated,+ .excludedUnitIncompleteCoverage: .excludedUnitIncompleteCoverage,+ ]+ XCTAssertEqual(+ Set(MeetingAssemblyCoverageGapReason.allCases),+ Set(expected.keys),+ "every assembly reason needs an explicit product mapping"+ )+ for (assemblyReason, productReason) in expected {+ XCTAssertEqual(+ MeetingProcessingPipeline.productCoverageGapReason(for: assemblyReason),+ productReason+ )+ }+ // Only an excluded capture era may wear the pre-existing unprotected-microphone label.+ let mapped = Set(expected.values)+ XCTAssertEqual(mapped.count, expected.count)+ }++ func testOldSessionJSONDecodesNilSidecarReferenceAndNewReferenceRoundTrips() throws {+ let fixture = self.makeInRoomFixture()+ let encoder = JSONEncoder()+ encoder.dateEncodingStrategy = .iso8601+ let decoder = JSONDecoder()+ decoder.dateDecodingStrategy = .iso8601++ // Sessions written before canonical publication carry no key at all.+ let data = try encoder.encode(fixture.session)+ let object = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any])+ XCTAssertNil(object["resultSidecarReference"])+ let legacyDecoded = try decoder.decode(MeetingSession.self, from: data)+ XCTAssertNil(legacyDecoded.resultSidecarReference)++ var published = fixture.session+ published.resultSidecarReference = MeetingResultSidecarReference(+ formatVersion: MeetingResultSidecarReferenceSchema.currentVersion,+ fileName: "result-\(UUID().uuidString).sidecar.json",+ sha256: String(repeating: "b", count: 64),+ byteCount: 128+ )+ let roundTrip = try decoder.decode(+ MeetingSession.self,+ from: encoder.encode(published)+ )+ XCTAssertEqual(roundTrip.resultSidecarReference, published.resultSidecarReference)+ }++ // MARK: - Coordinator publication transaction++ private actor RecordingSessionStore: MeetingSessionStoring {+ struct SaveFailure: Error {}+ private let wrapped: MeetingSessionStore+ private(set) var saves: [(state: MeetingSessionState, checkpointExisted: Bool, persisted: Bool)] = []+ private var failCompletedSaves = false++ init(wrapping wrapped: MeetingSessionStore) {+ self.wrapped = wrapped+ }++ func setFailCompletedSaves(_ value: Bool) {+ self.failCompletedSaves = value+ }++ func create(_ session: MeetingSession) async throws {+ try await self.wrapped.create(session)+ }++ func save(_ session: MeetingSession) async throws {+ let directory = try await self.wrapped.sessionDirectory(for: session.id)+ let checkpointExisted = FileManager.default.fileExists(+ atPath: directory.appendingPathComponent("checkpoint.json").path+ )+ if self.failCompletedSaves, session.state == .completed {+ self.saves.append((session.state, checkpointExisted, false))+ throw SaveFailure()+ }+ self.saves.append((session.state, checkpointExisted, true))+ try await self.wrapped.save(session)+ }++ func load(id: MeetingSessionID) async throws -> MeetingSession? {+ try await self.wrapped.load(id: id)+ }++ func loadAll() async throws -> [MeetingSession] {+ try await self.wrapped.loadAll()+ }++ func loadRecoverable() async throws -> [MeetingSession] {+ try await self.wrapped.loadRecoverable()+ }++ func sessionDirectory(for id: MeetingSessionID) async throws -> URL {+ try await self.wrapped.sessionDirectory(for: id)+ }++ func existingSessionDirectory(for id: MeetingSessionID) async throws -> URL? {+ try await self.wrapped.existingSessionDirectory(for: id)+ }++ func delete(id: MeetingSessionID) async throws {+ try await self.wrapped.delete(id: id)+ }++ func deleteAudioFiles(for id: MeetingSessionID) async throws {+ try await self.wrapped.deleteAudioFiles(for: id)+ }+ }++ private final class StubCapture: MeetingCaptureControlling, @unchecked Sendable {+ func preflightPermissions() async throws {}++ func start(+ session _: MeetingSession,+ configuration _: MeetingCaptureConfiguration,+ sessionDirectory _: URL,+ eventHandler _: @escaping @Sendable (MeetingCaptureEvent) -> Void,+ liveAudioHandler _: (@Sendable (MeetingAudioTrackKind, CMSampleBuffer) -> Void)?+ ) async throws -> MeetingCaptureStartResult {+ MeetingCaptureStartResult(tracks: [], firstPresentationTime: nil)+ }++ func stop(sessionID _: MeetingSessionID) async throws -> MeetingCaptureStopResult {+ MeetingCaptureStopResult(tracks: [], stoppedAt: Date())+ }++ func shutdownForTermination() async {}+ }++ private final class StubArbiter: MeetingAudioActivityArbitrating {+ func acquireMeetingCapture() async throws -> MeetingAudioActivityLease {+ MeetingAudioActivityLease(id: UUID())+ }++ func release(_: MeetingAudioActivityLease) async {}+ }++ func testCoordinatorSaveFailurePreservesSidecarAndCheckpointThenRetryPublishes() async throws {+ let chunk = self.makeChunk(sequence: 0, start: 100, end: 110)+ let track = self.makeMicTrack(chunks: [chunk], eraStart: 100)+ var session = self.makeSession(mode: .inRoom, tracks: [track], openAttempt: false)+ session.state = .interrupted+ session.endedAt = Date()+ session.recoveryResolvedAt = Date()++ let root = try self.makeTempSessionDirectory()+ .appendingPathComponent("meetings", isDirectory: true)+ let recording = RecordingSessionStore(wrapping: MeetingSessionStore(rootDirectory: root))+ try await recording.create(session)+ let directory = try await recording.sessionDirectory(for: session.id)+ let checkpointURL = directory.appendingPathComponent("checkpoint.json")+ try Data("checkpoint".utf8).write(to: checkpointURL)++ let backend = CanonicalFixtureBackend { plan, manifest in+ self.standardBundle(plan: plan, manifest: manifest)+ }+ let coordinator = MeetingSessionCoordinator(+ store: recording,+ capture: StubCapture(),+ processing: self.makeCanonicalPipeline(+ backend: backend,+ observer: FixtureObserver(results: [+ MeetingAnalysisChunkKey(trackID: track.id, chunkID: chunk.id):+ self.makeObserved(chunk, duration: 10),+ ])+ ),+ audioArbiter: StubArbiter()+ )++ // First attempt: the pipeline writes and verifies the sidecar, then the session save+ // fails. Nothing may be published, and the sidecar, checkpoint and source stay intact.+ await recording.setFailCompletedSaves(true)+ do {+ _ = try await coordinator.retryProcessing(sessionID: session.id)+ XCTFail("A failed publication save must surface as a processing failure")+ } catch {+ guard error is RecordingSessionStore.SaveFailure else {+ return XCTFail("Unexpected error: \(error)")+ }+ }+ guard case .failed = coordinator.state else {+ return XCTFail("Expected failed state, got \(coordinator.state)")+ }+ XCTAssertTrue(FileManager.default.fileExists(atPath: checkpointURL.path))+ let firstSidecarURL = try XCTUnwrap(self.sidecarFiles(in: directory).first)+ let firstSidecarBytes = try Data(contentsOf: firstSidecarURL)+ let failedRunSaves = await recording.saves+ XCTAssertFalse(+ failedRunSaves.contains { $0.state == .completed && $0.persisted },+ "a failed save must not publish a completed session"+ )++ // Retry: a fresh attempt publishes; the completed-state save still observed the+ // checkpoint on disk, proving the save ran before checkpoint removal.+ await recording.setFailCompletedSaves(false)+ let published = try await coordinator.retryProcessing(sessionID: session.id)+ guard case .completed = coordinator.state else {+ return XCTFail("Expected completed state, got \(coordinator.state)")+ }+ let reference = try XCTUnwrap(published.resultSidecarReference)+ let publishedAttempt = try XCTUnwrap(published.processingAttempts.last {+ $0.backendID == Self.canonicalBackendID.rawValue+ })+ let verified = try MeetingResultSidecarStore(sessionDirectory: directory).read(+ expectedAttemptID: publishedAttempt.id,+ expectedBackendID: Self.canonicalBackendID,+ reference: reference+ )+ XCTAssertEqual(verified.units.map(\.id), ["unit-0"])++ let allSaves = await recording.saves+ XCTAssertTrue(+ allSaves.contains { $0.state == .completed && $0.persisted && $0.checkpointExisted },+ "the session save must run before the checkpoint is removed"+ )+ XCTAssertFalse(+ FileManager.default.fileExists(atPath: checkpointURL.path),+ "the checkpoint is removed once publication succeeded"+ )++ // The earlier attempt's unreferenced sidecar was never overwritten or deleted.+ XCTAssertTrue(FileManager.default.fileExists(atPath: firstSidecarURL.path))+ XCTAssertEqual(try Data(contentsOf: firstSidecarURL), firstSidecarBytes)+ }+}++/// Mutable cancellation target the sidecar-verified probe can fire from inside the pipeline task.+private final class CancelBox: @unchecked Sendable {+ var cancel: () -> Void = {}+}diff --git a/Tests/FluidDictationIntegrationTests/MeetingEpochAudioMaterializerTests.swift b/Tests/FluidDictationIntegrationTests/MeetingEpochAudioMaterializerTests.swiftnew file mode 100644index 00000000..781eb090--- /dev/null+++ b/Tests/FluidDictationIntegrationTests/MeetingEpochAudioMaterializerTests.swift@@ -0,0 +1,324 @@+import AVFoundation+@testable import FluidVoice_Debug+import Foundation+import XCTest++/// Stage E of `MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md` (§3): epoch materialization against+/// real audio on disk. The manifest is built by the real observer over real WAV files, then the+/// materializer must slice, mono-mix, resample and concatenate exactly those spans — and fail+/// closed when the bytes change underneath it.+@MainActor+final class MeetingEpochAudioMaterializerTests: XCTestCase {+ // MARK: - WAV fixtures++ private struct WrittenChunk {+ let url: URL+ let relativePath: String+ let duration: Double+ let sha256: String+ let byteCount: Int64+ }++ private func writeWAV(+ into sessionDirectory: URL,+ relativePath: String,+ seconds: Double,+ sampleRate: Double = 16_000,+ channels: Int = 1,+ amplitude: Float = 0.5,+ secondHalfAmplitude: Float? = nil+ ) throws -> WrittenChunk {+ let url = sessionDirectory.appendingPathComponent(relativePath)+ try FileManager.default.createDirectory(+ at: url.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )+ let format = AVAudioFormat(+ commonFormat: .pcmFormatFloat32,+ sampleRate: sampleRate,+ channels: AVAudioChannelCount(channels),+ interleaved: false+ )!+ let frameCount = AVAudioFrameCount((seconds * sampleRate).rounded())+ let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameCount)!+ buffer.frameLength = frameCount+ for channel in 0..<channels {+ let data = buffer.floatChannelData![channel]+ for frame in 0..<Int(frameCount) {+ let half = frame >= Int(frameCount) / 2+ let amp = half ? (secondHalfAmplitude ?? amplitude) : amplitude+ data[frame] = amp * sin(2 * Float.pi * 440 * Float(frame) / Float(sampleRate))+ }+ }+ do {+ let file = try AVAudioFile(+ forWriting: url,+ settings: format.settings,+ commonFormat: .pcmFormatFloat32,+ interleaved: false+ )+ try file.write(from: buffer)+ }++ let attributes = try FileManager.default.attributesOfItem(atPath: url.path)+ let byteCount = (attributes[.size] as? NSNumber)!.int64Value+ let sha256 = MeetingChunkPathConfinement.sha256Hex(contentsOf: url)!+ return WrittenChunk(+ url: url,+ relativePath: relativePath,+ duration: seconds,+ sha256: sha256,+ byteCount: byteCount+ )+ }++ private struct TrackFixture {+ let session: MeetingSession+ let track: MeetingAudioTrack+ let manifest: MeetingAnalysisManifest+ let directory: URL+ }++ private func makeManifestFixture(+ directory: URL,+ chunks: [(chunk: MeetingAudioChunk, written: WrittenChunk)]+ ) throws -> TrackFixture {+ let track = MeetingAudioTrack(+ id: UUID(),+ kind: .microphone,+ sourceIdentifier: "microphone",+ sourceDisplayName: "microphone",+ format: nil,+ timebase: MeetingTimebaseMetadata(+ startedHostTime: 7, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil+ ),+ health: .waiting,+ chunks: chunks.map(\.chunk),+ captureMethod: .voiceProcessing,+ captureEras: [MeetingCaptureEra(+ method: .voiceProcessing,+ deviceUID: "mic-a",+ deviceName: "mic-a",+ roleAtElection: .unknown,+ echoProtection: .voiceProcessed,+ startSeconds: chunks.map { $0.chunk.presentationStart.seconds }.min() ?? 0+ )]+ )+ var session = MeetingSession(+ configuration: MeetingCaptureConfiguration(+ mode: .inRoom,+ title: "Materializer fixture",+ microphone: MeetingMicrophoneIdentity(captureDeviceID: "mic-a", displayName: "Mic")+ ),+ timebase: MeetingTimebaseMetadata(+ startedHostTime: 7, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil+ )+ )+ session.audioTracks = [track]+ session.processingAttempts = [MeetingProcessingAttempt(+ id: UUID(),+ startedAt: Date(timeIntervalSinceNow: -30),+ completedAt: nil,+ stage: .pending,+ pipelineVersion: MeetingProcessingPipeline.pipelineVersion,+ asrProvider: nil,+ asrModel: nil,+ diarizationModel: nil,+ lastCompletedTrackID: nil,+ errorCode: nil+ )]+ let request = MeetingBackendRequest(+ attemptID: session.processingAttempts.last?.id ?? UUID(),+ session: session,+ sessionDirectory: directory,+ configuration: MeetingFinalProcessingConfiguration(languageCode: "en")+ )+ let plan = MeetingBackendPlan(request: request, descriptor: MeetingParakeetNemotronBackend.descriptor)+ let manifest = try MeetingAnalysisManifestBuilder(+ plan: plan,+ observer: MeetingChunkAudioObserver(sessionDirectory: directory),+ analysisSampleRate: 16_000+ ).build()+ return TrackFixture(session: session, track: track, manifest: manifest, directory: directory)+ }++ private func makeChunk(+ sequence: Int,+ start: Double,+ end: Double,+ written: WrittenChunk+ ) -> MeetingAudioChunk {+ MeetingAudioChunk(+ id: UUID(),+ sequence: sequence,+ relativeFilePath: written.relativePath,+ presentationStart: MeetingMediaTime(value: Int64((start * 1000).rounded()), timescale: 1000),+ presentationEnd: MeetingMediaTime(value: Int64((end * 1000).rounded()), timescale: 1000),+ discontinuities: [],+ sha256: written.sha256,+ byteCount: written.byteCount,+ finalizationState: .finalized+ )+ }++ // MARK: - Materialization++ func testSlicesMonoMixesResamplesAndConcatenatesInAnalysisOrder() async throws {+ let directory = FileManager.default.temporaryDirectory+ .appendingPathComponent("materializer-write-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ self.addTeardownBlock { try? FileManager.default.removeItem(at: directory) }++ let first = try self.writeWAV(+ into: directory,+ relativePath: "tracks/microphone/chunk_0.wav",+ seconds: 2.0,+ amplitude: 0.5,+ secondHalfAmplitude: 0.05+ )+ let second = try self.writeWAV(+ into: directory,+ relativePath: "tracks/microphone/chunk_1.wav",+ seconds: 1.0,+ sampleRate: 48_000,+ channels: 2,+ amplitude: 0.3+ )+ let fixture = try self.makeManifestFixture(directory: directory, chunks: [+ (self.makeChunk(sequence: 0, start: 100, end: 102, written: first), first),+ (self.makeChunk(sequence: 1, start: 102, end: 103, written: second), second),+ ])+ let trackManifest = try XCTUnwrap(fixture.manifest.track(fixture.track.id))+ XCTAssertEqual(trackManifest.spans.count, 2, "contiguous chunks share one epoch, two spans")+ let epoch = try XCTUnwrap(trackManifest.epochs.first)+ XCTAssertEqual(trackManifest.epochs.count, 1)++ let materialized = try await MeetingEpochAudioMaterializer().materialize(+ epoch: epoch,+ track: trackManifest,+ manifest: fixture.manifest,+ sessionDirectory: fixture.directory+ )++ XCTAssertEqual(materialized.sampleRate, 16_000)+ XCTAssertEqual(materialized.spanSamples.count, 2)+ XCTAssertEqual(Double(materialized.samples.count), 3.0 * 16_000, accuracy: 64)+ XCTAssertEqual(+ materialized.spanSamples.map(\.spanID),+ epoch.spanIDs,+ "span sample ranges follow analysis order"+ )+ let firstRange = materialized.spanSamples[0].sampleRange+ let secondRange = materialized.spanSamples[1].sampleRange+ XCTAssertEqual(Double(firstRange.count), 2.0 * 16_000, accuracy: 64)+ XCTAssertEqual(Double(secondRange.count), 1.0 * 16_000, accuracy: 64)+ XCTAssertEqual(secondRange.lowerBound, firstRange.upperBound, "concatenated with no hole")++ // Content really came from the files: the first chunk's loud half beats its quiet half.+ let firstHalf = materialized.samples[firstRange.lowerBound..<(firstRange.lowerBound + 16_000)]+ let secondHalf = materialized.samples[(firstRange.lowerBound + 16_000)..<firstRange.upperBound]+ let loudMax = firstHalf.map(abs).max() ?? 0+ let quietMax = secondHalf.map(abs).max() ?? 0+ XCTAssertGreaterThan(loudMax, 0.3)+ XCTAssertLessThan(quietMax, 0.15)+ let resampledMax = materialized.samples[secondRange].map(abs).max() ?? 0+ XCTAssertGreaterThan(resampledMax, 0.15, "the 48k stereo chunk was mixed and resampled")+ }++ func testChangedBytesFailClosed() async throws {+ let directory = FileManager.default.temporaryDirectory+ .appendingPathComponent("materializer-write-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ self.addTeardownBlock { try? FileManager.default.removeItem(at: directory) }++ let written = try self.writeWAV(+ into: directory, relativePath: "tracks/microphone/chunk_0.wav", seconds: 1.0+ )+ let fixture = try self.makeManifestFixture(directory: directory, chunks: [+ (self.makeChunk(sequence: 0, start: 100, end: 101, written: written), written),+ ])+ let trackManifest = try XCTUnwrap(fixture.manifest.track(fixture.track.id))+ let epoch = try XCTUnwrap(trackManifest.epochs.first)++ // Rewrite shorter audio: the recorded byte count no longer matches.+ _ = try self.writeWAV(+ into: directory, relativePath: "tracks/microphone/chunk_0.wav", seconds: 0.5+ )+ do {+ _ = try await MeetingEpochAudioMaterializer().materialize(+ epoch: epoch,+ track: trackManifest,+ manifest: fixture.manifest,+ sessionDirectory: fixture.directory+ )+ XCTFail("changed bytes must fail closed")+ } catch MeetingEpochMaterializationError.byteCountChanged {+ // expected+ }++ // Same size, different content: the recorded digest no longer matches.+ _ = try self.writeWAV(+ into: directory, relativePath: "tracks/microphone/chunk_0.wav", seconds: 1.0, amplitude: 0.1+ )+ do {+ _ = try await MeetingEpochAudioMaterializer().materialize(+ epoch: epoch,+ track: trackManifest,+ manifest: fixture.manifest,+ sessionDirectory: fixture.directory+ )+ XCTFail("changed content must fail closed")+ } catch MeetingEpochMaterializationError.hashChanged {+ // expected+ }+ }++ func testMissingFileAndSymlinkFailClosed() async throws {+ let directory = FileManager.default.temporaryDirectory+ .appendingPathComponent("materializer-write-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ self.addTeardownBlock { try? FileManager.default.removeItem(at: directory) }++ let written = try self.writeWAV(+ into: directory, relativePath: "tracks/microphone/chunk_0.wav", seconds: 1.0+ )+ let fixture = try self.makeManifestFixture(directory: directory, chunks: [+ (self.makeChunk(sequence: 0, start: 100, end: 101, written: written), written),+ ])+ let trackManifest = try XCTUnwrap(fixture.manifest.track(fixture.track.id))+ let epoch = try XCTUnwrap(trackManifest.epochs.first)++ // Replaced by a symlink to an outside file: confinement rejects it before any read.+ let outside = directory.deletingLastPathComponent()+ .appendingPathComponent("outside-\(UUID().uuidString).wav")+ try FileManager.default.copyItem(at: written.url, to: outside)+ self.addTeardownBlock { try? FileManager.default.removeItem(at: outside) }+ try FileManager.default.removeItem(at: written.url)+ try FileManager.default.createSymbolicLink(at: written.url, withDestinationURL: outside)+ do {+ _ = try await MeetingEpochAudioMaterializer().materialize(+ epoch: epoch,+ track: trackManifest,+ manifest: fixture.manifest,+ sessionDirectory: fixture.directory+ )+ XCTFail("a symlinked chunk must fail closed")+ } catch MeetingEpochMaterializationError.pathRejected {+ // expected+ }++ // Removed entirely: missing, not readable.+ try FileManager.default.removeItem(at: written.url)+ do {+ _ = try await MeetingEpochAudioMaterializer().materialize(+ epoch: epoch,+ track: trackManifest,+ manifest: fixture.manifest,+ sessionDirectory: fixture.directory+ )+ XCTFail("a missing chunk must fail closed")+ } catch MeetingEpochMaterializationError.fileMissing {+ // expected+ }+ }+}diff --git a/Tests/FluidDictationIntegrationTests/MeetingMicrophoneCaptureTests.swift b/Tests/FluidDictationIntegrationTests/MeetingMicrophoneCaptureTests.swiftindex 21b7d53c..ada46530 100644--- a/Tests/FluidDictationIntegrationTests/MeetingMicrophoneCaptureTests.swift+++ b/Tests/FluidDictationIntegrationTests/MeetingMicrophoneCaptureTests.swift@@ -352,6 +352,34 @@ final class MeetingMicrophoneCaptureTests: XCTestCase {XCTAssertEqual(track.chunks.first?.discontinuities ?? [], [])}+ func testWriterPublishesPCMCAFMetadataAndReadyLedgerTerminal() async throws {+ let (writer, sessionDirectory) = try self.makeWriter()+ defer { try? FileManager.default.removeItem(at: sessionDirectory) }++ self.pushBuffer(writer, ptsSeconds: 0, frameCount: 480)+ let track = await writer.stop()++ let chunk = try XCTUnwrap(track.chunks.first)+ XCTAssertEqual(track.format, MeetingAudioFormat(codec: "lpcm-f32", sampleRate: 48_000, channelCount: 1, bitRate: nil))+ XCTAssertTrue(chunk.relativeFilePath.hasSuffix(".caf"))+ XCTAssertFalse(chunk.relativeFilePath.hasSuffix(".m4a"))+ XCTAssertEqual(chunk.finalizationState, .finalized)+ XCTAssertEqual(chunk.audioSchemaVersion, 2)+ let asset = try XCTUnwrap(chunk.captureAnalysisAsset)+ XCTAssertEqual(asset.encoding, .linearPCMFloat32CAFV1)+ XCTAssertEqual(asset.presence, .ready)+ XCTAssertEqual(asset.frameCount, 480)+ XCTAssertNil(chunk.playbackArchiveAsset)+ XCTAssertTrue(FileManager.default.fileExists(atPath: sessionDirectory.appendingPathComponent(chunk.relativeFilePath).path))+ let audioFiles = try FileManager.default.subpathsOfDirectory(atPath: sessionDirectory.path)+ .filter { $0.hasSuffix(".m4a") }+ XCTAssertTrue(audioFiles.isEmpty)++ let ledger = MeetingAudioChunkLedgerStore(sessionDirectory: sessionDirectory)+ XCTAssertEqual(try ledger.readTerminal(for: chunk.id)?.status, .ready)+ XCTAssertEqual(try ledger.readCheckpoint(for: chunk.id)?.writtenFrames, 480)+ }+func testOneTickOverlapTriggersClockDiscontinuityAndRotation() async throws {let (writer, sessionDirectory) = try self.makeWriter()defer { try? FileManager.default.removeItem(at: sessionDirectory) }diff --git a/Tests/FluidDictationIntegrationTests/MeetingNemotronModelLocatorTests.swift b/Tests/FluidDictationIntegrationTests/MeetingNemotronModelLocatorTests.swiftnew file mode 100644index 00000000..f10a8f73--- /dev/null+++ b/Tests/FluidDictationIntegrationTests/MeetingNemotronModelLocatorTests.swift@@ -0,0 +1,154 @@+@testable import FluidVoice_Debug+import Foundation+import XCTest++/// Stage E of `MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md` (§5): local Nemotron model+/// readiness. Injected URLs for tests, the development environment override, the versioned cache+/// location, and fail-closed structure validation. No network and no bundled 190 MB weights.+@MainActor+final class MeetingNemotronModelLocatorTests: XCTestCase {+ private func makeTempDirectory() throws -> URL {+ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("nemotron-locator-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)+ self.addTeardownBlock { try? FileManager.default.removeItem(at: url) }+ return url+ }++ @discardableResult+ private func makeFakePackage(at url: URL) throws -> URL {+ let package = url.appendingPathComponent("nemotron_diar_fp16.mlpackage", isDirectory: true)+ let coreML = package.appendingPathComponent("Data/com.apple.CoreML", isDirectory: true)+ try FileManager.default.createDirectory(at: coreML, withIntermediateDirectories: true)+ try Data("{}".utf8).write(to: package.appendingPathComponent("Manifest.json"))+ try Data("model".utf8).write(to: coreML.appendingPathComponent("model.mlmodel"))+ let weights = coreML.appendingPathComponent("weights", isDirectory: true)+ try FileManager.default.createDirectory(at: weights, withIntermediateDirectories: true)+ try Data("weights".utf8).write(to: weights.appendingPathComponent("weight.bin"))+ return package+ }++ func testInjectedURLValidatesStructureAndRechecks() throws {+ let root = try self.makeTempDirectory()+ let package = try self.makeFakePackage(at: root)+ let locator = MeetingNemotronModelLocator(injectedURL: package)++ let artifact = try locator.locate()+ XCTAssertEqual(artifact.packageURL, package.standardizedFileURL)+ XCTAssertEqual(artifact.fileCount, 3)+ XCTAssertGreaterThan(artifact.totalByteCount, 0)+ XCTAssertFalse(artifact.manifestSHA256.isEmpty)+ XCTAssertFalse(artifact.entryMetadataSHA256.isEmpty)++ XCTAssertEqual(try locator.recheck(artifact), artifact)++ // A changed artifact is refused at open time.+ try Data("{\"changed\":true}".utf8).write(to: package.appendingPathComponent("Manifest.json"))+ XCTAssertThrowsError(try locator.recheck(artifact)) {+ XCTAssertEqual(+ $0 as? MeetingNemotronModelReadinessError,+ .artifactChanged(path: package.standardizedFileURL.path)+ )+ }++ // Restore the manifest, locate again, then replace weights with the same byte count.+ // Entry metadata still changes, so recheck cannot be bypassed by preserving file size.+ try Data("{}".utf8).write(to: package.appendingPathComponent("Manifest.json"))+ let sameSizeBaseline = try locator.locate()+ try Data("changed".utf8).write(+ to: package.appendingPathComponent("Data/com.apple.CoreML/weights/weight.bin")+ )+ XCTAssertThrowsError(try locator.recheck(sameSizeBaseline)) {+ XCTAssertEqual(+ $0 as? MeetingNemotronModelReadinessError,+ .artifactChanged(path: package.standardizedFileURL.path)+ )+ }+ }++ func testStructureValidationRefusesMissingPiecesAndSymlinks() throws {+ let root = try self.makeTempDirectory()++ // Missing entirely.+ let missing = root.appendingPathComponent("nope.mlpackage")+ XCTAssertThrowsError(try MeetingNemotronModelLocator(injectedURL: missing).locate()) {+ guard case .modelNotInstalled = $0 as? MeetingNemotronModelReadinessError else {+ return XCTFail("expected modelNotInstalled, got \($0)")+ }+ }++ // No Manifest.json.+ let noManifest = root.appendingPathComponent("bad1.mlpackage", isDirectory: true)+ try FileManager.default.createDirectory(at: noManifest, withIntermediateDirectories: true)+ try Data("model".utf8).write(to: noManifest.appendingPathComponent("model.mlmodel"))+ XCTAssertThrowsError(try MeetingNemotronModelLocator(injectedURL: noManifest).locate()) {+ XCTAssertEqual($0 as? MeetingNemotronModelReadinessError, .invalidModelPackage(reason: "manifestMissing"))+ }++ // No model.mlmodel.+ let noModel = root.appendingPathComponent("bad2.mlpackage", isDirectory: true)+ try FileManager.default.createDirectory(at: noModel, withIntermediateDirectories: true)+ try Data("{}".utf8).write(to: noModel.appendingPathComponent("Manifest.json"))+ XCTAssertThrowsError(try MeetingNemotronModelLocator(injectedURL: noModel).locate()) {+ XCTAssertEqual($0 as? MeetingNemotronModelReadinessError, .invalidModelPackage(reason: "modelMissing"))+ }++ // A symlink anywhere inside the package is rejected.+ let linked = try self.makeFakePackage(at: root)+ let symlinkedWeights = linked.appendingPathComponent("Data/com.apple.CoreML/weights/weight.bin")+ try FileManager.default.removeItem(at: symlinkedWeights)+ try FileManager.default.createSymbolicLink(atPath: symlinkedWeights.path, withDestinationPath: "/etc/hosts")+ XCTAssertThrowsError(try MeetingNemotronModelLocator(injectedURL: linked).locate()) {+ XCTAssertEqual(+ $0 as? MeetingNemotronModelReadinessError,+ .invalidModelPackage(reason: "packageContainsSymlink")+ )+ }++ // The package itself may not be a symlink either.+ let real = try self.makeFakePackage(at: root.appendingPathComponent("real", isDirectory: true))+ let link = root.appendingPathComponent("linked.mlpackage")+ try FileManager.default.createSymbolicLink(atPath: link.path, withDestinationPath: real.path)+ XCTAssertThrowsError(try MeetingNemotronModelLocator(injectedURL: link).locate()) {+ XCTAssertEqual(+ $0 as? MeetingNemotronModelReadinessError,+ .invalidModelPackage(reason: "packageIsSymlink")+ )+ }+ }++ func testEnvironmentOverrideAndDefaultLocation() throws {+ let root = try self.makeTempDirectory()+ let package = try self.makeFakePackage(at: root)++ let key = MeetingNemotronModelLocator.environmentOverrideKey+ let overridden = MeetingNemotronModelLocator(environment: [key: package.path])+ XCTAssertEqual(try overridden.locate().packageURL, package.standardizedFileURL)++ // Blank override falls through to the versioned cache location. Whether a model is+ // installed there is developer-machine state and is covered separately through injected+ // present/missing paths; this routing test must not depend on that state.+ let blank = MeetingNemotronModelLocator(environment: [key: " "])+ XCTAssertEqual(+ blank.resolvedPackageURL(),+ MeetingNemotronModelLocator.defaultPackageURL()+ )+ }++ /// The supplied development package must pass structural validation — this catches a broken+ /// or moved checkout before any CoreML load is attempted.+ func testSuppliedDevelopmentPackageIsStructurallyValid() throws {+ let repoRoot = URL(fileURLWithPath: #filePath)+ .deletingLastPathComponent() // FluidDictationIntegrationTests+ .deletingLastPathComponent() // Tests+ .deletingLastPathComponent() // repo root+ let supplied = repoRoot+ .appendingPathComponent("nemotron-3-diarization/models/nemotron_diar_fp16.mlpackage")+ guard FileManager.default.fileExists(atPath: supplied.path) else {+ throw XCTSkip("the supplied Nemotron package is not present in this checkout")+ }+ let artifact = try MeetingNemotronModelLocator(injectedURL: supplied).locate()+ XCTAssertGreaterThan(artifact.fileCount, 0)+ XCTAssertGreaterThan(artifact.totalByteCount, 100_000_000, "the real package carries its weights")+ }+}diff --git a/Tests/FluidDictationIntegrationTests/MeetingNemotronRealModelSmokeTests.swift b/Tests/FluidDictationIntegrationTests/MeetingNemotronRealModelSmokeTests.swiftnew file mode 100644index 00000000..5c8a0fbd--- /dev/null+++ b/Tests/FluidDictationIntegrationTests/MeetingNemotronRealModelSmokeTests.swift@@ -0,0 +1,124 @@+import AVFoundation+@testable import FluidVoice_Debug+import Foundation+import XCTest++/// Stage E of `MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md`: opt-in smoke test of the real+/// Nemotron path — the supplied mlpackage, the production runtime's diarization phase, real audio.+/// Runs only when FLUIDVOICE_NEMOTRON_SMOKE_TEST=1 is set; never in CI. It asserts structure+/// (loads, runs, fresh per-epoch state, bounded segments), never model quality.+@MainActor+final class MeetingNemotronRealModelSmokeTests: XCTestCase {+ private func writeSmokeWAV(into directory: URL, seconds: Double = 6.0) throws -> (url: URL, samples: [Float]) {+ let sampleRate: Double = 16_000+ let frameCount = AVAudioFrameCount((seconds * sampleRate).rounded())+ let format = AVAudioFormat(+ commonFormat: .pcmFormatFloat32, sampleRate: sampleRate, channels: 1, interleaved: false+ )!+ let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameCount)!+ buffer.frameLength = frameCount+ let data = buffer.floatChannelData![0]+ // Two voiced bursts of different pitches separated by silence: structure only, not speech.+ for frame in 0..<Int(frameCount) {+ let t = Double(frame) / sampleRate+ let inFirstBurst = t >= 0.5 && t < 2.5+ let inSecondBurst = t >= 3.5 && t < 5.5+ let frequency: Float = inFirstBurst ? 180 : (inSecondBurst ? 320 : 0)+ data[frame] = frequency > 0+ ? 0.4 * sin(2 * Float.pi * frequency * Float(frame) / 16_000)+ : 0+ }+ let url = directory.appendingPathComponent("smoke.wav")+ do {+ let file = try AVAudioFile(+ forWriting: url,+ settings: format.settings,+ commonFormat: .pcmFormatFloat32,+ interleaved: false+ )+ try file.write(from: buffer)+ }+ let samples = Array(UnsafeBufferPointer(start: data, count: Int(frameCount)))+ return (url, samples)+ }++ func testRealNemotronModelDiarizesWithFreshStatePerEpoch() async throws {+ guard ProcessInfo.processInfo.environment["FLUIDVOICE_NEMOTRON_SMOKE_TEST"] == "1" else {+ throw XCTSkip("set FLUIDVOICE_NEMOTRON_SMOKE_TEST=1 to run the real-model smoke test")+ }+ let environment = ProcessInfo.processInfo.environment+ let modelURL: URL+ if let override = environment[MeetingNemotronModelLocator.environmentOverrideKey],+ !override.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ {+ modelURL = URL(fileURLWithPath: override)+ } else {+ modelURL = URL(fileURLWithPath: #filePath)+ .deletingLastPathComponent() // FluidDictationIntegrationTests+ .deletingLastPathComponent() // Tests+ .deletingLastPathComponent() // repo root+ .appendingPathComponent("nemotron-3-diarization/models/nemotron_diar_fp16.mlpackage")+ }+ guard FileManager.default.fileExists(atPath: modelURL.path) else {+ throw XCTSkip("no Nemotron model package at \(modelURL.path)")+ }++ let directory = FileManager.default.temporaryDirectory+ .appendingPathComponent("nemotron-smoke-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ self.addTeardownBlock { try? FileManager.default.removeItem(at: directory) }+ let (_, samples) = try self.writeSmokeWAV(into: directory)++ #if arch(arm64)+ let runtime = MeetingParakeetNemotronRuntime(+ asrServiceProvider: { ASRService() },+ modelLocator: MeetingNemotronModelLocator(+ injectedURL: modelURL,+ environment: environment+ )+ )+ let trackID = UUID()+ let epoch0 = MeetingAnalysisEpochID(trackID: trackID, ordinal: 0)+ let epoch1 = MeetingAnalysisEpochID(trackID: trackID, ordinal: 1)+ let duration = Double(samples.count) / 16_000++ let artifact = try MeetingNemotronModelLocator(+ injectedURL: modelURL,+ environment: environment+ ).locate()+ let results = try await runtime.withNemotronDiarization(artifact: artifact) { factory in+ var collected = MeetingNemotronPhaseResult()+ for epoch in [epoch0, epoch1] {+ let diarizer = try await factory.makeDiarizer(epoch: epoch)+ let segments = try await diarizer.diarize(samples: samples)+ // Test-only completion marker; the runtime phase result has no separate+ // success ledger for a valid epoch that happens to contain no speech.+ collected.failures[epoch] = "smokeCompleted"+ collected.activity.append(contentsOf: segments.map {+ MeetingBackendSpeakerActivity(+ token: MeetingBackendSpeakerToken(+ analysisEpochID: epoch,+ label: "slot-\($0.slotIndex)"+ ),+ start: $0.start,+ end: $0.end+ )+ })+ }+ return collected+ }++ XCTAssertEqual(Set(results.failures.keys), [epoch0, epoch1])+ for segment in results.activity {+ XCTAssertGreaterThanOrEqual(segment.start, 0, "\(segment.token.analysisEpochID)")+ XCTAssertGreaterThan(segment.end, segment.start, "\(segment.token.analysisEpochID)")+ XCTAssertLessThanOrEqual(+ segment.end, duration + 0.5,+ "\(segment.token.analysisEpochID): segments stay inside the audio"+ )+ }+ #else+ throw XCTSkip("the production runtime is Apple-Silicon only")+ #endif+ }+}diff --git a/Tests/FluidDictationIntegrationTests/MeetingPCMStoragePolicyTests.swift b/Tests/FluidDictationIntegrationTests/MeetingPCMStoragePolicyTests.swiftnew file mode 100644index 00000000..83951777--- /dev/null+++ b/Tests/FluidDictationIntegrationTests/MeetingPCMStoragePolicyTests.swift@@ -0,0 +1,64 @@+@testable import FluidVoice_Debug+import Foundation+import XCTest++final class MeetingPCMStoragePolicyTests: XCTestCase {+ func testBudgetMatchesFloat32CaptureTopologyAndIncludesWorkingHeadroom() {+ XCTAssertEqual(MeetingPCMStoragePolicy.pcmBytesPerSecond(trackCount: 1), 192_000)+ XCTAssertEqual(MeetingPCMStoragePolicy.pcmBytesPerSecond(trackCount: 2), 576_000)+ XCTAssertEqual(MeetingPCMStoragePolicy.estimatedPCMBytes(trackCount: 2), 576_000 * 60 * 60)+ let required = MeetingPCMStoragePolicy.requiredFreeBytes(trackCount: 2)+ XCTAssertGreaterThan(required, MeetingPCMStoragePolicy.estimatedPCMBytes(trackCount: 2))+ XCTAssertGreaterThan(required, 512 * 1024 * 1024)+ XCTAssertEqual(MeetingPCMStoragePolicy.trackCount(for: .onlineCall), 2)+ XCTAssertEqual(MeetingPCMStoragePolicy.trackCount(for: .inRoom), 1)+ }++ func testFirstPlaybackURLUsesArchiveWhenReadyAndOtherwiseUsesFinalizedCAFPath() throws {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("FluidVoice-PCM-presentation-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }++ let pcmPath = "tracks/microphone/000000.caf"+ let archivePath = "archive/microphone/000000.m4a"+ let pcmURL = root.appendingPathComponent(pcmPath)+ try FileManager.default.createDirectory(at: pcmURL.deletingLastPathComponent(), withIntermediateDirectories: true)+ try Data([1]).write(to: pcmURL)++ let microphone = MeetingMicrophoneIdentity(captureDeviceID: "mic", displayName: "Mic")+ let configuration = MeetingCaptureConfiguration(mode: .inRoom, title: "PCM", microphone: microphone)+ let timebase = MeetingTimebaseMetadata(startedHostTime: 0, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil)+ var session = MeetingSession(configuration: configuration, timebase: timebase)+ let chunk = MeetingAudioChunk(+ id: UUID(), sequence: 0, relativeFilePath: pcmPath,+ presentationStart: MeetingMediaTime(value: 0, timescale: 1),+ presentationEnd: MeetingMediaTime(value: 1, timescale: 1),+ discontinuities: [], sha256: "hash", byteCount: 1, finalizationState: .finalized,+ audioSchemaVersion: 2,+ captureAnalysisAsset: MeetingAudioAsset(+ role: .captureAnalysis, encoding: .linearPCMFloat32CAFV1, presence: .ready,+ relativeFilePath: pcmPath, byteCount: 1, sha256: "hash", sampleRate: 48_000,+ channelCount: 1, frameCount: 1+ )+ )+ session.audioTracks = [MeetingAudioTrack(+ id: UUID(), kind: .microphone, sourceIdentifier: "mic", sourceDisplayName: "Mic",+ format: nil, timebase: timebase, health: .waiting, chunks: [chunk]+ )]++ XCTAssertEqual(MeetingAudioPresentation.firstPlaybackURL(in: session, directory: root), pcmURL)++ var archivedChunk = chunk+ archivedChunk.playbackArchiveAsset = MeetingAudioAsset(+ role: .playbackArchive, encoding: .aacLCM4AV1, presence: .ready,+ relativeFilePath: archivePath, byteCount: 1, sha256: "archive", sampleRate: 48_000,+ channelCount: 1, frameCount: 1, sourceAssetSHA256: "hash"+ )+ session.audioTracks[0].chunks = [archivedChunk]+ let archiveURL = root.appendingPathComponent(archivePath)+ try FileManager.default.createDirectory(at: archiveURL.deletingLastPathComponent(), withIntermediateDirectories: true)+ try Data([2]).write(to: archiveURL)+ XCTAssertEqual(MeetingAudioPresentation.firstPlaybackURL(in: session, directory: root), archiveURL)+ }+}diff --git a/Tests/FluidDictationIntegrationTests/MeetingParakeetNemotronBackendTests.swift b/Tests/FluidDictationIntegrationTests/MeetingParakeetNemotronBackendTests.swiftnew file mode 100644index 00000000..c5952775--- /dev/null+++ b/Tests/FluidDictationIntegrationTests/MeetingParakeetNemotronBackendTests.swift@@ -0,0 +1,1118 @@+import AVFoundation+@testable import FluidVoice_Debug+import Foundation+import XCTest++/// Milestone E of `MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md`: the composite+/// Parakeet TDT v2 + Nemotron-3 backend. The runtime is faked (no CoreML here); the+/// materializer and pipeline integration tests use real WAV files on disk.+@MainActor+final class MeetingParakeetNemotronBackendTests: XCTestCase {+ // MARK: - Session fixtures++ private func makeChunk(+ sequence: Int,+ start: Double,+ end: Double,+ path: String = "tracks/microphone/chunk_0.caf",+ sha256: String = String(repeating: "a", count: 64),+ byteCount: Int64 = 1024+ ) -> MeetingAudioChunk {+ MeetingAudioChunk(+ id: UUID(),+ sequence: sequence,+ relativeFilePath: path,+ presentationStart: MeetingMediaTime(value: Int64((start * 1000).rounded()), timescale: 1000),+ presentationEnd: MeetingMediaTime(value: Int64((end * 1000).rounded()), timescale: 1000),+ discontinuities: [],+ sha256: sha256,+ byteCount: byteCount,+ finalizationState: .finalized+ )+ }++ private func makeObserved(+ _ chunk: MeetingAudioChunk,+ duration: Double,+ sampleRate: Double = 16_000+ ) -> MeetingChunkObservationResult {+ .observed(MeetingChunkObservedAudio(+ byteCount: chunk.captureAnalysisAsset?.byteCount ?? chunk.byteCount,+ sha256: chunk.captureAnalysisAsset?.sha256 ?? chunk.sha256,+ decoded: MeetingChunkDecodedFacts(+ sampleRate: sampleRate,+ channelCount: 1,+ frameCount: Int64((duration * sampleRate).rounded()),+ durationSeconds: duration,+ codecPriming: chunk.captureAnalysisAsset == nil+ ? .measuredFrames(0)+ : .notApplicable(.linearPCMFloat32CAFV1),+ processingFormatDescription: "fixture"+ )+ ))+ }++ private func makePCMChunk(sequence: Int, start: Double, end: Double) -> MeetingAudioChunk {+ let duration = end - start+ let asset = MeetingAudioAsset(+ role: .captureAnalysis,+ encoding: .linearPCMFloat32CAFV1,+ presence: .ready,+ relativeFilePath: "tracks/microphone/analysis-\(sequence).caf",+ byteCount: Int64((duration * 16_000 * 4).rounded()) + 1,+ sha256: String(repeating: "b", count: 64),+ sampleRate: 16_000,+ channelCount: 1,+ frameCount: Int64((duration * 16_000).rounded())+ )+ return MeetingAudioChunk(+ id: UUID(), sequence: sequence, relativeFilePath: "tracks/microphone/archive-\(sequence).m4a",+ presentationStart: MeetingMediaTime(value: Int64((start * 1000).rounded()), timescale: 1000),+ presentationEnd: MeetingMediaTime(value: Int64((end * 1000).rounded()), timescale: 1000),+ discontinuities: [], sha256: String(repeating: "a", count: 64), byteCount: 1,+ finalizationState: .finalized, audioSchemaVersion: 2, captureAnalysisAsset: asset+ )+ }++ private struct FixtureObserver: MeetingChunkAudioObserving {+ let results: [MeetingAnalysisChunkKey: MeetingChunkObservationResult]++ func observe(+ chunk: MeetingAudioChunk,+ trackID: MeetingAudioTrackID+ ) -> MeetingChunkObservationResult {+ self.results[MeetingAnalysisChunkKey(trackID: trackID, chunkID: chunk.id)]+ ?? .failed(.unreadable, detail: "no fixture observation")+ }+ }++ private func makeMicTrack(chunks: [MeetingAudioChunk], eraStart: Double) -> MeetingAudioTrack {+ MeetingAudioTrack(+ id: UUID(),+ kind: .microphone,+ sourceIdentifier: "microphone",+ sourceDisplayName: "microphone",+ format: nil,+ timebase: MeetingTimebaseMetadata(+ startedHostTime: 7,+ machTimebaseNumerator: 1,+ machTimebaseDenominator: 1,+ firstPresentationTime: nil+ ),+ health: .waiting,+ chunks: chunks,+ captureMethod: .voiceProcessing,+ captureEras: [MeetingCaptureEra(+ method: .voiceProcessing,+ deviceUID: "mic-a",+ deviceName: "mic-a",+ roleAtElection: .unknown,+ echoProtection: .voiceProcessed,+ startSeconds: eraStart+ )]+ )+ }++ private func makeAppTrack(chunks: [MeetingAudioChunk]) -> MeetingAudioTrack {+ MeetingAudioTrack(+ id: UUID(),+ kind: .applicationAudio,+ sourceIdentifier: "application",+ sourceDisplayName: "application",+ format: nil,+ timebase: MeetingTimebaseMetadata(+ startedHostTime: 7,+ machTimebaseNumerator: 1,+ machTimebaseDenominator: 1,+ firstPresentationTime: nil+ ),+ health: .waiting,+ chunks: chunks,+ captureMethod: .screenCaptureKit+ )+ }++ private func makeSession(+ mode: MeetingCaptureMode,+ tracks: [MeetingAudioTrack],+ languageCode: String = "en"+ ) -> MeetingSession {+ var session = MeetingSession(+ configuration: MeetingCaptureConfiguration(+ mode: mode,+ title: "Composite fixture",+ languageCode: languageCode,+ application: mode == .onlineCall+ ? MeetingApplicationIdentity(bundleIdentifier: "fixture.app", displayName: "Fixture")+ : nil,+ microphone: MeetingMicrophoneIdentity(captureDeviceID: "mic-a", displayName: "Mic")+ ),+ timebase: MeetingTimebaseMetadata(+ startedHostTime: 7,+ machTimebaseNumerator: 1,+ machTimebaseDenominator: 1,+ firstPresentationTime: nil+ )+ )+ session.audioTracks = tracks+ session.processingAttempts = [MeetingProcessingAttempt(+ id: UUID(),+ startedAt: Date(timeIntervalSinceNow: -30),+ completedAt: nil,+ stage: .pending,+ pipelineVersion: MeetingProcessingPipeline.pipelineVersion,+ asrProvider: nil,+ asrModel: nil,+ diarizationModel: nil,+ lastCompletedTrackID: nil,+ errorCode: nil+ )]+ return session+ }++ private func makeRequest(+ session: MeetingSession,+ directory: URL,+ configuration: MeetingFinalProcessingConfiguration = MeetingFinalProcessingConfiguration(languageCode: "en")+ ) -> MeetingBackendRequest {+ MeetingBackendRequest(+ attemptID: session.processingAttempts.last?.id ?? UUID(),+ session: session,+ sessionDirectory: directory,+ configuration: configuration+ )+ }++ private func makeBackend(+ runtime: FakeRuntime,+ materializer: FakeMaterializer = FakeMaterializer(),+ locator: any MeetingNemotronModelLocating = StubModelLocator()+ ) -> MeetingParakeetNemotronBackend {+ MeetingParakeetNemotronBackend(+ runtimeFactory: { _ in runtime },+ modelLocator: locator,+ materializer: materializer+ )+ }++ private func makeTempSessionDirectory() throws -> URL {+ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("composite-backend-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)+ self.addTeardownBlock { try? FileManager.default.removeItem(at: url) }+ return url+ }++ private func makeManifest(+ plan: MeetingBackendPlan,+ observations: [MeetingAnalysisChunkKey: MeetingChunkObservationResult]+ ) throws -> MeetingAnalysisManifest {+ try MeetingAnalysisManifestBuilder(+ plan: plan,+ observer: FixtureObserver(results: observations),+ analysisSampleRate: 16_000+ ).build()+ }++ /// Two mic chunks separated by a presentation gap (two epochs) plus one app chunk (one epoch).+ private struct TwoEpochFixture {+ let session: MeetingSession+ let micTrack: MeetingAudioTrack+ let appTrack: MeetingAudioTrack+ let chunks: [MeetingAudioChunk]+ let observations: [MeetingAnalysisChunkKey: MeetingChunkObservationResult]+ }++ private func makeTwoEpochFixture(mode: MeetingCaptureMode = .onlineCall) -> TwoEpochFixture {+ let micChunk0 = self.makeChunk(sequence: 0, start: 100, end: 102, path: "tracks/microphone/chunk_0.caf")+ let micChunk1 = self.makeChunk(sequence: 1, start: 105, end: 107, path: "tracks/microphone/chunk_1.caf")+ let appChunk = self.makeChunk(sequence: 0, start: 100, end: 102, path: "tracks/application/chunk_0.caf")+ let micTrack = self.makeMicTrack(chunks: [micChunk0, micChunk1], eraStart: 100)+ let appTrack = self.makeAppTrack(chunks: [appChunk])+ let session = self.makeSession(mode: mode, tracks: [micTrack, appTrack])+ var observations: [MeetingAnalysisChunkKey: MeetingChunkObservationResult] = [:]+ observations[MeetingAnalysisChunkKey(trackID: micTrack.id, chunkID: micChunk0.id)] = self.makeObserved(micChunk0, duration: 2)+ observations[MeetingAnalysisChunkKey(trackID: micTrack.id, chunkID: micChunk1.id)] = self.makeObserved(micChunk1, duration: 2)+ observations[MeetingAnalysisChunkKey(trackID: appTrack.id, chunkID: appChunk.id)] = self.makeObserved(appChunk, duration: 2)+ return TwoEpochFixture(+ session: session,+ micTrack: micTrack,+ appTrack: appTrack,+ chunks: [micChunk0, micChunk1, appChunk],+ observations: observations+ )+ }++ // MARK: - Registry selection++ func testRegistryUsesCompositeDefaultAndKeepsLegacyRegistered() throws {+ let registry = MeetingTranscriptionBackendRegistry.makeDefault()+ XCTAssertEqual(registry.defaultBackendID, .productionDefault)+ XCTAssertTrue(registry.contains(.parakeetNemotron))+ XCTAssertTrue(registry.contains(.legacyCompatibility))++ let runtime = FakeRuntime()+ let context = MeetingBackendHostContext(+ legacyExecutor: { _, _ in throw MeetingBackendError.unknownBackend(.legacyCompatibility) },+ parakeetNemotronRuntimeFactory: { _ in runtime }+ )+ let backend = try registry.makeBackend(id: .parakeetNemotron, context: context)+ XCTAssertEqual(backend.descriptor.id, .parakeetNemotron)+ XCTAssertEqual(backend.descriptor.resultContract, .canonicalEvidence)+ XCTAssertEqual(backend.descriptor.supportedFinalPrecisions, [.word, .utterance])+ XCTAssertEqual(backend.descriptor.supportedTrackKinds, Set(MeetingAudioTrackKind.allCases))+ XCTAssertEqual(backend.descriptor.supportedLanguageCodes, ["en"])+ XCTAssertEqual(backend.descriptor.execution, .local)+ XCTAssertEqual(backend.descriptor.analysisSampleRate, 16_000)++ let selectedDefault = try registry.makeBackend(id: registry.defaultBackendID, context: context)+ XCTAssertEqual(selectedDefault.descriptor.id, .parakeetNemotron)+ }++ func testCanonicalProductPublicationMergesWordEvidenceIntoTurns() {+ let trackID = UUID()+ let speakerID = UUID()+ func segment(_ text: String, _ start: Double, _ end: Double, speaker: UUID?) -> MeetingTranscriptSegment {+ MeetingTranscriptSegment(+ id: UUID(),+ start: MeetingMediaTime(value: Int64((start * 1000).rounded()), timescale: 1000),+ end: MeetingMediaTime(value: Int64((end * 1000).rounded()), timescale: 1000),+ sourceTrackID: trackID,+ speakerID: speaker,+ text: text,+ revision: 0,+ status: .final,+ overlap: .none,+ completeness: .complete+ )+ }+ let input = [+ segment("Hello", 0, 0.2, speaker: speakerID),+ segment(",", 0.21, 0.25, speaker: speakerID),+ segment("world", 0.3, 0.6, speaker: speakerID),+ segment("Other", 0.4, 0.7, speaker: UUID()),+ ]++ let first = MeetingProcessingPipeline.mergeCanonicalSegments(input)+ let second = MeetingProcessingPipeline.mergeCanonicalSegments(input)++ XCTAssertEqual(first.count, 2)+ XCTAssertEqual(first.first { $0.speakerID == speakerID }?.text, "Hello, world")+ XCTAssertEqual(first.map(\.id), second.map(\.id), "merged turn IDs are deterministic")+ }++ // MARK: - Plan validation++ func testPlanRejectsMissingModelUnsupportedLanguageAndUnsupportedOptions() async throws {+ let fixture = self.makeTwoEpochFixture()+ let directory = try self.makeTempSessionDirectory()++ let missingLocator = StubModelLocator(+ error: MeetingNemotronModelReadinessError.modelNotInstalled(path: "/tmp/none.mlpackage")+ )+ let unreadyBackend = self.makeBackend(runtime: FakeRuntime(), locator: missingLocator)+ XCTAssertThrowsError(try unreadyBackend.plan(self.makeRequest(session: fixture.session, directory: directory))) {+ XCTAssertEqual(+ $0 as? MeetingNemotronModelReadinessError,+ .modelNotInstalled(path: "/tmp/none.mlpackage")+ )+ }++ let german = self.makeSession(+ mode: .inRoom,+ tracks: [self.makeMicTrack(chunks: [self.makeChunk(sequence: 0, start: 0, end: 1)], eraStart: 0)],+ languageCode: "de"+ )+ let backend = self.makeBackend(runtime: FakeRuntime())+ XCTAssertThrowsError(try backend.plan(self.makeRequest(session: german, directory: directory))) {+ XCTAssertEqual(+ $0 as? MeetingBackendError,+ .unsupportedLanguage(backend: .parakeetNemotron, languageCode: "de")+ )+ }++ var boosted = MeetingFinalProcessingConfiguration(languageCode: "en")+ boosted = MeetingFinalProcessingConfiguration(+ asrModel: boosted.asrModel,+ languageCode: boosted.languageCode,+ vocabularyBoostingEnabled: true,+ pronunciationMatchingEnabled: boosted.pronunciationMatchingEnabled,+ customDictionaryRewritingEnabled: boosted.customDictionaryRewritingEnabled,+ experimentalUnifiedFinalEnabled: boosted.experimentalUnifiedFinalEnabled,+ diarizationFingerprint: boosted.diarizationFingerprint,+ pipelineVersion: boosted.pipelineVersion+ )+ XCTAssertThrowsError(try backend.plan(self.makeRequest(+ session: fixture.session,+ directory: directory,+ configuration: boosted+ ))) {+ XCTAssertEqual($0 as? MeetingProviderOptionsError, .unsupportedFeature("vocabularyBoosting"))+ }++ let plan = try backend.plan(self.makeRequest(session: fixture.session, directory: directory))+ XCTAssertEqual(plan.resultContract, .canonicalEvidence)+ XCTAssertEqual(plan.declaredFinalPrecisions, [.word, .utterance])+ XCTAssertEqual(Set(plan.chunkIDsByTrackID.keys), [fixture.micTrack.id, fixture.appTrack.id])+ }++ func testExecuteRechecksTheExactArtifactFrozenDuringPlan() async throws {+ let fixture = self.makeTwoEpochFixture()+ let locator = StubModelLocator()+ let runtime = FakeRuntime()+ let backend = self.makeBackend(runtime: runtime, locator: locator)+ let plan = try backend.plan(self.makeRequest(+ session: fixture.session,+ directory: try self.makeTempSessionDirectory()+ ))+ let manifest = try self.makeManifest(plan: plan, observations: fixture.observations)+ locator.error = MeetingNemotronModelReadinessError.artifactChanged(+ path: StubModelLocator.artifact.packageURL.path+ )++ await XCTAssertAsyncThrowsError(+ try await backend.execute(plan: plan, manifest: manifest, progress: { _ in })+ ) { error in+ XCTAssertEqual(+ error as? MeetingNemotronModelReadinessError,+ .artifactChanged(path: StubModelLocator.artifact.packageURL.path)+ )+ }+ XCTAssertEqual(runtime.diarizationScopeCount, 0)+ }++ // MARK: - Host request binding++ /// A fixture backend that asks the host for a runtime against a rewritten request.+ private final class RuntimeStealingBackend: MeetingTranscriptionBackend {+ let descriptor = MeetingBackendDescriptor(+ id: MeetingBackendID(rawValue: "fixture.runtime-stealer"),+ version: "test",+ execution: .local,+ supportedLanguageCodes: ["en"],+ supportedTrackKinds: Set(MeetingAudioTrackKind.allCases),+ supportedFinalPrecisions: [.word],+ resultContract: .canonicalEvidence,+ knownLimits: []+ )+ private let factory: MeetingParakeetNemotronRuntimeFactory++ init(factory: @escaping MeetingParakeetNemotronRuntimeFactory) {+ self.factory = factory+ }++ func plan(_ request: MeetingBackendRequest) throws -> MeetingBackendPlan {+ MeetingBackendPlan(request: request, descriptor: self.descriptor)+ }++ func execute(+ plan: MeetingBackendPlan,+ manifest _: MeetingAnalysisManifest?,+ progress _: @escaping @MainActor (MeetingProcessingStage) -> Void+ ) async throws -> MeetingBackendOutcome {+ let rewritten = MeetingBackendRequest(+ attemptID: UUID(),+ session: plan.request.session,+ sessionDirectory: plan.request.sessionDirectory,+ configuration: plan.request.configuration+ )+ _ = try self.factory(rewritten)+ throw MeetingBackendError.unknownBackend(self.descriptor.id)+ }+ }++ func testHostBindsRuntimeFactoryToTheFrozenRequest() async throws {+ let fixture = self.makeTwoEpochFixture()+ let directory = try self.makeTempSessionDirectory()+ let openAttemptID = try XCTUnwrap(fixture.session.processingAttempts.last?.id)++ final class RuntimeSpy {+ var requests: [MeetingBackendRequest] = []+ }+ let spy = RuntimeSpy()+ let runtime = FakeRuntime()++ let stealerID = MeetingBackendID(rawValue: "fixture.runtime-stealer")+ let registry = MeetingTranscriptionBackendRegistry(defaultBackendID: stealerID)+ registry.register(stealerID) { context in+ RuntimeStealingBackend(factory: context.parakeetNemotronRuntimeFactory)+ }+ let stealingPipeline = MeetingProcessingPipeline(+ asrServiceProvider: {+ XCTFail("Canonical dispatch must not reach ASR readiness")+ return ASRService()+ },+ serializationGate: MeetingProcessingSerializationGate(),+ backendRegistry: registry,+ chunkObserver: FixtureObserver(results: fixture.observations),+ meetingRuntimeFactory: { request in+ spy.requests.append(request)+ return runtime+ }+ )+ await XCTAssertAsyncThrowsError(+ try await stealingPipeline.process(session: fixture.session, sessionDirectory: directory) { _ in }+ ) { error in+ XCTAssertEqual(+ error as? MeetingBackendError,+ .hostCapabilityRequestMismatch(backend: stealerID)+ )+ }+ XCTAssertTrue(spy.requests.isEmpty, "a mismatched request must be refused before the factory runs")++ // And the composite backend, which passes its frozen plan's request, gets the runtime.+ let materializer = FakeMaterializer()+ let compositeRegistry = MeetingTranscriptionBackendRegistry(defaultBackendID: .parakeetNemotron)+ compositeRegistry.register(.parakeetNemotron) { context in+ MeetingParakeetNemotronBackend(+ runtimeFactory: context.parakeetNemotronRuntimeFactory,+ modelLocator: StubModelLocator(),+ materializer: materializer+ )+ }+ let pipeline = MeetingProcessingPipeline(+ asrServiceProvider: {+ XCTFail("Canonical dispatch must not reach ASR readiness")+ return ASRService()+ },+ serializationGate: MeetingProcessingSerializationGate(),+ backendRegistry: compositeRegistry,+ chunkObserver: FixtureObserver(results: fixture.observations),+ meetingRuntimeFactory: { request in+ spy.requests.append(request)+ return runtime+ }+ )+ runtime.asrSession.responses = [+ .init(text: "", words: []), .init(text: "", words: []), .init(text: "", words: []),+ ]+ let result = try await pipeline.process(+ session: fixture.session,+ sessionDirectory: directory,+ progress: { _ in }+ )+ XCTAssertEqual(spy.requests.count, 1)+ XCTAssertEqual(spy.requests.first?.attemptID, openAttemptID)+ XCTAssertEqual(spy.requests.first?.session.id, fixture.session.id)+ XCTAssertEqual(spy.requests.first?.sessionDirectory, directory)+ XCTAssertEqual(spy.requests.first?.configuration, MeetingFinalProcessingConfiguration(languageCode: "en"))+ XCTAssertEqual(result.attempt.backendID, MeetingBackendID.parakeetNemotron.rawValue)+ }++ // MARK: - Epoch isolation and unit assignment++ private func plannedManifest(+ fixture: TwoEpochFixture,+ runtime: FakeRuntime,+ materializer: FakeMaterializer = FakeMaterializer()+ ) async throws -> (backend: MeetingParakeetNemotronBackend, plan: MeetingBackendPlan, manifest: MeetingAnalysisManifest) {+ let directory = try self.makeTempSessionDirectory()+ let backend = self.makeBackend(runtime: runtime, materializer: materializer)+ let plan = try backend.plan(self.makeRequest(session: fixture.session, directory: directory))+ let manifest = try self.makeManifest(plan: plan, observations: fixture.observations)+ return (backend, plan, manifest)+ }++ private func executeComposite(+ fixture: TwoEpochFixture,+ runtime: FakeRuntime,+ materializer: FakeMaterializer = FakeMaterializer()+ ) async throws -> (bundle: MeetingCanonicalResultBundle, manifest: MeetingAnalysisManifest, plan: MeetingBackendPlan) {+ let (backend, plan, manifest) = try await self.plannedManifest(+ fixture: fixture, runtime: runtime, materializer: materializer+ )+ let outcome = try await backend.execute(plan: plan, manifest: manifest, progress: { _ in })+ guard case let .canonicalEvidence(bundle) = outcome else {+ XCTFail("composite must return canonical evidence")+ throw MeetingBackendError.outcomeContractMismatch(backend: .parakeetNemotron, declared: .canonicalEvidence)+ }+ return (bundle, manifest, plan)+ }++ func testPerEpochFreshDiarizerStateAndEpochScopedAssignment() async throws {+ let fixture = self.makeTwoEpochFixture()+ let runtime = FakeRuntime()+ let (backend, plan, manifest) = try await self.plannedManifest(fixture: fixture, runtime: runtime)+ let micEpochs = try XCTUnwrap(manifest.track(fixture.micTrack.id)?.epochs)+ let appEpochs = try XCTUnwrap(manifest.track(fixture.appTrack.id)?.epochs)+ XCTAssertEqual(micEpochs.count, 2, "the 3-second chunk gap must reset the mic epoch")+ XCTAssertEqual(appEpochs.count, 1)++ runtime.diarizerFactory.segmentsByEpoch = [+ micEpochs[0].id: [MeetingNemotronSpeakerSegment(slotIndex: 0, start: 0.2, end: 1.0)],+ micEpochs[1].id: [MeetingNemotronSpeakerSegment(slotIndex: 1, start: 0.0, end: 1.0)],+ appEpochs[0].id: [MeetingNemotronSpeakerSegment(slotIndex: 0, start: 0.0, end: 2.0)],+ ]+ runtime.asrSession.responses = [+ .init(text: "hello", words: [ASRWordTiming(text: "hello", start: 0.3, end: 0.6)]),+ .init(text: "world", words: [ASRWordTiming(text: "world", start: 0.1, end: 0.5)]),+ .init(text: "remote", words: [ASRWordTiming(text: "remote", start: 0.5, end: 1.0)]),+ ]+ let outcome = try await backend.execute(plan: plan, manifest: manifest, progress: { _ in })+ guard case let .canonicalEvidence(bundle) = outcome else {+ XCTFail("composite must return canonical evidence")+ throw MeetingBackendError.outcomeContractMismatch(backend: .parakeetNemotron, declared: .canonicalEvidence)+ }++ XCTAssertEqual(+ runtime.diarizerFactory.createdEpochs,+ [micEpochs[0].id, micEpochs[1].id, appEpochs[0].id],+ "one fresh diarizer state per track epoch, in analysis order"+ )+ XCTAssertEqual(runtime.diarizationScopeCount, 1, "one Nemotron residency per attempt")+ XCTAssertEqual(runtime.asrAttemptIDs.count, 1, "one prepared ASR scope per attempt")+ XCTAssertEqual(runtime.asrSession.callSampleCounts.count, 3)++ XCTAssertEqual(bundle.coverageReceipts.count, manifest.allSpans.count)+ XCTAssertTrue(bundle.coverageReceipts.allSatisfy { $0.status == .processed })++ let unitsByText = Dictionary(bundle.evidence.units.map { ($0.text, $0) }, uniquingKeysWith: { first, _ in first })+ let hello = try XCTUnwrap(unitsByText["hello"])+ guard case let .assigned(helloToken) = hello.speaker else {+ return XCTFail("hello must be assigned to the overlapping slot")+ }+ XCTAssertEqual(helloToken.analysisEpochID, micEpochs[0].id)+ XCTAssertEqual(helloToken.label, "slot-0")+ XCTAssertEqual(hello.analysisStart, micEpochs[0].analysisInterval.start + 0.3, accuracy: 1e-6)++ let world = try XCTUnwrap(unitsByText["world"])+ guard case let .assigned(worldToken) = world.speaker else {+ return XCTFail("world must be assigned")+ }+ XCTAssertEqual(worldToken.analysisEpochID, micEpochs[1].id)+ XCTAssertNotEqual(worldToken, helloToken, "slots never merge across epochs")++ let remote = try XCTUnwrap(unitsByText["remote"])+ guard case let .assigned(remoteToken) = remote.speaker else {+ return XCTFail("remote must be assigned")+ }+ XCTAssertEqual(remoteToken.analysisEpochID, appEpochs[0].id)+ XCTAssertEqual(remoteToken.label, "slot-0")+ XCTAssertNotEqual(remoteToken, helloToken, "the same slot label on another track is another speaker")++ XCTAssertEqual(bundle.evidence.speakerActivity.count, 3)+ // The bundle must assemble: exact receipts, epoch-scoped tokens and unit spans all validate.+ let verdicts = try await MeetingTextOverlapEchoVerdictProvider().echoVerdicts(+ for: bundle.evidence,+ manifest: manifest,+ plan: plan+ )+ _ = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: bundle.evidence,+ coverageReceipts: bundle.coverageReceipts,+ echoVerdicts: verdicts+ ))+ }++ func testPCMFirstEpochMaterializesOnceForBothModelPhases() async throws {+ let chunk = self.makePCMChunk(sequence: 0, start: 100, end: 101)+ let track = self.makeMicTrack(chunks: [chunk], eraStart: 100)+ let session = self.makeSession(mode: .inRoom, tracks: [track])+ let runtime = FakeRuntime()+ let materializer = FakeMaterializer()+ let backend = self.makeBackend(runtime: runtime, materializer: materializer)+ let plan = try backend.plan(self.makeRequest(+ session: session,+ directory: try self.makeTempSessionDirectory()+ ))+ let manifest = try self.makeManifest(plan: plan, observations: [+ MeetingAnalysisChunkKey(trackID: track.id, chunkID: chunk.id): self.makeObserved(chunk, duration: 1),+ ])+ let epoch = try XCTUnwrap(manifest.track(track.id)?.epochs.first)+ runtime.diarizerFactory.segmentsByEpoch[epoch.id] = [+ MeetingNemotronSpeakerSegment(slotIndex: 0, start: 0.1, end: 0.4),+ ]+ runtime.asrSession.responses = [+ .init(text: "pcm", words: [ASRWordTiming(text: "pcm", start: 0.2, end: 0.3)]),+ ]+ let outcome = try await backend.execute(plan: plan, manifest: manifest, progress: { _ in })+ guard case let .canonicalEvidence(bundle) = outcome else {+ return XCTFail("composite must return canonical evidence")+ }+ XCTAssertEqual(materializer.materializedEpochs, [epoch.id], "PCM is materialized once and shared")+ XCTAssertEqual(runtime.asrSession.callSampleCounts, [16_000])+ XCTAssertEqual(bundle.evidence.units.map(\.text), ["pcm"])+ }++ func testWordSlotAmbiguityAndUnassigned() async throws {+ let chunk = self.makeChunk(sequence: 0, start: 100, end: 104)+ let track = self.makeMicTrack(chunks: [chunk], eraStart: 100)+ let session = self.makeSession(mode: .inRoom, tracks: [track])+ let directory = try self.makeTempSessionDirectory()+ let runtime = FakeRuntime()+ let backend = self.makeBackend(runtime: runtime)+ let request = self.makeRequest(session: session, directory: directory)+ let plan = try backend.plan(request)+ let manifest = try self.makeManifest(+ plan: plan,+ observations: [MeetingAnalysisChunkKey(trackID: track.id, chunkID: chunk.id): self.makeObserved(chunk, duration: 4)]+ )+ let epoch = try XCTUnwrap(manifest.track(track.id)?.epochs.first)+ runtime.diarizerFactory.segmentsByEpoch = [+ epoch.id: [+ MeetingNemotronSpeakerSegment(slotIndex: 0, start: 0.0, end: 2.0),+ MeetingNemotronSpeakerSegment(slotIndex: 1, start: 1.0, end: 3.0),+ ],+ ]+ runtime.asrSession.responses = [+ .init(text: "a b c", words: [+ ASRWordTiming(text: "a", start: 0.2, end: 0.6),+ ASRWordTiming(text: "b", start: 1.2, end: 1.6),+ ASRWordTiming(text: "c", start: 3.2, end: 3.6),+ ]),+ ]++ let outcome = try await backend.execute(plan: plan, manifest: manifest, progress: { _ in })+ guard case let .canonicalEvidence(bundle) = outcome else {+ return XCTFail("composite must return canonical evidence")+ }+ let unitsByText = Dictionary(bundle.evidence.units.map { ($0.text, $0) }, uniquingKeysWith: { first, _ in first })++ guard case let .assigned(tokenA) = try XCTUnwrap(unitsByText["a"]).speaker else {+ return XCTFail("word a overlaps only slot 0")+ }+ XCTAssertEqual(tokenA.label, "slot-0")++ guard case let .ambiguous(candidates) = try XCTUnwrap(unitsByText["b"]).speaker else {+ return XCTFail("word b overlaps both slots")+ }+ XCTAssertEqual(candidates.map(\.label), ["slot-0", "slot-1"])++ guard case .unassigned = try XCTUnwrap(unitsByText["c"]).speaker else {+ return XCTFail("word c overlaps no activity")+ }++ // Assembly maps ambiguity into one visible unassigned segment, never two speakers.+ let assembly = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: bundle.evidence,+ coverageReceipts: bundle.coverageReceipts+ ))+ XCTAssertEqual(assembly.segments.map(\.text), ["a", "b"])+ XCTAssertEqual(assembly.speakers.count, 1, "only the unambiguous assigned slot mints a speaker")+ let ambiguous = try XCTUnwrap(assembly.sidecar.dispositions.first { $0.unitID == unitsByText["b"]?.id })+ XCTAssertEqual(ambiguous.disposition, .ambiguousUnassigned)+ let outside = try XCTUnwrap(assembly.sidecar.dispositions.first { $0.unitID == unitsByText["c"]?.id })+ XCTAssertEqual(outside.disposition, .outsideActivity)+ }++ func testProviderAndDiarizerTimesMapThroughActualSpanSampleRanges() async throws {+ let chunk0 = self.makeChunk(sequence: 0, start: 100, end: 101, path: "tracks/microphone/chunk_0.caf")+ let chunk1 = self.makeChunk(sequence: 1, start: 101, end: 102, path: "tracks/microphone/chunk_1.caf")+ let track = self.makeMicTrack(chunks: [chunk0, chunk1], eraStart: 100)+ let session = self.makeSession(mode: .inRoom, tracks: [track])+ let runtime = FakeRuntime()+ let materializer = FakeMaterializer()+ let backend = self.makeBackend(runtime: runtime, materializer: materializer)+ let plan = try backend.plan(self.makeRequest(+ session: session,+ directory: try self.makeTempSessionDirectory()+ ))+ let manifest = try self.makeManifest(plan: plan, observations: [+ MeetingAnalysisChunkKey(trackID: track.id, chunkID: chunk0.id): self.makeObserved(chunk0, duration: 1),+ MeetingAnalysisChunkKey(trackID: track.id, chunkID: chunk1.id): self.makeObserved(chunk1, duration: 1),+ ])+ let trackManifest = try XCTUnwrap(manifest.track(track.id))+ let epoch = try XCTUnwrap(trackManifest.epochs.first)+ XCTAssertEqual(epoch.spanIDs.count, 2)++ // Deliberately make the first one-second manifest span occupy only 0.5 seconds of the+ // materialized buffer. A local time of 0.6 seconds must therefore map into span 2.+ materializer.customSpanSampleCounts[epoch.id] = [8_000, 16_000]+ runtime.diarizerFactory.segmentsByEpoch[epoch.id] = [+ MeetingNemotronSpeakerSegment(slotIndex: 3, start: 0.55, end: 0.75),+ ]+ runtime.asrSession.responses = [+ .init(text: "mapped", words: [ASRWordTiming(text: "mapped", start: 0.6, end: 0.7)]),+ ]++ let outcome = try await backend.execute(plan: plan, manifest: manifest, progress: { _ in })+ guard case let .canonicalEvidence(bundle) = outcome else {+ return XCTFail("composite must return canonical evidence")+ }+ let unit = try XCTUnwrap(bundle.evidence.units.first)+ XCTAssertEqual(unit.analysisStart, 1.1, accuracy: 1e-6)+ XCTAssertEqual(unit.analysisEnd, 1.2, accuracy: 1e-6)+ XCTAssertEqual(unit.analysisSpanIDs, [epoch.spanIDs[1]])+ guard case let .assigned(token) = unit.speaker else {+ return XCTFail("mapped diarizer activity should assign the word")+ }+ XCTAssertEqual(token.label, "slot-3")+ }++ // MARK: - Receipts and partial failure++ func testEpochFailureMarksItsSpansFailedAndContinues() async throws {+ let fixture = self.makeTwoEpochFixture()+ let runtime = FakeRuntime()+ runtime.diarizerFactory.segmentsByEpoch = [:]+ runtime.asrSession.responses = [+ .init(text: "fine", words: [ASRWordTiming(text: "fine", start: 0.2, end: 0.4)]),+ .init(text: "ignored", words: [ASRWordTiming(text: "ignored", start: 0.2, end: 0.4)]),+ .init(text: "remote", words: [ASRWordTiming(text: "remote", start: 0.2, end: 0.4)]),+ ]+ runtime.asrSession.failingCallIndices = [1]++ let (bundle, manifest, plan) = try await self.executeComposite(fixture: fixture, runtime: runtime)+ let micEpochs = try XCTUnwrap(manifest.track(fixture.micTrack.id)?.epochs)+ let appEpochs = try XCTUnwrap(manifest.track(fixture.appTrack.id)?.epochs)++ let receiptsBySpan = Dictionary(+ bundle.coverageReceipts.map { ($0.spanID, $0) },+ uniquingKeysWith: { first, _ in first }+ )+ XCTAssertEqual(bundle.coverageReceipts.count, manifest.allSpans.count, "every admissible span is tiled")+ for span in manifest.allSpans {+ let receipt = try XCTUnwrap(receiptsBySpan[span.id])+ XCTAssertEqual(receipt.analysisStart, span.analysisInterval.start, accuracy: 1e-9)+ XCTAssertEqual(receipt.analysisEnd, span.analysisInterval.end, accuracy: 1e-9)+ if span.analysisEpochID == micEpochs[1].id {+ XCTAssertEqual(receipt.status, .failed)+ XCTAssertEqual(receipt.reasonCode, "asrFailed")+ } else {+ XCTAssertEqual(receipt.status, .processed)+ }+ }+ XCTAssertEqual(Set(bundle.evidence.units.map(\.analysisEpochID)), [micEpochs[0].id, appEpochs[0].id])++ // The partial bundle still assembles; the failed epoch becomes visible coverage gaps.+ let verdicts = try await MeetingTextOverlapEchoVerdictProvider().echoVerdicts(+ for: bundle.evidence,+ manifest: manifest,+ plan: plan+ )+ let assembly = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: bundle.evidence,+ coverageReceipts: bundle.coverageReceipts,+ echoVerdicts: verdicts+ ))+ XCTAssertFalse(assembly.isComplete)+ XCTAssertEqual(assembly.coverageGaps.filter { $0.reason == .processingFailed }.count, 1)+ }++ func testDiarizationFailureSkipsASRForThatEpochOnly() async throws {+ let fixture = self.makeTwoEpochFixture()+ let runtime = FakeRuntime()+ let directory = try self.makeTempSessionDirectory()+ let backend = self.makeBackend(runtime: runtime)+ let request = self.makeRequest(session: fixture.session, directory: directory)+ let plan = try backend.plan(request)+ let manifest = try self.makeManifest(plan: plan, observations: fixture.observations)+ let micEpochs = try XCTUnwrap(manifest.track(fixture.micTrack.id)?.epochs)+ runtime.diarizerFactory.failingEpochs = [micEpochs[0].id]+ runtime.asrSession.responses = [+ .init(text: "later", words: [ASRWordTiming(text: "later", start: 0.1, end: 0.3)]),+ .init(text: "remote", words: [ASRWordTiming(text: "remote", start: 0.1, end: 0.3)]),+ ]++ let outcome = try await backend.execute(plan: plan, manifest: manifest, progress: { _ in })+ guard case let .canonicalEvidence(bundle) = outcome else {+ return XCTFail("composite must return canonical evidence")+ }+ XCTAssertEqual(runtime.asrSession.callSampleCounts.count, 2, "the failed epoch is not transcribed")+ let failedReceipts = bundle.coverageReceipts.filter { $0.status == .failed }+ XCTAssertEqual(Set(failedReceipts.map(\.spanID)), Set(micEpochs[0].spanIDs))+ XCTAssertEqual(failedReceipts.first?.reasonCode, "diarizationFailed")+ XCTAssertEqual(Set(bundle.evidence.units.map(\.text)), ["later", "remote"])+ }++ // MARK: - Utterance fallback++ func testTextWithoutWordTimingsEmitsOneEpochCoveringUtterance() async throws {+ let chunk = self.makeChunk(sequence: 0, start: 100, end: 103)+ let track = self.makeMicTrack(chunks: [chunk], eraStart: 100)+ let session = self.makeSession(mode: .inRoom, tracks: [track])+ let directory = try self.makeTempSessionDirectory()+ let runtime = FakeRuntime()+ let backend = self.makeBackend(runtime: runtime)+ let request = self.makeRequest(session: session, directory: directory)+ let plan = try backend.plan(request)+ let manifest = try self.makeManifest(+ plan: plan,+ observations: [MeetingAnalysisChunkKey(trackID: track.id, chunkID: chunk.id): self.makeObserved(chunk, duration: 3)]+ )+ let epoch = try XCTUnwrap(manifest.track(track.id)?.epochs.first)+ runtime.diarizerFactory.segmentsByEpoch = [+ epoch.id: [MeetingNemotronSpeakerSegment(slotIndex: 2, start: 0.0, end: 3.0)],+ ]+ runtime.asrSession.responses = [.init(text: "hello there", words: [])]++ let outcome = try await backend.execute(plan: plan, manifest: manifest, progress: { _ in })+ guard case let .canonicalEvidence(bundle) = outcome else {+ return XCTFail("composite must return canonical evidence")+ }+ let unit = try XCTUnwrap(bundle.evidence.units.first)+ XCTAssertEqual(bundle.evidence.units.count, 1)+ XCTAssertEqual(unit.precision, .utterance)+ XCTAssertEqual(unit.analysisStart, epoch.analysisInterval.start, accuracy: 1e-9)+ XCTAssertEqual(unit.analysisEnd, epoch.analysisInterval.end, accuracy: 1e-9)+ XCTAssertEqual(unit.analysisSpanIDs, epoch.spanIDs)+ guard case let .assigned(token) = unit.speaker else {+ return XCTFail("the epoch-covering utterance takes the epoch's activity")+ }+ XCTAssertEqual(token.label, "slot-2")++ // Assembly accepts it as-is: no synthetic words exist.+ _ = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan, manifest: manifest,+ evidence: bundle.evidence, coverageReceipts: bundle.coverageReceipts+ ))+ }++ func testProcessedEpochWithNoTextIsValid() async throws {+ let fixture = self.makeTwoEpochFixture()+ let runtime = FakeRuntime()+ runtime.asrSession.responses = [+ .init(text: " ", words: []), .init(text: "", words: []), .init(text: "", words: []),+ ]+ let (bundle, manifest, _) = try await self.executeComposite(fixture: fixture, runtime: runtime)+ XCTAssertTrue(bundle.evidence.units.isEmpty)+ XCTAssertEqual(bundle.coverageReceipts.count, manifest.allSpans.count)+ XCTAssertTrue(bundle.coverageReceipts.allSatisfy { $0.status == .processed })+ }++ // MARK: - Cancellation++ func testCancellationPropagatesOutOfExecute() async throws {+ let fixture = self.makeTwoEpochFixture()+ let runtime = FakeRuntime()+ let latch = Latch()+ runtime.asrSession.latch = latch+ let entered = LockedFlag()+ runtime.asrSession.onCall = { entered.set() }++ let directory = try self.makeTempSessionDirectory()+ let backend = self.makeBackend(runtime: runtime)+ let request = self.makeRequest(session: fixture.session, directory: directory)+ let plan = try backend.plan(request)+ let manifest = try self.makeManifest(plan: plan, observations: fixture.observations)++ let task = Task { @MainActor in+ try await backend.execute(plan: plan, manifest: manifest, progress: { _ in })+ }+ let deadline = Date().addingTimeInterval(5)+ while !entered.value, Date() < deadline {+ try await Task.sleep(nanoseconds: 10_000_000)+ }+ XCTAssertTrue(entered.value, "the ASR phase must have started")+ task.cancel()+ await latch.open()+ await XCTAssertAsyncThrowsError(try await task.value) { error in+ XCTAssertTrue(error is CancellationError, "got \(error)")+ }+ }++ func testProviderCancellationIsNotAFailedReceipt() async throws {+ let fixture = self.makeTwoEpochFixture()+ let runtime = FakeRuntime()+ runtime.asrSession.responses = [+ .init(text: "fine", words: [ASRWordTiming(text: "fine", start: 0.2, end: 0.4)]),+ ]+ runtime.asrSession.cancellationCallIndices = [1]++ let directory = try self.makeTempSessionDirectory()+ let backend = self.makeBackend(runtime: runtime)+ let request = self.makeRequest(session: fixture.session, directory: directory)+ let plan = try backend.plan(request)+ let manifest = try self.makeManifest(plan: plan, observations: fixture.observations)+ await XCTAssertAsyncThrowsError(+ try await backend.execute(plan: plan, manifest: manifest, progress: { _ in })+ ) { error in+ XCTAssertTrue(error is CancellationError, "cancellation propagates; got \(error)")+ }+ }++ // MARK: - Helpers+}++// MARK: - Fakes++fileprivate actor Latch {+ private var waiters: [CheckedContinuation<Void, Never>] = []+ private var isOpen = false++ func wait() async {+ if self.isOpen { return }+ await withCheckedContinuation { self.waiters.append($0) }+ }++ func open() {+ self.isOpen = true+ let parked = self.waiters+ self.waiters.removeAll()+ for continuation in parked { continuation.resume() }+ }+}++fileprivate final nonisolated class FakeDiarizerFactory: MeetingNemotronDiarizerFactory, @unchecked Sendable {+ struct Session: MeetingNemotronDiarizerSession {+ let segments: [MeetingNemotronSpeakerSegment]+ func diarize(samples _: [Float]) async throws -> [MeetingNemotronSpeakerSegment] {+ self.segments+ }+ }++ var segmentsByEpoch: [MeetingAnalysisEpochID: [MeetingNemotronSpeakerSegment]] = [:]+ var failingEpochs: Set<MeetingAnalysisEpochID> = []+ private(set) var createdEpochs: [MeetingAnalysisEpochID] = []++ func makeDiarizer(epoch: MeetingAnalysisEpochID) async throws -> any MeetingNemotronDiarizerSession {+ self.createdEpochs.append(epoch)+ if self.failingEpochs.contains(epoch) {+ throw MeetingEpochMaterializationError.unreadable(spanID: "fake-diarizer-failure")+ }+ return Session(segments: self.segmentsByEpoch[epoch] ?? [])+ }+}++fileprivate final nonisolated class FakeASRSession: MeetingParakeetASRSession, @unchecked Sendable {+ struct Response {+ let text: String+ let words: [ASRWordTiming]+ }++ var responses: [Response] = []+ var failingCallIndices: Set<Int> = []+ var cancellationCallIndices: Set<Int> = []+ var latch: Latch?+ var onCall: (() -> Void)?+ private(set) var callSampleCounts: [Int] = []++ func transcribeWithTimings(+ _ samples: [Float]+ ) async throws -> (result: ASRTranscriptionResult, words: [ASRWordTiming]) {+ let index = self.callSampleCounts.count+ self.callSampleCounts.append(samples.count)+ self.onCall?()+ if let latch { await latch.wait() }+ if self.cancellationCallIndices.contains(index) { throw CancellationError() }+ if self.failingCallIndices.contains(index) {+ throw MeetingEpochMaterializationError.unreadable(spanID: "fake-asr-failure")+ }+ let response = index < self.responses.count ? self.responses[index] : Response(text: "", words: [])+ return (await ASRTranscriptionResult(text: response.text), response.words)+ }+}++fileprivate final nonisolated class FakeRuntime: MeetingParakeetNemotronRunning, @unchecked Sendable {+ let diarizerFactory = FakeDiarizerFactory()+ let asrSession = FakeASRSession()+ private(set) var diarizationScopeCount = 0+ private(set) var asrAttemptIDs: [UUID] = []+ private(set) var asrConfigurations: [MeetingFinalProcessingConfiguration] = []++ func withNemotronDiarization(+ artifact _: MeetingNemotronModelArtifact,+ _ body: nonisolated(nonsending) @escaping @Sendable (any MeetingNemotronDiarizerFactory) async throws -> MeetingNemotronPhaseResult+ ) async throws -> MeetingNemotronPhaseResult {+ self.diarizationScopeCount += 1+ return try await body(self.diarizerFactory)+ }++ func withPreparedASR(+ attemptID: UUID,+ configuration: MeetingFinalProcessingConfiguration,+ body: nonisolated(nonsending) @escaping @Sendable (any MeetingParakeetASRSession) async throws -> MeetingParakeetPhaseResult+ ) async throws -> MeetingParakeetPhaseResult {+ self.asrAttemptIDs.append(attemptID)+ self.asrConfigurations.append(configuration)+ return try await body(self.asrSession)+ }+}++fileprivate final nonisolated class FakeMaterializer: MeetingEpochAudioMaterializing, @unchecked Sendable {+ var failingEpochs: Set<MeetingAnalysisEpochID> = []+ var customSpanSampleCounts: [MeetingAnalysisEpochID: [Int]] = [:]+ private(set) var materializedEpochs: [MeetingAnalysisEpochID] = []++ func materialize(+ epoch: MeetingAnalysisEpochRecord,+ track: MeetingAnalysisTrackManifest,+ manifest _: MeetingAnalysisManifest,+ sessionDirectory _: URL+ ) async throws -> MeetingMaterializedEpoch {+ self.materializedEpochs.append(epoch.id)+ if self.failingEpochs.contains(epoch.id) {+ throw MeetingEpochMaterializationError.unreadable(spanID: epoch.spanIDs.first ?? "?")+ }+ var cursor = 0+ var ranges: [MeetingMaterializedSpanSamples] = []+ for (index, spanID) in epoch.spanIDs.enumerated() {+ guard let span = track.spans.first(where: { $0.id == spanID }) else { continue }+ let count: Int+ if let configured = self.customSpanSampleCounts[epoch.id], configured.indices.contains(index) {+ count = max(1, configured[index])+ } else {+ count = max(1, Int((span.analysisInterval.duration * 16_000).rounded()))+ }+ ranges.append(MeetingMaterializedSpanSamples(spanID: spanID, sampleRange: cursor..<(cursor + count)))+ cursor += count+ }+ return MeetingMaterializedEpoch(+ epochID: epoch.id,+ samples: [Float](repeating: 0, count: cursor),+ sampleRate: 16_000,+ spanSamples: ranges+ )+ }+}++fileprivate final nonisolated class StubModelLocator: MeetingNemotronModelLocating, @unchecked Sendable {+ var error: (any Error)?+ static let artifact = MeetingNemotronModelArtifact(+ packageURL: URL(fileURLWithPath: "/tmp/stub-nemotron.mlpackage"),+ totalByteCount: 1,+ fileCount: 1,+ manifestSHA256: "stub",+ entryMetadataSHA256: "stub"+ )++ init(error: (any Error)? = nil) {+ self.error = error+ }++ func locate() throws -> MeetingNemotronModelArtifact {+ if let error { throw error }+ return Self.artifact+ }++ func recheck(_ artifact: MeetingNemotronModelArtifact) throws -> MeetingNemotronModelArtifact {+ if let error { throw error }+ return artifact+ }+}+++private final class LockedFlag: @unchecked Sendable {+ private let lock = NSLock()+ private var flag = false++ var value: Bool {+ self.lock.withLock { self.flag }+ }++ func set() {+ self.lock.withLock { self.flag = true }+ }+}++/// Small async assert helper so throwing closures read like XCTAssertThrowsError.+private func XCTAssertAsyncThrowsError<T>(+ _ expression: @autoclosure () async throws -> T,+ _ message: String = "",+ file: StaticString = #filePath,+ line: UInt = #line,+ _ errorHandler: (Error) -> Void+) async {+ do {+ _ = try await expression()+ XCTFail("Expected error to be thrown. \(message)", file: file, line: line)+ } catch {+ errorHandler(error)+ }+}diff --git a/Tests/FluidDictationIntegrationTests/MeetingResultSidecarTests.swift b/Tests/FluidDictationIntegrationTests/MeetingResultSidecarTests.swiftnew file mode 100644index 00000000..8bfa0385--- /dev/null+++ b/Tests/FluidDictationIntegrationTests/MeetingResultSidecarTests.swift@@ -0,0 +1,918 @@+import CryptoKit+@testable import FluidVoice_Debug+import Foundation+import XCTest++/// Stage C1 of `MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md`: versioned Codable evidence, the+/// disposition/coverage ledger invariants, and the confined atomic sidecar store.+final class MeetingResultSidecarTests: XCTestCase {+ private let backendID = MeetingBackendID(rawValue: "fixture-sidecar-backend")+ private let backendVersion = "test-1"+ private let trackID = UUID()+ private let chunkID = UUID()++ private var epoch: MeetingAnalysisEpochID {+ MeetingAnalysisEpochID(trackID: self.trackID, ordinal: 0)+ }++ private func makeUnit(+ id: String = "u-0",+ text: String = "hello",+ speaker: MeetingBackendSpeakerAssignment? = nil,+ confidence: Double? = nil,+ analysisStart: TimeInterval = 1,+ analysisEnd: TimeInterval = 2,+ analysisSpanIDs: [String]? = nil+ ) -> MeetingFinalTextUnit {+ MeetingFinalTextUnit(+ id: id,+ trackID: self.trackID,+ analysisEpochID: self.epoch,+ precision: .word,+ text: text,+ analysisStart: analysisStart,+ analysisEnd: analysisEnd,+ speaker: speaker ?? .assigned(+ MeetingBackendSpeakerToken(analysisEpochID: self.epoch, label: "slot-0")+ ),+ analysisSpanIDs: analysisSpanIDs ?? ["span-0"],+ confidence: confidence+ )+ }++ private func makeReceipt(+ id: String = "receipt-0",+ spanID: String = "span-0",+ analysisStart: TimeInterval = 0,+ analysisEnd: TimeInterval = 5,+ status: MeetingSpanCoverageStatus = .processed+ ) -> MeetingSpanCoverageReceipt {+ MeetingSpanCoverageReceipt(+ id: id,+ spanID: spanID,+ analysisStart: analysisStart,+ analysisEnd: analysisEnd,+ status: status+ )+ }++ private func makeSidecar(+ attemptID: UUID = UUID(),+ units: [MeetingFinalTextUnit]? = nil,+ dispositions: [MeetingTextUnitDispositionRecord]? = nil,+ receipts: [MeetingSpanCoverageReceipt]? = nil+ ) -> MeetingResultSidecar {+ let resolvedUnits = units ?? [self.makeUnit()]+ let resolvedReceipts = receipts ?? [self.makeReceipt()]+ let spanIDs = Set(resolvedUnits.flatMap(\.analysisSpanIDs) + resolvedReceipts.map(\.spanID))+ return MeetingResultSidecar(+ backendID: self.backendID,+ backendVersion: self.backendVersion,+ attemptID: attemptID,+ analysisManifest: self.makeManifest(attemptID: attemptID, spanIDs: spanIDs),+ units: resolvedUnits,+ dispositions: dispositions ?? resolvedUnits.map {+ MeetingTextUnitDispositionRecord(unitID: $0.id, disposition: .emitted)+ },+ coverageReceipts: resolvedReceipts+ )+ }++ private func makeManifest(+ attemptID: UUID,+ spanIDs: Set<String>+ ) -> MeetingAnalysisManifest {+ let orderedIDs = spanIDs.sorted()+ let era = MeetingCaptureEraIdentity(+ index: 0,+ method: .avCaptureSession,+ deviceUID: "fixture-mic",+ deviceName: "Fixture Mic",+ normalizedStartSeconds: nil,+ echoProtection: .legacyUnclassified,+ aecProvenance: nil,+ clockDrift: nil+ )+ let spans = orderedIDs.enumerated().map { index, id in+ let start = Double(index) * 5+ let end = start + 5+ let chunk = MeetingAudioChunk(+ id: index == 0 ? self.chunkID : UUID(),+ sequence: index,+ relativeFilePath: "tracks/fixture-\(index).caf",+ presentationStart: MeetingMediaTime(value: Int64(start * 1_000), timescale: 1_000),+ presentationEnd: MeetingMediaTime(value: Int64(end * 1_000), timescale: 1_000),+ discontinuities: [],+ sha256: String(repeating: String((index % 9) + 1), count: 64),+ byteCount: 1_024,+ finalizationState: .finalized+ )+ let identity = MeetingAnalysisChunkIdentity(trackID: self.trackID, chunk: chunk)+ let decoded = MeetingChunkDecodedFacts(+ sampleRate: 100,+ channelCount: 1,+ frameCount: 500,+ durationSeconds: 5,+ codecPriming: .measuredFrames(0),+ processingFormatDescription: "fixture"+ )+ return MeetingAnalysisSpan(+ id: id,+ chunk: identity,+ pieceIndex: 0,+ trackKind: .microphone,+ analysisEpochID: self.epoch,+ recordedInterval: MeetingAnalysisInterval(start: start, end: end),+ sourceLocalInterval: MeetingAnalysisInterval(start: 0, end: 5),+ analysisInterval: MeetingAnalysisInterval(start: start, end: end),+ presentationInterval: MeetingAnalysisInterval(start: start, end: end),+ presentationMapping: MeetingAnalysisTimeTransform(+ hostClockAnchor: 0,+ rateRatio: 1,+ offsetSeconds: 0,+ sampleRateConversionRatio: nil,+ codecPrimingCompensationSeconds: 0,+ analysisRemovesGaps: true+ ),+ captureEra: era,+ admission: MeetingSpanAdmission(+ captureMode: .inRoom,+ trackKind: .microphone,+ echoProtection: .legacyUnclassified+ ),+ observed: MeetingChunkObservedAudio(+ byteCount: identity.storedByteCount,+ sha256: identity.storedSHA256,+ decoded: decoded+ ),+ discontinuity: .contiguous,+ timing: MeetingSpanTimingMetadata(+ certainty: .certain,+ fitResidualSeconds: 0,+ residualBoundSeconds: MeetingAnalysisManifestSchema.defaultResidualBoundSeconds,+ deDrift: .notApplicable+ )+ )+ }+ let epochRecords: [MeetingAnalysisEpochRecord] = spans.isEmpty ? [] : [+ MeetingAnalysisEpochRecord(+ id: self.epoch,+ resetReason: .trackStart,+ spanIDs: spans.map(\.id),+ analysisInterval: MeetingAnalysisInterval(+ start: 0,+ end: Double(spans.count) * 5+ )+ ),+ ]+ return MeetingAnalysisManifest(+ backendID: self.backendID,+ backendVersion: self.backendVersion,+ attemptID: attemptID,+ sessionID: UUID(),+ captureMode: .inRoom,+ presentationOriginSeconds: 0,+ analysisSampleRate: nil,+ tracks: [MeetingAnalysisTrackManifest(+ id: self.trackID,+ kind: .microphone,+ spans: spans,+ gaps: [],+ epochs: epochRecords+ )]+ )+ }++ private func makeTempSessionDirectory() throws -> URL {+ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("sidecar-tests-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)+ self.addTeardownBlock { try? FileManager.default.removeItem(at: url) }+ return url+ }++ private func encode<T: Encodable>(_ value: T) throws -> Data {+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.sortedKeys]+ return try encoder.encode(value)+ }++ // MARK: - Evidence Codable++ func testEvidenceCodableRoundTripPreservesAllAssignmentShapes() throws {+ let attemptID = UUID()+ let evidence = MeetingFinalTranscriptEvidence(+ backendID: self.backendID,+ attemptID: attemptID,+ units: [+ self.makeUnit(id: "w-0"),+ self.makeUnit(id: "w-1", speaker: .ambiguous([+ MeetingBackendSpeakerToken(analysisEpochID: self.epoch, label: "slot-0"),+ MeetingBackendSpeakerToken(analysisEpochID: self.epoch, label: "slot-1"),+ ])),+ self.makeUnit(id: "w-2", speaker: .unassigned, confidence: 0.5),+ ],+ speakerActivity: [+ MeetingBackendSpeakerActivity(+ token: MeetingBackendSpeakerToken(analysisEpochID: self.epoch, label: "slot-0"),+ start: 1,+ end: 2+ ),+ ]+ )+ let data = try self.encode(evidence)+ let decoded = try JSONDecoder().decode(MeetingFinalTranscriptEvidence.self, from: data)+ XCTAssertEqual(decoded, evidence)++ let object = try XCTUnwrap(+ JSONSerialization.jsonObject(with: data) as? [String: Any]+ )+ XCTAssertEqual(+ object["schemaVersion"] as? Int, MeetingBackendEvidenceSchema.currentVersion+ )+ }++ func testEvidenceDecodeRejectsUnknownSchemaVersion() throws {+ let evidence = MeetingFinalTranscriptEvidence(+ backendID: self.backendID, attemptID: UUID(), units: [self.makeUnit()]+ )+ var object = try XCTUnwrap(+ JSONSerialization.jsonObject(with: self.encode(evidence)) as? [String: Any]+ )+ object["schemaVersion"] = 99+ let mutated = try JSONSerialization.data(withJSONObject: object)+ XCTAssertThrowsError(+ try JSONDecoder().decode(MeetingFinalTranscriptEvidence.self, from: mutated)+ )+ }++ func testSpeakerAssignmentDecodeIsFailClosedForUnknownKinds() throws {+ let token = MeetingBackendSpeakerToken(analysisEpochID: self.epoch, label: "slot-0")+ let assignedJSON = """+ {"kind":"assigned","token":{"analysisEpochID":{"trackID":"\(+ self.trackID.uuidString+ )","ordinal":0,"generation":0},"label":"slot-0"}}+ """+ XCTAssertEqual(+ try JSONDecoder().decode(+ MeetingBackendSpeakerAssignment.self, from: Data(assignedJSON.utf8)+ ),+ .assigned(token)+ )+ XCTAssertEqual(+ try JSONDecoder().decode(+ MeetingBackendSpeakerAssignment.self, from: Data(#"{"kind":"unassigned"}"#.utf8)+ ),+ .unassigned+ )++ // An unknown kind or a kind missing its payload must throw, never map to a default.+ for badJSON in [+ #"{"kind":"guessed"}"#,+ #"{"kind":"assigned"}"#,+ #"{"kind":"unassigned","token":{"analysisEpochID":{"trackID":"00000000-0000-0000-0000-000000000000","ordinal":0,"generation":0},"label":"slot-0"}}"#,+ #"{"kind":"ambiguous","token":{"analysisEpochID":{"trackID":"00000000-0000-0000-0000-000000000000","ordinal":0,"generation":0},"label":"slot-0"},"candidates":[]}"#,+ ] {+ XCTAssertThrowsError(+ try JSONDecoder().decode(+ MeetingBackendSpeakerAssignment.self, from: Data(badJSON.utf8)+ ),+ badJSON+ )+ }++ // Fewer than two candidates may decode structurally, but evidence validation must+ // still reject them — ambiguity is never silently resolved.+ let thinAmbiguity = try JSONDecoder().decode(+ MeetingBackendSpeakerAssignment.self,+ from: Data(#"{"kind":"ambiguous","candidates":[]}"#.utf8)+ )+ guard case let .ambiguous(candidates) = thinAmbiguity else {+ return XCTFail("expected .ambiguous, got \(thinAmbiguity)")+ }+ XCTAssertTrue(candidates.isEmpty)+ }++ func testTextUnitPrecisionDecodeIsFailClosed() throws {+ XCTAssertThrowsError(try JSONDecoder().decode(+ MeetingTextUnitPrecision.self, from: Data(#""syllable""#.utf8)+ ))+ }++ // MARK: - Sidecar ledger invariants++ func testValidSidecarPassesValidation() throws {+ let ambiguousUnit = self.makeUnit(id: "w-amb", speaker: .ambiguous([+ MeetingBackendSpeakerToken(analysisEpochID: self.epoch, label: "slot-0"),+ MeetingBackendSpeakerToken(analysisEpochID: self.epoch, label: "slot-1"),+ ]))+ let sidecar = self.makeSidecar(+ units: [self.makeUnit(id: "w-0"), ambiguousUnit],+ dispositions: [+ MeetingTextUnitDispositionRecord(unitID: "w-0", disposition: .emitted),+ MeetingTextUnitDispositionRecord(+ unitID: "w-amb", disposition: .ambiguousUnassigned,+ reasonCode: MeetingUnitDispositionReason.ambiguousSpeaker.rawValue+ ),+ ],+ receipts: [+ self.makeReceipt(id: "receipt-0"),+ self.makeReceipt(+ id: "receipt-1", spanID: "span-1", analysisStart: 5, analysisEnd: 9,+ status: .failed+ ),+ ]+ )+ XCTAssertEqual(try sidecar.validated(), sidecar)+ }++ func testSidecarRequiresExactlyOneDispositionPerUnit() throws {+ let twoUnits = [self.makeUnit(id: "w-0"), self.makeUnit(id: "w-1")]++ let missing = self.makeSidecar(+ units: twoUnits,+ dispositions: [MeetingTextUnitDispositionRecord(unitID: "w-0", disposition: .emitted)]+ )+ XCTAssertThrowsError(try missing.validated()) { error in+ XCTAssertEqual(+ error as? MeetingResultSidecarError, .missingDisposition(unitID: "w-1")+ )+ }++ let duplicate = self.makeSidecar(+ units: twoUnits,+ dispositions: [+ MeetingTextUnitDispositionRecord(unitID: "w-0", disposition: .emitted),+ MeetingTextUnitDispositionRecord(unitID: "w-0", disposition: .echoSuppressed),+ MeetingTextUnitDispositionRecord(unitID: "w-1", disposition: .emitted),+ ]+ )+ XCTAssertThrowsError(try duplicate.validated()) { error in+ XCTAssertEqual(+ error as? MeetingResultSidecarError, .duplicateDisposition(unitID: "w-0")+ )+ }++ let unknown = self.makeSidecar(+ units: twoUnits,+ dispositions: [+ MeetingTextUnitDispositionRecord(unitID: "w-0", disposition: .emitted),+ MeetingTextUnitDispositionRecord(unitID: "w-1", disposition: .emitted),+ MeetingTextUnitDispositionRecord(unitID: "ghost", disposition: .emitted),+ ]+ )+ XCTAssertThrowsError(try unknown.validated()) { error in+ XCTAssertEqual(+ error as? MeetingResultSidecarError, .dispositionForUnknownUnit(unitID: "ghost")+ )+ }+ }++ func testSidecarRejectsAmbiguityInconsistencies() throws {+ let ambiguousUnit = self.makeUnit(id: "w-amb", speaker: .ambiguous([+ MeetingBackendSpeakerToken(analysisEpochID: self.epoch, label: "slot-0"),+ MeetingBackendSpeakerToken(analysisEpochID: self.epoch, label: "slot-1"),+ ]))++ let emittedAmbiguous = self.makeSidecar(+ units: [ambiguousUnit],+ dispositions: [+ MeetingTextUnitDispositionRecord(unitID: "w-amb", disposition: .emitted),+ ]+ )+ XCTAssertThrowsError(try emittedAmbiguous.validated()) { error in+ XCTAssertEqual(+ error as? MeetingResultSidecarError,+ .emittedDispositionWithAmbiguity(unitID: "w-amb")+ )+ }++ let assignedUnit = self.makeUnit(id: "w-0")+ let ambiguousWithoutCandidates = self.makeSidecar(+ units: [assignedUnit],+ dispositions: [+ MeetingTextUnitDispositionRecord(unitID: "w-0", disposition: .ambiguousUnassigned),+ ]+ )+ XCTAssertThrowsError(try ambiguousWithoutCandidates.validated()) { error in+ XCTAssertEqual(+ error as? MeetingResultSidecarError,+ .ambiguousDispositionWithoutCandidates(unitID: "w-0")+ )+ }++ // A resolved-looking unit may still be admitted as unassigned when an earlier stage left+ // it ambiguous (for example uncertain timing) — but only with that reason named.+ let reasonedAmbiguous = self.makeSidecar(+ units: [assignedUnit],+ dispositions: [+ MeetingTextUnitDispositionRecord(+ unitID: "w-0",+ disposition: .ambiguousUnassigned,+ reasonCode: MeetingUnitDispositionReason.timingUncertain.rawValue+ ),+ ]+ )+ XCTAssertNoThrow(try reasonedAmbiguous.validated())++ // Exclusion precedence: an ambiguous unit may still be excluded by an earlier stage.+ let excludedAmbiguous = self.makeSidecar(+ units: [ambiguousUnit],+ dispositions: [+ MeetingTextUnitDispositionRecord(+ unitID: "w-amb", disposition: .inadmissible,+ reasonCode: MeetingUnitDispositionReason.inadmissibleCaptureEra.rawValue+ ),+ ]+ )+ XCTAssertNoThrow(try excludedAmbiguous.validated())++ let duplicateToken = MeetingBackendSpeakerToken(+ analysisEpochID: self.epoch,+ label: "slot-0"+ )+ let duplicateCandidates = self.makeSidecar(+ units: [self.makeUnit(id: "w-duplicate", speaker: .ambiguous([+ duplicateToken,+ duplicateToken,+ ]))],+ dispositions: [+ MeetingTextUnitDispositionRecord(+ unitID: "w-duplicate", disposition: .ambiguousUnassigned+ ),+ ]+ )+ XCTAssertThrowsError(try duplicateCandidates.validated()) { error in+ XCTAssertEqual(+ error as? MeetingResultSidecarError,+ .invalidAmbiguity(unitID: "w-duplicate")+ )+ }+ }++ func testSidecarCouplesInvalidTimingToItsQuarantineDisposition() throws {+ let invalidUnit = self.makeUnit(id: "bad-time", analysisStart: 2, analysisEnd: 2)+ let notQuarantined = self.makeSidecar(+ units: [invalidUnit],+ dispositions: [+ MeetingTextUnitDispositionRecord(unitID: invalidUnit.id, disposition: .emitted),+ ]+ )+ XCTAssertThrowsError(try notQuarantined.validated()) { error in+ XCTAssertEqual(+ error as? MeetingResultSidecarError,+ .invalidTimingNotRejected(unitID: invalidUnit.id)+ )+ }++ let quarantined = self.makeSidecar(+ units: [invalidUnit],+ dispositions: [+ MeetingTextUnitDispositionRecord(+ unitID: invalidUnit.id,+ disposition: .rejectedInvalidTiming,+ reasonCode: MeetingUnitQuarantineReason.invalidTiming.rawValue+ ),+ ]+ )+ XCTAssertNoThrow(try quarantined.validated())++ // Sound-looking bounds may still be quarantined — but only with the provenance reason+ // named; a bare rejection of a valid-looking unit is never accepted.+ let validButRejected = self.makeSidecar(+ units: [self.makeUnit(id: "valid-time")],+ dispositions: [+ MeetingTextUnitDispositionRecord(+ unitID: "valid-time", disposition: .rejectedInvalidTiming+ ),+ ]+ )+ XCTAssertThrowsError(try validButRejected.validated()) { error in+ XCTAssertEqual(+ error as? MeetingResultSidecarError,+ .rejectedInvalidTimingForValidUnit(unitID: "valid-time")+ )+ }++ let provenanceQuarantined = self.makeSidecar(+ units: [self.makeUnit(id: "cross-span")],+ dispositions: [+ MeetingTextUnitDispositionRecord(+ unitID: "cross-span",+ disposition: .rejectedInvalidTiming,+ reasonCode: MeetingUnitQuarantineReason.spansNotContiguousWithinEpoch.rawValue+ ),+ ]+ )+ XCTAssertNoThrow(try provenanceQuarantined.validated())+ }++ func testSidecarRejectsMalformedUnitProvenanceAndConfidence() throws {+ let noSpans = self.makeSidecar(+ units: [self.makeUnit(id: "no-spans", analysisSpanIDs: [])],+ dispositions: [+ MeetingTextUnitDispositionRecord(unitID: "no-spans", disposition: .emitted),+ ]+ )+ XCTAssertThrowsError(try noSpans.validated()) { error in+ XCTAssertEqual(+ error as? MeetingResultSidecarError,+ .missingUnitAnalysisSpans(unitID: "no-spans")+ )+ }++ // Confidence is a value check, so it binds only to units the ledger claims were usable;+ // a quarantined unit may carry the out-of-range value that quarantined it.+ let invalidConfidence = self.makeSidecar(+ units: [self.makeUnit(id: "bad-confidence", confidence: 1.1)],+ dispositions: [+ MeetingTextUnitDispositionRecord(unitID: "bad-confidence", disposition: .emitted),+ ]+ )+ XCTAssertThrowsError(try invalidConfidence.validated()) { error in+ XCTAssertEqual(+ error as? MeetingResultSidecarError,+ .invalidConfidence(unitID: "bad-confidence")+ )+ }++ let quarantinedConfidence = self.makeSidecar(+ units: [self.makeUnit(id: "quarantined-confidence", confidence: 1.1)],+ dispositions: [+ MeetingTextUnitDispositionRecord(+ unitID: "quarantined-confidence",+ disposition: .rejectedInvalidTiming,+ reasonCode: MeetingUnitQuarantineReason.invalidConfidence.rawValue+ ),+ ]+ )+ XCTAssertNoThrow(try quarantinedConfidence.validated())++ let duplicateSpans = self.makeSidecar(+ units: [self.makeUnit(+ id: "duplicate-spans",+ analysisSpanIDs: ["span-0", "span-0"]+ )],+ dispositions: [+ MeetingTextUnitDispositionRecord(+ unitID: "duplicate-spans", disposition: .emitted+ ),+ ]+ )+ XCTAssertThrowsError(try duplicateSpans.validated()) { error in+ XCTAssertEqual(+ error as? MeetingResultSidecarError,+ .duplicateUnitAnalysisSpanID(unitID: "duplicate-spans")+ )+ }++ let invalidEpoch = MeetingFinalTextUnit(+ id: "negative-epoch",+ trackID: self.trackID,+ analysisEpochID: MeetingAnalysisEpochID(trackID: self.trackID, ordinal: -1),+ precision: .word,+ text: "hello",+ analysisStart: 1,+ analysisEnd: 2,+ speaker: .unassigned,+ analysisSpanIDs: ["span-0"]+ )+ XCTAssertThrowsError(try self.makeSidecar(+ units: [invalidEpoch],+ dispositions: [+ MeetingTextUnitDispositionRecord(unitID: invalidEpoch.id, disposition: .emitted),+ ]+ ).validated()) { error in+ XCTAssertEqual(+ error as? MeetingResultSidecarError,+ .invalidAnalysisEpochOrdinal(unitID: invalidEpoch.id)+ )+ }+ }++ func testSidecarRejectsMalformedCoverageReceipts() throws {+ let invalid = self.makeSidecar(receipts: [+ self.makeReceipt(id: "receipt-bad", analysisStart: 4, analysisEnd: 4),+ ])+ XCTAssertThrowsError(try invalid.validated()) { error in+ XCTAssertEqual(+ error as? MeetingResultSidecarError,+ .invalidCoverageInterval(receiptID: "receipt-bad")+ )+ }++ let noSpan = self.makeSidecar(receipts: [+ self.makeReceipt(id: "receipt-orphan", spanID: " "),+ ])+ XCTAssertThrowsError(try noSpan.validated()) { error in+ XCTAssertEqual(+ error as? MeetingResultSidecarError,+ .emptyCoverageReceiptSpanID(receiptID: "receipt-orphan")+ )+ }++ let duplicateIDs = self.makeSidecar(receipts: [+ self.makeReceipt(id: "receipt-0", analysisStart: 0, analysisEnd: 5),+ self.makeReceipt(id: "receipt-0", analysisStart: 5, analysisEnd: 9, status: .failed),+ ])+ XCTAssertThrowsError(try duplicateIDs.validated()) { error in+ XCTAssertEqual(+ error as? MeetingResultSidecarError, .duplicateCoverageReceiptID("receipt-0")+ )+ }+ }++ func testSidecarRejectsDuplicateUnitIDs() throws {+ let duplicated = self.makeSidecar(+ units: [self.makeUnit(id: "w-0"), self.makeUnit(id: "w-0")],+ dispositions: [+ MeetingTextUnitDispositionRecord(unitID: "w-0", disposition: .emitted),+ ]+ )+ XCTAssertThrowsError(try duplicated.validated()) { error in+ XCTAssertEqual(error as? MeetingResultSidecarError, .duplicateUnitID("w-0"))+ }+ }++ func testSidecarDecodeRejectsUnknownSchemaVersionAndDispositions() throws {+ let sidecar = self.makeSidecar()+ var object = try XCTUnwrap(+ JSONSerialization.jsonObject(with: self.encode(sidecar)) as? [String: Any]+ )+ object["schemaVersion"] = 0+ let mutated = try JSONSerialization.data(withJSONObject: object)+ XCTAssertThrowsError(try JSONDecoder().decode(MeetingResultSidecar.self, from: mutated))++ var wrongDisposition = try XCTUnwrap(+ JSONSerialization.jsonObject(with: self.encode(sidecar)) as? [String: Any]+ )+ wrongDisposition["dispositions"] = [["unitID": "w-0", "disposition": "published"]]+ let badDisposition = try JSONSerialization.data(withJSONObject: wrongDisposition)+ XCTAssertThrowsError(try JSONDecoder().decode(MeetingResultSidecar.self, from: badDisposition))+ }++ // MARK: - Store++ func testStoreWriteReadRoundTripVerifiesChecksumAndLineage() throws {+ let directory = try self.makeTempSessionDirectory()+ let store = MeetingResultSidecarStore(sessionDirectory: directory)+ let attemptID = UUID()+ let sidecar = self.makeSidecar(attemptID: attemptID)++ let reference = try store.write(sidecar)+ XCTAssertEqual(+ reference.formatVersion,+ MeetingResultSidecarReferenceSchema.currentVersion+ )+ XCTAssertEqual(reference.fileName, MeetingResultSidecarStore.fileName(for: attemptID))++ let url = try store.sidecarURL(for: attemptID)+ XCTAssertEqual(+ url.deletingLastPathComponent().standardizedFileURL,+ directory.standardizedFileURL+ )+ let onDisk = try Data(contentsOf: url)+ XCTAssertEqual(onDisk.count, reference.byteCount)+ let expectedHash = SHA256.hash(data: onDisk).map { String(format: "%02x", $0) }.joined()+ XCTAssertEqual(reference.sha256, expectedHash)++ let permissions = try FileManager.default.attributesOfItem(atPath: url.path)[.posixPermissions]+ as? NSNumber+ XCTAssertEqual(permissions?.int16Value, 0o600)+ let directoryPermissions = try FileManager.default.attributesOfItem(atPath: directory.path)[.posixPermissions]+ as? NSNumber+ XCTAssertEqual(directoryPermissions?.int16Value, 0o700)++ let read = try store.read(+ expectedAttemptID: attemptID,+ expectedBackendID: self.backendID,+ reference: reference+ )+ XCTAssertEqual(read, sidecar)+ }++ func testStoreReadDetectsTampering() throws {+ let directory = try self.makeTempSessionDirectory()+ let store = MeetingResultSidecarStore(sessionDirectory: directory)+ let attemptID = UUID()+ let reference = try store.write(self.makeSidecar(attemptID: attemptID))++ let url = try store.sidecarURL(for: attemptID)+ var tampered = try Data(contentsOf: url)+ tampered[tampered.count - 3] = tampered[tampered.count - 3] ^ 0xff+ try tampered.write(to: url)++ XCTAssertThrowsError(try store.read(+ expectedAttemptID: attemptID,+ expectedBackendID: self.backendID,+ reference: reference+ )) { error in+ guard case MeetingResultSidecarStoreError.checksumMismatch = error else {+ return XCTFail("expected checksumMismatch, got \(error)")+ }+ }+ }++ func testStoreReadRejectsWrongAttemptBackendSchemaAndFileName() throws {+ let directory = try self.makeTempSessionDirectory()+ let store = MeetingResultSidecarStore(sessionDirectory: directory)+ let attemptID = UUID()+ let reference = try store.write(self.makeSidecar(attemptID: attemptID))++ XCTAssertThrowsError(try store.read(+ expectedAttemptID: UUID(),+ expectedBackendID: self.backendID,+ reference: reference+ )) { error in+ guard case MeetingResultSidecarStoreError.unexpectedFileName = error else {+ return XCTFail("expected unexpectedFileName, got \(error)")+ }+ }++ XCTAssertThrowsError(try store.read(+ expectedAttemptID: attemptID,+ expectedBackendID: .legacyCompatibility,+ reference: reference+ )) { error in+ XCTAssertEqual(+ error as? MeetingResultSidecarStoreError,+ .backendMismatch(expected: .legacyCompatibility, actual: self.backendID)+ )+ }++ let futureReference = MeetingResultSidecarReference(+ formatVersion: 99,+ fileName: reference.fileName,+ sha256: reference.sha256,+ byteCount: reference.byteCount+ )+ XCTAssertThrowsError(try store.read(+ expectedAttemptID: attemptID,+ expectedBackendID: self.backendID,+ reference: futureReference+ )) { error in+ XCTAssertEqual(+ error as? MeetingResultSidecarStoreError,+ .unsupportedReferenceFormatVersion(found: 99)+ )+ }++ let renamedReference = MeetingResultSidecarReference(+ formatVersion: reference.formatVersion,+ fileName: "../checkpoint.json",+ sha256: reference.sha256,+ byteCount: reference.byteCount+ )+ XCTAssertThrowsError(try store.read(+ expectedAttemptID: attemptID,+ expectedBackendID: self.backendID,+ reference: renamedReference+ )) { error in+ guard case MeetingResultSidecarStoreError.unexpectedFileName = error else {+ return XCTFail("a reference must never be able to name another file: \(error)")+ }+ }+ }++ func testStoreRejectsInvalidSidecarInsteadOfWriting() throws {+ let directory = try self.makeTempSessionDirectory()+ let store = MeetingResultSidecarStore(sessionDirectory: directory)+ let attemptID = UUID()+ let invalid = self.makeSidecar(+ attemptID: attemptID,+ units: [self.makeUnit(id: "w-0")],+ dispositions: []+ )+ XCTAssertThrowsError(try store.write(invalid)) { error in+ XCTAssertEqual(+ error as? MeetingResultSidecarError, .missingDisposition(unitID: "w-0")+ )+ }+ XCTAssertFalse(+ FileManager.default.fileExists(+ atPath: directory.appendingPathComponent(+ MeetingResultSidecarStore.fileName(for: attemptID)+ ).path+ )+ )+ }++ func testStorePersistsQuarantinedNonFiniteEvidenceWithoutMakingItValid() throws {+ let directory = try self.makeTempSessionDirectory()+ let store = MeetingResultSidecarStore(sessionDirectory: directory)+ let attemptID = UUID()+ let unit = self.makeUnit(id: "nan-time", analysisStart: .nan, analysisEnd: 2)+ let sidecar = self.makeSidecar(+ attemptID: attemptID,+ units: [unit],+ dispositions: [+ MeetingTextUnitDispositionRecord(+ unitID: unit.id,+ disposition: .rejectedInvalidTiming,+ reasonCode: MeetingUnitQuarantineReason.invalidTiming.rawValue+ ),+ ]+ )++ let reference = try store.write(sidecar)+ let decoded = try store.read(+ expectedAttemptID: attemptID,+ expectedBackendID: self.backendID,+ reference: reference+ )+ XCTAssertTrue(decoded.units[0].analysisStart.isNaN)+ XCTAssertEqual(decoded.dispositions[0].disposition, .rejectedInvalidTiming)+ }++ func testStoreMakesAttemptSidecarImmutableAndAllowsIdempotentJoin() throws {+ let directory = try self.makeTempSessionDirectory()+ let store = MeetingResultSidecarStore(sessionDirectory: directory)+ let attemptID = UUID()+ let original = self.makeSidecar(attemptID: attemptID)+ let originalReference = try store.write(original)++ XCTAssertEqual(try store.write(original), originalReference)++ let changed = self.makeSidecar(+ attemptID: attemptID,+ units: [self.makeUnit(text: "changed")]+ )+ XCTAssertThrowsError(try store.write(changed)) { error in+ XCTAssertEqual(+ error as? MeetingResultSidecarStoreError,+ .conflictingExistingSidecar(attemptID: attemptID)+ )+ }+ XCTAssertEqual(+ try store.read(+ expectedAttemptID: attemptID,+ expectedBackendID: self.backendID,+ reference: originalReference+ ),+ original+ )+ }++ func testStoreRejectsPreexistingSidecarSymlinkEscapingSessionDirectory() throws {+ let directory = try self.makeTempSessionDirectory()+ let store = MeetingResultSidecarStore(sessionDirectory: directory)+ let attemptID = UUID()+ let outsideURL = FileManager.default.temporaryDirectory+ .appendingPathComponent("sidecar-outside-\(UUID().uuidString).json")+ let sentinel = Data("do-not-overwrite".utf8)+ try sentinel.write(to: outsideURL)+ self.addTeardownBlock { try? FileManager.default.removeItem(at: outsideURL) }+ let linkURL = directory.appendingPathComponent(+ MeetingResultSidecarStore.fileName(for: attemptID)+ )+ try FileManager.default.createSymbolicLink(+ at: linkURL,+ withDestinationURL: outsideURL+ )++ XCTAssertThrowsError(try store.write(self.makeSidecar(attemptID: attemptID))) { error in+ XCTAssertEqual(+ error as? MeetingResultSidecarStoreError,+ .pathEscapesSessionDirectory+ )+ }+ XCTAssertEqual(try Data(contentsOf: outsideURL), sentinel)+ }++ func testSidecarRejectsArbitraryDispositionReasonCodes() throws {+ let unit = self.makeUnit(id: "u-reason")+ let rejected = self.makeSidecar(+ units: [unit],+ dispositions: [+ MeetingTextUnitDispositionRecord(+ unitID: unit.id,+ disposition: .rejectedInvalidTiming,+ reasonCode: "trust-me"+ ),+ ]+ )+ XCTAssertThrowsError(try rejected.validated()) { error in+ XCTAssertEqual(+ error as? MeetingResultSidecarError,+ .rejectedInvalidTimingForValidUnit(unitID: unit.id)+ )+ }++ let emitted = self.makeSidecar(+ units: [unit],+ dispositions: [+ MeetingTextUnitDispositionRecord(+ unitID: unit.id,+ disposition: .emitted,+ reasonCode: "unexpected"+ ),+ ]+ )+ XCTAssertThrowsError(try emitted.validated()) { error in+ XCTAssertEqual(+ error as? MeetingResultSidecarError,+ .invalidDispositionReason(unitID: unit.id)+ )+ }+ }+}diff --git a/Tests/FluidDictationIntegrationTests/MeetingTextOverlapEchoVerdictProviderTests.swift b/Tests/FluidDictationIntegrationTests/MeetingTextOverlapEchoVerdictProviderTests.swiftnew file mode 100644index 00000000..848ed11f--- /dev/null+++ b/Tests/FluidDictationIntegrationTests/MeetingTextOverlapEchoVerdictProviderTests.swift@@ -0,0 +1,362 @@+@testable import FluidVoice_Debug+import Foundation+import XCTest++/// Stage E of `MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md`: the deterministic text/time echo+/// verdict provider. Only online-call microphone units get verdicts, and only against temporally+/// overlapping application units measured by the existing `MeetingEchoDetector`.+@MainActor+final class MeetingTextOverlapEchoVerdictProviderTests: XCTestCase {+ // MARK: - Fixtures++ private struct FixtureObserver: MeetingChunkAudioObserving {+ let results: [MeetingAnalysisChunkKey: MeetingChunkObservationResult]++ func observe(+ chunk: MeetingAudioChunk,+ trackID: MeetingAudioTrackID+ ) -> MeetingChunkObservationResult {+ self.results[MeetingAnalysisChunkKey(trackID: trackID, chunkID: chunk.id)]+ ?? .failed(.unreadable, detail: "no fixture observation")+ }+ }++ private func makeChunk(sequence: Int, start: Double, end: Double, path: String) -> MeetingAudioChunk {+ MeetingAudioChunk(+ id: UUID(),+ sequence: sequence,+ relativeFilePath: path,+ presentationStart: MeetingMediaTime(value: Int64((start * 1000).rounded()), timescale: 1000),+ presentationEnd: MeetingMediaTime(value: Int64((end * 1000).rounded()), timescale: 1000),+ discontinuities: [],+ sha256: String(repeating: "a", count: 64),+ byteCount: 1024,+ finalizationState: .finalized+ )+ }++ private func makeObserved(_ chunk: MeetingAudioChunk, duration: Double) -> MeetingChunkObservationResult {+ .observed(MeetingChunkObservedAudio(+ byteCount: chunk.byteCount,+ sha256: chunk.sha256,+ decoded: MeetingChunkDecodedFacts(+ sampleRate: 16_000,+ channelCount: 1,+ frameCount: Int64((duration * 16_000).rounded()),+ durationSeconds: duration,+ codecPriming: .measuredFrames(0),+ processingFormatDescription: "fixture"+ )+ ))+ }++ private struct EchoFixture {+ let plan: MeetingBackendPlan+ let manifest: MeetingAnalysisManifest+ let micTrackID: MeetingAudioTrackID+ let appTrackID: MeetingAudioTrackID+ let micEpoch: MeetingAnalysisEpochRecord+ let appEpochs: [MeetingAnalysisEpochRecord]+ }++ /// Online call: mic chunk [100,102) and app chunks [100,102) and [110,112).+ private func makeFixture(mode: MeetingCaptureMode = .onlineCall) throws -> EchoFixture {+ let micChunk = self.makeChunk(sequence: 0, start: 100, end: 102, path: "tracks/microphone/chunk_0.caf")+ let appChunk0 = self.makeChunk(sequence: 0, start: 100, end: 102, path: "tracks/application/chunk_0.caf")+ let appChunk1 = self.makeChunk(sequence: 1, start: 110, end: 112, path: "tracks/application/chunk_1.caf")+ let micTrack = MeetingAudioTrack(+ id: UUID(),+ kind: .microphone,+ sourceIdentifier: "microphone",+ sourceDisplayName: "microphone",+ format: nil,+ timebase: MeetingTimebaseMetadata(+ startedHostTime: 7, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil+ ),+ health: .waiting,+ chunks: [micChunk],+ captureMethod: .voiceProcessing,+ captureEras: [MeetingCaptureEra(+ method: .voiceProcessing,+ deviceUID: "mic-a",+ deviceName: "mic-a",+ roleAtElection: .unknown,+ echoProtection: .voiceProcessed,+ startSeconds: 100+ )]+ )+ let appTrack = MeetingAudioTrack(+ id: UUID(),+ kind: .applicationAudio,+ sourceIdentifier: "application",+ sourceDisplayName: "application",+ format: nil,+ timebase: MeetingTimebaseMetadata(+ startedHostTime: 7, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil+ ),+ health: .waiting,+ chunks: [appChunk0, appChunk1],+ captureMethod: .screenCaptureKit+ )+ var session = MeetingSession(+ configuration: MeetingCaptureConfiguration(+ mode: mode,+ title: "Echo fixture",+ application: mode == .onlineCall+ ? MeetingApplicationIdentity(bundleIdentifier: "fixture.app", displayName: "Fixture")+ : nil,+ microphone: MeetingMicrophoneIdentity(captureDeviceID: "mic-a", displayName: "Mic")+ ),+ timebase: MeetingTimebaseMetadata(+ startedHostTime: 7, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil+ )+ )+ session.audioTracks = [micTrack, appTrack]+ session.processingAttempts = [MeetingProcessingAttempt(+ id: UUID(),+ startedAt: Date(timeIntervalSinceNow: -30),+ completedAt: nil,+ stage: .pending,+ pipelineVersion: MeetingProcessingPipeline.pipelineVersion,+ asrProvider: nil,+ asrModel: nil,+ diarizationModel: nil,+ lastCompletedTrackID: nil,+ errorCode: nil+ )]+ let directory = FileManager.default.temporaryDirectory+ let request = MeetingBackendRequest(+ attemptID: session.processingAttempts.last?.id ?? UUID(),+ session: session,+ sessionDirectory: directory,+ configuration: MeetingFinalProcessingConfiguration(languageCode: "en")+ )+ let plan = MeetingBackendPlan(request: request, descriptor: MeetingParakeetNemotronBackend.descriptor)+ let manifest = try MeetingAnalysisManifestBuilder(+ plan: plan,+ observer: FixtureObserver(results: [+ MeetingAnalysisChunkKey(trackID: micTrack.id, chunkID: micChunk.id): self.makeObserved(micChunk, duration: 2),+ MeetingAnalysisChunkKey(trackID: appTrack.id, chunkID: appChunk0.id): self.makeObserved(appChunk0, duration: 2),+ MeetingAnalysisChunkKey(trackID: appTrack.id, chunkID: appChunk1.id): self.makeObserved(appChunk1, duration: 2),+ ]),+ analysisSampleRate: 16_000+ ).build()+ return EchoFixture(+ plan: plan,+ manifest: manifest,+ micTrackID: micTrack.id,+ appTrackID: appTrack.id,+ micEpoch: try XCTUnwrap(manifest.track(micTrack.id)?.epochs.first),+ appEpochs: try XCTUnwrap(manifest.track(appTrack.id)?.epochs)+ )+ }++ private func unit(+ _ id: String,+ trackID: MeetingAudioTrackID,+ epoch: MeetingAnalysisEpochRecord,+ text: String,+ analysisStart: Double,+ analysisEnd: Double+ ) -> MeetingFinalTextUnit {+ MeetingFinalTextUnit(+ id: id,+ trackID: trackID,+ analysisEpochID: epoch.id,+ precision: .word,+ text: text,+ analysisStart: analysisStart,+ analysisEnd: analysisEnd,+ speaker: .unassigned,+ analysisSpanIDs: epoch.spanIDs+ )+ }++ // MARK: - Verdicts++ func testSuppressesTemporallyOverlappingEchoOnly() async throws {+ let fixture = try self.makeFixture()+ let echoText = "the quick brown fox jumps over the lazy dog"+ let evidence = MeetingFinalTranscriptEvidence(+ backendID: .parakeetNemotron,+ attemptID: fixture.plan.attemptID,+ units: [+ self.unit("app-0", trackID: fixture.appTrackID, epoch: fixture.appEpochs[0], text: echoText, analysisStart: 0.2, analysisEnd: 1.8),+ self.unit("mic-0", trackID: fixture.micTrackID, epoch: fixture.micEpoch, text: echoText, analysisStart: 0.4, analysisEnd: 1.9),+ self.unit("mic-1", trackID: fixture.micTrackID, epoch: fixture.micEpoch, text: "an entirely local remark about lunch", analysisStart: 0.4, analysisEnd: 1.9),+ ]+ )+ let verdicts = try await MeetingTextOverlapEchoVerdictProvider().echoVerdicts(+ for: evidence, manifest: fixture.manifest, plan: fixture.plan+ )+ XCTAssertEqual(verdicts["mic-0"], .echoSuppressed(duplicateOfUnitID: "app-0"))+ XCTAssertEqual(verdicts["mic-1"], .notEcho)+ XCTAssertNil(verdicts["app-0"], "application units need no verdict")+ }++ func testWordPrecisionUsesTemporalPhraseContext() async throws {+ let fixture = try self.makeFixture()+ let words = ["quick", "brown", "fox", "jumps"]+ var units: [MeetingFinalTextUnit] = []+ for (index, word) in words.enumerated() {+ let start = 0.2 + Double(index) * 0.25+ units.append(self.unit(+ "app-word-\(index)", trackID: fixture.appTrackID, epoch: fixture.appEpochs[0],+ text: word, analysisStart: start, analysisEnd: start + 0.2+ ))+ units.append(self.unit(+ "mic-word-\(index)", trackID: fixture.micTrackID, epoch: fixture.micEpoch,+ text: word, analysisStart: start + 0.05, analysisEnd: start + 0.25+ ))+ }+ units.append(self.unit(+ "mic-local", trackID: fixture.micTrackID, epoch: fixture.micEpoch,+ text: "lunch", analysisStart: 1.3, analysisEnd: 1.5+ ))+ let evidence = MeetingFinalTranscriptEvidence(+ backendID: .parakeetNemotron,+ attemptID: fixture.plan.attemptID,+ units: units+ )++ let verdicts = try await MeetingTextOverlapEchoVerdictProvider().echoVerdicts(+ for: evidence, manifest: fixture.manifest, plan: fixture.plan+ )++ for index in words.indices {+ guard case .echoSuppressed? = verdicts["mic-word-\(index)"] else {+ return XCTFail("word-level echo \(index) should be suppressed using phrase context")+ }+ }+ XCTAssertEqual(verdicts["mic-local"], .notEcho)+ }++ func testEchoTextWithoutTemporalOverlapIsNotSuppressed() async throws {+ let fixture = try self.makeFixture()+ let echoText = "the quick brown fox jumps over the lazy dog"+ let farEpoch = fixture.appEpochs[1]+ let evidence = MeetingFinalTranscriptEvidence(+ backendID: .parakeetNemotron,+ attemptID: fixture.plan.attemptID,+ units: [+ // Same words, ten seconds later: text match alone must not suppress.+ self.unit("app-far", trackID: fixture.appTrackID, epoch: farEpoch, text: echoText, analysisStart: farEpoch.analysisInterval.start + 0.2, analysisEnd: farEpoch.analysisInterval.start + 1.8),+ self.unit("mic-0", trackID: fixture.micTrackID, epoch: fixture.micEpoch, text: echoText, analysisStart: 0.4, analysisEnd: 1.9),+ ]+ )+ let verdicts = try await MeetingTextOverlapEchoVerdictProvider().echoVerdicts(+ for: evidence, manifest: fixture.manifest, plan: fixture.plan+ )+ XCTAssertEqual(verdicts["mic-0"], .notEcho)+ }++ func testFutureRemoteRepetitionCannotSuppressEarlierMicrophoneWords() async throws {+ let fixture = try self.makeFixture()+ let words = ["quick", "brown", "fox", "jumps"]+ var units: [MeetingFinalTextUnit] = []+ for (index, word) in words.enumerated() {+ let micStart = 0.05 + Double(index) * 0.15+ let appStart = 1.1 + Double(index) * 0.15+ units.append(self.unit(+ "mic-earlier-\(index)", trackID: fixture.micTrackID, epoch: fixture.micEpoch,+ text: word, analysisStart: micStart, analysisEnd: micStart + 0.1+ ))+ units.append(self.unit(+ "app-later-\(index)", trackID: fixture.appTrackID, epoch: fixture.appEpochs[0],+ text: word, analysisStart: appStart, analysisEnd: appStart + 0.1+ ))+ }+ let evidence = MeetingFinalTranscriptEvidence(+ backendID: .parakeetNemotron,+ attemptID: fixture.plan.attemptID,+ units: units+ )++ let verdicts = try await MeetingTextOverlapEchoVerdictProvider().echoVerdicts(+ for: evidence, manifest: fixture.manifest, plan: fixture.plan+ )++ for index in words.indices {+ XCTAssertEqual(verdicts["mic-earlier-\(index)"], .notEcho)+ }+ }++ func testInRoomSessionNeedsNoVerdicts() async throws {+ let fixture = try self.makeFixture(mode: .inRoom)+ let evidence = MeetingFinalTranscriptEvidence(+ backendID: .parakeetNemotron,+ attemptID: fixture.plan.attemptID,+ units: [+ self.unit("mic-0", trackID: fixture.micTrackID, epoch: fixture.micEpoch, text: "anything", analysisStart: 0.4, analysisEnd: 1.0),+ ]+ )+ let verdicts = try await MeetingTextOverlapEchoVerdictProvider().echoVerdicts(+ for: evidence, manifest: fixture.manifest, plan: fixture.plan+ )+ XCTAssertTrue(verdicts.isEmpty)+ }++ func testQuarantinedUnitsAreSkipped() async throws {+ let fixture = try self.makeFixture()+ var bad = self.unit("mic-bad", trackID: fixture.micTrackID, epoch: fixture.micEpoch, text: "broken", analysisStart: 1.5, analysisEnd: 1.0)+ bad = MeetingFinalTextUnit(+ id: bad.id,+ trackID: bad.trackID,+ analysisEpochID: bad.analysisEpochID,+ precision: bad.precision,+ text: bad.text,+ analysisStart: 1.5,+ analysisEnd: 1.0,+ speaker: bad.speaker,+ analysisSpanIDs: bad.analysisSpanIDs+ )+ let evidence = MeetingFinalTranscriptEvidence(+ backendID: .parakeetNemotron,+ attemptID: fixture.plan.attemptID,+ units: [bad]+ )+ let verdicts = try await MeetingTextOverlapEchoVerdictProvider().echoVerdicts(+ for: evidence, manifest: fixture.manifest, plan: fixture.plan+ )+ XCTAssertTrue(verdicts.isEmpty, "quarantined units get no verdict and no interval arithmetic")+ }++ func testAssemblySuppressesTheEchoAndKeepsTheApplicationCopy() async throws {+ let fixture = try self.makeFixture()+ let echoText = "the quick brown fox jumps over the lazy dog"+ let evidence = MeetingFinalTranscriptEvidence(+ backendID: .parakeetNemotron,+ attemptID: fixture.plan.attemptID,+ units: [+ self.unit("app-0", trackID: fixture.appTrackID, epoch: fixture.appEpochs[0], text: echoText, analysisStart: 0.2, analysisEnd: 1.8),+ self.unit("mic-0", trackID: fixture.micTrackID, epoch: fixture.micEpoch, text: echoText, analysisStart: 0.4, analysisEnd: 1.9),+ ]+ )+ let verdicts = try await MeetingTextOverlapEchoVerdictProvider().echoVerdicts(+ for: evidence, manifest: fixture.manifest, plan: fixture.plan+ )+ let receipts = fixture.manifest.allSpans.map { span in+ MeetingSpanCoverageReceipt(+ id: "receipt:\(span.id)",+ spanID: span.id,+ analysisStart: span.analysisInterval.start,+ analysisEnd: span.analysisInterval.end,+ status: .processed+ )+ }+ let assembly = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: fixture.plan,+ manifest: fixture.manifest,+ evidence: evidence,+ coverageReceipts: receipts,+ echoVerdicts: verdicts+ ))+ let dispositions = Dictionary(+ assembly.sidecar.dispositions.map { ($0.unitID, $0.disposition) },+ uniquingKeysWith: { first, _ in first }+ )+ XCTAssertEqual(dispositions["mic-0"], .echoSuppressed)+ XCTAssertEqual(dispositions["app-0"], .emitted)+ XCTAssertEqual(assembly.segments.map(\.text), [echoText], "the microphone copy is ledger-only")+ }+}diff --git a/Tests/FluidDictationIntegrationTests/MeetingTimelineMigrationTests.swift b/Tests/FluidDictationIntegrationTests/MeetingTimelineMigrationTests.swiftnew file mode 100644index 00000000..11dedf9c--- /dev/null+++ b/Tests/FluidDictationIntegrationTests/MeetingTimelineMigrationTests.swift@@ -0,0 +1,132 @@+@testable import FluidVoice_Debug+import Foundation+import XCTest++final class MeetingTimelineMigrationTests: XCTestCase {+ func testCanonicalAbsoluteTimelineMigratesSegmentsAndGapsExactlyOnce() throws {+ let origin = 505_879.706+ let fixture = self.session(+ origin: origin,+ segmentStart: origin + 0.24,+ segmentEnd: origin + 78.56,+ gapStart: origin + 2.09,+ gapEnd: origin + 4.25+ )++ let migrated = try XCTUnwrap(MeetingSessionStore.migratingCanonicalTimelineToMeetingRelative(+ fixture,+ presentationOriginSeconds: origin+ ))++ XCTAssertEqual(migrated.transcriptTimeDomain, .meetingRelative)+ XCTAssertEqual(migrated.transcriptSegments[0].start.seconds, 0.24, accuracy: 0.001)+ XCTAssertEqual(migrated.transcriptSegments[0].end.seconds, 78.56, accuracy: 0.001)+ XCTAssertEqual(migrated.transcriptCoverageGaps?[0].start ?? -1, 2.09, accuracy: 0.000_001)+ XCTAssertEqual(migrated.transcriptCoverageGaps?[0].end ?? -1, 4.25, accuracy: 0.000_001)+ XCTAssertEqual(migrated.transcriptSegments[0].id, fixture.transcriptSegments[0].id)+ XCTAssertEqual(migrated.transcriptSegments[0].speakerID, fixture.transcriptSegments[0].speakerID)+ XCTAssertNil(MeetingSessionStore.migratingCanonicalTimelineToMeetingRelative(+ migrated,+ presentationOriginSeconds: origin+ ))+ }++ func testSmallHostOriginIsMigratedByExplicitDomainNotMagnitudeHeuristic() throws {+ let origin = 30.0+ let fixture = self.session(+ origin: origin,+ segmentStart: 30.25,+ segmentEnd: 79.75,+ gapStart: 31,+ gapEnd: 32+ )++ let migrated = try XCTUnwrap(MeetingSessionStore.migratingCanonicalTimelineToMeetingRelative(+ fixture,+ presentationOriginSeconds: origin+ ))+ XCTAssertEqual(migrated.transcriptSegments[0].start.seconds, 0.25, accuracy: 0.001)+ XCTAssertEqual(migrated.transcriptSegments[0].end.seconds, 49.75, accuracy: 0.001)+ }++ func testMigrationRefusesOriginThatWouldMakeTranscriptNegative() {+ let fixture = self.session(+ origin: 100,+ segmentStart: 99,+ segmentEnd: 101,+ gapStart: 100,+ gapEnd: 101+ )+ XCTAssertNil(MeetingSessionStore.migratingCanonicalTimelineToMeetingRelative(+ fixture,+ presentationOriginSeconds: 100+ ))+ }++ private func session(+ origin: TimeInterval,+ segmentStart: TimeInterval,+ segmentEnd: TimeInterval,+ gapStart: TimeInterval,+ gapEnd: TimeInterval+ ) -> MeetingSession {+ let configuration = MeetingCaptureConfiguration(+ mode: .inRoom,+ title: "Timeline migration",+ microphone: MeetingMicrophoneIdentity(captureDeviceID: "mic", displayName: "Mic")+ )+ var session = MeetingSession(+ configuration: configuration,+ startedAt: Date(timeIntervalSince1970: 1_700_000_000),+ timebase: MeetingTimebaseMetadata(+ startedHostTime: 1,+ machTimebaseNumerator: 1,+ machTimebaseDenominator: 1,+ firstPresentationTime: self.mediaTime(origin)+ )+ )+ let trackID = UUID()+ let speakerID = UUID()+ session.audioTracks = [MeetingAudioTrack(+ id: trackID,+ kind: .microphone,+ sourceIdentifier: "mic",+ sourceDisplayName: "Mic",+ format: nil,+ timebase: session.timebase,+ health: .waiting,+ chunks: []+ )]+ session.speakers = [MeetingSessionSpeaker(+ id: speakerID,+ displayName: "Speaker 1",+ diarizationClusterID: "slot-0",+ trackKind: .microphone,+ isLocalUser: false,+ identityCandidates: []+ )]+ session.transcriptSegments = [MeetingTranscriptSegment(+ id: UUID(),+ start: self.mediaTime(segmentStart),+ end: self.mediaTime(segmentEnd),+ sourceTrackID: trackID,+ speakerID: speakerID,+ text: "hello",+ revision: 0,+ status: .final,+ overlap: .none,+ completeness: .complete+ )]+ session.transcriptCoverageGaps = [MeetingTranscriptCoverageGap(+ trackID: trackID,+ start: gapStart,+ end: gapEnd,+ reason: .processingFailed+ )]+ return session+ }++ private func mediaTime(_ seconds: TimeInterval) -> MeetingMediaTime {+ MeetingMediaTime(value: Int64((seconds * 1_000).rounded()), timescale: 1_000)+ }+}diff --git a/Tests/FluidDictationIntegrationTests/MeetingTranscriptAssemblerTests.swift b/Tests/FluidDictationIntegrationTests/MeetingTranscriptAssemblerTests.swiftnew file mode 100644index 00000000..424de835--- /dev/null+++ b/Tests/FluidDictationIntegrationTests/MeetingTranscriptAssemblerTests.swift@@ -0,0 +1,1265 @@+@testable import FluidVoice_Debug+import Foundation+import XCTest++private nonisolated struct AssemblerFixtureObserver: MeetingChunkAudioObserving {+ let results: [MeetingAnalysisChunkKey: MeetingChunkObservationResult]++ func observe(+ chunk: MeetingAudioChunk,+ trackID: MeetingAudioTrackID+ ) -> MeetingChunkObservationResult {+ self.results[MeetingAnalysisChunkKey(trackID: trackID, chunkID: chunk.id)]+ ?? .failed(.unreadable, detail: "No fixture observation")+ }+}++/// Stage C2b1 of `MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md`: the pure assembler. Every fixture+/// builds a real manifest through `MeetingAnalysisManifestBuilder` so units, receipts and gaps are+/// exercised against spans the validator actually proved.+final class MeetingTranscriptAssemblerTests: XCTestCase {+ private let backendID = MeetingBackendID(rawValue: "fixture.assembler")++ // MARK: - Session/manifest fixtures++ private func chunk(+ id: UUID = UUID(),+ sequence: Int,+ start: Double,+ end: Double,+ discontinuities: [MeetingAudioDiscontinuity] = []+ ) -> MeetingAudioChunk {+ MeetingAudioChunk(+ id: id,+ sequence: sequence,+ relativeFilePath: "tracks/chunk-\(sequence).m4a",+ presentationStart: self.mediaTime(start),+ presentationEnd: self.mediaTime(end),+ discontinuities: discontinuities,+ sha256: String(repeating: String((sequence % 9) + 1), count: 64),+ byteCount: 1024,+ finalizationState: .finalized+ )+ }++ private func mediaTime(_ seconds: Double) -> MeetingMediaTime {+ MeetingMediaTime(value: Int64((seconds * 1000).rounded()), timescale: 1000)+ }++ private func era(+ protection: MeetingMicrophoneEchoProtection,+ start: Double,+ deviceUID: String = "mic-a",+ drift: MeetingClockDriftRecord? = nil+ ) -> MeetingCaptureEra {+ MeetingCaptureEra(+ method: .voiceProcessing,+ deviceUID: deviceUID,+ deviceName: deviceUID,+ roleAtElection: .unknown,+ echoProtection: protection,+ startSeconds: start,+ clockDrift: drift+ )+ }++ private func track(+ id: UUID = UUID(),+ kind: MeetingAudioTrackKind,+ chunks: [MeetingAudioChunk],+ captureMethod: MeetingAudioTrackCaptureMethod? = nil,+ eras: [MeetingCaptureEra]? = nil+ ) -> MeetingAudioTrack {+ MeetingAudioTrack(+ id: id,+ kind: kind,+ sourceIdentifier: kind.rawValue,+ sourceDisplayName: kind.rawValue,+ format: nil,+ timebase: MeetingTimebaseMetadata(+ startedHostTime: 42,+ machTimebaseNumerator: 1,+ machTimebaseDenominator: 1,+ firstPresentationTime: nil+ ),+ health: .waiting,+ chunks: chunks,+ captureMethod: captureMethod,+ captureEras: eras+ )+ }++ private func plan(+ mode: MeetingCaptureMode,+ tracks: [MeetingAudioTrack]+ ) -> MeetingBackendPlan {+ let application = mode == .onlineCall+ ? MeetingApplicationIdentity(bundleIdentifier: "fixture.app", displayName: "Fixture")+ : nil+ var session = MeetingSession(+ configuration: MeetingCaptureConfiguration(+ mode: mode,+ title: "Assembler fixture",+ application: application,+ microphone: MeetingMicrophoneIdentity(+ captureDeviceID: "mic-a",+ coreAudioUID: "mic-a",+ displayName: "Mic"+ )+ ),+ timebase: MeetingTimebaseMetadata(+ startedHostTime: 1,+ machTimebaseNumerator: 1,+ machTimebaseDenominator: 1,+ firstPresentationTime: nil+ )+ )+ session.audioTracks = tracks+ let request = MeetingBackendRequest(+ attemptID: UUID(),+ session: session,+ sessionDirectory: FileManager.default.temporaryDirectory,+ configuration: MeetingFinalProcessingConfiguration()+ )+ return MeetingBackendPlan(+ request: request,+ descriptor: MeetingBackendDescriptor(+ id: self.backendID,+ version: "c2b1-test",+ execution: .local,+ supportedLanguageCodes: ["en"],+ supportedTrackKinds: Set(MeetingAudioTrackKind.allCases),+ supportedFinalPrecisions: [.word, .utterance],+ resultContract: .canonicalEvidence,+ knownLimits: []+ )+ )+ }++ private func observed(+ _ chunk: MeetingAudioChunk,+ duration: Double,+ priming: MeetingCodecPriming = .measuredFrames(0)+ ) -> MeetingChunkObservationResult {+ .observed(MeetingChunkObservedAudio(+ byteCount: chunk.byteCount,+ sha256: chunk.sha256,+ decoded: MeetingChunkDecodedFacts(+ sampleRate: 100,+ channelCount: 1,+ frameCount: Int64((duration * 100).rounded()),+ durationSeconds: duration,+ codecPriming: priming,+ processingFormatDescription: "fixture"+ )+ ))+ }++ private func buildManifest(+ plan: MeetingBackendPlan,+ observations: [(MeetingAudioTrackID, MeetingAudioChunk, MeetingChunkObservationResult)]+ ) throws -> MeetingAnalysisManifest {+ try MeetingAnalysisManifestBuilder(+ plan: plan,+ observer: AssemblerFixtureObserver(results: Dictionary(+ uniqueKeysWithValues: observations.map {+ (MeetingAnalysisChunkKey(trackID: $0.0, chunkID: $0.1.id), $0.2)+ }+ ))+ ).build()+ }++ /// One online microphone chunk, presentation 100..<100+duration>, one admissible era.+ private func onlineMicFixture(+ duration: Double = 10,+ priming: MeetingCodecPriming = .measuredFrames(0),+ drift: MeetingClockDriftRecord? = nil+ ) throws -> (plan: MeetingBackendPlan, manifest: MeetingAnalysisManifest, span: MeetingAnalysisSpan) {+ let chunk = self.chunk(sequence: 0, start: 100, end: 100 + duration)+ let track = self.track(+ kind: .microphone,+ chunks: [chunk],+ eras: [self.era(protection: .voiceProcessed, start: 100, drift: drift)]+ )+ let plan = self.plan(mode: .onlineCall, tracks: [track])+ let manifest = try self.buildManifest(+ plan: plan,+ observations: [(track.id, chunk, self.observed(chunk, duration: duration, priming: priming))]+ )+ let span = try XCTUnwrap(manifest.track(track.id)?.spans.first)+ return (plan, manifest, span)+ }++ private func receipts(+ for manifest: MeetingAnalysisManifest,+ status: MeetingSpanCoverageStatus = .processed+ ) -> [MeetingSpanCoverageReceipt] {+ manifest.allSpans.enumerated().map { index, span in+ MeetingSpanCoverageReceipt(+ id: "receipt-\(index)",+ spanID: span.id,+ analysisStart: span.analysisInterval.start,+ analysisEnd: span.analysisInterval.end,+ status: status+ )+ }+ }++ private func unit(+ id: String,+ span: MeetingAnalysisSpan,+ text: String = "word",+ analysisStart: TimeInterval? = nil,+ analysisEnd: TimeInterval? = nil,+ epoch: MeetingAnalysisEpochID? = nil,+ speaker: MeetingBackendSpeakerAssignment? = nil,+ spanIDs: [String]? = nil,+ confidence: Double? = nil+ ) -> MeetingFinalTextUnit {+ let resolvedEpoch = epoch ?? span.analysisEpochID+ return MeetingFinalTextUnit(+ id: id,+ trackID: span.trackID,+ analysisEpochID: resolvedEpoch,+ precision: .word,+ text: text,+ analysisStart: analysisStart ?? span.analysisInterval.start,+ analysisEnd: analysisEnd ?? span.analysisInterval.end,+ speaker: speaker ?? .assigned(+ MeetingBackendSpeakerToken(analysisEpochID: resolvedEpoch, label: "slot-0")+ ),+ analysisSpanIDs: spanIDs ?? [span.id],+ confidence: confidence+ )+ }++ private func evidence(+ plan: MeetingBackendPlan,+ units: [MeetingFinalTextUnit],+ activity: [MeetingBackendSpeakerActivity] = []+ ) -> MeetingFinalTranscriptEvidence {+ MeetingFinalTranscriptEvidence(+ backendID: plan.backendID,+ attemptID: plan.attemptID,+ units: units,+ speakerActivity: activity+ )+ }++ private func dispositions(+ _ result: MeetingAssemblyResult+ ) -> [String: MeetingTextUnitDispositionRecord] {+ Dictionary(+ result.sidecar.dispositions.map { ($0.unitID, $0) },+ uniquingKeysWith: { first, _ in first }+ )+ }++ // MARK: - Deterministic identity++ func testDeterministicIDsAndSpeakerIsolationAcrossTracksAndAttempts() throws {+ let micChunk = self.chunk(sequence: 0, start: 100, end: 110)+ let appChunk = self.chunk(sequence: 0, start: 100, end: 110)+ let mic = self.track(+ kind: .microphone,+ chunks: [micChunk],+ eras: [self.era(protection: .voiceProcessed, start: 100)]+ )+ let app = self.track(kind: .applicationAudio, chunks: [appChunk])+ let plan = self.plan(mode: .onlineCall, tracks: [mic, app])+ let manifest = try self.buildManifest(plan: plan, observations: [+ (mic.id, micChunk, self.observed(micChunk, duration: 10)),+ (app.id, appChunk, self.observed(appChunk, duration: 10)),+ ])+ let micSpan = try XCTUnwrap(manifest.track(mic.id)?.spans.first)+ let appSpan = try XCTUnwrap(manifest.track(app.id)?.spans.first)++ // The same backend label on two tracks: the product speakers must never merge.+ let units = [+ self.unit(id: "m-0", span: micSpan, text: "mine", analysisStart: 1, analysisEnd: 2),+ self.unit(id: "a-0", span: appSpan, text: "remote", analysisStart: 1, analysisEnd: 2),+ ]+ let input = MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: units),+ coverageReceipts: self.receipts(for: manifest),+ echoVerdicts: ["m-0": .notEcho]+ )+ let first = try MeetingTranscriptAssembler().assemble(input)+ let second = try MeetingTranscriptAssembler().assemble(input)+ XCTAssertEqual(first, second)++ XCTAssertEqual(first.speakers.count, 2)+ XCTAssertEqual(Set(first.speakers.map(\.id)).count, 2)+ XCTAssertTrue(first.speakers.allSatisfy { !$0.isLocalUser && $0.identityCandidates.isEmpty })+ XCTAssertEqual(Set(first.speakers.map(\.trackKind)), [.microphone, .applicationAudio])++ let micSegment = try XCTUnwrap(first.segments.first { $0.sourceTrackID == mic.id })+ let appSegment = try XCTUnwrap(first.segments.first { $0.sourceTrackID == app.id })+ XCTAssertNotEqual(micSegment.speakerID, appSegment.speakerID)+ XCTAssertNotNil(micSegment.speakerID)+ XCTAssertNotNil(appSegment.speakerID)+ XCTAssertEqual(micSegment.start.seconds, 1, accuracy: 1e-3)+ XCTAssertEqual(micSegment.end.seconds, 2, accuracy: 1e-3)+ }++ func testSameLabelAcrossEpochsNeverMerges() throws {+ let first = self.chunk(sequence: 0, start: 100, end: 105)+ let second = self.chunk(+ sequence: 1,+ start: 105,+ end: 110,+ discontinuities: [MeetingAudioDiscontinuity(+ kind: .microphoneDisconnected,+ presentationTime: self.mediaTime(105),+ gapSeconds: 0,+ detail: "fixture"+ )]+ )+ let mic = self.track(+ kind: .microphone,+ chunks: [first, second],+ eras: [self.era(protection: .voiceProcessed, start: 100)]+ )+ let plan = self.plan(mode: .onlineCall, tracks: [mic])+ let manifest = try self.buildManifest(plan: plan, observations: [+ (mic.id, first, self.observed(first, duration: 5)),+ (mic.id, second, self.observed(second, duration: 5)),+ ])+ let spans = try XCTUnwrap(manifest.track(mic.id)?.spans)+ XCTAssertEqual(spans.count, 2)+ XCTAssertNotEqual(spans[0].analysisEpochID, spans[1].analysisEpochID)++ let units = [+ self.unit(id: "u-0", span: spans[0], analysisStart: 1, analysisEnd: 2),+ self.unit(id: "u-1", span: spans[1], analysisStart: 6, analysisEnd: 7),+ ]+ let result = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: units),+ coverageReceipts: self.receipts(for: manifest),+ echoVerdicts: ["u-0": .notEcho, "u-1": .notEcho]+ ))+ // Same label, same track, different epochs: two speakers, never one.+ XCTAssertEqual(result.speakers.count, 2)+ XCTAssertNotEqual(result.speakers[0].id, result.speakers[1].id)+ XCTAssertEqual(Set(result.speakers.compactMap(\.diarizationClusterID)).count, 2)+ XCTAssertEqual(Set(result.segments.compactMap(\.speakerID)).count, 2)+ }++ // MARK: - Mapping++ func testAnalysisIntervalMapsThroughSpansExactlyOnceIncludingDrift() throws {+ // An eligible VPIO drift fit: factor 1.00006. The segment must carry exactly one+ // application of that rate — the manifest's transform — never a second correction.+ let drift = MeetingClockDriftRecord(+ cumulativeAbsorbedSeconds: 0.006,+ elapsedValidHostSeconds: 100,+ eligible: true+ )+ let (plan, manifest, span) = try self.onlineMicFixture(drift: drift)+ guard case .appliedOnce = span.timing.deDrift else {+ return XCTFail("fixture must exercise a real de-drift application")+ }+ let transform = span.presentationMapping+ XCTAssertNotEqual(transform.rateRatio, 1)++ let unit = self.unit(id: "u-0", span: span, analysisStart: 1, analysisEnd: 2)+ let result = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: [unit]),+ coverageReceipts: self.receipts(for: manifest),+ echoVerdicts: ["u-0": .notEcho]+ ))+ let segment = try XCTUnwrap(result.segments.first)+ let expectedStart = transform.presentationTime(forAnalysisTime: 1)+ let expectedEnd = transform.presentationTime(forAnalysisTime: 2)+ XCTAssertEqual(segment.start.seconds, expectedStart, accuracy: 1e-3)+ XCTAssertEqual(segment.end.seconds, expectedEnd, accuracy: 1e-3)+ XCTAssertEqual(self.dispositions(result)[unit.id]?.disposition, .emitted)+ }++ func testCrossSpanUnitMapsOnceAcrossChunkBoundary() throws {+ let first = self.chunk(sequence: 0, start: 100, end: 105)+ let second = self.chunk(sequence: 1, start: 105, end: 110)+ let mic = self.track(+ kind: .microphone,+ chunks: [first, second],+ eras: [self.era(protection: .voiceProcessed, start: 100)]+ )+ let plan = self.plan(mode: .onlineCall, tracks: [mic])+ let manifest = try self.buildManifest(plan: plan, observations: [+ (mic.id, first, self.observed(first, duration: 5)),+ (mic.id, second, self.observed(second, duration: 5)),+ ])+ let spans = try XCTUnwrap(manifest.track(mic.id)?.spans)+ XCTAssertEqual(spans.count, 2)++ let unit = self.unit(+ id: "u-0",+ span: spans[0],+ analysisStart: 4.5,+ analysisEnd: 5.5,+ spanIDs: spans.map(\.id)+ )+ let result = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: [unit]),+ coverageReceipts: self.receipts(for: manifest),+ echoVerdicts: ["u-0": .notEcho]+ ))+ let segment = try XCTUnwrap(result.segments.first)+ // Start maps through the first span's transform, end through the last's — once each.+ let expectedStart = spans[0].presentationMapping.presentationTime(forAnalysisTime: 4.5)+ let expectedEnd = spans[1].presentationMapping.presentationTime(forAnalysisTime: 5.5)+ XCTAssertEqual(segment.start.seconds, expectedStart, accuracy: 1e-3)+ XCTAssertEqual(segment.end.seconds, expectedEnd, accuracy: 1e-3)+ XCTAssertEqual(self.dispositions(result)[unit.id]?.disposition, .emitted)+ }++ // MARK: - Quarantine++ func testInvalidTimingAndBrokenSpanProvenanceQuarantineUnits() throws {+ let chunks = (0..<3).map { self.chunk(sequence: $0, start: 100 + 2 * Double($0), end: 102 + 2 * Double($0)) }+ let mic = self.track(+ kind: .microphone,+ chunks: chunks,+ eras: [self.era(protection: .voiceProcessed, start: 100)]+ )+ let plan = self.plan(mode: .onlineCall, tracks: [mic])+ let manifest = try self.buildManifest(+ plan: plan,+ observations: chunks.map { (mic.id, $0, self.observed($0, duration: 2)) }+ )+ let spans = try XCTUnwrap(manifest.track(mic.id)?.spans)+ XCTAssertEqual(spans.count, 3)++ let units = [+ self.unit(id: "bad-time", span: spans[0], analysisStart: 2, analysisEnd: 2),+ self.unit(+ id: "skip-span",+ span: spans[0],+ analysisStart: 0.5,+ analysisEnd: 5.5,+ spanIDs: [spans[0].id, spans[2].id]+ ),+ self.unit(id: "out-of-bounds", span: spans[2], analysisStart: 5.5, analysisEnd: 6.5),+ self.unit(id: "bad-confidence", span: spans[1], confidence: 2),+ ]+ let result = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: units),+ coverageReceipts: self.receipts(for: manifest),+ echoVerdicts: [:]+ ))+ let ledger = self.dispositions(result)+ XCTAssertEqual(+ ledger["bad-time"]?.reasonCode,+ MeetingUnitQuarantineReason.invalidTiming.rawValue+ )+ XCTAssertEqual(+ ledger["skip-span"]?.reasonCode,+ MeetingUnitQuarantineReason.spansNotContiguousWithinEpoch.rawValue+ )+ XCTAssertEqual(+ ledger["out-of-bounds"]?.reasonCode,+ MeetingUnitQuarantineReason.spansDoNotCoverUnitInterval.rawValue+ )+ XCTAssertEqual(+ ledger["bad-confidence"]?.reasonCode,+ MeetingUnitQuarantineReason.invalidConfidence.rawValue+ )+ XCTAssertTrue(ledger.values.allSatisfy { $0.disposition == .rejectedInvalidTiming })+ // Quarantined units never reach segments, and quarantine needs no echo verdicts.+ XCTAssertTrue(result.segments.isEmpty)+ XCTAssertNoThrow(try result.sidecar.validated())+ }++ func testUnitWhoseSpansBelongToAnotherEpochIsQuarantined() throws {+ let first = self.chunk(sequence: 0, start: 100, end: 105)+ let second = self.chunk(+ sequence: 1,+ start: 105,+ end: 110,+ discontinuities: [MeetingAudioDiscontinuity(+ kind: .clockDiscontinuity,+ presentationTime: self.mediaTime(105),+ gapSeconds: nil,+ detail: "fixture"+ )]+ )+ let mic = self.track(+ kind: .microphone,+ chunks: [first, second],+ eras: [self.era(protection: .voiceProcessed, start: 100)]+ )+ let plan = self.plan(mode: .onlineCall, tracks: [mic])+ let manifest = try self.buildManifest(plan: plan, observations: [+ (mic.id, first, self.observed(first, duration: 5)),+ (mic.id, second, self.observed(second, duration: 5)),+ ])+ let spans = try XCTUnwrap(manifest.track(mic.id)?.spans)+ XCTAssertEqual(spans.count, 2)++ // Declares epoch 0, points at an epoch-1 span: provenance the assembler cannot honor.+ let unit = self.unit(+ id: "epoch-mismatch",+ span: spans[1],+ analysisStart: 5.5,+ analysisEnd: 6.5,+ epoch: spans[0].analysisEpochID,+ spanIDs: [spans[1].id]+ )+ let result = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: [unit]),+ coverageReceipts: self.receipts(for: manifest)+ ))+ let record = try XCTUnwrap(self.dispositions(result)[unit.id])+ XCTAssertEqual(record.disposition, .rejectedInvalidTiming)+ XCTAssertEqual(record.reasonCode, MeetingUnitQuarantineReason.analysisEpochMismatch.rawValue)+ XCTAssertTrue(result.segments.isEmpty)+ }++ // MARK: - Ambiguity and activity++ func testAmbiguousUnitAppearsExactlyOnceUnassigned() throws {+ let (plan, manifest, span) = try self.onlineMicFixture()+ let unit = self.unit(+ id: "u-amb",+ span: span,+ text: "overlapped",+ analysisStart: 1,+ analysisEnd: 2,+ speaker: .ambiguous([+ MeetingBackendSpeakerToken(analysisEpochID: span.analysisEpochID, label: "slot-0"),+ MeetingBackendSpeakerToken(analysisEpochID: span.analysisEpochID, label: "slot-1"),+ ])+ )+ let result = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: [unit]),+ coverageReceipts: self.receipts(for: manifest),+ echoVerdicts: ["u-amb": .notEcho]+ ))+ XCTAssertEqual(self.dispositions(result)[unit.id]?.disposition, .ambiguousUnassigned)+ let matching = result.segments.filter { $0.text == "overlapped" }+ XCTAssertEqual(matching.count, 1)+ XCTAssertNil(matching[0].speakerID)+ XCTAssertEqual(matching[0].overlap, .ambiguous)+ // Ambiguity candidates are reported, never resolved into product speakers.+ XCTAssertTrue(result.speakers.isEmpty)+ }++ func testUncertainTimingIsAdmittedAsAmbiguous() throws {+ // Unknown codec priming leaves the span timing-uncertain: the text stays visible but is+ // never confidently assigned to a speaker.+ let (plan, manifest, span) = try self.onlineMicFixture(priming: .unknown(.decoderDidNotReport))+ XCTAssertEqual(span.timing.certainty, .timingUncertain)+ let unit = self.unit(id: "u-0", span: span, analysisStart: 1, analysisEnd: 2)+ let result = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: [unit]),+ coverageReceipts: self.receipts(for: manifest),+ echoVerdicts: ["u-0": .notEcho]+ ))+ let record = try XCTUnwrap(self.dispositions(result)[unit.id])+ XCTAssertEqual(record.disposition, .ambiguousUnassigned)+ XCTAssertEqual(record.reasonCode, "timingUncertain")+ let segment = try XCTUnwrap(result.segments.first)+ XCTAssertNil(segment.speakerID)+ XCTAssertEqual(segment.overlap, .ambiguous)+ XCTAssertTrue(result.speakers.isEmpty)+ }++ func testUnitOutsideSpeakerActivityIsExcluded() throws {+ let (plan, manifest, span) = try self.onlineMicFixture()+ let activity = [+ MeetingBackendSpeakerActivity(+ token: MeetingBackendSpeakerToken(analysisEpochID: span.analysisEpochID, label: "slot-0"),+ start: 0,+ end: 1+ ),+ ]+ let inside = self.unit(id: "u-in", span: span, text: "inside", analysisStart: 0.2, analysisEnd: 0.8)+ let outside = self.unit(id: "u-out", span: span, text: "outside", analysisStart: 2, analysisEnd: 3)+ let result = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: [inside, outside], activity: activity),+ coverageReceipts: self.receipts(for: manifest),+ echoVerdicts: ["u-in": .notEcho, "u-out": .notEcho]+ ))+ let ledger = self.dispositions(result)+ XCTAssertEqual(ledger[inside.id]?.disposition, .emitted)+ XCTAssertEqual(ledger[outside.id]?.disposition, .outsideActivity)+ XCTAssertEqual(result.segments.map(\.text), ["inside"])+ }++ func testSpeakerActivityMustStayInsideItsEpoch() throws {+ let (plan, manifest, span) = try self.onlineMicFixture()+ let unit = self.unit(id: "u-0", span: span, analysisStart: 1, analysisEnd: 2)+ let activity = MeetingBackendSpeakerActivity(+ token: MeetingBackendSpeakerToken(+ analysisEpochID: span.analysisEpochID,+ label: "slot-0"+ ),+ start: 9,+ end: 11+ )+ XCTAssertThrowsError(try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: [unit], activity: [activity]),+ coverageReceipts: self.receipts(for: manifest),+ echoVerdicts: [unit.id: .notEcho]+ ))) { error in+ XCTAssertEqual(+ error as? MeetingBackendEvidenceError,+ .activityOutsideEpoch(index: 0)+ )+ }+ }++ // MARK: - Echo++ func testOnlineMicrophoneWithoutEchoVerdictFailsAssembly() throws {+ let (plan, manifest, span) = try self.onlineMicFixture()+ let unit = self.unit(id: "u-0", span: span, analysisStart: 1, analysisEnd: 2)+ XCTAssertThrowsError(try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: [unit]),+ coverageReceipts: self.receipts(for: manifest)+ ))) { error in+ XCTAssertEqual(error as? MeetingAssemblyError, .missingEchoVerdict(unitID: "u-0"))+ }+ }++ func testEchoSuppressedMicrophoneIsLedgerOnlyAndApplicationCopyIsRetained() throws {+ let micChunk = self.chunk(sequence: 0, start: 100, end: 110)+ let appChunk = self.chunk(sequence: 0, start: 100, end: 110)+ let mic = self.track(+ kind: .microphone,+ chunks: [micChunk],+ eras: [self.era(protection: .voiceProcessed, start: 100)]+ )+ let app = self.track(kind: .applicationAudio, chunks: [appChunk])+ let plan = self.plan(mode: .onlineCall, tracks: [mic, app])+ let manifest = try self.buildManifest(plan: plan, observations: [+ (mic.id, micChunk, self.observed(micChunk, duration: 10)),+ (app.id, appChunk, self.observed(appChunk, duration: 10)),+ ])+ let micSpan = try XCTUnwrap(manifest.track(mic.id)?.spans.first)+ let appSpan = try XCTUnwrap(manifest.track(app.id)?.spans.first)++ let micUnit = self.unit(id: "m-echo", span: micSpan, text: "remote words", analysisStart: 1, analysisEnd: 2)+ let appUnit = self.unit(id: "a-0", span: appSpan, text: "remote words", analysisStart: 1, analysisEnd: 2)+ let result = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: [micUnit, appUnit]),+ coverageReceipts: self.receipts(for: manifest),+ // The application track is remote evidence and needs no verdict; the microphone copy+ // is suppressed by a real one.+ echoVerdicts: ["m-echo": .echoSuppressed(duplicateOfUnitID: "a-0")]+ ))+ let ledger = self.dispositions(result)+ XCTAssertEqual(ledger[micUnit.id]?.disposition, .echoSuppressed)+ XCTAssertEqual(ledger[appUnit.id]?.disposition, .emitted)+ XCTAssertEqual(result.segments.map(\.text), ["remote words"])+ XCTAssertEqual(result.segments[0].sourceTrackID, app.id)+ // Ledger-only still means ledger: the suppressed mic copy stays in the sidecar.+ XCTAssertTrue(result.sidecar.units.contains { $0.id == micUnit.id })+ XCTAssertEqual(result.speakers.count, 1)+ XCTAssertEqual(result.speakers[0].trackKind, .applicationAudio)+ }++ func testInRoomMicrophoneBypassesEchoAdmission() throws {+ let chunk = self.chunk(sequence: 0, start: 100, end: 110)+ let mic = self.track(+ kind: .microphone,+ chunks: [chunk],+ captureMethod: .avCaptureSession+ )+ let plan = self.plan(mode: .inRoom, tracks: [mic])+ let manifest = try self.buildManifest(+ plan: plan,+ observations: [(mic.id, chunk, self.observed(chunk, duration: 10))]+ )+ let span = try XCTUnwrap(manifest.track(mic.id)?.spans.first)+ let unit = self.unit(id: "u-0", span: span, analysisStart: 1, analysisEnd: 2)+ let result = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: [unit]),+ coverageReceipts: self.receipts(for: manifest)+ ))+ XCTAssertEqual(self.dispositions(result)[unit.id]?.disposition, .emitted)+ XCTAssertEqual(result.segments.count, 1)+ }++ func testEchoVerdictForUnknownUnitThrows() throws {+ let (plan, manifest, span) = try self.onlineMicFixture()+ let unit = self.unit(id: "u-0", span: span, analysisStart: 1, analysisEnd: 2)+ XCTAssertThrowsError(try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: [unit]),+ coverageReceipts: self.receipts(for: manifest),+ echoVerdicts: ["u-0": .notEcho, "ghost": .notEcho]+ ))) { error in+ XCTAssertEqual(error as? MeetingAssemblyError, .echoVerdictForUnknownUnit(unitID: "ghost"))+ }+ }++ // MARK: - Coverage++ func testExactReceiptTilingAndTruncationGap() throws {+ let (plan, manifest, span) = try self.onlineMicFixture()+ let unit = self.unit(id: "u-0", span: span, analysisStart: 1, analysisEnd: 2)+ let receipts = [+ MeetingSpanCoverageReceipt(+ id: "r-0", spanID: span.id, analysisStart: 0, analysisEnd: 4, status: .processed+ ),+ MeetingSpanCoverageReceipt(+ id: "r-1", spanID: span.id, analysisStart: 4, analysisEnd: 10,+ status: .providerTruncated+ ),+ ]+ let result = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: [unit]),+ coverageReceipts: receipts,+ echoVerdicts: ["u-0": .notEcho]+ ))+ XCTAssertFalse(result.isComplete)+ let gap = try XCTUnwrap(result.coverageGaps.first)+ XCTAssertEqual(gap.reason, .providerTruncated)+ XCTAssertEqual(gap.trackID, span.trackID)+ XCTAssertEqual(gap.start, 4, accuracy: 1e-3)+ XCTAssertEqual(gap.end, 10, accuracy: 1e-3)+ // Truncation is a coverage fact, not a text fact: the recognized unit is still emitted.+ XCTAssertEqual(self.dispositions(result)[unit.id]?.disposition, .emitted)+ }++ func testMissingReceiptFailsEvenWhenTextExists() throws {+ let (plan, manifest, span) = try self.onlineMicFixture()+ let unit = self.unit(id: "u-0", span: span, analysisStart: 1, analysisEnd: 2)+ // A span full of recognized text but no receipt: text never implies coverage.+ XCTAssertThrowsError(try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: [unit]),+ coverageReceipts: [],+ echoVerdicts: ["u-0": .notEcho]+ ))) { error in+ XCTAssertEqual(+ error as? MeetingAssemblyError, .missingCoverageReceipt(spanID: span.id)+ )+ }+ }++ func testDuplicateUnknownOutOfBoundsAndPartialReceiptsThrow() throws {+ let (plan, manifest, span) = try self.onlineMicFixture()+ let validReceipts = self.receipts(for: manifest)+ let baseEvidence = self.evidence(plan: plan, units: [])++ XCTAssertThrowsError(try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan, manifest: manifest, evidence: baseEvidence,+ coverageReceipts: validReceipts + [MeetingSpanCoverageReceipt(+ id: "receipt-0", spanID: span.id, analysisStart: 9, analysisEnd: 10, status: .processed+ )]+ ))) { error in+ XCTAssertEqual(error as? MeetingAssemblyError, .duplicateCoverageReceiptID("receipt-0"))+ }++ XCTAssertThrowsError(try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan, manifest: manifest, evidence: baseEvidence,+ coverageReceipts: [MeetingSpanCoverageReceipt(+ id: "r-x", spanID: "no-such-span", analysisStart: 0, analysisEnd: 1, status: .processed+ )]+ ))) { error in+ XCTAssertEqual(+ error as? MeetingAssemblyError, .unknownCoverageReceiptSpan(spanID: "no-such-span")+ )+ }++ XCTAssertThrowsError(try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan, manifest: manifest, evidence: baseEvidence,+ coverageReceipts: [MeetingSpanCoverageReceipt(+ id: "r-oob", spanID: span.id, analysisStart: 0, analysisEnd: 99, status: .processed+ )]+ ))) { error in+ XCTAssertEqual(+ error as? MeetingAssemblyError, .coverageReceiptOutOfBounds(receiptID: "r-oob")+ )+ }++ XCTAssertThrowsError(try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan, manifest: manifest, evidence: baseEvidence,+ coverageReceipts: [+ MeetingSpanCoverageReceipt(+ id: "r-0", spanID: span.id, analysisStart: 0, analysisEnd: 6, status: .processed+ ),+ MeetingSpanCoverageReceipt(+ id: "r-1", spanID: span.id, analysisStart: 5, analysisEnd: 10, status: .processed+ ),+ ]+ ))) { error in+ XCTAssertEqual(+ error as? MeetingAssemblyError, .overlappingCoverageReceipts(spanID: span.id)+ )+ }++ XCTAssertThrowsError(try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan, manifest: manifest, evidence: baseEvidence,+ coverageReceipts: [MeetingSpanCoverageReceipt(+ id: "r-partial", spanID: span.id, analysisStart: 0, analysisEnd: 5, status: .processed+ )]+ ))) { error in+ XCTAssertEqual(+ error as? MeetingAssemblyError, .missingCoverageReceipt(spanID: span.id)+ )+ }++ XCTAssertThrowsError(try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan, manifest: manifest, evidence: baseEvidence,+ coverageReceipts: [MeetingSpanCoverageReceipt(+ id: "r-flat", spanID: span.id, analysisStart: 5, analysisEnd: 5, status: .processed+ )]+ ))) { error in+ XCTAssertEqual(+ error as? MeetingAssemblyError, .invalidCoverageReceiptInterval(receiptID: "r-flat")+ )+ }+ }++ func testFailedAndSkippedReceiptsSurfaceAsGapsAndSkippedChunks() throws {+ let first = self.chunk(sequence: 0, start: 100, end: 105)+ let second = self.chunk(sequence: 1, start: 105, end: 110)+ let mic = self.track(+ kind: .microphone,+ chunks: [first, second],+ eras: [self.era(protection: .voiceProcessed, start: 100)]+ )+ let plan = self.plan(mode: .onlineCall, tracks: [mic])+ let manifest = try self.buildManifest(plan: plan, observations: [+ (mic.id, first, self.observed(first, duration: 5)),+ (mic.id, second, self.observed(second, duration: 5)),+ ])+ let spans = try XCTUnwrap(manifest.track(mic.id)?.spans)+ let receipts = [+ MeetingSpanCoverageReceipt(+ id: "r-0", spanID: spans[0].id, analysisStart: 0, analysisEnd: 5, status: .failed+ ),+ MeetingSpanCoverageReceipt(+ id: "r-1", spanID: spans[1].id, analysisStart: 5, analysisEnd: 10, status: .skipped+ ),+ ]+ let result = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: []),+ coverageReceipts: receipts+ ))+ XCTAssertFalse(result.isComplete)+ XCTAssertEqual(result.coverageGaps.map(\.reason), [.processingFailed, .skipped])+ XCTAssertEqual(+ result.skippedChunks,+ [MeetingAnalysisChunkIdentity(trackID: mic.id, chunk: second)]+ )+ XCTAssertTrue(result.segments.isEmpty)+ }++ func testTextCannotEmitFromFailedOrTruncatedReceiptRegion() throws {+ let (plan, manifest, span) = try self.onlineMicFixture()+ let failedUnit = self.unit(+ id: "failed-text", span: span, analysisStart: 1, analysisEnd: 2+ )+ XCTAssertThrowsError(try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: [failedUnit]),+ coverageReceipts: [MeetingSpanCoverageReceipt(+ id: "failed-receipt",+ spanID: span.id,+ analysisStart: 0,+ analysisEnd: 10,+ status: .failed+ )],+ echoVerdicts: [failedUnit.id: .notEcho]+ ))) { error in+ XCTAssertEqual(+ error as? MeetingAssemblyError,+ .textContradictsCoverage(+ unitID: failedUnit.id,+ receiptID: "failed-receipt",+ status: .failed+ )+ )+ }++ let truncatedUnit = self.unit(+ id: "truncated-text", span: span, analysisStart: 5, analysisEnd: 6+ )+ XCTAssertThrowsError(try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: [truncatedUnit]),+ coverageReceipts: [+ MeetingSpanCoverageReceipt(+ id: "processed-prefix",+ spanID: span.id,+ analysisStart: 0,+ analysisEnd: 4,+ status: .processed+ ),+ MeetingSpanCoverageReceipt(+ id: "truncated-tail",+ spanID: span.id,+ analysisStart: 4,+ analysisEnd: 10,+ status: .providerTruncated+ ),+ ],+ echoVerdicts: [truncatedUnit.id: .notEcho]+ ))) { error in+ XCTAssertEqual(+ error as? MeetingAssemblyError,+ .textContradictsCoverage(+ unitID: truncatedUnit.id,+ receiptID: "truncated-tail",+ status: .providerTruncated+ )+ )+ }+ }++ func testManifestGapsSurfaceAsProductCoverageGaps() throws {+ let chunk = self.chunk(sequence: 0, start: 100, end: 110)+ let mic = self.track(+ kind: .microphone,+ chunks: [chunk],+ eras: [+ self.era(protection: .voiceProcessed, start: 100),+ self.era(protection: .unprotected, start: 105),+ self.era(protection: .softwareEchoCancelled, start: 108),+ ]+ )+ let plan = self.plan(mode: .onlineCall, tracks: [mic])+ let manifest = try self.buildManifest(+ plan: plan,+ observations: [(mic.id, chunk, self.observed(chunk, duration: 10))]+ )+ let spans = try XCTUnwrap(manifest.track(mic.id)?.spans)+ let units = spans.enumerated().map { index, span in+ self.unit(id: "u-\(index)", span: span)+ }+ let result = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: units),+ coverageReceipts: self.receipts(for: manifest),+ echoVerdicts: Dictionary(uniqueKeysWithValues: units.map { ($0.id, MeetingUnitEchoVerdict.notEcho) })+ ))+ XCTAssertFalse(result.isComplete)+ let inadmissible = try XCTUnwrap(result.coverageGaps.first { $0.reason == .inadmissibleCaptureEra })+ XCTAssertEqual(inadmissible.start, 5, accuracy: 1e-3)+ XCTAssertEqual(inadmissible.end, 8, accuracy: 1e-3)+ // The unprotected era was never analyzed, so both admissible pieces' text is emitted.+ XCTAssertEqual(Set(result.segments.map(\.text)), Set(units.map(\.text)))+ }++ // MARK: - Conservation++ func testEveryInputUnitHasExactlyOneDispositionAndExcludedUnitsNeverAppear() throws {+ let micChunk = self.chunk(sequence: 0, start: 100, end: 110)+ let appChunk = self.chunk(sequence: 0, start: 100, end: 110)+ let mic = self.track(+ kind: .microphone,+ chunks: [micChunk],+ eras: [self.era(protection: .voiceProcessed, start: 100)]+ )+ let app = self.track(kind: .applicationAudio, chunks: [appChunk])+ let plan = self.plan(mode: .onlineCall, tracks: [mic, app])+ let manifest = try self.buildManifest(plan: plan, observations: [+ (mic.id, micChunk, self.observed(micChunk, duration: 10)),+ (app.id, appChunk, self.observed(appChunk, duration: 10)),+ ])+ let micSpan = try XCTUnwrap(manifest.track(mic.id)?.spans.first)+ let appSpan = try XCTUnwrap(manifest.track(app.id)?.spans.first)+ let activity = [+ MeetingBackendSpeakerActivity(+ token: MeetingBackendSpeakerToken(analysisEpochID: micSpan.analysisEpochID, label: "slot-0"),+ start: 0,+ end: 5+ ),+ ]++ let units = [+ self.unit(id: "emitted", span: micSpan, text: "kept", analysisStart: 1, analysisEnd: 2),+ self.unit(+ id: "ambiguous", span: micSpan, text: "fuzzy", analysisStart: 1.5, analysisEnd: 2.5,+ speaker: .ambiguous([+ MeetingBackendSpeakerToken(analysisEpochID: micSpan.analysisEpochID, label: "slot-0"),+ MeetingBackendSpeakerToken(analysisEpochID: micSpan.analysisEpochID, label: "slot-1"),+ ])+ ),+ self.unit(id: "quarantined", span: micSpan, text: "broken", analysisStart: 3, analysisEnd: 3),+ self.unit(id: "echo", span: micSpan, text: "copy", analysisStart: 2, analysisEnd: 3),+ self.unit(id: "inactive", span: micSpan, text: "idle", analysisStart: 7, analysisEnd: 8),+ self.unit(id: "remote", span: appSpan, text: "remote", analysisStart: 1, analysisEnd: 2),+ ]+ let result = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: units, activity: activity),+ coverageReceipts: self.receipts(for: manifest),+ echoVerdicts: [+ "emitted": .notEcho,+ "ambiguous": .notEcho,+ "echo": .echoSuppressed(duplicateOfUnitID: "remote"),+ "inactive": .notEcho,+ ]+ ))++ let ledger = self.dispositions(result)+ XCTAssertEqual(Set(ledger.keys), Set(units.map(\.id)))+ XCTAssertEqual(result.sidecar.dispositions.count, units.count)+ XCTAssertEqual(ledger["emitted"]?.disposition, .emitted)+ XCTAssertEqual(ledger["ambiguous"]?.disposition, .ambiguousUnassigned)+ XCTAssertEqual(ledger["quarantined"]?.disposition, .rejectedInvalidTiming)+ XCTAssertEqual(ledger["echo"]?.disposition, .echoSuppressed)+ XCTAssertEqual(ledger["inactive"]?.disposition, .outsideActivity)+ XCTAssertEqual(ledger["remote"]?.disposition, .emitted)+ XCTAssertNoThrow(try result.sidecar.validated())++ // Admitted text renders once each; excluded text never renders at all.+ XCTAssertEqual(+ result.segments.map(\.text).sorted(),+ ["fuzzy", "kept", "remote"]+ )+ XCTAssertEqual(+ Set(result.sidecar.units.map(\.id)),+ Set(units.map(\.id))+ )+ }++ func testExtraReferencedSpanIsQuarantinedAndCannotReportComplete() throws {+ let first = self.chunk(sequence: 0, start: 100, end: 105)+ let second = self.chunk(sequence: 1, start: 105, end: 110)+ let mic = self.track(+ kind: .microphone,+ chunks: [first, second],+ eras: [self.era(protection: .voiceProcessed, start: 100)]+ )+ let plan = self.plan(mode: .onlineCall, tracks: [mic])+ let manifest = try self.buildManifest(plan: plan, observations: [+ (mic.id, first, self.observed(first, duration: 5)),+ (mic.id, second, self.observed(second, duration: 5)),+ ])+ let spans = try XCTUnwrap(manifest.track(mic.id)?.spans)+ let unit = self.unit(+ id: "extra-span",+ span: spans[1],+ analysisStart: 5.2,+ analysisEnd: 5.8,+ spanIDs: spans.map(\.id)+ )+ let result = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: [unit]),+ coverageReceipts: self.receipts(for: manifest)+ ))+ XCTAssertEqual(+ self.dispositions(result)[unit.id]?.reasonCode,+ MeetingUnitQuarantineReason.spansDoNotCoverUnitInterval.rawValue+ )+ XCTAssertTrue(result.segments.isEmpty)+ XCTAssertFalse(result.isComplete)+ }++ func testEchoDuplicateTargetMustExistAndBeApplicationAudio() throws {+ let (plan, manifest, span) = try self.onlineMicFixture()+ let first = self.unit(id: "mic-0", span: span, analysisStart: 1, analysisEnd: 2)+ let second = self.unit(id: "mic-1", span: span, analysisStart: 2, analysisEnd: 3)+ let evidence = self.evidence(plan: plan, units: [first, second])++ XCTAssertThrowsError(try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: evidence,+ coverageReceipts: self.receipts(for: manifest),+ echoVerdicts: [+ first.id: .echoSuppressed(duplicateOfUnitID: "missing"),+ second.id: .notEcho,+ ]+ ))) { error in+ XCTAssertEqual(+ error as? MeetingAssemblyError,+ .echoDuplicateTargetUnknown(unitID: first.id, duplicateID: "missing")+ )+ }++ XCTAssertThrowsError(try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: evidence,+ coverageReceipts: self.receipts(for: manifest),+ echoVerdicts: [+ first.id: .echoSuppressed(duplicateOfUnitID: second.id),+ second.id: .notEcho,+ ]+ ))) { error in+ XCTAssertEqual(+ error as? MeetingAssemblyError,+ .echoDuplicateTargetNotApplicationAudio(unitID: first.id, duplicateID: second.id)+ )+ }+ }++ func testEchoDuplicateTargetMustRemainVisible() throws {+ let micChunk = self.chunk(sequence: 0, start: 100, end: 110)+ let appChunk = self.chunk(sequence: 0, start: 100, end: 110)+ let mic = self.track(+ kind: .microphone,+ chunks: [micChunk],+ eras: [self.era(protection: .voiceProcessed, start: 100)]+ )+ let app = self.track(kind: .applicationAudio, chunks: [appChunk])+ let plan = self.plan(mode: .onlineCall, tracks: [mic, app])+ let manifest = try self.buildManifest(plan: plan, observations: [+ (mic.id, micChunk, self.observed(micChunk, duration: 10)),+ (app.id, appChunk, self.observed(appChunk, duration: 10)),+ ])+ let micSpan = try XCTUnwrap(manifest.track(mic.id)?.spans.first)+ let appSpan = try XCTUnwrap(manifest.track(app.id)?.spans.first)+ let micUnit = self.unit(id: "mic", span: micSpan, analysisStart: 1, analysisEnd: 2)+ let invalidApp = self.unit(+ id: "app-invalid",+ span: appSpan,+ analysisStart: 1,+ analysisEnd: 1+ )++ XCTAssertThrowsError(try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: [micUnit, invalidApp]),+ coverageReceipts: self.receipts(for: manifest),+ echoVerdicts: [+ micUnit.id: .echoSuppressed(duplicateOfUnitID: invalidApp.id),+ ]+ ))) { error in+ XCTAssertEqual(+ error as? MeetingAssemblyError,+ .echoDuplicateTargetNotVisible(unitID: micUnit.id, duplicateID: invalidApp.id)+ )+ }+ }++ func testEpochGenerationChangesProductSpeakerIdentityWithoutChangingOrdinal() throws {+ let chunk = self.chunk(sequence: 0, start: 100, end: 110)+ let mic = self.track(+ kind: .microphone,+ chunks: [chunk],+ eras: [self.era(protection: .voiceProcessed, start: 100)]+ )+ let plan = self.plan(mode: .onlineCall, tracks: [mic])+ let observations = [(mic.id, chunk, self.observed(chunk, duration: 10))]+ let firstManifest = try self.buildManifest(plan: plan, observations: observations)+ let key = MeetingAnalysisEpochGenerationKey(trackID: mic.id, ordinal: 0)+ let secondManifest = try MeetingAnalysisManifestBuilder(+ plan: plan,+ observer: AssemblerFixtureObserver(results: [+ MeetingAnalysisChunkKey(trackID: mic.id, chunkID: chunk.id):+ self.observed(chunk, duration: 10),+ ]),+ epochGenerations: [key: 1]+ ).build()+ let firstSpan = try XCTUnwrap(firstManifest.track(mic.id)?.spans.first)+ let secondSpan = try XCTUnwrap(secondManifest.track(mic.id)?.spans.first)+ XCTAssertEqual(firstSpan.analysisEpochID.ordinal, secondSpan.analysisEpochID.ordinal)+ XCTAssertNotEqual(firstSpan.analysisEpochID.generation, secondSpan.analysisEpochID.generation)++ func speakerID(+ manifest: MeetingAnalysisManifest,+ span: MeetingAnalysisSpan+ ) throws -> UUID {+ let unit = self.unit(id: "same-unit", span: span, analysisStart: 1, analysisEnd: 2)+ let result = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: [unit]),+ coverageReceipts: self.receipts(for: manifest),+ echoVerdicts: [unit.id: .notEcho]+ ))+ return try XCTUnwrap(result.speakers.first?.id)+ }+ XCTAssertNotEqual(+ try speakerID(manifest: firstManifest, span: firstSpan),+ try speakerID(manifest: secondManifest, span: secondSpan)+ )+ }++ func testSidecarOrderingIsCanonicalAcrossBackendOrdering() throws {+ let (plan, manifest, span) = try self.onlineMicFixture()+ let a = self.unit(id: "a", span: span, analysisStart: 1, analysisEnd: 2)+ let z = self.unit(id: "z", span: span, analysisStart: 3, analysisEnd: 4)+ let receipts = [+ MeetingSpanCoverageReceipt(+ id: "z-receipt",+ spanID: span.id,+ analysisStart: 5,+ analysisEnd: 10,+ status: .processed+ ),+ MeetingSpanCoverageReceipt(+ id: "a-receipt",+ spanID: span.id,+ analysisStart: 0,+ analysisEnd: 5,+ status: .processed+ ),+ ]+ let result = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: [z, a]),+ coverageReceipts: receipts,+ echoVerdicts: [a.id: .notEcho, z.id: .notEcho]+ ))+ XCTAssertEqual(result.sidecar.units.map(\.id), ["a", "z"])+ XCTAssertEqual(result.sidecar.dispositions.map(\.unitID), ["a", "z"])+ XCTAssertEqual(result.sidecar.coverageReceipts.map(\.id), ["a-receipt", "z-receipt"])+ }++ func testUnpositionedManifestGapCannotReportComplete() throws {+ let chunk = self.chunk(sequence: 0, start: 100, end: 100)+ let mic = self.track(kind: .microphone, chunks: [chunk], captureMethod: .avCaptureSession)+ let plan = self.plan(mode: .inRoom, tracks: [mic])+ let manifest = try self.buildManifest(plan: plan, observations: [])+ XCTAssertEqual(manifest.allGaps.count, 1)+ XCTAssertNil(manifest.allGaps[0].recordedInterval)++ let result = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(+ plan: plan,+ manifest: manifest,+ evidence: self.evidence(plan: plan, units: []),+ coverageReceipts: []+ ))+ XCTAssertTrue(result.coverageGaps.isEmpty)+ XCTAssertFalse(result.isComplete)+ }+}diff --git a/Tests/FluidDictationIntegrationTests/MeetingTranscriptionBackendTests.swift b/Tests/FluidDictationIntegrationTests/MeetingTranscriptionBackendTests.swiftnew file mode 100644index 00000000..f2dc411d--- /dev/null+++ b/Tests/FluidDictationIntegrationTests/MeetingTranscriptionBackendTests.swift@@ -0,0 +1,1138 @@+@testable import FluidVoice_Debug+import Foundation+import XCTest++/// Milestone A of `MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md`: the backend contract, the+/// injectable registry, evidence validation, and proof that `MeetingProcessingPipeline.process`+/// really dispatches through a selected backend.+///+/// The dispatch tests deliberately fail the `asrServiceProvider` closure: a fixture backend must be+/// reached without any ASR model readiness work, which is what makes "selection happens before+/// expensive model loading" a checked property rather than a claim.+@MainActor+final class MeetingTranscriptionBackendTests: XCTestCase {+ // MARK: - Fixture backend++ private final class FixtureMeetingBackend: MeetingTranscriptionBackend {+ let descriptor: MeetingBackendDescriptor+ private let makeOutcome: @MainActor (MeetingBackendPlan) -> MeetingBackendOutcome+ /// Lets a test hand back a plan that contradicts the request it was given.+ private let planOverride: (@MainActor (MeetingBackendRequest) -> MeetingBackendPlan)?+ private(set) var planCallCount = 0+ private(set) var executeCallCount = 0+ private(set) var lastPlan: MeetingBackendPlan?+ private(set) var receivedManifest: MeetingAnalysisManifest??+ private(set) var observedStages: [MeetingProcessingStage] = []++ init(+ descriptor: MeetingBackendDescriptor,+ planOverride: (@MainActor (MeetingBackendRequest) -> MeetingBackendPlan)? = nil,+ makeOutcome: @escaping @MainActor (MeetingBackendPlan) -> MeetingBackendOutcome+ ) {+ self.descriptor = descriptor+ self.planOverride = planOverride+ self.makeOutcome = makeOutcome+ }++ func plan(_ request: MeetingBackendRequest) throws -> MeetingBackendPlan {+ self.planCallCount += 1+ let plan = self.planOverride?(request)+ ?? MeetingBackendPlan(request: request, descriptor: self.descriptor)+ self.lastPlan = plan+ return plan+ }++ func execute(+ plan: MeetingBackendPlan,+ manifest: MeetingAnalysisManifest?,+ progress: @escaping @MainActor (MeetingProcessingStage) -> Void+ ) async throws -> MeetingBackendOutcome {+ self.executeCallCount += 1+ self.receivedManifest = manifest+ progress(.transcribing)+ self.observedStages.append(.transcribing)+ return self.makeOutcome(plan)+ }+ }++ /// Calls the host's legacy executor with whatever request a test wants, to prove the host+ /// refuses anything but the exact request it froze.+ private final class LegacyCallbackBackend: MeetingTranscriptionBackend {+ let descriptor: MeetingBackendDescriptor+ private let executor: MeetingLegacyBackendExecutor+ private let rewriteRequest: @MainActor (MeetingBackendRequest) -> MeetingBackendRequest++ init(+ descriptor: MeetingBackendDescriptor,+ executor: @escaping MeetingLegacyBackendExecutor,+ rewriteRequest: @escaping @MainActor (MeetingBackendRequest) -> MeetingBackendRequest+ ) {+ self.descriptor = descriptor+ self.executor = executor+ self.rewriteRequest = rewriteRequest+ }++ func plan(_ request: MeetingBackendRequest) throws -> MeetingBackendPlan {+ MeetingBackendPlan(request: request, descriptor: self.descriptor)+ }++ func execute(+ plan: MeetingBackendPlan,+ manifest: MeetingAnalysisManifest?,+ progress: @escaping @MainActor (MeetingProcessingStage) -> Void+ ) async throws -> MeetingBackendOutcome {+ try .legacyCompatibility(await self.executor(self.rewriteRequest(plan.request), progress))+ }+ }++ /// Parks inside `execute` on a latch that ignores cancellation, then returns successfully —+ /// a backend that does not cooperate with `Task` cancellation.+ private final class BlockingFixtureBackend: MeetingTranscriptionBackend {+ let descriptor: MeetingBackendDescriptor+ private let latch: Latch+ private let onEnter: @MainActor () -> Void+ private let makeOutcome: @MainActor (MeetingBackendPlan) -> MeetingBackendOutcome+ private(set) var executeCallCount = 0+ private(set) var didProduceOutcome = false++ init(+ descriptor: MeetingBackendDescriptor,+ latch: Latch,+ onEnter: @escaping @MainActor () -> Void,+ makeOutcome: @escaping @MainActor (MeetingBackendPlan) -> MeetingBackendOutcome+ ) {+ self.descriptor = descriptor+ self.latch = latch+ self.onEnter = onEnter+ self.makeOutcome = makeOutcome+ }++ func plan(_ request: MeetingBackendRequest) throws -> MeetingBackendPlan {+ MeetingBackendPlan(request: request, descriptor: self.descriptor)+ }++ func execute(+ plan: MeetingBackendPlan,+ manifest: MeetingAnalysisManifest?,+ progress: @escaping @MainActor (MeetingProcessingStage) -> Void+ ) async throws -> MeetingBackendOutcome {+ self.executeCallCount += 1+ self.onEnter()+ await self.latch.wait()+ self.didProduceOutcome = true+ return self.makeOutcome(plan)+ }+ }++ /// Deliberately cancellation-deaf: a parked waiter is only resumed by `open()`.+ private actor Latch {+ private var waiters: [CheckedContinuation<Void, Never>] = []+ private var isOpen = false++ func wait() async {+ if self.isOpen { return }+ await withCheckedContinuation { self.park($0) }+ }++ func open() {+ self.isOpen = true+ let parked = self.waiters+ self.waiters.removeAll()+ for continuation in parked {+ continuation.resume()+ }+ }++ private func park(_ continuation: CheckedContinuation<Void, Never>) {+ self.waiters.append(continuation)+ }+ }++ private nonisolated static let fixtureBackendID = MeetingBackendID(rawValue: "fixture-test-backend")++ private func makeFixtureDescriptor(+ id: MeetingBackendID = MeetingTranscriptionBackendTests.fixtureBackendID,+ version: String = "test",+ trackKinds: Set<MeetingAudioTrackKind> = Set(MeetingAudioTrackKind.allCases),+ precisions: Set<MeetingTextUnitPrecision> = [.word, .utterance],+ resultContract: MeetingBackendResultContract = .legacyResult+ ) -> MeetingBackendDescriptor {+ MeetingBackendDescriptor(+ id: id,+ version: version,+ execution: .local,+ supportedLanguageCodes: ["en"],+ supportedTrackKinds: trackKinds,+ supportedFinalPrecisions: precisions,+ resultContract: resultContract,+ knownLimits: ["Fixture only; performs no inference."]+ )+ }++ // MARK: - Session fixtures++ private func makeChunk(sequence: Int, path: String) -> MeetingAudioChunk {+ MeetingAudioChunk(+ id: UUID(),+ sequence: sequence,+ relativeFilePath: path,+ presentationStart: MeetingMediaTime(value: Int64(sequence) * 1000, timescale: 1000),+ presentationEnd: MeetingMediaTime(value: Int64(sequence + 1) * 1000, timescale: 1000),+ discontinuities: [],+ sha256: "fixture-\(sequence)",+ byteCount: 1024,+ finalizationState: .finalized+ )+ }++ private func makeTrack(kind: MeetingAudioTrackKind, chunks: [MeetingAudioChunk]) -> MeetingAudioTrack {+ MeetingAudioTrack(+ id: UUID(),+ kind: kind,+ sourceIdentifier: kind.rawValue,+ sourceDisplayName: kind.rawValue,+ format: nil,+ timebase: MeetingTimebaseMetadata(+ startedHostTime: 0,+ machTimebaseNumerator: 1,+ machTimebaseDenominator: 1,+ firstPresentationTime: nil+ ),+ health: .waiting,+ chunks: chunks+ )+ }++ private func makeSession(+ languageCode: String = "en",+ tracks: [MeetingAudioTrack]? = nil,+ processingAttempts: [MeetingProcessingAttempt] = []+ ) -> MeetingSession {+ var session = MeetingSession(+ configuration: MeetingCaptureConfiguration(+ mode: .onlineCall,+ title: "Backend fixture",+ languageCode: languageCode,+ microphone: MeetingMicrophoneIdentity(captureDeviceID: "mic-1", displayName: "Mic")+ ),+ timebase: MeetingTimebaseMetadata(+ startedHostTime: 0,+ machTimebaseNumerator: 1,+ machTimebaseDenominator: 1,+ firstPresentationTime: nil+ )+ )+ session.audioTracks = tracks ?? [+ self.makeTrack(kind: .microphone, chunks: [self.makeChunk(sequence: 0, path: "tracks/microphone/chunk_0.caf")]),+ ]+ session.processingAttempts = processingAttempts+ return session+ }++ private func makeResult(attemptID: UUID, text: String) -> MeetingProcessingResult {+ MeetingProcessingResult(+ speakers: [],+ segments: [+ MeetingTranscriptSegment(+ id: UUID(),+ start: MeetingMediaTime(value: 0, timescale: 1000),+ end: MeetingMediaTime(value: 1000, timescale: 1000),+ sourceTrackID: UUID(),+ speakerID: nil,+ text: text,+ revision: 1,+ status: .final,+ overlap: .none,+ completeness: .complete+ ),+ ],+ attempt: MeetingProcessingAttempt(+ id: attemptID,+ startedAt: Date(),+ completedAt: Date(),+ stage: .completed,+ pipelineVersion: MeetingProcessingPipeline.pipelineVersion,+ asrProvider: "fixture",+ asrModel: "fixture",+ diarizationModel: nil,+ lastCompletedTrackID: nil,+ errorCode: nil+ )+ )+ }++ private func makePipeline(+ registry: MeetingTranscriptionBackendRegistry,+ backendID: MeetingBackendID?,+ gate: MeetingProcessingSerializationGate = MeetingProcessingSerializationGate()+ ) -> MeetingProcessingPipeline {+ MeetingProcessingPipeline(+ asrServiceProvider: {+ XCTFail("Backend dispatch must not reach ASR readiness for a fixture backend")+ return ASRService()+ },+ serializationGate: gate,+ backendRegistry: registry,+ backendID: backendID+ )+ }++ func testRegistryRejectsFactoryIdentityMismatch() throws {+ let registry = MeetingTranscriptionBackendRegistry()+ registry.register(Self.fixtureBackendID) { [self] _ in+ FixtureMeetingBackend(descriptor: self.makeFixtureDescriptor(id: .legacyCompatibility)) { _ in+ fatalError("Mismatched factory must not execute")+ }+ }+ XCTAssertThrowsError(try registry.makeBackend(+ id: Self.fixtureBackendID,+ context: MeetingBackendHostContext(legacyExecutor: { _, _ in+ throw MeetingProcessingError.noRecoverableAudio+ })+ )) { error in+ XCTAssertEqual(error as? MeetingBackendError, .backendIdentityMismatch(+ requested: Self.fixtureBackendID, produced: .legacyCompatibility+ ))+ }+ }++ func testPipelineRejectsPlanForDifferentDirectory() async throws {+ let descriptor = self.makeFixtureDescriptor()+ let registry = MeetingTranscriptionBackendRegistry(defaultBackendID: Self.fixtureBackendID)+ registry.register(Self.fixtureBackendID) { _ in+ FixtureMeetingBackend(descriptor: descriptor, planOverride: { request in+ MeetingBackendPlan(request: MeetingBackendRequest(+ attemptID: request.attemptID, session: request.session,+ sessionDirectory: request.sessionDirectory.appendingPathComponent("another-session"),+ configuration: request.configuration+ ), descriptor: descriptor)+ }) { _ in fatalError("Substituted plan must not execute") }+ }+ do {+ _ = try await self.makePipeline(registry: registry, backendID: nil).process(+ session: self.makeSession(), sessionDirectory: FileManager.default.temporaryDirectory,+ progress: { _ in }+ )+ XCTFail("Substituted request must fail before model work")+ } catch {+ XCTAssertEqual(+ error as? MeetingBackendError,+ .planDisagreesWithRequest(backend: Self.fixtureBackendID, defect: .request)+ )+ }+ }++ func testLegacyExecutorRejectsSubstitutedRequest() async throws {+ let descriptor = self.makeFixtureDescriptor()+ let registry = MeetingTranscriptionBackendRegistry(defaultBackendID: Self.fixtureBackendID)+ registry.register(Self.fixtureBackendID) { context in+ LegacyCallbackBackend(descriptor: descriptor, executor: context.legacyExecutor) { request in+ MeetingBackendRequest(+ attemptID: UUID(), session: request.session, sessionDirectory: request.sessionDirectory,+ configuration: request.configuration+ )+ }+ }+ do {+ _ = try await self.makePipeline(registry: registry, backendID: nil).process(+ session: self.makeSession(), sessionDirectory: FileManager.default.temporaryDirectory,+ progress: { _ in }+ )+ XCTFail("Substituted executor request must fail")+ } catch {+ XCTAssertEqual(+ error as? MeetingBackendError,+ .legacyExecutorRequestMismatch(backend: Self.fixtureBackendID)+ )+ }+ }++ func testCancelledNonCooperativeBackendDoesNotPublishAndReleasesLease() async throws {+ let gate = MeetingProcessingSerializationGate()+ let entered = Latch()+ let latch = Latch()+ let registry = MeetingTranscriptionBackendRegistry(defaultBackendID: Self.fixtureBackendID)+ registry.register(Self.fixtureBackendID) { [self] _ in+ BlockingFixtureBackend(+ descriptor: self.makeFixtureDescriptor(),+ latch: latch,+ onEnter: { Task { await entered.open() } }+ ) { plan in+ .legacyCompatibility(self.makeResult(attemptID: plan.attemptID, text: "cancelled"))+ }+ }+ let pipeline = self.makePipeline(registry: registry, backendID: nil, gate: gate)+ let task = Task {+ try await pipeline.process(+ session: self.makeSession(),+ sessionDirectory: FileManager.default.temporaryDirectory,+ progress: { _ in }+ )+ }+ await entered.wait()+ task.cancel()+ await latch.open()+ do {+ _ = try await task.value+ XCTFail("Cancelled backend result must not be returned")+ } catch is CancellationError {} catch { XCTFail("Unexpected error: \(error)") }++ registry.register(Self.fixtureBackendID) { [self] _ in+ FixtureMeetingBackend(descriptor: self.makeFixtureDescriptor()) { plan in+ .legacyCompatibility(self.makeResult(attemptID: plan.attemptID, text: "next"))+ }+ }+ let result = try await pipeline.process(+ session: self.makeSession(),+ sessionDirectory: FileManager.default.temporaryDirectory,+ progress: { _ in }+ )+ XCTAssertEqual(result.segments.map(\.text), ["next"])+ }++ func testMeetingPreferencePreservesUnknownIDsAndDoesNotChangeDictation() {+ let defaults = UserDefaults.standard+ let key = "MeetingTranscriptionBackendID"+ let oldValue = defaults.object(forKey: key)+ defer {+ if let oldValue { defaults.set(oldValue, forKey: key) }+ else { defaults.removeObject(forKey: key) }+ }+ let settings = SettingsStore.shared+ let dictationModel = settings.selectedSpeechModel+ defaults.removeObject(forKey: key)+ XCTAssertEqual(settings.meetingTranscriptionBackendID, .productionDefault)+ let future = MeetingBackendID(rawValue: "future.unavailable-engine")+ settings.meetingTranscriptionBackendID = future+ XCTAssertEqual(settings.meetingTranscriptionBackendID, future)+ XCTAssertEqual(defaults.string(forKey: key), future.rawValue)+ XCTAssertEqual(settings.selectedSpeechModel, dictationModel)+ }++ func testMeetingPreferenceBackupPreservesUnknownIDAndMigratesMissingToDefault() async throws {+ let defaults = UserDefaults.standard+ let key = "MeetingTranscriptionBackendID"+ let oldValue = defaults.object(forKey: key)+ defer {+ if let oldValue { defaults.set(oldValue, forKey: key) }+ else { defaults.removeObject(forKey: key) }+ }+ let settingsStore = SettingsStore.shared+ let future = MeetingBackendID(rawValue: "future.hosted-provider")+ settingsStore.meetingTranscriptionBackendID = future++ let document = try await BackupService.shared.makeBackupDocument()+ XCTAssertEqual(document.settings.meetingTranscriptionBackendID, future.rawValue)++ let encoded = try BackupService.shared.encode(document)+ let decoded = try BackupService.shared.decode(encoded)+ settingsStore.meetingTranscriptionBackendID = .legacyCompatibility+ settingsStore.restore(from: decoded.settings)+ XCTAssertEqual(settingsStore.meetingTranscriptionBackendID, future)++ var root = try XCTUnwrap(JSONSerialization.jsonObject(with: encoded) as? [String: Any])+ var payload = try XCTUnwrap(root["settings"] as? [String: Any])+ payload.removeValue(forKey: "meetingTranscriptionBackendID")+ root["settings"] = payload+ let legacy = try BackupService.shared.decode(JSONSerialization.data(withJSONObject: root))+ XCTAssertNil(legacy.settings.meetingTranscriptionBackendID)++ settingsStore.meetingTranscriptionBackendID = future+ settingsStore.restore(from: legacy.settings)+ XCTAssertEqual(settingsStore.meetingTranscriptionBackendID, .productionDefault)+ }++ func testSelectionIsFrozenDuringExecutionAndRefreshedForNextAttempt() async throws {+ let firstID = Self.fixtureBackendID+ let secondID = MeetingBackendID(rawValue: "fixture-second")+ let registry = MeetingTranscriptionBackendRegistry(defaultBackendID: firstID)+ let entered = Latch()+ let latch = Latch()+ registry.register(firstID) { [self] _ in+ BlockingFixtureBackend(+ descriptor: self.makeFixtureDescriptor(),+ latch: latch,+ onEnter: { Task { await entered.open() } }+ ) { plan in+ .legacyCompatibility(self.makeResult(attemptID: plan.attemptID, text: "first"))+ }+ }+ registry.register(secondID) { [self] _ in+ FixtureMeetingBackend(descriptor: self.makeFixtureDescriptor(id: secondID)) { plan in+ .legacyCompatibility(self.makeResult(attemptID: plan.attemptID, text: "second"))+ }+ }+ var selected = firstID+ var selectionReads = 0+ let pipeline = MeetingProcessingPipeline(+ asrServiceProvider: { fatalError("Fixture must not load ASR") },+ serializationGate: MeetingProcessingSerializationGate(), backendRegistry: registry,+ backendIDProvider: { selectionReads += 1; return selected }+ )+ let session = self.makeSession()+ let task = Task {+ try await pipeline.process(+ session: session,+ sessionDirectory: FileManager.default.temporaryDirectory,+ progress: { _ in }+ )+ }+ await entered.wait()+ selected = secondID+ await latch.open()+ let first = try await task.value+ XCTAssertEqual(first.segments.map(\.text), ["first"])+ XCTAssertEqual(selectionReads, 1)+ let second = try await pipeline.process(+ session: session,+ sessionDirectory: FileManager.default.temporaryDirectory,+ progress: { _ in }+ )+ XCTAssertEqual(second.segments.map(\.text), ["second"])+ XCTAssertEqual(selectionReads, 2)+ }++ // MARK: - Registry++ func testDefaultRegistryUsesProductionDefaultAndKeepsLegacyRollback() throws {+ let registry = MeetingTranscriptionBackendRegistry.makeDefault()+ XCTAssertEqual(registry.defaultBackendID, .productionDefault)+ XCTAssertEqual(registry.registeredBackendIDs, [.legacyCompatibility, .parakeetNemotron])++ let backend = try registry.makeBackend(+ id: registry.defaultBackendID,+ context: MeetingBackendHostContext(legacyExecutor: { _, _ in+ XCTFail("Legacy executor must not run while only resolving the backend")+ throw MeetingProcessingError.noRecoverableAudio+ })+ )+ XCTAssertEqual(backend.descriptor.id, .parakeetNemotron)+ XCTAssertEqual(backend.descriptor.execution, .local)+ XCTAssertEqual(+ backend.descriptor.supportedFinalPrecisions, [.word, .utterance]+ )+ }++ func testRegistryRejectsAnUnknownBackendIdentifier() {+ let registry = MeetingTranscriptionBackendRegistry.makeDefault()+ let unknown = MeetingBackendID(rawValue: "not-registered")+ XCTAssertFalse(registry.contains(unknown))+ XCTAssertThrowsError(+ try registry.makeBackend(+ id: unknown,+ context: MeetingBackendHostContext(legacyExecutor: { _, _ in+ throw MeetingProcessingError.noRecoverableAudio+ })+ )+ ) { error in+ XCTAssertEqual(error as? MeetingBackendError, .unknownBackend(unknown))+ }+ }++ // MARK: - Pipeline dispatch++ func testPipelineDispatchesToTheInjectedBackendBeforeAnyModelWork() async throws {+ let session = self.makeSession()+ var captured: MeetingProcessingResult?+ let registry = MeetingTranscriptionBackendRegistry(defaultBackendID: Self.fixtureBackendID)+ var fixture: FixtureMeetingBackend?+ registry.register(Self.fixtureBackendID) { [self] _ in+ let backend = FixtureMeetingBackend(descriptor: self.makeFixtureDescriptor()) { plan in+ let result = self.makeResult(attemptID: plan.attemptID, text: "dispatched")+ captured = result+ return .legacyCompatibility(result)+ }+ fixture = backend+ return backend+ }++ let pipeline = self.makePipeline(registry: registry, backendID: nil)+ var stages: [MeetingProcessingStage] = []+ let result = try await pipeline.process(+ session: session,+ sessionDirectory: FileManager.default.temporaryDirectory,+ progress: { stages.append($0) }+ )++ let backend = try XCTUnwrap(fixture)+ XCTAssertEqual(backend.planCallCount, 1)+ XCTAssertEqual(backend.executeCallCount, 1)+ XCTAssertEqual(stages, [.transcribing], "the backend's progress reaches the caller unchanged")+ XCTAssertEqual(result.segments.map(\.text), ["dispatched"])+ XCTAssertEqual(result.attempt.id, captured?.attempt.id)++ let plan = try XCTUnwrap(backend.lastPlan)+ XCTAssertEqual(plan.backendID, Self.fixtureBackendID)+ XCTAssertEqual(plan.trackKindsByID.count, 1)+ XCTAssertEqual(plan.chunkIDsByTrackID.values.first?.count, 1)+ }++ func testPipelineReusesTheOpenAttemptIdentifierForTheRequest() async throws {+ let openAttempt = MeetingProcessingAttempt(+ id: UUID(),+ startedAt: Date(timeIntervalSinceNow: -60),+ completedAt: nil,+ stage: .transcribing,+ pipelineVersion: MeetingProcessingPipeline.pipelineVersion,+ asrProvider: nil,+ asrModel: nil,+ diarizationModel: nil,+ lastCompletedTrackID: nil,+ errorCode: nil+ )+ let session = self.makeSession(processingAttempts: [openAttempt])+ let registry = MeetingTranscriptionBackendRegistry(defaultBackendID: Self.fixtureBackendID)+ var fixture: FixtureMeetingBackend?+ registry.register(Self.fixtureBackendID) { [self] _ in+ let backend = FixtureMeetingBackend(descriptor: self.makeFixtureDescriptor()) { plan in+ .legacyCompatibility(self.makeResult(attemptID: plan.attemptID, text: "retry"))+ }+ fixture = backend+ return backend+ }++ let pipeline = self.makePipeline(registry: registry, backendID: nil)+ let result = try await pipeline.process(+ session: session,+ sessionDirectory: FileManager.default.temporaryDirectory,+ progress: { _ in }+ )+ XCTAssertEqual(fixture?.lastPlan?.attemptID, openAttempt.id)+ XCTAssertEqual(result.attempt.id, openAttempt.id)+ }++ func testPipelineRejectsAnUnknownBackendIdentifierExplicitly() async {+ let registry = MeetingTranscriptionBackendRegistry.makeDefault()+ let unknown = MeetingBackendID(rawValue: "muse-cloud-v0")+ let pipeline = self.makePipeline(registry: registry, backendID: unknown)+ do {+ _ = try await pipeline.process(+ session: self.makeSession(),+ sessionDirectory: FileManager.default.temporaryDirectory,+ progress: { _ in }+ )+ XCTFail("An unregistered backend must not silently fall back to legacy")+ } catch {+ XCTAssertEqual(error as? MeetingBackendError, .unknownBackend(unknown))+ }+ }++ func testLegacyPreflightChecksStillRunBeforeBackendSelection() async {+ var factoryCallCount = 0+ func registry() -> MeetingTranscriptionBackendRegistry {+ let registry = MeetingTranscriptionBackendRegistry(defaultBackendID: Self.fixtureBackendID)+ registry.register(Self.fixtureBackendID) { [self] _ in+ factoryCallCount += 1+ return FixtureMeetingBackend(descriptor: self.makeFixtureDescriptor()) { plan in+ .legacyCompatibility(self.makeResult(attemptID: plan.attemptID, text: "unused"))+ }+ }+ return registry+ }++ do {+ _ = try await self.makePipeline(registry: registry(), backendID: nil).process(+ session: self.makeSession(languageCode: "fr"),+ sessionDirectory: FileManager.default.temporaryDirectory,+ progress: { _ in }+ )+ XCTFail("Non-English sessions must still be rejected")+ } catch {+ guard case MeetingProcessingError.unsupportedLanguage = error else {+ return XCTFail("Expected unsupportedLanguage, got \(error)")+ }+ }++ do {+ _ = try await self.makePipeline(registry: registry(), backendID: nil).process(+ session: self.makeSession(tracks: [self.makeTrack(kind: .microphone, chunks: [])]),+ sessionDirectory: FileManager.default.temporaryDirectory,+ progress: { _ in }+ )+ XCTFail("A session with no chunks must still be rejected")+ } catch {+ guard case MeetingProcessingError.noRecoverableAudio = error else {+ return XCTFail("Expected noRecoverableAudio, got \(error)")+ }+ }++ XCTAssertEqual(factoryCallCount, 0, "preflight failures must not construct a backend")+ }++ /// Every chunk reports unreadable, so a manifest builds to explicit gaps without fixture audio.+ private struct UnreadableFixtureObserver: MeetingChunkAudioObserving {+ func observe(+ chunk: MeetingAudioChunk,+ trackID: MeetingAudioTrackID+ ) -> MeetingChunkObservationResult {+ .failed(.unreadable, detail: "fixture")+ }+ }++ func testPipelineSurfacesMalformedCanonicalEvidenceAsAValidationFailure() async throws {+ let session = self.makeSession()+ let trackID = try XCTUnwrap(session.audioTracks.first?.id)+ let epoch = MeetingAnalysisEpochID(trackID: trackID, ordinal: 0)++ // A scope defect — text the backend never really produced — still fails validation,+ // now on the canonical path after a real (all-gap) manifest was built and handed over.+ let scopeRegistry = MeetingTranscriptionBackendRegistry(defaultBackendID: Self.fixtureBackendID)+ scopeRegistry.register(Self.fixtureBackendID) { [self] _ in+ FixtureMeetingBackend(+ descriptor: self.makeFixtureDescriptor(resultContract: .canonicalEvidence)+ ) { plan in+ .canonicalEvidence(MeetingCanonicalResultBundle(+ evidence: MeetingFinalTranscriptEvidence(+ backendID: plan.backendID,+ attemptID: plan.attemptID,+ units: [+ MeetingFinalTextUnit(+ id: "u-0",+ trackID: trackID,+ analysisEpochID: epoch,+ precision: .utterance,+ text: " ",+ analysisStart: 2,+ analysisEnd: 4,+ speaker: .unassigned,+ analysisSpanIDs: ["span-0"]+ ),+ ]+ ),+ coverageReceipts: []+ ))+ }+ }++ do {+ _ = try await MeetingProcessingPipeline(+ asrServiceProvider: {+ XCTFail("Canonical fixture must not load ASR")+ return ASRService()+ },+ serializationGate: MeetingProcessingSerializationGate(),+ backendRegistry: scopeRegistry,+ backendID: nil,+ chunkObserver: UnreadableFixtureObserver()+ ).process(+ session: session,+ sessionDirectory: FileManager.default.temporaryDirectory,+ progress: { _ in }+ )+ XCTFail("Empty evidence text must not pass through the pipeline")+ } catch {+ XCTAssertEqual(error as? MeetingBackendEvidenceError, .emptyText(unitID: "u-0"))+ }+ }++ func testPipelineRejectsAnOutcomeThatContradictsTheDeclaredResultContract() async throws {+ // Declared canonical, returns the legacy shape: the pipeline must not reinterpret it.+ let canonicalRegistry = MeetingTranscriptionBackendRegistry(defaultBackendID: Self.fixtureBackendID)+ canonicalRegistry.register(Self.fixtureBackendID) { [self] _ in+ FixtureMeetingBackend(+ descriptor: self.makeFixtureDescriptor(resultContract: .canonicalEvidence)+ ) { plan in+ .legacyCompatibility(self.makeResult(attemptID: plan.attemptID, text: "wrong shape"))+ }+ }+ do {+ _ = try await MeetingProcessingPipeline(+ asrServiceProvider: {+ XCTFail("Canonical fixture must not load ASR")+ return ASRService()+ },+ serializationGate: MeetingProcessingSerializationGate(),+ backendRegistry: canonicalRegistry,+ backendID: nil,+ chunkObserver: UnreadableFixtureObserver()+ ).process(+ session: self.makeSession(),+ sessionDirectory: FileManager.default.temporaryDirectory,+ progress: { _ in }+ )+ XCTFail("A legacy outcome under a canonical contract must be rejected")+ } catch {+ XCTAssertEqual(+ error as? MeetingBackendError,+ .outcomeContractMismatch(backend: Self.fixtureBackendID, declared: .canonicalEvidence)+ )+ }++ // Declared legacy, returns canonical evidence: likewise a typed failure.+ let legacyRegistry = MeetingTranscriptionBackendRegistry(defaultBackendID: Self.fixtureBackendID)+ legacyRegistry.register(Self.fixtureBackendID) { [self] _ in+ FixtureMeetingBackend(descriptor: self.makeFixtureDescriptor(resultContract: .legacyResult)) { plan in+ .canonicalEvidence(MeetingCanonicalResultBundle(+ evidence: MeetingFinalTranscriptEvidence(+ backendID: plan.backendID,+ attemptID: plan.attemptID,+ units: []+ ),+ coverageReceipts: []+ ))+ }+ }+ do {+ _ = try await self.makePipeline(registry: legacyRegistry, backendID: nil).process(+ session: self.makeSession(),+ sessionDirectory: FileManager.default.temporaryDirectory,+ progress: { _ in }+ )+ XCTFail("Canonical evidence under a legacy contract must be rejected")+ } catch {+ XCTAssertEqual(+ error as? MeetingBackendError,+ .outcomeContractMismatch(backend: Self.fixtureBackendID, declared: .legacyResult)+ )+ }+ }++ // MARK: - Evidence validation++ private struct EvidenceFixture {+ let plan: MeetingBackendPlan+ let trackID: MeetingAudioTrackID+ let otherTrackID: MeetingAudioTrackID+ let epoch: MeetingAnalysisEpochID+ }++ private func makeEvidenceFixture(+ precisions: Set<MeetingTextUnitPrecision> = [.word, .utterance]+ ) throws -> EvidenceFixture {+ let microphone = self.makeTrack(+ kind: .microphone,+ chunks: [self.makeChunk(sequence: 0, path: "tracks/microphone/chunk_0.caf")]+ )+ let application = self.makeTrack(+ kind: .applicationAudio,+ chunks: [self.makeChunk(sequence: 0, path: "tracks/application/chunk_0.caf")]+ )+ let session = self.makeSession(tracks: [microphone, application])+ let request = MeetingBackendRequest(+ attemptID: UUID(),+ session: session,+ sessionDirectory: FileManager.default.temporaryDirectory,+ configuration: MeetingFinalProcessingConfiguration()+ )+ let plan = MeetingBackendPlan(+ request: request,+ descriptor: self.makeFixtureDescriptor(precisions: precisions)+ )+ return try EvidenceFixture(+ plan: plan,+ trackID: microphone.id,+ otherTrackID: application.id,+ epoch: MeetingAnalysisEpochID(trackID: microphone.id, ordinal: 0)+ )+ }++ private func makeUnit(+ _ fixture: EvidenceFixture,+ id: String = "u-0",+ precision: MeetingTextUnitPrecision = .word,+ text: String = "hello",+ analysisStart: TimeInterval = 1,+ analysisEnd: TimeInterval = 2,+ trackID: MeetingAudioTrackID? = nil,+ epoch: MeetingAnalysisEpochID? = nil,+ speaker: MeetingBackendSpeakerAssignment? = nil,+ analysisSpanIDs: [String]? = nil,+ confidence: Double? = nil+ ) -> MeetingFinalTextUnit {+ let resolvedEpoch = epoch ?? fixture.epoch+ return MeetingFinalTextUnit(+ id: id,+ trackID: trackID ?? fixture.trackID,+ analysisEpochID: resolvedEpoch,+ precision: precision,+ text: text,+ analysisStart: analysisStart,+ analysisEnd: analysisEnd,+ speaker: speaker ?? .assigned(MeetingBackendSpeakerToken(analysisEpochID: resolvedEpoch, label: "slot-0")),+ analysisSpanIDs: analysisSpanIDs ?? ["span-0"],+ confidence: confidence+ )+ }++ private func evidence(+ _ fixture: EvidenceFixture,+ units: [MeetingFinalTextUnit],+ activity: [MeetingBackendSpeakerActivity] = []+ ) -> MeetingFinalTranscriptEvidence {+ MeetingFinalTranscriptEvidence(+ backendID: fixture.plan.backendID,+ attemptID: fixture.plan.attemptID,+ units: units,+ speakerActivity: activity+ )+ }++ func testEvidenceAcceptsWordAndUtteranceUnitsAndOptionalActivity() throws {+ let fixture = try self.makeEvidenceFixture()+ let payload = self.evidence(+ fixture,+ units: [+ self.makeUnit(fixture, id: "w-0", precision: .word, analysisStart: 1, analysisEnd: 1.4),+ self.makeUnit(+ fixture, id: "utt-0", precision: .utterance, text: "a whole sentence",+ analysisStart: 2, analysisEnd: 6, speaker: .unassigned, confidence: 0.75+ ),+ self.makeUnit(+ fixture, id: "utt-1", precision: .utterance, text: "overlapped",+ analysisStart: 6, analysisEnd: 7,+ speaker: .ambiguous([+ MeetingBackendSpeakerToken(analysisEpochID: fixture.epoch, label: "slot-0"),+ MeetingBackendSpeakerToken(analysisEpochID: fixture.epoch, label: "slot-1"),+ ])+ ),+ ],+ activity: [+ MeetingBackendSpeakerActivity(+ token: MeetingBackendSpeakerToken(analysisEpochID: fixture.epoch, label: "slot-0"),+ start: 1,+ end: 1.4+ ),+ ]+ )+ XCTAssertEqual(try payload.validated(against: fixture.plan), payload)+ }++ func testEvidenceRejectsUnitsWithoutDeclaredPrecisionSupport() throws {+ let fixture = try self.makeEvidenceFixture(precisions: [.utterance])+ let payload = self.evidence(fixture, units: [self.makeUnit(fixture, id: "w-0", precision: .word)])+ XCTAssertThrowsError(try payload.validated(against: fixture.plan)) { error in+ XCTAssertEqual(+ error as? MeetingBackendEvidenceError,+ .unsupportedPrecision(unitID: "w-0", precision: .word)+ )+ }+ }++ func testEvidenceScopeValidationAdmitsInvalidTimingForQuarantine() throws {+ // Scope validation answers "does this reference something planned?", not "is this timing+ // usable?". Impossible bounds are quarantined per unit at assembly time so every input+ // unit still receives exactly one sidecar disposition.+ let fixture = try self.makeEvidenceFixture()+ let invalidIntervals: [(TimeInterval, TimeInterval)] = [+ (.nan, 2),+ (1, .nan),+ (1, .infinity),+ (-1, 2),+ (2, 2),+ (3, 1),+ ]+ for (start, end) in invalidIntervals {+ let payload = self.evidence(fixture, units: [+ self.makeUnit(fixture, analysisStart: start, analysisEnd: end),+ ])+ XCTAssertNoThrow(+ try payload.validated(against: fixture.plan),+ "start=\(start) end=\(end) is a quarantine matter, not a scope error"+ )+ }+ }++ func testEvidenceRejectsDuplicateAndEmptyUnitIdentifiers() throws {+ let fixture = try self.makeEvidenceFixture()+ let duplicates = self.evidence(fixture, units: [+ self.makeUnit(fixture, id: "same", analysisStart: 1, analysisEnd: 2),+ self.makeUnit(fixture, id: "same", analysisStart: 3, analysisEnd: 4),+ ])+ XCTAssertThrowsError(try duplicates.validated(against: fixture.plan)) { error in+ XCTAssertEqual(error as? MeetingBackendEvidenceError, .duplicateUnitID("same"))+ }++ let empty = self.evidence(fixture, units: [self.makeUnit(fixture, id: " ")])+ XCTAssertThrowsError(try empty.validated(against: fixture.plan)) { error in+ XCTAssertEqual(error as? MeetingBackendEvidenceError, .emptyUnitID)+ }+ }++ func testEvidenceRejectsSourcesOutsideThePlannedScope() throws {+ let fixture = try self.makeEvidenceFixture()++ let unknownTrack = self.evidence(fixture, units: [self.makeUnit(+ fixture, trackID: UUID(), epoch: fixture.epoch+ )])+ XCTAssertThrowsError(try unknownTrack.validated(against: fixture.plan)) { error in+ XCTAssertEqual(error as? MeetingBackendEvidenceError, .unknownSourceTrack(unitID: "u-0"))+ }++ let noSpans = self.evidence(fixture, units: [self.makeUnit(fixture, analysisSpanIDs: [])])+ XCTAssertThrowsError(try noSpans.validated(against: fixture.plan)) { error in+ XCTAssertEqual(error as? MeetingBackendEvidenceError, .missingAnalysisSpans(unitID: "u-0"))+ }++ let duplicateSpans = self.evidence(fixture, units: [self.makeUnit(+ fixture,+ analysisSpanIDs: ["span-0", "span-0"]+ )])+ XCTAssertThrowsError(try duplicateSpans.validated(against: fixture.plan)) { error in+ XCTAssertEqual(+ error as? MeetingBackendEvidenceError,+ .duplicateAnalysisSpanID(unitID: "u-0")+ )+ }++ // A microphone unit may not carry an epoch minted for the application track: the epoch is+ // what scopes speaker state, so crossing tracks here would silently merge identities.+ let foreignEpoch = self.evidence(fixture, units: [self.makeUnit(+ fixture,+ epoch: MeetingAnalysisEpochID(trackID: fixture.otherTrackID, ordinal: 0)+ )])+ XCTAssertThrowsError(try foreignEpoch.validated(against: fixture.plan)) { error in+ XCTAssertEqual(error as? MeetingBackendEvidenceError, .analysisEpochOutOfScope(unitID: "u-0"))+ }++ let negativeEpoch = self.evidence(fixture, units: [self.makeUnit(+ fixture,+ epoch: MeetingAnalysisEpochID(trackID: fixture.trackID, ordinal: -1),+ speaker: .unassigned+ )])+ XCTAssertThrowsError(try negativeEpoch.validated(against: fixture.plan)) { error in+ XCTAssertEqual(+ error as? MeetingBackendEvidenceError,+ .invalidAnalysisEpochOrdinal(unitID: "u-0")+ )+ }+ }++ func testEvidenceRejectsSpeakerTokensFromAnotherEpochOrTrack() throws {+ let fixture = try self.makeEvidenceFixture()++ let laterEpochToken = self.evidence(fixture, units: [self.makeUnit(+ fixture,+ speaker: .assigned(MeetingBackendSpeakerToken(+ analysisEpochID: MeetingAnalysisEpochID(trackID: fixture.trackID, ordinal: 1),+ label: "slot-0"+ ))+ )])+ XCTAssertThrowsError(try laterEpochToken.validated(against: fixture.plan)) { error in+ XCTAssertEqual(error as? MeetingBackendEvidenceError, .speakerTokenOutOfScope(unitID: "u-0"))+ }++ let crossTrackCandidate = self.evidence(fixture, units: [self.makeUnit(+ fixture,+ speaker: .ambiguous([+ MeetingBackendSpeakerToken(analysisEpochID: fixture.epoch, label: "slot-0"),+ MeetingBackendSpeakerToken(+ analysisEpochID: MeetingAnalysisEpochID(trackID: fixture.otherTrackID, ordinal: 0),+ label: "slot-0"+ ),+ ])+ )])+ XCTAssertThrowsError(try crossTrackCandidate.validated(against: fixture.plan)) { error in+ XCTAssertEqual(error as? MeetingBackendEvidenceError, .speakerTokenOutOfScope(unitID: "u-0"))+ }++ let singleCandidateAmbiguity = self.evidence(fixture, units: [self.makeUnit(+ fixture,+ speaker: .ambiguous([MeetingBackendSpeakerToken(analysisEpochID: fixture.epoch, label: "slot-0")])+ )])+ XCTAssertThrowsError(try singleCandidateAmbiguity.validated(against: fixture.plan)) { error in+ XCTAssertEqual(error as? MeetingBackendEvidenceError, .invalidAmbiguity(unitID: "u-0"))+ }++ let emptyTokenLabel = self.evidence(fixture, units: [self.makeUnit(+ fixture,+ speaker: .assigned(MeetingBackendSpeakerToken(+ analysisEpochID: fixture.epoch,+ label: " "+ ))+ )])+ XCTAssertThrowsError(try emptyTokenLabel.validated(against: fixture.plan)) { error in+ XCTAssertEqual(+ error as? MeetingBackendEvidenceError,+ .emptySpeakerTokenLabel(unitID: "u-0")+ )+ }+ }++ func testEvidenceScopeAdmitsOutOfRangeConfidenceForQuarantine() throws {+ // An out-of-range confidence is a value defect, not a scope violation: it quarantines the+ // unit at assembly rather than failing the payload. Absent confidence stays fine.+ let fixture = try self.makeEvidenceFixture()+ for value in [Double.nan, -0.01, 1.01, .infinity] {+ let payload = self.evidence(fixture, units: [self.makeUnit(fixture, confidence: value)])+ XCTAssertNoThrow(try payload.validated(against: fixture.plan), "confidence=\(value)")+ }+ let absent = self.evidence(fixture, units: [self.makeUnit(fixture, confidence: nil)])+ XCTAssertNoThrow(try absent.validated(against: fixture.plan))+ }++ func testEvidenceRejectsMismatchedBackendOrAttemptAndBadActivity() throws {+ let fixture = try self.makeEvidenceFixture()+ let otherBackend = MeetingBackendID(rawValue: "someone-else")++ let wrongBackend = MeetingFinalTranscriptEvidence(+ backendID: otherBackend,+ attemptID: fixture.plan.attemptID,+ units: [self.makeUnit(fixture)]+ )+ XCTAssertThrowsError(try wrongBackend.validated(against: fixture.plan)) { error in+ XCTAssertEqual(+ error as? MeetingBackendEvidenceError,+ .backendMismatch(expected: fixture.plan.backendID, actual: otherBackend)+ )+ }++ let wrongAttempt = MeetingFinalTranscriptEvidence(+ backendID: fixture.plan.backendID,+ attemptID: UUID(),+ units: [self.makeUnit(fixture)]+ )+ XCTAssertThrowsError(try wrongAttempt.validated(against: fixture.plan)) { error in+ guard case .attemptMismatch = (error as? MeetingBackendEvidenceError) else {+ return XCTFail("expected attemptMismatch, got \(error)")+ }+ }++ let badActivity = self.evidence(+ fixture,+ units: [self.makeUnit(fixture)],+ activity: [MeetingBackendSpeakerActivity(+ token: MeetingBackendSpeakerToken(analysisEpochID: fixture.epoch, label: "slot-0"),+ start: 5,+ end: 5+ )]+ )+ XCTAssertThrowsError(try badActivity.validated(against: fixture.plan)) { error in+ XCTAssertEqual(error as? MeetingBackendEvidenceError, .invalidActivityTiming(index: 0))+ }++ let unplannedActivityTrack = self.evidence(+ fixture,+ units: [self.makeUnit(fixture)],+ activity: [MeetingBackendSpeakerActivity(+ token: MeetingBackendSpeakerToken(+ analysisEpochID: MeetingAnalysisEpochID(trackID: UUID(), ordinal: 0),+ label: "slot-0"+ ),+ start: 1,+ end: 2+ )]+ )+ XCTAssertThrowsError(try unplannedActivityTrack.validated(against: fixture.plan)) { error in+ XCTAssertEqual(error as? MeetingBackendEvidenceError, .activityTokenOutOfScope(index: 0))+ }++ let negativeActivityEpoch = self.evidence(+ fixture,+ units: [self.makeUnit(fixture)],+ activity: [MeetingBackendSpeakerActivity(+ token: MeetingBackendSpeakerToken(+ analysisEpochID: MeetingAnalysisEpochID(trackID: fixture.trackID, ordinal: -1),+ label: "slot-0"+ ),+ start: 1,+ end: 2+ )]+ )+ XCTAssertThrowsError(try negativeActivityEpoch.validated(against: fixture.plan)) { error in+ XCTAssertEqual(+ error as? MeetingBackendEvidenceError,+ .invalidActivityEpochOrdinal(index: 0)+ )+ }+ }+}diff --git a/tools/patches/README.md b/tools/patches/README.mdnew file mode 100644index 00000000..c681a5dc--- /dev/null+++ b/tools/patches/README.md@@ -0,0 +1,31 @@+# FluidAudio Nemotron compatibility patch++Base FluidAudio revision: `3fd63887eef1dc25edea8263ce4b44aa854d898b`.++`fluidaudio-nemotron-compatibility.patch` preserves the independent dependency work. The current+development workspace points the app at that maintained local checkout; this must become a+published immutable fork revision before merge. Apply the patch at the base revision with+`git apply --check` followed by `git apply`. Do not patch Xcode DerivedData.+The current working checkout is `.local-dependencies/FluidAudio`, branch `codex/nemotron-diarization`;+that workspace is ignored, and this patch includes all nine changed/new source and test files.++Implemented: configurable speaker count, explicit Nemotron tensor geometry, strict shape/dtype and+length validation, Float16 output decoding, caller-controlled compute configuration, local compiled+model loading, cancellation checks around loading, and overflow-checked dimension validation.+The Nemotron factory preserves the explicitly supplied update cadence, including 300, rather than+silently applying the older Sortformer clamp to 340. Cache scoring parameters remain explicit. The+host mel ABI is frozen per model family: Nemotron uses the checked-in NeMo settings and frame-count+semantics, while legacy Sortformer retains its existing framing behavior. Complete-file Nemotron+processing emits the final core tail instead of leaving it as right-context-only audio. Streaming+state rejects inconsistent buffers and invalid reported embedding lengths.++Verified: the 67-test Sortformer/legacy integration selection passed, and the 10-test Nemotron+compatibility suite passed with the actual local CoreML artifact. The real-model suite loads the+model and runs one complete fixed window plus its final core tail end-to-end. It is enabled with+`NEMOTRON_DIARIZATION_MODEL_PATH` pointing to an `.mlpackage` or `.mlmodelc` directory. No model weights+are included in the patch or the DMG.++This establishes the Swift runtime contract and end-to-end execution. Model quality and performance+measurements are intentionally out of scope because they were completed separately. Once the+dependency changes are committed to the maintained fork, update the app's Xcode and Swift package+pins together.diff --git a/tools/patches/fluidaudio-nemotron-compatibility.patch b/tools/patches/fluidaudio-nemotron-compatibility.patchnew file mode 100644index 00000000..ff6fe732--- /dev/null+++ b/tools/patches/fluidaudio-nemotron-compatibility.patch@@ -0,0 +1,1695 @@+diff --git a/Sources/FluidAudio/Diarizer/Sortformer/SortformerDiarizerPipeline.swift b/Sources/FluidAudio/Diarizer/Sortformer/SortformerDiarizerPipeline.swift+index 1609e7e..43c0d90 100644+--- a/Sources/FluidAudio/Diarizer/Sortformer/SortformerDiarizerPipeline.swift++++ b/Sources/FluidAudio/Diarizer/Sortformer/SortformerDiarizerPipeline.swift+@@ -66,7 +66,7 @@ public final class SortformerDiarizer: Diarizer {+ private var _models: SortformerModels?++ // Native mel spectrogram (used when useNativePreprocessing is enabled)+- private let melSpectrogram = AudioMelSpectrogram()++ private let melSpectrogram: AudioMelSpectrogram++ // Audio buffering+ private var audioBuffer: [Float] = []+@@ -88,6 +88,7 @@ public final class SortformerDiarizer: Diarizer {+ var timelineConfig = timelineConfig+ timelineConfig.numSpeakers = config.numSpeakers+ self.config = config++ self.melSpectrogram = config.melFrontend.makeSpectrogram()+ self.stateUpdater = SortformerStateUpdater(config: config)+ self._state = SortformerStreamingState(config: config)+ self._timeline = DiarizerTimeline(config: timelineConfig)+@@ -96,17 +97,24 @@ public final class SortformerDiarizer: Diarizer {+ /// Initialize with CoreML models (combined pipeline mode).+ ///+ /// - Parameters:+- /// - mainModelPath: Path to Sortformer.mlpackage++ /// - mainModelPath: Path to `Sortformer.mlpackage`, or to an already compiled `.mlmodelc`++ /// - configuration: Optional CoreML configuration; used verbatim when supplied++ /// - Throws: `CancellationError` if the task is cancelled before the model is published; the++ /// diarizer is then left uninitialized rather than half-initialized.+ public func initialize(+- mainModelPath: URL++ mainModelPath: URL,++ configuration: MLModelConfiguration? = nil+ ) async throws {+ logger.info("Initializing Sortformer diarizer (combined pipeline mode)")++ let loadedModels = try await SortformerModels.load(+ config: config,+- mainModelPath: mainModelPath++ mainModelPath: mainModelPath,++ configuration: configuration+ )+++ try Task.checkCancellation()+++ // Use withLock helper to avoid direct NSLock usage in async context+ withLock {+ self._models = loadedModels+@@ -450,6 +458,14 @@ public final class SortformerDiarizer: Diarizer {++ // Trim embeddings to actual length+ let embLength = output.chunkLength++ guard embLength >= 0,++ embLength <= output.chunkEmbeddings.count / config.preEncoderDims++ else {++ throw SortformerError.inferenceFailed(++ "Model reported invalid chunk embedding length \(embLength) for "++ + "\(output.chunkEmbeddings.count / config.preEncoderDims) available frames"++ )++ }+ let chunkEmbs = Array(output.chunkEmbeddings.prefix(embLength * config.preEncoderDims))++ // Update state with correct context values+@@ -690,6 +706,14 @@ public final class SortformerDiarizer: Diarizer {++ // Trim embeddings to actual length+ let embLength = output.chunkLength++ guard embLength >= 0,++ embLength <= output.chunkEmbeddings.count / config.preEncoderDims++ else {++ throw SortformerError.inferenceFailed(++ "Model reported invalid chunk embedding length \(embLength) for "++ + "\(output.chunkEmbeddings.count / config.preEncoderDims) available frames"++ )++ }+ let chunkEmbs = Array(output.chunkEmbeddings.prefix(embLength * config.preEncoderDims))++ // Compute left/right context for prediction extraction+@@ -767,9 +791,14 @@ public final class SortformerDiarizer: Diarizer {++ guard audioBuffer.count >= samplesNeeded else { return }+++ let expectedFrameCount = config.melFrontend.family == .nemotron3Diarization++ ? config.melFrontend.storageFrameCount(sampleCount: audioBuffer.count)++ : nil+ let (mel, melLength, _) = melSpectrogram.computeFlatTransposed(+ audio: audioBuffer,+- lastAudioSample: lastAudioSample++ lastAudioSample: lastAudioSample,++ paddingMode: .center,++ expectedFrameCount: expectedFrameCount+ )++ guard melLength > 0 else { return }+@@ -884,7 +913,9 @@ public final class SortformerDiarizer: Diarizer {+ guard audioBuffer.count >= config.melWindow else {+ return 0+ }+- // Use center-padded frame count formula matching AudioMelSpectrogram.computeFlatTransposed++ if config.melFrontend.family == .nemotron3Diarization {++ return config.melFrontend.storageFrameCount(sampleCount: audioBuffer.count)++ }+ let paddedCount = audioBuffer.count + melSpectrogram.nFFT+ return 1 + (paddedCount - config.melWindow) / config.melStride+ }+diff --git a/Sources/FluidAudio/Diarizer/Sortformer/SortformerModelGeometry.swift b/Sources/FluidAudio/Diarizer/Sortformer/SortformerModelGeometry.swift+new file mode 100644+index 0000000..d24b147+--- /dev/null++++ b/Sources/FluidAudio/Diarizer/Sortformer/SortformerModelGeometry.swift+@@ -0,0 +1,443 @@++@preconcurrency import CoreML++import Foundation++++// MARK: - Feature Names++++/// CoreML feature names resolved against a concrete Sortformer-family model.++///++/// Two export families are supported:++/// - the shipped Streaming Sortformer exports (`speaker_preds[_out]`, `chunk_pre_encoder_*`)++/// - locally converted Nemotron exports (`spkcache_fifo_chunk_preds`, `chunk_pre_encode_*`)++public struct SortformerFeatureNames: Sendable, Equatable {++ public let chunk: String++ public let chunkLengths: String++ public let spkcache: String++ public let spkcacheLengths: String++ public let fifo: String++ public let fifoLengths: String++ public let predictions: String++ public let chunkEmbeddings: String++ public let chunkEmbeddingLengths: String++++ /// Accepted aliases, most-preferred first.++ enum Alias {++ static let chunk = ["chunk", "chunk_in", "audio_signal"]++ static let chunkLengths = ["chunk_lengths", "chunk_length", "audio_signal_lengths"]++ static let spkcache = ["spkcache", "spkcache_in", "speaker_cache"]++ static let spkcacheLengths = ["spkcache_lengths", "spkcache_length", "speaker_cache_lengths"]++ static let fifo = ["fifo", "fifo_in", "fifo_queue"]++ static let fifoLengths = ["fifo_lengths", "fifo_length", "fifo_queue_lengths"]++++ static let predictions = [++ "speaker_preds_out",++ "speaker_preds",++ "spkcache_fifo_chunk_preds",++ "spkcache_fifo_chunk_preds_out",++ "preds",++ ]++ static let chunkEmbeddings = [++ "chunk_pre_encoder_embs_out",++ "chunk_pre_encoder_embs",++ "chunk_pre_encode_embs",++ "chunk_pre_encode_embs_out",++ ]++ static let chunkEmbeddingLengths = [++ "chunk_pre_encoder_lengths_out",++ "chunk_pre_encoder_lengths",++ "chunk_pre_encode_lengths",++ "chunk_pre_encode_lengths_out",++ ]++ }++}++++// MARK: - Tensor Spec++++/// One multi-array feature exactly as the model declares it.++///++/// The shape is stored verbatim so validation can distinguish "the model says 512" from "the model++/// left this axis flexible" from "the model is not even rank-3".++public struct SortformerTensorSpec: Sendable, Equatable {++ public let name: String++ /// Shape as declared by the model. A non-positive entry means the axis is unconstrained.++ public let shape: [Int]++ public let dataType: MLMultiArrayDataType++++ public init(name: String, shape: [Int], dataType: MLMultiArrayDataType) {++ self.name = name++ self.shape = shape++ self.dataType = dataType++ }++++ init(name: String, constraint: MLMultiArrayConstraint) {++ self.init(name: name, shape: constraint.shape.map(\.intValue), dataType: constraint.dataType)++ }++++ /// `true` when the model declares `[1, time, features]`, the layout every input buffer uses.++ public var isBatchOneRank3: Bool {++ shape.count == 3 && shape[0] == 1++ }++++ /// Time axis, or `nil` when the tensor is not a fixed rank-3 batch-1 shape.++ public var timeDimension: Int? { fixedAxis(1) }++++ /// Feature axis, or `nil` when the tensor is not a fixed rank-3 batch-1 shape.++ public var featureDimension: Int? { fixedAxis(2) }++++ /// `true` when the model declares exactly `[1]`, the layout of every length feature.++ public var isSingleElement: Bool {++ shape == [1]++ }++++ public var shapeDescription: String {++ "[" + shape.map(String.init).joined(separator: ", ") + "]"++ }++++ private func fixedAxis(_ axis: Int) -> Int? {++ guard isBatchOneRank3, shape[axis] > 0 else { return nil }++ return shape[axis]++ }++}++++// MARK: - Model Geometry++++/// Tensor geometry read from a model's `MLModelDescription`.++///++/// Nothing here is inferred from a file name or a README — every value comes from the compiled++/// model's own feature descriptions. Axes the model leaves unconstrained are preserved as declared++/// and are *rejected* by ``validate(against:)`` rather than skipped, because the runtime allocates++/// fixed-size input buffers and cannot adapt to a flexible axis.++public struct SortformerModelGeometry: Sendable {++ public let chunk: SortformerTensorSpec++ public let chunkLengths: SortformerTensorSpec++ public let spkcache: SortformerTensorSpec++ public let spkcacheLengths: SortformerTensorSpec++ public let fifo: SortformerTensorSpec++ public let fifoLengths: SortformerTensorSpec++ public let predictions: SortformerTensorSpec++ public let chunkEmbeddings: SortformerTensorSpec++ public let chunkEmbeddingLengths: SortformerTensorSpec++++ public init(++ chunk: SortformerTensorSpec,++ chunkLengths: SortformerTensorSpec,++ spkcache: SortformerTensorSpec,++ spkcacheLengths: SortformerTensorSpec,++ fifo: SortformerTensorSpec,++ fifoLengths: SortformerTensorSpec,++ predictions: SortformerTensorSpec,++ chunkEmbeddings: SortformerTensorSpec,++ chunkEmbeddingLengths: SortformerTensorSpec++ ) {++ self.chunk = chunk++ self.chunkLengths = chunkLengths++ self.spkcache = spkcache++ self.spkcacheLengths = spkcacheLengths++ self.fifo = fifo++ self.fifoLengths = fifoLengths++ self.predictions = predictions++ self.chunkEmbeddings = chunkEmbeddings++ self.chunkEmbeddingLengths = chunkEmbeddingLengths++ }++++ public var names: SortformerFeatureNames {++ SortformerFeatureNames(++ chunk: chunk.name,++ chunkLengths: chunkLengths.name,++ spkcache: spkcache.name,++ spkcacheLengths: spkcacheLengths.name,++ fifo: fifo.name,++ fifoLengths: fifoLengths.name,++ predictions: predictions.name,++ chunkEmbeddings: chunkEmbeddings.name,++ chunkEmbeddingLengths: chunkEmbeddingLengths.name++ )++ }++++ /// The five `[1, time, features]` tensors the runtime binds fixed-size buffers to.++ var tensors: [SortformerTensorSpec] {++ [chunk, spkcache, fifo, predictions, chunkEmbeddings]++ }++++ /// The four `Int32 [1]` length features.++ var lengthFeatures: [SortformerTensorSpec] {++ [chunkLengths, spkcacheLengths, fifoLengths, chunkEmbeddingLengths]++ }++++ /// Mel frames per chunk, i.e. the `chunk` input's time dimension.++ public var chunkMelFrames: Int? { chunk.timeDimension }++ /// Mel filterbank count, i.e. the `chunk` input's feature dimension.++ public var melFeatures: Int? { chunk.featureDimension }++ /// Speaker cache capacity, i.e. the `spkcache` input's time dimension.++ public var spkcacheLen: Int? { spkcache.timeDimension }++ /// FIFO capacity, i.e. the `fifo` input's time dimension.++ public var fifoLen: Int? { fifo.timeDimension }++ /// Speaker slots, i.e. the prediction output's trailing dimension.++ public var numSpeakers: Int? { predictions.featureDimension }++ /// Prediction rows, i.e. the prediction output's time dimension.++ public var predictionFrames: Int? { predictions.timeDimension }++ /// Encoder frames emitted per chunk, i.e. the chunk embedding output's time dimension.++ public var chunkEncoderFrames: Int? { chunkEmbeddings.timeDimension }++++ /// Pre-encoder embedding width, or `nil` when the model's own tensors disagree (or leave the++ /// axis flexible). A disagreement is never resolved by picking a side — ``validate(against:)``++ /// checks each tensor's width individually and reports every offender.++ public var preEncoderDims: Int? {++ let widths = Set([spkcache.featureDimension, fifo.featureDimension, chunkEmbeddings.featureDimension])++ guard widths.count == 1, let width = widths.first else { return nil }++ return width++ }++++ /// Human-readable dump, used by the opt-in real-model smoke test and by load-failure logs.++ public var debugDescription: String {++ func line(_ label: String, _ spec: SortformerTensorSpec) -> String {++ "\(label)[\(spec.name)]: \(spec.shapeDescription) \(spec.dataType.fluidName)"++ }++ return [++ line("chunk", chunk),++ line("chunk_lengths", chunkLengths),++ line("spkcache", spkcache),++ line("spkcache_lengths", spkcacheLengths),++ line("fifo", fifo),++ line("fifo_lengths", fifoLengths),++ line("preds", predictions),++ line("embs", chunkEmbeddings),++ line("emb_lengths", chunkEmbeddingLengths),++ ].joined(separator: "\n")++ }++}++++// MARK: - Inspection++++extension SortformerModelGeometry {++++ /// Read the geometry of a loaded Sortformer-family model from its own description.++ ///++ /// - Throws: `SortformerError.modelLoadFailed` when a required input or output is missing, or is++ /// not a multi-array.++ public static func inspect(model: MLModel) throws -> SortformerModelGeometry {++ let description = model.modelDescription++ let inputs = description.inputDescriptionsByName++ let outputs = description.outputDescriptionsByName++++ func input(_ aliases: [String]) throws -> SortformerTensorSpec {++ try spec(aliases, in: inputs, kind: "input")++ }++ func output(_ aliases: [String]) throws -> SortformerTensorSpec {++ try spec(aliases, in: outputs, kind: "output")++ }++++ return SortformerModelGeometry(++ chunk: try input(SortformerFeatureNames.Alias.chunk),++ chunkLengths: try input(SortformerFeatureNames.Alias.chunkLengths),++ spkcache: try input(SortformerFeatureNames.Alias.spkcache),++ spkcacheLengths: try input(SortformerFeatureNames.Alias.spkcacheLengths),++ fifo: try input(SortformerFeatureNames.Alias.fifo),++ fifoLengths: try input(SortformerFeatureNames.Alias.fifoLengths),++ predictions: try output(SortformerFeatureNames.Alias.predictions),++ chunkEmbeddings: try output(SortformerFeatureNames.Alias.chunkEmbeddings),++ chunkEmbeddingLengths: try output(SortformerFeatureNames.Alias.chunkEmbeddingLengths)++ )++ }++++ private static func spec(++ _ aliases: [String],++ in descriptions: [String: MLFeatureDescription],++ kind: String++ ) throws -> SortformerTensorSpec {++ for alias in aliases {++ guard let description = descriptions[alias] else { continue }++ guard let constraint = description.multiArrayConstraint else {++ throw SortformerError.modelLoadFailed("\(kind.capitalized) '\(alias)' is not a multi-array")++ }++ return SortformerTensorSpec(name: alias, constraint: constraint)++ }++ let available = descriptions.keys.sorted().joined(separator: ", ")++ throw SortformerError.modelLoadFailed(++ "Model has no \(kind) matching any of [\(aliases.joined(separator: ", "))]. Available: [\(available)]"++ )++ }++}++++// MARK: - Validation++++extension SortformerModelGeometry {++++ /// Data types the runtime can read a float output from.++ ///++ /// `int32` is deliberately excluded: a quantized-to-integer prediction or embedding tensor would++ /// decode to garbage probabilities rather than fail loudly.++ static let supportedFloatOutputTypes: [MLMultiArrayDataType] = [.float16, .float32, .double]++++ /// Check that a configuration can actually drive this model.++ ///++ /// Every mismatch is collected so a misconfigured run reports the full picture in one error++ /// instead of one dimension per attempt.++ ///++ /// - Throws: `SortformerError.configurationError` listing every mismatch.++ public func validate(against config: SortformerConfig) throws {++ try config.validateGeometry()++ var problems: [String] = []++++ /// Require a fixed `[1, time, features]` shape and match it against the configuration.++ func checkTensor(++ _ label: String,++ _ spec: SortformerTensorSpec,++ time: Int,++ timeLabel: String,++ features: Int,++ featuresLabel: String++ ) {++ guard spec.isBatchOneRank3 else {++ problems.append(++ "\(label) '\(spec.name)' must be rank-3 [1, \(time), \(features)] but the model declares "++ + spec.shapeDescription++ )++ return++ }++ checkAxis(label, spec, timeLabel, spec.timeDimension, time)++ checkAxis(label, spec, featuresLabel, spec.featureDimension, features)++ }++++ func checkAxis(++ _ label: String, _ spec: SortformerTensorSpec, _ axisLabel: String, _ actual: Int?, _ expected: Int++ ) {++ guard let actual else {++ problems.append(++ "\(label) '\(spec.name)' \(axisLabel) is not a fixed dimension "++ + "(model declares \(spec.shapeDescription), config expects \(expected))"++ )++ return++ }++ guard actual != expected else { return }++ problems.append("\(label) '\(spec.name)' \(axisLabel): model=\(actual) config=\(expected)")++ }++++ checkTensor(++ "chunk input", chunk,++ time: config.chunkMelFrames, timeLabel: "mel frames",++ features: config.melFeatures, featuresLabel: "mel features")++ checkTensor(++ "spkcache input", spkcache,++ time: config.spkcacheLen, timeLabel: "cache length",++ features: config.preEncoderDims, featuresLabel: "pre-encoder dims")++ checkTensor(++ "fifo input", fifo,++ time: config.fifoLen, timeLabel: "fifo length",++ features: config.preEncoderDims, featuresLabel: "pre-encoder dims")++ checkTensor(++ "predictions output", predictions,++ time: config.predictionFrames, timeLabel: "prediction frames",++ features: config.numSpeakers, featuresLabel: "speaker count")++ checkTensor(++ "chunk embeddings output", chunkEmbeddings,++ time: config.chunkEncoderFrames, timeLabel: "encoder frames",++ features: config.preEncoderDims, featuresLabel: "pre-encoder dims")++++ // The copy path into the model's input buffers is float32-only.++ for spec in [chunk, spkcache, fifo] where spec.dataType != .float32 {++ problems.append(++ "input '\(spec.name)' dtype \(spec.dataType.fluidName) is unsupported (expected float32)")++ }++++ for spec in [predictions, chunkEmbeddings]++ where !Self.supportedFloatOutputTypes.contains(spec.dataType) {++ problems.append(++ "output '\(spec.name)' dtype \(spec.dataType.fluidName) is unsupported "++ + "(expected float16, float32 or double)")++ }++++ // Every length feature is bound as a single Int32 element in both directions.++ for spec in lengthFeatures {++ if !spec.isSingleElement {++ problems.append(++ "length feature '\(spec.name)' must be shape [1] but the model declares "++ + spec.shapeDescription)++ }++ if spec.dataType != .int32 {++ problems.append(++ "length feature '\(spec.name)' dtype \(spec.dataType.fluidName) is unsupported "++ + "(expected int32)")++ }++ }++++ guard problems.isEmpty else {++ throw SortformerError.configurationError(++ "Sortformer model/config mismatch: " + problems.joined(separator: "; ")++ + ". Model geometry:\n\(debugDescription)"++ )++ }++ }++}++++// MARK: - Output Reading++++extension SortformerModelGeometry {++++ /// Read a float output regardless of whether the export emits Float32 or Float16.++ ///++ /// Nemotron emits Float16 predictions and embeddings; the shipped Sortformer exports emit Float32++ /// predictions and (depending on the conversion) Float16 embeddings.++ static func floatScalars(from provider: MLFeatureProvider, named name: String) -> [Float]? {++ guard let value = provider.featureValue(for: name) else { return nil }++++ if let scalars = value.shapedArrayValue(of: Float32.self)?.scalars {++ return scalars++ }++++ #if arch(arm64)++ if #available(macOS 15.0, iOS 18.0, *),++ let scalars = value.shapedArrayValue(of: Float16.self)?.scalars++ {++ return scalars.map { Float($0) }++ }++ #endif++++ guard let array = value.multiArrayValue else { return nil }++ return floatScalars(from: array)++ }++++ /// Element-wise fallback for data types without a `MLShapedArray` fast path.++ static func floatScalars(from array: MLMultiArray) -> [Float]? {++ guard array.dataType.isReadableAsFloat else { return nil }++ var scalars = [Float](repeating: 0, count: array.count)++ for index in 0..<array.count {++ scalars[index] = array[index].floatValue++ }++ return scalars++ }++++ /// Read the first element of an integer output (chunk embedding lengths).++ static func firstInt(from provider: MLFeatureProvider, named name: String) -> Int? {++ guard let value = provider.featureValue(for: name) else { return nil }++++ if let scalar = value.shapedArrayValue(of: Int32.self)?.scalars.first {++ return Int(scalar)++ }++ if let array = value.multiArrayValue, array.count > 0 {++ return array[0].intValue++ }++ return nil++ }++}++++// MARK: - Data Type Helpers++++extension MLMultiArrayDataType {++ /// Short name for diagnostics (`description` is not stable across SDKs).++ var fluidName: String {++ switch self {++ case .float32: return "float32"++ case .float16: return "float16"++ case .double: return "double"++ case .int32: return "int32"++ default: return "unknown(\(rawValue))"++ }++ }++++ var isReadableAsFloat: Bool {++ switch self {++ case .float32, .float16, .double: return true++ default: return false++ }++ }++}+diff --git a/Sources/FluidAudio/Diarizer/Sortformer/SortformerModelInference.swift b/Sources/FluidAudio/Diarizer/Sortformer/SortformerModelInference.swift+index 0973292..5d12941 100644+--- a/Sources/FluidAudio/Diarizer/Sortformer/SortformerModelInference.swift++++ b/Sources/FluidAudio/Diarizer/Sortformer/SortformerModelInference.swift+@@ -17,6 +17,9 @@ public struct SortformerModels {+ /// Time taken to compile/load models+ public let compilationDuration: TimeInterval+++ /// Tensor geometry and feature names read from `mainModel`'s own description.++ public let geometry: SortformerModelGeometry+++ /// Cached buffers+ private let memoryOptimizer: ANEMemoryOptimizer+ private let chunkArray: MLMultiArray+@@ -26,6 +29,8 @@ public struct SortformerModels {+ private let spkcacheArray: MLMultiArray+ private let spkcacheLengthArray: MLMultiArray+++ /// - Throws: `SortformerError.modelLoadFailed` if the model's inputs/outputs are unrecognized, or++ /// `SortformerError.configurationError` if `config` does not match the model's declared shapes.+ public init(+ config: SortformerConfig,+ main: MLModel,+@@ -34,6 +39,11 @@ public struct SortformerModels {+ self.mainModel = main+ self.compilationDuration = compilationDuration+++ try config.validateGeometry()++ let geometry = try SortformerModelGeometry.inspect(model: main)++ try geometry.validate(against: config)++ self.geometry = geometry+++ self.memoryOptimizer = .init()+ self.chunkArray = try memoryOptimizer.createAlignedArray(+ shape: [1, NSNumber(value: config.chunkMelFrames), NSNumber(value: config.melFeatures)], dataType: .float32)+@@ -56,10 +66,12 @@ extension SortformerModels {+ /// Load models from local file paths (combined pipeline mode).+ ///+ /// - Parameters:+- /// - preprocessorPath: Path to SortformerPreprocessor.mlpackage+- /// - mainModelPath: Path to Sortformer.mlpackage+- /// - configuration: Optional MLModel configuration++ /// - config: Sortformer configuration; validated against the model's declared shapes++ /// - mainModelPath: Path to `Sortformer.mlpackage` (compiled on load) or to an already++ /// compiled `Sortformer.mlmodelc` directory (loaded as-is)++ /// - configuration: Optional MLModel configuration; used verbatim when supplied+ /// - Returns: Loaded SortformerModels++ /// - Throws: `CancellationError` if the enclosing task is cancelled before the model is returned.+ public static func load(+ config: SortformerConfig,+ mainModelPath: URL,+@@ -69,16 +81,36 @@ extension SortformerModels {++ let startTime = Date()++- // Compile mlpackage to mlmodelc first+- logger.info("Compiling main model...")+- let compiledMainModelURL = try await MLModel.compileModel(at: mainModelPath)++ try Task.checkCancellation()++++ // An `.mlmodelc` directory is already compiled; anything else (`.mlpackage`, `.mlmodel`)++ // goes through the compiler.++ let compiledMainModelURL: URL++ if mainModelPath.pathExtension.lowercased() == "mlmodelc" {++ logger.info("Using pre-compiled main model")++ compiledMainModelURL = mainModelPath++ } else {++ logger.info("Compiling main model...")++ compiledMainModelURL = try await MLModel.compileModel(at: mainModelPath)++ }++- // Load main model - .all lets CoreML pick optimal compute units+- let mainConfig = MLModelConfiguration()+- mainConfig.computeUnits = .all+- let mainModel = try MLModel(contentsOf: compiledMainModelURL, configuration: mainConfig)++ try Task.checkCancellation()++++ // Honor a caller-supplied configuration; otherwise keep the historical default where++ // .all lets CoreML pick optimal compute units.++ let mainConfig: MLModelConfiguration++ if let configuration {++ mainConfig = configuration++ } else {++ mainConfig = MLModelConfiguration()++ mainConfig.computeUnits = .all++ }++ let mainModel = try await MLModel.load(contentsOf: compiledMainModelURL, configuration: mainConfig)+ logger.info("Loaded main Sortformer model")+++ // Loading can take tens of seconds; don't hand a model back to a caller that gave up.++ try Task.checkCancellation()+++ let duration = Date().timeIntervalSince(startTime)+ logger.info("Models loaded in \(String(format: "%.2f", duration))s")++@@ -225,71 +257,37 @@ extension SortformerModels {+ // Create speaker cache length input+ spkcacheLengthArray[0] = NSNumber(value: Int32(spkcacheLength))++- // Run inference++ // Run inference using the feature names resolved from the model's own description, so both++ // the shipped Sortformer exports and Nemotron-style exports work unchanged.++ let names = geometry.names+ let inputFeatures = try MLDictionaryFeatureProvider(dictionary: [+- "chunk": MLFeatureValue(multiArray: chunkArray),+- "chunk_lengths": MLFeatureValue(multiArray: chunkLengthArray),+- "spkcache": MLFeatureValue(multiArray: spkcacheArray),+- "spkcache_lengths": MLFeatureValue(multiArray: spkcacheLengthArray),+- "fifo": MLFeatureValue(multiArray: fifoArray),+- "fifo_lengths": MLFeatureValue(multiArray: fifoLengthArray),++ names.chunk: MLFeatureValue(multiArray: chunkArray),++ names.chunkLengths: MLFeatureValue(multiArray: chunkLengthArray),++ names.spkcache: MLFeatureValue(multiArray: spkcacheArray),++ names.spkcacheLengths: MLFeatureValue(multiArray: spkcacheLengthArray),++ names.fifo: MLFeatureValue(multiArray: fifoArray),++ names.fifoLengths: MLFeatureValue(multiArray: fifoLengthArray),+ ])++ let output = try mainModel.prediction(from: inputFeatures)++- // Extract outputs (names must match CoreML Sortformer model)+- // Note: Output names use _out suffix to avoid macOS 26+ BNNS compiler error+- // where input and output tensors cannot share the same name+-+- // Chunk embeddings may be Float16 (head module uses fp16) or Float32+- let chunkEmbeddings: [Float]+- let predictions: [Float]+- let chunkEmbeddingsLength: Int+-+- // Get speaker probabilities+- if let preds = output.featureValue(for: "speaker_preds_out")?.shapedArrayValue(of: Float32.self)?.scalars {+- predictions = preds+- } else if let preds = output.featureValue(for: "speaker_preds")?.shapedArrayValue(of: Float32.self)?.scalars {+- predictions = preds+- } else {+- throw SortformerError.inferenceFailed("Missing speaker_preds or speaker_preds_out")++ // Predictions and embeddings may be Float16 (Nemotron, and fp16 head modules) or Float32.++ guard let predictions = SortformerModelGeometry.floatScalars(from: output, named: names.predictions)++ else {++ throw SortformerError.inferenceFailed("Missing or unreadable output '\(names.predictions)'")+ }++- // Get chunk length+- if let length = output.featureValue(for: "chunk_pre_encoder_lengths_out")?.shapedArrayValue(+- of: Int32.self)?.scalars.first+- {+- chunkEmbeddingsLength = Int(length)+- } else if let length = output.featureValue(for: "chunk_pre_encoder_lengths")?.shapedArrayValue(+- of: Int32.self)?.scalars.first+- {+- chunkEmbeddingsLength = Int(length)+- } else {+- throw SortformerError.inferenceFailed("Missing chunk_pre_encoder_lengths or chunk_pre_encoder_lengths_out")++ guard++ let chunkEmbeddingsLength = SortformerModelGeometry.firstInt(++ from: output, named: names.chunkEmbeddingLengths)++ else {++ throw SortformerError.inferenceFailed("Missing or unreadable output '\(names.chunkEmbeddingLengths)'")+ }++- // Get acoustic embeddings+- if let fp32 = output.featureValue(for: "chunk_pre_encoder_embs_out")?.shapedArrayValue(of: Float32.self)?+- .scalars+- {+- chunkEmbeddings = fp32+- } else if let fp32 = output.featureValue(for: "chunk_pre_encoder_embs")?.shapedArrayValue(of: Float32.self)?+- .scalars+- {+- chunkEmbeddings = fp32+- } else {+- #if arch(arm64)+- if #available(macOS 15.0, iOS 18.0, *),+- let fp16 = output.featureValue(for: "chunk_pre_encoder_embs_out")?.shapedArrayValue(of: Float16.self)?+- .scalars+- {+- chunkEmbeddings = fp16.map { Float($0) }+- } else {+- throw SortformerError.inferenceFailed("Missing chunk_pre_encoder_embs_out")+- }+- #else+- throw SortformerError.inferenceFailed("Missing chunk_pre_encoder_embs_out")+- #endif++ guard++ let chunkEmbeddings = SortformerModelGeometry.floatScalars(from: output, named: names.chunkEmbeddings)++ else {++ throw SortformerError.inferenceFailed("Missing or unreadable output '\(names.chunkEmbeddings)'")+ }++ return MainModelOutput(+diff --git a/Sources/FluidAudio/Diarizer/Sortformer/SortformerNemotronConfig.swift b/Sources/FluidAudio/Diarizer/Sortformer/SortformerNemotronConfig.swift+new file mode 100644+index 0000000..497f619+--- /dev/null++++ b/Sources/FluidAudio/Diarizer/Sortformer/SortformerNemotronConfig.swift+@@ -0,0 +1,156 @@++import Foundation++++/// Configuration for locally converted Nemotron streaming diarization exports.++///++/// Nemotron is a Sortformer-family model with a different tensor geometry (8 speaker slots, a much++/// longer chunk, a larger speaker cache). Everything in ``SortformerConfig/NemotronGeometry`` is++/// transcribed from an actual `MLModel` description, not from a file name or a README — the model's++/// own descriptions are authoritative and are re-validated at load time by++/// ``SortformerModelGeometry/validate(against:)``.++///++/// - Important: Only *runtime* compatibility (feature names, shapes, dtypes, streaming state layout)++/// is covered here. Exact mel front-end and cache-configuration parity with the upstream NeMo++/// checkpoint cannot be claimed without the `.nemo` file and reference mel fixtures.++extension SortformerConfig {++++ /// Tensor geometry of the Nemotron diarization export.++ ///++ /// Reference model description (`nemotron_diar_fp16.mlpackage`):++ /// - in `chunk` Float32 [1, 3040, 128]++ /// - in `chunk_lengths` Int32 [1]++ /// - in `spkcache` Float32 [1, 264, 512]++ /// - in `spkcache_lengths` Int32 [1]++ /// - in `fifo` Float32 [1, 40, 512]++ /// - in `fifo_lengths` Int32 [1]++ /// - out `spkcache_fifo_chunk_preds` Float16 [1, 684, 8]++ /// - out `chunk_pre_encode_embs` Float16 [1, 380, 512]++ /// - out `chunk_pre_encode_lengths` Int32 [1]++ ///++ /// 3040 mel frames / subsampling 8 = 380 encoder frames = 0 left + 340 core + 40 right, and++ /// 264 + 40 + 380 = 684 prediction rows.++ public enum NemotronGeometry {++ public static let numSpeakers = 8++ public static let chunkLen = 340++ public static let chunkLeftContext = 0++ public static let chunkRightContext = 40++ public static let fifoLen = 40++ public static let spkcacheLen = 264++++ /// Mel frames on the `chunk` input: (340 + 0 + 40) * 8.++ public static let chunkMelFrames = 3040++ /// Encoder frames on the `chunk_pre_encode_embs` output: 3040 / 8.++ public static let chunkEncoderFrames = 380++ /// Rows on the `spkcache_fifo_chunk_preds` output: 264 + 40 + 380.++ public static let predictionFrames = 684++++ /// Update periods the streaming state updater can run safely with this geometry.++ ///++ /// `SortformerStateUpdater` pops `max(spkcacheUpdatePeriod, contextLength - fifoLen)` frames,++ /// capped at `contextLength`, so any period in `[1, fifoLen + chunkLen]` keeps the FIFO and++ /// speaker cache within their declared capacities. A period below `chunkLen` only makes the++ /// cache update lag one chunk behind; it never pops more than the FIFO holds.++ public static let spkcacheUpdatePeriodRange = 1...(fifoLen + chunkLen)++++ /// Update period assigned by the reference Nemotron conversion script.++ ///++ /// - Important: This value is **not** verified against the upstream NeMo checkpoint; it is++ /// recorded here only so callers can pass it explicitly. See the note on++ /// ``SortformerConfig/nemotron(spkcacheUpdatePeriod:spkcacheSilFramesPerSpk:predScoreThreshold:silenceThreshold:scoresBoostLatest:strongBoostRate:weakBoostRate:minPosScoresRate:debugMode:)``++ /// for how it differs from the generic initializer's clamp.++ public static let referenceScriptSpkcacheUpdatePeriod = 300++++ /// Reject an update period the streaming updater cannot run with this geometry.++ static func validate(spkcacheUpdatePeriod: Int) throws {++ guard spkcacheUpdatePeriodRange.contains(spkcacheUpdatePeriod) else {++ throw SortformerError.configurationError(++ "spkcacheUpdatePeriod \(spkcacheUpdatePeriod) is outside the range supported by the "++ + "Nemotron geometry [\(spkcacheUpdatePeriodRange.lowerBound), "++ + "\(spkcacheUpdatePeriodRange.upperBound)] "++ + "(chunkLen=\(chunkLen), fifoLen=\(fifoLen))"++ )++ }++ }++ }++++ /// Build a configuration for a Nemotron export.++ ///++ /// The tensor geometry is pinned to ``NemotronGeometry``. The parameters below are *not* derivable++ /// from tensor sizes — they come from the conversion/NeMo streaming configuration — so they are++ /// required rather than guessed from a size formula.++ ///++ /// ## Update period: 300 vs 340++ ///++ /// The reference conversion script assigns `spkcache_update_period = 300`++ /// (``NemotronGeometry/referenceScriptSpkcacheUpdatePeriod``), which is *below* this geometry's++ /// `chunkLen` of 340. ``SortformerConfig/init(modelVariant:numSpeakers:chunkLen:chunkLeftContext:chunkRightContext:fifoLen:spkcacheLen:spkcacheUpdatePeriod:silenceThreshold:spkcacheSilFramesPerSpk:predScoreThreshold:scoresBoostLatest:strongBoostRate:weakBoostRate:minPosScoresRate:debugMode:)``++ /// clamps any period up to `chunkLen`, so the generic path would silently turn 300 into 340 — a++ /// different streaming cadence (340 drains the FIFO completely on each update, 300 leaves the++ /// 40-frame FIFO full). This factory does **not** clamp: it validates the value against++ /// ``NemotronGeometry/spkcacheUpdatePeriodRange`` and keeps it exactly as given, so passing 300++ /// yields 300 and passing an unusable value throws.++ ///++ /// - Important: Keeping the value the reference script uses is a *runtime* compatibility measure++ /// only. It does not establish numerical parity with the upstream NeMo checkpoint: that would++ /// require the `.nemo` file and reference fixtures, neither of which is checked here.++ ///++ /// - Parameters:++ /// - spkcacheUpdatePeriod: Frames popped from the FIFO into the speaker cache per update.++ /// Must be within ``NemotronGeometry/spkcacheUpdatePeriodRange`` = `[1, 380]`; it is used++ /// verbatim, never clamped.++ /// - spkcacheSilFramesPerSpk: Silence placeholder frames reserved per speaker during cache++ /// compression. Must satisfy `spkcacheLen / numSpeakers - value > 0`, i.e. `< 33`.++ /// - predScoreThreshold: Probability clamp used when scoring cached frames for compression.++ /// - silenceThreshold: Summed-probability threshold below which a frame updates the silence profile.++ /// - debugMode: Enable verbose logging.++ /// - Throws: `SortformerError.configurationError` if the resulting geometry is unusable.++ public static func nemotron(++ spkcacheUpdatePeriod: Int,++ spkcacheSilFramesPerSpk: Int,++ predScoreThreshold: Float,++ silenceThreshold: Float = 0.2,++ scoresBoostLatest: Float = 0.05,++ strongBoostRate: Float = 0.75,++ weakBoostRate: Float = 1.5,++ minPosScoresRate: Float = 0.5,++ debugMode: Bool = false++ ) throws -> SortformerConfig {++ try NemotronGeometry.validate(spkcacheUpdatePeriod: spkcacheUpdatePeriod)++ guard (0..<33).contains(spkcacheSilFramesPerSpk),++ predScoreThreshold.isFinite, predScoreThreshold > 0, predScoreThreshold < 1++ else {++ throw SortformerError.configurationError("Invalid Nemotron cache scoring configuration")++ }++ var config = SortformerConfig(++ // Nemotron is local-path only: there is no HuggingFace bundle to resolve.++ modelVariant: nil,++ melFrontend: .nemotron3Diarization,++ numSpeakers: NemotronGeometry.numSpeakers,++ chunkLen: NemotronGeometry.chunkLen,++ chunkLeftContext: NemotronGeometry.chunkLeftContext,++ chunkRightContext: NemotronGeometry.chunkRightContext,++ fifoLen: NemotronGeometry.fifoLen,++ spkcacheLen: NemotronGeometry.spkcacheLen,++ spkcacheUpdatePeriod: spkcacheUpdatePeriod,++ silenceThreshold: silenceThreshold,++ spkcacheSilFramesPerSpk: spkcacheSilFramesPerSpk,++ predScoreThreshold: predScoreThreshold,++ scoresBoostLatest: scoresBoostLatest,++ strongBoostRate: strongBoostRate,++ weakBoostRate: weakBoostRate,++ minPosScoresRate: minPosScoresRate,++ debugMode: debugMode++ )++++ // Preserve the caller's explicit reference cadence after the generic legacy clamp.++ config.spkcacheUpdatePeriod = spkcacheUpdatePeriod++ guard config.spkcacheLen == NemotronGeometry.spkcacheLen else {++ throw SortformerError.configurationError(++ "spkcacheSilFramesPerSpk \(spkcacheSilFramesPerSpk) forces spkcacheLen to "++ + "\(config.spkcacheLen), but the model requires \(NemotronGeometry.spkcacheLen)"++ )++ }++++ try config.validateGeometry()++ return config++ }++}+diff --git a/Sources/FluidAudio/Diarizer/Sortformer/SortformerStateUpdater.swift b/Sources/FluidAudio/Diarizer/Sortformer/SortformerStateUpdater.swift+index 64ce647..b93d932 100644+--- a/Sources/FluidAudio/Diarizer/Sortformer/SortformerStateUpdater.swift++++ b/Sources/FluidAudio/Diarizer/Sortformer/SortformerStateUpdater.swift+@@ -43,6 +43,21 @@ public struct SortformerStateUpdater {+ let currentSpkcacheLength = state.spkcacheLength+ let currentFifoLength = state.fifoLength+++ guard chunk.count.isMultiple(of: fcDModel) else {++ throw SortformerError.insufficientChunkLength(++ "Chunk embedding buffer has \(chunk.count) scalars, not a multiple of width \(fcDModel)"++ )++ }++ guard currentSpkcacheLength >= 0,++ currentFifoLength >= 0,++ state.spkcache.count == currentSpkcacheLength * fcDModel,++ state.fifo.count == currentFifoLength * fcDModel,++ state.spkcachePreds == nil || state.spkcachePreds?.count == currentSpkcacheLength * numSpeakers,++ state.fifoPreds == nil || state.fifoPreds?.count == currentFifoLength * numSpeakers++ else {++ throw SortformerError.invalidState("Streaming state lengths do not match their embedding/prediction buffers")++ }+++ // Extract FIFO predictions if FIFO exists+ if currentFifoLength > 0 {+ let fifoPredsStart = currentSpkcacheLength * numSpeakers+@@ -61,6 +76,13 @@ public struct SortformerStateUpdater {+ let rc = rightContext+ let coreFrames = (chunk.count / fcDModel) - lc - rc+++ guard lc >= 0, rc >= 0, coreFrames > 0, coreFrames <= config.chunkLen else {++ throw SortformerError.insufficientChunkLength(++ "Invalid encoded chunk geometry: total=\(chunk.count / fcDModel), left=\(lc), "++ + "core=\(coreFrames), right=\(rc), maximumCore=\(config.chunkLen)"++ )++ }+++ // Extract core embeddings only (frames lc..<lc+coreFrames)+ let embsStartIdx = lc * fcDModel+ let embsEndIdx = (lc + coreFrames) * fcDModel+diff --git a/Sources/FluidAudio/Diarizer/Sortformer/SortformerTypes.swift b/Sources/FluidAudio/Diarizer/Sortformer/SortformerTypes.swift+index c345113..cbab9c0 100644+--- a/Sources/FluidAudio/Diarizer/Sortformer/SortformerTypes.swift++++ b/Sources/FluidAudio/Diarizer/Sortformer/SortformerTypes.swift+@@ -1,5 +1,135 @@+ import Foundation+++// MARK: - Mel Frontend Contract++++/// Immutable host-side feature contract for a Sortformer-family export.++///++/// The CoreML graph starts after feature extraction, so these values are part of the model ABI just++/// as much as its tensor shapes. `family` deliberately remains part of the value even when two++/// exports currently share the same numbers; this prevents a new model from silently inheriting a++/// different model family's defaults.++public struct SortformerMelFrontendContract: Sendable, Equatable {++ public enum Family: String, Sendable {++ case streamingSortformer++ case nemotron3Diarization++ }++++ public enum Padding: String, Sendable {++ case centeredConstant++ }++++ public enum Window: String, Sendable {++ case symmetricHann++ }++++ public enum MelScale: String, Sendable {++ case slaneyNormalized++ }++++ public enum LogGuard: String, Sendable {++ case additive++ }++++ public enum Normalization: String, Sendable {++ case none++ }++++ public let family: Family++ public let sampleRate: Int++ public let featureCount: Int++ public let fftLength: Int++ public let windowLength: Int++ public let hopLength: Int++ public let preemphasis: Float++ public let dither: Float++ public let padding: Padding++ public let window: Window++ public let melScale: MelScale++ public let magnitudePower: Float++ public let logGuard: LogGuard++ public let logGuardValue: Float++ public let normalization: Normalization++ public let padTo: Int++ public let padValue: Float++++ private init(family: Family) {++ self.family = family++ self.sampleRate = 16_000++ self.featureCount = 128++ self.fftLength = 512++ self.windowLength = 400++ self.hopLength = 160++ self.preemphasis = 0.97++ self.dither = 0++ self.padding = .centeredConstant++ self.window = .symmetricHann++ self.melScale = .slaneyNormalized++ self.magnitudePower = 2++ self.logGuard = .additive++ self.logGuardValue = powf(2, -24)++ self.normalization = .none++ self.padTo = 0++ self.padValue = 0++ }++++ public static let streamingSortformer = SortformerMelFrontendContract(family: .streamingSortformer)++++ /// Host contract extracted from Nemotron-3's NeMo preprocessor configuration.++ ///++ /// Dither is frozen to zero for deterministic inference. NeMo's configured 25 ms window and++ /// 10 ms hop produce mel frames; the encoder's 8x feature stacking is what produces the 80 ms++ /// diarization cadence.++ public static let nemotron3Diarization = SortformerMelFrontendContract(family: .nemotron3Diarization)++++ /// Number of valid NeMo feature frames for an unpadded signal.++ public func validFrameCount(sampleCount: Int) -> Int {++ guard sampleCount > 0 else { return 0 }++ return sampleCount / hopLength++ }++++ /// Number of physical frames emitted by centered STFT before NeMo masks the final frame.++ public func storageFrameCount(sampleCount: Int) -> Int {++ guard sampleCount > 0 else { return 0 }++ return validFrameCount(sampleCount: sampleCount) + 1++ }++++ func makeSpectrogram() -> AudioMelSpectrogram {++ AudioMelSpectrogram(++ sampleRate: sampleRate,++ nMels: featureCount,++ nFFT: fftLength,++ hopLength: hopLength,++ winLength: windowLength,++ preemph: preemphasis,++ padTo: padTo,++ logFloor: logGuardValue,++ logFloorMode: .additive,++ windowPeriodic: false++ )++ }++}++++// MARK: - Saturating Arithmetic++++extension Int {++ /// `self + other`, pinned to `Int.min`/`Int.max` instead of trapping.++ ///++ /// Used only by `SortformerConfig.init`, whose clamping must survive absurd inputs long enough++ /// for `validateGeometry()` to describe them. Identical to `+` for every non-overflowing pair.++ static func fluidSaturatingAdd(_ lhs: Int, _ rhs: Int) -> Int {++ let (value, overflow) = lhs.addingReportingOverflow(rhs)++ guard overflow else { return value }++ return rhs > 0 ? .max : .min++ }++++ /// `lhs * rhs`, pinned to `Int.min`/`Int.max` instead of trapping.++ static func fluidSaturatingMultiply(_ lhs: Int, _ rhs: Int) -> Int {++ let (value, overflow) = lhs.multipliedReportingOverflow(by: rhs)++ guard overflow else { return value }++ return (lhs > 0) == (rhs > 0) ? .max : .min++ }++}+++ // MARK: - Configuration++ /// Configuration for Sortformer streaming diarization.+@@ -13,8 +143,14 @@ public struct SortformerConfig: Sendable {++ public let modelVariant: ModelVariant?++- /// Number of speaker slots (fixed at 4 for current model)+- public let numSpeakers: Int = 4++ /// Host-side preprocessing ABI paired with this model export.++ public let melFrontend: SortformerMelFrontendContract++++ /// Number of speaker slots.++ ///++ /// Must match the trailing dimension of the model's prediction output. The shipped Sortformer++ /// exports use 4; other exports (e.g. a locally converted Nemotron model) may use more.++ public let numSpeakers: Int++ /// Pre-encoder embedding dimension+ public let preEncoderDims: Int = 512+@@ -56,16 +192,16 @@ public struct SortformerConfig: Sendable {+ // MARK: - Audio Parameters++ /// Sample rate in Hz+- public let sampleRate: Int = 16000++ public var sampleRate: Int { melFrontend.sampleRate }++ /// Mel spectrogram window size in samples (25ms)+- public let melWindow: Int = 400++ public var melWindow: Int { melFrontend.windowLength }++ /// Mel spectrogram stride in samples (10ms)+- public let melStride: Int = 160++ public var melStride: Int { melFrontend.hopLength }++ /// Number of mel filterbank features+- public let melFeatures: Int = 128++ public var melFeatures: Int { melFrontend.featureCount }++ // MARK: - Thresholds++@@ -104,6 +240,17 @@ public struct SortformerConfig: Sendable {+ chunkLen * subsamplingFactor+ }+++ /// Encoder (post-subsampling) frames produced for one chunk, including left/right context.++ /// This is the second dimension of the model's chunk embedding output.++ public var chunkEncoderFrames: Int {++ chunkLen + chunkLeftContext + chunkRightContext++ }++++ /// Rows in the model's prediction output: speaker cache + FIFO + chunk encoder frames.++ public var predictionFrames: Int {++ spkcacheLen + fifoLen + chunkEncoderFrames++ }+++ /// Frame duration in seconds+ public var frameDurationSeconds: Float {+ Float(subsamplingFactor) * Float(melStride) / Float(sampleRate)+@@ -197,6 +344,8 @@ public struct SortformerConfig: Sendable {+ /// - Warning: If you don't use one of the default configurations, you must use a local model converted with that configuration.+ public init(+ modelVariant: ModelVariant? = .fastV2_1,++ melFrontend: SortformerMelFrontendContract = .streamingSortformer,++ numSpeakers: Int = 4,+ chunkLen: Int = 6,+ chunkLeftContext: Int = 1,+ chunkRightContext: Int = 7,+@@ -213,6 +362,8 @@ public struct SortformerConfig: Sendable {+ debugMode: Bool = false+ ) {+ self.modelVariant = modelVariant++ self.melFrontend = melFrontend++ self.numSpeakers = max(1, numSpeakers)+ self.chunkLen = max(1, chunkLen)+ self.chunkLeftContext = chunkLeftContext+ self.chunkRightContext = chunkRightContext+@@ -226,15 +377,140 @@ public struct SortformerConfig: Sendable {+ self.weakBoostRate = weakBoostRate+ self.minPosScoresRate = minPosScoresRate++- // The following parameters must meet certain constraints+- self.spkcacheLen = max(spkcacheLen, (1 + self.spkcacheSilFramesPerSpk) * self.numSpeakers)+- self.spkcacheUpdatePeriod = max(min(spkcacheUpdatePeriod, self.fifoLen + self.chunkLen), self.chunkLen)++ // The following parameters must meet certain constraints. The arithmetic saturates instead of++ // trapping so that extreme inputs reach `validateGeometry()` and are reported; for every++ // in-range configuration the result is identical to plain `+` and `*`.++ let silencePlaceholders = Int.fluidSaturatingMultiply(++ Int.fluidSaturatingAdd(1, self.spkcacheSilFramesPerSpk), self.numSpeakers)++ self.spkcacheLen = max(spkcacheLen, silencePlaceholders)++ let fifoPlusChunk = Int.fluidSaturatingAdd(self.fifoLen, self.chunkLen)++ self.spkcacheUpdatePeriod = max(min(spkcacheUpdatePeriod, fifoPlusChunk), self.chunkLen)+ }+++ /// Whether two configurations describe the same model tensor geometry.++ ///++ /// Compares every dimension that shapes a CoreML input or output, so a configuration that only++ /// differs in tuning knobs (thresholds, boost rates, debug mode) is still compatible, while one++ /// that would need a differently-shaped export is not.+ public func isCompatible(with other: SortformerConfig) -> Bool {+- return+- (self.chunkMelFrames == other.chunkMelFrames && self.fifoLen == other.fifoLen+- && self.spkcacheLen == other.spkcacheLen)++ return self.melFrontend == other.melFrontend++ && self.numSpeakers == other.numSpeakers++ && self.chunkMelFrames == other.chunkMelFrames++ && self.melFeatures == other.melFeatures++ && self.fifoLen == other.fifoLen++ && self.spkcacheLen == other.spkcacheLen++ && self.preEncoderDims == other.preEncoderDims++ && self.subsamplingFactor == other.subsamplingFactor++ && self.chunkEncoderFrames == other.chunkEncoderFrames++ }++++ /// Validate that the configured geometry can drive the streaming state updater safely.++ ///++ /// This checks only self-consistency; it does not know anything about a particular model file.++ /// Use ``SortformerModelGeometry/validate(against:)`` for that.++ ///++ /// - Throws: `SortformerError.configurationError` describing every violated constraint.++ public func validateGeometry() throws {++ var problems: [String] = []++++ if numSpeakers < 1 {++ problems.append("numSpeakers must be >= 1 (got \(numSpeakers))")++ }++ if chunkLen < 1 {++ problems.append("chunkLen must be >= 1 (got \(chunkLen))")++ }++ if chunkLeftContext < 0 {++ problems.append("chunkLeftContext must be >= 0 (got \(chunkLeftContext))")++ }++ if chunkRightContext < 0 {++ problems.append("chunkRightContext must be >= 0 (got \(chunkRightContext))")++ }++ if fifoLen < 1 {++ problems.append("fifoLen must be >= 1 (got \(fifoLen))")++ }++ if spkcacheLen < 1 {++ problems.append("spkcacheLen must be >= 1 (got \(spkcacheLen))")++ }++ if spkcacheSilFramesPerSpk < 0 {++ problems.append("spkcacheSilFramesPerSpk must be >= 0 (got \(spkcacheSilFramesPerSpk))")++ }++++ // Cache compression budgets one slice of the speaker cache per speaker and reserves++ // `spkcacheSilFramesPerSpk` of it for silence placeholders; the remainder must stay positive.++ if numSpeakers >= 1, spkcacheLen >= 1, spkcacheSilFramesPerSpk >= 0 {++ let perSpeaker = spkcacheLen / numSpeakers - spkcacheSilFramesPerSpk++ if perSpeaker <= 0 {++ problems.append(++ "spkcacheLen / numSpeakers - spkcacheSilFramesPerSpk must be > 0 "++ + "(\(spkcacheLen) / \(numSpeakers) - \(spkcacheSilFramesPerSpk) = \(perSpeaker))"++ )++ }++ }++++ // Every derived size is computed with overflow reporting *before* anything uses it, so an++ // absurd configuration produces a listed problem instead of trapping. `nil` means "this size++ // overflowed"; a problem has already been recorded for it and dependent checks are skipped.++ func sum(_ label: String, _ values: Int...) -> Int? {++ var total = 0++ for value in values {++ let (next, overflow) = total.addingReportingOverflow(value)++ if overflow {++ problems.append("\(label) overflows Int (\(values.map(String.init).joined(separator: " + ")))")++ return nil++ }++ total = next++ }++ return total++ }++++ func product(_ label: String, _ lhs: Int?, _ rhs: Int) -> Int? {++ guard let lhs else { return nil }++ let (value, overflow) = lhs.multipliedReportingOverflow(by: rhs)++ if overflow {++ problems.append("\(label) overflows Int (\(lhs) * \(rhs))")++ return nil++ }++ return value++ }++++ // `fifoLen + chunkLen` bounds the update period; it is also the FIFO buffer's reserved size.++ let fifoPlusChunk = sum("fifoLen + chunkLen", fifoLen, chunkLen)++ if let fifoPlusChunk {++ // The lower bound is 1, not chunkLen: `SortformerStateUpdater` raises the pop length to++ // `contextLength - fifoCapacity` when the period is smaller, so a shorter period only++ // changes cache cadence, it cannot pop more frames than the FIFO holds. The default++ // initializer still clamps to `>= chunkLen`; configurations that intentionally keep a++ // smaller reference period (see `SortformerConfig.nemotron`) set it explicitly.++ if spkcacheUpdatePeriod < 1 || spkcacheUpdatePeriod > fifoPlusChunk {++ problems.append(++ "spkcacheUpdatePeriod must be within [1, fifoLen + chunkLen] = "++ + "[1, \(fifoPlusChunk)] (got \(spkcacheUpdatePeriod))"++ )++ }++ }++++ // chunkMelFrames = (chunkLen + chunkLeftContext + chunkRightContext) * subsamplingFactor++ let encoderFrames = sum("chunkEncoderFrames", chunkLen, chunkLeftContext, chunkRightContext)++ let melFrames = product("chunkMelFrames", encoderFrames, subsamplingFactor)++ _ = product("chunk input element count", melFrames, melFeatures)++++ // predictionFrames = spkcacheLen + fifoLen + chunkEncoderFrames, and the prediction buffer.++ let predictionRows = encoderFrames.flatMap { sum("predictionFrames", spkcacheLen, fifoLen, $0) }++ _ = product("prediction element count", predictionRows, numSpeakers)++++ // Streaming buffers reserved in `SortformerStreamingState`.++ _ = product("fifo buffer element count", fifoPlusChunk, preEncoderDims)++ _ = product(++ "spkcache buffer element count",++ sum("spkcacheLen + spkcacheUpdatePeriod", spkcacheLen, spkcacheUpdatePeriod),++ preEncoderDims)++ _ = product("chunk embedding element count", encoderFrames, preEncoderDims)++++ guard problems.isEmpty else {++ throw SortformerError.configurationError(++ "Invalid Sortformer geometry: " + problems.joined(separator: "; ")++ )++ }+ }+ }++@@ -313,6 +589,7 @@ public struct SortformerFeatureLoader: Sendable {+ private let rc: Int+ private let chunkLen: Int+ private let melFeatures: Int++ private let emitsPartialTail: Bool++ private let featSeq: [Float]+ private let featLength: Int+@@ -326,14 +603,29 @@ public struct SortformerFeatureLoader: Sendable {+ self.rc = config.chunkRightContext * config.subsamplingFactor+ self.chunkLen = config.chunkLen * config.subsamplingFactor+ self.melFeatures = config.melFeatures++ self.emitsPartialTail = config.melFrontend.family == .nemotron3Diarization++ self.startFeat = 0+ self.endFeat = 0+- (self.featSeq, self.featLength, self.featSeqLength) = AudioMelSpectrogram().computeFlatTransposed(audio: audio)+- // numChunks accounts for right context requirement: need endFeat + rc <= featLength+- // Chunk n has endFeat = (n+1) * chunkLen, so valid when (n+1) * chunkLen + rc <= featLength+- // numChunks = floor((featLength - rc) / chunkLen)+- self.numChunks = max(0, (self.featLength - self.rc) / self.chunkLen)++ let frontend = config.melFrontend++ if self.emitsPartialTail {++ let storageFrames = frontend.storageFrameCount(sampleCount: audio.count)++ let features = frontend.makeSpectrogram().computeFlatTransposed(++ audio: audio,++ paddingMode: .center,++ expectedFrameCount: storageFrames++ )++ self.featSeq = features.mel++ self.featLength = min(frontend.validFrameCount(sampleCount: audio.count), features.numFrames)++ self.featSeqLength = self.featLength++ self.numChunks = self.featLength == 0 ? 0 : (self.featLength + self.chunkLen - 1) / self.chunkLen++ } else {++ let features = frontend.makeSpectrogram().computeFlatTransposed(audio: audio)++ self.featSeq = features.mel++ self.featLength = features.melLength++ self.featSeqLength = features.numFrames++ self.numChunks = max(0, (self.featLength - self.rc) / self.chunkLen)++ }+ }++ public mutating func next() -> (chunkFeatures: [Float], chunkLength: Int, leftOffset: Int, rightOffset: Int)? {+@@ -343,11 +635,12 @@ public struct SortformerFeatureLoader: Sendable {+ // Need at least one core frame+ guard endFeat > startFeat else { return nil }++- // Require full right context (same as streaming getNextChunkFeatures)+- guard endFeat + rc <= featLength else { return nil }++ if !emitsPartialTail {++ guard endFeat + rc <= featLength else { return nil }++ }++ let leftOffset = min(lc, startFeat)+- let rightOffset = rc++ let rightOffset = min(rc, featLength - endFeat)++ let chunkStartFrame = startFeat - leftOffset+ let chunkEndFrame = endFeat + rightOffset+@@ -384,10 +677,10 @@ public struct StreamingUpdateResult: Sendable {+ public let numSpeakers: Int++ /// Number of confirmed frames+- public var confirmedFrameCount: Int { confirmed.count / numSpeakers } // Assumes 4 speakers++ public var confirmedFrameCount: Int { confirmed.count / numSpeakers }++ /// Number of tentative frames+- public var tentativeFrameCount: Int { tentative.count / numSpeakers } // Assumes 4 speakers++ public var tentativeFrameCount: Int { tentative.count / numSpeakers }++ public init(confirmed: [Float], tentative: [Float], numSpeakers: Int = 4) {+ self.confirmed = confirmed+diff --git a/Tests/FluidAudioTests/Diarizer/Sortformer/SortformerNemotronCompatibilityTests.swift b/Tests/FluidAudioTests/Diarizer/Sortformer/SortformerNemotronCompatibilityTests.swift+new file mode 100644+index 0000000..72578da+--- /dev/null++++ b/Tests/FluidAudioTests/Diarizer/Sortformer/SortformerNemotronCompatibilityTests.swift+@@ -0,0 +1,229 @@++import CoreML++import Foundation++import XCTest++@testable import FluidAudio++++final class SortformerNemotronCompatibilityTests: XCTestCase {++ private func configuration() throws -> SortformerConfig {++ // Explicit cache parameters for contract testing, not a claim of NeMo parity.++ try .nemotron(spkcacheUpdatePeriod: 300, spkcacheSilFramesPerSpk: 3, predScoreThreshold: 0.25)++ }++++ private func geometry(++ chunkShape: [Int] = [1, 3040, 128],++ fifoShape: [Int] = [1, 40, 512],++ lengthShape: [Int] = [1],++ lengthType: MLMultiArrayDataType = .int32,++ predictionType: MLMultiArrayDataType = .float16++ ) -> SortformerModelGeometry {++ SortformerModelGeometry(++ chunk: .init(name: "chunk", shape: chunkShape, dataType: .float32),++ chunkLengths: .init(name: "chunk_lengths", shape: lengthShape, dataType: lengthType),++ spkcache: .init(name: "spkcache", shape: [1, 264, 512], dataType: .float32),++ spkcacheLengths: .init(name: "spkcache_lengths", shape: [1], dataType: .int32),++ fifo: .init(name: "fifo", shape: fifoShape, dataType: .float32),++ fifoLengths: .init(name: "fifo_lengths", shape: [1], dataType: .int32),++ predictions: .init(name: "spkcache_fifo_chunk_preds", shape: [1, 684, 8], dataType: predictionType),++ chunkEmbeddings: .init(name: "chunk_pre_encode_embs", shape: [1, 380, 512], dataType: .float16),++ chunkEmbeddingLengths: .init(name: "chunk_pre_encode_lengths", shape: [1], dataType: .int32)++ )++ }++++ func testExplicitNemotronCadenceAndLegacyDefaults() throws {++ let config = try configuration()++ XCTAssertEqual(config.melFrontend.family, .nemotron3Diarization)++ XCTAssertEqual(SortformerConfig.default.melFrontend.family, .streamingSortformer)++ XCTAssertEqual(config.numSpeakers, 8)++ XCTAssertEqual(config.chunkMelFrames, 3040)++ XCTAssertEqual(config.predictionFrames, 684)++ XCTAssertEqual(config.spkcacheUpdatePeriod, 300)++ XCTAssertNil(config.modelVariant)++ XCTAssertEqual(SortformerConfig.default.numSpeakers, 4)++ XCTAssertEqual(SortformerConfig(chunkLen: 340, spkcacheUpdatePeriod: 300).spkcacheUpdatePeriod, 340)++ XCTAssertThrowsError(try geometry().validate(against: .default))++ XCTAssertNoThrow(try geometry().validate(against: config))++ }++++ func testNemotronFrontendContractIsFrozenToExtractedNeMoConfiguration() throws {++ let frontend = try configuration().melFrontend++ XCTAssertEqual(frontend.sampleRate, 16_000)++ XCTAssertEqual(frontend.featureCount, 128)++ XCTAssertEqual(frontend.fftLength, 512)++ XCTAssertEqual(frontend.windowLength, 400)++ XCTAssertEqual(frontend.hopLength, 160)++ XCTAssertEqual(frontend.preemphasis, 0.97)++ XCTAssertEqual(frontend.dither, 0)++ XCTAssertEqual(frontend.padding, .centeredConstant)++ XCTAssertEqual(frontend.window, .symmetricHann)++ XCTAssertEqual(frontend.melScale, .slaneyNormalized)++ XCTAssertEqual(frontend.magnitudePower, 2)++ XCTAssertEqual(frontend.logGuard, .additive)++ XCTAssertEqual(frontend.logGuardValue, powf(2, -24))++ XCTAssertEqual(frontend.normalization, .none)++ XCTAssertEqual(frontend.padTo, 0)++ XCTAssertEqual(frontend.padValue, 0)++ XCTAssertEqual(frontend.validFrameCount(sampleCount: 16_000), 100)++ XCTAssertEqual(frontend.storageFrameCount(sampleCount: 16_000), 101)++ // The older `(L + nFFT - windowLength) / hop` approximation returns 102 here.++ XCTAssertEqual(frontend.validFrameCount(sampleCount: 16_100), 100)++ XCTAssertEqual(frontend.storageFrameCount(sampleCount: 16_100), 101)++ }++++ func testOfflineFeatureLoaderEmitsRightContextAgainAsFinalCoreTail() throws {++ let config = try configuration()++ // Exactly one fixed model window: 3040 valid 10 ms mel frames. NeMo chunks by the++ // 2720-frame core, so the final 320 frames must be emitted a second time as core after++ // serving as the first call's right context.++ let audio = [Float](repeating: 0.125, count: config.chunkMelFrames * config.melStride)++ var loader = SortformerFeatureLoader(config: config, audio: audio)++++ XCTAssertEqual(loader.numChunks, 2)++ let first = try XCTUnwrap(loader.next())++ XCTAssertEqual(first.chunkLength, config.chunkMelFrames)++ XCTAssertEqual(first.leftOffset, 0)++ XCTAssertEqual(first.rightOffset, config.chunkRightContext * config.subsamplingFactor)++ XCTAssertEqual(first.chunkFeatures.count, config.chunkMelFrames * config.melFeatures)++++ let tail = try XCTUnwrap(loader.next())++ XCTAssertEqual(tail.chunkLength, config.chunkRightContext * config.subsamplingFactor)++ XCTAssertEqual(tail.leftOffset, 0)++ XCTAssertEqual(tail.rightOffset, 0)++ XCTAssertEqual(tail.chunkFeatures.count, tail.chunkLength * config.melFeatures)++ XCTAssertNil(loader.next())++ }++++ func testNemotronStateCadenceLeavesExactlyFifoCapacity() throws {++ let config = try configuration()++ let updater = SortformerStateUpdater(config: config)++ var state = SortformerStreamingState(config: config)++ let chunk = [Float](repeating: 0.25, count: config.chunkEncoderFrames * config.preEncoderDims)++ let predictions = [Float](repeating: 0.1, count: config.predictionFrames * config.numSpeakers)++++ let first = try updater.streamingUpdate(++ state: &state,++ chunk: chunk,++ preds: predictions,++ leftContext: config.chunkLeftContext,++ rightContext: config.chunkRightContext++ )++ XCTAssertEqual(first.confirmedFrameCount, config.chunkLen)++ XCTAssertEqual(first.tentativeFrameCount, config.chunkRightContext)++ XCTAssertEqual(state.spkcacheLength, config.spkcacheLen)++ XCTAssertEqual(state.fifoLength, config.fifoLen)++++ _ = try updater.streamingUpdate(++ state: &state,++ chunk: chunk,++ preds: predictions,++ leftContext: config.chunkLeftContext,++ rightContext: config.chunkRightContext++ )++ XCTAssertEqual(state.spkcacheLength, config.spkcacheLen)++ XCTAssertEqual(state.fifoLength, config.fifoLen)++ XCTAssertEqual(state.spkcache.count, config.spkcacheLen * config.preEncoderDims)++ XCTAssertEqual(state.fifo.count, config.fifoLen * config.preEncoderDims)++ }++++ func testPartialEncodedTailUsesReportedLengthNotFixedCapacity() throws {++ let config = try configuration()++ let updater = SortformerStateUpdater(config: config)++ var state = SortformerStreamingState(config: config)++ let partialFrames = 5++++ let result = try updater.streamingUpdate(++ state: &state,++ chunk: [Float](repeating: 1, count: partialFrames * config.preEncoderDims),++ preds: [Float](repeating: 0.2, count: partialFrames * config.numSpeakers),++ leftContext: 0,++ rightContext: 0++ )++++ XCTAssertEqual(result.confirmedFrameCount, partialFrames)++ XCTAssertEqual(result.tentativeFrameCount, 0)++ XCTAssertEqual(state.fifoLength, partialFrames)++ XCTAssertEqual(state.fifo.count, partialFrames * config.preEncoderDims)++ }++++ func testModelGeometryRejectsInvalidRanksAndDisagreeingWidths() throws {++ let config = try configuration()++ for shape in [[3040, 128], [2, 3040, 128], [1, -1, 128], [1, 3040, 64]] {++ XCTAssertThrowsError(try geometry(chunkShape: shape).validate(against: config))++ }++ XCTAssertThrowsError(try geometry(fifoShape: [1, 40, 256]).validate(against: config))++ XCTAssertThrowsError(try geometry(lengthShape: [1, 1]).validate(against: config))++ XCTAssertThrowsError(try geometry(lengthType: .float32).validate(against: config))++ XCTAssertThrowsError(try geometry(predictionType: .int32).validate(against: config))++ }++++ func testExtremeGeometryThrowsInsteadOfOverflowing() throws {++ var config = try configuration()++ config.chunkLeftContext = Int.max++ config.chunkRightContext = Int.max++ XCTAssertThrowsError(try config.validateGeometry())++ XCTAssertThrowsError(try geometry().validate(against: config))++ config = try configuration()++ config.spkcacheSilFramesPerSpk = Int.min++ XCTAssertThrowsError(try config.validateGeometry())++ for silenceFrames in [Int.min, -1, 33, Int.max] {++ XCTAssertThrowsError(try SortformerConfig.nemotron(++ spkcacheUpdatePeriod: 300, spkcacheSilFramesPerSpk: silenceFrames, predScoreThreshold: 0.25++ ))++ }++ }++++ func testFloat16PredictionValuesAreReadWithoutAnotherSigmoid() throws {++ let values = try MLMultiArray(shape: [1, 3], dataType: .float16)++ values[0] = 0++ values[1] = 0.25++ values[2] = 1++ let provider = try MLDictionaryFeatureProvider(dictionary: ["preds": values])++ let decoded = try XCTUnwrap(SortformerModelGeometry.floatScalars(from: provider, named: "preds"))++ XCTAssertEqual(decoded, [0, 0.25, 1])++ let integers = try MLMultiArray(shape: [1], dataType: .int32)++ XCTAssertNil(SortformerModelGeometry.floatScalars(from: integers))++ }++++ func testRealNemotronArtifactLoadsWithSuppliedComputeConfiguration() async throws {++ guard let path = ProcessInfo.processInfo.environment["NEMOTRON_DIARIZATION_MODEL_PATH"] else {++ throw XCTSkip("Set NEMOTRON_DIARIZATION_MODEL_PATH for real-artifact metadata validation")++ }++ let configuration = MLModelConfiguration()++ configuration.computeUnits = .cpuOnly++ let models = try await SortformerModels.load(++ config: self.configuration(), mainModelPath: URL(fileURLWithPath: path), configuration: configuration++ )++ XCTAssertEqual(models.geometry.numSpeakers, 8)++ XCTAssertEqual(models.geometry.predictions.dataType, .float16)++ XCTAssertEqual(models.geometry.names.predictions, "spkcache_fifo_chunk_preds")++ XCTAssertEqual(models.mainModel.configuration.computeUnits, .cpuOnly)++ XCTAssertThrowsError(try models.geometry.validate(against: .default))++ }++++ func testRealNemotronArtifactProcessesFixedWindowAndCoreTail() async throws {++ guard let path = ProcessInfo.processInfo.environment["NEMOTRON_DIARIZATION_MODEL_PATH"] else {++ throw XCTSkip("Set NEMOTRON_DIARIZATION_MODEL_PATH for real-artifact inference validation")++ }++ let config = try self.configuration()++ let modelConfiguration = MLModelConfiguration()++ modelConfiguration.computeUnits = .cpuOnly++ let models = try await SortformerModels.load(++ config: config,++ mainModelPath: URL(fileURLWithPath: path),++ configuration: modelConfiguration++ )++ let diarizer = SortformerDiarizer(config: config)++ diarizer.initialize(models: models)++++ // One fixed 3040-frame model window is 380 encoder frames. The first call confirms 340++ // and uses 40 as right context; the loader must issue those 40 again as the final core tail.++ let samples = (0..<(config.chunkMelFrames * config.melStride)).map {++ Float(sin(Double($0) * 2 * .pi * 220 / Double(config.sampleRate))) * 0.05++ }++ let timeline = try diarizer.processComplete(samples)++++ XCTAssertEqual(timeline.numFinalizedFrames, config.chunkLen + config.chunkRightContext)++ XCTAssertEqual(timeline.numTentativeFrames, 0)++ XCTAssertEqual(diarizer.state.spkcacheLength, config.spkcacheLen)++ XCTAssertEqual(diarizer.state.fifoLength, 0)++ }++}+diff --git a/Tests/FluidAudioTests/Diarizer/Sortformer/SortformerStateUpdaterTests.swift b/Tests/FluidAudioTests/Diarizer/Sortformer/SortformerStateUpdaterTests.swift+index 66288f3..61198dc 100644+--- a/Tests/FluidAudioTests/Diarizer/Sortformer/SortformerStateUpdaterTests.swift++++ b/Tests/FluidAudioTests/Diarizer/Sortformer/SortformerStateUpdaterTests.swift+@@ -76,7 +76,7 @@ final class SortformerStateUpdaterTests: XCTestCase {+ var state = SortformerStreamingState(config: config)++ // Provide enough chunk data but insufficient predictions+- let chunkFrames = config.coreFrames + config.chunkLeftContext + config.chunkRightContext++ let chunkFrames = config.chunkEncoderFrames+ let chunk = [Float](repeating: 0, count: chunkFrames * config.preEncoderDims)+ let preds = [Float](repeating: 0, count: 1) // Way too short++@@ -107,7 +107,7 @@ final class SortformerStateUpdaterTests: XCTestCase {+ var state = SortformerStreamingState(config: config)++ // Build valid-sized inputs+- let totalChunkFrames = config.coreFrames + config.chunkLeftContext + config.chunkRightContext++ let totalChunkFrames = config.chunkEncoderFrames+ let chunk = [Float](repeating: 0, count: totalChunkFrames * config.preEncoderDims)+ let predsFrames = totalChunkFrames // spkcache=0, fifo=0, so preds matches chunk frames+ let preds = [Float](repeating: 0, count: predsFrames * config.numSpeakers)+@@ -121,8 +121,37 @@ final class SortformerStateUpdaterTests: XCTestCase {+ )++ XCTAssertEqual(+- result.confirmed.count, config.coreFrames * config.numSpeakers,+- "Confirmed should have coreFrames * numSpeakers elements"++ result.confirmed.count, config.chunkLen * config.numSpeakers,++ "Confirmed should have chunkLen * numSpeakers elements"+ )+ }++++ func testStreamingUpdateRejectsEmbeddingScalarRemainder() {++ let config = SortformerConfig.default++ let updater = SortformerStateUpdater(config: config)++ var state = SortformerStreamingState(config: config)++++ XCTAssertThrowsError(try updater.streamingUpdate(++ state: &state,++ chunk: [Float](repeating: 0, count: config.chunkEncoderFrames * config.preEncoderDims - 1),++ preds: [Float](repeating: 0, count: config.predictionFrames * config.numSpeakers),++ leftContext: config.chunkLeftContext,++ rightContext: config.chunkRightContext++ ))++ }++++ func testStreamingUpdateRejectsStateLengthBufferMismatch() {++ let config = SortformerConfig.default++ let updater = SortformerStateUpdater(config: config)++ var state = SortformerStreamingState(config: config)++ state.fifoLength = 1++++ XCTAssertThrowsError(try updater.streamingUpdate(++ state: &state,++ chunk: [Float](repeating: 0, count: config.chunkEncoderFrames * config.preEncoderDims),++ preds: [Float](repeating: 0, count: config.predictionFrames * config.numSpeakers),++ leftContext: config.chunkLeftContext,++ rightContext: config.chunkRightContext++ ))++ }+ }+diff --git a/Tests/FluidAudioTests/Diarizer/Sortformer/SortformerTests.swift b/Tests/FluidAudioTests/Diarizer/Sortformer/SortformerTests.swift+index 81d5882..657aa71 100644+--- a/Tests/FluidAudioTests/Diarizer/Sortformer/SortformerTests.swift++++ b/Tests/FluidAudioTests/Diarizer/Sortformer/SortformerTests.swift+@@ -33,10 +33,12 @@ final class SortformerTests: XCTestCase {+ streamingChunks.append(mel)+ }++- // 3. Compare+- XCTAssertEqual(batchChunks.count, streamingChunks.count, "Chunk count mismatch")++ // 3. Compare every chunk the non-finalized streaming path can currently emit. The complete++ // file loader intentionally emits additional partial tail chunks; the streaming path emits++ // those only during finalization after padding supplies the missing future context.++ XCTAssertGreaterThanOrEqual(batchChunks.count, streamingChunks.count)++- for i in 0..<batchChunks.count {++ for i in 0..<streamingChunks.count {+ let batch = batchChunks[i]+ let stream = streamingChunks[i]