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
chore: keep internal markdown plans and reports local
altic-deva0f4f4bf1d05
diff --git a/.gitignore b/.gitignoreindex 1f07ccfd..67fba786 100644--- a/.gitignore+++ b/.gitignore@@ -226,3 +226,9 @@ sample/.codexAGENTS.mdbuilds/++# Internal Markdown plans and reports stay local by default+*.md+!README.md+!CONTRIBUTING.md+!.github/pull_request_template.mddiff --git a/DICTATION_LATENCY_INVESTIGATION.md b/DICTATION_LATENCY_INVESTIGATION.mddeleted file mode 100644index 4e05d141..00000000--- a/DICTATION_LATENCY_INVESTIGATION.md+++ /dev/null@@ -1,209 +0,0 @@-# Dictation start/stop latency investigation--Branch: `B/overlay-smoked-glass`. Host: Apple silicon, macOS 27 beta.-Goal: instant start, instant stop, overlay gone by the time text is pasted.-Rule: no behavior changes in audio capture (`DirectCoreAudioInput`, capture-path in `ASRService`). Any finding there is logged, not fixed here.--## Method--- Scripted trigger: `FluidDebugRemoteToggleEnabled` defaults flag plus the- `com.FluidApp.debug.toggleRecording` distributed notification runs the- exact Right Option hotkey path. Driver CLI lives in the session scratchpad- (`fluidctl`, `fluid_toggle.sh`).-- Timing: `rg 'HIDE_NOW|STOP_TRACE|CLOSE_DETAIL|DICTATION_SUMMARY' ~/Library/Logs/Fluid/Fluid.log`-- Main-thread stacks: `sample FluidVoice 2 1` started 300 ms before the- scripted stop or start, so the aggregate is the stall itself.--## Findings and fixes (chronological)--### 1. Overlay hide blocked on WindowServer fences (fixed, 094b8d0e)--Every window-management call (`orderOut`, `setFrameOrigin` offscreen park,-the `_windowMoved` echo, `orderFrontRegardless`, `ignoresMouseEvents`,-explicit `CATransaction.flush`) goes through `NSWMWindowCoordinator-performTransactionUsingBlock` -> `CAFenceHandle newFenceFromDefaultServer`--> `mach_msg` and blocks until WindowServer answers. Measured 70-300 ms each.-Hide now sets `alphaValue = 0` only. Hide time: 216 ms -> 37 us.--| Build | Hide call | Lock held (typical) |-| --- | ---: | ---: |-| before | 82-216 ms | 300-660 ms |-| after | 28-37 us | 150-250 ms |---### 2. Final ASR ran on the main thread (fixed, 761f2c8c)--`final_executor_begin mainThread=true`: the TranscriptionExecutor closure-inherited main-actor isolation from the @MainActor method that formed it.-Inference (40-130 ms) blocked the run loop and every await hop waited for a-busy main thread. Detached with `Task.detached`. Lock 249 ms -> 64 ms on a-2 s silent recording. Audio capture untouched.--### 3. Hide transaction committed 550-660 ms late (fixed, ebcc71ab)--New metric `HIDE_COMMIT` = hide call -> transaction carrying alpha 0 committed-to WindowServer. This is the "box stays after the paste" number. SwiftUI state-clears, the `ignoresMouseEvents` fence (80-100 ms) and the status item refresh-were queued into the same run loop turn as the alpha change. All moved into a-`CATransaction.setCompletionBlock`. HIDE_COMMIT 551-658 ms -> 15-18 ms.--### 4. Status icon redrawn on every start and stop (fixed, fea6d6c9)--`updateMenuBarIcon` assigned a fresh `NSImage` on each `isRunning` change even-though the template icon never changes. Each assignment: status item redraw,-`NSStatusItemScene updateSettings`, `BKSAnimationFenceHandle` fence, ~118 ms in-samples, plus a `CABackingStoreSynchronize` wait. Assign once.--### 5. Transcribing status fired for most utterances (fixed, 526c2aa2)--Delay raised 100 ms -> 250 ms. Below that the status only added an overlay-re-render that delayed the result it announced.--### 6. Overlay re-evaluated ~94 times a second while recording (fixed, 6335acc4)--Root of the sluggish feel. Audio levels hit `NotchContentState` (an-ObservableObject observed by the whole overlay) once per audio buffer. 1 s-sample during silent recording: 312 ms of SwiftUI graph updates on main.-Level moved to `OverlayAudioLevelState`, observed only by the waveform,-throttled to 30 Hz. Graph updates during recording: ~20 ms/s.--### Warm stop after fixes 1-6 (2 s silent recording)--| Metric | Before | After |-| --- | ---: | ---: |-| Shortcut lock held | 250-660 ms | 54-77 ms |-| Inference -> caller wait | 90-190 ms | 0 ms |-| HIDE_COMMIT | 550-660 ms | 14-17 ms |-| SHOW_COMMIT (start -> first frame committed) | n/a | 10-27 ms |--### 7. Every CA commit blocks the main thread under WindowServer load (root, external)--2 ms samples during silent recording: 50-95% of main-thread samples sit in-`CA::Render::Message::send_message`, i.e. waiting for WindowServer to accept a-commit. WindowServer runs at 42-60% CPU on this host with FluidVoice quit-(macOS 27 beta, other apps). Any overlay frame committed while a stop is in-flight delays the result hop back to the main actor by 90-190 ms, and the-alpha 0 commit itself can wait 200-700 ms.--A/B results (3 runs each, HIDE_COMMIT / mid-recording caSend fraction):--| Variant | Effect |-| --- | --- |-| Material velvet / original / smokedGlass | no difference; blocking is per commit, not per material |-| Waveform 30 Hz -> 10 Hz | fewer commits, but a single commit still blocks 80% of a second when the server is busy |-| Transcription sounds off | no improvement (HIDE_COMMIT ~200 ms consistently) |-| Explicit `CATransaction.flush()` after alpha 0 | regression: the flush itself blocked 300-550 ms. Reverted. |-| Freeze waveform at stop begin (fcb54e49) | removes our own in-flight frames from the stop window |--Warm stop with a quiet WindowServer: lock 54-77 ms, HIDE_COMMIT 13-18 ms,-SHOW_COMMIT 8-17 ms, rapid restart accepted 120 ms after unlock. With a-saturated WindowServer the same code shows HIDE_COMMIT 200-700 ms; nothing in-our process is running then, the commit is queued at the server.--### 8. Rapid restart (stop, start 150 ms later)--Accepted every time after the fixes (no `shortcutRejected`). Show cost on a-rapid restart was 136-250 ms (orderFront fence 40 ms + first-frame flush-95 ms) versus 9-12 ms cold; the deferred mouse-events fence and the guarded-state publishes reduce it, the remaining cost is the first-frame commit.--## Status for the morning--Committed on `B/overlay-smoked-glass` (all builds installed to /Applications):--1. a1b9adfa feat(overlay): closing animation opt-in setting-2. 974cad2b chore(diagnostics): stop path traces-3. 094b8d0e perf(overlay): hide by alpha, no window transactions-4. 238ff3f4 chore(hotkey): local debug toggle trigger-5. 761f2c8c perf(asr): final transcription off the main actor-6. ebcc71ab perf(overlay): commit hide before post-stop state work-7. fea6d6c9 perf(menubar): stop redrawing the identical status icon-8. 526c2aa2 perf(asr): Transcribing status delay 250 ms-9. 6335acc4 perf(overlay): waveform level isolated and throttled-10. 22270dcc perf(asr): cancel Transcribing status right after inference-11. fcb54e49 perf(overlay): freeze waveform at stop, defer mouse fence--Not done / open:--- Real speech through the mic was not exercised by script (text-to-speech- through the speakers did not reach the input device). The text delivery- path (typing, history append, overlay observing TranscriptionHistoryStore)- was measured only on the older builds: typing 1.4-2 ms.-- The overlay still observes SettingsStore, AppServices, ActiveAppMonitor and- TranscriptionHistoryStore as whole objects; any publish on those- re-evaluates the whole body (~3-4 ms) and commits a frame.-- `FluidDebugRemoteToggleEnabled` is set in defaults on this machine so the- scripted trigger works. Remove with- `defaults delete com.FluidApp.app FluidDebugRemoteToggleEnabled`.-- Diagnostics builds used `LOCAL_SIGNING_XCCONFIG` pointing at a scratch- xcconfig adding `FLUIDVOICE_DIAGNOSTICS`; the final installed build is a- plain Release build without it.--### 9. No-text-field detection (51e62364)--`DeliveryTargetAssessment.assessFocusedElement()` runs inside-`TypingService.typeTextInstantly`, so every delivery path and the retry-button go through it. Rule, in order:--1. Accessibility not trusted, focused element unreadable, role unreadable ->- unknown, paste as before.-2. Role in {AXTextField, AXTextArea, AXComboBox, AXSecureTextField} or- AXValue settable -> editable, paste.-3. Role in the never-text set (buttons, menus, static text, images, links,- sliders, toolbars, windows, sheets, application) -> notEditable: transcript- stays on the clipboard, overlay shows "Not in a text field" with Copy.-4. Any other role (AXGroup, AXWebArea, AXList, AXTable, AXCell, AXScrollArea...)- -> unknown, paste as before. Table roles are deliberately here: a selected- spreadsheet cell accepts pasted text. No per-app rules.--Verified via the `FOCUS_ASSESS at=stop` log line (0.3-1.2 ms per stop):-Finder desktop -> unknown (AXList), Stickies and TextEdit -> editable-(AXTextArea), FluidVoice's own window -> unknown (AXScrollArea). The refuse-branch was not exercised with real speech; a button or menu focus at stop-would trigger it.-### 10. Paste read-back verification--`PasteVerifier` (TypingService, off-main after the paste command):--- Snapshot before: focused element, role, AXValue (skipped above 60k chars),- AXNumberOfCharacters, AXSelectedTextRange.-- Read back at 150 ms and again at 500 ms. Same element required.-- confirmed when the text appears in the value, or the character count or- caret advanced by the text length.-- notLanded only when value, count and caret were all readable and all- unchanged on both reads. Then the overlay comes back with "Text was not- inserted" and Copy.-- everything else unknown and silent (Finder, most containers, apps that- expose no value).--Verified with the paste-last debug trigger: Stickies -> confirmed by value in-165 ms; Finder desktop -> unknown (nothing readable); Claude Desktop with a-button focused -> refused before pasting by rule 9. The Claude Desktop-"nothing focused" case reports AXGroup and needs a real dictation to see what-the read-back returns; check `rg PASTE_VERIFY ~/Library/Logs/Fluid/Fluid.log`.--## Measurement caveats--- `OverlayCloseRunLoopProbe` (`CLOSE_DETAIL runLoop occupiedMs`) over-reports on- macOS 27: the loop runs in non-common modes during the AppKit update cycle,- so idle waits get counted as occupied. Use HIDE_COMMIT, SHOW_COMMIT,- heldMs and the ASR_BENCH executor lines instead.-- `sample` at 1 ms perturbs the app (adds ~1 s stalls). Use 5 ms or 2 ms- for at most 1 s windows.-- First cycle after launch is slower (SHOW_COMMIT ~170 ms, HIDE_COMMIT- ~300 ms). Warm-up, not regression.-- WindowServer sits at ~28% CPU idle on this host. Every commit that- redraws a bitmap-backed layer waits 50-100 ms in `wait_for_synchronize`.- The fixes above remove our commits from the critical path; they cannot- make WindowServer faster.--## Not touched--- Audio capture start: `START()` -> first PCM is 90-235 ms. Mic path, out- of scope by rule. Logged as `Audio capture running after first PCM`.-- `ignoresMouseEvents = true` after each hide still costs a 70-90 ms fence- on the main thread (post-commit, so not visible). It exists because an- alpha 0 panel could otherwise swallow clicks.-- The closing-animation setting path (`hide()` with animation on) still- parks the window offscreen.diff --git a/MEETING_AUDIO_PHASE0_RUNBOOK.md b/MEETING_AUDIO_PHASE0_RUNBOOK.mddeleted file mode 100644index 71190a06..00000000--- a/MEETING_AUDIO_PHASE0_RUNBOOK.md+++ /dev/null@@ -1,82 +0,0 @@-# Meeting Audio Freeze — Phase 0 Evidence Runbook--This runbook classifies meeting audio freezes before any production behavior is changed, including the post-meeting stop/processing transition. Diagnostics are DEBUG-only and opt-in. They record numeric Core Audio topology events; they do not record audio, device names, meeting titles, window titles, URLs, or transcripts.--## Acceptance rule--A hypothesis may advance to a fix only when all three artifacts agree on the same blocking boundary:--1. the durable `stall-*.jsonl` snapshot identifies the last completed and first incomplete operation;-2. `sample` shows the main-thread waiter and the owning AVFoundation/Core Audio stack;-3. the condition matrix changes the reproduction rate in the predicted direction.--Absence of a stall is not proof of safety. Run each condition at least 20 start/stop cycles, and compare against the pre-rebase revision on the same Mac, OS, microphone, output route, and meeting application.--## Launch--Use the installed, consistently signed Debug app. Do not run an ad-hoc build product because that changes macOS privacy identity.--```sh-mkdir -p /tmp/fluidvoice-audio-evidence-FLUIDVOICE_AUDIO_TOPOLOGY_DIAGNOSTICS=1 \-FLUIDVOICE_AUDIO_TOPOLOGY_TRACE_DIRECTORY=/tmp/fluidvoice-audio-evidence \-FLUIDVOICE_AUDIO_TOPOLOGY_STALL_SECONDS=2 \-"/Applications/FluidVoice Debug.app/Contents/MacOS/FluidVoice Debug"-```--The watchdog runs independently of the main thread. After two seconds without a main-runloop heartbeat it immediately writes and `fsync`s:--- `fluidvoice-audio-topology-stall-<pid>-<sequence>.jsonl`-- `fluidvoice-audio-topology-<pid>.stall`--The normal trace is drained at utility QoS without `fsync`; only a stall snapshot is durability-critical.--## Capture a process sample--Keep the frozen process alive. In another terminal:--```sh-tools/capture_audio_topology_stall.sh /tmp/fluidvoice-audio-evidence-```--The script reads the newest marker, validates its PID, and immediately runs Apple's `sample` tool. If `sample` cannot attach, run it from an administrator terminal. For an unresolved kernel/daemon interaction, capture a sysdiagnose immediately afterward with Control-Option-Command-Shift-Period and note its timestamp. Do not attach sysdiagnose archives to the repository; they may contain unrelated private system data.--## Meeting-end reproduction--1. Launch the installed signed Debug app with diagnostics enabled as above.-2. Start a meeting capture, keep both application and microphone audio active, then stop it normally.-3. Leave the app untouched while capture finalization and transcription finish. If the UI stalls, do not force quit.-4. Immediately run `tools/capture_audio_topology_stall.sh /tmp/fluidvoice-audio-evidence`.-5. Preserve the trace, stall snapshot, process sample, selected input/output transport classes, meeting mode, OS/build identifiers, and exact commit.--Interpret the final unmatched pair using its complete key: event category, owner, object ID, selector, scope, element, phase, and generation. `is_main_thread` reports the actual execution thread for each event; `queue_role` describes the intended delivery/control role. A callback begin without its matching end identifies an in-flight delivery. A main-hop begin without its end identifies work scheduled by a delivery that entered the main actor. Runtime, writer, output-listener release, AV capture stop, ScreenCaptureKit stop, processing, and activity-lease phases locate the owning meeting-end boundary. Always correlate this with the process sample; the trace alone does not prove the other side of a circular wait.--The ring retains 8,192 events. If a device storm overwrites an unmatched begin before the watchdog snapshot, classification may be incomplete; record the observed sequence span and do not interpret absence of an open pair as proof that no operation was blocked.--## Controlled condition matrix--Keep every uncontrolled variable fixed. Record successes, freezes, and failures separately.--| ID | Revision | App path | Purpose |-|---|---|---|---|-| A | pre-rebase | real coordinator | Historical control |-| B | current | isolated microphone capture | VPIO + AVAudioEngine baseline on its actor |-| C | current | B + retained AVFoundation discovery/default lookup | AVFoundation catalog interaction |-| D | current | B + physical-input liveness listeners only | Listener scope interaction |-| E | current | B + all-input liveness listeners | Rebase-introduced ledger interaction |-| F | current | full signed app + real `MeetingSessionCoordinator` | Production ordering after observer, ASR, detector, and UI readiness |-| G | current | B executed on MainActor | Executor sensitivity; never substitute for B |--For C, measure discovery, default lookup, and authorization timing independently rather than treating them as one toggle. For D/E, keep listener registration active through capture quiescence. Condition F begins only after the existing UI gate has opened and the log contains `Audio subsystems initialized`; it must not use a mock coordinator.--## Interpreting the boundary--- Incomplete `vpioEnableBegin`: VPIO creation/configuration is the active boundary.-- VPIO completed but `engineStartBegin` is incomplete: AVAudioEngine start is the active boundary.-- Incomplete listener add/remove or HAL query before the stall: topology listener interaction is implicated.-- Heartbeat stalled with all phases closed: look outside the instrumented topology transition; do not force-fit a Core Audio conclusion.-- A callback marker proves delivery only. All HAL work is separately bracketed so callback arrival is never confused with callback-side querying.--## Promotion gate--Do not ship a fix from a single reproduction. Require at least one clear discriminating A/B result, a matching process sample, and repeated-cycle evidence. Preserve the raw trace, sample, OS/build identifiers, selected input/output transport class, condition ID, and exact commit hashes in a separate evidence folder.diff --git a/MEETING_AUDIO_START_FREEZE_RCA.md b/MEETING_AUDIO_START_FREEZE_RCA.mddeleted file mode 100644index 6cffa468..00000000--- a/MEETING_AUDIO_START_FREEZE_RCA.md+++ /dev/null@@ -1,775 +0,0 @@-# Meeting transcription start freeze — root cause analysis--**Incident:** BUG-001-**Date:** 2026-08-25-**Severity:** P0 / meeting capture unavailable-**Status:** Narrow production mitigation implemented and validated; long-run and queue-ownership hardening remain-**Affected build:** FluidVoice Debug 1.6.9 (20), macOS 26.5.1 (25F80)--## 1. Executive summary--FluidVoice reproducibly freezes while meeting capture enables `AVAudioEngine` voice processing and-Core Audio publishes/tears down virtual aggregate devices. In both incidents, the main thread remained-parked in AVFoundation's device-liveness listener while removing HAL property listeners; concurrently,-HAL's device-teardown notification queue remained parked in `dispatch_sync`.--The samples prove a permanent two-thread wait during the same topology transition. They are strongly-consistent with a circular wait, but they do **not** expose HAL's synchronous target queue or the-complete wait-for graph. Phase 0 eliminated the meeting microphone catalog as a sufficient cause,-then isolated the rebase-introduced broad `DeviceIsAlive` ledger as the strongest empirical inducing-condition. With the normal AVFoundation catalog restored, excluding only aggregate-transport inputs-from that ledger passed normal dictation and three meeting start/stop cycles. This supports a narrow-production mitigation, but it is not a statistical proof that the full private HAL deadlock class is-closed.--The investigation did prove two FluidVoice hazards around that transition:--1. several FluidVoice Core Audio owners register, add, or remove device listeners on the main queue;- and-2. the current “exclusive activity” lease excludes another transcription job but does not quiesce the- prepared dictation backend, drain route recovery, suspend topology-driven reconciliation, or own- meeting backend switches. It is logical exclusivity without audio-hardware exclusivity.--The production mitigation therefore excludes only aggregate transports from-`AudioHardwareObserver`'s broad ledger. Physical, Bluetooth, USB, virtual, and unknown transports are-unchanged; system/default-device listeners, full liveness refreshes, and ASR's selected-device listener-remain active. Moving Core Audio listener lifecycle ownership off main remains mandatory hardening and-the correct long-term seam, but is not required to ship this evidence-scoped mitigation.--The rebase history materially sharpens the leading hypothesis. The pre-rebase meeting branch already-contained the VPIO meeting path, but did not contain the newer multi-device dictation availability-observer. Rebasing onto `origin/main` introduced per-input `DeviceIsAlive` listeners that are added and-removed on `DispatchQueue.main` during device-list churn. VPIO deliberately creates and destroys-temporary aggregate devices, so this new observer is exercised at exactly the incident boundary. Its-remove call is the closest FluidVoice-owned structural match to the frozen AVFoundation/Core Audio-stack. This is now the highest-priority **rebase-introduced FluidVoice suspect**, but not the leading-incident hypothesis: AVFoundation+VPIO remains co-equal because the sampled waiter is AVFoundation's-own listener. The pre/post-rebase and mechanism-isolation rows must reproduce the difference.--## 2. User impact--- Starting meeting transcription beachballs the entire application.-- No stop, cancel, or fallback action remains available because the main thread is blocked.-- Restarting restores the app but starting meeting transcription can reproduce the freeze.-- No evidence indicates transcript or recording corruption because capture never reaches its committed- recording state; this must still be verified during the eventual recovery-path tests.--## 3. Incident evidence--### 3.1 Reproduction 1--- App PID: `13288`-- Meeting start: `06:41:49.076`-- Aggregate devices appeared by `06:41:49.422`:- - `CADefaultDeviceAggregate-13288-0`- - `VPAUAggregateAudioDevice-0xa37144040`-- The prepared direct dictation capture invalidated on `stream_configuration`, `virtual_format`, and- `physical_format`, then scheduled route-recovery generations 11–13.-- Meeting microphone and application models finished warming, after which logging stopped.--### 3.2 Reproduction 2--- App PID: `46188`-- Meeting start: `06:57:15.100`-- Aggregate devices appeared by `06:57:15.406`:- - `CADefaultDeviceAggregate-46188-0`- - `VPAUAggregateAudioDevice-0xaab760040`-- The prepared direct dictation capture again invalidated on the same three format properties and- scheduled route-recovery generations 1–3.-- Meeting microphone and application models finished warming, after which logging stopped.--The second incident followed a clean app restart and reproduced the same stack and event order.--### 3.3 Identical main-thread stack in both incidents--```text-com.apple.main-thread- __DeviceIsAliveListener_block_invoke AVFCapture- -[AVCaptureHALDevice _refreshConnectionID:KVONotify:]- -[AVCaptureHALDevice _removePropertyListeners]- AudioObjectRemovePropertyListener_mac_imp CoreAudio- HALObject::RemovePropertyListener- CADeprecated::CAGuard::WaitFor- _pthread_cond_wait-```--### 3.4 Concurrent HAL notification stack in both incidents--```text-HALC_ProxyNotification Call Listener Queue- HALC_ProxyNotifications::CallListener- HALC_ShellPlugIn::ProxyObject_PropertiesChanged- HALSystem::AudioObjectsPublishedAndDied- HALSystem::ObjectsPublishedAndDied- HALDevice::Teardown- HALObject::PropertiesChanged- _dispatch_sync_f_slow- __DISPATCH_WAIT_FOR_QUEUE__-```--This proves two permanently parked threads during device teardown/listener removal and is strongly-consistent with a circular wait. It does not reveal HAL's synchronous target queue, prove the complete-wait-for cycle, or identify any FluidVoice callback as a participant.--### 3.5 Rebase/regression timeline--- The meeting branch's pre-rebase tip was `d5b998a` on 2026-08-19 12:00 PDT. It already contained the- VPIO meeting commits, including Phase 3 from 2026-08-17 and later route-following work.-- The recorded rebase began on 2026-08-19 12:50 PDT by checking out `origin/main` at `6f0684e`; it- completed at `1f9af82`, followed by reconciliation commit `a029a69`.-- The old meeting branch and rebased upstream share base `8d140fc` from 2026-08-05. Therefore- `8d140fc..6f0684e` is the relevant upstream delta introduced underneath the meeting work.-- That upstream delta changed approximately 1,400 lines across `ASRService.swift`,- `AudioDeviceService.swift`, and `DirectCoreAudioInput.swift` and contains a concentrated series of- microphone-priority, liveness, prewarm-handoff, and Bluetooth recovery changes.-- The user reports meeting start did not freeze before the rebase. Its denominator, exact installed- revision, macOS version, and route are currently unknown, so it establishes a regression lead—not a- negative experimental result. Both revisions must be exercised in the same harness and hardware/OS- configuration.-- Reconciliation commit `a029a69` changed only file-transcription code and tests, not ASR, Core Audio,- or meeting capture. It remains part of the post-rebase comparison revision but is not a direct audio- source-change candidate.--### 3.6 Candidate commit analysis--| Confidence | Commit | Change introduced by rebased upstream | Relevance to this freeze |-| --- | --- | --- | --- |-| Medium-high / unconfirmed rebase-introduced suspect | `2dce5cd` — `fix microphone priority routing` | Adds `DeviceIsAlive` listeners on main to **every enumerated input**, with no virtual/aggregate exclusion. A device-list callback reconciles the ledger and removes vanished-device listeners on main. The large commit also changes selection and recovery. | VPIO creates/removes transient inputs; both freezes end in device-liveness listener removal during teardown. This is the closest new FluidVoice source-level match, but the sampled waiter is AVFoundation-owned. |-| Medium / co-dependent amplifier | `03a0cfd` — `fix cache microphone liveness off main` | Moves the first query off main, but makes availability callbacks enumerate and query liveness for every input during topology churn, retains listener add/remove/delivery on main, and adds liveness-driven ASR recovery. | Adds HAL property reads and recovery reactions at the incident boundary. It is not a complete listener-lifecycle mitigation. |-| Medium / co-dependent amplifier | `3e04401` — `fix isolate microphone availability updates` | Adds a separate availability tick and a `ContentView` reaction that refreshes input liveness and reconciles microphone selection on availability/default-input changes. | Adds another churn-driven HAL enumeration/reconciliation consumer. It depends on the availability events introduced by `2dce5cd`, so tests must isolate both the listener ledger and its consumers. |-| Low–medium | `9417cfc`, `405e033`, `77f3573`, `d3f9461`, `9d27956`, `c9eece6`, `7d780f4`, `3789b79` | Expands and hardens Bluetooth/device route-recovery behavior. | Can increase work scheduled after VPIO topology changes. Logs show recovery requests, but not that recovery execution entered the captured wait. |-| Low / negative control | direct Core Audio prewarm and its lifecycle controller | Already existed before common base `8d140fc`; it was not introduced by the rebase. | Still overlaps meeting start and must be quiesced architecturally, but timing alone no longer makes it the leading regression trigger. |--The pre-rebase tip contains none of `inputAvailabilityListenerTokens`,-`listInputDevicesRefreshingLiveness`, or `cachedInputLivenessByUID`; the post-rebase revision contains-all three. Older global ASR/default-device listeners **and** ASR's main-queue per-device-`DeviceIsAlive` listener for the single monitored microphone existed before the rebase. The regression-claim is therefore narrow: the newly introduced **all-input reconciliation that can attach listeners-to transient virtual/aggregate devices**, plus its new recovery reactions, is suspect—not the general-existence of `DeviceIsAlive` on main and not every Core Audio or multi-device change.--### 3.7 Phase 0 shipped-path isolation results--All rows used the same bundle ID, Team ID, designated requirement, installed `/Applications` path,-diagnostics, and current meeting path. The flags are DEBUG-only and are not production fixes.--| Row | Variable changed | Result | Interpretation |-| --- | --- | --- | --- |-| Baseline | Current microphone catalog and full all-input liveness ledger | Frozen | Reproduced the incident with the two-thread wait above. |-| Catalog isolation | Replaced AVFoundation microphone discovery/default lookup with the Core Audio catalog; retained the ledger | Frozen | AVFoundation catalog removal is not sufficient. The trace contains no discovery/default events before VPIO, yet the identical wait remains. |-| Ledger isolation | Held catalog isolation constant; omitted only `AudioHardwareObserver`'s rebase-introduced all-input `DeviceIsAlive` ledger | Normal dictation and three meeting cycles passed | Strongly supports the ledger as an inducing participant, but removes more behavior than a production fix should. |-| Transient-input isolation | Restored physical-device ledger listeners; excluded aggregate, virtual, and unknown transports | Normal dictation and three meeting cycles passed | Narrows the inducing surface to transient-style transports while preserving physical multi-device behavior. |-| Aggregate-only isolation | Restored the normal AVFoundation catalog and retained all non-aggregate transports; excluded only aggregate transports from the broad ledger | Normal dictation and three meeting cycles passed | This is the narrowest passing production-shaped row and the basis of the shipped policy. |--The successful traces completed microphone authorization, VPIO enable, input binding, engine prepare,-and engine start. The frozen rows attached the broad `DeviceIsAlive` ledger to persistent inputs and-then to VPIO aggregate inputs. The aggregate-only trace excluded those aggregate attachments while-retaining physical attachments, the normal catalog, and the active meeting detector. That detector's-separate `DeviceIsRunningSomewhere` ledger remained active—including on aggregate IDs—and the run still-passed; this is evidence that the observed failure is selector/ownership-path specific, not that every-main-queue Core Audio listener is sufficient to freeze. A scoped run executed 185 tests with zero-failures and one expected opt-in hardware skip. The Release configuration also compiled successfully.--Adversarial review of the production diff found the predicate, token-removal ordering, Release-reachability, and dictation-preservation boundary sound. Kimi K3 approved. Claude Opus requested the-evidence wording and detector configuration be made explicit; both are addressed above. Review also-agreed that dedicated off-main listener lifecycle ownership remains mandatory follow-up hardening.-Three clean cycles justify this narrow mitigation after a reproducible incident and controlled A/B,-but do not satisfy the 2,995-cycle statistical gate defined later in this document.--## 4. What is proven, inferred, and still unknown--### Proven--- `MeetingSessionCoordinator` acquires `.meeting` through `AudioActivityArbiter`, but the lease only- updates ASR state fields. It performs no audio-backend handoff- (`MeetingSessionCoordinator.swift:31-67`, `ASRService.swift:246-264`).-- Startup leaves a prepared direct Core Audio dictation backend and its format listeners alive- (`ASRService.swift:1471-1510`, `DirectCoreAudioInput.swift:1207-1354`).-- Neither idle prewarm nor route recovery is suppressed by the active meeting lease- (`ASRService.swift:880-1007`, `ASRService.swift:3368-3613`).-- Meeting capture calls `input.setVoiceProcessingEnabled(true)`, the observed boundary that creates VPIO audio- topology, while the prepared dictation backend is still present- (`MeetingMicrophoneCapture.swift:637-692`).-- VPIO topology changes invalidated the prepared dictation capture in both incidents and caused three- ASR route-recovery requests.-- Multiple FluidVoice services independently add and remove Core Audio listener blocks on- `DispatchQueue.main`. At the initial VPIO boundary, the active sets include- `AudioHardwareObserver`, ASR device monitoring, and meeting auto-detection. Meeting microphone and- output-route monitoring use the same unsafe pattern elsewhere, but are installed only after VPIO- microphone startup and therefore cannot trigger this initial-start incident.-- The online-meeting configuration enumerates microphones through- `AVCaptureDevice.DiscoverySession` before VPIO begins- (`MeetingCaptureEngine.swift:1257-1284`).-- The installed build predates the meeting-overlay changes. Relevant microphone/VPIO/ASR code has no- current working-tree diff, so the overlay implementation is excluded from the causal path.-- Runtime logs prove `MeetingAutoDetector` was active in the second incident build even though its- source is currently untracked. Repository `HEAD` alone is not evidence of installed-build contents.--### Strongly inferred--- Aggregate-device publication/death causes HAL to deliver a main-queue device event. AVFoundation's- liveness handler removes its HAL listeners while HAL teardown synchronously waits for listener- delivery. This is the leading wait-cycle hypothesis, not a proven closed graph.-- Main-queue listener concentration and concurrent ASR invalidation/recovery enlarge the hazardous- topology window. They are architectural contributors even if one Apple-internal AVFoundation- listener is the immediate deadlock participant.-- Ephemeral AVFoundation discovery before VPIO causes AVFoundation to materialize audio-device- objects whose lifecycle overlaps the VPIO aggregate-device transition.-- AVFoundation may retain HAL device objects/listeners after the local discovery session is released;- the captured AVFCapture stack makes this plausible, but only the ephemeral-versus-retained Phase 0- rows can establish the lifetime.-- The rebased `2dce5cd` per-input listener ledger is the highest-priority new FluidVoice regression- suspect, co-equal with the pre-existing AVFoundation/VPIO hypothesis rather than ranked above it.- Its main-queue removal of `DeviceIsAlive` listeners is activated by the same transient VPIO device- churn seen in both incidents and was absent from the pre-rebase meeting branch.-- The later liveness/priority recovery work can widen or repeat the hazardous topology window, but the- logs do not yet show it beginning a rebuild before the freeze.--### Not yet proven--- The exact dispatch queue targeted by `HALObject::PropertiesChanged` in the private Core Audio frame.-- Whether AVFoundation discovery plus VPIO alone reproduces the deadlock in a minimal process.-- Whether removing idle direct prewarm alone changes reproduction frequency. That experiment would- isolate an amplifier, not establish a sufficient production fix.-- Whether this is a macOS 26.5.1 framework regression. FluidVoice must remove its unsafe concurrency- regardless; a minimal reproduction and sysdiagnose should be submitted to Apple if it persists.-- Whether a scheduled ASR route-recovery task began executing before the deadlock. The logs prove- three requests were created and that direct-listener invalidation/drain ran; they do not prove the- debounced recovery reached its rebuild phase before the main thread stopped.-- Whether an older recovery request was still sleeping or executing when reproduction 1 began. Its- generations 11–13 show prior route events but not the state of generation 10 at meeting start.-- Absence of later app log lines is not proof that background work never began: user-facing logging- commonly hops through main-actor state, which was already blocked.-- Whether `d5b998a` remains non-hanging under the same macOS, device route, permissions, and repeated- cycle count, and whether adding `2dce5cd` alone makes it hang.-- Whether the necessary additional participant is the new FluidVoice listener ledger, pre-existing- AVFoundation device materialization, or their combination. The sampled `DeviceIsAlive` callback is- AVFoundation-owned, and the pre-rebase meeting path already used discovery and authorization APIs.--## 5. Observed sequence and competing causal hypotheses--```text-Startup- -> ASR prepares DirectCoreAudio input and installs format listeners- -> global ASR, hardware, and meeting-detection listeners remain active--User starts online meeting transcription- -> configuration enumerates AVCaptureDevice microphones- -> logical .meeting lease is acquired, but audio hardware is not handed off- -> meeting enables AVAudioEngine voice processing- -> Core Audio publishes VPIO/default aggregate devices and tears transitional devices down--Observed concurrent reactions- -> direct dictation input receives three format invalidations- -> ASR invalidates its prepared backend and schedules idle route recovery- -> device observers enumerate devices and add/remove per-device listeners- -> AVFoundation receives device-liveness changes for its HAL device objects--Permanent wait- -> main queue: AVFoundation removes a HAL listener and waits in Core Audio- -> HAL notification queue: device teardown waits in dispatch_sync- -> neither advances across either sample; the UI freezes permanently-```--Three hypotheses fit that sequence and must be isolated:--1. **AVFoundation/VPIO:** AVFoundation audio-device materialization alone leaves a main-queue liveness- listener that deadlocks with VPIO aggregate teardown. If reproduced, removing AVFoundation catalog- work from the VPIO path is curative; FluidVoice listener/coordinator work is defense-in-depth.-2. **FluidVoice main-queue listeners:** HAL is synchronously targeting main because a FluidVoice- registration is delivered there while main is already inside listener removal. The closest source- match is `AudioHardwareObserver.replaceInputAvailabilityListeners`, which removes and adds- `DeviceIsAlive` listeners from main during device-list reconciliation. This exact per-input path was- introduced by upstream commit `2dce5cd` and was absent before the rebase. Auto-detection performs- the same class of main-queue per-device reconciliation for `DeviceIsRunningSomewhere`.-3. **Prepared dictation overlap:** direct prewarm or recovery is necessary to create the teardown- ordering. The direct backend already uses dedicated queues and completed its recorded listener- drain, so current evidence makes it an ownership violation and likely amplifier—not the leading- immediate participant.--## 6. Root-cause statement--### Confirmed incident mechanism--VPIO aggregate-device publication/teardown overlaps an AVFoundation device-liveness callback on main.-The callback blocks removing HAL listeners while HAL teardown blocks in a synchronous dispatch. The-unresolved target queue prevents claiming the exact closed wait graph.--### Proven architectural root hazard--FluidVoice has no single owner for process-wide audio-topology transitions, and it delivers/removes-multiple Core Audio listeners on main. Its exclusive-activity model arbitrates user operations but not-hardware lifecycle. Consequently, listener reconciliation, dictation prewarm/recovery, AVFoundation-device materialization, and meeting VPIO transitions are permitted to overlap. Phase 0 must determine-which of these permitted overlaps closes this incident's wait cycle.--### Highest-priority rebase-introduced FluidVoice suspect--The strongest new-FluidVoice-source regression explanation is the interaction introduced by rebasing the-reportedly non-freezing meeting VPIO path onto the new multi-device dictation observer from-`2dce5cd`:--```text-VPIO publishes/destroys aggregate input devices- -> system device-list listener fires on main- -> FluidVoice enumerates the new list off-main- -> FluidVoice returns to main and removes DeviceIsAlive listeners for vanished devices- -> removal overlaps HAL/AVFoundation teardown at the captured freeze boundary-```--This explains the timing and source-level operation without claiming the unobserved final wait edge.-It does not outrank the AVFoundation-retention hypothesis by direct stack evidence: the captured-callback is AVFoundation-owned, and AVFoundation discovery existed pre-rebase. The new ledger may be-the missing sync-edge participant, a timing amplifier, or incidental; only the isolation rows decide.-The proper fix is not to special-case VPIO device names or add delay; it is to establish off-main,-stable listener ownership and suppress reconciliation during topology transitions. The diagnostic-matrix below must first establish whether that slice alone removes the incident.--### Contributing conditions--1. Core Audio listener ownership is duplicated across at least five services. Three pre-existing- listener owners are active at the initial VPIO boundary; the later-installed meeting listeners are- additional architectural debt, not the temporal trigger for these two incidents.-2. Many listeners use the main queue directly; some callbacks query Core Audio or add/remove listeners- from that same delivery queue. `AudioDeviceService.swift:621-658` is the closest FluidVoice-owned- structural match to the captured removal wait.-3. Route recovery does not respect `.meeting` exclusivity.-4. Meeting auto-detection continues monitoring FluidVoice's own audio-device changes during capture.-5. Microphone selection combines two identity systems—Core Audio UID and- `AVCaptureDevice.uniqueID`—and eagerly invokes AVFoundation even for the VPIO primary path.-6. Configuration is resolved before the meeting lease, then the microphone is enumerated again inside- the VPIO transition.-7. `MeetingMicrophoneCapture.start` calls `AVCaptureDevice.authorizationStatus(for:)` immediately- before VPIO, despite an existing source comment that this API activates AVFCapture/Core Audio.--## 7. Rejected patch fixes--The following may alter timing but do not establish safe ownership:--- adding a sleep/debounce before or after `setVoiceProcessingEnabled(true)`;-- retrying meeting start after a timeout;-- adding only `guard activeExclusiveActivity != .meeting` to one recovery call;-- disabling only startup prewarm;-- moving only the listener seen in the current stack off main;-- catching the VPIO error or falling back after a deadline—the main thread cannot execute fallback- once deadlocked;-- killing and restarting the app automatically;-- permanently disabling voice processing without evaluating the capture-quality contract.--These are rejected because other listeners and topology owners would remain able to recreate the same-class of race.--## 8. Required invariants--The final architecture is complete only when these invariants are enforced in code and tests. The-Phase 0 decision matrix determines which subset is curative for BUG-001 and therefore must land first.--1. **Single topology writer:** exactly one coordinator owns prepare/start/stop/destroy operations for- dictation Core Audio, meeting VPIO, and recovery transitions.-2. **True handoff:** `{dictation prepared/running/recovering}` and- `{meeting preparing/recording/switching/stopping}` never overlap. Meeting admission while dictation- is active is rejected without preempting or discarding the current utterance; the user may retry- after dictation completes.-3. **Transition suppression:** hardware events received during meeting start, stop, or backend switch- are coalesced as a dirty snapshot; they cannot start recovery, prewarm, or listener reconfiguration.-4. **No FluidVoice HAL work on main callbacks:** FluidVoice Core Audio callbacks do constant-time event- capture only. They do not query Core Audio, add/remove listeners, mutate observable UI state, or- synchronously cross queues. FluidVoice cannot enforce this inside AVFoundation, so AVFoundation- materialization must not overlap VPIO transitions.-5. **Stable listener ownership:** every listener has one owner, a retained registration record, and the- exact same dedicated serial queue argument for matching add/remove. Neither removal nor draining- executes from that listener's delivery queue; both are owned by a separate control executor.-6. **Backend-specific identity and lifetime:** the VPIO path uses a previously selected Core Audio UID.- It does not create an AVFoundation discovery session during topology transition. Before SCK→VPIO,- FluidVoice releases every app-owned AVCapture session/device/discovery object and observes the- topology/listener barrier. If Phase 0 proves AVFoundation retains hazardous process-global objects,- SCK→VPIO upgrade is prohibited in that process; the meeting remains on SCK.-7. **Ordered restoration:** meeting stop fully retires VPIO and waits for topology quiescence before one- reconciled dictation prewarm. It never replays every event received during the meeting.-8. **UI isolation:** MainActor receives immutable topology snapshots and state changes only; it never- owns Core Audio listener delivery.-9. **Backend switches are transitions:** VPIO→SCK downgrade and SCK→VPIO upgrade remain meeting-owned- but pass through the same quiescence, listener, identity, and rollback rules as initial start/stop.-10. **Service reset has one owner:** Core Audio service restart during any transition cannot trigger- independent re-registration in ASR, device monitoring, or meeting capture.-11. **Quarantined failure:** if a HAL call wedges or teardown cannot be proven complete, the state is- `failedQuarantined`, not stable. No capture, listener reinstallation, or prewarm begins until an- explicit audio-service reset or app restart establishes a new generation.-12. **Frozen-main distinction:** `failedQuarantined` is an in-process state only while the main heartbeat- remains alive. An off-main watchdog that observes a dead main loop persists a privacy-safe marker- and VPIO-disable flag for the next launch; it never attempts in-process audio recovery.--## 9. Proposed architecture--### 9.1 `AudioTopologyCoordinator`--After Phase 0 identifies the curative slice, introduce one process-wide actor with an explicit state-machine for every topology-changing backend operation:--```text-stableDictationIdle- <-> stableDictationActive- -> handingOffToMeeting- -> meetingStarting(vpio | sck)- -> meetingActive(vpio | sck)- -> switchingMeetingBackend(vpioToSCK | sckToVPIO)- -> meetingActive(vpio | sck)- -> handingBackToDictation- -> stableDictationIdle--Any state -> rollingBack -> stableDictationIdle | failedQuarantined-```--It owns transition generations and leases. A lease is granted only after the previous owner is fully-quiescent; it is not a Boolean permission flag. In-room SCK microphone capture and online fallback,-downgrade, and upgrade legs are included because they materialize backend-specific audio devices.-`stableDictationActive` rejects meeting admission; it does not preempt the current utterance.--### 9.2 Asynchronous meeting handoff--`beginMeetingCapture` must:--1. close the gate to new ASR prewarm/recovery;-2. reuse `ASRService.cancelAudioRouteRecoveryAndWait()` to cancel and await sleeping or active route- recovery rather than creating a second barrier;-3. stop/invalidate the prepared direct input, remove its listeners on their registered queue, drain- callbacks, and retire any dictation `AVAudioEngine` off the main actor;-4. suspend/coalesce `AudioHardwareObserver`, detector, and legacy listener reconciliation so no- per-device listener add/remove can occur during the transition;-5. snapshot microphone authorization, selected Core Audio UID, and output-route facts before the- transition without `AVCaptureDevice.DiscoverySession`, `.default`, or `.authorizationStatus` in the- VPIO window;-6. grant the meeting topology lease;-7. create/start VPIO on the coordinator's audio-control executor;-8. commit `meetingActive(.vpio)` only after first microphone PCM and application capture are healthy.--If any step fails, rollback runs on the control executor—never main and never a listener queue. Every-step has an observed completion boundary. A deadline reports failure but cannot declare topology safe;-if teardown does not complete, enter `failedQuarantined` and keep all new audio work closed.--### 9.3 Ordered handback--`endMeetingCapture` must:--1. stop sample acceptance;-2. stop application capture and VPIO;-3. remove and drain meeting listeners and release the engine on the audio-control executor;-4. wait until observed topology generations are quiet;-5. take one current device snapshot and reconcile selection;-6. reopen ASR event handling and optionally prewarm dictation exactly once.--A bounded deadline may report a failed transition, but it must not permit two owners to proceed. A-dictation hotkey pressed during handback waits for the same barrier or returns a bounded unavailable-result; it never starts a competing backend.--### 9.4 `AudioHardwareEventHub`--Replace service-local Core Audio listener management with one registration ledger and coalescing hub.-The hub is justified by the need for one dirty-generation boundary during transitions; a generic-broadcast framework is not required:--- one dedicated serial listener queue, never `DispatchQueue.main`;-- one registration ledger for system devices/defaults/service restart and necessary per-device facts;-- callbacks capture property addresses and IDs, then enqueue a coalesced event to the topology actor;-- UI, detector, microphone-selection, and health services subscribe to immutable snapshots;-- auto-detection suppresses or tags FluidVoice-owned capture transitions so it does not react to its- own VPIO devices as evidence of an external meeting.--No listener callback may query additional “necessary per-device facts”; those are read later by the-control executor after the callback returns. I/O-thread properties that Apple documents as synchronously-delivered permit atomic/statistics updates only.--### 9.5 Separate microphone selection from backend binding--Replace the configuration's eager dual-framework lookup with:--- a stable selected microphone value based on Core Audio UID plus display metadata;-- a VPIO binder that resolves the current Core Audio object ID under the topology lease;-- an AVFoundation/SCK resolver invoked only when starting an AVCapture or SCK-microphone backend;-- lazy fallback resolution only after VPIO is fully torn down and topology is quiet.--The online VPIO configuration/catalog path must not call `AVCaptureDevice.DiscoverySession`,-`AVCaptureDevice.default`, or `AVCaptureDevice.authorizationStatus` near the transition. Authorization-is resolved before handoff. If SCK fallback is needed, resolve its required unique ID only after VPIO-teardown is observed complete. Production code does not infer “no aggregate was published” from elapsed-time; it requires a topology-generation observation. Without that observation, fallback follows the-same teardown/quarantine path. Before any SCK→VPIO upgrade, release app-owned AVFoundation objects and-pass the same barrier; if retained AVFoundation state is proven hazardous, do not upgrade in-process.--For ScreenCaptureKit, Apple's SDK header states that `microphoneCaptureDeviceID` is an-`AVCaptureDevice.uniqueID`; that requirement belongs in the SCK adapter, not the shared product model.--## 10. Proof plan before production rollout--### Phase 0 — isolate and instrument--Before production changes, capture one full spindump dispatch-queue section from the frozen app and a-sysdiagnose/Core Audio log window where possible. Resolve HAL's `dispatch_sync` target queue. Build a-minimal signed harness and measure the baseline failure rate for these conditions:--1. VPIO only;-2. main-thread AVFoundation discovery/default lookup followed by VPIO, with ephemeral and retained- discovery-session variants;-3. direct Core Audio prewarm with its existing off-main listeners followed by VPIO and no AVFoundation- catalog (negative control for the prewarm hypothesis);-4. FluidVoice-equivalent main-queue Devices/`DeviceIsAlive` listeners followed by VPIO;-5. AVFoundation discovery plus FluidVoice main-queue listeners followed by VPIO;-6. all current FluidVoice conditions together.--Record main-runloop heartbeat, topology generation, listener owner/queue, VPIO begin/end, and route-recovery scheduled/begin/end separately. Run on macOS 26.5.1 and one other supported OS. For every-stall capture a spindump/sysdiagnose; for every non-stall record the denominator. Choose cycle counts-from the observed baseline. The targeted curative harness gate is a per-start residual hang probability-of at most 0.1% at 95% confidence: with zero failures, this requires at least 2,995 independent cycles.--#### Phase 0B — isolate the rebase regression--Use the same signed diagnostic harness, macOS build, microphone/output route, and meeting-start cycle-for every row. Do not replace the installed production-style debug app with a differently signed-historical build; preserve its privacy grants and run historical variants as isolated harnesses.--1. `d5b998a` pre-rebase meeting implementation on its original audio base;-2. `a029a69` post-rebase implementation before later working-tree overlay/detector changes;-3. a synthetic old-base build containing only the `2dce5cd` per-input availability listener ledger,- without the remainder of that 2,390-line selection/recovery commit;-4. an integration build with full `2dce5cd`, followed by one through `03a0cfd`, then one through- `3e04401`; replay the real intervening commits in order rather than blind cherry-picks that silently- resolve conflicts. These are diagnostic states, not claims about shipped revisions;-5. current path with only the `AudioHardwareObserver` per-input listener ledger omitted while the- `3e04401` default-input/availability consumer remains active;-6. current path with the per-input listener ledger retained while only the `3e04401` availability-tick- consumer is held inactive;-7. current path with the same listener coverage and consumers retained, but delivery on a dedicated- serial listener queue and- add/remove owned by a separate control executor;-8. current path with per-input listeners intact but topology-driven route recovery/prewarm scheduling- suppressed, separating the immediate listener trigger from the recovery amplifier;-9. current path with the `2dce5cd` ledger retained but AVFoundation discovery/default/authorization- removed from the VPIO transition, separating AVFoundation materialization from the new ledger;-10. current path with the ledger retained for physical inputs but transient virtual/aggregate inputs- excluded, while the older ASR monitored-device `DeviceIsAlive` listener remains active as the- pre-rebase baseline.--Rows 1–4 must use an explicitly identical meeting-detector configuration. Prefer two matched blocks:-detector absent, then the incident-equivalent detector present. A negative detector-absent run is not-binding for the incident configuration because the second frozen build had the detector's main-queue-per-device listener owner active even though that source is absent from the historical commit objects.--For each add/remove record registration ID, owner, object ID, selector, delivery queue, control queue,-generation, transport/virtual classification, and monotonic timestamp. Do not record device names.-Correlate FluidVoice token object IDs with the object IDs published and torn down by VPIO; without that-match, do not claim the ledger participated in the incident. Record route-recovery `scheduled`, `began`,-and `ended` separately so a queued request is not mistaken for an executing rebuild.--Start with randomized, interleaved blocks of 100 cycles per row to reduce ordering, thermal, and audio--daemon state bias. Any captured matching freeze rules a row in. Zero failures is only preliminary;-before declaring a suspected condition unnecessary or a fix curative, run at least 2,995 independent-cycles for that row, matching the 0.1%/95% gate above. Record the user's approximate historical-pre-rebase start count if recoverable, but never combine it with controlled harness denominators.--Interpretation:--- Rows 1 versus 2 establish whether the rebase reproduces the regression under controlled conditions.-- If row 1 reproduces the same freeze, the rebase-regression claim is falsified: `2dce5cd` cannot be an- inducing requirement, though later changes may still amplify a pre-existing AVFoundation/VPIO race.-- Row 3 becoming positive identifies the listener ledger as sufficient in the synthetic harness. Row- 4 shows whether the complete commit series changes that result and prevents misattributing another- part of the large `2dce5cd` commit to the ledger.-- Rows 5 and 6 independently distinguish the listener ledger from its UI/reconciliation consumer;- neither is interpreted by removing both variables at once.-- Row 7 becoming negative proves queue/lifecycle ownership is the curative slice rather than merely- deleting multi-device availability support.-- Row 8 affects an amplifier only if the listener rows remain positive while recovery suppression- changes the failure rate.-- Row 9 distinguishes AVFoundation materialization from the ledger on the real integration path.-- Row 10 tests the unique new mechanism—all-input listener attachment to transient objects—without- removing physical multi-device availability or the older single monitored-device baseline.-- A positive minimal AVFoundation-discovery+VPIO row with no FluidVoice per-input ledger falsifies the- ledger as an inducing requirement, even if it remains an amplifier.-- If row 2 is positive but rows 3–4 are negative, automate `git bisect` across the remaining upstream- audio commits using the harness; do not nominate a commit from log messages alone.--Decision gate:--- If condition 1 hangs, quarantine/disable VPIO on the affected OS and use the supported SCK path while- filing the minimal reproduction with Apple. Application-side coordination is not the curative fix.-- If condition 2 hangs but 1 does not, identity/AVFoundation isolation is a curative slice.-- If condition 4/5 hangs but 1 does not, listener migration and transition suspension are a curative- slice. They begin by retargeting the implicated existing owners and moving add/remove to a separate- control executor; they do not wait for the hub.-- Compare condition 3 with condition 1. If prewarm adds hangs or materially worsens the measured rate,- async dictation quiescence is a curative slice.-- If only condition 6 hangs, add combinations until the smallest sufficient trigger is identified.-- If multiple isolation rows hang independently, Phase 1 is the union of every positive row's curative- slices. Re-run every positive row and their combination after each slice; a lower rate is not a pass.-- If no harness row reproduces, do not guess a curative fix or enable VPIO broadly. Escalate to the- instrumented in-app path/device matrix, ship the two proven hazard repairs (off-main listener- discipline and transition suppression) behind the VPIO kill switch as defense-in-depth, and keep- VPIO disabled on the affected OS until the shipped-path gate is met.--### Phase 1 — curative slice selected by Phase 0--Implement only the smallest change that Phase 0 proves removes the trigger: AVFoundation isolation,-off-main listener ownership, or dictation quiescence. Re-run the same isolation condition before-combining architectural changes. Keep a kill switch for the VPIO path so rollback does not require a-new build; never use the switch to bypass incomplete teardown. This phase may retarget existing listener-owners directly and must not wait for the hub/ledger architecture.--### Phase 2 — listener discipline and transition suspension--Move all FluidVoice Core Audio listener delivery off main, prohibit add/remove from the delivery queue,-and suspend per-device reconciliation across start/stop/switch. Migrate one complete owner at a time;-never leave an owner half hub/half legacy. Both listener add and remove paths get runtime diagnostics.--### Phase 3 — real topology ownership and handoff--Add the coordinator state machine and dependency protocols. Make meeting acquisition async: suppress-events, reuse the existing cancel/drain barrier, retire prewarm, then start VPIO. Cover start, stop,-VPIO↔SCK backend switches, service restart, cancellation, and quarantined failure. Reverse the sequence-before exactly one dictation reconciliation/prewarm.--### Phase 4 — identity/backend separation--If not already selected as Phase 1, remove AVFoundation discovery/default/authorization calls from the-online VPIO transition. Resolve AVFoundation IDs only inside in-room or SCK adapters after topology-handoff. Test device replacement where an object ID changes but the Core Audio UID remains stable.--### Phase 5 — system validation and rollout--- statistically justified automated start/stop cycles with idle prewarm and detector enabled;-- input/output matrix: built-in, USB, Bluetooth, and mismatched input/output routes;-- device disconnect, default-route change, sleep/wake, and audio-service restart during every state;-- Zoom desktop, Google Meet in Chrome, and Teams desktop while application audio is active;-- main-runloop stall budget and zero overlap assertions from signposts;-- two-hour meeting soak followed by successful dictation handback;-- fallback and rollback verification with no permission/signing changes.-- forced VPIO→SCK downgrade and dwell-based SCK→VPIO upgrade under Bluetooth/output-route changes;-- hotkey input during post-meeting handback and `failedQuarantined` behavior;-- own VPIO activity produces no meeting-detection prompt;-- listener ledger count returns to baseline after selected-microphone unplug and service restart.-- a privacy-safe off-main main-runloop watchdog is active at meeting start/stop/switch boundaries and- persists only phase/generation/timing plus a next-launch VPIO-disable marker; it records no audio,- transcript, meeting title, device name, or application/window title.--## 11. Acceptance criteria--- No main-thread hang on any shipped capture path. A VPIO-only harness hang is an acceptable diagnostic- outcome only when VPIO is disabled on that affected OS and the shipped SCK path passes its gates.-- Every Phase 0-positive targeted harness row has zero failures in at least 2,995 independent post-fix- cycles, bounding per-start hang probability to at most 0.1% at 95% confidence; the real-device matrix- additionally has zero hangs in at least 100 cycles per representative route.-- Runtime instrumentation reports no FluidVoice Core Audio listener add **or remove** using- `DispatchQueue.main`, and no removal from its listener's delivery queue.-- No ASR prewarm or route-recovery start while the topology coordinator is meeting-owned.-- At most one coalesced dictation reconciliation after meeting handback.-- Meeting start or backend switch either commits healthy capture or returns a bounded error after- fully observed rollback; incomplete teardown enters `failedQuarantined` and does not reopen audio.-- Dictation behavior before and after a meeting passes its existing integration tests and real-device- smoke matrix.-- Instrumentation proves zero overlap among dictation prepared/running/recovering and meeting- preparing/recording/switching/stopping states using matched interval signposts checked by tests.-- The production off-main heartbeat records a next-launch quarantine marker when main stalls during an- audio transition and never attempts recovery from the frozen process.--## 12. Apple documentation basis--- [`AudioObjectAddPropertyListenerBlock`](https://developer.apple.com/documentation/coreaudio/audioobjectaddpropertylistenerblock%28_%3A_%3A_%3A_%3A%29)- retains the supplied dispatch queue until matching removal and documents asynchronous delivery except- for I/O-context properties.-- [`AudioObjectRemovePropertyListenerBlock`](https://developer.apple.com/documentation/coreaudio/audioobjectremovepropertylistenerblock%28_%3A_%3A_%3A_%3A%29)- requires the queue on which the listener was dispatched, supporting an explicit registration ledger.-- [`setVoiceProcessingEnabled`](https://developer.apple.com/documentation/avfaudio/avaudioionode/setvoiceprocessingenabled%28_%3A%29)- is the supported AVAudio I/O-node boundary for enabling voice processing.-- [`AVCaptureDevice.DiscoverySession`](https://developer.apple.com/documentation/avfoundation/avcapturedevice/discoverysession)- materializes the currently available capture devices and can monitor device-list changes.-- [`SCStreamConfiguration`](https://developer.apple.com/documentation/screencapturekit/scstreamconfiguration)- supports microphone capture. The installed SDK's `SCStream.h` specifies that- `microphoneCaptureDeviceID` is an `AVCaptureDevice.uniqueID`.--## 13. Review status--Initial independent verdicts were all **REVISE**:--- Fireworks Kimi K3 through OpenCode: `REVISE`;-- xAI Grok 4.6: the Orchestrate route failed before producing analysis; a direct Grok 4.6 continuation- then returned `REVISE` without modifying files;-- Claude Opus 5 through Orchestrate: `REVISE`.--### Consensus accepted--- Two parked stacks are consistent with, but do not prove, a closed circular wait. Resolve HAL's sync- target before naming the final cycle.-- Direct prewarm invalidation and scheduled recovery prove an ownership gap, not participation in the- observed wait. The direct lifecycle's dedicated listener/control queues are a pattern to preserve.-- FluidVoice's per-device listener add/remove on main is the strongest app-owned participant hypothesis- and must be isolated before building a coordinator around an assumed cause.-- AVFoundation identity/materialization can be the whole trigger; the VPIO path must be tested without- it, and authorization lookup inside `MeetingMicrophoneCapture.start` must leave the transition.-- Phase order must follow the isolation result. “Coordinator first” was removed.-- Backend switches, service restart, incomplete rollback, Bluetooth behavior, detector self-activity,- and post-meeting hotkeys require explicit topology states and tests.--### Review disagreements resolved--- One review inferred that auto-detection was absent because its source is untracked and absent from- repository `HEAD`. That inference is rejected: the second incident's installed-app log explicitly- records `MeetingAutoDetector detector-started` before the freeze. It remains an active incident-build- listener owner. The installed build predating the later overlay work does not imply it predates the- detector work.-- Reviewers differed on whether a global hub/coordinator is oversized. This revision makes the curative- BUG-001 slice evidence-dependent and narrows the hub to a registration ledger plus transition-event- coalescer. The full topology state machine remains required for the already-existing VPIO↔SCK switch- paths, but it is not allowed to delay the Phase 0-proven curative change.--### Final gate and closure--The first post-revision gate returned Kimi `APPROVE`, Opus `APPROVE` with five blocking clarifications,-and Grok `REVISE`. The final clarifications are incorporated:--- AVFoundation object/listener retention moved from proven to inferred;-- the decision gate now handles multiple positive rows and zero reproduction;-- the Phase 1 listener slice explicitly does not wait for a hub;-- SCK→VPIO requires app-owned AVFoundation release plus an observed barrier and can be prohibited- in-process when retained framework state is hazardous;-- `stableDictationActive`, next-launch quarantine for a dead main loop, a production off-main watchdog,- and numerical statistical gates are defined.--Grok's final closure review returned **APPROVE** with no remaining implementation blockers. Final-review state: **Kimi APPROVE, Opus APPROVE, Grok APPROVE**.--### Rebase-regression addendum review--The later rebase analysis initially returned **REVISE** from both Kimi K3 and Grok 4.6. Their accepted-corrections demote `2dce5cd` from a claimed trigger to an unconfirmed rebase-introduced suspect, keep-AVFoundation+VPIO co-equal, add `3e04401`, split the ledger from its consumer, control detector state,-require token-to-dying-object correlation, add transient-device exclusion, and define statistical and-falsification gates. Claude Opus was not rerun for this addendum because the current repository-disclosure policy/tool gate permits relevant source and diffs only to Kimi and Grok; the previous Opus-approval applies to the base RCA, not this addendum.--After those corrections, the final rebase-addendum gate returned **Kimi APPROVE** and-**Grok APPROVE**, with no remaining regression-analysis blockers.--### Production mitigation closure--Subsequent Phase 0 rows isolated aggregate membership in `AudioHardwareObserver`'s broad-`DeviceIsAlive` ledger as the narrowest passing condition. The production implementation now filters-only `kAudioDeviceTransportTypeAggregate` before both the ledger's removal set and add loop. It is-unconditional in Debug and Release; diagnostic flags are not required. Non-aggregate monitoring,-system/default-device listeners, liveness queries, and ASR's selected-device listener remain unchanged.--Final validation completed:--- normal dictation and three meeting start/stop cycles passed on the production-shaped A/B build;-- 185 scoped meeting/dictation/diagnostic tests passed, with one expected opt-in hardware skip;-- the Release configuration and canonical Apple-signed Debug build both compiled successfully;-- Kimi K3 and Grok 4.6 approved the scoped production policy; Claude Opus's requested evidence wording- and detector-provenance corrections are incorporated here; and-- the installed `/Applications/FluidVoice Debug.app` retained the same bundle ID, Team ID, Apple- Development identity, and designated requirement, and passed strict deep signature verification.--This closes the reproducible incident with an evidence-scoped mitigation. It does **not** close the-entire private HAL deadlock class or satisfy the 2,995-cycle statistical reliability gate. Dedicated-off-main Core Audio listener lifecycle ownership, live USB/Bluetooth/iPhone hot-plug acceptance, and-the long-run reliability gate remain explicit follow-up work.diff --git a/MEETING_CALENDAR_INTEGRATION_PLAN.md b/MEETING_CALENDAR_INTEGRATION_PLAN.mddeleted file mode 100644index f07e9588..00000000--- a/MEETING_CALENDAR_INTEGRATION_PLAN.md+++ /dev/null@@ -1,496 +0,0 @@-# Local Calendar Meeting Reminder Plan--**Status:** Deferred / ready for implementation planning-**Last revised:** 2026-08-22-**Product direction:** Local-first EventKit integration with FluidVoice in-app reminders first. System notifications are a later phase after dogfooding.--## 1. Objective--Add an optional local calendar integration that reads meeting events already available through macOS Calendar and reminds the user through FluidVoice's existing in-app notification surfaces.--The first release does not use OAuth, a sync backend, meeting bots, automatic recording, or macOS system notifications. Calendar data is context for reminders and later post-confirmation metadata; it is never evidence that independently creates or confirms a live meeting episode.--### Initial user flow--1. The user enables **Calendar meeting reminders** in Meeting Settings.-2. FluidVoice explains why macOS labels the permission as Full Access even though FluidVoice performs no calendar writes.-3. FluidVoice activates its Settings window and requests EventKit access.-4. The user selects calendars. Nothing is selected automatically.-5. FluidVoice fetches eligible meetings from those calendars.-6. At approximately one minute before an eligible meeting, FluidVoice shows its nonactivating reminder HUD.-7. The reminder offers:- - **Join** — revalidate and open the conference URL.- - **Prepare** — open Meeting setup with an ephemeral title seed; never start recording.- - **Not now** — suppress only that occurrence.-8. After 20 seconds, an unhandled HUD collapses into an actionable Upcoming Meetings section in the existing FluidVoice menu.--## 2. Non-negotiable invariants--1. Calendar access is optional and off by default.-2. FluidVoice never writes through EventKit.-3. Calendar data never creates or confirms a `MeetingAutoDetector` episode.-4. Calendar data never changes live-detection thresholds or confidence.-5. No calendar path calls recording or capture-configuration APIs.-6. Exact PID/window capture targeting remains unchanged.-7. Denied, revoked, unavailable, stale, or malformed calendar data cannot reduce existing live-detection behavior.-8. EventKit objects remain inside one serialized provider and never escape into the application.-9. Calendar event payloads are not cached on disk in v1.-10. Titles, notes, locations, raw URLs, meeting codes, passcodes, and attendees never enter logs or analytics.-11. No new status item is introduced; reminders use the existing FluidVoice HUD and menu.-12. No meeting-related `UNUserNotificationCenter` permission, category, or request is introduced before the in-app dogfood gate passes.--## 3. Apple platform constraints--- EventKit has no read-only authorization. Reading events requires `requestFullAccessToEvents()` and `NSCalendarsFullAccessUsageDescription`, even when application code never writes.-- Sandboxed macOS apps require the calendar entitlement. FluidVoice is currently not sandboxed, so the entitlement should not be added until App Sandbox is actually enabled.-- `events(matching:)` is synchronous and must not run on the main actor.-- `EKEventStoreChanged` means previously fetched objects may be stale. Refetch the current range and replace the complete snapshot set.-- Do not automatically call `EKEventStore.reset()` for store-change notifications. Apple documents `reset()` as reverting unsaved state and invalidating store-created objects; notification guidance requires a refetch.-- Event and calendar identifiers can change after synchronization or account removal/re-add. They are hints, not permanent primary keys.-- A predicate with `nil` calendars searches every calendar. FluidVoice must skip the fetch entirely when zero selected identifiers resolve to calendars.--Primary references:--- [Accessing the Event Store](https://developer.apple.com/documentation/eventkit/accessing-the-event-store)-- [Retrieving Events and Reminders](https://developer.apple.com/documentation/eventkit/retrieving-events-and-reminders)-- [Updating with Notifications](https://developer.apple.com/documentation/eventkit/updating-with-notifications)-- [`EKEventStore.reset()`](https://developer.apple.com/documentation/eventkit/ekeventstore/reset%28%29)-- [`calendarItemIdentifier`](https://developer.apple.com/documentation/eventkit/ekcalendaritem/calendaritemidentifier)--## 4. V1 product policy--### Eligible meeting--An event is eligible when all of the following are true:--- It belongs to a resolved, user-selected calendar.-- It is timed and not all-day.-- It is not canceled.-- Its duration is between 5 minutes and 8 hours.-- A directly validated conferencing HTTPS URL is found in `event.url`, location, or notes.-- The current user has not explicitly declined, when that state can be reduced to a transient Boolean without retaining the roster.--Tentative events remain eligible. Attendees, organizer, busy/free state, and attendee count are not required.--### Reminder window--- Opens at `start - 60 seconds`.-- Closes at `start + 2 minutes`.-- The actionable menu entry remains available until `event end + 2 minutes`.-- Ending a recording after the event start never triggers a catch-up HUD; the event remains menu-only.--### Calendar selection--- Permission grant selects zero calendars.-- The picker appears immediately after grant.-- Missing or re-added calendar identifiers remain visibly unresolved.-- FluidVoice never silently substitutes all calendars.-- If the resolved selection is empty, no predicate is constructed and no event fetch occurs.--### Sensitive UI--The floating HUD uses generic copy by default, such as **Meeting starts in 1 minute**, with time and provider icon. It does not render the raw event title, reducing accidental disclosure during screen sharing.--The event title may appear in the explicit Upcoming Meetings UI/menu and Prepare flow. It becomes ordinary persisted meeting metadata only after the user explicitly starts or saves a meeting.--## 5. Target architecture--```text-EventKitCalendarProvider- |- v-LocalCalendarEventSnapshot[]- |- +--> CalendarConferenceLinkParser- |- v-CalendarReminderReconciler- |- +--> CalendarPromptCoordinator --> existing FluidVoice HUD- |- +--> UpcomingMeetingsModel -----> existing FluidVoice menu/settings UI- |- `--> CalendarMeetingCorrelator (later, post-confirmation only)-```--### Proposed responsibilities--#### `EventKitCalendarProvider`--- Own exactly one long-lived `EKEventStore`.-- Serialize every store operation.-- Request permission on the main actor.-- Run event predicates off-main.-- Convert EventKit objects immediately into immutable `Sendable` snapshots.-- Check authorization before and after a fetch.-- Discard a result if authorization changed during the fetch.-- Replace snapshots wholesale rather than merging framework objects.--#### `LocalCalendarEventSnapshot`--V1 fields:--- Volatile local/external identity hints.-- Selected calendar identifier.-- Sensitive, non-`Codable` title value with redacted textual description.-- Start and end dates.-- All-day and canceled flags.-- Transient `isCurrentUserDeclined` Boolean.-- Normalized provider and meeting identity.-- Ephemeral actionable URL.--No attendee, organizer, notes, location, or raw URL persistence.--#### `CalendarConferenceLinkParser`--- Pure and independently testable.-- Scan `event.url`, location, then notes; continue past non-meeting URLs.-- Bound the number of notes bytes inspected.-- Extract bounded HTML `href` candidates where necessary.-- Accept direct provider HTTPS URLs only in v1.-- Reject redirect wrappers, userinfo, non-HTTPS schemes, non-ASCII hosts, malformed hosts, and incorrect subdomain boundaries.-- Share a data-driven provider host table with live detection while keeping invite and strict in-call policies separate.-- Preserve existing `MeetingInCallURLMatcher` results exactly.--#### `CalendarReminderReconciler`--Derive reminder state rather than incrementally mutating independent timers:--```text-snapshots- -> eligible occurrences- -> desired HUD/menu state- -> reconcile against presented/terminal aliases-```--- Use an injected clock.-- Use one rescheduled wall-clock timer for the next reminder boundary, expiry, or fetch horizon.-- Revalidate selection, snapshot, URL, recording state, expiry, and suppression immediately before presentation or action.-- Inspect only existing materialization-safe activity properties; never instantiate the lazy meeting coordinator merely to check recording state.--#### Source-neutral prompt coordinator--Semantic identity is typed:--```swift-enum MeetingPromptIdentity {- case live(LiveEpisodeID)- case calendar(CalendarOccurrenceKey)-}-```--An independent internal presentation token retains async race/cancellation protection.--Calendar and live prompts have separate typed action closures. A calendar code path must be unable to call detector dismissal, timeout, adoption, or start methods.--The coordinator treats both a visible live prompt and the detector's hidden suppression-retrying prompt as live occupancy.--Priority:--1. Active recording.-2. Visible or pending live prompt.-3. Calendar reminder.--Outcomes:--- `acted`-- `dismissed`-- `displaced`-- `collapsed`-- `expired`--## 6. Reminder presentation behavior--### Calendar HUD--- Calendar bypasses bundle/frontmost matching because the meeting application may not yet be running.-- It yields to active recording and active dictation/command overlays.-- It is visible for `min(20 seconds, expiresAt - now)`.-- Hover and accessibility interaction pause the visible countdown without extending the absolute eligibility deadline.-- Accessibility announcements use generic provider/time copy rather than the sensitive title.-- After 20 seconds it collapses into the existing FluidVoice menu.--### Displacement--- Live prompt arrives before calendar becomes visible: no presented alias; calendar may requeue until expiry.-- Live prompt arrives after calendar becomes visible: write/retain the presented alias, collapse calendar to menu, and do not re-show its HUD.-- Calendar presentation never traverses the detector's existing replacement-timeout callback path.--### Wake and restart--- Wake/restart inside the eligibility window with no presented alias: show the HUD.-- Wake/restart after presentation: restore the menu entry, not the HUD.-- Wake after expiry: no HUD.-- If the HMAC secret is temporarily unavailable, fail closed for HUD presentation until it becomes readable; do not generate a replacement secret or rewrite aliases.--### Multiple meetings--- At most one calendar HUD is visible.-- Choose among newly eligible, unpresented occurrences by `(startDate, occurrenceAlias)`.-- If several become eligible in one reconciliation, show one HUD and put the others directly in the menu to avoid a burst.-- Meetings whose windows open later remain independently eligible for their own HUD.--### Existing menu--- Add an independent Upcoming Meetings section; do not reuse or instantiate meeting-session UI state to populate it.-- Derive entries lazily when the menu opens from current snapshots and opaque reminder state.-- Entries expose Join, Prepare, and Not now using the same revalidation pipeline as the HUD.--## 7. Identity and persistence--Use HMAC-SHA256 with a per-install secret stored as `AfterFirstUnlockThisDeviceOnly` and cached once per process.--```text-primary alias = HMAC(- selectedCalendarID- + external/server identifier- + original occurrence date or start- + scheduled UTC start-)--fallback alias = HMAC(- selectedCalendarID- + normalized conference identity- + scheduled UTC start-)-```--Including scheduled start deliberately re-arms a rescheduled meeting.--Rules:--- Generate the secret only on definitive item-not-found.-- On any other Keychain error, enter fail-closed reminder mode.-- Never use raw identifiers as persistent fallback keys.-- Never delete or rewrite stored aliases merely because the secret could not be read.-- Persist a presented alias only once the HUD is actually visible.-- Join, Prepare, and Not now create terminal occurrence state.-- Prune aliases after `event end + 2 minutes + 7 days`.--## 8. Refresh and lifecycle--Fetch range:--```text-now - 5 minutes ... now + 48 hours-```--All refresh triggers feed one coalescing coordinator:--- UI-ready startup.-- Permission or selection change.-- Debounced `EKEventStoreChanged`.-- Application activation.-- Wake/session activation.-- Timezone or system-clock change.-- `lastSuccessfulFetch + 6 hours`.--The six-hour horizon boundary prevents a continuously running Mac from missing meetings that were outside the previous 48-hour fetch range. It is scheduled through the same one-shot timer, not an independent polling loop.--On an EventKit change notification:--1. Treat existing EventKit objects as stale.-2. Refetch the full current range.-3. Convert to new value snapshots.-4. Atomically replace the old snapshot set.-5. Reconcile reminder state.--## 9. Prepare and Join actions--### Prepare--Navigation needs an atomic, memory-only seed:--```swift-case meetingTranscription(seed: EphemeralMeetingSetupSeed?)-```--- Apply only when setup is pristine.-- Never overwrite a visible dirty draft.-- Never write the seed to `SettingsStore`.-- Clear it at event end or after consumption.-- Calendar invokes navigation only; it never invokes recording APIs.--### Join--- Refetch/reconcile current state as necessary.-- Confirm the calendar remains selected.-- Confirm the event remains eligible.-- Reparse and revalidate the URL.-- Open only the validated in-memory URL after the user's click.-- On failure, keep the reminder/menu available with a content-free error; never open a fallback URL.--## 10. Phased implementation--### Phase 0 — Contract and build prerequisites--- Amend the PRD requirements described above.-- Add the calendar usage description.-- Add educational permission UI and activated-window flow.-- Lock privacy and persistence rules.--**Gate:** no EventKit API is reachable without the usage string and explicit user action.--### Phase 1A — Source-neutral HUD--- Introduce typed semantic identity and source-specific callbacks.-- Preserve live prompt behavior exactly.-- Treat visible and suppression-retrying live prompts as occupancy.-- Move detector-invariance Cartesian tests into this phase.--**Gate:** existing live tests retain identical results; calendar identities cannot reach detector APIs.--### Phase 1B — Calendar HUD policy--- Add calendar payload, priority, displacement, collapse, fullscreen-safe generic copy, and in-memory reminder state behind the feature flag.-- Do not introduce EventKit persistence keys here.--**Gate:** fake calendar requests cannot mutate detector state or start recording.--### Phase 1C — EventKit provider and parser--- Add permission/status provider, calendar selection, bounded fetch, snapshots, conference parser, refresh coordinator, and HMAC secret service.--**Gate:** empty resolved selections perform zero event fetches; malicious parser corpus passes; revocation clears UI and snapshots.--### Phase 2 — Upcoming Meetings UI--- Show selected/unresolved calendars, eligible/ineligible events, reasons, last refresh time, and repair actions.-- Add the actionable Upcoming Meetings status-menu section.--**Gate:** users can diagnose permission, selection, freshness, and parser eligibility before reminders are enabled.--### Phase 3 — In-app reminder reconciler--- Add deterministic scheduler, one-shot timer, durable opaque aliases, wake/restart behavior, and HUD/menu coordination.--**Gate:** automated timing/churn suite and real-meeting dogfood criteria below pass.--### Phase 4 — Post-confirmation calendar correlation--Only after reminder dogfood:--- Consume an already-confirmed live candidate plus snapshots.-- Strong match: normalized conference identity.-- Medium match: provider, time overlap, and captured application.-- Title-only or ambiguous: no enrichment.-- Never change detector confidence or exact capture target.--### Phase 5 — System local notifications--Only after Phase 3:--- Request notification permission separately.-- Add deterministic opaque request identifiers.-- Use minimal lock-screen content.-- Add Join and Prepare actions.-- Reconcile pending/delivered requests.-- Refetch and revalidate on action.-- Select exactly one surface: FluidVoice HUD or system notification.--### Phase 6 — Attendee-assisted naming--Separate explicit opt-in:--- Fetch roster only for an unambiguous matched event.-- Reduce and discard raw participant data.-- Require confirmation for every proposed name.-- No cross-meeting voice identity.--## 11. Test strategy--### Detector isolation--Run the Cartesian product of calendar actions against live states:--- No live prompt.-- Visible live prompt.-- Suppression-retrying live prompt.-- Live prompt starting.-- Active recording.-- Dictation/command overlay.--Assert detector episode, consumption, bundle suppression, and dismissal-counter state is identical to the calendar-absent baseline.--### Permission and EventKit--- Feature disabled creates no event store and no TCC prompt.-- Grant followed by zero selection performs no event fetch.-- Denial and restriction.-- Revocation before, during, and after a fetch.-- Account/calendar removal and re-add.-- Empty and unresolved calendar selection.-- Store-change storms and stale-generation cancellation.-- Manual signed Debug and Release TCC matrix.--### Scheduler--- Reminder boundary and expiry.-- 20-second collapse.-- Wake before and after presentation.-- Restart inside and outside eligibility.-- DST fold/gap.-- Timezone and clock change.-- Six-hour fetch horizon.-- Edit, delete, cancel, reschedule, recurring detach, and identifier churn.-- Overlap, equal-start ties, back-to-back events, and several newly due events.-- Recording ends before and after event start.-- Keychain locked, unavailable, item-not-found, and transient error.--### URL security--- Non-HTTPS and custom schemes.-- Userinfo.-- Non-ASCII and malformed hosts.-- Dot-boundary attacks.-- Redirect wrappers.-- HTML notes and scan-size limits.-- Multiple source fields where an earlier value is not a meeting URL.-- Join-time revalidation and stale-link failure.--### Privacy--Run a fixture calendar containing distinctive titles, attendee names, notes, URLs, codes, and passcodes. Capture:--- Logs.-- Analytics payloads.-- UserDefaults.-- Keychain values.-- Meeting setup state before explicit start/save.--Assert that only selected calendar identifiers, opaque aliases, provider enums, and content-free counters persist or leave the calendar subsystem.--## 12. Phase 3 dogfood gate--Use at least 20 real eligible meetings.--- At least 95% of first HUD presentations occur within ±5 seconds of the first schedulable moment.-- Zero calendar-caused detector-state mutations.-- Zero duplicate HUDs in one process lifecycle.-- Zero wake bursts.-- Zero wrong Join targets.-- Zero raw calendar content in logs, analytics, or persistence.-- Correct reminders after reschedule and recurring detach.-- Fetch latency and energy impact recorded using content-free metrics.--Do not begin system-notification work until this gate passes.--## 13. Suggested first implementation slice--Start only with Phase 0 and Phase 1A:--1. Amend the PRD and add the usage description.-2. Add educational permission UI scaffolding without calling EventKit yet.-3. Introduce source-neutral prompt identity and callbacks.-4. Preserve live behavior.-5. Add the detector-invariance interleaving suite.--Do not combine this slice with EventKit fetching or reminder scheduling. Keeping the first change narrow makes any live-detection regression attributable to the HUD refactor.--## 14. Deferred product choices--- Whether users may opt into showing meeting titles in the floating HUD.-- Whether redirect wrappers are common enough in real EventKit data to justify bounded offline unwrapping.-- Whether the six-hour horizon should change after energy measurements.-- Whether overlapping meetings eventually need a chooser rather than menu-only secondary entries.-- Whether system notifications should replace or complement the in-app HUD when FluidVoice is running.diff --git a/MEETING_DETECTION_NOTIFICATION_DESIGN.md b/MEETING_DETECTION_NOTIFICATION_DESIGN.mddeleted file mode 100644index e5ef26da..00000000--- a/MEETING_DETECTION_NOTIFICATION_DESIGN.md+++ /dev/null@@ -1,612 +0,0 @@-# Meeting Detection and Notification Design--Status: proposed-Scope: calendar-independent runtime detection, in-app reminder, and meeting-end assistance-Product posture: local-first, privacy-first, user-initiated recording--## 1. Outcome--FluidVoice should recognize a likely live call quickly enough to prevent a missed transcript, while treating every detection as a suggestion rather than permission to record.--The system must:--- notify only when independent, current signals identify the same application or browser meeting;-- never begin recording without an explicit user action;-- revalidate the meeting and exact capture target when the user acts;-- withdraw a stale reminder when the evidence disappears;-- identify likely meeting end conservatively without automatically stopping by default;-- keep raw URLs, window titles, audio, and detection history on the device;-- remain useful when optional permissions or newer CoreAudio attribution APIs are unavailable.--Calendar events may enrich a candidate later, but are neither required nor authoritative for this design.--## 2. Current implementation--The current detector already has several strong properties:--- Recording is prompt-only and requires an explicit click.-- Native applications and browser meetings use separate tiers.-- A native confirmation requires audio plus a qualifying application window.-- Browser confirmation requires audio plus a fixed meeting-domain/path match.-- Browser URL values and native window titles are not logged.-- Exact application and, when known, window identifiers are passed to capture.-- The detector remains separate from the lazily created recording coordinator.-- Busy recording or dictation state suppresses new reminders.-- Prompts deduplicate within an episode and explicit dismissals suppress repeats.-- Sleep, screen lock, and user switching clear transient state.-- The prompt supports VoiceOver announcements, Reduce Motion, keyboard actions, hover pause, and no auto-start.--The implementation is currently a two-second polling state machine on the main actor. It combines:--1. known running applications;-2. device-wide microphone start/stop edges;-3. per-application CoreAudio input or output activity on macOS 14.4 and later;-4. native application window presence;-5. a frontmost browser tab URL for supported meeting sites;-6. capture readiness and existing FluidVoice activity.--## 3. Root gaps--These are correctness gaps in the signal model, not UI polish issues.--### G1. Device activity is per device, but consumed as global activity--The device listener emits an edge whenever any monitored input device changes. Its consumer treats each inactive edge as if all microphones became inactive. With two microphones, a loopback device, an aggregate device, or a device transition, one device stopping can incorrectly end evidence while another remains active.--Required correction: maintain a set of currently active input device IDs and publish only aggregate transitions from zero to nonzero and nonzero to zero. Explicitly classify or exclude FluidVoice-created loopback devices.--### G2. Process input and output are collapsed--The process provider returns one Boolean when either application input or output is active. These signals mean different things:--- input activity means the application owns a microphone path;-- output activity may mean remote participants, a ringtone, media preview, or ordinary application sound.--Required correction: expose input and output independently, with bundle identifier, CoreAudio process object, PID when resolvable, observation time, and source quality.--### G3. Process attribution can use stale foreground history--Device-wide evidence requires a recent foreground event, but process-attributed evidence only requires that the application has been foreground at least once during its lifetime. An application activated hours earlier can therefore satisfy this gate.--Required correction: every foreground-dependent rule must have an explicit freshness window. Direct microphone ownership can reduce the need for foreground evidence, but must not silently turn an old timestamp into current intent.--### G4. Confirmation is instantaneous--Once audio and window/URL evidence coincide, the detector immediately creates an episode. A ringtone, pre-join test, transient microphone probe, or one polling sample can therefore produce a reminder. The queued/visible reminder is not promptly cancelled when those signals disappear.--Required correction: add positive stability, negative hysteresis, and cancellation while stabilizing or prompting.--### G5. Start validates readiness, not current meeting identity--At click time, `canStart` checks that the episode is unconsumed and FluidVoice is ready. It does not require fresh live evidence. A user can act on a stale reminder after the call has ended or the browser has navigated away.--Required correction: perform a fresh, bounded revalidation of the candidate, exact application, browser meeting locator when applicable, and capture source immediately before recording.--### G6. Native window evidence has uneven specificity--The Zoom path recognizes meeting-specific titles, but any layer-zero Teams or Webex window qualifies. Persistent home windows can combine with unrelated output activity and old activation history.--Required correction: application-specific evidence policies. When a reliable meeting-window marker is unavailable, require stronger process ownership, current activation, and longer stability.--### G7. Browser detection observes only the frontmost tab--This avoids scanning private browser state broadly, but it misses a background or minimized call and can lose identity when the user presents from another tab. Browser process audio cannot identify which tab owns audio.--Required correction: retain the last verified meeting locator ephemerally and refresh it opportunistically. Treat a different foreground tab as loss of visible correlation, not immediate proof that the call ended. Do not broaden to full-history or all-tab collection.--### G8. Detector health is too narrow--Only unreadable Zoom titles are surfaced. Process attribution availability, device-listener health, browser URL access, Accessibility timeouts, permission degradation, and stale polling are not represented coherently.--Required correction: publish a capability snapshot and operational health state, separate from candidate confidence.--### G9. Notification outcomes do not match user intent precisely--“Not now” suppresses the whole application for 30 minutes, while timeout suppresses only the current episode. There is no direct permanent per-application control, pause control, explanation of why the reminder appeared, or persistent place to recover an auto-dismissed action.--Required correction: model episode dismissal, time snooze, and source exclusion as different product actions.--## 4. Design principles--1. **Explicit rules before opaque scoring.** Use a small evidence-policy matrix whose outcomes can be explained and tested. A confidence band is an output, not an uninspectable weighted score.-2. **Current evidence only.** Every fact has an observation time, freshness limit, source, and health quality.-3. **Stable identity.** Evidence must refer to the same canonical application family and candidate locator.-4. **Positive stability and negative hysteresis.** Starting a suggestion needs sustained evidence; losing it needs a shorter cancellation window before recording and a longer safety window during recording.-5. **Asymmetric safety.** Prompt false positives damage trust; automatic recording is forbidden. Meeting-end false positives can lose content, so end detection only nudges by default.-6. **Graceful degradation.** Missing optional permissions lower the available confidence; they do not masquerade as a healthy detector.-7. **Minimal observation.** Read only the processes and windows already in the fixed registry. Reduce browser URLs immediately to an allowed provider plus opaque meeting locator.-8. **One episode, one interruption.** A dismissal or timeout suppresses the current episode until it genuinely ends.--## 4.1 User controls and sensitive contexts--Detector accuracy is not consent to interrupt. A technically correct meeting match may still be a conversation the user never wants to transcribe.--Launch controls are therefore part of the notification safety boundary, not later personalization:--- **Suggestion mode:** `Passive` or `Floating reminder`. New installations default to Passive. Existing installations preserve their current explicit detector preference. A passive meeting indicator can explain the feature and offer to enable floating reminders, but it never changes the mode automatically.-- **Pause all suggestions:** one hour, until tomorrow, or indefinitely from the menu bar and Meeting settings.-- **Application exclusions:** never suggest for a selected native application or browser.-- **Provider exclusions:** never suggest for a selected browser meeting provider without excluding the whole browser.-- **Suggest only when I use my microphone:** optional stricter mode for users who do not want muted/listen-only calls suggested.-- **End reminders:** independently enabled or disabled; default on only while FluidVoice is actively recording.--Private browser windows are excluded by default. A browser adapter may participate only if it can reliably identify private-window state and fail closed. If that distinction is not reliable for a browser/version, browser meeting suggestions are unavailable for that adapter rather than inspecting the window optimistically.--Only the active macOS login session is observed. Lock, fast-user-switch, logout, or sleep clears transient candidates and private locator digests. FluidVoice does not infer who is physically operating a shared Mac; the reminder always says that nothing is recording and requires an action in the active session.--The first successful capture started from a suggestion shows a concise, one-time local reminder that the user is responsible for following participant-consent and organization rules. Managed organization policy can make that reminder recurring or disable suggested capture, but cannot enable automatic recording.--## 5. Architecture--```text-Workspace events CoreAudio process observations-Device aggregate Window / browser correlation- \ /- MeetingSignalMonitor (background actor)- |- timestamped facts- |- MeetingEvidenceReducer (pure)- |- MeetingCandidateStore- |- PromptPolicy- |- InAppMeetingReminderCoordinator- |- explicit Start -> fresh revalidation- |- MeetingSessionCoordinator-```--### 5.1 MeetingSignalMonitor--This component owns observation and health, off the main actor.--It publishes immutable snapshots:--```swift-struct MeetingSignalSnapshot: Sendable {- let observedAt: DetectorInstant- let applications: [ApplicationAudioObservation]- let aggregateInput: AggregateInputObservation- let windows: [ObservedMeetingWindow]- let browserCorrelations: [BrowserMeetingCorrelation]- let capabilities: DetectionCapabilities- let generation: UInt64-}-```--`DetectorInstant` wraps `ContinuousClock.Instant`. Sleep advances this clock so every pre-sleep fact fails freshness checks after wake; `SuspendingClock` is forbidden in detector policy.--Properties:--- Process input and output are separate facts.-- Snapshots have a monotonic generation and timestamp; stale async AX results are discarded.-- CoreAudio enumeration runs off-main.-- A device edge requests an immediate process refresh, rate-limited to avoid storms.-- Normal cadence is one second while a candidate is stabilizing or recording, one second while relevant apps are running unless a proven process-audio push signal supplies equivalent latency, and thirty seconds only when push listeners are healthy and no relevant application is running.-- A watchdog marks the monitor degraded after five missed expected observations.-- Device changes temporarily lower confidence instead of creating false start/end edges.--### 5.2 Canonical identities--Do not key candidates only by PID and window number. Both can be reused.--```text-application family = canonical supported application or browser-process identity = PID + launch timestamp when available-meeting locator = native window token or provider + one-way in-memory locator digest-episode identity = application family + process identity + meeting locator generation-```--The digest is session-random and is never persisted. Raw URLs and titles never enter logs, analytics, or notification copy.--### 5.3 MeetingEvidenceReducer--The reducer is a pure state machine. It accepts snapshots and user outcomes and emits candidate transitions. This makes timing deterministic in tests.--Candidate states:--```text-idle- -> observing- -> stabilizing- -> confirmed- -> reminderPresented- -> accepted | dismissed | timedOut- -> ending- -> ended-```--Rules:--- `observing`: at least one relevant signal exists.-- `stabilizing`: a valid application-specific evidence combination exists.-- `confirmed`: the same combination remains valid for its stability threshold.-- `reminderPresented`: PromptPolicy authorizes an interruption.-- `accepted`: the user requested capture and fresh revalidation passed.-- `dismissed` or `timedOut`: no more reminders for this episode.-- `ending`: required evidence weakened; negative grace is running.-- `ended`: application exited, meeting locator disappeared and audio ceased, or the absence threshold elapsed.--Any loss of the required combination during `stabilizing` returns to `observing`. Before capture, a confirmed or visible reminder is invalidated after three seconds without a valid combination. During capture, signal loss never automatically stops the recording by default.--### 5.4 Evidence policy matrix--| Context | Required evidence | Stability | Result |-|---|---|---:|---|-| Native, meeting-specific window | same app has input or output activity + meeting window | 4 s | high-confidence reminder |-| Native, generic persistent window | same app owns input; recent activation is supporting evidence | 6 s | high-confidence reminder |-| Native, generic persistent window, muted | same app has sustained output + recent activation + app-specific call marker | 8 s | high-confidence reminder |-| Browser | browser input or output + currently verified supported meeting locator | 5 s | high-confidence reminder |-| Browser, locator temporarily unreadable after verification | same browser audio continues and locator was verified recently | no new reminder; preserve existing candidate for 15 s | continuity only |-| Legacy/degraded OS attribution | aggregate mic + recent foreground + qualifying window/URL | 8 s | medium confidence, passive in-app status only initially |-| Audio only | any | — | no reminder |-| Window/URL only | any | — | no reminder |-| Generic browser mic with no supported meeting locator | any | — | no reminder |--The exact thresholds are launch defaults, not remote feature flags. They may be adjusted only through a versioned local policy after trace evaluation.--“Recent activation” means no more than 30 seconds old and is supporting evidence only. A direct same-process input owner does not require the app to remain frontmost; background calls must work.--### 5.5 Capability and health model--```swift-struct DetectionCapabilities: Sendable, Equatable {- let processInputAttribution: Availability- let processOutputAttribution: Availability- let aggregateInputActivity: Availability- let nativeWindowIdentity: Availability- let browserMeetingCorrelation: Availability- let capturePermission: CapturePermissionState- let monitorHealth: MonitorHealth-}-```--Availability is `available`, `permissionRequired`, `unsupported`, or `temporarilyDegraded`. Health is not evidence. The UI can explain why detection is limited without accidentally increasing confidence.--## 6. Fresh start revalidation--Clicking “Start transcript” executes the cancellable start transaction defined in Phase 4 of `MEETING_DETECTOR_PHASED_IMPLEMENTATION_PLAN.md`. That transaction owns the authoritative ordering, deadline, target-liveness race, and acceptance semantics.--Failure leaves the user in control:--- Evidence ended: “The call no longer appears active.”-- Target changed or ambiguous: open source selection with the detected application preselected.-- Permission missing: show the exact missing capability and a direct repair action.-- FluidVoice busy: keep the current work untouched and explain that another audio task is active.--No episode is consumed before capture succeeds. Repeated clicks are single-flight.--## 7. In-app notification design--### 7.1 Presentation policy--The first user-facing phase uses only FluidVoice-owned surfaces. A high-confidence candidate always receives passive menu-bar status and receives a floating reminder only when the user has enabled Floating-reminder mode.--It must:--- use the display containing the detected meeting application when known, otherwise the active display;-- never activate FluidVoice or steal keyboard focus;-- remain keyboard and VoiceOver accessible;-- respect Reduce Motion and avoid appearing over another application’s full-screen presentation;-- keep a recoverable “Meeting suggestion” action in the menu bar while the transient panel is hidden;-- withdraw within three seconds when pre-capture evidence becomes invalid;-- show only once per episode.--The menu-bar state is a first-class surface, not a fallback implementation detail:--- Passive mode shows a neutral meeting-suggestion indicator without animation or sound.-- Floating-reminder mode shows the same indicator whenever the panel is visible, suppressed, or timed out.-- The menu item reads “Possible meeting in Zoom — Start transcript” and exposes the same source and privacy status to VoiceOver.-- It persists until the episode ends, the user selects Not now, the source becomes excluded, or capture begins. Short correlation gaps use the episode’s end grace rather than removing it immediately.-- A dot/badge may be enabled later; sound is default-off and outside the initial release.--Recommended copy:--```text-Meeting may have started-Zoom is using call audio. Nothing is being recorded.--[Not now] [Start transcript]-```--Use “Call may have started” for call-oriented applications when the registry knows that distinction. Do not display a URL, window title, participant, or calendar subject in the calendar-free reminder.--The panel remains available for 30 seconds; hover or keyboard interaction pauses the countdown. Panel timeout suppresses another floating interruption for that episode but preserves the passive menu-bar action until the episode ends. Timeout is therefore distinct from an active decline even though neither causes another panel.--### 7.2 Actions are distinct--- **Start transcript:** fresh revalidation followed by user-initiated capture.-- **Not now:** actively decline and suppress this episode until it ends; remove its passive menu-bar action.-- **Snooze 10 minutes:** hide the current panel, preserve only its passive menu-bar recovery, and prohibit another floating reminder for that episode. Other candidates may be detected but remain passive until the snooze expires. Expiry never re-presents an existing episode; only a different episode that becomes stable after expiry may show a panel.-- **Don’t suggest for this app:** optional overflow action; persist a reversible local source exclusion.-- **Why this appeared:** opens a local explanation using coarse evidence labels such as “meeting window” and “call audio,” never raw observed values.-- **Pause suggestions:** menu-bar control with one hour, until tomorrow, and indefinite choices.--Automatic timeout suppresses further floating interruptions for the episode but does not remove passive menu-bar recovery and does not count as negative feedback. An explicit “Not now” may contribute to a local suggestion to mute that source after repeated occurrences, but FluidVoice must not change settings automatically.--### 7.3 Setup reminders--A confirmed meeting can expose that capture is unavailable, but permission status determines whether FluidVoice may interrupt:--- `notDetermined`: one contextual setup reminder may appear. If the user chooses Not now, persist that setup-reminder decline and do not ask again until a manual meeting-capture or settings action.-- `denied`: passive settings/menu-bar status only. After the user declines a repair action, do not prompt again until they manually revisit meeting capture or re-enable setup reminders.-- `restricted`: passive explanation only, with no misleading System Settings action.-- `unsupported` or temporarily unavailable: passive explanation and retry status only.--The auto-detected online-call path does not offer microphone-only capture when application/system audio permission is missing. A mic-only transcript would omit remote participants and violate the promise of a meeting transcript. If a separate mic-only mode is introduced later, it requires explicit source copy and its own product design.--When a contextual setup reminder is allowed, it should name one repair action rather than sending the user to a generic setup screen:--```text-Meeting may have started-Allow Screen Recording to capture Zoom audio. Nothing is being recorded.--[Not now] [Open System Settings]-```--Show at most once per episode. Returning from System Settings triggers a fresh capability check. If permission remains absent, keep passive status and offer “Try again” in settings; never loop or immediately reopen System Settings. Detection settings must show the same capability state persistently.--### 7.4 Interruption suppression and passive recovery--Full-screen presentation, user-configured quiet mode, dictation, active recording, and another prompt can suppress the floating panel. macOS does not provide arbitrary applications a general Focus-state API, so FluidVoice must not claim to read Focus state; later system notifications inherit the operating system’s Focus delivery behavior. Suppression never produces a second toast explaining the first suppression. Instead, the menu-bar indicator changes to the neutral “possible meeting” state and remains accessible for the episode.--Source exclusions produce no candidate indicator because the user explicitly requested silence. A diagnostics/settings row may show that a source is excluded without revealing a live meeting. Busy FluidVoice activity may show “Meeting suggestion available after current task” passively, but must never stop or replace the current task.--### 7.5 Simultaneous-candidate arbitration--Only one floating panel is allowed. Rank eligible candidates deterministically by:--1. high confidence over medium confidence;-2. exact same-process microphone input ownership;-3. meeting-specific locator over generic application evidence;-4. capture readiness;-5. most recent transition into a stable candidate.--Do not replace a visible panel or an in-progress Start transaction. Other valid candidates appear as menu-bar choices under “Other possible meetings.” If the user selects one, source selection clearly names each viable application before capture. Accepting one candidate suppresses interruptions while FluidVoice is busy but does not end or merge distinct episodes; they remain passive and may become actionable after the recording ends if still live.--### 7.6 Browser observation contract--Before browser detection is enabled, show this user-facing disclosure:--> FluidVoice checks the current page only in supported browsers to recognize supported meeting sites. Matching happens on this Mac. It does not scan history or all tabs, and it does not store page addresses or titles. Private windows are excluded.--Initial adapters are Chrome, Safari, Arc, Edge, Brave, and their supported meeting PWAs. Each browser/version must pass fixtures for current-page access and private-window exclusion. If Accessibility or page access is unavailable, that adapter reports degraded/unavailable and produces no browser reminder. The session-random meeting-locator digest is regenerated at launch and never appears in exported traces, so it cannot link meetings across sessions.--### 7.7 System notifications later--System notifications are a later phase behind a separate “System meeting notifications” setting, default off. Passive suggestion mode never escalates to a system notification unless the user independently enables this setting. When enabled, system delivery is considered only when FluidVoice is not visible or the floating reminder cannot be presented. Copy remains generic, and actions route through the same fresh revalidation transaction. System notifications never bypass source exclusions, episode suppression, pause, operating-system Focus delivery, or the no-auto-start rule.--## 8. Meeting-end assistance--Start and end use different policies.--Before capture:--- invalidate the reminder after three seconds without a valid start combination;-- end the episode after 30 seconds of both missing application audio and missing meeting locator, or immediately when the process exits;-- tolerate short browser correlation loss and device transitions.--During capture:--- never stop solely because the microphone is muted, the window is minimized, or one audio direction stops;-- treat recent transcript output, application audio, a verified meeting locator, an alive exact capture target, or a qualifying native call marker as continuation evidence;-- after 60 seconds in which none of the continuation-evidence signals above is present, show one non-modal, non-focus-stealing “Still recording?” nudge positioned away from detected presentation controls;-- offer “Stop recording” and “Keep recording,” and state that stopping will finalize the local transcript;-- choosing “Keep recording” suppresses every further end nudge for that recording, including after later source fluctuations;-- default to no automatic stop.--A future automatic-stop preference may be designed separately, with an explicit opt-in and substantially longer absence window. It is outside this phase.--## 9. Privacy and local diagnostics--### 9.1 Data handling invariants--- Raw URLs and window titles are processed in memory and immediately reduced to provider, allowed-path classification, and ephemeral locator digest.-- No participant names, content, titles, raw process paths, device names, audio, or transcript text enter detection diagnostics.-- Candidate history is memory-only by default. Explicitly enrolled dogfood diagnostics may persist only the redacted bounded trace described below.-- Persisted operational state is limited to user-facing preferences: suggestion mode, pause, source exclusions, end-nudge preference, setup-reminder dismissal, and consent acknowledgment.-- No detector telemetry leaves the device without a separate, explicit opt-in design.--### 9.2 Local decision trace--Add a bounded, redacted circular buffer suitable for testing and support export:--```text-time delta | candidate token | transition | evidence classes | policy result | health-```--Example evidence classes are `processInput`, `processOutput`, `meetingWindow`, `meetingURL`, `recentActivation`, and `aggregateMicFallback`. Tokens are random per launch. Raw bundle identifiers, PIDs, device identifiers, locator digests, URLs, paths, and titles are never written into the trace buffer; redaction happens at write time, not at export.--The in-memory default buffer holds at most 5,000 transitions and clears at launch. Explicitly enrolled dogfood diagnostics may retain the same redacted records for at most seven days. Users can inspect detector health, export the redacted trace explicitly, or select “Clear detection diagnostics.” Export never includes the session locator digest. A test gate verifies that detector operation and trace review make no network requests.--Dogfood enrollment is explicit. Enrolled builds provide a local review inbox containing coarse candidate time, registry application label, outcome, and evidence classes. Review data remains on device unless the user exports it.--Local aggregate counters may include:--- candidates created, confirmed, cancelled during stability, and ended;-- reminders shown, suppressed, timed out, dismissed, and accepted;-- time from first valid combination to reminder and from reminder to capture;-- start revalidation failures by coarse reason;-- end nudges accepted or rejected;-- capability and monitor degradation counts.--## 10. Product decisions--This design resolves the following defaults:--| Decision | Default |-|---|---|-| Automatic recording | Never |-| New-install suggestion mode | Passive menu-bar status; user enables floating reminders |-| Existing-install suggestion mode | Preserve the user’s current detector setting |-| High-confidence candidate | Menu-bar status, plus floating reminder when enabled |-| Medium-confidence candidate | Menu-bar status only during initial rollout |-| Explicit “Not now” | Suppress current episode |-| Timeout | No second panel; preserve passive recovery; no negative-feedback count |-| Permanent source exclusion | Explicit, reversible local setting |-| Private browser windows | Excluded; unsupported adapter fails closed |-| Missing denied/restricted permission | Passive status only; no recurring repair prompt |-| Likely meeting end | Ask once; never auto-stop by default |-| End nudge preference | Independent toggle; default on during active recording |-| Consent reminder | One-time on first suggestion-started capture; policy may require recurring |-| Raw URL/title retention | None |-| External detector telemetry | None |-| System notification | Later, separate explicit opt-in; default off even in Passive mode |--One-hour/until-tomorrow pause, application exclusions, and browser-provider exclusions ship with the first strengthened reminder release. Browser-profile-specific exclusions and organization-policy management remain later extensions.--## 11. Phased implementation rationale--The authoritative phase numbering, work packages, and gates are in `MEETING_DETECTOR_PHASED_IMPLEMENTATION_PLAN.md`. This section is retained only as the original rollout rationale; references to implementation phases must use the detailed plan.--### Rationale A — Correct signal semantics--- Aggregate device state across all input devices.-- Exclude known FluidVoice loopback devices.-- Split process input and output observations.-- Add observation generations, health, and a watchdog.-- Move CoreAudio enumeration off-main.-- Add freshness to every timestamp-dependent rule.-- Build deterministic trace-replay tests.--Exit gate: multi-device and stale-attribution tests pass; observation does not block the main actor; no product behavior is broadened.--### Rationale B — Candidate reducer in shadow mode--- Implement the pure evidence reducer and application-specific policies.-- Run old and new decisions side by side locally without showing additional reminders.-- Make redacted trace export available in debug builds.-- Dogfood native applications first, then opt-in browsers.--Exit gate: the labelled-evaluation sample and confidence-bound requirements in Section 13.1 pass for each supported application family, no duplicate episode reminders occur, and p90 confirmation remains under ten seconds for high-confidence joins.--### Rationale C — Strengthened in-app reminder--- Route visible reminders through the new candidate/prompt policy.-- Add positive stability, live invalidation, current-episode dismissal, menu-bar recovery, and fresh start revalidation.-- Add exact capability repair CTAs.-- Add Passive/Floating mode, global pause, application/provider exclusions, and end-nudge preference.-- Add deterministic simultaneous-candidate arbitration and the private-browser fail-closed contract.-- Retain no-auto-start.--Exit gate: zero starts after failed live revalidation; stale reminders withdraw within three seconds; exclusions and pause act immediately; menu-bar recovery and source identification pass task-based usability tests; median unwanted reminders no more than one per active user per week during dogfood.--### Rationale D — Explanation and coverage--- Add local “Why this appeared?” evidence explanation.-- Expand application-specific policies only with trace fixtures and precision evidence.-- Handle browser/native handoff, reconnects, waiting rooms, breakout transitions, and simultaneous candidate applications.--Exit gate: each added source meets the same per-source precision target; exclusions take effect immediately and survive restart.--### Rationale E — System notifications--- Request notification permission contextually and only after user opt-in.-- Add a separate System meeting notifications preference; never infer it from Passive/Floating suggestion mode.-- Use system notifications only when the in-app surface is unavailable.-- Reuse the same episode suppression, actions, privacy copy, and start revalidation.--“In-app surface unavailable” means no eligible floating panel was presented because the panel was suppressed by presentation policy, or a passive menu-bar action remained unactivated for the configured system-notification delay. FluidVoice does not claim to know whether the user visually noticed the menu item. It never means source exclusion, explicit Not now, pause, denied permission, or an invalid candidate. When the system surface is selected, the floating panel is cancelled so the two surfaces never duplicate.--Exit gate: system and in-app surfaces never duplicate; Focus and permission states degrade to menu-bar recovery; notification opt-out does not disable detection.--## 12. Test strategy--### Reducer and invariants--- Audio-only and window-only never confirm.-- A candidate cannot confirm before its stability interval.-- Loss during stability cancels without a reminder.-- Every reminder maps to one live episode.-- Dismiss, timeout, and exclusion have distinct persistence semantics.-- No recording begins without explicit action and successful fresh revalidation.-- A consumed episode cannot re-prompt until it ends.-- Monotonic generation rejects stale async observations.--### Signal fixtures--- Two microphones where only one stops.-- Aggregate and loopback device appearance/disappearance.-- Input active without output; output active without input.-- Ringtone or notification audio in a persistent meeting application window.-- Stale foreground activation followed by unrelated output.-- Muted join with remote output.-- Waiting room, pre-join device test, reconnect, and breakout transition.-- Browser meeting moved to background or minimized.-- Browser navigates away before and after reminder presentation.-- Application PID and window ID reuse.-- Same-count replacement of one active application by another.-- Detector startup during an already-running meeting.-- Sleep, wake, lock, fast user switch, audio service restart, and device change.-- Two simultaneous meeting candidates with deterministic prompt arbitration.--### Notification fixtures--- Full-screen presentation suppresses interruption but preserves menu-bar recovery.-- Dictation overlay and active recording suppress new reminders.-- Incoming candidates cannot replace a Start transaction.-- VoiceOver can discover status and invoke both primary actions.-- Keyboard navigation never focuses the underlying application unexpectedly.-- Reduce Motion and increased contrast render correctly.-- Setup reminder deep-links to the correct capability.-- Denied and restricted permissions never produce recurring contextual repair prompts.-- Passive mode, timeout, full-screen suppression, and user-configured quiet mode preserve accessible menu-bar recovery.-- Application/provider exclusions, private-window exclusion, and global pause produce no live candidate indicator.-- Simultaneous candidates remain separately selectable and accepting one does not merge their episodes.-- Evidence loss silently withdraws visible and pending reminders.--## 13. Launch metrics and stop conditions--Metrics are calculated locally during dogfood unless users explicitly export a diagnostic report.--### 13.1 Labelled evaluation protocol--Dogfood users review a local periodic digest rather than receiving an extra interruption after every reminder. Each sampled episode can be labelled `meeting`, `not a meeting`, or `unsure`. The digest samples across every outcome: panel shown, Not now, timeout, passive recovery opened, capture started, candidate suppressed by presentation policy, and eligible shadow candidate not shown. Silence and `unsure` are never counted as confirmation.--Report separate denominators and label-response rates for each outcome. Prompt precision is `labelled meeting / (labelled meeting + labelled not a meeting)` among reminders actually shown; passive and shadow precision are reported separately. Manual online-call recordings with no eligible suggestion are counted as missed-opportunity proxies, not automatically as detector false negatives.--An application family may enter explicit opt-in V2 dogfood after the preliminary gate in the implementation plan. Default-on rollout uses the larger sample and confidence-bound gate defined there. Expansion decisions use per-family results, never only an aggregate average. Unreachable sample volume keeps a family opt-in; it never relaxes the gate automatically.--An active user-week for burden metrics is a local calendar week in which FluidVoice ran on at least three days and observed at least one eligible candidate. This avoids diluting interruption burden with inactive installations.--Launch targets:--- Prompt precision: meet the labelled-evaluation gate above for every supported application family.-- Prompt burden: median no more than one unwanted reminder per active user per week.-- Detection latency: p90 under ten seconds from a valid high-confidence combination.-- Stale reminder latency: at most three seconds after pre-capture evidence becomes invalid.-- Duplicate rate: zero duplicate reminders within one episode.-- Start safety: 100% of starts have explicit action, live revalidation, and an exact viable capture target.-- Accidental auto-starts: zero by construction.-- Main-thread impact: no synchronous CoreAudio enumeration or unbounded AX work on the main actor.-- Missed-value proxy: track manual online-call recordings lacking a prior eligible suggestion, segmented by source, without weakening the precision gate.-- Trust: track local suggestion disablement, pause, and source exclusion shortly after a reminder.-- Permission burden: no repeat contextual setup prompt after denied/restricted status or an explicit repair dismissal.-- User comprehension: in moderated task tests, at least 95% of participants correctly identify whether recording started, which source is captured, how to stop, and why the suggestion appeared.-- Accessibility: keyboard and VoiceOver users can discover passive status and complete Start, Not now, source choice, Keep recording, and Stop recording without focus loss.-- Privacy: automated integration tests observe no detector or diagnostics network traffic and exported traces contain no raw URL, title, path, participant, device name, or cross-session token.--Stop rollout and return to shadow mode for an application family if:--- labelled precision falls below 85%;-- unwanted reminders exceed two per active user per week at the 75th percentile;-- any recording starts after failed or stale revalidation;-- a privacy invariant is violated;-- monitor degradation produces repeated or unwithdrawn reminders.--## 14. Recommended implementation slice--The first implementation should not add application coverage or system notifications. It should deliver one coherent vertical slice:--1. correct aggregate device state;-2. structured per-process input/output observations off-main;-3. pure candidate reducer with four- or six-second stability;-4. visible reminder cancellation on evidence loss;-5. current-episode “Not now” semantics;-6. fresh start revalidation;-7. redacted local trace and deterministic tests.--This slice fixes the detector’s root semantics and makes the existing in-app reminder trustworthy. Coverage, personalization, calendar enrichment, and system delivery can then build on a stable episode model rather than adding exceptions to the current Boolean pipeline.diff --git a/MEETING_DETECTOR_PHASE0_PROBE_REPORT.md b/MEETING_DETECTOR_PHASE0_PROBE_REPORT.mddeleted file mode 100644index 25209369..00000000--- a/MEETING_DETECTOR_PHASE0_PROBE_REPORT.md+++ /dev/null@@ -1,98 +0,0 @@-# Meeting Detector — Phase 0 Probe: Local Evidence Report--- Date: 2026-08-23-- Environment: macOS 26.5.1 (build 25F80), arm64, Xcode 26.6 (build 17F113)-- App deployment target: macOS 15--## Scope--DEBUG-only feasibility probe plus DEBUG AppDelegate env hook. No production detector or notification behavior; no browser, Accessibility, Apple Events, TCC, or network access; no listeners or observers; no project membership change; no commit.--## Trigger--`FLUIDVOICE_MEETING_PROBE_DURATION_SECONDS` valid only for integer values in `5...300`; absent or invalid values are a no-op. Probe runs at most once per process (lock-guarded check-and-set gate).--## Implementation Evidence--- One utility-QoS serial sampling queue; a separate control queue is the sole owner of file handle, deadline timer, terminal reason, record count, output path, and in-flight flag.-- Exact GCD monotonic deadline timer; `ContinuousClock` records monotonic offsets, and any in-flight sample past the deadline yields `deadlineExceeded`.-- Dynamically sized, bounded HAL process/device list reads: size query then data read with one bounded retry on churn; layout validation (`size % stride == 0`, `<= 4096` objects, `<= 65536` stream-config bytes, `<= 4096` buffers).-- Independent input/output process selector reads (`kAudioProcessPropertyIsRunningInput` / `...Output`) with closed states (`active`/`inactive`/`readError`/`unsupported`).-- Low-level input-device reads (stream configuration, transport, running-somewhere, UID) without device names.-- Per-run salted device token: SHA-256 over 16-byte random salt + device UID, truncated to 128 bits; unlinkable across runs.-- Full non-desktop CG window list (`optionAll`, `excludeDesktopElements`) captured off-main inside `autoreleasepool`; only success flag, count, and latency retained — no window metadata persisted.-- Closed Codable schema: key sets for start/sample/terminal/process/device records validated at setup before any sampling; schema mismatch aborts with `validationFailure`.-- Output: one UUID-named JSONL file under the macOS temp directory, created with `0600` POSIX permissions; path prefix-validated against the temp dir.-- Release builds contain none of this code: entire file is wrapped in `#if DEBUG`, and the AppDelegate call site is `#if DEBUG`-guarded.--## Verification--| Check | Result |-| --- | --- |-| Debug build | Succeeded |-| Release build | Succeeded |-| Release scan for env key and probe-specific symbols | Absent |-| Debug scan for env key and probe-specific symbols | Present |-| Existing `MeetingAutoDetectorTests` | 48 passed, 0 failed |-| Run 1 (5 s) | start + 5 samples + terminal; terminal reason `completed` at exactly 5000 ms; JSON parse/schema passed; forbidden raw field/value scan: no matches; file mode `0600`; window enumeration success, latency <= 4 ms |-| Run 2 (5 s) | start + 5 samples + terminal; terminal reason `completed` at exactly 5000 ms; JSON parse/schema passed; forbidden raw field/value scan: no matches; file mode `0600`; window enumeration success, latency <= 4 ms |-| Leaks run (15 s) | start + 14 samples + terminal; `completed` at 15001 ms; forbidden scan: no matches; file mode `0600`; window latency <= 5 ms |-| Active Zoom call run (60 s, 2026-08-25) | start + 56 samples + terminal; `completed` at 60001 ms; all HAL list reads `ok`; classification failures: 0; every sample contained one Zoom audio-process object at `active`/`active` plus an inactive helper object; built-in input reported `running`; file mode `0600`; forbidden raw field/value scan: no matches; window enumeration succeeded in every sample, latency <= 8 ms |-| Follow-up run (15 s, 2026-08-25) | start + 14 samples + terminal; `completed` at 15001 ms; the same Zoom and device states persisted; file mode `0600`; forbidden raw field/value scan: no matches; window enumeration succeeded in every sample, latency <= 8 ms. The operator's leave action was not explicitly confirmed, so this run is not counted as call-ended evidence. |-| Confirmed joined run (90 s, 2026-08-25) | start + 86 samples + terminal; `completed` at 90001 ms; every sample contained a Zoom audio-process object at `active`/`active`, with built-in input `running`; file mode `0600`; forbidden raw field/value scan: no matches. The leave confirmation arrived near/after the deadline, so this run is counted only as joined-state evidence. |-| Confirmed post-leave run (20 s, 2026-08-25) | start + 19 samples + terminal; `completed` at 20001 ms; the operator had explicitly confirmed leaving while keeping Zoom open; every sample contained only Zoom `inactive`/`inactive`, with built-in input `notRunning`; all HAL list reads `ok`; classification failures: 0; file mode `0600`; forbidden raw field/value scan: no matches; window enumeration succeeded in every sample, latency <= 5 ms. |-| Token unlinkability | 2 unique device tokens in each run, 0 shared across runs |-| Stack-filtered `leaks` pass | App-wide scan reported framework/XPC allocations, but no leak stack matched the probe, session, CF-string reader, or window-capture symbols |-| Code review — initial plan | REVISE (required deadline/CF/buffer/privacy/evidence corrections) |-| Code review — revised plan | APPROVE |-| Code review — final code | APPROVE |-| Code review — post-fix | APPROVE |--Review attribution: Grok 4.6 attempts stalled/timed out without edits or verdict and are explicitly not counted as approval; Kimi K3 provided the explicit approvals.--## Observed Facts--- CoreAudio process enumeration recognized the `selfProcess` and `zoom` coarse families. Both input and output selector reads succeeded independently but observed `inactive`/`inactive` in this short non-active-call run. Duplicate family entries can represent primary/helper audio process objects; no raw mapping leaked.-- Two input devices were stable within each run by token, both `notRunning`; transports `builtIn` and `other`; classification failures: 0.-- Full CG window list succeeded in all samples with <= 4 ms query latency.--### Active-call observation — 2026-08-25--- With an operator-confirmed active Zoom meeting, one Zoom audio-process object reported `active` input and `active` output in every 1-second sample. A second Zoom helper object remained `inactive`/`inactive`; family-level aggregation must therefore tolerate multiple process objects.-- The built-in input device reported `running` for the whole active-call run. The other input-capable device remained `notRunning`.-- The operator explicitly acknowledged entering a muted interval, but neither the active Zoom process state nor the built-in device state changed. These signals establish call activity, not Zoom's UI mute state.-- No call-ended transition was observed before either probe deadline. Because the requested leave action was not explicitly acknowledged, this is ambiguous coordination evidence and cannot establish persistence after leaving.-- A subsequent controlled cycle removed that ambiguity: the joined run showed Zoom `active`/`active` and built-in input `running`; a fresh probe launched only after explicit leave confirmation showed Zoom `inactive`/`inactive` and built-in input `notRunning` in all 19 samples while Zoom remained open.-- Active-versus-post-leave state separation is therefore validated at 1-second cadence. Exact leave-transition latency is not yet measured because the acknowledgement landed near the first probe's deadline and the definitive post-leave evidence came from a fresh process.-- The live runs remained metadata-only: no audio, titles, participant data, raw bundle identifiers, raw device identifiers, paths, or URLs were written.--## Phase-0 Questions — Status--1. Process selector API path and independent input/output reads: **supported**. Active Zoom call and post-leave state separation: **VALIDATED AT 1-SECOND CADENCE**. UI mute-state detection from these signals: **NOT SUPPORTED BY THE OBSERVED EVIDENCE**. Same-process join/leave transition latency remains **NOT YET VALIDATED**.-2. Known primary/helper family mapping works without paths for observed Zoom processes. Other families: **NOT YET EMPIRICALLY VALIDATED**.-3. Input-capable devices stable within a run and unlinkable across runs. External switching, aggregate/removal, and any app-owned loopback: **NOT YET VALIDATED**.-4. HAL enumeration and full window snapshot completed off-main in two bounded runs. Rapid switching and sleep/wake stress: **NOT YET VALIDATED**.--## Residual Gates Before Phase 1--- Same-probe join and explicitly acknowledged leave/relaunch transitions plus application playback at 1 s / 2 s / 5 s sampling cadences. Mute/unmute should be treated as a negative-control test unless a separate local signal is justified.-- External input switching, aggregate-device concurrency, device removal, zero-device/headless runs where feasible; identify whether an app-owned loopback exists.-- Rapid app switching and user-coordinated sleep/wake.-- Separate, explicitly consented browser privacy/TCC spike.-- Lock `DetectorInstant` `ContinuousClock` choice, self-observation exclusion, and actor single-flight contracts after evidence.--## Verdict--First execution slice **IMPLEMENTED AND CODE-APPROVED**, but the full Phase 0 exit gate remains **OPEN**. Phase 1 must not start yet. No heuristics added.--## Artifacts--- Probe source: `Sources/Fluid/Services/Meeting/MeetingDetectorFeasibilityProbe.swift`-- DEBUG hook: `Sources/Fluid/AppDelegate.swift` (`applicationDidFinishLaunching`, `#if DEBUG` block)-- Existing detector tests: `Tests/FluidDictationIntegrationTests/MeetingAutoDetectorTests.swift`-- This report: `MEETING_DETECTOR_PHASE0_PROBE_REPORT.md`-- Raw JSONL outputs: UUID-named files, inspected in the macOS temp directory (exact names and device tokens intentionally not recorded here). They remain only in temp, may be purged by the OS at any time, and are not copied into the repo.--## Rollback--Remove the DEBUG AppDelegate hook and the new probe/report files only. Existing user detector work is unrelated and must not be reverted.diff --git a/MEETING_DETECTOR_PHASED_IMPLEMENTATION_PLAN.md b/MEETING_DETECTOR_PHASED_IMPLEMENTATION_PLAN.mddeleted file mode 100644index 3b21bc3e..00000000--- a/MEETING_DETECTOR_PHASED_IMPLEMENTATION_PLAN.md+++ /dev/null@@ -1,932 +0,0 @@-# Meeting Detector Phased Implementation Plan--Status: proposed after implementation grounding; pending adversarial PE review-Parent design: `MEETING_DETECTION_NOTIFICATION_DESIGN.md`-Scope: calendar-independent detector, in-app notification lifecycle, and safe meeting-end assistance-Delivery rule: no automatic recording; no system notifications until the in-app path passes dogfood gates--## 1. Objective--Replace the current mixed signal/state/UI pipeline with a trustworthy detector that:--- observes microphone devices and application audio correctly;-- combines only fresh, same-target evidence;-- requires positive stability before suggesting capture;-- models one durable episode instead of emitting isolated prompts;-- withdraws stale reminders and revalidates immediately before recording;-- supports passive menu-bar recovery and explicit user controls;-- fails closed when browser privacy state or required evidence is unreadable;-- keeps all detection and evaluation data local by default.--This plan changes architecture before expanding application coverage. Calendar integration and automatic recording remain out of scope.--## 2. Verified baseline--### 2.1 Current data flow--```text-NSWorkspace / CoreAudio / CGWindow / Accessibility- ↓- MeetingAutoDetector @MainActor- records + evidence + episodes + policy + polling- ↓- MeetingDetectionPromptController @MainActor- ↓- AppServices start transaction- ↓- MeetingSessionCoordinator-```--Current implementation files:--- `Sources/Fluid/Services/Meeting/MeetingAutoDetectSignals.swift`-- `Sources/Fluid/Services/Meeting/MeetingAutoDetector.swift`-- `Sources/Fluid/Services/Meeting/MeetingAppRegistry.swift`-- `Sources/Fluid/UI/MeetingDetectionPrompt.swift`-- `Sources/Fluid/Services/AppServices.swift`-- `Sources/Fluid/Services/MenuBarManager.swift`-- `Sources/Fluid/Persistence/SettingsStore.swift`-- `Sources/Fluid/UI/MeetingTranscriptionView.swift`-- `Tests/FluidDictationIntegrationTests/MeetingAutoDetectorTests.swift`--The application target uses a file-system-synchronized source group. Test files still require explicit Xcode project membership.--### 2.2 Baseline verification--Focused command:--```sh-xcodebuild test \- -project Fluid.xcodeproj \- -scheme Fluid \- -configuration Debug \- -destination 'platform=macOS' \- -only-testing:FluidDictationIntegrationTests/MeetingAutoDetectorTests \- CODE_SIGNING_ALLOWED=NO-```--Verified result on 2026-08-22: 48 tests, 0 failures.--### 2.3 Worktree constraint--The detector sources, prompt, tests, and design documents are currently untracked while related application wiring is modified in an already-dirty worktree. Those changes are the working baseline and must not be staged, committed, reset, or cleaned as part of implementation without an explicit user request.--Before the first edit of every phase:--1. record `git status --short --untracked-files=all` and a complete target-file inventory;-2. after one scoped filesystem approval, copy only the phase’s target files into a stable local development archive outside the repository and outside purgeable temporary storage;-3. record SHA-256 hashes plus the pre-phase list of files that do not yet exist;-4. record `project.pbxproj` changes as a targeted patch only; never restore that already-dirty file wholesale;-5. after the phase, review tracked diffs, the targeted project patch, every created file, and full contents of untracked target files;-6. never touch unrelated media, render scripts, or meeting work.--Runtime rollback uses an injected detector policy mode. File rollback is a targeted, reviewed reversal using the stable archive and created-file manifest, never a bulk restore or destructive Git command. Persisted settings migrations must remain readable by the previous runtime mode.--## 3. Non-negotiable invariants--Every phase must preserve these:--1. No recording without an explicit user action.-2. No raw browser URL, window title, participant data, device name, or transcript text in logs or diagnostics.-3. Audio-only, window-only, and generic-browser-only evidence never trigger a floating reminder.-4. Busy dictation, file transcription, or meeting capture is never interrupted or replaced.-5. A candidate and capture target belong to the same canonical application family.-6. Start is single-flight and succeeds only after fresh evidence and capture readiness pass.-7. Loss of one signal never automatically stops an active recording.-8. Lock, sleep, fast-user-switch, and monitor restart clear or demote transient authority.-9. Existing manual meeting capture and transcription behavior remains unchanged.-10. Each phase has an independent disable/rollback path and passes focused tests before the next begins.-11. FluidVoice process audio is never eligible meeting evidence. When FluidVoice holds any exclusive audio lease, aggregate-input fallback loses start/end authority; device-level aggregation cannot distinguish ownership and must not be treated as self-excluded.--## 4. Locked technical decisions--### 4.1 Time model--Live detector ordering uses `DetectorInstant`, a wrapper over `ContinuousClock.Instant`, not `Date`. `ContinuousClock` advances across system sleep, so every pre-sleep fact expires after wake. `SuspendingClock` is forbidden. Reducer events carry detector instants supplied by an injected clock. Wall time is used only for persisted user preferences such as “pause until tomorrow.”--This prevents clock changes, timezone changes, and wake correction from creating false freshness or end decisions.--### 4.2 Signal identity--Process audio observations are not attached directly to a UI process PID. They first map to a canonical application family because helper processes may own audio for a different main application process.--```swift-struct ApplicationAudioObservation {- let audioObjectID: AudioObjectID- let processID: pid_t?- let observedBundleIdentifier: String- let canonicalFamily: MeetingApplicationFamily- let inputActive: Bool- let outputActive: Bool- let observedAt: DetectorInstant-}-```--The registry owns helper-to-family mapping. Window and browser correlation then resolve the main UI process and exact capture target.--### 4.3 Snapshot and generation model--`MeetingSignalMonitor` is the sole producer of immutable snapshots from Phase 2 onward. Every refresh has a monotonic generation minted inside the actor. Async results carry the generation that requested them and are dropped if superseded.--Generation prevents stale async writes; freshness thresholds still apply within accepted snapshots. Neither replaces the other.--HAL listeners run on one dedicated serial queue and yield ordered events through an `AsyncStream` consumed by the monitor actor; callbacks never create unordered unstructured tasks. The actor permits at most one refresh pass in flight. Concurrent requests coalesce, with a pending-priority bit requesting the next pass. Blocking provider work runs in cancellable child tasks and returns values to the actor; no provider mutates monitor state.--A priority snapshot request races its deadline outside the actor. It may use a completed snapshot only when its relevant facts are no more than one second old. Otherwise it returns `deadlineExceeded` and revalidation fails closed. It never waits indefinitely behind a suspended actor refresh.--### 4.4 Reducer boundary--`MeetingEvidenceReducer` is pure:--```text-old state + timestamped event + policy → new state + effects-```--It does not call CoreAudio, Accessibility, `NSWorkspace`, settings, logging, or capture readiness. Effects such as `candidateConfirmed`, `reminderInvalidated`, and `episodeEnded` are handled outside the reducer.--Capture readiness is notification policy, not meeting identity. A confirmed meeting can exist while capture needs setup.--### 4.5 Rollout modes--Use an internal injected mode, not a remote flag:--- `legacy`: current detector is authoritative;-- `shadow`: legacy is authoritative, new reducer records redacted decisions only;-- `nativeV2Dogfood`: new reducer is authoritative only for explicitly enrolled users and validated native families; other users remain legacy;-- `browserShadow`: native V2 remains authoritative where enabled while V2 browser adapters record counterfactual decisions only;-- `v2`: new reducer is authoritative for every validated adapter.--Policy mode selects the decision engine; the per-family/per-adapter support matrix independently selects eligibility. Both must permit a candidate. Production defaults change only at explicit phase exit gates. The legacy path remains for one dogfood release after default-on native cutover and is never deleted while its only durable copy is untracked.--### 4.6 Document precedence--Where this plan and `MEETING_DETECTION_NOTIFICATION_DESIGN.md` state different implementation values, this plan governs. Amend the design in the same change so both documents state the same value.--## 5. Dependency graph--```text-Phase 0: feasibility probes + contracts- ↓-Phase 1: correct signal semantics- ↓-Phase 2: monitor snapshots + pure reducer- ↓-Phase 3: shadow evaluation + local diagnostics- ↓-Phase 4: native cutover + fresh start revalidation- ↓-Phase 5: notification lifecycle + controls- ↓-Phase 6: browser privacy adapters- ↓-Phase 7: end assistance + legacy removal- ↓-Phase 8: optional system notifications-```--Phase 6 may be delayed without blocking the native detector. Phase 8 is a separate release decision.--## 6. Phase 0 — Feasibility probes and contracts--### Goal--Validate public API assumptions before rewriting production state. Produce evidence, not product behavior.--### Work packages--#### P0.1 CoreAudio process probe--Build a debug-only probe that samples the CoreAudio process object list and records redacted transitions for:--- input and output selectors independently;-- primary meeting application and helper-process bundle mapping;-- process object/PID stability across join, mute, unmute, leave, relaunch, and application audio playback;-- observation latency at one-, two-, and five-second polling cadences;-- unavailable selector/error behavior.--No process path or user data may be logged.--#### P0.2 Device aggregation probe--Observe built-in input, external input, device switching, aggregate devices, and device removal. Verify:--- stable device IDs during one run;-- aggregate zero→nonzero and nonzero→zero semantics;-- one device stopping does not emit global inactive while another remains active;-- loopback devices can be excluded by stable UID or owned-device metadata, never display-name matching.--#### P0.3 Background-call probe--Move only probe queries for process objects and window snapshots to a utility executor. Exercise rapid app switching, sleep/wake, and repeated refresh to confirm no deadlock, crash, or main-thread dependency.--#### P0.4 Browser privacy spike--For each intended browser adapter, determine whether a private window can be identified reliably through supported local state. The probe report must name the mechanism and permission boundary for that adapter:--- bounded Accessibility attributes that require existing Accessibility access;-- Apple Events only where a documented browser dictionary exposes the needed state and the user explicitly authorizes the resulting Automation TCC prompt;-- no process-argument scraping, private API, title-string guessing, or UI-language matching.--Return `supported`, `permissionMissing`, or `unsupported`; do not collapse permission denial into an unsupported browser. Test normal/private windows, multiple profiles, PWAs, and minimized windows. A validated browser/version still performs a runtime capability assertion at launch. Unknown/new versions and unknown private state fail closed until revalidated.--Automation probes change real TCC state and are excluded from the first execution slice. They run only in a separately announced, user-consented probe. Fail criterion: if private state cannot be distinguished reliably, that adapter is marked unsupported for V2 notifications. Do not weaken the privacy contract.--#### P0.5 Contract types--Add or draft the core value types and protocols with no production wiring:--- `DetectorInstant` and `MeetingDetectionClock`;-- `MeetingApplicationFamily` and helper mapping;-- `ApplicationAudioObservation`;-- `AggregateInputObservation`;-- `DetectionCapabilities` and `MonitorHealth`;-- `MeetingSignalSnapshot`;-- `MeetingDetectionPolicyMode`.--### Files--Prefer new debug/test files plus narrowly scoped types in `MeetingAutoDetectSignals.swift` and `MeetingAppRegistry.swift`. Do not change confirmation or notification behavior.--### Tests--- selector error/unsupported mapping;-- canonical helper-family mapping;-- monotonic clock fixture;-- capability state mapping;-- probe output redaction;-- no network dependency.--### Exit gate--- Input/output selectors behave independently on the supported deployment target.-- Off-main HAL and window queries complete a repeated stress probe without UI stalls or deadlock.-- Device aggregation and loopback exclusion have stable identifiers.-- Every browser has an explicit supported/unsupported privacy result.-- The supported application deployment target is macOS 15.0; pre-14.4 behavior is not a product path. Availability guards remain defensive and report unsupported health rather than broad fallback.-- Existing 48 detector tests remain green.--If any native API assumption fails, revise the evidence matrix before Phase 1; do not add heuristics to hide the failure.--### Rollback--Phase 0 is additive and unreachable in Release. Disable the debug affordance and reverse only the probe/type additions using the phase manifest. TCC changes are not rolled back by file restoration, which is why Automation probing is a separate user-consented action with its state recorded in the report.--## 7. Phase 1 — Correct signal semantics--### Goal--Fix observation truth while preserving the current authoritative detector behavior.--### Work packages--#### P1.1 Aggregate microphone state--Replace per-device Boolean edges with snapshots or edges containing device identity. `CoreAudioMicActivitySignal` maintains the active eligible-device set and emits only aggregate transitions.--Device list changes perform a resync before emitting. Sleep/wake and service restart reset authority until the resync completes.--#### P1.2 Structured process audio--Replace `AudioProcessActivityProviding.isAudioActive(...) -> Bool` with a structured observation API returning input/output separately, source health, generation, and observation time.--The provider reports every relevant family in one process-list pass rather than enumerating the process list once per candidate PID.--FluidVoice and its helper processes are excluded before canonical-family mapping. Aggregate device state remains observable, but the compatibility adapter cannot use it as meeting evidence while `DetectionActivityGate` reports any FluidVoice audio activity.--#### P1.3 Fresh foreground facts--All activation evidence receives an explicit expiry. Remove the `lastFrontmostAt != nil` shortcut for process audio. Direct same-family input ownership may confirm in the later reducer without requiring foreground state; weaker fallback rules require recent activation.--#### P1.4 Move blocking reads off-main--CoreAudio process enumeration and CG window snapshots execute outside `@MainActor`. Main-actor bridges deliver immutable values only. Keep HAL listener callbacks minimal and never synchronously wait on the main actor.--### Files--- `MeetingAutoDetectSignals.swift`-- `MeetingAppRegistry.swift`-- `MeetingAutoDetector.swift` as a compatibility adapter-- `MeetingAutoDetectorTests.swift`--### Tests first--- device A active + device B stops → aggregate remains active;-- last active device stops → exactly one aggregate inactive edge;-- device added/removed during activity;-- excluded loopback never changes aggregate state;-- input-only, output-only, both, and neither observations;-- helper process maps to the correct canonical family;-- stale activation cannot satisfy an attribution gate;-- one process enumeration serves multiple candidates;-- generation rejects an old completion after resync.--### Exit gate--- Existing visible prompt outcomes remain unchanged for the old fixtures.-- New multi-device and directionality tests pass.-- Thread sanitizer/debug stress shows no cross-actor violation in the signal path.-- No synchronous CoreAudio enumeration or full window snapshot runs on the main actor.-- Focused suite and full application build pass.--### Rollback--Switch policy mode to `legacy` using the compatibility adapter. Reverse Phase 1 signal changes through the reviewed stable archive/targeted patch if the compatibility layer itself is faulty.--## 8. Phase 2 — Snapshot monitor and pure episode reducer--### Goal--Create the V2 state machine without changing which path shows reminders.--### Work packages--#### P2.1 `MeetingSignalMonitor`--Create a background actor that owns:--- relevant running-app state;-- adaptive polling cadence;-- immediate rate-limited refresh after aggregate device edges;-- process audio observations;-- native window and browser correlation requests;-- capability health and watchdog state;-- snapshot generation.--Cadence defaults:--- one second while stabilizing or recording;-- one second while any relevant application is running, unless a proven process-audio push signal supplies equivalent latency;-- thirty seconds only when push listeners are healthy and no relevant application is running.--Relevant-application launch, process-audio edge when available, aggregate-device edge, service restart, and wake request an immediate rate-limited refresh. Detection latency is measured from the first observable valid combination; the probe report also records the worst unobserved interval.--Cadence is injected and testable. It is not a collection of inline sleep literals.--#### P2.2 Canonical candidate identity--Use:--```text-family + process launch identity + ephemeral meeting locator + locator generation-```--PID/window-number reuse cannot reuse an ended episode. Browser locators become session-random digests before entering state.--#### P2.3 Pure reducer--Implement candidate states:--```text-idle → observing → stabilizing → confirmed → presented- ↓ ↓- ending ← accepted/dismissed/timedOut- ↓- ended-```--Encode application-family policies as data. Do not scatter family-specific branches through the reducer.--Initial policies:--- meeting-specific native window + same-family input/output: 4 seconds;-- generic persistent native window + same-family input: 6 seconds;-- generic persistent window + output + recent activation + call marker: 8 seconds;-- fallback aggregate mic + recent activation + qualifying marker: 8 seconds, medium/passive only;-- audio-only, marker-only, or generic browser audio: never confirm.--Pre-capture evidence loss invalidates a confirmed/presented effect after three seconds. Episode end uses a longer independent absence policy.--#### P2.4 Effect adapter--Reducer effects are translated into callbacks by a thin coordinator. In `shadow` mode, visible callbacks are discarded and only redacted comparisons are recorded.--At Phase 2 wiring, the legacy detector stops owning independent CoreAudio/window polling. A compatibility adapter derives its legacy Boolean/window inputs from `MeetingSignalMonitor` snapshots. Shadow mode therefore compares decision engines over one observation stream rather than running two sensor stacks.--### New files--- `MeetingSignalMonitor.swift`-- `MeetingEvidenceReducer.swift`-- `MeetingCandidateModels.swift`-- `MeetingDetectionPolicy.swift`-- `MeetingDetectionTrace.swift`-- `MeetingEvidenceReducerTests.swift`--Update the Xcode test target for every new test file.--### Tests--- table-driven policy cases for every evidence combination;-- stability boundary at threshold minus/at/plus one tick;-- signal flap resets stability;-- negative grace cancels a visible reminder effect;-- duplicate snapshots and out-of-order generations are idempotent;-- PID/window reuse creates a new identity only after end;-- back-to-back same-window meetings rearm;-- two candidates remain independent;-- lock/wake/service restart demotes authority;-- property test: no event sequence emits `startRecording`;-- property test: at most one present effect per episode;-- trace events contain only allowed enums/tokens.--### Exit gate--- Reducer tests are deterministic with no sleeps.-- Legacy and V2 paths run together with only legacy producing UI.-- Every V2 decision has a redacted reason code.-- The new path adds no measurable main-thread polling work.-- Existing detector and capture tests remain green.--### Rollback--Set mode to `legacy` while keeping the shared monitor and compatibility adapter. If the monitor itself is faulty, disable the detector globally and reverse only Phase 2-created files plus targeted compatibility wiring using the phase manifest; do not restart the removed dual poller as an emergency path.--## 9. Phase 3 — Shadow dogfood and local evaluation--### Goal--Measure V2 precision and disagreements before making it authoritative.--### Work packages--#### P3.1 Redacted comparison trace--Record, in memory by default:--- candidate token;-- registry family category;-- evidence classes;-- legacy/V2 decision and transition;-- suppression reason;-- capability/health class;-- monotonic time delta.--Never store raw URL/path, title, bundle path, device name, PID in export, or meeting locator digest.--#### P3.2 Debug diagnostics--Add a debug-only local view to:--- inspect detector health;-- see legacy/V2 disagreement counts;-- label sampled episodes `meeting`, `not a meeting`, or `unsure`;-- clear local diagnostics;-- explicitly export a redacted report.--Production history remains memory-only and clears at launch. Seven-day persistence is allowed only after explicit dogfood enrollment.--Dogfood persistence uses an application-support subdirectory protected by the current user account, bounded by seven days and 5,000 redacted transitions. Disabling enrollment deletes it immediately. Export is an explicit copy action; raw identifiers never enter the stored buffer, so export has no second redaction boundary.--#### P3.3 Replay corpus--Convert redacted labelled transitions into deterministic, content-free fixtures. Include:--- join muted/unmuted;-- ringtone and ordinary app playback;-- waiting room and pre-join test;-- persistent home window;-- background call;-- device switch;-- sleep/wake;-- two simultaneous applications;-- process or audio-service restart;-- app relaunch and ID reuse.--### Files--- `MeetingDetectionTrace.swift`-- new debug diagnostics view/model-- `MeetingEvidenceReducerTests.swift`-- fixture resources and loader-- narrowly scoped settings for dogfood enrollment only--### Preliminary opt-in cutover gate--Per native application family:--- at least 30 labelled V2 counterfactual confirms from the local digest;-- at least 15 labelled V2 non-confirm/passive candidates;-- at least 80% requested-label response rate;-- observed counterfactual precision at least 90%;-- no start-safety, duplicate, privacy, or stale-generation violation;-- p90 confirmation under ten seconds;-- all named replay families pass.--This gate permits only explicit `nativeV2Dogfood`; it does not change production defaults. Labels apply to V2 counterfactual confirms whether or not the legacy path displayed a prompt. Silence and `unsure` are excluded and label-response rate is reported.--### Default-on rollout gate--Per family: at least 150 labelled V2 counterfactual confirms, 75 labelled non-confirm candidates, 70% response, observed precision at least 92%, and 95% Wilson lower bound at least 86%. If volume is unreachable, the family remains opt-in; time alone never relaxes the gate.--If either gate is not met, revise policy data and replay tests, then repeat shadow evaluation. Do not cut over on aggregate accuracy alone.--### Rollback--Disable dogfood enrollment and clear the redacted store. Shadow decisions stop, legacy remains authoritative, and no user-facing setting migration has occurred.--## 10. Phase 4 — Native V2 cutover and fresh start revalidation--### Goal--Make V2 authoritative only for explicitly enrolled dogfood users and validated native families, with a minimal passive/floating choice before any V2 interruption.--### Work packages--#### P4.1 Family-scoped cutover--`nativeV2Dogfood` routes only validated native families through V2 for enrolled users. Enrollment explicitly chooses Passive or Floating; Passive is the default. Add an immediately available Pause control before enabling Floating. Unsupported or degraded families stay silent rather than falling back to broad Boolean logic. Non-enrolled users remain legacy until the default-on gate passes.--Phase 4 includes the minimum passive surface by extending the existing `MenuBarManager`: one neutral possible-meeting item, Start, Not now, and Pause. It does not create a second status item. Phase 5 adds migration, exclusions, multi-candidate menus, explanations, and full presentation policy.--#### P4.2 Prompt invalidation--Reducer `reminderInvalidated` effects call the existing `MeetingDetectionPromptController.invalidateEpisode`. Visible and suppression-pending reminders withdraw within three seconds of invalid evidence.--#### P4.3 Fresh revalidation transaction--Extend the existing `AppServices.startAutoDetectedRecording` seam as a cancellable race between episode liveness, deadline, and capture start:--1. freeze episode and reject duplicate taps;-2. request a priority snapshot with a two-second deadline;-3. require a current start-eligible policy for the same episode identity;-4. resolve the exact live application/window target;-5. recheck capture permissions, storage, and FluidVoice activity;-6. create capture configuration;-7. recheck episode and target once more;-8. start capture while subscribing to episode/target invalidation;-9. if the target dies before the capture engine reports a live exact source, cancel/stop startup, discard any empty provisional session, leave the episode unconsumed, and show “The call no longer appears active”;-10. mark accepted only after the exact source reports success and the episode remains eligible.--The priority refresh API is cooperatively cancellable. Deadline expiry returns `deadlineExceeded` and fails closed; it never falls back to an arbitrarily old cached snapshot.--If evidence ended, close the reminder with “The call no longer appears active.” If the exact target is ambiguous, open source selection with candidates preselected. Never silently fall back to another application.--#### P4.4 Episode outcomes--Change semantics:--- explicit Not now: suppress current episode until end;-- timeout: prevent another floating panel but retain passive eligibility for Phase 5;-- capture failure: do not consume the episode;-- successful capture: accept the episode and suppress other interruptions while busy.--Remove the current bundle-wide 30-minute dismissal from the authoritative V2 path. Preserve it only inside legacy mode until legacy deletion.--#### P4.5 First-capture consent reminder--Before the first capture started from a suggestion, show the one-time local participant-consent/organization-policy reminder. Persist acknowledgment separately from detector mode. Cancellation leaves the episode live and does not start capture.--### Files--- `MeetingAutoDetector.swift` or its new coordinator replacement-- `MeetingDetectionPrompt.swift`-- `AppServices.swift`-- `MenuBarManager.swift` for the minimum passive dogfood surface-- dogfood-only suggestion-mode/Pause settings-- reducer/effect models-- detector and AppServices-focused tests--### Tests--- signal loss during visible reminder invalidates it;-- signal loss during fullscreen suppression invalidates pending state;-- fresh snapshot timeout fails closed;-- target changes before click;-- target disappears during configuration;-- capture failure permits retry while episode remains live;-- repeated click is single-flight;-- Not now and timeout differ;-- busy activity remains untouched;-- native family cutover cannot activate an unvalidated family.--### Exit gate--- Zero capture starts after stale/failed revalidation.-- 100% of starts use the exact validated target.-- Stale visible/pending reminder withdrawal is at most three seconds.-- Existing manual capture tests pass unchanged.-- Runtime rollback to `legacy` is verified in a debug build.-- Explicit dogfood users can choose Passive before V2 activation and Pause immediately.-- Unwanted floating reminders remain at or below one per active enrolled user-week median and two at the 75th percentile.-- Any privacy, accidental-start, exact-target, duplicate, or stale-reminder stop condition returns the affected family to `shadow`.--### Rollback--Set enrolled users back to `shadow`; non-enrolled users were never cut over. Passive/Floating choice, Pause, and consent acknowledgment remain backward-readable but have no authority in legacy. Cancel any V2 prompt or pending start before changing mode.--## 11. Phase 5 — Notification lifecycle, passive recovery, and controls--### Goal--Complete the user-facing in-app notification policy without system notifications.--### Work packages--#### P5.1 Settings migration--Add typed settings for:--- suggestion mode: `passive` or `floating`;-- pause-until;-- excluded native families;-- excluded browser providers;-- “suggest only when my microphone is active”;-- end-nudge preference;-- setup-reminder dismissal by capability.--Migration:--- existing install with detector explicitly enabled → `floating`;-- existing install with detector disabled → preserve disabled state;-- new install → `passive`;-- browser remains separate opt-in;-- migration has an idempotent version marker and tests for absent/corrupt/old values.--#### P5.2 Reuse `MenuBarManager`--Extend the existing `NSStatusItem`; do not create a second status item.--Add a meeting suggestion presentation separate from active recording presentation:--- neutral icon/accessibility status;-- primary possible-meeting item with Start action;-- other candidates submenu;-- Not now, Pause, and source-exclusion actions;-- passive action persists until episode end, explicit Not now, exclusion, or capture start;-- active recording status remains higher priority than suggestions.--#### P5.3 Floating reminder policy--- shown only in floating mode for high-confidence candidates;-- never steals focus;-- one visible panel at a time;-- 30-second panel timeout preserves passive menu recovery;-- hover/keyboard interaction pauses timer;-- fullscreen other app, quiet mode, dictation overlay, or busy activity suppresses panel but preserves passive recovery;-- evidence loss removes both surfaces after the end grace;-- setup reminders follow `notDetermined`/`denied`/`restricted` semantics and never nag after explicit decline.-- place the panel on the display containing the detected application/window when resolvable, otherwise the active display;-- Snooze 10 minutes hides the current panel, preserves passive recovery, prohibits another panel for that episode, and keeps other candidates passive until expiry;-- “Why this appeared” shows only coarse evidence classes from the already-redacted decision record.--#### P5.4 Arbitration--Rank one floating candidate by:--1. confidence band;-2. same-process input ownership;-3. meeting-specific locator;-4. capture readiness;-5. most recent stable transition.--Other candidates remain separately selectable in the menu. Accepting one never merges or ends another episode.--### Files--- `SettingsStore.swift`-- `MeetingTranscriptionView.swift`-- `MenuBarManager.swift`-- `MeetingDetectionPrompt.swift`-- `AppServices.swift`-- new notification policy/controller tests--### Tests--- every settings migration path;-- Pause expiry never re-presents an existing episode;-- timeout keeps passive action; Not now removes it;-- exclusions take effect immediately and persist;-- active recording overrides suggestion icon/menu state;-- simultaneous candidate ranking and selection;-- fullscreen/quiet/busy suppression preserves passive state;-- permission dismissal is sticky until manual setup action;-- Snooze expiry never re-presents the existing episode;-- Why-this-appeared contains no raw observed values;-- multi-display placement follows the detected target with active-display fallback;-- menu actions and labels are keyboard/VoiceOver accessible;-- Reduce Motion path;-- one status item only.--### Exit gate--- Task tests confirm users can identify recording state, capture source, Start, Not now, and Stop.-- No duplicate in-app surfaces for one episode.-- Median unwanted floating reminders is at most one per active dogfood user-week.-- Source exclusions and Pause are immediately effective.-- No permission-repair repeat after denial or explicit decline.-- Existing menu-bar recording/processing states remain correct.--### Rollback--Disable V2 user-facing delivery and return enrolled users to `shadow`. New settings use backward-compatible defaults and remain inert in legacy. Remove suggestion menu items/panel state through targeted wiring reversal without replacing the existing `NSStatusItem` or reverting unrelated `MenuBarManager` work.--## 12. Phase 6 — Browser adapters and privacy cutover--### Goal--Move browser detection to V2 only for adapters that pass the Phase 0 privacy spike.--### Work packages--#### P6.1 Adapter interface--Each adapter returns only:--- supported provider enum;-- allowed meeting-locator classification;-- session-random locator digest;-- private-window status;-- health/availability;-- observation generation and time.--Raw URL/title values stay inside the adapter call and are discarded immediately.--#### P6.2 Fail-closed support matrix--An adapter is enabled only when it can:--- read the current page within a bounded deadline;-- distinguish private state reliably;-- match the allowed provider/path locally;-- reject landing, post-call, media, and unrelated pages;-- avoid all-tab/history scanning;-- pass supported browser-version fixtures.--Unknown private state equals unavailable, not normal browsing.--#### P6.3 Browser policy--- browser process input/output + verified current locator: five-second high-confidence candidate;-- temporary locator loss after verification: continuity for 15 seconds, never a new prompt;-- generic browser microphone ownership: no reminder;-- background/minimized behavior is supported only where the adapter retains a verified locator without broader tab collection;-- browser/native handoff ends or links episodes through explicit policy, never string similarity.--Every adapter begins in `browserShadow` while native V2 behavior remains unchanged. The local digest labels V2 browser counterfactual confirms directly; it does not infer truth from a legacy prompt. Only an adapter that passes the browser-specific preliminary and default-on gates advances to `v2` eligibility.--### Files--- `MeetingAutoDetectSignals.swift` split into adapter files if needed-- `MeetingAppRegistry.swift`-- new browser adapter/protocol files-- reducer policy tables-- browser fixture tests-- settings disclosure and provider exclusions--### Exit gate--Each browser/provider combination independently meets the Phase 3 precision and privacy gates. Failed adapters remain disabled without blocking native V2.--### Rollback--Set the affected adapter to unsupported and clear its ephemeral locator state. Native V2 remains unchanged. Persisted provider exclusions remain inert and backward-compatible; no raw browser state exists to migrate or restore.--## 13. Phase 7 — End assistance, health UX, and legacy removal--### Goal--Finish the detector lifecycle and remove temporary architecture after a stable rollback window.--### Work packages--#### P7.1 Conservative end assistance--While recording, continuation evidence includes any of:--- recent transcript output;-- exact capture target alive;-- same-family process input/output;-- verified meeting locator;-- qualifying native call marker.--After 60 seconds in which none of the above continuation signals is present—any one signal suffices—show one non-modal “Still recording?” nudge with:--- Stop recording;-- Keep recording.--State explicitly that stopping finalizes the local transcript. Keep recording suppresses further end nudges for that recording. No automatic stop.--#### P7.2 Health UX--Expose coarse capability states in Meeting settings:--- process attribution unavailable;-- monitor temporarily degraded;-- native window identity unavailable;-- browser adapter unavailable/private-state unsupported;-- capture permission missing.--Health never appears as evidence and never exposes observed content.--#### P7.3 Remove legacy path--After one stable dogfood release with no rollback:--- require the legacy implementation to have a user-authorized durable archive or Git commit before deletion; if it remains untracked-only, legacy deletion is blocked and the code stays in place;--- remove `legacy`/dual-decision code;-- remove legacy bundle-wide suppression;-- delete obsolete CandidateRecord/attemptConfirm state;-- keep replay fixtures as regression tests;-- retain a global detector disable switch as the operational kill path.--### Exit gate--- end nudge never auto-stops;-- recent transcript or transient mute prevents a premature nudge;-- Keep recording is sticky for that recording;-- degraded health is visible and actionable without prompting;-- full suite passes after legacy deletion;-- no dead legacy settings or migration paths remain.--### Rollback--End-assistance and health UI are independently disableable. Legacy removal has no runtime rollback and therefore occurs only after its durable-recovery precondition and a fresh user-authorized execution plan. Without that authorization, Phase 7 closes with legacy disabled but retained.--## 14. Phase 8 — Optional system notifications--This is deliberately outside initial detector completion.--Proceed only after Phase 5 notification burden and trust gates pass. Add a separate `System meeting notifications` preference, default off. Passive mode alone never opts a user into system delivery.--Reuse the authoritative episode, suppression, exclusion, and fresh-revalidation paths. The system and floating surfaces are mutually exclusive for one episode. Operating-system Focus behavior is inherited rather than inferred by FluidVoice.--### Rollback--Disable the separate system-notification preference, cancel pending detector notification requests by episode identifier, and retain in-app passive recovery. Notification permission state is operating-system state and is never treated as rolled back by code.--## 15. Cross-phase verification--### Per implementation slice--1. Run new unit tests for the slice.-2. Run `MeetingAutoDetectorTests`.-3. Run detector/reducer trace replays.-4. Build the application with code signing disabled.-5. Run `git diff --check` for tracked files and inspect full untracked target files.-6. Run a fresh adversarial code review before moving to the next phase.--### Phase gates--After Phases 1, 2, 4, 5, and 7:--- run the entire `FluidDictationIntegrationTests` target;-- compile detector changes with complete strict-concurrency checking and treat new warnings in changed files as failures;-- run a reentrancy/single-flight stress harness plus Thread Sanitizer; Thread Sanitizer alone does not prove actor isolation or prevent logical reentrancy;-- check CPU/wakeups in idle, relevant-app-running, stabilizing, and recording states;-- verify no detector network activity;-- inspect exported trace for forbidden fields;-- dogfood at least one native join muted, join unmuted, ordinary application playback, dismiss, timeout, capture start, and meeting leave.--### Main performance gates--- no synchronous HAL process enumeration or full window scan on main;-- no unbounded Accessibility traversal;-- no more than one relevant process-list enumeration per monitor refresh;-- no polling faster than one second;-- watchdog detects five missed expected refreshes;-- detector main-actor signposts remain below 4 ms p95 and 16 ms maximum in a 30-minute stress run;-- with no relevant app, average detector CPU delta stays below 0.2 percentage point and attributable wakeups below six per minute versus detector-disabled baseline;-- with a relevant app but no candidate, average CPU delta stays below 0.5 percentage point and attributable wakeups below two per second;-- while stabilizing, average CPU delta stays below 1 percentage point and attributable wakeups below four per second.--Measure with Instruments Time Profiler/Points of Interest and Energy Log, using identical feature-disabled and feature-enabled runs. If hardware noise makes an absolute gate inconclusive, repeat the paired run; do not replace measurement with subjective UI observation.--These budgets are provisional until Phase 0 records paired baselines on the development Mac. Phase 0 may tighten or relax a number only by recording the raw baseline, measurement variance, and an explicit reviewed replacement before Phase 1 begins.--## 16. PE execution protocol--Every phase follows the same cycle:--1. **Analyze:** re-read the phase targets, current diffs, prior phase evidence, and relevant replay fixtures.-2. **Plan:** produce a file/symbol-level implementation checklist and explicit invariants.-3. **Adversarial plan review:** fresh-context PE reviewer plus an external non-Claude review through `orchestrate`; rank findings by severity.-4. **Revise and lock:** resolve every blocker and major finding in the checklist before code.-5. **Execute:** delegate bounded implementation packages through the configured orchestration tier; the primary agent retains architecture and review responsibility.-6. **Verify:** focused tests, build, replay/stress checks, and privacy checks.-7. **Adversarial code review:** fresh-context review of the phase diff for duplication, magic constants, actor violations, stale-event loopholes, missing tests, privacy leaks, and behavior broadening.-8. **Fix and re-review:** a phase does not close on a `REVISE` verdict.--No phase is committed or pushed unless the user explicitly requests it.--## 17. Recommended first execution boundary--Begin with one additive Phase 0 slice only. Do not combine it with Phase 1 and do not request browser Automation permission.--The slice:--1. records the full worktree inventory and focused 48-test baseline;-2. adds one debug-only, Release-unreachable probe source under the file-system-synchronized application group, requiring no `project.pbxproj` edit;-3. performs process input/output and aggregate-device observation through one shared off-main CoreAudio pass;-4. emits append-only redacted JSONL containing reason enums, family categories, salted device-token hashes, and monotonic deltas—never names, PIDs, titles, paths, or URLs;-5. registers no listener that survives probe completion;-6. exercises app switching and sleep/wake stress;-7. records observed behavior and residual uncertainty in a local probe report.--The first deliverable answers:--1. Are process input/output selectors independently reliable on the supported macOS target?-2. Can audio helper processes be mapped to the correct application family without process-path heuristics?-3. Can every active input device and FluidVoice-owned loopback be identified stably?-4. Are HAL process enumeration and full window snapshots safe off-main under stress?--Browser privacy/TCC probing and production contract types are explicitly deferred until the first four answers, clock choice, self-observation rule, and actor single-flight contract have been reviewed. Only then may the remaining Phase 0 work and Phase 1 contracts be locked. This prevents the reducer and notification policy from being built on assumed sensor semantics.diff --git a/MEETING_DIARIZATION_V2_IMPLEMENTATION_PLAN.md b/MEETING_DIARIZATION_V2_IMPLEMENTATION_PLAN.mddeleted file mode 100644index 5fe328d5..00000000--- a/MEETING_DIARIZATION_V2_IMPLEMENTATION_PLAN.md+++ /dev/null@@ -1,510 +0,0 @@-# Meeting Diarization V2 — Evidence-Driven Implementation Plan--Status: **Revised after adversarial review**-Scope: post-meeting remote/application-audio diarization-Constraints: local-first, bounded resources, recoverable processing, no microphone or dictation regression--## 1. Outcome--Improve speaker separation and identity consistency, beginning with the measured failure where an-8:14 five-speaker recording produced four valid remote identities and absorbed a brief recurring-speaker into a dominant speaker.--The implementation is deliberately conditional. The same visible failure can be caused by five-different stages, and each requires a different fix. No long-window or clustering change begins until-a diagnostic pass identifies the stage that lost the speaker.--## 2. Current pipeline--1. Capture writes application and microphone audio into independent 60-second durability chunks.-2. Each application chunk is diarized independently with FluidAudio's offline pipeline.-3. FluidVoice reduces every local chunk label to one centroid and average quality.-4. `MeetingGlobalSpeakerStitcher` merges those label-level observations across chunks.-5. When the ASR provider supports word timings, each chunk is transcribed once and words are assigned- to diarizer turns in chunk-local time.-6. Final meeting segments retain paragraph/turn time ranges and text, not individual word timings.--This architecture makes one claim certain: once a brief participant has been absorbed into a local-chunk label, the final stitcher cannot reconstruct that participant from a mixed centroid. It does-**not** establish where the absorption happened.--## 3. Verified dependency behavior--These facts were verified against the currently checked-out FluidAudio fork, but must be re-verified-after the actual build revision is pinned:--- The offline diarizer uses 10-second segmentation windows with a 0.2 step ratio, AHC initialization,- PLDA/VBx refinement, and final timeline reconstruction.-- The URL path converts audio into a memory-mapped disk-backed source.-- Whole-file processing retains segmentation outputs, embeddings, clustering inputs, and- reconstruction arrays until completion. Audio is disk-backed, but peak memory still grows with- meeting duration.-- Final embedding assignments are recomputed using nearest-centroid similarity after VBx-derived- centroids. The plan must not describe the final timeline as a direct HMM-state output.-- Public `TimedSpeakerSegment.embedding` is the resolved cluster centroid repeated on every segment.- It is not an independent turn embedding.-- Raw timed embeddings and their cluster assignments exist internally. A debug export path can expose- them for local diagnosis, but it is not an acceptable production API.-- Default reconstruction uses exclusive segments and can trim overlapping speech. Short remnants can- disappear during sanitization.-- The embedding extractor can still produce evidence for short speech; the configured minimum affects- clean-mask selection and reconstruction behavior, so the exact failing stage must be inspected.-- `StreamingAudioSampleSource` and `process(audioSource:audioLoadingSeconds:)` are public in the- inspected checkout and may support a composed source without creating one monolithic scratch WAV.--### Dependency reproducibility blocker--`Package.swift` tracks the `altic-dev/FluidAudio` fork's moving `main` branch. The revision recorded in-`Package.resolved` and the current local checkout do not match, and the resolved object is absent from-the shallow local checkout. Before collecting a baseline:--1. determine the exact revision used by the installed/test build;-2. pin the package to an immutable reviewed revision or release;-3. clean-resolve and verify that the checkout, resolved file, build metadata, and evaluation report all- carry the same SHA;-4. re-check every API and behavioral claim in this document against that SHA.--Upstream documentation is research input, not proof of behavior in the pinned fork.--## 4. Competing root-cause hypotheses--| ID | Failure stage | What it would look like | Correct intervention |-|---|---|---|---|-| H1 | Local clustering under-merges | Distinct raw embeddings exist, but a 60-second pass assigns the brief speaker to a dominant cluster | Calibrate clustering or evaluate longer/global context |-| H2 | Overlap/reconstruction deletion | The brief speaker exists before reconstruction but is trimmed/dropped from the final timeline | Fix overlap/exclusive/min-duration policy |-| H3 | Embedding contamination | The brief speech's embedding is already acoustically close/mixed with the dominant speaker | Improve segmentation/masking/embedding model; longer context and downstream prototypes will not help |-| H4 | Cross-chunk stitcher merge | Local chunks preserve the fifth identity, but FluidVoice merges it globally | Fix the application-only stitcher; do not add whole-era processing |-| H5 | Word attribution error | Diarizer turns are correct, but ASR words cross the wrong boundary or are dropped | Fix time mapping and word assignment |--Whole-era diarization is the likely fix only for H1. It may conceal H4, and it does not inherently fix-H2, H3, or H5.--## 5. Design principles--1. **Diagnose before selecting architecture.**-2. **Capture chunks remain durability units, never presumed speaker boundaries.**-3. **Application and microphone behavior are isolated in code and tests.**-4. **A false merge is more destructive than a provisional split**, but weak noise must not become a- confident person.-5. **Acoustic evidence is authoritative.** Language context may flag ambiguity but cannot identify a- voice by itself.-6. **No repeated centroid may be presented as turn-level evidence.**-7. **No exact speaker count in product behavior.** Exact counts are evaluation-only oracles.-8. **Embeddings remain session-local and absent from exports, analytics, logs, and production debug- artifacts.**-9. **Word attribution is part of every diarization intervention**, not a later cleanup phase.-10. **No threshold changes without a development/held-out evaluation split.**--## 6. Phase 0 — Reproducible evaluation foundation--### 6.1 Pin inputs--- Pin the exact FluidAudio fork revision.-- Record the diarization model bundle fingerprint and relevant configuration.-- Record ASR provider/model/version, normalization configuration, pipeline version, and fixture hash.-- Add the diarization fingerprint to checkpoint compatibility checks.--### 6.2 Corpus--Create a local, gitignored evaluation manifest supporting:--- audio/session path;-- RTTM or equivalent reference speaker timeline;-- reference transcript with word times where available;-- expected speaker count;-- recurring-speaker relationships;-- overlap regions;-- capture discontinuities and known missing intervals;-- fixture tags such as short speaker, similar voices, overlap, boundary, and long meeting.--The initial development set must contain more than the measured fixture:--1. five speakers with two brief appearances by one person;-2. two clean speakers;-3. one speaker;-4. similar-sounding speakers;-5. short interjection during overlap;-6. a speaker first appearing at a 60-second boundary;-7. paired application/microphone audio with leakage and genuine local speech;-8. at least one 60–90-minute session for resource measurement.--Create a held-out set before tuning begins. User recordings remain local and gitignored. Commit only-synthetic fixtures or audio with explicit repository rights.--### 6.3 Metrics--Primary product metrics:--- speaker merge count;-- speaker split/fragmentation count;-- recovery recall by total speaking-duration buckets (`<1 s`, `1–3 s`, `3–10 s`, `>10 s`);-- recurring-speaker consistency across distant appearances;-- speaker-attributed word error / cpWER;-- word conservation: assigned once, explicitly ambiguous, or explicitly unassigned;-- microphone You/Unknown/echo classification on paired-track fixtures.--Secondary diagnostic metrics:--- DER with miss, false alarm, and confusion components;-- JER;-- speaker-count error;-- purity and coverage;-- plain WER;-- turn-boundary error.--Report both:--- a comparable diagnostic score with 250 ms collar and overlap ignored;-- a strict product score with zero collar and overlap scored, only when the hypothesis format actually- represents overlap.--Do not use speaker count, DER, or cpWER alone as a gate. A system can recover the requested count by-splitting the wrong person, while a brief merged speaker contributes little duration to DER.--### 6.4 Harness--- Port or wrap the pinned FluidAudio fork's DER/JER metric implementation into a repository-owned- evaluation tool.-- Extend the existing opt-in retained-meeting replay without ever rewriting source sessions.-- Emit per-stage reports and hypotheses into a user-selected or protected local temporary directory.-- Add deterministic synthetic unit tests for clustering logic independent of real audio.--Exit gate:--- one command produces repeatable baseline metrics and resource reports;-- the five-speaker failure reproduces;-- the held-out manifest already exists;-- dictation and paired-track microphone baselines are recorded;-- no source/model/revision mismatch remains.--## 7. Phase 0.5 — Decisive failure-stage diagnosis--This phase is mandatory and may stop the rest of the plan.--### 7.1 Diagnostic runs--For the failing fixture, run:--1. each original 60-second application chunk independently;-2. the contiguous application capture era as one diagnostic input;-3. the same inputs with `withSpeakers(exactly: 5)` as an evaluation-only oracle;-4. raw timed-embedding export in a debug/test-only build;-5. pre- and post-reconstruction timeline inspection;-6. current word-to-turn assignment inspection.--The debug embedding export must:--- be impossible to enable in production builds;-- write to a newly created `0700` directory and `0600` files;-- contain no participant names;-- be deleted on success/failure/cancellation and by next-launch stale-artifact cleanup;-- never be committed, uploaded, logged, or included in crash reports.--### 7.2 Evidence captured--- raw embedding count, window time, mask quality, and assignment;-- distance of the brief speaker's observations to every resolved centroid;-- cluster membership before and after final nearest-centroid reassignment;-- speaker timeline immediately before exclusive-overlap handling and sanitization;-- duration removed by overlap trimming/minimum-duration filtering;-- per-chunk local labels and the FluidVoice global stitch merge graph;-- diarizer turns versus chunk-local words, including every dropped/ambiguous word;-- NaN/invalid embeddings and any silent cluster-zero assignment;-- result under the exact-five oracle.--### 7.3 Decision tree--```text-Did the brief speech produce distinct raw embeddings?- no -> H3: segmentation/masking/embedding investigation- yes -> Did it form a distinct local cluster?- no -> H1: clustering/global-context experiment- yes -> Did reconstruction preserve the turn?- no -> H2: overlap/reconstruction fix- yes -> Did FluidVoice preserve it globally?- no -> H4: application stitcher fix- yes -> H5: word attribution fix-```--Exit gate:--- one hypothesis is supported by stage-local evidence on the target fixture;-- the same diagnostic is run on at least two additional fixtures;-- the selected implementation branch states why the other branches are not being implemented.--## 8. Conditional Branch A — Local clustering/global-context fix (H1)--Choose this branch only if distinct raw evidence exists but local clustering merges it.--### A1. Whole-era experiment--Evaluate one offline pass over each contiguous application-audio era. This is an experiment, not the-default architecture.--Implementation requirements:--- introduce a meeting-only analysis timeline that maps **analysis time ↔ meeting presentation time ↔- source chunk-local time**;-- extend/reuse existing epoch-boundary logic rather than creating a conflicting `MeetingCaptureEra`- concept;-- prefer a composed `StreamingAudioSampleSource` over a monolithic decoded scratch file;-- place decoded samples by source PTS, not by assuming encoded AAC frame count equals presentation- duration;-- measure AAC priming/padding per chunk and prove it cannot accumulate timeline drift;-- derive gaps from adjacent PTS directly, including gaps below the writer's 0.5-second discontinuity- threshold;-- split around corrupt/unreadable chunks, preserve `skippedChunkIDs`, and process healthy spans;-- never create turns spanning missing or unfinalized audio;-- keep post-meeting-only behavior: live captions remain You/Them and final speaker labels are published- only after processing completes.--Word attribution is part of A1:--- map global turns back into each chunk's local clock;-- run the current chunk ASR once with word timings;-- assign words to globally resolved turns;-- assert that each word is assigned exactly once or explicitly reported ambiguous/unassigned;-- preserve current zero nearest-turn tolerance on microphone audio.--### A2. Resource experiment before defaulting--Measure 8-minute, 30-minute, 60-minute, and 120-minute sessions:--- peak RSS and memory growth per audio hour;-- segmentation/embedding/clustering/reconstruction allocations;-- AHC and total wall time/real-time factor;-- temporary bytes and stale-artifact behavior;-- cancellation latency and dictation preemption latency;-- crash/retry cost, since the current checkpoint is after the complete application pass.--Whole-era processing may become the default only if resource growth and cancellation are acceptable on-the minimum supported Apple Silicon machine. Disk-backed audio alone is not sufficient evidence.--### A3. Bounded strategy if whole-era fails--If whole-era resource gates fail, design bounded sequential super-windows as the primary architecture,-not as an afterthought:--- select window/overlap duration from measurements rather than assuming 5 minutes/30 seconds;-- process one window at a time;-- reconcile the overlap with acoustic evidence and cannot-link constraints;-- checkpoint after each accepted window;-- freeze resolved IDs deterministically;-- prove no boundary-only label changes or duplicated transcript text;-- demonstrate peak memory independent of meeting duration.--Branch A acceptance:--- brief-speaker recovery improves in its speaking-duration bucket;-- no dominant speaker is merged or fragmented;-- paired-track You/Unknown/echo results are unchanged;-- chunk-local word attribution is correct across every chunk/era boundary;-- corrupt-chunk recovery and retry remain functional;-- dictation can preempt or cancel within a measured product budget;-- resource gates pass on long sessions and minimum hardware.--## 9. Conditional Branch B — Overlap/reconstruction fix (H2)--Choose this branch if clustering finds the speaker but reconstruction deletes or trims the turn.--Tasks:--- measure the effect of `exclusiveSegments`, overlap masks, minimum output duration, onset/offset, and- gap merging independently;-- preserve overlap when the source model supports multiple active speakers;-- do not lower a minimum globally without measuring false-alarm speakers;-- separate minimum duration for embedding evidence from minimum duration for displayed transcript- turns;-- preserve a short high-confidence turn even when it cannot yet be promoted to a durable identity;-- attribute overlapping words explicitly rather than forcing all text to one survivor.--Acceptance:--- short-overlap speaker recall improves;-- false-alarm speaker duration and nuisance speaker count do not materially increase;-- strict overlap-scored DER and speaker-attributed WER improve on held-out overlap fixtures.--## 10. Conditional Branch C — Embedding/segmentation fix (H3)--Choose this branch if raw evidence is already contaminated or indistinguishable.--Tasks:--- inspect speech masks and overlap exclusion around the brief turn;-- test shorter/multi-scale embedding windows while retaining longer context for voice quality;-- benchmark an alternative local segmentation/embedding model using the same clustering backend;-- preserve multiple independent observations only after proving they contain distinct information;-- reject long-context clustering and multi-prototype work until acoustic separability improves.--Acceptance:--- same/different-speaker distance distributions separate on the development set and hold out;-- the brief speaker becomes separable before final clustering;-- no material degradation on noisy, similar-voice, and single-speaker fixtures;-- local model, license, memory, and latency remain compatible with the product.--## 11. Conditional Branch D — Application-only global resolver fix (H4)--Choose this branch if local diarization preserves the speaker and FluidVoice merges it later.--Create a new application-only resolver. Do not modify the stitcher instance/type used by microphone-You/Unknown classification in the first change.--Resolver rules:--- consume independent raw observations, never repeated cluster centroids described as turns;-- retain up to four deterministic quality/duration-ranked medoids per speaker;-- different simultaneous local labels are cannot-link;-- labels already distinct in one local diarizer result are cannot-link;-- merge only below a calibrated distance with a first-versus-second ambiguity margin;-- enforce maximum pairwise diameter to prevent centroid chaining;-- weak observations may attach to strong cores but cannot move their prototypes;-- multiple consistent weak appearances may form one provisional speaker;-- unresolved evidence remains explicit rather than being forced onto the nearest dominant speaker;-- output is deterministic under input, chunk, and retry ordering.--Production use requires a stable FluidAudio API exposing raw timed embeddings, assignments, and defined-quality signals. The debug export is diagnostic-only. Decide during Phase 0 whether this is an upstream-change merged into the fork or a maintained pinned-fork patch with contract tests.--Acceptance:--- the fifth identity is preserved without splitting a dominant speaker;-- merge/split metrics improve on held-out sessions;-- a single noisy observation does not create a confident speaker;-- two consistent brief appearances can recover one identity;-- microphone stitcher output is byte-equivalent to baseline fixtures;-- paired-track You/Unknown/echo behavior is unchanged.--## 12. Conditional Branch E — Word-level attribution fix (H5)--Choose this branch if diarizer turns are correct but text is assigned incorrectly.--Tasks:--- preserve processing-time word IDs, text, start/end, and assignment outcome;-- make all three time domains explicit;-- define half-open boundary behavior and overlap ties;-- replace silent word drops with explicit counts and reasons;-- make the allowed dropped-word target relative to measured baseline before setting a stricter target;-- compute speaker-attributed WER/cpWER;-- add boundary tests for encoded-chunk priming, gaps, and diarizer turns spanning a capture boundary;-- decide separately whether product persistence uses `session.json` or a versioned local sidecar.--Acceptance:--- every ASR word is emitted once or explicitly ambiguous/unassigned;-- unexplained word loss improves from baseline;-- speaker-attributed WER improves without material plain-WER regression;-- retry is deterministic for an identical model/configuration fingerprint.--## 13. Shared reliability, privacy, and rollout requirements--### Checkpoints and cancellation--- Bump both processing-pipeline and checkpoint schema versions when compatibility changes.-- Record diarizer model/configuration/dependency fingerprint in checkpoint compatibility.-- Document that the current checkpoint is after the application pass; do not claim finer resume points- until implemented.-- Add explicit cancellation opportunities around long diarizer phases. Measure worst-case cancellation- latency because the dependency may not check cancellation internally.-- A failed V2 experiment may fall back only through a typed, recorded technical failure. Never choose a- result merely because it reports a preferred speaker count.--### Privacy--- Keep remote and microphone tracks separate.-- No cross-meeting profiles or real-name inference.-- No embeddings in session JSON, exports, logs, analytics, crash reports, or UI state.-- Production scratch files, if unavoidable, use protected directories/files, explicit deletion on all- exits, and stale-artifact cleanup after crashes.-- Debug raw-embedding export remains test-build-only and requires explicit local invocation.-- Any resumable embedding checkpoint requires a separate biometric-adjacent storage review and- authenticated encryption.--### Dictation and microphone isolation--- Initial implementation changes only post-meeting application-audio processing.-- Do not change capture writers, microphone diarization, echo detection, near-field gating, You- election, dictation providers, or dictation audio routing.-- Prove isolation with tests rather than relying on type boundaries.-- Run meeting echo, You/Unknown, multi-device dictation, route recovery, deadlock/freeze, and complete- dictation integration suites for every selected branch.-- Measure ANE/model contention and dictation preemption with a long application diarization pass.--### Rollout--- Put the selected V2 branch behind an internal flag.-- Replay V1 and V2 locally against the same immutable fixture manifest.-- Default new meetings to V2 only after development and held-out gates pass.-- Preserve V1 retry compatibility until retained-meeting replay and dogfooding show no regression.--## 14. Expected file areas--- `Package.swift` and `Package.resolved` for an intentional immutable dependency pin-- `Sources/Fluid/Services/SpeakerDiarizationService.swift`-- `Sources/Fluid/Services/Meeting/MeetingProcessingPipeline.swift`-- new application-only diagnostic/resolver/time-mapping files under- `Sources/Fluid/Services/Meeting/`-- `Sources/Fluid/Services/Meeting/MeetingModels.swift` for fingerprint/checkpoint metadata only when- required-- `Tests/FluidDictationIntegrationTests/SpeakerTurnMergingTests.swift`-- `Tests/FluidDictationIntegrationTests/MeetingExistingAudioReplayTests.swift`-- new local evaluation tooling with no committed user recordings or embeddings-- the pinned FluidAudio fork only if a reviewed public raw-observation API is required--## 15. Explicit non-goals--- cross-meeting voice profiles;-- real participant naming from voice;-- full live diarization during recording;-- changing capture chunk duration;-- changing the dictation ASR path;-- exact speaker-count configuration in normal product behavior;-- language-model-only speaker assignment;-- building all conditional branches.--## 16. Adversarial-review disposition--Three independent reviews agreed on the main correction:--- Kimi K3: **approve with revisions**; whole-era remains plausible after dependency pinning and a- stage-local diagnostic.-- Grok 4.6: **no-go beyond diagnosis**; the original linear plan overfit one fixture and used gameable- aggregate gates.-- Claude Opus: **do not start the original Phase 1**; the dependency's debug export can identify the- actual failure stage first, and whole-era memory/timeline assumptions were incomplete.--The revised plan adopts the shared blocking feedback:--1. pin and verify the actual dependency;-2. run a per-stage diagnostic decision tree;-3. make whole-era processing conditional rather than presumed;-4. treat overlap, raw-embedding availability, time mapping, word attribution, corrupt chunks,- cancellation, and long-session resources as first-class gates;-5. isolate any new application resolver from microphone behavior;-6. use merge/split and short-speaker recovery as primary metrics, with DER/JER as diagnostics.--## 17. Recommended next action--Implement only Phase 0 and Phase 0.5 first. The immediate deliverable is a local diagnostic report for-the failing five-speaker fixture showing exactly where the fifth speaker disappears.--That report—not architectural preference—selects Branch A, B, C, D, or E. This prevents a large,-technically elegant change from fixing the wrong stage.--## 18. Research sources--- FluidAudio documentation and source for the **pinned fork revision** (authoritative after pinning)-- Upstream FluidAudio offline diarization overview:- https://github.com/FluidInference/FluidAudio/blob/main/Documentation/Diarization/GettingStarted.md-- VBx theory:- https://arxiv.org/abs/2012.14952-- Multi-scale diarization decoder:- https://arxiv.org/abs/2203.15974-- NVIDIA NeMo diarization model design:- https://docs.nvidia.com/nemo-framework/user-guide/latest/nemotoolkit/asr/speaker_diarization/models.html-- Reproducible DER and diagnostic metrics:- https://github.com/pyannote/pyannote-metrics-paper/blob/master/paper.tex-- Overlap-aware diarization fusion:- https://arxiv.org/abs/2011.01997diff --git a/MEETING_ECHO_AND_LIVE_PLAN.md b/MEETING_ECHO_AND_LIVE_PLAN.mddeleted file mode 100644index a8b48007..00000000--- a/MEETING_ECHO_AND_LIVE_PLAN.md+++ /dev/null@@ -1,257 +0,0 @@-# Meeting echo handling and live transcription — measured plan--Status: **analysis complete, scorer built standalone, integration not started.** Measurements taken-2026-08-14 against a real 3.2-minute Zoom session (both raw tracks on disk).-------## 1. Corrected root causes--Two separate defects were conflated earlier. They need different fixes.--### 1a. Interjections swallowed by echo classification--`MeetingEchoDetector` scores a whole diarized turn by word containment against the far end. A turn-that is mostly speaker bleed but contains a short local interjection scores as echo, and the user's-words are hidden with it. Observed: "I'm testing." and "Notetaker." absent from our transcript,-present in a competitor's.--### 1b. One utterance split across a chunk boundary, labelled two ways--Observed: `119.09–120.12` → *Microphone / Unknown*, `120.06–127.53` → *You*. Same sentence, split at-the 120 s chunk boundary.--**An earlier diagnosis blaming per-chunk local-speaker resolution was wrong.**-`processMicrophoneTrack` stages turns across all chunks and calls `finishMicrophoneTrack` once, so-resolution is already session-wide. The real cause is cluster identity: the emit rule keys on-`turn.clusterID == localClusterID`, and the 1.04 s fragment was assigned a different cluster.-Diarization runs per chunk; a ~1 s fragment yields a weak embedding, and cross-chunk matching-(max cosine distance 0.35, ambiguity margin 0.08) rejects it.--Consequence: **signal-based echo scoring cannot fix 1b.** A turn in the wrong cluster is not labelled-`You` regardless of its echo verdict. 1b needs its own fix, un-designed as of tonight.-------## 2. Measurements--All on the real session, raw tracks, `microphone` vs `applicationAudio`.--### Alignment-- Both tracks decode to identical duration (192.400 s) — one shared `SCStream` clock.-- Delay by GCC-PHAT: mic content **leads** app audio by **31.9 ms**, std **0.3 ms** across the session.-- Drift **+6.9 ppm** (~25 ms/hour) — real, above measurement resolution, slow enough to track.-- Per chunk: −32.28, −31.97, −31.62, −31.38 ms. A smooth monotonic progression **through** chunk- boundaries (6.4 ppm), not discontinuities. AAC priming does **not** shift the tracks differentially.-- The 31.9 ms is a capture-pipeline offset, not an acoustic path. It is hardware-specific, can be- either sign, and Bluetooth output can invert it by 100–300 ms. **Never hardcode it; always estimate.**--### Cancellation potential-- Per-2 s frequency-domain Wiener filter: **9–11 dB ERLE** in echo-dominant blocks.-- A single session-wide filter achieves only 1.6 dB — drift defeats it. Adaptation is mandatory.-- Overall 3.9 dB, dragged down by blocks where the far end is silent (nothing to cancel).--### Turn-level separability (the decisive measurement)--Per-frame explained fraction = `1 − residual_energy / mic_energy`, 1024-sample frames, 256 hop.--| turn kind | n | mean | median | longest low-run (<0.35) |-|---|---|---|---|---|-| pure echo | 5 | 0.53–0.68 | 0.62–0.82 | **0.24–0.59 s** |-| contains local speech | 1 | 0.43 | 0.38 | **0.98 s** |-| local speech only | 3 | 0.02–0.03 | 0.00–0.02 | **0.96–10.27 s** |--**Mean and median cannot separate the mixed turn** — it sits between the two populations. The-**longest contiguous low-scoring run** does, with a clean gap: echo never exceeds 0.59 s, anything-containing local speech never falls below 0.96 s. This is the rescue statistic the design needs.--Caveat: one recording, one room, ten turns. The gap is real but the sample is small.--### Operating envelope of the rescue rule (found in code review, measured)--The statistic is `1 − residual/mic`. When local speech is **added on top of** echo — which is what-real speakerphone double-talk is — the fraction is approximately `echo / (echo + local)`. To fall-below `localSpeechFractionThreshold` (0.35) the local speech must therefore carry roughly-**1.86× the echo energy at the microphone**.--That holds comfortably for a laptop mic near the speaker's mouth with the far end coming from the-same laptop's speakers — it was satisfied throughout the real recording. It does **not** hold for a-quiet interjection over a loud far end, or a mic far from the user. That is the rule's operating-envelope, and it is a genuine limitation rather than a tuning constant: a louder threshold trades-directly against false rescues of pure echo.--Consequence for calibration: the held-out recordings must include a quiet-interjection case, not-just more of the easy one.-------## 3. Decisions from adversarial review--Reviewed by two independent external models. Both independently reached the same conclusions.--| decision | reason |-|---|---|-| Signal acts as a **veto only** on text-positive turns | Making it primary creates a new false-positive class that hides user speech |-| **Do not** feed signal evidence into `localSpeakerEvidence` | The purity rule `supporting > echoed` plus the 1.75× winner margin means a misclassification can elect the *far-end* cluster as "You" — a high-amplification failure |-| Three-state verdict: echo / containsLocalSpeech / **unknown** | Absence of reference audio is not evidence of local speech. Headphone users, silent far end, and low delay confidence must abstain, not score 0 |-| Turn aggregation must use the **low-run** statistic, not an average | Measured above; an average reproduces the exact bug being fixed |-| Reference audio must be gathered by **time range across all app chunks**, not chunk N ↔ chunk N | The two tracks' `MeetingAudioChunkWriter`s rotate independently and diverge permanently after a discontinuity on either track |-| Reference-read failure must be **total** (degrade to `.unknown`, never throw) | Today only the mic chunk's own `audioUnreadable` skips a chunk; a sick app track must not take down a healthy mic track |-| Exclude discontinuity-adjacent windows | A shared clock does not make content contiguous after dropped samples |-| Bump `pipelineVersion` when classification changes | Checkpoint reuse would otherwise mix classification rules mid-session |--Open, unresolved: threshold portability across hardware/rooms/volumes (one recording); non-speech-far-end audio (music, video) is a false-positive class today's text detector cannot produce; whether-to persist the score, and if so versioned against the scorer.-------## 4. Built--**`MeetingEchoSignalScorer.swift`** — pure functions over PCM: GCC-PHAT delay estimation with a-confidence measure, per-frame explained fractions with NaN for unscoreable frames, and a three-state-turn verdict using the low-run rule. Unit tested on deterministic synthetic signals.--**Integrated as a veto** (`pipelineVersion` 3 → 4). The design point both reviewers converged on is-**two separate echo fields**:--- `isLikelyEcho` stays **text-only** and remains the sole input to `localSpeakerEvidence`. Signal- evidence must never influence the local-speaker election — a misclassification there could elect- the *far-end* cluster as "You" through the 1.75× winner rule, which is a far worse failure than- any single mislabelled turn.-- `effectiveEcho = isLikelyEcho && signalVerdict != .containsLocalSpeech` drives **both** loss paths:- the `isCleanLocalTurn` assignment and the emitted echo flag that the UI and exporter filter on.--Supporting decisions:-- Reference audio is gathered by **presentation timestamp** across all intersecting application- chunks. Never by chunk index: the two writers rotate independently and diverge permanently after a- discontinuity, so a mic chunk can straddle two app chunks.-- Gaps are **zero-filled, not masked**. A zero-filled block has no reference energy, so the scorer's- own floor already forces those frames to NaN — an explicit mask would mean reopening a tested- module for no behavioural gain.-- Delay falls back to a **rolling median within a capture epoch**, never a session-wide scalar; an- epoch ends at any discontinuity on either track.-- Every reference failure degrades to `.unknown` and mutates nothing. A sick application track must- never skip a healthy microphone chunk.--**Known limits, deliberately documented rather than hidden:**-- Turns shorter than ~0.8 s can never be vetoed (`minimumLocalSpeechRunSeconds` is 0.75 s), so a- standalone backchannel — "yeah", "okay" — stays hidden. The measured failure case survives only- because those interjections sat inside a 25.9 s turn.-- The 1.86× energy envelope means a quiet interjection over a loud far end is not rescued.--Together these cap how much of the motivating bug this fixes. It is a real improvement, not a-general solution.-------## 5. Live transcription — shape only--Capture stays on ScreenCaptureKit. Voice Processing I/O is disqualified: instantiating it ducks all-other applications' audio system-wide, which would corrupt the very `applicationAudio` track we-record. Core Audio process taps are a permission-UX decision, not an echo fix, and risk zero-filled-buffers for WebRTC apps (Zoom, Meet, Teams).--**Decision (2026-08-14): no diarization during the meeting.** Live shows only *You* and *Them*,-derived from which track the audio arrived on — not from analysing voices. Speaker identity is-resolved after the meeting by the existing batch pipeline.--- **Live** — streaming ASR on both tracks. Mic = You, application audio = Them. Correct by- construction in any 1:1. **Depends on echo suppression**, or "You" transcribes the far end.-- **On meeting end** — today's batch pipeline runs unchanged and replaces the live text with the- word-aligned, properly diarized final transcript, turning *Them* into Speaker 1/2/3.--Why this ordering rather than a live diarizer:-- The streaming diarizer measured **1,011 MB resident** (see below). Deferring it keeps that- entirely out of the meeting, which removes the model-contention question rather than answering it.-- Streaming diarization is 10–15 % worse DER than the offline path, so deferring *improves* the- final transcript instead of compromising it.-- Label churn disappears: nothing can retroactively relabel text the user already read, because no- speaker decision is made live.-- Cost: in a 3+ person call, everyone else reads as *Them* until processing finishes. In a 1:1,- nothing is lost.--### Measured memory (2026-08-14, this machine)--| component | peak RSS | note |-|---|---|---|-| Streaming diarizer (Sortformer) | **1,011 MB** | real run, 56.7 s for 192 s audio (~3.4× realtime) |-| Nemotron streaming ASR | 688 MB | models loaded, then **failed** before transcribing |--The diarizer's 1 GB is far above its 21 MB on-disk footprint. Contention between the two was **not**-measured: Nemotron aborts with a CoreML `zero shape error` during type inference on ordinary 16 kHz-mono input, both full-length and on a 30 s clip with an explicit chunk size. That failure blocks the-live path itself, not just the measurement, and is the first thing to resolve.--Still open: whether one streaming ASR instance can serve both tracks, or whether two instances-(~690 MB each) are required.--Hard constraints, verified in FluidAudio at the pinned commit:-- Streaming ASR produces **no word timestamps** (zero `TokenTiming` references in the streaming- path). Our word→turn assignment cannot run live; final quality must come from the batch pass.-- Streaming "partials" only grow — greedy RNNT, never revised. `.provisional` would have meant- "growing", not "correctable". **As built, `MeetingTranscriptStatus.provisional` stays unused**:- live text is held in memory and published from the coordinator, never entering- `session.transcriptSegments`, so there is nothing to mark. That containment is deliberate — it- makes lowercase, unpunctuated live text unreachable by export and copy by construction rather- than by filtering, and means a crash or a failed batch pass cannot leave it posing as the- transcript.-- Streaming diarization is 10–15 % worse DER than the offline VBx pipeline in use today.-- Below ~560 ms chunks, WER degrades sharply (2.1 % → ~10 % at 160 ms).-- Nothing in FluidAudio combines streaming ASR with streaming diarization; we would align them.-------## 6. First real live run (2026-08-14, headphones, 2.5 min Zoom)--Live transcription ran end to end against a real meeting. Both tracks transcribed; "You" and "Them"-were correct by construction. Four defects found and fixed.--| defect | evidence | fix |-|---|---|---|-| Utterance spans swallow leading silence | mic EOU #1 reported `119.6s`; wall clock shows speech `18:56:32→18:57:11`, EOU at `18:57:13` | anchor `utteranceStartPTS` to the first decoded token, backdated one chunk, clamped to the previous utterance's end |-| ~5s of meeting-opening audio shed | 381 drops between `11.123` and `13.833`, then never again | run CoreML warmup on silence *before* `isModelReady`; queue 24 → 512 slots |-| 255 decoder resets and 255 degraded notifications in one burst | one `handleDrop` per dropped sample | coalesce to one resync per burst, applied by the drain loop |-| `handleEOU` reentrancy on `await manager.reset()` | `consume` could set a stale start during the suspension | dissolves — `consume` no longer touches utterance start |--**The endpointer is not slow.** EOU fires ~1.5–2s after speech stops, matching the model's 1280ms-debounce. An earlier reading of "78–120s latency" was a misinterpretation of the inflated spans.--## 7. Whole-chunk microphone fallback: neither echo classifier can score it--The same run put 60s of garbled far-end bleed in the transcript as `Microphone / Unknown`,-`isLikelyEcho=false`. Root cause: the whole-chunk fallback appends straight to-`accumulator.segments`, bypassing `stagedTurns` — and all echo classification runs over-`stagedTurns`.--Two candidate fixes were **measured and rejected**:--- **Text detector.** The bleed block scores **0.31** containment against its own 60s window- (threshold 0.5) — it would not be flagged. Genuine user speech from the same session scores- 0.05–0.29 even against the whole-meeting corpus, so widening the window is not the answer either.-- **Signal scorer.** A probe over the real chunks returns **no delay estimate and no verdict** for- the two bleed chunks (`verdict=nil, delay=none`); GCC-PHAT finds no confident echo path and- correctly abstains. Only chunk 2 scored, at `containsLocalSpeech`, delay `-50ms`.--Reproduce with `MeetingFallbackEchoProbeTests` (`TEST_RUNNER_FLUIDVOICE_ECHO_PROBE=<session dir>`).--**Actual fix:** `LabeledPassError.emptyTurn` no longer falls through to `transcribeWholeChunk`.-Diarization succeeding while every turn transcribes empty is positive evidence that the microphone-holds no intelligible speech; re-transcribing 60s of near-silence only produces hallucinated text-that is unattributable and unscoreable. Genuine diarization failure — including-`SpeakerDiarizationService.isSupported == false` — still gets the fallback. `pipelineVersion` 4 → 5.--Still open: `wordAttachmentTolerance` is `0` for the microphone (`MeetingProcessingPipeline:1463`),-which disables the nearest-neighbour rescue in `assignWords` and drops any word whose timing-disagrees with a diarizer boundary (observed `29/67`, `8/30` unassigned). Loosening it trades-directly against crediting bleed to the user; needs its own measurement.-------## 8. Deferred--Fluid One transcript cleanup (measured: ~648 ms/turn on a 1.5 B proxy model with prefix KV caching-on, ~2 min/meeting-hour; Fluid One is 3.3 GB so estimate 5–8 min — a background job, not a blocking-step). Vocabulary biasing for meetings is independent and cheap: the meeting pipeline does not use-`ParakeetVocabularyStore` / `PronunciationDictionaryStore` at all today, which likely explains-"Cloud Code" for "Claude Code".diff --git a/MEETING_M3_SPEAKER_IDENTITY.md b/MEETING_M3_SPEAKER_IDENTITY.mddeleted file mode 100644index 63e7d6a5..00000000--- a/MEETING_M3_SPEAKER_IDENTITY.md+++ /dev/null@@ -1,126 +0,0 @@-# M3 — Speaker identity: research and revised direction--Status: **direction changed**. The original M3 (voice profiles / remembered voice identities) is-withdrawn in favour of calendar attendees plus transcript inference. Research date: 2026-08-12.-------## 1. What the market actually does--Named-speaker attribution in this category is overwhelmingly **not** biometric. It comes from a-participant roster the tool obtains by joining the call.--| Attribution method | Products |-|---|---|-| Roster / attendee names from joining the call as a bot or participant | Bot-based meeting assistants, Zoom, Google Meet |-| Manual labelling only; naming by voice explicitly not offered | **Rev** ("supports speaker diarization but does not support speaker identification"), Descript |-| True persistent voiceprints | Microsoft Teams Voice & Face Enrollment, Sembly Voice ID, Fireflies, Circleback, Read.ai |--Two facts that decide our design:--- **FluidVoice cannot use the common method.** We are a standalone recorder: no bot joins the call,- so there is no roster and no per-participant audio stream. Only mixed application audio plus the- local microphone.-- **No major competitor ships on-device-only voice enrollment.** It exists as an SDK (Picovoice- Eagle) and in indie apps. There is no market-tested consent or UX pattern to copy.--Fallback behaviour for unknown speakers is universal: Teams, Fireflies, Descript and Rev all fall-back to generic "Speaker 1 / Speaker 2" rather than guessing.--## 2. Legal position on voiceprints--- Illinois BIPA expressly lists "voiceprint" as a biometric identifier. It carries a **private- right of action** with statutory damages ($1,000 negligent / $5,000 intentional) and, since- *Rosenbach*, requires no actual injury.-- Texas CUBI has no private right of action but is now aggressively enforced by the state AG- ($1.4B Meta settlement 2024; $1.375B Google 2025).-- GDPR Article 9: a voice embedding used to identify a person is special-category data. The EDPB's- virtual-voice-assistant guidance says biometric processing should **not** extend to- non-registered users — which would remove most of the feature's value in the EU.--Active litigation against directly comparable products:--- *Cruz v. Fireflies.AI* (C.D. Ill., filed 2025-12-18; second suit N.D. Ill. 2026-03). Plaintiff had- no Fireflies account, joined a meeting where the host had enabled it, and a voiceprint of her was- generated. Claims: no published retention schedule, no written notice, no written release from- non-account-holders.-- *In re Otter.ai Privacy Litigation* (N.D. Cal.) — same theory, stacked with federal wiretap and- California all-party-consent claims.-- *Basich v. Microsoft* (W.D. Wash., filed 2026-02-05) — alleges Teams' **default live- transcription** extracts voiceprint-like vectors without BIPA notice. Not the enrollment feature;- the ordinary path.--Microsoft geo-blocks its own opt-in Voice & Face Enrollment in Illinois entirely.--**On-device is not a safe harbour.** No court has held that vendor-inaccessible on-device-processing falls outside BIPA. Apple argued exactly that for on-device face grouping in Photos; a-class was certified in June 2026 regardless. On-device is a mitigation, not an exemption.--## 3. Decision--**Do not build voice profiles.** The value is concentrated in naming *other* participants, which is-precisely the litigated pattern, and we would be doing it without the roster that makes it-defensible for everyone else.--## 4. Revised design — calendar attendees plus transcript inference--Names come from the meeting invite and from what people say. Neither is biometric data, so the-BIPA / CUBI / Article 9 analysis does not apply, and no geographic gating or legal gate is required-before shipping.--**Sources of identity, in order of reliability**--1. **Calendar attendees.** Match the session to a calendar event by time overlap (we already record- `startedAt` / `endedAt` and `capturedApplication`). EventKit gives display names and emails.- This yields a *closed candidate set*, which is what makes everything below tractable.-2. **1:1 auto-assignment.** Two attendees and two voice clusters, one already identified as the- local user → the remaining cluster is the invitee. High confidence, covers a large share of real- meetings.-3. **Transcript inference for 3+ participants**, ranked by reliability:- - self-introduction ("This is Sarah", "Sarah here") → strong positive- - direct address ("Thanks, Sarah") → speaker is **not** Sarah; the next speaker probably is- - third-person mention ("Sarah said earlier") → weak negative on the speaker- With a closed candidate set this is a small constraint-satisfaction problem; ruling candidates- out is often enough to force the remaining assignment.-4. **Manual naming** — already shipped in M2 (rename / reassign / merge, with undo).--**Why the closed candidate set matters more than it looks.** Our ASR mangles proper nouns badly-(observed: "did I sign a lucron?", "She Spile Seashore"). Open-vocabulary name spotting would be-hopeless on that output. Fuzzy-matching against a *known* attendee list is robust — "Sara" / "Sera"-/ "Sarah" all resolve when the candidate set is known in advance.--**Consequence for shipped code.** `MeetingSessionSpeaker.diarizationEmbedding` and-`diarizationEmbeddingObservationCount` are currently persisted to `session.json` specifically so-"embedding/cluster provenance survives for M3". Under this design nothing needs them across-sessions. Stop persisting them; that also retires the *Basich*-style exposure on already-shipped-functionality. Within-session clustering still uses embeddings in memory — that is unavoidable and-is what every product in the category does.--## 5. Constraints and failure modes to design against--- Attendee list is **not** a speaker list. People skip meetings, extras join, two people share one- room. Never assume a bijection.-- Ad-hoc meetings have no invite. Manual naming remains the fallback and must stay first-class.-- Attendees may appear as bare email addresses with no display name.-- Recurring events, optional attendees, and delegated invites all pollute the candidate set.-- A wrong name is worse than "Speaker 2". Nothing may stick without explicit user confirmation —- this preserves the original M3 exit criterion of conservative candidates with Yes/No confirmation.-- Calendar access is a new permission prompt, on a product that has already spent user patience on- microphone and screen-recording permissions. It must be optional and requested in context.-- No cross-meeting memory by voice. Each meeting re-derives names from its own invite. This is the- privacy-preserving property, not a limitation to engineer around.--## 6. Phasing--1. **Shipped (M2)** — manual rename / reassign / merge with undo.-2. **Next** — calendar match plus 1:1 auto-assignment behind a Yes/No confirmation.-3. **After** — conservative inference for 3+ participants; confirmation still required.-4. **Cleanup, independent of the above** — stop persisting diarization embeddings.--## 7. Open questions--- Does the calendar match key on time overlap alone, or also on the meeting URL / captured app?-- What confidence bar must an inferred name clear before it is even *offered* for confirmation?-- Should a confirmed name persist to the calendar contact, so the same person is proposed faster in- a later meeting with the same invitee? (Contact-linked, not voice-linked — no biometric issue.)-- Do we surface "no invite found" explicitly, or silently fall back to manual naming?diff --git a/MEETING_MICROPHONE_ADMISSION_IMPLEMENTATION_PLAN.md b/MEETING_MICROPHONE_ADMISSION_IMPLEMENTATION_PLAN.mddeleted file mode 100644index e8813010..00000000--- a/MEETING_MICROPHONE_ADMISSION_IMPLEMENTATION_PLAN.md+++ /dev/null@@ -1,262 +0,0 @@-# Microphone speech admission and speaker-profile integrity--Date: 2026-09-08 (local)-Status: revision 7 — Stage A and offline B1/B2 plus eight-recording B3 development evaluation implemented. Five controlled recordings were added on 2026-09-09. Scoped Kimi reviews completed and findings addressed/dispositioned; no production approval is claimed. Current evidence still rejects threshold selection. No transcript/profile enforcement, runtime integration or app reinstall is included.--## Objective and relationship to existing work--Prevent playback remnants and unsupported ASR text from becoming accepted microphone speech or microphone speaker profiles, while preserving genuine quiet speech, short replies, overlap, and multiple people sharing a microphone.--This is a scoped execution plan for the microphone-admission P2/P3 work in `MEETING_RELIABILITY_IMPLEMENTATION_PLAN.md`. It does not replace that plan's corpus or release gates. `MEETING_RELIABILITY_P0_BASELINE.md` remains the baseline reference. Live-caption watchdog recovery is a separate workstream; this plan neither fixes nor gates it on microphone filtering.--Non-goals: lower microphone gain by default; add a hard universal volume cutoff; enforce one microphone speaker; restore a “You” election; change dictation or application-track diarization; replace ASR/AEC models; upload recordings or embeddings; automatically rewrite historical meetings.--## 1. Evidence driving the change--| Local fixture | User ground truth | Current output | Evaluation role |-| --- | --- | --- | --- |-| `3774ED4C…` (~100 seconds) | User did not speak | Seven microphone segments, 143 whitespace-delimited words, two represented microphone speaker identities, no echo flags | Development negative regression |-| `88E3BD44…` (~261 seconds) | User spoke only the supplied script near the end | Eight earlier microphone segments / 167 words; scripted speech retained around 208–250 seconds | Development negative intervals plus positive speech |-| `3B9AC1A8…` (~133 seconds) | User-reported playback-only | Prior false microphone text; live-caption blackout also investigated | Additional development regression; separate live issue |--The latest microphone recording has RMS approximately −56.4 dBFS, versus −27.8 dBFS for digital playback. In 32 of 48 two-second windows, the strongest waveform match occurs 55–70 ms after playback; median absolute correlation is only 0.108, versus 0.045 for a mismatched-reference control. These measurements support residual playback leakage but do not establish microphone gain, acoustic source distance, or the origin of every sound. They are not production thresholds.--The source video's captions around 34:05–35:43 corroborate several garbled playback phrases in the microphone transcript. Caption comparison is supporting evidence, not independently annotated audio truth. Do not use source-caption wording as a runtime whitelist or infer speech identity from semantic similarity alone.--All three recordings have already informed diagnosis and belong in development, never held-out acceptance. No claim of quiet-speech recall or statistical reliability follows from these few fixtures.--### Local competitor implementation findings--These are static observations from unpacked client snapshots, not current-service documentation, a runtime activation audit, or evidence that either product passes our fixtures. No competitor code was executed or sent to an external reviewer.--| Snapshot and inspected files | Verified mechanism | Applicability and limits |-| --- | --- | --- |-| Wispr Flow 1.6.492: `/Users/shreeram/Projects/wispr/reverse-engineering/wispr-flow-v1.6.492/extracted/.webpack/main/index.js` | FFT-based microphone/system comparison; repeated lag-stability checks; attack/release hysteresis; timestamped exclusion spans and epochs; conference-room latch; final encoder receives microphone-zeroing spans while original mic PCM is retained | Strong motivation for a temporal duplicate detector. Feature-dependent activation is unverified. Does not prove double-talk safety or successful detection on our low-correlation residuals. |-| Granola 7.498.1: `/Users/shreeram/Projects/granola/Granola - AI Notepad-unpacked/Granola-app-source/dist-electron/audio_process/index.js` and `main/feature-flags.generated-DtBFb_Zf.js` | Native capture wrapper receives echo-cancellation/headphone and gain-compensation options; separate microphone/system buffers and optional capture timestamps | Native cancellation implementation is not exposed here. Bundled defaults are not live feature settings. Do not infer that a flag means effective cancellation. |-| Granola 7.498.1: same source root, `dist-electron/local_diarization_process/index.js` | Segmentation/clustering, adaptive gain, energy-based activity backend, and a minimum voiced-duration check in the fallback embedding path | Supplied embeddings bypass that duration check; the inspected Community-1 path supplies cluster centroids. This is not independent clean-speech validation for every identity. |--Wispr's inspected defaults include an 8 kHz comparison stream, 16,384-point FFT, five consistent lag observations within an eight-observation history, three attack updates and a two-second release hangover. Its lag sign convention must not be assumed to match our analysis. These are reference implementation facts, **not proposed FluidVoice constants**. Its detector has fail-open and processing-budget safeguards; microphone zeroing is refused when preservation/reference checks fail.--Granola's worker applies bounded adaptive gain before its energy-based activity check. That check is not a neural near-end speech detector. The supplied-centroid bypass reinforces our requirement to validate profile provenance on every path rather than rely on the presence of a VAD-named component.--Design decision: adopt the architectural idea of temporal playback-duplicate evidence, independently implemented and calibrated locally. Do not copy proprietary implementation bodies, transplant thresholds, introduce adaptive gain, or zero original microphone audio. Keep the stricter shared speech-admission/profile contract below.--## 2. Verified code gaps--- `MeetingEchoSignalScorer.verdict` returns `containsLocalSpeech` for a sufficiently long low-explanation run. This measures failure to explain the mic with playback, not positive near-end speech evidence. Its rescue precedes the echo coverage gate.-- `MeetingProcessingPipeline.StagedMicrophoneTurn.effectiveEcho` lets that verdict veto both text and signal echo suppression.-- `trustedMicrophoneObservationKeys` excludes only text-echo turns. Global microphone stitching can therefore consume observations whose speech validity was never established.-- An observation key can represent a chunk-level speaker cluster shared by several turns. Accepting one clean-looking sibling cannot make the shared centroid clean.-- At the pinned FluidAudio revision, offline returned segment embeddings repeat cluster centroids; they are not independent interval embeddings.-- `MeetingModels` persists optional `isLikelyEcho`, and `MeetingTranscriptExporter` consumes echo visibility. A boolean cannot represent uncertain speech separately from echo.-- `MeetingFinalProcessingConfiguration` explicitly describes itself as inert. Adding a field there is not runtime enforcement; configuration must actually be captured and applied by the processing run.--Reconfirm call sites, runtime entry points and active consumers before implementation. Legacy local-speaker-election helpers/comments exist; do not reactivate them or assume they describe the current global-stitch path.--## 3. Contracts to implement--### Evidence, decisions and identity are separate--Introduce proposed `MeetingMicrophoneEvidence` and `MeetingMicrophoneAdmissionPolicy` types. Keep policy evaluation pure and deterministic. Evidence is timestamped in the original capture timeline, with explicit mapping to any adjusted display timestamps.--Evidence fields:--- protected capture era, route discontinuity, and interval coverage;-- playback context: `scoreablePlayback`, `verifiedNoPlayback`, `playbackExpectedButUnscoreable`, or `unknown`;-- local speech-detector output, coverage, model/artifact/version and unknown reason;-- playback explanation, delay confidence/coverage and text similarity as separate signals;-- temporal duplicate state, supporting-window count, lag spread, evidence freshness, transition reason and capture epoch; these are correlated with playback explanation and must not be double-counted as independent confidence;-- ASR provider/model and whole-chunk/per-turn/alignment fallback provenance, preserving failed alignment evidence through retries;-- overlap and interval duration;-- embedding provenance/quality, represented separately from speech validity.--Mandatory identity scope: session ID, chunk ID, turn index/key (`microphone:<chunkID>:<index>`), explicit observation reference (`microphone:<chunkID>:<label>` when available, otherwise unavailable), and capture epoch. One observation can have many sibling turns; the evidence contract must preserve that relationship. Never fabricate an observation key for an unassigned fallback. Temporal evidence additionally carries matching identity and interval scope.--Keep `noDelayLock`, `referenceUnavailable`, `unscoredCoverage`, and `scoredInconclusive` distinct; their Stage A compatibility projection may collapse to legacy `.unknown`, but their detailed reason must remain available to shadow evaluation.--Distinguish measured zero from missing data. No invented ASR confidence when the provider exposes none. Do not multiply correlated scores as independent probabilities. An active application track alone does not prove audible speaker playback; a missing reference does not prove silence.--Proposed decision outcomes:--| Outcome | Default transcript/summary/export after enforcement | Speaker-profile contribution |-| --- | --- | --- |-| `acceptedSpeech` | Included; identity may remain unknown | Only independently supported, clean interval evidence |-| `likelyPlaybackDuplicate` | Excluded; available in local review | None |-| `uncertainCandidate` | Excluded from default text; explicitly reviewable | None |-| `noSupportedSpeech` | No accepted text; evidence retained under retention policy | None |--Unknown identity is not uncertain speech. Accepted speech without usable embeddings remains readable under an unknown-identity label. A missing detector/reference must not cause all legitimate microphone speech to disappear.--### Decision rules before calibration--1. Preserve existing capture-era safety checks; record exclusion reasons and retain original audio.-2. Low playback explanation alone never proves local speech and never automatically rescues a likely echo.-3. Reliable playback-duplicate evidence with no independent near-end support favors `likelyPlaybackDuplicate`.-4. Mixed playback/local speech requires interval-level handling. A short local reply must not rescue the entire contaminated turn, nor must playback evidence erase the reply. Split only where timing evidence supports it; otherwise preserve an explicit uncertain candidate.-5. Speech-detector activity alone cannot distinguish leaked speech from near-end speech. In playback conditions, require jointly evaluated evidence; unresolved conflict stays uncertain.-6. Where playback is absent or reference unavailable, evaluate speech support without requiring an impossible echo match. In-room and reference-failure cases need their own calibrated paths.-7. `noSupportedSpeech` requires adequate negative evidence, not merely a missing model, absent confidence, failed ASR, or low amplitude.--These define semantics, not final score thresholds. Feasibility of separating nonlinear residual speech from quiet local speech remains an experimental gate. If available evidence cannot do it reliably, do not enable automatic suppression.--### Temporal playback-duplicate detector--Add proposed `MeetingPlaybackDuplicateDetector` with bounded state, injectable clock/configuration and deterministic paired-audio input. Implement offline shadow evaluation first; reuse of the component in live capture is a separate integration decision.--- Align microphone and reference using original capture PTS, explicit resampling and valid-sample masks. Account for chunk boundaries, discontinuities, AAC padding and clock drift. Define and unit-test the lag sign. Search a bounded lag range instead of hard-coding the observed 60 ms.-- Compute windowed playback similarity and lag evidence, with checks for available reference, usable energy, periodic/ambiguous peaks and match quality relative to deliberately mismatched reference. Low energy or missing coverage means insufficient evidence, not silence or local speech.-- Proposed states: `insufficientEvidence`, `observing`, `duplicateCandidate`, and `duplicateSupported`. Require repeated support with stable delay before advancing; use separately calibrated entry/release criteria. State is evidence, not an immediate instruction to hide or zero audio.-- Track onset uncertainty and a bounded release hangover. Never extend suppression automatically across an unobserved gap or let a conference-room latch hide an entire microphone track. Short local interruptions and simultaneous playback/speech require the shared policy's mixed-interval handling.-- Reset evidence on route/era/sample-rate changes, gaps and reference loss; require fresh support after reacquisition. Do not freeze a stale duplicate decision indefinitely. Record detector-unavailable/over-budget reasons and disable this evidence contribution on repeated failures; do not manufacture `acceptedSpeech` or `noSupportedSpeech` as a fallback.- Stage B1 binds capture epochs to the intervals between `MeetingProcessingPipeline.epochBoundaries` (either-track discontinuities), plus explicit route/reference discontinuities where no recorded boundary exists. Reuse the current ±`blockSeconds` discontinuity guard exclusions for initial evaluation; changing that guard policy requires separate tests/review. Invalidate prior evidence and delay state at the same boundaries, and keep samples masked by guards unavailable rather than treating the mask's zero values as silence.-- Preserve original audio. Candidate ranges are sidecar evidence mapped into transcript/profile decisions. Any future derived-ASR-input masking is a separate, reviewed experiment requiring positive-speech gates and recoverable originals; it is not in this implementation scope.-- Bound buffers, FFT/window work, pending jobs and evidence history. Run outside capture callbacks; emit no raw audio or transcript in routine metrics. Select latency/memory budgets from local profiling and freeze them before acceptance testing.--## 4. Incremental implementation sequence--### A — Evidence contract and semantics, behavior unchanged--Targets: `MeetingEchoSignalScorer.swift`, `MeetingProcessingPipeline.swift`; new evidence/policy files; `MeetingEchoSignalScorerTests.swift`, `MeetingEchoVetoTests.swift`.--1. Rename the in-memory verdict to `residualNotExplained` (or equivalently precise name), including thresholds/comments/log labels. This enum is not currently a persisted Codable field; do not invent an enum migration.-2. Preserve existing output behavior in a clearly named legacy mapping. Merely renaming must not silently remove the existing rescue and suppress real speech before validation.- The scorer body is mechanically renamed, not reimplemented: preserve rescue-before-coverage ordering, short-NaN-gap bridging, and the conjunctive trivial-run exclusion. The legacy mapping simply wraps the unchanged `effectiveEcho` boolean expression; characterization tests pin all these edge cases.-3. Add typed evidence and reason codes; represent unmeasured RMS/coverage explicitly rather than interpreting sentinel zero as a measurement.- Include the temporal detector's evidence contract and a fake implementation; do not load an audio model or enable suppression in Stage A.-4. Implement a pure shadow decision function with injected evidence. Mark uncalibrated outcomes experimental; no user-visible suppression.- Stage A invocation is **tests only**. No production call site, runtime flag, persistence, logging, model loading or fake detector wiring. Its deliberately conservative output is `uncertainCandidate` with diagnostic reasons; it does not yet produce accepted/no-speech decisions or calibrated would-suppress counts. Stage B introduces an explicit default-off shadow collection configuration; Stage D alone adds enforcement.-5. Add adversarial unit cases: low explanation with noise, garbled playback, short real reply inside echo, missing reference, empty/NaN coverage, identical real repetition of playback, two near-end people and no playback.--Exit: each test explicitly distinguishes the unchanged legacy result from the experimental shadow reason. In particular, characterize the legacy rescue separately from `legacyRescueDisagreement`, and do not assert aspirational filtering as legacy behavior. Tests compare turns/profile eligibility before and after invoking the pure shadow function; static call-site inspection confirms no production invocation. New scorer labels never describe low explanation as confirmed speech. This is not an end-to-end runtime shadow-mode test; that belongs to Stage B.--### B — Local evidence collection and shadow evaluation--Targets: processing pipeline; proposed `MeetingSpeechActivityDetector` adapter, `MeetingPlaybackDuplicateDetector` and tests; effective processing configuration and tests.--1. Audit the pinned local VAD API, available artifacts, licensing, sample rate, padding/context and probability semantics. Prototype with local cached models; no automatic network fallback during evaluation. Add an injected detector for deterministic tests.-2. Capture one immutable effective runtime configuration per attempt. Wire detector, admission mode and versions into the actual processing path; integration-test enforcement rather than only fingerprint equality.-3. Measure playback-conditioned speech support over bounded windows with monotonic timing and bounded buffers. Preserve chunk-edge context without concurrent unbounded model instances. Check cancellation and specify model-load failure behavior.-4. Attach shadow decisions before global stitching and final assembly; retain all current display/profile behavior. Count would-accept/would-suppress/would-exclude-from-profile outcomes separately.-5. Aggregate reason counts and durations locally. Raw audio/text/embeddings are not new default logs. Store any detailed evaluation sidecars separately from original sessions, with bounded retention and exclusive output creation.-6. Run the existing negative and scripted fixtures locally. Add controlled positives/negatives and annotations before threshold selection. Include comparison with detector-disabled baseline.--Deliver Stage B as three reviewable increments:--- **B1: temporal duplicate detector.** Implement timestamp-aligned paired-window measurements and state transitions above; run local negative fixtures with sidecar outputs only. Report lag distributions, lock/hold/release errors and unknown coverage. A consistent lag in our exploratory analysis is a hypothesis to test, not a sufficient acceptance criterion.-- **B2: speech evidence and combined policy.** Add the validated activity adapter and evaluate mixed-speech conflicts. Keep temporal similarity and existing echo explanation separate but acknowledge their statistical dependence. Do not turn weak correlation into positive local-speech evidence.-- **B3: calibration and ablations.** Compare unchanged baseline, existing echo evidence alone, temporal evidence alone, speech activity alone, and the combined policy on identical development recordings. Report false accepted words/identities alongside lost quiet/short/double-talk speech. Freeze the selected policy before held-out evaluation.--Exit: measurable operating-point tradeoffs, complete unknown/fallback reporting, bounded resource use and no shadow-mode change to persisted transcript or profile contents. If local VAD plus current evidence is insufficient, report that result and review a new detector/dependency scope rather than selecting an unsafe threshold.--### C — Independent speaker evidence and shared admission integration--Targets: `trustedMicrophoneObservationKeys`, pending/staged turns, `MeetingGlobalSpeakerStitcher`, `MeetingSpeakerEmbeddingIndex`, final microphone assembly.--1. Carry one decision identifier plus audio interval and evidence/policy fingerprint through every path. Profile eligibility and final text consumption must refer to the same decision, not recompute conflicting rules.-2. Replace the “any non-text-echo turn admits its observation key” rule. Mixed accepted/rejected siblings must not bless a shared cluster centroid.-3. Evaluate compatible clean-interval extraction. The public legacy `EmbeddingExtractor` is not assumed compatible with the offline model/PLDA space. A dependency extension needs its own reviewed API and compatibility tests.- Explicitly test supplied-embedding paths: a precomputed centroid must not bypass interval admission, minimum supported duration, overlap constraints or contamination checks. Minimum duration gates identity evidence only, not the visibility of otherwise accepted short replies.-4. Until compatible independent extraction is proven, exclude contaminated shared observations from profile updates while retaining accepted text with uncertain identity. Do not drop all accepted speech just because embeddings are unavailable.-5. Count trusted duration using the union of accepted, supported intervals, excluding overlap/duplication as required by the extractor. Do not count repeated centroids as independent observations.-6. Create speaker identities lazily from eligible evidence; remove unused candidate identities only from the new processing result, never destructively from historical sessions. Profile contributions must be traceable for session-local recomputation.--Exit: no rejected/uncertain interval can contribute through a sibling, retry, whole-chunk fallback or resumed run. Genuine multiple near-end speakers remain supported; the system does not pass merely by assigning everyone unknown.--### D — Versioned enforcement and consistent consumers--Targets: `MeetingModels.swift`, `MeetingProcessingPipeline.swift`, effective configuration/checkpoint logic, `MeetingTranscriptExporter.swift`, all discovered transcript UI/search/copy/summary consumers.--1. Add versioned persisted admission status, reason/provenance references and explicit legacy interpretation. Keep speech admission separate from `isLikelyEcho`; uncertain text must not be mislabeled proven echo.-2. Build a shared visibility/eligibility projection used by UI, copy/export, summaries and search. Review uncertain-candidate UX before enabling suppression. Summaries must not silently ingest hidden candidates.-3. Use explicit `off`, `shadow`, and `enforce` modes, default off/shadow until acceptance. Snapshot mode at attempt start, not midway through a run.-4. Bump processing version when final output semantics change (currently 10; choose the next unused value at implementation). Update mirrored defaults/tests and include actual policy/detector/artifact versions in attempt provenance.-5. Audit checkpoint contents and resume paths. Reuse only with matching effective fingerprints; invalidate/rebuild incompatible derived artifacts. Old sessions lacking new evidence remain legacy, not silently accepted under the new policy.-6. Reprocessing is explicit and transactional: prepare a separate result, preserve the original until success, handle cancellation/failure without partial replacement. No automatic historical migration.-7. Rollback must retain the meaning of previously persisted uncertain/rejected evidence; switching the flag off cannot reinterpret it as accepted. Verify compatibility before offering older binaries as rollback.--Exit: all consumers agree, compatibility/resume/cancellation tests pass, and held-out quality gates pass before enforcement is enabled.--## 5. Validation and release gates--Use the parent reliability plan's minimum corpus and statistical gates; this scope does not relax them:--- At least 12 independent negative sessions across three output configurations and two acoustic environments. Include real active-microphone playback, headphones, silence, noise, distorted playback and reference failure; synthetic zero/noise is a control only.-- Separate held-out quiet, brief-reply and double-talk positives: at least 30 annotated minutes across three independent recordings per condition, with at least 100 labeled short replies for that gate. Add multiple near-end speakers, in-room/no reference and real repeated playback phrases.-- Split by recording/device/speaker before tuning. Freeze policy structure, thresholds and splits before held-out evaluation. A failed held-out set becomes development data; obtain fresh held-out data for a subsequent quality claim.-- Zero accepted microphone words and zero represented false microphone identities on the curated playback-only regression set, with exposure and recording-level uncertainty reported. Extend negative screening to at least two hours per condition before release claims.-- At most one percentage point absolute increase in missed-speech duration and speaker-attributed WER per populated quiet/short/double-talk condition; report paired uncertainty and require upper bounds to meet the parent gates or mark evidence insufficient.-- No increase in false confident identities; at most one additional identity fragmentation event per annotated hour on echo-heavy held-out positives. Report unknown-identity coverage so an all-unknown system cannot pass.-- Separately report uncertain-candidate suppression, false words/minute, false identities/session, retained short replies, embedding coverage, latency/memory and capture drops. No new drops or unbounded growth during hour-long checks.--Required integration matrix: normal aligned output; low word/turn agreement and per-turn retry; whole-chunk fallback; silent/empty output; missing/corrupt reference; detector unavailable; protected/unprotected capture eras; chunk/route boundaries; mixed clean/contaminated cluster; stop/cancel; resume with matching/mismatching fingerprint; old-session read; new-result UI/export/summary parity; transactional reprocess failure; rollback interpretation.--Temporal-detector tests additionally cover positive/negative/zero lag conventions, reference timestamps shifted in both directions, wrong reference, music/periodic signals, nonlinear residuals with weak raw correlation, changing delay/drift, insufficient-energy windows, delayed/missing channels, AAC chunk padding, model-independent clock injection, detector budget exhaustion and freshness reset. Measure lock-onset/release latency and near-end speech lost during hold periods. Test a quiet reply while a duplicate state is already supported, not only isolated clean speech. Never compare competitor score thresholds directly with our exploratory normalized-correlation values without proving equivalent definitions.--## 6. Review, safety and delivery--Review after stages A/B and before enforcement: explicitly challenge all-speech-rejected, all-identities-unknown, repeated-centroid contamination, quiet double-talk loss, stale checkpoint and hidden-summary-leak counterexamples. Kimi K3 reviewed revision 2 through OpenCode in read-only plan mode. The six findings and their scope are recorded in `tools/MEETING_MICROPHONE_ADMISSION_PLAN_REVIEW.md`; revision 3 addresses test-only enablement, exact compatibility boundaries, identity keys, explicit test outcomes, epoch/guard alignment and distinct unknown reasons. That review is not sign-off on this amended document or the implementation. Any later external review receives scoped source/diffs only, not meeting recordings, transcripts, embeddings or secrets.--The existing FluidVoice source-review authorization does not automatically authorize sending Wispr/Granola bundles to an external model. Keep competitor inspection local; any separate disclosure requires appropriate authorization. Review temporal detector stale-state/latch behavior, threshold portability, and supplied-embedding bypass before enabling enforcement.--Preserve unrelated dirty-tree work. Do not install during the plan or shadow-data collection by default. Any later authorized Debug installation must follow AGENTS.md: same bundle ID/destination, valid deep/strict signature, matching designated requirement and Team ID, exact-app replacement, relaunch from `/Applications`. Stop before replacing the app if identity cannot be preserved.--Deliver each stage as a separately reviewable change with test evidence. Recommended first implementation unit: **Stage A only—typed evidence, precise naming with a legacy compatibility mapping, pure shadow decisions and regression tests.** No gain change, profile filtering, transcript suppression or app reinstall in that first unit.--## 7. Stage A execution record--Implemented after the user's review-and-proceed request:--- `MeetingEchoSignalScorer.swift`: renamed the verdict and low-explanation threshold identifiers; numeric thresholds and scorer control flow are unchanged. `legacyEffectiveEcho(textEcho:)` preserves the historical display truth table.-- `MeetingProcessingPipeline.swift`: uses the compatibility mapping and precise verdict name in diagnostics. Text-only profile eligibility is deliberately unchanged at this stage.-- `MeetingMicrophoneEvidence.swift`: non-persisted, immutable evidence/identity types; explicit missing-vs-zero and unknown reasons; temporal source protocol. The conservative pure shadow policy returns experimental uncertainty plus reasons, not calibrated admission or profile eligibility.-- `MeetingMicrophoneAdmissionContractTests.swift`: fake temporal source and characterization tests. Existing integration-test enum references were mechanically updated.--Validation: isolated `FluidASRBaseline` build-for-testing succeeded; 15 admission-contract tests and five existing live diagnostic tests passed, with zero failures/skips (`/private/tmp/fv-admission-stage-a-v1.xcresult`). A normalized source comparison confirmed the scorer's `verdict` body matches HEAD after identifier substitutions and comment removal. Static call-site inspection found shadow evaluation and the fake temporal implementation only in tests. The broader app integration suite and a Release build were not run; existing unrelated compiler warnings remain.--The known generated CTranscribe framework packaging defect required repairing only the isolated host's version symlinks, retaining the replaced build artifacts in temporary backups, then signing and deep/strict verifying that test host. The installed Debug app was not changed. No recording was opened, processed, reclassified, or sent to the external reviewer during Stage A.--Next implementation unit: Stage B1, real temporal duplicate measurements on local development fixtures with sidecar-only results. Stage A does not reduce the false microphone words yet, and its all-uncertain proposals cannot satisfy the release gates.--Post-implementation review attempt: Kimi K3 was asked to inspect the new evidence/test files and the two production diffs in read-only mode. That follow-up timed out at 180 seconds without findings. The completed revision-2 plan review and local verification stand; there is **no completed external code sign-off** for Stage A. Complete that code review before Stage B integration/enforcement.--## 8. Initial Stage B1 execution record--Implemented `MeetingPlaybackDuplicateDetector.swift`, the explicitly invoked offline `tools/meeting_temporal_shadow.swift` evaluator and 11 detector tests. No detector result is projected into turn admission or profile eligibility, and no production caller was added. Detailed configuration, implementation limitations, reproducible commands and numeric results are in `tools/MEETING_TEMPORAL_SHADOW_B1.md`.--The three development recordings produced zero supported locks at the initial experimental operating point: 196 of 244 windows were scored but inconclusive; 48 had insufficient coverage/energy. Unwindowed tails remain unmeasured. This does not establish useful weak-residual detection, speech recall, or a false-caption fix. Thresholds were not tuned downward after seeing these outcomes. Do not enable suppression from this result; B2/B3 and potentially a stronger temporal feature remain necessary.--Validation: final isolated baseline-host build succeeded; 31 targeted tests passed with zero failures/skips (11 detector, 15 Stage A contract, five existing live diagnostics), `/private/tmp/fv-temporal-b1-v3.xcresult`. The offline optimized evaluator compiled and ran locally on all three inputs; final sidecars are the v2 files documented in the report. No full app integration suite, Release build, held-out accuracy test or hour-long capture-load test was run. The existing generated framework packaging repair/signing was confined to the isolated test host, with displaced files retained in temporary backups. Installed Debug app unchanged.--Adversarial code review was retried with authorized Kimi K3 (180-second initial call and 300-second continuation) and Grok 4.6 (180 seconds, embedded scoped source only). All attempts timed out without returned findings. No review completion or sign-off is claimed. The completed earlier plan review is not code approval. Keep B1 offline-only until a completed code review and subsequent evidence gates; do not infer permission to integrate/enforce from this implementation record.--## 9. Initial Stage B2 execution record--After the user's “do it”, added a direct local CoreML speech-activity adapter, an injected model seam, bounded recurrent-state evaluation, and a conservative speech/playback diagnostic combination. The standalone CLI explicitly opts in with a local model argument; no production consumer exists. Cached model schema and aggregate-probability semantics were audited against the pinned source and local model graph. There is no model download, gain adjustment, app install or output suppression.--Three local development recordings yielded 1,916 full speech frames, including 153 active diagnostic windows and 24 unknown frames; all combined proposals remain uncertain. Both user-reported playback-only fixtures contain active windows, while temporal matching still has zero supported locks. This is evidence against enabling this simple combination as a near-end admission gate. No speech recall, false-word reduction, independent-person accuracy or held-out acceptance claim follows from these counts.--Kimi K3 completed three scoped reviews covering B1 core, B2 adapter/evaluator and the Stage A contract. Changes include exact integer lag-spread comparison, session-local failure latches, full-coverage temporal joins across mismatched frame grids, explicit unavailable controls and missing-playback-context diagnostics. Exact Stage A snapshot binding and cleared support counts after release are deliberately retained. Full finding dispositions, model audit, hashes, numeric results and verification are in `tools/MEETING_SPEECH_SHADOW_B2.md`.--The earlier review timeouts remain in the historical records above, but no longer describe the current review status. Post-fix code has not been independently re-reviewed in full and is not approved for enforcement. B3 annotated evaluation/calibration, effective app shadow integration, profile provenance, consumer consistency and release gates remain outstanding. The legacy echo score is not measured by this CLI, so the current two-signal comparison is not the complete planned ablation.--Final verification: isolated baseline-host build succeeded; 46 targeted tests passed with no failures/skips in `/private/tmp/fv-speech-b2-v3.xcresult` (11 speech, 13 temporal, 17 admission-contract, five live diagnostics). Final local fixture sidecars are the v2 files in the B2 report. Full app/Release, capture-load and held-out tests remain unrun. Installed app unchanged.--## 10. Existing-data Stage B3 execution record--After the user's “go”, added a versioned development annotation manifest and aggregate-only B3 evaluator with unit tests. The evaluator binds each sidecar to session bytes, pinned detector/model provenance and independently recomputed audio duration. It explicitly counts unknown/boundary/outside evidence and current transcript words without emitting transcript content or identities. All thresholds are descriptive; there is no selected/frozen operating point or production caller.--The available set has two pure-negative recordings, one mixed-label recording containing a negative interval plus only a coarse script region, and zero independently frame-labelled positives. Current saved output contains 324 visible microphone words and four per-session visible speaker slots in known-negative intervals; one saved echo segment accounts for seven additional hidden words. This is current-output inventory, not a projection of the candidate policies. The coarse script region contains 89 visible words whose accuracy is unverified.--At the cached VAD's 0.85 diagnostic threshold, 31/1,691 known-negative measured frames are still accepted while 121/161 coarse-region frames are accepted. A 0.04 threshold accepts 160/161 coarse-region frames but also 549 negative frames. Because frames are correlated and the coarse region contains unlabelled pauses, neither ratio is speech recall or an independent trial estimate. B1 has no supported locks, making temporal-only identical to accept-all and combined identical to speech-only on these inputs. No threshold is safe or selected.--Kimi K3's B3 review found eight issues across two passes: denominator drift, hard-coded frame duration, silent transcript-boundary exclusions, ambiguous overlapping cohort counts, selection-flavored reporting, empty annotations, unpinned model hashes and sidecar-only duration bounds. All were addressed; final post-fix verification returned no findings, and 11 evaluator unit tests pass. Final report and review dispositions: `tools/MEETING_ADMISSION_B3_DEVELOPMENT_EVAL.md`; aggregate artifact: `/private/tmp/fv-admission-b3-dev-v7.json`. No app build/test was required for evaluator-only changes; the last Swift validation remains B2's 46 passing targeted tests. Installed app unchanged.--## 11. Controlled Stage B3 extension--The user completed five separate development recordings with the installed app: playback only; normal speech without playback; quiet speech without playback; three normal-voice repetitions over the same YouTube playback; and two sequences of five quiet replies over that playback. The user confirmed that YouTube playback used speakers, their speech entered through the microphone, no headphones were used, and nobody else was speaking nearby. The runs ranged from 10 to 159 seconds. Every microphone/application track completed with zero recorded dropped samples, discontinuities or failures.--The existing offline B1/B2 CLI created numeric-only sidecars for all five without modifying the sessions. The playback-only run yielded four visible microphone-attributed segments and 49 words despite user-reported silence. B1 found no `duplicateSupported` window in any controlled run; three isolated candidates in the playback-only run did not satisfy stability. At diagnostic speech threshold 0.85, 10/600 controlled playback-only frames were accepted, while 137/445 frames in coarse user-speech regions were accepted. Those coarse regions contain pauses and playback-only time and are not recall denominators.--Across the eight-recording development set, threshold 0.04 accepts 681/2,291 known-negative frames and 507/606 coarse-region frames; threshold 0.85 accepts 41/2,291 and 258/606 respectively. The temporal ablation remains identical to accept-all because there are no supported locks. No operating point is selected: there is still no independently frame-labelled positive recording or held-out set, and transcript-localized overlap intervals are explicitly non-independent. Current aggregate artifact: `/private/tmp/fv-admission-b3-controlled-v3.json`. Full method, limits and hashes are in `tools/MEETING_ADMISSION_B3_DEVELOPMENT_EVAL.md`. The installed app and runtime behavior remain unchanged.--The next evidence gate requires independently timed quiet, normal, short-reply and double-talk recordings. These become development data; separate recordings remain required for held-out evaluation. Do not proceed to runtime shadow integration, threshold freezing, suppression or profile filtering from this result.diff --git a/MEETING_MODEL_RESIDENCY_PLAN.md b/MEETING_MODEL_RESIDENCY_PLAN.mddeleted file mode 100644index bd6cb1c9..00000000--- a/MEETING_MODEL_RESIDENCY_PLAN.md+++ /dev/null@@ -1,71 +0,0 @@-# Meeting model residency plan and implementation--Status: implemented, installed locally and running; regression, RAM and private-build evidence is recorded below. No release, commit or model download is part of this change.--## The sequence--1. Acquire the existing meeting/audio lease. Reject busy model operations before unloading anything; do not interrupt an active generation or installation.-2. Close ordinary model admission and snapshot actual loaded model IDs/configurations. No model references or selected-but-unloaded models enter this snapshot.-3. Unload dictation providers and Fluid. Await actual helper exit. Invalidate queued startup/dictation warmups.-4. Run the meeting backend. The Nemotron/WeSpeaker/Parakeet backend already has sequential scoped model owners. The legacy backend is also gated, but retains its existing diarizer + selected-ASR implementation and memory profile.-5. If a summary provider is registered, save the transcript first, load/generate through the adapter, and await cleanup on success, error or cancellation. Summary errors remain separate from the transcript.-6. After all meeting work has returned and its resources are released, restore only eligible snapshots, serially. Selection changes and explicit unloads can veto restoration; they cannot add a new model. Never download or delete files as part of restoration.-7. Resume ordinary admission and idle unloading. Quit suppresses restoration. Failed restoration leaves the model unloaded and logs the error without discarding a successful transcript.--```mermaid-stateDiagram-v2- Normal --> Suspending: snapshot actual residency- Suspending --> Transcription: all old resources released- Transcription --> Summary: transcript saved and provider configured- Transcription --> Cleaning: no summary- Summary --> Cleaning: provider drained and unloaded- Suspending --> Cleaning: error or cancellation- Transcription --> Cleaning: error or cancellation- Cleaning --> Restoring: meeting resources released- Restoring --> Normal: eligible snapshots restored or unloaded fallback- Normal --> Terminating: quit- Restoring --> Terminating: quit suppresses further loads-```--Quit also applies from every intermediate phase. Cancellation never frees an in-use model underneath its inference call: the gate stays closed until that call returns. There is no persisted busy flag and no automatic replay of rejected warmups.--## Code ownership--- `MeetingModelResidencyCoordinator`: MainActor admission, unique generation per lease, scoped owner/model grants, immutable snapshot list, vetoes and joined restoration. A reused attempt ID cannot revive an old grant.-- `ASRService`: actual successfully loaded model identity; unload all speech-provider caches before meeting work; restore only a still-selected, installed snapshot. Existing meeting-ASR ownership drains Parakeet before returning.-- `PrivateAIIntegrationService`: guards load, prepare, verify, prewarm, inference and status paths. Update admission spans installation through commit/rollback. Idle unloading pauses during the meeting.-- Private bridge: captures actual ready runtime/configuration, restores without the settings action that deletes inactive models, and awaits helper exit. Retired helper clients reject late status calls instead of launching another process.-- `MeetingProcessingPipeline`: wraps both backend contracts, saves the completed transcript before optional post-processing, and returns summary errors separately.-- `MeetingSessionCoordinator`: still checks operation generation before publication; cancellation during optional summary can preserve a finished transcript when the attempt is still current.--## Summary plug-in contract--`MeetingPostProcessingProviding` supplies provider/model IDs, an input-character bound, non-loading readiness, preparation, and idempotent cleanup. `PreparedMeetingPostProcessor` supplies generation and awaited cancellation/unload. Provider cleanup must also drain a failed partial preparation. Neither cleanup may return while its model is still running.--Requests contain session/attempt IDs, transcript hash, language, speakers, segments and coverage gaps. Output contains a summary plus source-segment IDs. The host rejects oversized input, empty/oversized output and unknown source IDs. Artifacts are saved separately with model/provider provenance. No provider means no-op; no model has been chosen or downloaded. A real adapter still needs model-specific context limits, generation policy and its own memory measurements.--## Validation--- Deterministic tests cover actual-residency-only restoration, busy admission, vetoes, cancellation during non-cooperative work, partial suspension/snapshot failure, restoration failure, termination, stale/reused grants, legacy speech-only grants, queued warmup invalidation and summary preparation/generation/citation/cancellation failures.-- Real shared-service runs cover Parakeet loaded with Fluid unloaded, and Parakeet + Fluid Mini both loaded. They verify original identities return and the old helper exits before meeting inference.-- Full recording: **2.51 GB** meeting peak without Fluid initially loaded; **2.77 GB** with Fluid initially loaded and suspended. Approximately **9.8 seconds** processing. Text, 5,650 word timings and 789 speaker-activity entries unchanged. Original recording/session retained.-- [Measured report](build/meeting-model-residency/report.md) and [raw metrics](build/meeting-model-residency/measurements.json).-- Final regression: 108 tests passed; two opt-in experiments skipped in that run (the full-recording experiment was run separately above). Strict lint: zero violations. Private build/install and deep signature verification passed. Installed Mach-O UUID: `4DF0945A-2C94-3BCF-8A57-6CB5A9FE999C`; local health reports `1.6.10-beta.6`. Final test/build/install logs: `/tmp/fluidvoice-residency-regression.log`, `/tmp/fluidvoice-residency-lint.log`, `/tmp/fluidvoice-residency-install.log`.--## Practical limits and release follow-up--The full-recording benchmark uses the production model owners and residency coordinator, but the continuous mixed timeline remains experimental. This change does not silently replace the selected production transcription backend.--A 3 GB total cap is not guaranteed: restoring multiple previously loaded models can exceed it. The measured pre-meeting app/helper sum was 5.07 GB and the restored sum peaked at 3.15 GB; shared pages may be counted twice. No real summary model, Intel/older-macOS runtime, non-Parakeet round trip or physical first-word microphone check has been validated here. There is no forced timeout for an in-process CoreML call: it must finish before safe unloading; no cancellation watchdog UI was added.--The private bridge and private build wrapper are intentionally gitignored. This local test uses an explicit development-only bridge override after validating the pinned runtime. The changed bridge must be integrated and verified in the private FI release source before distribution; no FI pin or production manifest was changed. An older bridge with an already-loaded model fails before suspension rather than silently losing restoration eligibility.--## Additional independent review and production replay--Three reviewers audited and fixed VAD/enrollment admission, restoration veto races, private helper replacement and residency evidence, summary failure/cancellation handling, and equal-time word ordering. **154 tests pass**, including six production replays of two large recordings with twelve file-dictation calls. See [review and measurements](build/residency-review/report.md).--The final full-workflow sampled peak is **5.460 GB**, so the requested 3 GB total budget **does not pass**. During meeting inference, sampled speaker-identification/transcription maxima are 2.475/1.622 GB; restoration plus dictation reaches 3.727 GB. After explicit unload and 30 seconds, 132 MB remains and every test helper has exited. No accumulating growth was observed over six runs. The production speaker count on the larger meeting is still 17; this review does not establish speaker accuracy or replace the experimental continuous-audio path.--Reviewed private build installed and launched: UUID `2FBCCA22-B25C-33EC-9555-374CE521487C`; signature and health checks passed. This supersedes the earlier installed UUID recorded above.--Isolated reproduction correction: speaker detection briefly reached **3.341 GB without a Fluid helper**, so meeting-only memory is not reliably below 3 GB. Fresh pre-unload total was 4.776 GB; post-restore 3.722 GB. Large empty allocator regions were observed in vmmap. Detailed evidence: `scratch/residency-recheck/report.md`.diff --git a/MEETING_OVERLAY_IMPLEMENTATION_PLAN.md b/MEETING_OVERLAY_IMPLEMENTATION_PLAN.mddeleted file mode 100644index 78734cf3..00000000--- a/MEETING_OVERLAY_IMPLEMENTATION_PLAN.md+++ /dev/null@@ -1,457 +0,0 @@-# Meeting overlay visual unification — implementation plan--Status: **implemented through the code-hardening gates on 2026-08-25. Unsigned test build succeeds,-14 focused meeting/dictation overlay tests pass, and the final adversarial implementation review is-APPROVE. Remaining release gates are manual visual/interaction testing, the VoiceOver checklist,-multi-display/full-screen/screen-share checks, and the two-hour soak.**--## 1. Product decision--FluidVoice keeps dictation and meeting overlays independent at the lifecycle and settings layers,-but both use the same visual primitives. Meeting recording exposes two presentation choices:--- **Pill** — a persistent 84×32 recording control suitable for a long meeting.-- **Captions** — a fixed-size rolling subtitle strip, initially 480×132.--The saved meeting preference is independent from the dictation overlay size. A user can therefore-use Compact/Small for dictation and Pill for meetings. Clicking the meeting Pill temporarily expands-to Captions; collapsing returns to Pill. A preference change applies at the **next meeting start**;-it never overrides temporary presentation choices in an active meeting.--The on-demand resizable full captions window remains a separate destination. It is not a third-meeting-overlay preference.--## 2. Goals and acceptance criteria--### Product--- Pill and Captions use the established dictation overlay as the canonical visual recipe: same black- surface, border vocabulary, shadow, waveform vocabulary, and spacing scale. Meeting-specific- differences are limited to content and long-duration motion.-- Meeting and dictation preferences are stored independently.-- The visible Pill remains exactly 84×32 and unobtrusive for the entire meeting; its panel is larger- only to reserve transparent shadow/hit-test insets. Stop remains immediately available.-- Pill ↔ Captions morphs in place without opening a second panel, jumping screens, or losing the- user-positioned anchor.-- Captions update without resizing the panel for each partial transcript update.-- Meeting recording lifecycle, stop behavior, degraded states, and full captions remain unchanged.--### Accessibility and platform behavior--- VoiceOver exposes recording state, expand/collapse, Stop, and caption content without duplicate- announcements for rapidly changing partial text.-- Reduce Motion removes the spring/large geometry interpolation and uses an immediate resize plus a- short cross-fade, or no animation when cross-fade preference also requires it.-- Controls retain usable hit regions even though the visible Pill is 84×32.-- The panel remains non-activating, movable, visible across Spaces/full-screen apps, and clamped to- the active display after display changes.-- Screen-share exclusion is **not** an acceptance guarantee. Apple now documents- `NSWindow.SharingType.none` as a legacy constant macOS no longer uses. Keep it only as best-effort- compatibility if it produces no warning, and test popular meeting apps manually. The small Pill is- the dependable mitigation when a whole display is shared.--### Engineering--- Shared primitives have no dependency on `NotchContentState`, `MeetingSessionCoordinator`, or a- singleton settings store.-- Dictation behavior and dimensions do not change as an incidental result of extraction.-- Meeting presentation is modeled explicitly; it is not another Boolean layered onto `isExpanded`.-- Presentation initializes only on the transition into a new recording, never on degraded/recovered- state publishes inside the same recording.-- All setting decoding is backward-compatible, including backup import from older builds.--## 3. Current architecture and constraints--### Established dictation overlay--- `BottomOverlayView.swift` owns dictation layout presets (`pill`, `small`, `medium`, `large`), its- black surface, border, shadow, waveform rendering, and content.-- `BottomWaveformView` cannot be reused directly because it reads `NotchContentState.shared` and- owns dictation-specific processing/release animation.-- `BottomOverlayWindowController` cannot host meetings because its lifecycle, hit-testing, menus,- target app state, and dismissal behavior are dictation-specific.--### New meeting overlay from this iteration--- `MeetingRecordingPillController` owns one persistent `NSPanel`, saved placement, display clamping,- and the current 84×32 ↔ 480×132 resize.-- `MeetingRecordingPillContent` owns recording level, Stop, rolling subtitle composition, and the- current matched-geometry transition.-- `MeetingFloatingPanelFactory` supplies the correct non-activating, floating, movable panel behavior.-- `MeetingLiveBubbleComposer` and `MeetingLiveBubbleScrollList` already separate caption composition- from the panel presentation and should remain the caption data/view foundations.--### Important constraints--- AppKit owns the outer panel frame and is the only geometry animation clock. The current AppKit cubic- resize and independent SwiftUI spring are a confirmed race that the new design must remove.-- The meeting overlay can remain visible for hours. Do not copy the dictation Pill's continuous- 30-fps rotating border into the persistent meeting surface. Share its static visual recipe, while- audio bars update only when levels change.-- Captions can update many times per second. Their fixed panel dimensions must not cause fitting-size- recalculation or AppKit frame animation on transcript changes.-- The repository currently has no view/controller tests for meeting overlay presentation.-- The cached panel root currently snapshots theme construction and has no explicit live view model;- presentation, appearance, and accessibility state need an observable bridge that survives meetings.--## 4. Target architecture--```text-Shared visual layer (stateless)-├── FluidOverlaySurface-├── FluidOverlaySurfaceStyle-├── FluidOverlayShadowMetrics-├── FluidOverlayLevelBars-└── FluidOverlayMotionCurve--Dictation feature (existing lifecycle)-├── BottomOverlayWindowController-├── BottomOverlayView-└── Dictation waveform/state adapter--Meeting feature (independent lifecycle)-├── MeetingRecordingOverlayController-├── MeetingOverlayViewModel-├── MeetingOverlayPreference: pill | captions-├── MeetingOverlayPresentation: pill | captions-├── MeetingOverlayGeometry-├── MeetingOverlayPresentationReducer-├── MeetingRecordingOverlayContent-└── Meeting level/transcript/state adapter-```--### Shared primitives--Create `Sources/Fluid/UI/FluidOverlayPrimitives.swift` containing only stateless visual types:--- `FluidOverlaySurfaceStyle`: fill, border gradient/opacities, line width, corner radius, shadow.-- `FluidOverlaySurface`: renders the background from a supplied style and shape.-- `FluidOverlayLevelBars`: renders supplied normalized bar heights/level using supplied metrics.-- `FluidOverlayShadowMetrics`: visible and hit-test shadow extents.-- `FluidOverlayMotionCurve`: one duration and cubic curve representable as AppKit timing and, where- needed for opacity only, SwiftUI timing. Geometry never uses a SwiftUI spring.--Do not put feature sizes into the shared visual layer. Dictation retains its current layout presets;-meeting retains 84×32 and 480×132 constants. Sharing appearance must not imply that unrelated-features need identical dimensions.--The canonical compact recipe is the dictation Pill's black fill, white border gradient, radius, and-shadow. The meeting Pill uses the same static recipe; it does **not** copy the dictation Pill's-continuous rotating-border timeline because a meeting may last hours. Captions use the established-larger dictation surface recipe. Recording accent appears in content, not a feature-specific border.--### Meeting state--Add two distinct concepts:--```swift-enum MeetingOverlayPreference: String, Codable, CaseIterable {- case pill- case captions-}--enum MeetingOverlayPresentation: Equatable {- case pill- case captions-}-```--`MeetingOverlayPreference` is persisted. `MeetingOverlayPresentation` is session UI state. On the-non-visible → recording edge, the controller initializes presentation from the saved preference. A-tap or collapse only changes presentation. A settings or backup-restore change during a recording is-saved for the next recording and does not mutate the active presentation.--Use an enum even though there are two cases; this prevents contradictory `isExpanded`, preferred,-floating-window-visible, and recording-state Booleans as the feature grows.--### Observable state bridge--Create one `@MainActor MeetingOverlayViewModel: ObservableObject` and inject it into the cached panel-root once. It owns current presentation, recording/session identity, appearance inputs, Reduce Motion,-and the precomposed caption string. The controller mutates this model; the root never snapshots a-preference or accent value at panel creation.--Initialize presentation only when a new recording becomes visible. `recording ↔ recordingDegraded`-must preserve the user's temporary Pill/Captions choice.--### Geometry and position--Add pure `MeetingOverlayGeometry` before controller work. Inputs are current visible-content frame,-target visible size, transparent outer insets, and screen visible frames. Output is a clamped panel-frame plus the visible-content frame inside it.--The 84×32 and 480×132 values describe the **visible surface**, not the `NSPanel` frame. The panel adds-transparent insets for shadow and larger control hit regions. A meeting-specific hosting view rejects-hits in transparent shadow-only regions, matching the established dictation approach.--Do not persist a size-dependent window origin. Persist a presentation-independent anchor derived from-the visible surface (center X and bottom Y, with display identity when available), then derive either-presentation frame from it. Preserve `"MeetingRecordingPill"` long enough to migrate the existing-autosaved frame once; renaming Swift types must not lose the user's position.--Expose `currentOverlayFrame` for every visible presentation. Replace `expandedPanelFrame` and the-detection nudge's hard-coded 84×32 fallback so caption-window and nudge placement use the real frame.--### Morph ownership--Keep Pill and Captions in the same `NSPanel` and SwiftUI root. Use one transition coordinator:--1. Resolve target presentation and pre-clamped target frame from the pure geometry layer.-2. Increment a presentation generation token; stale animation completions become no-ops.-3. Let AppKit animate the outer frame with the single cubic timing curve.-4. Disable independent SwiftUI geometry animation. Lay out the persistent surface and controls from- actual hosting-view bounds so they follow AppKit interpolation on every frame.-5. Keep both content layers in one root. Derive caption opacity/clip progress from actual width rather- than elapsed time, making panel bounds the single source of morph progress.-6. With Reduce Motion, set the frame directly and use only the system-preferred cross-fade, or no- transition when cross-fade isn't preferred.--Stop remains interactive throughout. Repeated clicks resolve to the latest target; the generation-token drops stale completion handlers.--Reduce Motion has one source of truth in the observable view model and updates from the macOS display-accessibility-change notification. Controller and view must not read unrelated snapshots.--## 5. Phased implementation--### Phase 0 — Characterization and safety net--Purpose: lock down established dictation behavior before extracting shared visuals.--- Record current dimensions, surface colors/opacities, corner radii, shadow, waveform metrics, panel- position, and Pill hit-testing as explicit values or focused tests.-- First add pure `MeetingOverlayGeometry` and `MeetingOverlayPresentationReducer` seams; the controller- continues using old behavior until these seams are characterized.-- Test Pill ↔ Captions frames, shadow-padded panel bounds, pre-animation clamping, display removal,- anchor migration, and center preservation where space allows.-- Test new-recording edges, preference/restore changes during recording, temporary expand/collapse,- degraded/recovered state, recording stop, and rapid toggles.-- Capture manual baseline screenshots for dictation Pill and current meeting Pill in light/dark theme.-- Record the canonical dictation surface values and intentional long-duration meeting deltas.--Exit gate: baseline build/tests are green and expected visual metrics are recorded. No production-appearance changes.--### Phase 1 — Extract shared visual primitives--Purpose: establish one visual language without merging feature controllers.--- Extract the dictation overlay's static Pill surface recipe, border, shadow, and low-level bar- rendering into `FluidOverlayPrimitives.swift`.-- Adapt `BottomOverlayView` and `BottomWaveformView` to consume the primitives while preserving its- state adapter, processing shimmer, dimensions, and public behavior.-- Replace duplicated meeting surface and bar rendering with the same primitives, configured for the- meeting dimensions. Keep recording semantics inside content, not the outer surface recipe.-- Add meeting hosting-view insets/hit-testing so the visible 84×32 surface has unclipped shadow and a- usable Stop hit area without intercepting clicks in transparent padding.-- Keep the meeting panel factory and dictation window controller separate.--Exit gate: pixel/visual comparison shows no unintended dictation change; dictation overlay tests,-build, and manual record/process/dismiss cycle pass. Meeting recording/Stop still works.--### Phase 2 — Independent meeting preference--Purpose: let users select Pill or Captions independently of dictation size.--- Add `MeetingOverlayPreference` to `SettingsStore`, defaulting to `.pill`.-- Rename the established Settings > Overlay row to “Dictation overlay size” and add an independent- “Meeting overlay” picker there with Pill and Captions. Persist immediately like other overlay- preferences, avoiding one-off Cancel/Save semantics inside the meeting setup sheet.-- Add the field to `SettingsBackupPayload` as optional so older backups decode, and restore only when- present. Keep the backup schema major version unchanged because the addition is backward-compatible.-- Rename the controller/content from `MeetingRecordingPill*` to `MeetingRecordingOverlay*` once in- this phase so names match the two supported presentations. Update detection-prompt anchors.-- Add the observable view model and initialize only on a new-recording edge. Preference/restore- changes during an active meeting apply next meeting.-- Migrate the saved frame to the presentation-independent anchor; keep the legacy autosave key stable- during migration.-- Replace `expandedPanelFrame` with `currentOverlayFrame` and update captions-window/nudge anchors.--Exit gate: dictation and meeting selections survive relaunch independently; old settings and old-backup fixtures restore to Pill; changing/restoring preference mid-meeting doesn't disturb the active-presentation; existing position survives rename/migration.--### Phase 3 — Robust Pill ↔ Captions morph--Purpose: preserve the fluid expansion while making transition behavior deterministic.--- Connect the controller to the Phase 0 geometry/reducer seams and fixed visible presentation sizes.-- Replace `isExpanded` with `MeetingOverlayPresentation` and centralize transitions in the controller.-- Keep one surface identity and remove the competing SwiftUI geometry spring. Controls and captions- lay out/fade from actual panel bounds.-- Coalesce rapid toggles and protect against recording ending, panel hiding, display changes, or full- captions opening during a transition.-- Captions preference starts expanded; Pill preference starts compact. Manual expand/collapse remains- temporary and does not rewrite the preference.-- Preserve the current transition into the full resizable captions window, but source it only from a- stable completed Captions frame; opening it mid-transition first resolves the overlay state.-- Subscribe to/coalesce transcript composition only while Captions is presented (target 5–10 UI- updates/second). Pill mode must not repeatedly compose rolling caption rows.--Exit gate: no jumps, clipping, orphan panels, or stale `isExpanded` state under normal and rapid-interaction; Reduce Motion path passes; Stop is usable in both modes and during/after transitions.--### Phase 4 — Accessibility, longevity, and platform validation--Purpose: validate a control that may remain onscreen for hours.--- Provide explicit accessibility actions for Show Captions, Hide Captions, Open Captions Window,- and Stop Meeting Recording.-- Keep partial captions from repeatedly taking VoiceOver focus; finalized content remains reachable- in the full captions view.-- Use a named manual VoiceOver checklist; ordinary XCTest cannot verify SwiftUI accessibility- modifiers reliably.-- Verify hit regions, keyboard/menu-bar fallback for Stop, high contrast, Reduce Transparency,- Differentiate Without Color, and Reduce Motion.-- Run a 2-hour soak: observe CPU/GPU wakeups, memory growth, panel ordering, transcript update cost,- and behavior across sleep/wake and monitor changes.-- Manually test Zoom, Google Meet in Chrome, Teams, Webex, and macOS full-display/window sharing. Log- whether the overlay appears in each sharing mode; do not claim reliable exclusion based on- `sharingType = .none`.--Exit gate: no sustained timeline redraw loop; Pill redraws are bounded by audio-level/state updates;-caption UI publishes no faster than the chosen coalescing rate; memory stays bounded; no focus theft;-VoiceOver checklist passes; screen-sharing behavior is documented.--## 6. Expected files--### Add--- `Sources/Fluid/UI/FluidOverlayPrimitives.swift`-- `Tests/FluidDictationIntegrationTests/MeetingOverlayPresentationTests.swift`--### Modify--- `Sources/Fluid/Views/BottomOverlayView.swift`-- `Sources/Fluid/UI/MeetingRecordingPill.swift` (renamed after Phase 1 safety gate)-- `Sources/Fluid/UI/MeetingFloatingCaptionsPanel.swift`-- `Sources/Fluid/UI/MeetingDetectionPrompt.swift`-- `Sources/Fluid/UI/SettingsView.swift`-- `Sources/Fluid/Persistence/SettingsStore.swift`-- `Sources/Fluid/Persistence/BackupService.swift`-- existing settings/backup tests as appropriate-- Xcode project references if the project does not discover new files automatically--Do not mix detector behavior, calendar integration, notification redesign, or dictation-during--meeting audio arbitration into this change.--## 7. Test strategy--### Automated--- Presentation reducer/state transitions, including rapid/reentrant requests.-- Frame calculation and clamping on one/multiple displays and near every screen edge.-- Preference default, persistence, invalid raw-value fallback, and independence from dictation size.-- Backup decode with the new field absent; round-trip with Pill and Captions.-- Caption rolling-text composition remains deterministic.-- Observable propagation of presentation, appearance, accessibility, and new-recording edges.-- Existing meeting live-transcription and dictation integration tests stay green.--### Manual visual/interaction matrix--For Pill and Captions, test:--- light/dark appearance and each accent color;-- normal motion and Reduce Motion;-- recording, degraded microphone, stopping, and recording-ended states;-- click expand, collapse, full captions, Stop, dragging, and rapid toggles;-- bottom/side screen placement, Dock/menu-bar changes, multiple monitors, full-screen Spaces;-- live partial captions at high update frequency;-- dictation overlays before and after the primitive extraction;-- major meeting apps' window-share and display-share modes.--### Commands during implementation--- Run focused overlay/settings tests after each phase.-- Run `swift test` after state/settings work.-- Run the signed app build and manual meeting test after Phases 1, 3, and 4.-- Reinstall only through the repository's stable-signing workflow; never replace the installed app- with an ad-hoc or identity-mismatched build.--## 8. Risks and mitigations--| Risk | Mitigation |-|---|---|-| Shared extraction regresses dictation | Characterize first; extract stateless rendering only; visual baseline gate |-| AppKit and SwiftUI animations fight | AppKit frame is the only geometry clock; SwiftUI derives layout/progress from actual bounds |-| Cached panel freezes settings/theme | Inject one persistent observable view model and mutate it explicitly |-| Captions cause resize/layout thrash | Fixed presentation dimensions; transcript updates never request panel fitting size |-| Persistent animation wastes battery | No copied 30-fps glossy-border timeline; event-driven audio level updates; soak test |-| Preference and temporary state diverge | Separate persisted preference from session presentation; reducer tests |-| Stop becomes hard to hit in 84×32 | Preserve visible control and expand its invisible hit region; menu-bar fallback |-| Older backups fail decoding | Optional backup field with Pill fallback and fixture test |-| Screen-share privacy claim is false | Treat legacy sharing flag as best effort; test and document; rely on compact footprint |-| Rename breaks position/anchors | Migrate to a size-independent anchor, freeze the legacy key, expose current-frame semantics |-| Degrade/recover resets presentation | Initialize only on a new-recording edge, covered by reducer tests |--## 9. Rollout and rollback--- Land phases as reviewable slices; do not combine the primitive extraction and animation rewrite in- one unreviewable change.-- Default everyone to Pill so the new preference does not unexpectedly occupy more screen space.-- Keep the old meeting rendering available behind a temporary debug switch through Phase 3 if visual- comparison reveals regressions; remove the switch before release.-- Rollback is presentation-only: meeting recording and transcript capture must not depend on the- overlay being visible or on either preference value.--## 10. Research basis--- Apple documents- [`matchedGeometryEffect`](https://developer.apple.com/documentation/swiftui/view/matchedgeometryeffect%28id%3Ain%3Aproperties%3Aanchor%3Aissource%3A%29)- as synchronizing inserted/removed view geometry in one SwiftUI transaction and warns that its source- must be unambiguous; it doesn't synchronize an independent AppKit animation context.-- Apple says- [`accessibilityReduceMotion`](https://developer.apple.com/documentation/swiftui/environmentvalues/accessibilityreducemotion)- should avoid large animations, especially depth-like movement.-- Apple's [motion guidance](https://developer.apple.com/design/human-interface-guidelines/motion)- recommends purposeful, brief motion and avoiding unnecessary motion for frequent actions.-- AppKit's- [`nonactivatingPanel`](https://developer.apple.com/documentation/appkit/nswindow/stylemask-swift.struct/nonactivatingpanel)- avoids activating the owning app, while- [`fullScreenAuxiliary`](https://developer.apple.com/documentation/appkit/nswindow/collectionbehavior-swift.struct/fullscreenauxiliary)- allows the panel alongside a full-screen window.-- Apple now labels- [`NSWindow.SharingType.none`](https://developer.apple.com/documentation/appkit/nswindow/sharingtype-swift.enum)- a legacy constant macOS no longer uses. ScreenCaptureKit- [exclusion filters](https://developer.apple.com/documentation/screencapturekit/sccontentfilter/init%28display%3Aexcludingwindows%3A%29)- apply only when FluidVoice owns that capture filter; they can't control another application's- display-share filter.--## 11. Adversarial review findings and resolutions--Both independent reviewers returned **REVISE** on the initial draft.--### Agreement--- The AppKit resize and SwiftUI spring were unsynchronized; synchronization was asserted, not designed.-- Persisted preference and temporary presentation needed explicit, tested semantics.-- The autosaved size-dependent origin and stale `expandedPanelFrame` contract were unsafe once- Captions could be the resting presentation.-- Shared visuals needed a canonical recipe rather than an unspecified “same family.”-- Long-lived Pill performance needed to address transcript/coordinator redraws, not only the rotating- border animation.--### Differences and decision--- Opus recommended AppKit as the sole geometry driver; Kimi proposed matching cubic curves across- AppKit and SwiftUI. This plan takes the stricter single-driver approach: AppKit bounds drive SwiftUI- layout and morph progress. A shared cubic curve remains only for AppKit geometry and opacity.-- Opus recommended an observable live-state bridge. Kimi emphasized ambiguous active-meeting setting- changes. The revised plan adds the bridge but applies preferences only at the next recording edge.-- Kimi challenged putting a draft preference inside a Save/Cancel sheet. The setting now lives in the- established global Overlay settings and persists immediately.-- Kimi caught that 84×32 couldn't simultaneously be the full panel frame, preserve shadow, and offer- larger hit targets. It is now explicitly the visible-surface size with transparent panel insets.--Neither reviewer recommended merging dictation and meeting lifecycle controllers. Both accepted-shared stateless primitives plus independent feature state as the correct boundary.--## 12. PE-cycle status--1. Analyse — complete.-2. Plan — complete.-3. Adversarial review — complete through Orchestrate: Opus 5 and Kimi K3; both initial verdicts- `REVISE`.-4. Revise/lock — reviewer findings incorporated; awaiting user approval.-5. Implement — explicitly out of scope until the plan is approved.-6. Post-implementation review — required after each phase and at completion.diff --git a/MEETING_PCM_FIRST_IMPLEMENTATION_PLAN.md b/MEETING_PCM_FIRST_IMPLEMENTATION_PLAN.mddeleted file mode 100644index c6856455..00000000--- a/MEETING_PCM_FIRST_IMPLEMENTATION_PLAN.md+++ /dev/null@@ -1,511 +0,0 @@-# 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_PLAYBACK_ATTRIBUTION_V2_IMPLEMENTATION_PLAN.md b/MEETING_PLAYBACK_ATTRIBUTION_V2_IMPLEMENTATION_PLAN.mddeleted file mode 100644index 878bdedc..00000000--- a/MEETING_PLAYBACK_ATTRIBUTION_V2_IMPLEMENTATION_PLAN.md+++ /dev/null@@ -1,447 +0,0 @@-# Reference-aware microphone de-echo and speech preservation--Date: 2026-09-09 (local)-Status: revision 2 after adversarial review. Implementation plan only. No runtime behavior, installed app, recording, transcript, or speaker profile is changed by this document.--## Decision--The recommended solution is a **post-capture, reference-aware echo-cancellation and attribution pipeline** that consumes the selected application's clean-within-scope ScreenCaptureKit audio as a far-end/render reference and produces a derived microphone residual for ASR. Preserve the recorded microphone and application tracks unchanged; speaker-profile enrollment remains limited to verified clean no-playback microphone intervals in the first release.--Do not try to fix this by lowering the existing correlation threshold, adding a louder VAD cutoff, trusting the `voiceProcessingEnabled` flag, or building a new echo canceller from a single transfer-function estimate. The controlled development recordings show that the current waveform detector and current spectral scorer do not identify this residual reliably. A speech VAD also fires on leaked playback and therefore cannot identify near-end speech by itself.--The solution order is: **(1) fix or rule out FluidVoice's current Apple VPIO configuration, (2) evaluate ScreenCaptureKit's already-implemented paired microphone/application stream, then (3) evaluate a pinned, minimal WebRTC Audio Processing Module / AEC3 wrapper on the winning raw topology.** Cascading AEC3 after the current VPIO output is a fallback experiment, not the preferred input: Apple's nonlinear suppressor/AGC may have removed the linear relationship AEC3 needs. A smaller native Swift/Accelerate multi-band attribution detector is the required comparison and an independent enforcement guard, but it is not the place to recreate a production adaptive echo canceller. If no candidate preserves quiet double-talk on FluidVoice's actual streams, enforcement remains off.--This plan supersedes the feature-selection parts of `MEETING_MICROPHONE_ADMISSION_IMPLEMENTATION_PLAN.md`; its evidence contracts and profile-integrity rules remain applicable. The earlier B1/B2/B3 work is retained as a baseline and regression harness, not promoted to production.--Review record: `tools/MEETING_PLAYBACK_ATTRIBUTION_V2_ADVERSARIAL_REVIEW.md` documents the Claude Opus 5, Kimi K3, and Grok 4.6 findings and their revision-2 dispositions.--## 1. What is established, and what is still a hypothesis--### Established locally--- FluidVoice's preferred built-in-speaker online-call path enables voice processing on an `AVAudioEngine` input node, records a tap from that node, and separately captures selected-application audio with ScreenCaptureKit. Its fallback runtime already captures ScreenCaptureKit `.audio` and `.microphone` outputs from one `SCStream`, but marks speaker-route microphone audio unprotected and therefore does not admit it to transcription.-- The selected application's audio does not enter FluidVoice through an app-owned `AVAudioEngine` render source. It arrives through the ScreenCaptureKit `.audio` output.-- On the five controlled recordings made with speakers and no other nearby talker, the playback-only recording still produced four visible microphone-attributed segments and 49 words.-- The existing B1 two-second raw waveform detector produced zero `duplicateSupported` windows across all eight development recordings, including all five controlled recordings.-- The existing `MeetingEchoSignalScorer` already estimates delay with GCC-PHAT and fits a blockwise frequency-domain transfer function. On the controlled playback-only and overlap data, its explained fractions were generally near zero and it frequently returned the legacy low-explanation rescue. Its failure is therefore not fixed by merely adding “adaptive filter” terminology or reducing the B1 NCC threshold.-- Silero VAD activity remains present in playback-only recordings. It is speech activity evidence, not speaker-source evidence.--### Apple behavior that is documented--Apple describes AVAudioEngine voice processing as intended for echo cancellation and VoIP. Enabling it switches both I/O nodes into voice-processing mode, and it is available only when rendering to an audio device. Apple also says AUVoiceIO and AVAudioEngine expose the same voice-processing capabilities and that FaceTime and Phone use these APIs. The processing includes echo cancellation, noise suppression, and AGC and is device-tuned:--- [What's New in AVAudioEngine, WWDC19](https://developer.apple.com/videos/play/wwdc2019/510/)-- [What's new in voice processing, WWDC23](https://developer.apple.com/videos/play/wwdc2023/10235/)-- [`AVAudioIONode`](https://developer.apple.com/documentation/avfaudio/avaudioionode)-- [`kAUVoiceIOProperty_BypassVoiceProcessing`](https://developer.apple.com/documentation/audiotoolbox/kauvoiceioproperty_bypassvoiceprocessing)-- [`AVAudioInputNode.isVoiceProcessingAGCEnabled`](https://developer.apple.com/documentation/avfaudio/avaudioinputnode/isvoiceprocessingagcenabled)--ScreenCaptureKit provides audio sample buffers separately from microphone output and exposes their configured sample format. It does not document a public API for supplying an arbitrary ScreenCaptureKit stream as the far-end reference of AUVoiceIO/AVAudioEngine:--- [`SCStreamOutputType`](https://developer.apple.com/documentation/screencapturekit/scstreamoutputtype)-- [`SCStreamOutputType.audio`](https://developer.apple.com/documentation/screencapturekit/scstreamoutputtype/audio)-- [`SCStreamOutput`](https://developer.apple.com/documentation/screencapturekit/scstreamoutput)-- [`SCStreamConfiguration.capturesAudio`](https://developer.apple.com/documentation/screencapturekit/scstreamconfiguration/capturesaudio)--### Important unresolved point--Apple's public material does **not** specify enough to assert that macOS VPIO either does or does not use the system-wide output mix from other processes as an echo reference. WWDC19's phrase “audio that is coming from the device” is broader than “audio rendered by this engine,” while its same-I/O-path examples are VoIP-oriented. Therefore:--- treat “Chrome never reaches the VPIO reference” as a plausible architectural hypothesis, not a fact;-- do not infer correct AEC from `isVoiceProcessingEnabled == true`;-- measure the actual behavior on the supported Mac/device/route matrix before changing capture architecture.--FaceTime owns its remote-media receive path and is documented to use Apple's voice processing. A conventional WhatsApp-style VoIP client likewise owns both render and capture streams, but WhatsApp's current proprietary audio implementation is not publicly verified here. Do not claim that its internal AEC is identical to FaceTime or to a particular WebRTC revision.--## 2. Why the current approaches are insufficient--### Voice processing is a useful first layer, not proof of clean microphone audio--`MeetingMicrophoneCapture` requests VPIO, configures other-audio ducking, taps processed input, and records settled device metadata. It binds and reads back audio-unit element 1 (input), but does not bind or persist element 0 (output); the source comments already note that element 0 once read back an unrelated AirPods output. It also persists `voiceProcessingEnabled: true` as a literal after the setter succeeds rather than persisting the getter/readback, and it does not persist bypass or AGC readbacks. The engine has no explicit application render source. These are strong configuration hypotheses, not proof of causality. The controlled recording is direct evidence only that the resulting track can still contain ASR-visible playback.--### B1 waveform correlation assumes too much signal similarity--The B1 detector compares two-second, 2 kHz windows using mean-centered normalized correlation over a bounded lag search. Voice processing, speaker/microphone acoustics, room reverberation, non-linear suppression, AGC, and frequency coloration can leave intelligible speech while reducing raw waveform correlation. The observed correlations never reached the exploratory support threshold. Lowering that threshold would also increase matches to mismatched controls and periodic content.--### The current spectral scorer is not a robust AEC--`MeetingEchoSignalScorer` estimates a single delay, learns one complex transfer coefficient per frequency bin over two-second blocks, and measures residual energy. It lacks a continuously adapting partitioned echo path, explicit double-talk adaptation control, render/capture queue jitter handling, clock-drift tracking, nonlinear residual suppression, ERL/ERLE state, and echo-path-change recovery. Its low explained fraction is ambiguous between near-end speech, nonlinear residual echo, bad alignment, insufficient excitation, and a changing acoustic path.--### VAD and ASR text cannot identify the acoustic source--- VAD answers “does this resemble speech?” Leaked playback is speech.-- Text similarity can corroborate playback, but ASR errors, paraphrase-like errors, repeated phrases, and deliberate local repetition make it unsafe as the only suppression signal.-- Speaker clustering can assign stable identities to repeated leakage. A centroid is not proof of near-end speech.--### Competitor lessons are architectural, not thresholds to copy--Static inspection of Wispr Flow 1.6.492 found separate microphone/system PCM, repeated lag-stability evidence, attack/release behavior, timestamped exclusion spans, epoch resets, bounded-work fail-open behavior, and preservation checks before final microphone zeroing. Those are useful design patterns. Its feature activation and performance on FluidVoice recordings are unverified, and its constants are not FluidVoice calibration.--Static inspection of Granola 7.498.1 found a native capture boundary with separate microphone/system buffers and options related to AEC and gain compensation. The native implementation is unavailable in the inspected JavaScript. Its local diarization worker's gain/VAD/centroid path is not independent near-end proof.--## 3. Target architecture--```text-ScreenCaptureKit app audio ──► reference timeline ─┐- ├─► synchronizer ─► AEC/attribution engine-preserved microphone track ──► capture timeline ──┘ │- ├─► derived residual PCM- ├─► delay/ERL/ERLE/echo state- └─► explicit unknown reasons--derived residual PCM ─► VAD + microphone ASR ─► interval evidence ─► admission/profile policy-preserved original PCM ─────────────────────────────────────────────► local recovery/review only-application ASR ────────────────────────────────────────────────────► supporting text alignment-```--### Capture invariants--1. Preserve the original application and microphone tracks byte-for-byte.-2. Treat every derived residual as reproducible output with a versioned configuration and source hashes.-3. Keep original PTS, valid-sample masks, capture eras, route identity, device identity, discontinuities, and clock-drift observations.-4. Never substitute zeroes for unavailable samples before evidence scoring. Missing coverage stays unknown.-5. Never play ScreenCaptureKit-captured application audio back through FluidVoice during normal operation; doing so would duplicate audible output and create a new latency/feedback path.-6. Persist the reference scope (`selectedWindow`, `selectedApplication`, or an explicitly authorized broader mix). The current selected-application reference is not the acoustic system-output mix: other processes, notifications, volume changes, output DSP, and uncaptured helper processes can be absent or transformed.-7. A present selected-application reference is not automatically a complete reference. Carry `referenceScopeLimited`/`referenceCompletenessUnobservable` separately from absent/gapped reference. Without an explicitly authorized broader reference, the feature can promise suppression only for playback attributable to the selected scope; unrelated playback remains fail-open text and cannot be claimed solved.-8. Do not silently broaden capture to the full system mix. Any diagnostic or product full-mix reference requires explicit user-facing scope, retention, privacy, and deletion rules; it must not be transcribed or persisted by default merely because it is useful to AEC.--### Synchronizer--Add a bounded `MeetingReferenceSynchronizer` that emits fixed 10 ms render/capture frames plus metadata. It must:--- resample through an explicitly versioned converter and account for converter delay;-- define three timelines explicitly: microphone host/sample-count time, ScreenCaptureKit PTS, and the derived session-monotonic frame time. Never assume the first two share a clock merely because both use `CMSampleBuffer`;-- reset at either-track discontinuities, route/device changes, sample-rate changes, decoder gaps, or invalid/non-monotonic PTS;-- expose measured buffer delay and slowly varying drift. Either bound an epoch when drift exceeds a frozen limit or apply explicit, versioned drift-compensating resampling; never silently time-stretch one stream;-- compensate codec encoder priming/remainder, edit-list timing, and every converter's algorithmic delay;-- carry valid masks and an epoch ID into every result;-- distinguish `referenceAbsent`, `referenceGap`, `referenceScopeLimited`, `referenceCompletenessUnobservable`, `captureGap`, `captureTimingSynthesized`, `delayUnresolved`, `clockDriftUnstable`, and `engineUnavailable`;-- freeze adaptation, rather than fabricate aligned samples, across microphone spans whose PTS was synthesized after invalid host time; reset after the recorded resynchronization boundary;-- bound queues and processing time and fail open without blocking capture callbacks.--The initial implementation is offline-only and runs from completed lossless chunk files. No real-time callback may call C++ AEC, FFT, ASR, or file I/O.--### Candidate A: native multi-band attribution--Build a new offline experimental detector rather than tuning B1 in place:--- 16 kHz mono analysis, 20–32 ms Hann frames, 10 ms hop;-- log-mel or perceptual multi-band energies plus band-limited modulation envelopes;-- per-band robust normalization so gain and static coloration do not dominate;-- bounded lag candidates and a monotonic delay path with explicit slope/drift limits;-- coherence/support computed across frequency and time, excluding low-excitation and periodic/ambiguous frames;-- deliberately mismatched reference controls from the same recording;-- attack/release state that resets at the synchronizer epoch and never crosses missing coverage;-- a `duplicateSupported` result only when lag-path continuity, multi-band support, and control margin all pass.--This candidate produces attribution evidence only. It does not manufacture residual audio, call speech activity “near-end,” or suppress text by itself. A chosen enforcement path must retain it, or an equivalently independent reference-attribution guard, rather than trusting residual VAD/ASR alone.--### Candidate B: WebRTC APM/AEC3--Build a minimal offline C++/Objective-C++ wrapper around a **pinned commit** of WebRTC APM/AEC3. Feed the application stream to the render/reverse side and the microphone stream to the capture side in the API's required frame order. Export only:--- both the linear-filter output and the nonlinear/suppressed output, identified separately; treat the linear output as the first ASR/embedding-preservation candidate rather than assuming the listening-optimized suppressor output is best;-- convergence/delay state;-- available echo metrics such as ERL/ERLE or residual-echo likelihood;-- reset/failure reason and processing cost;-- the exact WebRTC commit, build flags, configuration, license, and artifact hash.--AEC3 is a mature reference/capture processor: its current code handles 10 ms frames, delay buffering/estimation, adaptive filtering, render/capture timing, residual echo estimation, and clock drift. Its source is BSD-licensed with a separate patent grant, but a dependency/security/license review is still mandatory:--- [WebRTC Audio Processing Module overview](https://webrtc.googlesource.com/src/+/refs/heads/main/modules/audio_processing/g3doc/audio_processing_module.md)-- [`EchoCanceller3`](https://webrtc.googlesource.com/src/+/refs/heads/main/modules/audio_processing/aec3/echo_canceller3.h)-- [`EchoPathDelayEstimator`](https://webrtc.googlesource.com/src/+/refs/heads/main/modules/audio_processing/aec3/echo_path_delay_estimator.h)-- [`ResidualEchoEstimator`](https://webrtc.googlesource.com/src/+/refs/heads/main/modules/audio_processing/aec3/residual_echo_estimator.cc)-- [WebRTC license](https://webrtc.googlesource.com/src/+/main/LICENSE) and [patent grant](https://webrtc.googlesource.com/src/+/refs/heads/main/PATENTS)--Do not vendor all of WebRTC. First prove a reproducible minimal target and enumerate its transitive source/build dependencies, including Abseil, `rtc_base`, `common_audio`, SIMD/FFT code, generated configuration, and field-trial behavior. Pin the field-trial string and all AEC3 suppressor/comfort-noise/high-pass options as part of engine identity. Do not enable WebRTC AGC or separate noise suppression in the first AEC-only comparison; changing multiple processors at once would make attribution and speech-preservation results uninterpretable.--### Capture-input bake-off--Test Candidate B against three explicitly different capture inputs, in this order:--1. **SCK paired microphone + SCK selected-application audio from one `SCStream`.** This code path already exists. Measure—do not assume—whether the microphone is unprocessed, whether the two outputs share a usable clock, and what latency/jitter it adds.-2. **Exclusive raw diagnostic microphone + SCK reference.** Run with VPIO fully torn down; never make two microphone owners race for the same device. Use only if it adds information beyond the paired SCK path.-3. **Current VPIO output + SCK reference.** This is the smallest product diff but the least identifiable signal model because it cascades AEC after Apple's time-varying nonlinear processing. Reject it if delay/convergence/ERLE are unstable or if most valid coverage remains inert/uncertain; do not tune around non-convergence.--Never silently replace VPIO capture based on one recording. On speaker routes, the current SCK microphone era is `.unprotected`, which blocks both live and offline mic transcription. A production raw/SCK topology therefore needs a separately reviewed capture migration and a distinct state such as `rawWithValidatedOfflineCancellation`; it cannot masquerade as behavior-unchanged shadow mode. That migration must cover exclusive device ownership, common-clock verification, interruption/recovery, permission state, file size, rollback to the whole VPIO runtime, and live-caption consequences.--### Admission and speaker-profile policy--The AEC residual is a candidate analysis/ASR source, not ground truth. Combine evidence without pretending correlated signals are independent:--- `likelyPlaybackOnly`: reliable render reference, converged delay/path, sustained echo attribution, and no supported residual speech interval;-- `acceptedNearEndSpeech`: measurable residual speech with adequate coverage and a preservation-safe AEC state; identity may remain unknown;-- `mixedOrUncertain`: residual speech and playback overlap, conflicting engines, unconverged/path-change state, or coarse timing;-- `unscored`: reference/capture/model/engine unavailable;-- `scopeLimited`: the selected reference is healthy but cannot establish whether other audible processes contributed. This is not equivalent to a complete acoustic reference.--Rules:--1. In the first enforcement release, use a selected linear or suppressed residual as the microphone ASR input only for intervals where the chosen engine is valid and held-out tests show speech preservation. Fall back to the existing microphone ASR input when evidence is unscored; include those fail-open words in the playback-leak metric so abstention cannot make a candidate pass.-2. Never delete or overwrite original microphone PCM.-3. Never drop an entire turn because playback was present somewhere in it. Split only at validated frame boundaries with padding; otherwise retain a recoverable uncertain candidate.-4. Do not admit any microphone-derived speaker embedding from `likelyPlaybackOnly`, `mixedOrUncertain`, `scopeLimited`, invalid, or shared-centroid-contaminated intervals.-5. In the first enforcement release, update speaker profiles only from verified no-playback clean intervals using original microphone PCM restricted to independently admitted speech. Do not enroll from overlap residuals. Separately evaluate embeddings from linear residual, suppressed residual, and clean original PCM for domain shift before any later relaxation.-6. Application/microphone fuzzy transcript alignment is supporting evidence and diagnostic output only until independently ablated. It cannot override strong residual speech or prove identity.-7. Missing reference/model/metrics never means “no speech” or “playback only.”-8. Run original and residual ASR side by side offline. Original words with an empty residual are not automatically rescued—that can be successful echo removal—but if residual-side speech activity, the independent attribution engine, or timing evidence conflicts with the empty residual, degrade the interval to `mixedOrUncertain` rather than silently dropping it.-9. Specify whether interval selection occurs before ASR or from word timestamps after ASR. Do not splice original/residual token streams until boundary padding, duplicate removal, and timestamp accuracy are independently tested.--## 4. Implementation phases--### Phase 0 — close the Apple/capture evidence gap--Deliverable: `tools/MEETING_VPIO_REFERENCE_PROBE.md` plus numeric-only result sidecars.--Create a diagnostic-only, correctly signed build or isolated harness. Use a safe-level, known local stimulus containing an impulse/maximum-length-sequence-style alignment probe plus speech-like material; do not use the current scorer's explained-fraction as the sole Apple-AEC meter. On each supported route, run short exclusive trials:--| Trial | Microphone path | Audible render/reference | Purpose |-| --- | --- | --- | --- |-| A | current VPIO input tap | helper/external process, selected-app SCK reference | Reproduce current architecture |-| B | VPIO input tap | known local PCM through a source node on the same engine; reference from an engine-local tap | Test paired VPIO I/O. Informational only: FluidVoice cannot productize ownership of another app's render path |-| C1 | same VPIO graph, uplink processing bypassed | same external stimulus as A | Quantify voice-processing attenuation without changing capture technology |-| C2 | SCK paired `.microphone` + `.audio` from one stream | same external stimulus | Test the already-implemented paired topology, mic processing, clock relation, latency, and jitter |-| D | VPIO with AGC disabled/enabled; ducking variants reported separately | A and B stimulus where public APIs permit | Separate AGC behavior; do not treat ducking volume change as AEC evidence |-| E | headphones | external process | Negative acoustic-leak control |-| F | exclusive raw/HAL diagnostic, VPIO fully stopped | external process | Only if it adds information beyond C2; never use simultaneous mic owners |-| G | selected app plus a second process and a mid-trial volume change | selected-app reference; optional explicitly authorized full-mix diagnostic reference | Measure incomplete-reference and post-tap gain/DSP failure modes |--Before acoustic conclusions, read and persist the actual input and output `kAudioOutputUnitProperty_CurrentDevice` elements, output render activity/connection, `isVoiceProcessingEnabled`, `isVoiceProcessingBypassed` / `kAUVoiceIOProperty_BypassVoiceProcessing`, `isVoiceProcessingAGCEnabled` / `kAUVoiceIOProperty_VoiceProcessingEnableAGC`, `isVoiceProcessingInputMuted`, and ducking state where supported. The exact property, scope, element, `OSStatus`, and value belong in the probe result. Verify that B's render is audible on the read-back output device. Force-binding element 0 is diagnostic-only until route-change and user-output behavior are understood.--For each trial persist only numeric diagnostics unless the user explicitly authorizes local audio retention: device/property readbacks; graph connection/render state; sample formats; all three timelines; delay sign/distribution; drift; multiband coherence; RMS; attenuation; and uncertainty. SCK-paired timestamps are measured rather than assumed to share a clock. A broader full-system reference in G is opt-in, ephemeral, never transcribed, and cannot become a product default through this probe.--Exit: rank (1) a reproducible Apple VPIO graph/device/property fix, (2) SCK-paired capture quality and clock behavior, and (3) current VPIO residual explainability. If the Apple-only configuration passes later speech-preservation gates, prefer it and stop. If SCK pairing wins, freeze that topology before building AEC3. If the current VPIO residual has unstable delay/coherence, remove VPIO+Aec3 from further work rather than tuning it.--### Phase 1 — freeze corpus and evaluation protocol--Deliverables: versioned annotation manifest, local-only runner, aggregate-only report.--1. Keep all existing eight recordings development-only and fixture-only. They exercise the VPIO topology and cannot calibrate a new SCK/raw topology.-2. Add frame-level timing labels for playback-only, clean normal speech, clean quiet speech, short quiet overlap replies, sustained overlap speech, pauses, route transitions, and reference gaps. Coarse whole-recording labels cannot select thresholds.-3. Build the calibration/held-out corpus only after Phase 0 freezes each evaluated topology. Include other-process speech, window-vs-application scope, helper-process audio, system volume changes, music, silence, periodic sounds, and multiple voices.-4. Reserve separate speakers/sessions/environments as held-out before tuning.-5. Compute recording-level metrics; correlated 10/256 ms frames are not independent samples.-6. The corpus minimums and split rules in `MEETING_RELIABILITY_IMPLEMENTATION_PLAN.md` remain binding: at least 12 independent negative sessions across three output configurations and two acoustic environments; at least 30 annotated minutes across three independent recordings for each populated quiet/short/double-talk positive condition; at least 100 labeled short replies; splits by recording/device/speaker; and fresh held-out data after a failed held-out run.-7. Keep source recordings and transcripts local. Reports contain aggregate numbers, hashes, versions, and failure reasons only. Include label-quality/independent-adjudication reporting for quiet overlap.--Metrics:--- playback-only visible microphone words/minute and speech-seconds/minute;-- percentage reduction from the current pipeline;-- scripted near-end WER or phrase recall, separately for clean, quiet, and overlap;-- false removal of near-end intervals;-- speaker-profile contamination and clean-profile yield;-- unscored/unknown coverage by reason;-- decision/inertness coverage: fractions reaching playback-only, accepted, uncertain, scope-limited, and unscored outcomes for each input topology;-- delay lock time, path-reset recovery, CPU time, peak memory, and derived-file size;-- speaker-embedding domain shift: clean-original versus linear-residual versus suppressed-residual similarity and cross-session verification error, reported separately from ASR quality.--### Phase 2 — synchronizer and deterministic fixtures--Targets: new `MeetingReferenceSynchronizer`, offline CLI, and baseline-host tests.--Required fixtures:--- known impulse/FIR echo with positive and negative delay;-- slowly drifting clocks;-- dropped render and capture blocks;-- codec encoder priming/remainder and edit-list offsets;-- discontinuity/route/sample-rate epochs;-- valid audio with synthesized microphone timing, adaptation freeze, and resynchronization;-- silence and low-excitation references;-- nonlinear coloration/clipping;-- near-end-only, echo-only, and double-talk at multiple echo-to-near-end ratios;-- cancellation-safe exact repetition by the near-end talker;-- deterministic replay and bounded-resource failure.--Exit: frame pairing, lag sign, converter delay, masks, and resets are independently test-pinned before either candidate is scored.--### Phase 3 — offline candidate bake-off--Implement Candidate A and a minimal Candidate B behind a common `MeetingReferenceAttributionEngine` protocol. First run a time-boxed out-of-tree AEC3 build-feasibility spike: require a reproducible macOS arm64/x86_64 artifact, enumerated transitive sources/licenses/field trials, a size report, and a Swift-callable smoke test. If that cannot be produced within a project-owner-approved time box, stop the extraction rather than letting WebRTC vendoring dominate the work; evaluate a maintained standalone WebRTC-audio-processing distribution only after the same provenance/security review, or return to the capture-topology/source-separation decision.--After Phase 0 freezes the input topology, run blinded IDs through the corresponding frozen development set. Do not tune on held-out data. VPIO, SCK-paired, and exclusive-raw recordings are different signal domains; results and thresholds do not transfer silently between them.--A candidate is rejected if it:--- labels leaked playback as accepted near-end speech at an unacceptable recording rate;-- removes or corrupts quiet/overlap phrases beyond the corpus gate;-- relies on a VAD or ASR-text-only source decision;-- carries support across gaps/epochs;-- cannot report unknown rather than fabricate a decision;-- is mostly inert: valid coverage remains unconverged/uncertain or fails to reach actionable states;-- depends on a selected-app reference while silently treating unrelated-process or post-volume/DSP audio as covered;-- cannot meet a bounded local processing/storage budget.--Decision rule:--- choose Apple-only if Phase 0 proves it meets the same output gates;-- otherwise choose SCK-paired microphone plus AEC3 if it materially reduces playback-only microphone words while preserving quiet/overlap speech and has an acceptable vendoring footprint;-- consider current VPIO plus AEC3 only when Phase 0 proves its residual remains delay-locked and learnable and it beats the SCK-paired arm on playback reduction without worse speech preservation;-- require Candidate A, or an equivalently independent reference-attribution guard, for any automatic playback-only/residual-ASR enforcement;-- do not implement a home-grown production adaptive canceller if AEC3 fails. Investigate capture topology or a separately reviewed source-separation model instead.--All Phase 3 comparisons use the binding parent-plan release metrics, including unscored/fail-open output in session totals. “Unacceptable recording rate” is not renegotiated during the bake-off.--### Phase 4 — shadow integration, no behavior change--Targets include `MeetingProcessingConfiguration`, `MeetingProcessingPipeline`, a versioned sidecar schema, and local numeric logging.--1. Add explicit `off` and `shadow` modes; default `off`.-2. Snapshot mode/version at processing start. Never consult a mutable global mid-run.-3. Generate the derived residual and typed evidence after chunk finalization, outside capture callbacks.-4. Run residual ASR/VAD and profile eligibility in parallel with the unchanged legacy outputs.-5. Persist only bounded local evidence needed for comparison; no raw PCM or transcript text in logs.-6. Record would-change counts: words, segments, profile observations, unknowns, processing cost, and candidate/legacy disagreements.-7. Make restart/retry idempotent and key outputs by session, source hashes, epoch, engine version, and configuration hash.--Exit: repeated processing is deterministic for the same architecture, binary, configuration, and inputs; record architecture and build hash rather than requiring cross-architecture floating-point byte identity. `off` is identical to today's behavior; `shadow` never changes UI/export/summary/profile output; injected engine failure falls back cleanly.--This phase applies directly only if the selected topology can preserve today's capture path. If SCK/raw wins, first produce the separate capture-migration design described above. A speaker-route raw era cannot be called “shadow/no behavior change” because today's `.unprotected` gate suppresses its mic transcript; the migration's rollback unit is the entire capture runtime.--### Phase 5 — held-out gate and limited offline enforcement--Before enabling enforcement, freeze:--- the engine revision/configuration and all decision thresholds;-- minimum reference and residual-speech coverage;-- delay convergence and path-change recovery requirements;-- interval padding/splitting rules;-- resource budgets;-- recording-level acceptance thresholds.--The stricter parent-plan release gates apply unchanged; this plan does not replace them with relaxed percentages:--- zero false accepted microphone words and zero visible microphone identities on the curated playback-only regression set, with an exposure-normalized upper confidence bound and session-level paired reporting;-- at most one absolute percentage-point increase in missed-speech duration and one point in speaker-attributed WER on each populated quiet, short-reply, and double-talk held-out condition;-- no increase in false confident microphone identities and no more than one additional identity-fragmentation event per annotated hour on echo-heavy held-out positives;-- zero known instances of cross-gap/route/epoch suppression;-- all missing/incomplete-reference, over-budget, dependency-load, and corrupt-sidecar tests fail open with originals recoverable;-- processing completes within a separately measured and product-approved local CPU/memory/latency budget.--Each gate is evaluated only after the binding corpus minimums above are met. Report recording-level paired uncertainty, and require the upper bound to satisfy each non-inferiority margin; do not use a word-level binomial model for bursty errors. Playback-leak totals include unscored/fail-open intervals and have a separately frozen cap on unscored coverage, so abstention cannot pass. Passing development fixtures alone is prohibited.--First enforcement scope:--- offline final processing only;-- supported built-in speaker/microphone routes with validated device metadata;-- derived residual ASR; speaker-profile updates remain restricted to verified clean no-playback original-microphone intervals until the separate embedding-domain gate passes;-- local recovery path that can show/reprocess from original audio;-- a kill switch returning immediately to legacy processing.--Bluetooth, HDMI, external/aggregate, and unknown output routes remain outside this first enforcement scope; their current unprotected-microphone admission behavior is unchanged until they have topology-specific evidence.--Keep live captions unchanged until offline enforcement has passed a longer soak. This deliberately means live text can differ from the cleaned final transcript; document that product tradeoff rather than silently hiding live mic captions whenever application audio is active.--### Phase 6 — live processing, only if separately justified--Real-time AEC introduces callback scheduling, render/capture ordering, latency, interruption, and state-recovery risks. Treat it as a separate project. A live implementation must use a bounded non-real-time worker, never block ScreenCaptureKit/AVAudioEngine callbacks, and must define behavior for stale/missing render frames. It requires its own stress, interruption, sleep/wake, route-change, CPU-pressure, and long-call tests.--## 5. Dependency and packaging gate for AEC3--Before Candidate B code lands:--1. Pin an immutable WebRTC commit and record the repository/commit in source and SBOM.-2. Build only the transitive APM/AEC3 subset needed for macOS arm64/x86_64; enumerate generated and third-party dependencies.-3. Preserve WebRTC license notices and patent-grant text; obtain project-owner/legal review if required by release policy.-4. Reproducibly build a signed/static artifact from source. Do not download a mutable binary during app execution or testing.-5. Run dependency vulnerability and symbol/export review.-6. Wrap C++ ownership in a narrow Objective-C++ API with explicit frame geometry, resets, and error returns; no exceptions across Swift.-7. Prove no network access, telemetry, audio logging, or debug dump is enabled.-8. Verify binary size, startup time, peak memory, CPU, and notarization/code-signing impact before choosing it.-9. Make feasibility time-boxed with an explicit abort result. A failed minimal/reproducible build is a decision outcome, not permission to vendor the full WebRTC tree or fetch a mutable prebuilt binary.--## 6. Required tests--### Unit/property tests--- PTS mapping, converter latency, lag sign, drift, and epoch reset;-- masks never become measured silence;-- render/capture ordering and exact 10 ms frame counts;-- multi-channel render versus versioned downmix policy, with a measured downmix error budget;-- deterministic AEC reset/replay;-- missing/late/duplicate/non-finite frames;-- double-talk adaptation safety and echo-path changes;-- exact local repetition of playback;-- shared speaker-centroid exclusion;-- no profile output from uncertain/playback-only intervals;-- all reason-code and legacy fallback branches;-- bounded queue, cancellation, timeout, and repeated failure latch reset by new session.--### Integration tests--- complete session reprocess with original hashes unchanged;-- `off`/`shadow` output equality;-- shadow sidecar restart/idempotence;-- app-only, mic-only, overlap, route change, and missing reference;-- selected-window/application reference plus unrelated-process audio and system-volume changes;-- SCK-paired microphone/application PTS comparison and raw-era admission behavior;-- model/dependency unavailable with no download attempt;-- exporter/summary/profile behavior under each admission outcome;-- installed-app capture unchanged until Phase 5.--### Acoustic and adversarial tests--- built-in speaker volume/distance/room sweep;-- male/female and quiet/normal/loud near-end voices;-- fast interjections during loud playback;-- music, applause, silence, noise, and periodic tones;-- speaker movement and device rotation;-- output-route and microphone changes;-- intentionally repeated far-end words by the local user;-- one and multiple nearby local speakers;-- long recordings and thermal/CPU pressure.--## 7. Observability and privacy--Emit numeric/enum diagnostics only:--- engine/version/config/source hashes;-- epoch and aggregate valid coverage;-- delay/convergence/path-reset counts;-- ERL/ERLE or candidate-specific aggregate metrics;-- residual/original energy ratios;-- admission outcome/reason counts;-- would-change segment/word/profile counts;-- CPU, memory, duration, and fallback reason.--Never log transcript text, raw PCM, embeddings, window titles, speaker labels, or absolute recording paths. Reviewer prompts may include relevant source and diffs under the repository authorization, but not recordings, transcripts, model weights, secrets, or unrelated files.--## 8. Rollback and recovery--- Feature modes are `off`, `shadow`, and narrowly scoped `enforce`; `off` remains a one-step kill switch.-- Originals are immutable; derived outputs are versioned and disposable.-- Reprocessing from originals can reproduce either legacy or selected-engine output.-- Unsupported routes, missing reference, failed convergence, corrupt sidecars, dependency load failures, or resource-budget failures use the documented fail-open text path and exclude uncertain audio from speaker-profile learning.-- Never reinstall an ad-hoc/invalidly signed build over `/Applications/FluidVoice Debug.app`. Existing bundle identifier, Team ID, designated requirement, and strict signature checks remain mandatory for any later install.--## 9. Concrete first implementation slice--The first code change after this plan is approved is **the revised Phase 0 plus the synchronizer test harness**, not production AEC and not threshold changes:--1. add VPIO input/output element, graph-render, enabled, bypass, AGC, mute, and ducking property readbacks behind a debug-only probe; replace no production metadata yet;-2. run the A/B/C1/C2/D/E/F/G trials above, including SCK-paired capture, unrelated-process/reference-scope, volume-change, and signed-delay measurement;-3. explicitly rank Apple graph/configuration repair, SCK-paired capture, and current VPIO-residual learnability before any AEC3 recommendation is activated;-4. add an offline `MeetingReferenceSynchronizer` with three-timeline, codec-priming, alignment, drift, synthesized-timing, mask, and gap tests;-5. define the common attribution-engine protocol and aggregate result schema;-6. run the time-boxed out-of-tree AEC3 build/license/size spike only if Phase 0 still requires software cancellation;-7. leave all production transcript/profile behavior unchanged.--Only after that slice establishes what reference Apple receives, whether SCK pairing shares a usable timeline, which reference scope is acceptable, and whether the residual remains learnable should an in-tree AEC3 target be introduced.--## 10. Completion definition--This work is complete only when:--- the Apple reference-path question is answered by repeatable hardware evidence rather than API inference;-- selected-app versus full-mix reference limitations are explicit in product behavior and privacy scope;-- the chosen engine wins a frozen development bake-off and a separate held-out evaluation;-- quiet and overlap speech preservation meets the recording-level gate;-- playback-only microphone text and profile contamination meet the reduction gate;-- dependency, privacy, signing, resource, and recovery reviews pass;-- shadow soak shows no unexplained disagreements or cross-epoch decisions;-- enforcement is reversible and original audio remains recoverable;-- live behavior is either deliberately unchanged or separately validated.--Until then, suppression stays off.diff --git a/MEETING_PLAYBACK_ECHO_CANCELLATION_EXECUTION_PLAN.md b/MEETING_PLAYBACK_ECHO_CANCELLATION_EXECUTION_PLAN.mddeleted file mode 100644index 13b9a852..00000000--- a/MEETING_PLAYBACK_ECHO_CANCELLATION_EXECUTION_PLAN.md+++ /dev/null@@ -1,376 +0,0 @@-# Playback echo cancellation and microphone admission — execution plan--Date: 2026-09-10 (local)-Status: revision 3 after completed Grok 4.6 and Claude Opus 5 adversarial reviews. Planning artifact only; no production behavior is authorized or changed by this document.--## 1. Decision and user-visible outcome--FluidVoice will treat playback cleanup as two different safety systems:--1. **Candidate primary signal cleanup:** if a pre-dependency signal-domain gate proves the paired ScreenCaptureKit streams are learnable, a pinned WebRTC Audio Processing Module / AEC3 engine receives the far-end render reference and microphone capture, then produces a derived microphone residual for offline ASR. AEC3 is rejected before vendoring if that gate fails.-2. **Independent admission guard:** reference-attribution evidence decides whether residual speech is supported near-end speech, likely playback, mixed/uncertain, or unscored. AEC output, VAD activity, or ASR text alone can never prove speaker ownership.--The original application and microphone recordings remain immutable. The first releasable scope is final, offline meeting processing on explicitly validated built-in speaker/microphone routes. Live captions and unsupported routes remain unchanged until separately validated.--The required product outcome is stronger than “the microphone waveform contains no speaker audio,” which software cannot guarantee on an open-speaker route. The enforceable outcome is:--- playback attributable to the captured reference does not enter accepted microphone transcript text or microphone speaker profiles;-- genuine quiet speech, short replies, and double-talk are preserved within the frozen non-inferiority gates;-- missing, incomplete, stale, or invalid evidence stays explicit and recoverable;-- originals remain available for deterministic reprocessing and rollback.--This plan supersedes the remaining execution sequence in `MEETING_PLAYBACK_ATTRIBUTION_V2_IMPLEMENTATION_PLAN.md`. That plan's capture invariants, privacy limits, evaluation minima, and profile-integrity rules remain binding.--Review record: `tools/MEETING_PLAYBACK_ECHO_CANCELLATION_ADVERSARIAL_REVIEW.md` records the completed Grok 4.6 and Claude Opus 5 reviews and every revision-3 disposition. Neither review is implementation approval.--## 2. Current evidence and starting point--### Established--- The selected application's ScreenCaptureKit audio is a clean-within-scope far-end reference. It is not necessarily a complete acoustic reference: other applications, notifications, helper processes, output gain, and device DSP may be absent or transformed.-- Historical paired ScreenCaptureKit recordings already showed that `.audio` plus `.microphone` from one `SCStream` can run for long meetings, but raw speaker-route microphone audio contains substantial playback leakage.-- Current production correctly marks the paired-SCK speaker-route microphone as `.unprotected` and excludes those microphone turns from transcript/profile admission. This is safe against contamination but loses legitimate local speech.-- The existing B1 raw-waveform temporal detector produced no supported locks on the difficult development recordings. Lowering its threshold is not an acceptable fix.-- VAD fires on leaked speech and cannot identify near-end ownership.-- The three controlled VPIO Trial B runs were invalid or inconclusive and are frozen. No additional generic Trial B is planned.-- The unlocked C2 metadata-only run established viable paired delivery: both SCK tracks arrived with valid timing and stable formats. It did not establish acoustic cancellation.-- Trial A did not capture an excited application reference, so it cannot support an AEC conclusion. Later attempts failed closed before capture because the controlled PLAYING window could not be uniquely established.-- `MeetingReferenceSynchronizer`, deterministic replay, valid masks, epoch/gap handling, source timelines, resource bounds, and strict `MeetingReferenceAttributionContracts` already exist with focused test coverage. They are infrastructure, not evidence that an AEC engine works.--### Unresolved--- Whether paired-SCK microphone PCM is the best AEC3 capture input on every supported built-in route.-- Whether the selected-app reference remains sufficiently complete through helper processes and output-device processing.-- Whether a minimal, pinned AEC3 build is maintainable within FluidVoice's binary-size, signing, CPU, memory, and licensing constraints.-- Whether AEC3's linear or nonlinear output preserves quiet speech and double-talk better for ASR.-- Whether independent attribution can reliably distinguish weak nonlinear playback remnants from near-end speech.--## 3. Non-goals and hard boundaries--- Do not implement a home-grown production adaptive echo canceller.-- Do not lower microphone gain or introduce a universal amplitude cutoff.-- Do not treat `isVoiceProcessingEnabled`, ERLE, residual energy, VAD, diarization, or ASR text as proof of near-end identity.-- Do not overwrite original microphone PCM or application PCM.-- Do not feed captured application audio back to an output device.-- Do not broaden selected-application capture to the full system mix without a separate user-facing privacy and retention decision.-- Do not migrate speaker-route capture or enable transcript suppression in the same change that introduces the AEC dependency.-- Do not tune thresholds on held-out recordings or transfer thresholds across VPIO, raw SCK, and external-device signal domains.-- Do not enroll speaker profiles from AEC residuals in the first release.-- Do not modify live transcription in the first release.--## 4. Target architecture and trust boundaries--```text-validated render reference ─► immutable reference track ─┐- ├─► MeetingReferenceSynchronizer-validated microphone input ─► immutable microphone track ┘ │- ▼- fixed 10 ms frames + masks- │- ┌──────────────────────────────┴─────────────┐- ▼ ▼- candidate pinned WebRTC AEC3 independent attribution- linear + suppressed residuals stable delay/multiband support- │ │- └──────────────────┬─────────────────────────┘- ▼- microphone admission policy- │- ┌─────────────────────────────┴──────────────────────┐- ▼ ▼- derived residual ASR clean-original profile input- offline final text only no-playback intervals only-```--### Trust rules--- `MeetingReferenceSynchronizer` owns clock mapping to a common chronological grid, format conversion, continuous clock-drift compensation by explicitly versioned resampling, masks, and epochs. It does not adaptively estimate or remove acoustic echo delay.-- The synchronizer may apply exactly one frozen, constant **render-lead pre-roll** by holding capture frames until the causally related render is queued. This is scheduling, not adaptive acoustic-delay removal. The value and source measurement are persisted per era; it cannot change inside an era.-- When AEC3 is selected, AEC3 alone owns the remaining adaptive acoustic-path bulk-delay estimate. Chronological render frames, including the constant lead, are fed before capture frames; a bounded measured device/buffer-delay hint may seed AEC3, but two components must never adapt the same delay.-- AEC3 owns signal transformation and engine state. It does not own transcript visibility or speaker identity.-- The independent attribution engine owns reference-support evidence. It does not directly erase PCM or text.-- One pure admission policy consumes typed evidence and produces one versioned interval decision used consistently by ASR assembly, export, summaries, search, and profile eligibility.-- Missing samples are unavailable, never measured silence. An invalid mask freezes adaptation and forces an explicit unscored interval.-- Reference scope is session/era provenance, not automatic proof of an interval outcome. Known concurrent out-of-scope playback, helper-process playback, or a route/volume/DSP transition produces `scopeLimited` or `unscored`, never `acceptedNearEndSpeech`; unknown out-of-scope playback remains an explicit limit of a selected-app-only product claim.--### One rendered artifact for every quality metric--All transcript quality metrics and all consumers use the same versioned final-transcript projection:--| Outcome | Default final transcript | Speaker-profile mutation |-| --- | --- | --- |-| `acceptedNearEndSpeech` | Validated residual ASR is visible | None unless a separately verified no-playback original-mic interval qualifies |-| `likelyPlaybackOnly` | Hidden from the default transcript; recoverable in local review | None |-| `mixedOrUncertain` | Fail open to recoverable original-mic ASR, visibly marked unknown/uncertain | None |-| `unscored` | Fail open to the legacy original-mic result | None |-| `scopeLimited` | Fail open to the legacy original-mic result | None |--Playback-leak, missed-speech, and WER gates are all computed from that same projection. Recoverability by itself never counts as visible speech preservation. The duration ceiling for each non-accepted outcome is frozen per corpus condition before candidate tuning.--## 5. Implementation sequence--Every stage is a separate reviewable change. A failed exit gate stops progression; it does not authorize threshold relaxation or architectural shortcuts.--### Stage 0 — freeze baseline and retire redundant experiments--Deliverables:--- Update the existing diagnostic/runbook documents with the final Trial B, C2, and Trial A dispositions.-- Freeze hashes for the current development recordings and current legacy outputs.-- Freeze hashes and reversible snapshots for current speaker-profile/centroid state; no later quarantine or kill-switch operation may destroy or silently reinterpret that baseline.-- Record the current production truth table for VPIO versus paired-SCK capture, `.unprotected` eras, live admission, offline admission, and speaker-profile eligibility.-- Keep the completed synchronizer/contracts/replay infrastructure production-inert.--Exit gate:--- One checked-in baseline manifest names the recordings, topology, route, annotations, source hashes, and whether each artifact is development-only.-- No new acoustic claim is inferred from an invalid Trial B or unexcited Trial A.-- No additional Trial B is scheduled.--### Stage 0.5 — prove the signal domain before choosing AEC3--Use existing paired-SCK lossless recordings if they contain the required excitation. If they do not, acquire the smallest new, safety-reviewed paired-SCK corpus; do not substitute C2 metadata or synthetic fixtures for acoustic evidence.--Tasks:--1. Measure render/capture chronology, delivery jitter, clock drift, signed acoustic delay, frequency-dependent coherence, path stability, clipping, and whether the paired microphone appears raw or already time-varying/nonlinearly processed. Persist p50/p95/p99 delay and drift distributions, not only means.-2. Define the AEC delay contract in an executable test: synchronizer maps clocks/epochs, continuously compensates measured clock drift, and may add one constant render-lead pre-roll; chronological render then enters before capture; AEC3 receives at most one bounded hint and owns all remaining adaptive delay.-3. Compare selected-window, selected-application, and—only under a separate explicit privacy authorization—ephemeral full-system reference completeness. Include helper-process and concurrent-other-process playback plus output-volume changes.-4. Keep current VPIO plus external reference only as a last comparison if existing valid material shows a coherent, learnable residual. Frozen invalid Trial B is neither proof for nor proof against it and does not justify another generic run.-5. Before measuring candidate outcomes, pre-register: the exact eligible built-in route/session predicate; allowed ineligibility reasons and maximum ineligible-session fraction; minimum exposure per condition; maximum render-lead pre-roll; AEC delay-search safety margin; maximum drift ppm and maximum uncorrected cumulative offset per era; at least 99% valid synchronized timing/reference coverage per eligible offline session; and condition-specific `mixedOrUncertain`/`scopeLimited` duration ceilings. Every excluded session and reason remains in the aggregate report.--Exit gate:--- Proceed to AEC3 only if at least one supported capture/reference topology has stable chronological mapping, bounded delay/drift, adequate multiband excitation/coherence, and no evidence that preprocessing makes the echo path unlearnable. After the single frozen render lead, each eligible session's p99 signed echo delay must be causal and fit inside the pinned candidate's documented search/buffer range minus the frozen safety margin; otherwise that era is `unscored`.-- If paired SCK fails, do not vendor AEC3 for that topology. Either retain the current `.unprotected` behavior, evaluate an already-supported Apple path using valid evidence, or open a separately reviewed full-mix/source-separation decision.-- C2 delivery metadata and deterministic FIR fixtures cannot satisfy this gate.--### Stage 1 — conditional, time-boxed AEC3 dependency feasibility spike--Proposed targets: an out-of-tree spike first, followed only on success by `Packages/MeetingAEC3` and `Sources/MeetingAEC3Bridge`.--Tasks:--1. Pin one immutable WebRTC source commit and all build inputs. Record license, patent grant, third-party notices, field trials, compiler flags, SIMD policy, source hashes, suppressor settings, comfort-noise behavior, high-pass filtering, and every enabled/disabled APM submodule.-2. Produce reproducible macOS arm64 and x86_64 static artifacts from source. Do not download a mutable runtime binary.-3. Enumerate the exact transitive APM/AEC3 subset; do not vendor the full WebRTC repository by default.-4. Prove a minimal C ABI/Objective-C++ smoke bridge can create, reset, process, and destroy an engine without exceptions crossing into Swift.-5. Disable AGC, general noise suppression, telemetry, raw-audio debug dumps, and network behavior for the initial AEC-only comparison.-6. Pin one portable SIMD baseline, disable runtime kernel dispatch where feasible, and forbid fast-math and uncontrolled floating-point contraction. Record the CPU feature vector, ABI, native/Rosetta mode, compiler, and deployment target in engine identity even when dispatch is disabled.-7. Measure artifact size, clean-build time, startup time, peak memory, per-10-ms-frame CPU, notarization/signing behavior, and deterministic configuration identity.-8. Run dependency/security/license review before in-tree vendoring.--Exit gate:--- Both architectures build reproducibly and a Swift-callable smoke test passes under sanitizers.-- The transitive source and binary footprint is enumerated and accepted.-- No hidden download, telemetry, dump, exception, or mutable field-trial behavior exists.-- If the spike exceeds the project-owner-approved time/size/maintenance budget, stop and record AEC3 as rejected. Do not fall back to an improvised canceller.--### Stage 2 — narrow engine wrapper and contracts--Proposed targets: `MeetingAEC3Bridge`, `MeetingWebRTCAEC3Engine.swift`, and extensions to the existing `MeetingReferenceAttributionEngine` contracts.--Tasks:--1. Accept chronological 10 ms render/capture frames plus validity masks and epoch identity. “Synchronized” means common clock/epoch mapping, not pre-removal of acoustic delay.-2. Enforce render-before-capture ordering, supported sample rates/channel layouts, the single-owner delay policy, and explicit reset at every epoch/path/route/device/volume-DSP change.-3. Export separately named linear-filter and nonlinear/suppressed outputs. Neither is declared the production winner in code.-4. Export only bounded numeric state available from the pinned revision: convergence, delay, ERL/ERLE/residual likelihood where supported, reset/failure reason, CPU, and allocation counts.-5. Make ownership RAII-safe across Swift/Objective-C++/C++. Return typed errors; never throw a C++ exception across the ABI.-6. Make engine/config/build identity part of every sidecar and cache key.-7. Reject non-finite PCM, wrong frame geometry, invalid masks, stale epochs, and output non-finites without trapping.-8. Freeze a versioned stereo/multichannel-to-mono render policy and measure its cancellation error. Never silently choose one channel or average channels with overflow/non-finite risk.-9. Define asymmetric gaps causally: exactly one render block is queued for each capture block on the common grid. A render-only or capture-only gap beyond a frozen tolerance resets the engine and marks the interval `unscored`; missing blocks are never zero-filled into adaptation.-10. Use original/reference/linear-filter signals for energy, coherence, independent attribution, and residual-empty conflict detection. The nonlinear suppressed output, including any comfort noise, is an ASR candidate only. Measure and report its synthesized comfort-noise floor separately.--Exit gate:--- Deterministic impulse/FIR, echo-only, near-end-only, double-talk, path-change, render-only gap, capture-only gap, drift, clipping, repetition, and low-excitation fixtures pass.-- A synthetic drift ramp of at least one hour proves synchronizer de-drift and AEC3 adaptive delay do not oscillate against each other or repeatedly reconverge.-- Invalid/missing frames never advance adaptation or become silence.-- Address/undefined/thread sanitizers pass the wrapper tests.-- Cancellation, repeated resets, and destruction leak no resources.--### Stage 3 — offline AEC replay, still no behavior change--Proposed targets: the existing baseline replay host, `MeetingReferenceSynchronizer`, `MeetingReferenceAttributionContracts`, and a new numeric-only AEC evaluation report.--Tasks:--1. Feed lossless finalized application/microphone chunks through the existing synchronizer, never from capture callbacks.-2. Run original, linear-residual, and suppressed-residual arms from identical synchronized frames.-3. Preserve original hashes and store derived audio only in an explicitly enabled, mode-0700 local evaluation workspace protected at least as strongly as source recordings. Every report, diagnostic, crash artifact, and sanitizer artifact unconditionally excludes PCM, transcript text, embeddings, absolute paths, window titles, and speaker labels. Mark the workspace excluded from backup and indexing, default its TTL to 24 hours with a hard seven-day maximum, and destroy derived PCM when the evaluation gate closes or the user cancels.-4. Run identical ASR/VAD evaluation on each arm. An empty residual transcript is not automatically success. Residual-empty plus original speech activity, mixed attribution, exact-repetition evidence, or timing disagreement must become `mixedOrUncertain`, retain recoverable original words, and never become playback-only solely because the residual emitted nothing.-5. Emit valid/unscored coverage by reason, delay/convergence time, path resets, ERL/ERLE, residual energy ratios, ASR deltas, processing cost, and engine identity.-6. Make replay idempotent and resumable only when all source/config/build hashes, CPU feature identity, ABI, and translation mode match.--Exit gate:--- With feature mode `off`, persisted meeting output is byte/semantically identical to the current baseline.-- Engine failure, corrupt source, missing reference, budget exhaustion, and cancellation leave originals and legacy output intact.-- The declared reference build/CPU configuration is bit-identical on replay. Other explicitly supported machines must produce tolerance-bounded metrics and identical interval decisions in a cross-machine replay; their sidecars are never reused across mismatched CPU/ABI/translation identities.--### Stage 4 — strengthen the independent playback-attribution guard--Proposed targets: `MeetingPlaybackDuplicateDetector.swift`, a new multi-band candidate behind `MeetingReferenceAttributionEngine`, and `MeetingMicrophoneEvidence.swift`.--Tasks:--1. Retain the current B1 detector as a fixed baseline; do not tune it in place.-2. Add a separate multiband/log-energy or coherence candidate with robust gain normalization, bounded lag-path tracking, ambiguity controls, repeated stable-delay support, attack/release state, freshness, and epoch resets.-3. Require deliberately mismatched-reference controls and explicit low-excitation/periodic unknowns.-4. Treat attribution and AEC metrics as correlated evidence, not independent probabilities.-5. Add interval outcomes: `likelyPlaybackOnly`, `acceptedNearEndSpeech`, `mixedOrUncertain`, `unscored`, and `scopeLimited`.-6. Keep the guard observational until Stage 5 shows it preserves exact repetition, short replies, and double-talk.--Exit gate:--- The chosen guard materially improves playback-only precision beyond AEC/VAD alone on development data.-- On development data it satisfies the structural speech-preservation invariants and cannot carry support across gaps, routes, epochs, stale references, or conference-room latches. Held-out thresholds are evaluated only in Stage 5 after the recorded one-time unlock.-- No decision can be produced solely from VAD, ASR text, residual energy, or ERLE.--### Stage 5 — corpus acquisition and candidate bake-off--Existing VPIO recordings remain useful regressions but cannot calibrate a raw paired-SCK AEC path. Acquire a topology-matched local corpus only after the Stage 2 wrapper and Stage 4 observational guard are stable.--Required conditions:--- playback-only speech, music, silence, applause, and periodic/ambiguous audio;-- clean normal and quiet near-end speech;-- at least 100 short replies;-- quiet and normal double-talk across multiple echo-to-near-end ratios;-- exact deliberate repetition of far-end words by the local talker;-- multiple nearby speakers and an in-room/no-reference condition;-- selected-app playback plus helper-process and unrelated-process playback;-- system-volume changes, speaker/microphone movement, route changes, gaps, sleep/wake, and CPU pressure;-- built-in speakers plus built-in microphone in at least two acoustic environments, with built-in microphone plus headphones as a negative acoustic-leak control. Bluetooth, HDMI, aggregate, external, and mixed built-in/external routes are separate unsupported domains.--The parent corpus minimums remain binding: at least 12 independent negative sessions across three output configurations and two environments, and at least 30 annotated minutes across three independent recordings for each populated quiet/short/double-talk condition. Split by recording, device, environment, and speaker before tuning. A failed held-out set becomes development data.--Each recording must carry consent provenance appropriate to all participants and the recording jurisdiction before corpus admission. Before the held-out split is opened, record a one-time unlock. Any access to held-out audio, labels, or per-recording outcomes before that unlock reclassifies the affected split as development data and requires a fresh held-out set.--Compare:--- unchanged production baseline;-- Apple VPIO baseline where valid;-- AEC3 linear output;-- AEC3 suppressed output;-- temporal/multiband attribution alone;-- each AEC output combined with the already-implemented observational admission guard.--Accounting rules:--- Count accepted, uncertain, scope-limited, and fail-open original microphone words in every playback-only leak total. A candidate cannot pass by classifying all contaminated intervals unknown or hiding them from the numerator.-- Reject a candidate before ASR scoring if valid actionable coverage is below the pre-registered operational gate, if any individual eligible session falls below it, or if it returns empty residuals while original speech/evidence conflicts.-- Report accepted, mixed/uncertain, unscored, and known-scope-limited duration separately. Do not impose one global cap on legitimate double-talk `mixedOrUncertain`; freeze condition-specific caps before tuning.-- Unknown identity counts against identity coverage. An all-unknown system cannot pass the identity gate.-- Compute playback leak, missed-speech duration, and WER from the one default final-transcript projection in §4, never from different hidden/recoverable artifacts.-- Gate playback leakage with a pre-registered one-sided upper confidence bound on leak events or false words per exposure-hour and a minimum exposure below which the outcome is `insufficientEvidence`, even when zero events are observed.--Reject any candidate that is mostly unscored/inert, bridges gaps, hides incomplete reference scope, damages quiet/double-talk speech beyond the frozen margin, or passes by dropping all microphone text/identities.--### Stage 6 — separately reviewed paired-SCK capture migration--This stage is necessary only if paired-SCK microphone plus AEC3 wins. It is not bundled with dependency or engine work.--Tasks:--1. Add an explicit, default-off capture mode for one `SCStream` emitting selected-app `.audio` and `.microphone`.-2. Preserve both tracks losslessly and retain the current `.unprotected` semantics until offline cancellation for that exact era is validated.-3. Represent successful derived processing in an immutable versioned sidecar/decision record for that capture era. If a new state such as `rawWithValidatedOfflineCancellation` is introduced, it is derived provenance, never an in-place rewrite of the original `.unprotected` era.-4. Keep live microphone admission closed on raw speaker-route eras in the first release. Final offline processing may later derive accepted text from validated residual intervals.-5. Handle exclusive device ownership, permissions, selected-window/application churn, duplicate app records, route changes, interruption, sleep/wake, stream restart, and format changes.-6. Make rollback swap the entire capture runtime back to the current VPIO path. Do not splice capture implementations mid-era without a recorded boundary.-7. Preserve current behavior for headphones, Bluetooth, HDMI, aggregate, external, and unknown routes unless separately evaluated.-8. Inventory and test every current admission consumer before migration: capture-era gates, live track admission, offline `microphoneIntervalIsAdmitted`, ASR retry and whole-chunk fallbacks, `trustedMicrophoneObservationKeys`, global stitching, transcript/UI/export/summary/search, and speaker-profile persistence. All offline consumers must read one persisted interval decision rather than independently interpreting capture protection.-9. Quarantine pre-existing microphone centroids whose provenance cannot prove clean admitted intervals using a reversible, non-destructive flag. Retain original embeddings, bind quarantine decisions to the Stage 0 profile-state hash, and make the kill switch restore the exact pre-migration eligibility state. Reprocessing must never make historical leakage-trained centroids eligible, and original-PCM retry/fallback paths must not bypass the new decision.--Exit gate:--- Hour-long paired capture has no unexplained gaps, backward timestamps, unbounded queues, or format drift.-- Stop/restart/interruption and route transitions create deterministic eras and never open raw live transcript admission.-- The default-off migration does not change ordinary meeting capture.-- A rollback test proves the profile/centroid state hash returns exactly to the Stage 0 baseline.--### Stage 7 — shadow integration and soak--Tasks:--1. Add effective modes `off` and `shadow`, snapshotted at processing-attempt start. Default remains `off`.-2. In `shadow`, run synchronized AEC, residual ASR/VAD, independent attribution, and admission decisions after capture finalization.-3. Keep existing transcript, UI, export, summary, search, and profile output unchanged.-4. Persist a bounded, versioned sidecar keyed by source hashes, capture eras, engine/config/build identity, and policy fingerprint.-5. Record would-change words, segments, intervals, profiles, unknowns, resource use, and baseline disagreements without logging content.-6. Soak cancellation, resume, corrupt sidecars, app upgrades, old sessions, missing dependencies, and repeated processing.--Exit gate:--- `off` remains identical to current behavior.-- `shadow` has no user-visible or profile effect, no callback-path work, and no unbounded storage/CPU growth.-- At least the parent-plan long-call and corpus gates pass with recording-level uncertainty and a frozen configuration.--### Stage 8 — limited offline enforcement--Enforcement is enabled only after a new adversarial code review and held-out acceptance report.--Rules:--1. Apply validated residual ASR only to supported built-in routes and valid intervals.-2. Use one persisted admission decision for transcript, UI, export, summary, search, and profile consumers.-3. Split mixed intervals only at validated frame/word boundaries with frozen padding. Otherwise keep an explicit recoverable uncertain candidate.-4. Exclude playback-only, uncertain, scope-limited, invalid, and unscored intervals from speaker-profile learning.-5. Do not add new speaker-profile enrollment from cleaned paired-SCK speaker-route eras in the first transcript-enforcement release. Existing clean-profile matching may remain read-only. Enrollment yield and residual/original embedding domain behavior move to a separately gated later stage; do not weaken the verified-no-playback original-microphone rule to make identity coverage pass.-6. Unsupported routes and invalid engine/reference states retain the documented legacy/fail-open text behavior but remain excluded from unsafe profile learning. Their false words still count against release metrics.-7. Keep a one-step kill switch back to legacy processing. Do not reinterpret already persisted decisions when the switch changes.-8. Enforce the residual-empty conflict rule from Stage 3: if original speech activity, mixed attribution, exact repetition, or timing evidence conflicts with an empty residual, persist `mixedOrUncertain` and retain recoverable original text; never infer playback-only from silence produced by the canceller.-9. Restrict the first enforcement matrix to built-in output plus built-in microphone. A route/device change closes the current era, resets synchronizer/AEC/guard state, and returns the new era to its route-specific legacy protection until independently supported.--Release gates for transcript enforcement:--- The observed playback-only target is zero accepted microphone words and zero false identities, but passing additionally requires the pre-registered one-sided upper confidence bound on false words/events per exposure-hour and the minimum independent exposure. Zero observations alone never pass.-- At most one percentage point absolute increase in missed-speech duration and speaker-attributed WER for every populated quiet, short-reply, and double-talk held-out condition.-- No increase in false confident identities; no more than one additional fragmentation event per annotated hour.-- Zero known cross-gap, cross-route, cross-epoch, stale-reference, or incomplete-scope suppression events.-- Frozen caps for unscored coverage, CPU, peak memory, processing latency, derived storage, and dependency failures.-- At least 99% valid synchronized timing/reference coverage for each eligible offline session, subject to tightening before tuning; playback-only words in uncertain/scope-limited/fail-open output remain in the leak metric.-- Original audio remains recoverable and deterministic reprocessing/rollback succeeds.-- Identity labeling from existing profiles is non-inferior to the current baseline. New speaker-route profile enrollment and its enrollment-yield gate are explicitly deferred; transcript enforcement cannot mutate profiles merely to satisfy identity coverage.--### Stage 9 — live processing is a separate project--Do not reuse offline approval for live captions. A live design requires a bounded non-real-time worker, render/capture scheduling guarantees, latency UX, stale-reference behavior, interruption and thermal tests, and separate double-talk gates. Until then, live text may differ from the cleaned final transcript and must be documented as such.--## 6. Reviewable delivery units--1. **Signal-domain gate:** acoustic learnability, delay ownership, and reference-scope report; no dependency or app behavior change.-2. **Dependency spike:** pinned AEC3 build, license/SBOM/size report, smoke bridge; no app target linkage.-3. **Engine unit:** wrapper, deterministic fixtures, sanitizers; no meeting pipeline caller.-4. **Offline replay unit:** synchronizer-to-AEC adapter and numeric evaluation; no persisted meeting behavior change.-5. **Attribution unit:** independent multiband guard and evidence policy; offline only and completed before the combined bake-off.-6. **Capture-migration unit:** default-off paired-SCK runtime with immutable originals and closed live admission.-7. **Shadow unit:** versioned sidecar and would-change metrics; output invariant.-8. **Enforcement unit:** offline final transcript only after held-out and code-review approval.--Each unit must include source tests, failure-path tests, resource measurements, a privacy check, and an explicit statement of what remains unproven.--## 7. Required adversarial review questions--The reviewers must try to falsify this plan, specifically:--- Can AEC3 operate correctly with the proposed SCK reference/capture timing, frame order, and reference scope?-- Does paired SCK actually improve the signal domain, or does macOS apply undocumented processing that defeats the assumption?-- Can the plan erase quiet double-talk, exact repetition, or speech immediately after a path change?-- Are `scopeLimited`, missing masks, and fail-open behavior consistent across transcript and profile consumers?-- Does the proposed profile policy prevent shared-centroid contamination and retries/fallbacks from bypassing admission?-- Is the minimal AEC3 dependency/build strategy realistic, reproducible, licensable, and maintainable?-- Are there callback-thread, memory-ownership, exception, sanitizer, signing, or universal-binary hazards?-- Can a candidate pass by abstaining, returning empty residual ASR, or making every identity unknown?-- Is the capture migration sequenced late enough and independently reversible?-- What simpler architecture should replace this one if AEC3 or selected-app reference completeness fails?--## 8. Completion definition--The work is complete only when the chosen topology and engine pass frozen held-out playback-removal and speech-preservation gates; all consumers honor one admission decision; profiles remain uncontaminated; originals and rollback work; dependency/privacy/signing/resource reviews pass; and shadow soak shows no unexplained cross-epoch or incomplete-reference decisions.--Until then, enforcement stays off and paired-SCK speaker-route microphone audio remains unprotected.diff --git a/MEETING_REFERENCE_SYNCHRONIZER_NOTES.md b/MEETING_REFERENCE_SYNCHRONIZER_NOTES.mddeleted file mode 100644index 45bcd9de..00000000--- a/MEETING_REFERENCE_SYNCHRONIZER_NOTES.md+++ /dev/null@@ -1,72 +0,0 @@-# Offline synchronizer first slice--`MeetingReferenceSynchronizer` is a production-inert, deterministic in-memory fixture-API. It converts microphone and ScreenCaptureKit-style reference PCM into 10 ms analysis-frames, preserving valid-sample masks and carrying the microphone source, reference PTS,-and derived session-monotonic timelines.--The slice implements versioned linear conversion metadata, explicit converter delay-compensation, codec priming/remainder/edit-list offsets, bounded input/output budgets,-epoch boundaries, scope/completeness reasons, and synthesized microphone timing freeze and-resynchronization metadata. Missing coverage is represented by masks and unknown reasons;-it is never zero-filled as measured silence.--Frames are consumed in caller arrival order. The first arrival for a sequence number wins;-duplicates and lower-than-the-latest sequence numbers are dropped and counted without adding a-gap or overwriting accepted samples. A forward sequence jump creates an epoch/reset boundary. A-positive interval between the prior accepted end and the current start is marked as unknown gap;-contiguous sample times receive only the boundary marker, so the valid current frame is not-misclassified as missing. Rejected frames consume their sequence number and event insertion is-deduplicated, preventing one malformed frame from manufacturing multiple epochs. Repeated or-overlapping source timestamps are dropped and counted as late/duplicate input. Empty and-pre-origin invalid frames are dropped without claiming a source origin; only a midstream empty-block contributes one inferred unknown interval.--Microphone source origin is established only by the first valid frame. Reference drift maps both-segment starts and segment durations through the same affine scale; output resampling uses the-corresponding session rate so multi-frame placement remains consistent. Each domain is anchored to-its own first valid source coordinate for session placement; the original reference PTS remains in-the source timeline. The exposed lag is configured/mapped alignment (the difference between mapped-first-valid starts), not an observed acoustic delay; `.delayUnresolved` remains present because this-offline fixture has no shared-clock calibration. The value preserves priming, converter, edit-list,-and path-offset coordinates while remaining invariant to unrelated absolute clock origins and-without treating independently selected first samples in a partial output frame as a measured-delay. Synthesized microphone timing freezes adaptation until a real host-time boundary;-sequence/gap boundaries reset state but do not themselves claim measured drift or acoustic delay.--Multichannel PCM is expected to be interleaved and divisible by its declared channel count.-The deterministic fixture policy downmixes by arithmetic channel mean before resampling;-channel-layout-aware mixing and a measured downmix error budget are deferred.--Deferred by design: acoustic delay estimation, adaptive drift estimation, AEC/attribution-engines, file readers, callback integration, and production policy wiring. The configured-reference offset and drift are fixture controls for deterministic replay, not a claim that-those quantities have been measured from a recording.--## Offline replay command--`FluidASRBaselineHost` remains inert in its normal launch path. The replay command is-enabled only by an explicit `--offline-synchronizer-replay` argument or by setting-`FLUID_ASR_OFFLINE_REPLAY=1`; without one of those gates it enters the existing host app-path unchanged. Input is a local JSON fixture supplied on stdin, or with-`--input /absolute/path/to/fixture.json` when the explicit gate is present:--```sh-FluidASRBaselineHost.app/Contents/MacOS/FluidASRBaselineHost \- --offline-synchronizer-replay --input /absolute/path/to/fixture.json-```--The fixture schema is version `1` and contains only synchronizer configuration, enum-strings, frame metadata, and PCM sample numbers. The CLI rejects unknown keys, unknown-enum values, non-finite numbers, malformed channel arrays, invalid ranges, and inputs-outside both the configured and hard safety budgets before invoking the synchronizer.-The result is one bounded JSON summary containing a canonical SHA-256 replay identity,-frame/mask/timeline ranges, epoch and unknown-reason counts, and numeric diagnostics.-It never emits raw PCM arrays, file paths, transcript text, labels, embeddings, or model-artifacts. Failed gate, validation, and synchronizer-open cases return nonzero status;-normal host behavior and production capture/transcription wiring are unchanged.--The host fixture profile is intentionally bounded to roughly 2,000,000 input samples and-6,000 output frames (about 60 seconds at the default 16 kHz/10 ms grid), with a 64 MiB-encoded-input ceiling and a corresponding output-sample allocation cap. These limits are-applied before decoding/normalization to keep replay memory use finite.diff --git a/MEETING_RELIABILITY_IMPLEMENTATION_PLAN.md b/MEETING_RELIABILITY_IMPLEMENTATION_PLAN.mddeleted file mode 100644index d0d80c3e..00000000--- a/MEETING_RELIABILITY_IMPLEMENTATION_PLAN.md+++ /dev/null@@ -1,196 +0,0 @@-# Meeting reliability: live recovery and evidence-based speaker admission--Date: 2026-09-08-Status: Revision v2 — revised after independent Kimi K3 (OpenCode) and Claude Opus reviews. P0 is ready to scope; P1–P3 behavior changes remain gated on its measurements and the contracts below. Reviewers reviewed v1, not this amended version; this is not a claim of external sign-off.-Scope: implementation plan only; this task does not authorize application changes, deployment, model replacement, or cloud upload of meeting audio.--Execution update (subsequent user authorization, 2026-09-08): the first P0 instrumentation/baseline slice is implemented and locally tested; see `MEETING_RELIABILITY_P0_BASELINE.md`. P0 remains open for controlled acoustic fixtures, annotation and the other documented evidence gaps. No P1–P3 policy change or app reinstall was performed.--## 1. Outcomes and boundaries--Detect sustained live-caption blackouts during audible speech and recover responsive decoder stalls; uninterruptible inference has an explicit degraded/final-reconciliation path, not a live-continuity guarantee. Prevent playback-only microphone artifacts from becoming accepted speech or speaker profiles. Preserve quiet speech, brief acknowledgments, multiple microphone-side people, overlap, local-first processing, and installed macOS privacy grants.--This plan complements MEETING_DIARIZATION_V2_IMPLEMENTATION_PLAN.md. That plan addresses application-track speaker separation and cross-chunk identity. This plan owns live-recognizer health and microphone evidence admission; neither may silently redefine the other's models or thresholds. Existing uncommitted work remains untouched.--Non-goals: restore a "You"/ownership election; equate microphone with one person; force speaker counts; infer acoustic identity from conversational meaning; change dictation; replace AEC or ASR merely on vendor benchmarks; automatically erase ambiguous evidence.--## 2. Evidence and uncertainty--Latest playback-only test: approximately 133 seconds, user reports no microphone-side speech.--- App partials stopped after a forced 20-second utterance reset, at approximately 42 seconds. Count remained 123 while feed advanced; text resumed around 80 seconds. No queue drops were logged. Offline text covers the interval.-- Confirmed source-level recovery defect in the inspected tree: rotateLongUtteranceIfNeeded requires utteranceStartPTS and utteranceTurnID; both are established only by a first partial and cleared on reset. No-first-partial stalls evade it. Binary provenance for this recording remains to be verified.-- Initial decoder failure remains unproven. Other resets recovered quickly. Callback generation races, blank decoder output, reset context loss, conversion effects, and runtime scheduling must be distinguished.-- Live microphone produced no partials. Offline processing retained six microphone phrases, five visible and one marked echo.-- Two microphone chunks had 69/75 and 58/76 words unassigned and fell back to per-turn ASR.-- All six scored turns had 100% scoreable coverage. Five verdicts were unknown; one was containsLocalSpeech. Missing coverage is not the explanation for this fixture.-- The signal scorer's low-explanation run is not a dedicated speech detector. Low correlation can reflect noise, nonlinear residual echo, mismatch, or speech.-- trustedMicrophoneObservationKeys currently excludes text echo only. Observation/profile evidence is chunk-label based; public per-turn embeddings may actually repeat cluster centroids. Do not call those independent clean-turn evidence.--Before claiming causality, pin the exact app build, FluidAudio revision and model artifacts. A currently checked-out source tree is not proof of the binary used in the recording.--## 3. Research basis and limits--The following are public documentation or papers, not independent product benchmarks:--1. Recall.ai separates participant streams when bots/platform support allow it; hybrid processing diarizes within streams. Desktop SDK lacks that separate-stream path: https://docs.recall.ai/docs/diarization-2. Granola uses microphone/system audio and platform speaker tags with shared-device and overlap limitations: https://docs.granola.ai/help-center/taking-notes/speaker-attribution-3. Otter distinguishes generic, known and unknown identity and supports corrections: https://help.otter.ai/hc/en-us/articles/21665587209367-Speaker-Identification-Overview-4. MacWhisper documents local speaker grouping and correction/merging, not perfect identity: https://docs.macwhisper.com/article/32-automatic-speaker-recognition-in-macwhisper-5. Deepgram distinguishes interim text, finalized segments and endpoints. Word-gap endpointing is not an independent first-text watchdog: https://developers.deepgram.com/docs/understand-endpointing-interim-results and https://developers.deepgram.com/docs/utterance-end-6. NN3A jointly models residual echo suppression and near-end speech probability, explicitly balancing suppression and speech distortion: https://arxiv.org/html/2110.08437v1-7. AEC Challenge evaluates single/double talk and recognition quality: https://arxiv.org/abs/2202.13290-8. Coria et al. use overlap-aware embedding weighting and incremental clustering: https://arxiv.org/abs/2109.06483-9. Streaming Sortformer maintains quality-selected speaker memory across chunks; the described four-speaker model is not a drop-in unrestricted desktop solution: https://arxiv.org/html/2507.18446v1-10. WhisperX uses VAD segmentation and alignment; alignment is not proof of speech authenticity: https://arxiv.org/abs/2303.00747-11. Careless Whisper documents non-vocal-duration-associated hallucinations in Whisper, not a measured Parakeet rate: https://arxiv.org/abs/2402.08021-12. pyannote exposes attribution confidence and separate exclusive/overlapping views: https://docs.pyannote.ai/tutorials/confidence-scores and https://docs.pyannote.ai/tutorials/speaker-configuration--Engineering inference: separate capture provenance, speech validity, playback duplication, identity, and word attribution. No cited source proves a competitor solves this exact reset stall or playback fixture.--## 4. Proposed contracts--### 4.1 Live health is separate from utterance formatting--Introduce a testable LiveRecognitionHealth state machine with monotonic clock injection and generation-scoped events. Available wrapper inputs: audio PTS/frames accepted at offer, conversion success, append/process call start/completion, activity-detector output, partial/EOU callback sequence, queue backlog/drop, reset invocation/completion. Decode token/blank progress and reliable reset failure reporting are not public hooks in the inspected dependency; exposing them requires an explicit reviewed dependency patch, not an assumed adapter API. External supervision reads thread-safe progress counters; queue count is available but takeDroppedCount is destructive, so metrics must have one consumer or add a non-destructive snapshot.--States: awaitingSpeech, awaitingFirstText, transcribing, recovering, degraded, stopped. Readiness/loading is explicit and not counted as a post-ready stall. State transitions run in one owner; callbacks carry generation, sequence and originating audio range rather than reading only mutable currentFeedPTS.--Use audio-time for speech exposure and timeline mapping, an explicitly chosen monotonic clock for hangs and user latency. Handle sleep/wake through explicit lifecycle events: invalidate old watchdog deadlines, mark discontinuity, and re-baseline after wake. Verify actual clock semantics; do not infer them from systemUptime's name. Detect capture loss from offer progress versus elapsed time independently of speech. Distinguish no speech, speech without text, slow inference/backlog, callback delivery failure and capture loss. VAD is an imperfect signal: low-confidence activity is not grounds for endless resets or transcript rejection.--Caption segmentation must not automatically imply destruction of the acoustic decoder context. Determine pinned manager capabilities before designing soft-finalize; if unavailable, retain current working endpoint behavior until a tested context-preserving strategy exists.--### 4.2 Evidence-based microphone admission--Introduce per-interval MicrophoneEvidence with typed, independently recorded fields:--- capture protection/era and reference availability;-- playback context: scoreablePlayback, verifiedNoPlayback, playbackExpectedButUnscoreable, or unknownPlaybackContext. In-room mode is not by itself proof of no ambient playback; use the available capture facts and label uncertainty. Missing/zero-filled reference audio must not be interpreted as observed silence;-- speech presence (probability, coverage, detector/version, unknown reason);-- playback explanation (score, confidence, delay/coverage, echo/unknown verdict);-- ASR evidence (timings, alignment agreement, provenance, available model confidence);-- overlap and speaker-embedding quality/provenance;-- admission decision and reason codes.--Do not fabricate confidence for providers that do not expose it. Unknown is distinct from negative evidence. Do not multiply correlated scores as if independent. The same admission function is used before profile construction and final transcript assembly.--Proposed outcomes: acceptedSpeech, likelyPlaybackDuplicate, uncertainCandidate, noSupportedSpeech. Speech confidence and identity confidence remain separate: accepted speech may retain unknown identity. Uncertain text remains locally reviewable with provenance but does not update profiles or silently enter default summaries/exports. Final UI/export semantics require explicit tests and product review; original audio is preserved under existing retention policy.--The policy is not a universal AND gate demanding a valid playback reference: genuine microphone-side speech must remain supportable when reference scoring is unavailable. Conversely, AEC being enabled is not positive proof of speech.--## 5. Phases, deliverables, and exit gates--### P0 — Reproducible baseline and instrumentation (must precede policy tuning)--1. Record installed build identity, code SHA/dirty fingerprint, dependency/model revisions, capture era/route, provider options and processing version. Resolve revision mismatches without silently changing dependencies for the baseline.-2. Preserve original session; use local read-only audio fixtures and separate evaluation outputs. No meeting audio, raw transcript, embeddings or credentials go to reviewers/services without separate authorization.-3. Annotate speech/overlap/speaker truth locally. Preserve the user's report of no speech as evidence; ASR output does not refute it. Label this historical fixture user-reported playback-only, with local audio adjudication and ambiguous intervals flagged separately. Add controlled playback-only captures with the microphone active, known playback and an independently verified silent room, plus synchronized microphone-side speech fixtures. Digital-zero and muted-microphone inputs are ASR controls, not substitutes for acoustic leakage tests. Initial corpus requirement: at least 12 independent negative sessions across three output configurations and two acoustic environments, and separately held-out positive sessions covering quiet/brief/overlap speech; increase coverage if uncertainty remains. Split by recording/device/speaker before policy selection; never reuse held-out data for tuning.-4. Add privacy-safe aggregate metrics to live feed/decode/callback boundaries. Record time-to-first-token, longest speech-without-text interval, decoding latency/backlog, generation changes, dropped frames and recovered audio ranges. Diagnostic raw text is opt-in, local, bounded, and off by default.-5. Add an injectable recognizer adapter, activity detector and clock to permit deterministic state tests without loading CoreML models. Preserve production behavior in this instrumentation change.-6. Measure the pinned ASR on digital silence, low-level noise and controlled AEC residuals, in both whole-chunk and per-turn modes. Begin with bounded 10-minute screening per condition, then at least two hours per negative condition before release claims. Compare detector-gated and ungated processing on development data only. Report false words/phrases per minute; do not infer a Parakeet rate from Whisper research.-7. Verify embedding provenance and supported extraction APIs now, before P3 depends on them. Record independently embeddable accepted-duration coverage by condition, including double-talk. If the necessary independent evidence is unavailable, choose and review a dependency extension or an explicit unknown-identity fallback before P3 implementation; do not discover the limitation at release time. Existing configuration snapshots are inert until runtime enforcement is proven by integration tests.--Exit: reproducible baseline report, exact build provenance or explicit limits, annotated negative/positive fixtures, and deterministic reproduction of the watchdog blind spot. Initial decoder cause must be characterized or explicitly remain open; instrumentation is not a completed fix.--### P1 — Live recovery, independently releasable--Targets: MeetingLiveTrackEngine.swift, MeetingLiveModels.swift, MeetingLiveTranscriptionCoordinator.swift, MeetingLiveBoundedQueue.swift, live test suites; new health/adapter types as needed.--0. Prove reset effectiveness for the reproduced responsive-stall class before selecting reset as the recovery action. The inspected dependency suppresses resetStates errors with try?; expose success/failure via a reviewed patch, or treat reset completion as unverified until a bounded token-progress probe succeeds. A completed reset is never a successful-recovery metric by itself. If reset is ineffective, gate a sequential manager replacement on confirmed retirement, measured load time and memory; do not overlap managers. Cache corruption is a counterexample hypothesis, not the proven incident cause.-1. Implement first-text and in-utterance monitoring from the new state machine; reject stale generation callbacks after resets and stop.-2. Log decode heartbeats independently of callbacks. A watchdog on an actor blocked by inference is insufficient: control/supervision must observe progress without waiting for that actor to finish. Chosen policy: one live manager per track, no quarantined parallel CoreML instance. For responsive decoding without text, perform bounded recovery; for uninterruptible inference, retire outputs by generation, enter degraded state and preserve recording. Full live recovery from a hung backend is explicitly unsupported until a separately reviewed process-isolation design exists. The measured incident had continued consumption, so a 90-second inference hang is an adversarial case, not its established cause.-3. Prototype a timestamped recovery buffer with an initial 60-second cap per track at 16 kHz float mono (3.84 MB per track), enough to retain the observed 38-second interval. P0 may lower or raise the cap based on measured blackout distribution and memory/latency budgets, with a reviewed bounded maximum. Maximum two recovery attempts per minute and at most one live manager per track. Replay work has a wall-time budget and cannot let current audio grow without bound; prioritize current captions and record unreplayed historical ranges. These settings are development proposals, not efficacy claims.-4. Maintain a coverage ledger for original, consumed, committed, replayed, dropped and unresolved audio ranges. Require post-meeting reconciliation of gaps against the existing final-processing result, not blind duplicate ASR work. If final processing does not cover a gap, attempt bounded local catch-up after live model retirement; retain an explicit unresolved marker on cancellation/failure. Report live-only and final coverage separately. A longer ring buffer does not guarantee lossless or fast catch-up.-5. Establish committed versus provisional transcript ranges. Committed live text remains immutable; corrected final text is a separate product. Decode with overlapping audio context, discard only confidently timed replay words wholly before the commit boundary, and retain a provisional reconciliation band for boundary-crossing words. A straddling word must not be blindly discarded. Without reliable word timings, use bounded segment overlap alignment and retain an unresolved boundary rather than asserting lossless deduplication. Test real repeated phrases, changed replay hypotheses and PTS discontinuities. Generation plus source audio range is mandatory; text-only matching is insufficient.-6. Surface recovery/degraded status separately from recording status. Avoid permanent "healthy" based solely on incoming audio.--Exit: deterministic tests for no first partial, token/blank stall, delayed inference, callback reorder, reset completion, stop during recovery, real silence/music and queue loss; replay tests at realistic pacing with no missing/duplicated boundary speech. Proposed target: flag confirmed-speech no-text conditions within 5 seconds after readiness, attempt safe recovery within the next 3 seconds when the backend is responsive. Calibrate and freeze the detector operating point using P0 data; do not promise recovery from an uninterruptible backend.--### P2 — Microphone evidence in shadow mode--Targets: MeetingEchoSignalScorer.swift, MeetingEchoDetector.swift, MeetingProcessingPipeline.swift, MeetingProcessingConfiguration.swift and evidence tests.--1. Add explicit speech-presence evidence using an available local detector after verifying its behavior on AEC-processed residuals. Generic VAD detects leaked speech too; combine with playback-reference evidence and evaluate on transformed/noisy reference cases. A near-end-aware model is an experimental alternative, not a prerequisite or assumed available API.-2. Replace the semantic claim containsLocalSpeech with residual-not-explained evidence internally. The inspected TurnEchoVerdict is Equatable/Sendable in-memory state, not Codable; do not invent an enum migration. Audit all consumers, logs and tests to confirm that scope. Persisted isLikelyEcho and new admission/schema meanings still require versioned compatibility. Revisit its override of text echo only through the new evaluated policy.-3. Carry alignment/fallback provenance and uncertainty across every retry. High word/turn disagreement must not be erased by a successful per-turn text return. Use bounded retries; silence/no-speech remains a valid result.-4. Compute shadow admission alongside existing behavior using the ordered decision contract in section 9. Record aggregate candidate/accepted/uncertain outcomes and reason counts locally; make no user-visible filtering changes yet. Policy structure may be developed on development data only; freeze structure, thresholds and corpus before a single held-out acceptance run. A failed held-out run requires a fresh held-out set for a new quality claim.--Exit: a calibrated policy with false-positive/false-negative trade-offs, including noisy playback, low-volume acknowledgments, no reference, double-talk, route transitions and in-room multi-person capture. No thresholds selected only to remove the five observed phrases.--### P3 — Admission and profile integrity--Targets: trustedMicrophoneObservationKeys, staged/pending microphone turns, MeetingGlobalSpeakerStitcher/embedding index integration, transcript/export/summary consumers, session serialization.--1. Apply evaluated admission before constructing any profile and at transcript finalization. Unit-test all entry paths, including whole-chunk fallback, unreadable reference, word-aligned and per-turn providers, resume/checkpoint and reprocessing.-2. Obtain true independent interval embeddings from validated non-overlap speech. Verify dependency APIs: repeated chunk centroids are not substitutes. If unavailable, conservatively exclude contaminated observations from profile updates and retain accepted text with uncertain identity. Do not gate all valid text on embedding availability.-3. Aggregate trusted duration/quality only over accepted evidence. Profile updates must retain provenance sufficient for session-local recomputation if admission changes; rejected turns must not contaminate siblings through a shared centroid.-4. Lazily create unknown identities; count only identities represented in accepted visible speech. Distinguish unknown person from uncertain speech. Support correcting/merging attribution without overwriting original evidence.-5. Version decision schema and processing cache/checkpoints; old artifacts without evidence are legacy/unknown, never silently trusted. Classification changes bump MeetingProcessingPipeline.pipelineVersion (inspected value 10); coordinate mirrored configuration defaults. Record effective admission-policy/detector versions and flag state in processing-attempt provenance, plus live-policy provenance in the appropriate capture/session record. Checkpoints currently hold the application pass, not microphone evidence; require an exact final-policy fingerprint on resume or explicitly invalidate/rebuild. Existing fingerprints must be proven enforced at runtime. Reprocessing is explicit, transactional, resumable and cancellable. Do not mutate old sessions automatically. Old UI/export reads preserve historical display until explicit reprocessing; rollback cannot reinterpret a new uncertain decision as accepted speech.--Exit: playback-only regression corpus produces zero accepted mic words and zero visible mic identities; genuine short/quiet/overlap speech preservation meets held-out gates. All display/export/summary consumers agree about decision semantics; original evidence remains recoverable.--### P4 — Optional diarization bake-off, not a dependency of P1–P3--Compare current pinned pipeline against overlap-aware alternatives on approved local fixtures. Evaluate pyannote-style segmentation/embedding weighting and streaming cache concepts; any actual model integration requires license, supported speaker count, CoreML/CPU/GPU feasibility, memory and energy checks. Do not add cloud uploads, meeting bots, browser extensions, voice enrollment or persistent voiceprints as an implicit implementation step.--Keep native overlapping timelines separate from exclusive display views. Preserve word attribution uncertainty when multiple speakers overlap; exclusive diarization does not separate voices or recover masked words. Coordinate application-track changes with the existing Diarization V2 plan.--Exit: measured improvement on held-out data justifies cost and migration; otherwise retain current diarizer with P1–P3 controls.--## 6. Evaluation and release gates--Report per-condition results, not only averages:--- Playback-only built-in/external speakers at multiple volumes; headphones; silence; music; fan/keyboard noise; reverberation; nonlinear/distorted playback; missing/wrong reference.-- Quiet microphone-side speech, one-word replies, accents, two nearby people, similar voices, simultaneous playback and speech, real repeated phrases.-- Long continuous speech, onset after silence/reset, hour-long sessions, warmup, system load, queue saturation, route/sample-rate/era changes, stop/resume and cancellation.-- Final metrics: false mic words/minute, false identities/session, missed speech duration, speaker-attributed word errors, speaker confusion/splits/merges and alignment coverage. DER settings must declare overlap handling and boundary collars; silence-only fixtures need false-alarm metrics because DER has no speech denominator.-- Offline live-evaluation metrics: first-text latency from annotated speech onset after readiness, p95/max blackout during annotated speech, omission/duplication at recovery and final coverage reconciliation. Production proxies: time from detector-indicated onset to text, detector-active time without text, decode heartbeat latency/backlog, recovery/degraded duration, CPU/memory/energy and capture drops. Proxies are not ground-truth missed-speech measures.--Proposed gates, to be frozen after baseline and before implementation tuning: zero false accepted mic words/identities on the curated playback-only regression set; at most 1 percentage point absolute increase in missed-speech duration and 1 point speaker-attributed WER on each populated quiet/short/double-talk held-out condition; no new capture drops; no unbounded growth in hour-long runs. Each positive gate condition needs at least 30 minutes annotated audio across three independent recordings, with at least 100 labeled short replies for the short-reply gate; this is a minimum, not sufficient statistical power by itself. Report paired uncertainty intervals and require their upper bounds to meet the non-inferiority margins or report insufficient evidence. Add no increase in false confident mic identities and no more than one additional identity fragmentation event per annotated hour on echo-heavy held-out positives, reporting uncertain-attribution coverage separately so an all-unknown system cannot pass. These are engineering targets, not statistical guarantees.--For the zero-observed-false-positive regression gate, also report an exposure-normalized upper confidence bound and recording-level paired uncertainty; zero on a small corpus is not zero risk. Do not apply a binomial formula directly to words/minute. If using a Poisson rate bound, declare its event/independence assumptions and supplement with session-level results for bursty errors.--Release independently behind liveRecoveryV1 and microphoneAdmissionV1 configuration controls. Test all four flag combinations, not merely all-on/all-off. Roll back behavior independently while retaining compatible evidence records; ensure disabled behavior has regression coverage. Progress from shadow evaluation to opt-in debug to broader rollout only after gates pass. Debug reinstall must preserve com.FluidApp.app, /Applications/FluidVoice Debug.app, verified signature, matching designated requirement and Team ID; stop rather than replace with mismatched signing.--## 7. Work breakdown and review checklist--Suggested implementation slices: (1) provenance/harness, (2) adapter/telemetry, (3) live state tests, (4) bounded live recovery, (5) evidence/shadow policy, (6) independent profile evidence, (7) admission consumers/migration, (8) held-out evaluation/rollout. Each slice has focused tests and a small reversible diff; no broad pipeline rewrite.--Adversarial reviewers should challenge: provenance assumptions; VAD false negatives and leaked-speech false positives; uninterruptible inference/reentrancy; replay boundaries; corrupted sibling embeddings; uncertainty UX; in-room/no-reference policy; migration/rollback; data leakage; hard limits and test feasibility. Demand falsifiable counterexamples and concrete changes. Distinguish confirmed code facts from proposals and unavailable dependency capabilities.--## 8. External review disposition--Both reviewers returned "revise before implementation" on v1. This v2 incorporates adjudicated findings, with empirical questions retained as explicit gates rather than claimed solved. See docs/reviews/meeting-reliability/draft-v1.md, kimi-k3-review.md, claude-opus-review.md and disposition.md. Kimi reviewed relevant source as well as the plan; Claude reviewed only the supplied plan with tools disabled. No reviewer was authorized to implement application changes or access meeting recordings, secrets, credentials or unrelated files.--## 9. Admission decision contract (ordered, shadow-first)--This is a proposed policy structure to freeze on development data before held-out evaluation, not a proven classifier. Numeric operating points remain P2 deliverables. Speech-positive means calibrated acoustic support, not merely ASR text. Speech-negative requires sufficient valid audio and corroborated no-speech evidence, not a single low VAD score. Generic VAD is not independent near-end evidence during playback. ASR conflict includes severe alignment disagreement and uncorroborated fallback; per-turn fallback alone is not automatic rejection when independently supported.--Apply the first matching row; wildcard rows cover remaining combinations:--| Order | Condition | Result/reason |-|---|---|---|-| 1 | Existing online capture-protection admission fails | Excluded by capture policy; preserve evidence. No new AEC-based assumption of speech |-| 2 | No candidate text | No text emitted; if speech evidence exists, record an ASR coverage gap rather than claim silence |-| 3 | Valid corroborated speech-negative audio | noSupportedSpeech; short/quiet duration alone cannot trigger this |-| 4 | Mixed playback/local speech or contradictory evidence | Split only when validated temporal evidence permits; otherwise uncertainCandidate/mixedEvidence, never suppress the whole turn as echo |-| 5 | Strong playback-duplicate evidence, no supported independent speech, no conflict | likelyPlaybackDuplicate; short-text matches alone are insufficient |-| 6 | Speech unknown or ASR conflict remains | uncertainCandidate/insufficientEvidence; no profile update |-| 7 | Speech positive, ASR supported, verifiedNoPlayback | acceptedSpeech; identity may remain unknown |-| 8 | Speech positive, ASR supported, scoreablePlayback AND validated independent microphone-side support | acceptedSpeech; identity evaluated separately |-| 9 | Speech positive during playbackExpectedButUnscoreable or unknownPlaybackContext | uncertainCandidate/referenceUncertain unless separately validated microphone-side evidence satisfies a pre-registered rescue; default policy has no such rescue |-| 10 | Any other combination | uncertainCandidate/unresolved; no profile update |--Unknown context does not silently become accepted. Conversely, in-room/verified-no-playback positives do not require an echo score or an owner voiceprint. This intentionally risks uncertainty for legitimate speech during unscoreable playback; P2 must measure uncertain/missed coverage and cannot ship if positive-speech gates fail. Evaluate the detector's added discrimination within each echo-score/context bucket, not just aggregate AUC. If it adds no useful discrimination, redesign the evidence source instead of counting correlated votes twice.--## 10. Required test artifacts and unresolved decisions--- Annotation format: local interval/word records with recording ID, track, start/end, speaker ID, speech/overlap label and adjudication confidence. Annotator disagreement is retained. Fixture manifests carry provenance and split, not audio in external-review packets.-- Deterministic recovery tests use a fake decoder with exact known tokens/timestamps: each expected token is committed once; overlapping audio may intentionally decode in multiple generations. Audio-range replay across generations is not itself a duplication bug.-- Real replay uses manually verified word-boundary neighborhoods (at least two seconds either side of resets) against annotated speech, not offline ASR as unquestioned ground truth. Report insertions/deletions, genuine repetition preservation and alignment uncertainty. No fixed 0.9 text-containment heuristic is presumed sufficient.-- P0 must settle dependency hooks/reset observability, exact binary/model provenance and independent-embedding feasibility. Missing APIs require a separately scoped patch; their absence is not papered over with fake confidence or repeated centroids.-- P1 must demonstrate responsive-stall recovery and independently demonstrate hang detection/gap reconciliation. Add fake never-returning inference and bounded stop tests; stop/UI return cannot await the hung manager indefinitely. Keep capture ownership and post-meeting handback safe until the worker really retires; mark final processing deferred if model/resource handback is unsafe.-- P2 must validate the proposed decision structure and choose thresholds using development data only. No-reference positives, playback-with-unreadable-reference negatives and mixed-turn short interjections are mandatory adversarial fixtures.-- P3 must settle the clean-embedding API or explicit identity fallback, versioned consumer contract and uncertainty review UI before user-visible activation. Accepted speech must not require a profile; fallback must not create a new person per fragment.-- Product/engineering review must approve uncertain-content visibility/export behavior and revised quantitative gates before implementation activation. No new cloud upload, recording retention expansion, or model download is implied by this planning task.diff --git a/MEETING_RELIABILITY_P0_BASELINE.md b/MEETING_RELIABILITY_P0_BASELINE.mddeleted file mode 100644index d403586e..00000000--- a/MEETING_RELIABILITY_P0_BASELINE.md+++ /dev/null@@ -1,94 +0,0 @@-# Meeting reliability P0 baseline--Date: 2026-09-08 (local). Status: instrumentation and initial measurement slice; **P0 exit gate remains open**. No recovery/admission policy, dependency revision, installed app, privacy permission, or saved recording was changed.--## Execution plan and scope--1. Preserve the existing recording and fingerprint local source, installed binary, processing metadata and staged models.-2. Add an injectable recognizer/clock and opt-in numeric wrapper diagnostics without changing live rotation policy. Reproduce the no-first-partial blind spot deterministically.-3. Measure digital silence and seeded low noise using the pinned offline ASR, in 60-second and 3-second calls. Keep test completion separate from speech-quality verdicts.-4. Obtain an Orchestrate adversarial review, address evidence/reporting defects, and document remaining controlled-corpus gates before P1.--## Evidence and provenance--Local machine-readable inventory: `/private/tmp/fv-reliability-p0-20260908/inventory-v3.json`. Earlier inventory files are superseded.--- Source HEAD: `b701716177bebba97a82d68aa9aa8f765292a8a2`; dirty tree preserved. Inventory records the tracked-diff hash, not an assertion that untracked files are covered.-- Package declaration, both resolved files, and local FluidAudio checkout agree on `3fd63887eef1dc25edea8263ce4b44aa854d898b`.-- Installed `/Applications/FluidVoice Debug.app`: `com.FluidApp.app`, version 1.6.10, build 22, Team `A8467RRA3D`. Deep/strict signature verification succeeded using host trust access. Launcher SHA256 `14948a43786af513c65fb53c0d4b07c0afdf1e77823321b83d9493278f7d5377`; debug dylib SHA256 `f9907c5e5cb623732c9f76627d1cf38803b4a1e370501f848e16e8988be27000`.-- Exact historical binary-to-source match is **unproven**: no embedded build manifest. A present-day hash does not establish recording-time identity.-- Historical session SHA256 `fbccf8fce03fb83a87643192e47e164a5d588726e2ad45f273d6d6383d3de557`; all six chunk hashes match stored values. Inventory contains aggregate metadata only, no transcript or audio.-- User-reported playback-only, approximately 133 seconds. This report preserves that account; no independent listening/annotation adjudication was performed. Application capture was ScreenCaptureKit, 48 kHz stereo; microphone was voice-processing I/O, 48 kHz mono. No stored capture drops/chunk discontinuities or session failures were found.-- Selected log lines 4825–5004 show app partial count 123 unchanged while audio advances 30.1 seconds over 30.071 seconds of sampled wall time. This is a sampled lower bound, not the full blackout duration or proof of audible speech. A silent microphone having no partials is expected.-- Offline staged model manifest SHA256 `b39baf9bf54a0c70e9821989da9cdde32ca3f1f4e74894efa85f982320affad3`; 22 artifacts checked. Inventory reports both hash agreement and exact repository file-set agreement. Hugging Face artifact revision is unavailable; hashes identify local content, not publisher authenticity. Live/diarizer model provenance is not yet complete.--## Instrumentation and deterministic tests--`MeetingLiveTrackEngine` now accepts a recognizer and monotonic clock. Debug diagnostics are opt-in with `FLUIDVOICE_MEETING_LIVE_DIAGNOSTICS=1`; release diagnostics are forced off. New counters contain numbers only. Existing logging behavior outside this change is not a privacy audit.--Tests exercise the actual engine conversion/append/process/rotation path with a fake recognizer, without capture or model loading:--- 40 seconds of feed with no first partial invokes no reset.-- A forced 20-second boundary followed by 38 seconds without partials does not trigger another recovery, despite continued process returns.-- Explicitly disabled diagnostics do not accumulate counters.-- Injected seven-second processing delay is measured without sleeping.-- A thrown process call is not counted as a successful return.--These characterize the existing recovery blind spot; they do not establish why the real decoder first stopped emitting text. `recognizerResetReturned` means wrapper return only. `wrapperGeneration` is a reset ordinal, not a callback-origin epoch. First-partial latency starts after reset returns. Actor-local counters cannot supervise a blocked actor, measure decoder token/blank progress, establish speech activity, or prove recovery. Activity-detector injection and independently readable watchdog progress remain pending.--## Synthetic negative screen--The isolated `com.FluidApp.ASRBaselineHost` requires app sandboxing and rejects microphone/network entitlements at runtime. It uses direct local CoreML constructors, with no model-download API. It never opens the historical recording. The installed Debug app is not used or replaced.--Default exposure is 600 seconds for each of four condition/mode combinations: digital silence and seeded uniform noise at peak 0.001, each in 60-second and 3-second calls. This is 40 minutes of synthetic ASR exposure, not 40 minutes of independent acoustic recordings. No VAD, AEC, diarization, production provider, or live EOU recognizer is exercised. Three-second calls approximate short segmentation; they are not the production fallback pipeline.--Pinned `ASR/Parakeet/AsrManager.swift:524–548` awaits throwing `resetDecoderState()` before returning a successful array transcription. `initialize(models:)` installs supplied local models. This source check supports sequential state-reset semantics, not universal offline safety; host entitlements enforce the screen's network boundary. Errors abort the screen. The between-call wall budget cannot interrupt a stuck CoreML invocation.--Every report has `verdict: measured_only`. XCTest success means execution/schema checks completed, even if all inputs generated text. Nonempty outputs and whitespace-delimited words are reported; text is not attached. No confidence interval or release-quality conclusion is justified by repeated deterministic silence.--Completed measurement in `screen-v3.xcresult`; JSON attachment `/private/tmp/fv-reliability-p0-20260908/attachments-v3/71D9A149-34D2-4880-9039-A1DD95D5E4DA.json`. Model load took 11.654 seconds.--| Input | Call length | Audio exposure | Calls | Nonempty outputs | Words/minute |-| --- | --- | --- | --- | --- | --- |-| Digital silence | 60 seconds | 600 seconds | 10 | 0 | 0 |-| Digital silence | 3 seconds | 600 seconds | 200 | 0 | 0 |-| Seeded low noise | 60 seconds | 600 seconds | 10 | 0 | 0 |-| Seeded low noise | 3 seconds | 600 seconds | 200 | 0 | 0 |--Zero words in these controls does **not** explain or exclude playback-leakage hallucinations. The v3 test bundle had eight passing tests and one failing path-alias fixture test (nonexistent paths cannot reliably resolve aliases); the inference measurement itself completed. That fixture was corrected to create an actual local directory and alias; final rerun status is recorded below.--Final rerun: `screen-v4.xcresult` — **9 passed, 0 failed, 0 skipped**. Final attachment: `/private/tmp/fv-reliability-p0-20260908/attachments-v4/34F372C3-E600-4570-8255-3C4E97491046.json`. Eight Python inventory regression tests also pass; `git diff --check` is clean. Existing unrelated compiler actor-isolation warnings remain; no production-app test/install or release build was performed.--The final rerun again measured 420 calls / 2,400 audio seconds with zero nonempty outputs and zero words; warm model load was 0.132 seconds. Repeated runs are not independent acoustic exposure.--Final tested file SHA256 fingerprints (supplement the tracked-diff inventory):--```text-8e1e5c0634d9aaa18181b18259d0377ead80772cef52764c1f70c67b9d9c37a0 MeetingLiveTrackEngine.swift-e94f7c8a3d7a0234d26ec3ae7c5bb0d4c5c2b5bc4745f0d27d07410d41f5450c MeetingLiveP0DiagnosticsTests.swift-d2d920fd5c2db77a71ca67171084ccf74b79b3f09c57f6bf8107bb6a9e62b8eb MeetingReliabilityNegativeScreenTests.swift-2c35e544313e6a978915fbb75ee26c8e84c571efed04e59a6c346f219e994e06 meeting_reliability_baseline.py-8643d41129b662114a7b626fde122436802b2762d597d6170cf65be928c13abc test_meeting_reliability_baseline.py-```--## Embedding API audit--At the pinned revision, `Diarizer/Offline/Utils/OfflineReconstruction.swift:337–345` assigns the cluster centroid to each returned `TimedSpeakerSegment.embedding`; trimming/merging retains it. These are not independent clean-turn embeddings.--The offline extraction implementation is internal (`Offline/Extraction/OfflineEmbeddingExtractor.swift`). A separate public `EmbeddingExtractor.getEmbeddings(audio:masks:)` exists, with a fixed `[3,160000]` waveform shape and legacy WeSpeaker model interface. Its existence does not establish compatibility with offline feature/PLDA space or current profile similarity thresholds. No extraction compatibility or independent accepted-duration coverage was measured. P3 must review a compatible interval-extraction extension or an explicit uncertain-identity fallback before trusting independent evidence; this slice chooses neither implementation.--## Adversarial review disposition--Orchestrate standard route completed a read-only Grok 4.6 review of the five scoped code/test/tool files (`editedTree=false`). An earlier route failed; the heavy route was blocked by host policy and was not bypassed. No private meeting audio, transcript, embeddings, or credentials were supplied.--Findings addressed: added an explicit measurement-only verdict; renamed reset return/generation counters and moved latency start after reset return; added exact-tree inventory checks; made missing capture-drop schema fail closed and excluded missing speaker IDs from person counts. Removed hard-coded recording-condition inference from the reusable inventory. Verified the pinned offline transcription reset implementation locally in response to the review's uncertainty. Review occurred before these amendments; it is not external sign-off on the amended tree.--## Reproduction and remaining exit gates--Run inventory regressions with `python3 -m unittest discover -s tools -p test_meeting_reliability_baseline.py`. The inventory CLI requires explicit repo/app/session/model-manifest paths; log parsing additionally requires a caller-selected same-session line range. Output creation is exclusive.--Build the existing `FluidASRBaseline` scheme with staged `FLUID_ASR_BASELINE_INPUTS`, using the stable local signing identity. Then run the two P0 XCTest classes with `TEST_RUNNER_FLUID_RELIABILITY_NEGATIVE_SCREEN=1`. Test-run settings accept `FLUID_RELIABILITY_SECONDS` (60–600, default 600) and `FLUID_RELIABILITY_WALL_SECONDS` (60–1800, default 1200); with xcodebuild forward them using `TEST_RUNNER_`. Retain the xcresult and its JSON attachment. Never install this baseline host over the Debug app.--The packaged CTranscribe framework was copied with broken version symlinks by the current build inputs. Only the generated baseline-host copy was repaired, originals preserved in a temporary backup, then re-signed and deep/strict verified. Rebuilds may recreate this packaging defect. This is not a fix to the upstream framework or production packaging.--P0 is not complete until controlled active-microphone playback/AEC-residual and positive speech fixtures are collected and independently annotated: at least 12 independent negative sessions across three output configurations and two acoustic environments, with separate quiet/brief/overlap held-out positives. The human acoustic setup/speech truth cannot be supplied by synthetic samples. Freeze recording/device/speaker splits before tuning; extend negative exposure to the plan's release minimum before claims. Complete effective runtime options/model provenance, activity instrumentation, embedding coverage and detector-gated development comparisons. The original decoder cause remains open.diff --git a/MEETING_SPEAKER_OVERLAP_TURN_ORDER_IMPLEMENTATION_PLAN.md b/MEETING_SPEAKER_OVERLAP_TURN_ORDER_IMPLEMENTATION_PLAN.mddeleted file mode 100644index 410ea7bb..00000000--- a/MEETING_SPEAKER_OVERLAP_TURN_ORDER_IMPLEMENTATION_PLAN.md+++ /dev/null@@ -1,122 +0,0 @@-# Speaker Overlap and Turn Order Implementation Plan--Status: implemented after router adversarial review; focused verification passed-Scope: canonical Parakeet + Nemotron final transcript attribution, product turn construction, and-speaker labels. Timeline normalization is already complete and is not reopened here.--## Problem statement--The latest 78.8-second Chrome recording produced two valid Nemotron speaker slots and 278 Parakeet-word units. Of those, 263 were assigned, 13 were marked ambiguous because both slots intersected the-word, and two were outside all speaker activity. The product then:--1. treats any second-slot intersection larger than the manifest's one-microsecond mapping tolerance- as real speaker overlap;-2. renders every nil speaker ID as `Unknown speaker`, collapsing genuine overlap, no activity, and- timing uncertainty into one label;-3. drops outside-activity ASR text from the visible transcript; and-4. groups all segments by speaker/state before merging, so A → B → A can become one long A row with- B displayed inside its time interval.--## Invariants--- Preserve every admitted ASR word exactly once and in chronological order.-- Never invent a speaker identity when evidence is genuinely ambiguous.-- A segment between two same-speaker segments breaks the turn, even if the gap is small.-- Cross-track segments do not merge with each other and do not reorder either track's local turns.-- Speaker activity intervals for one token are unioned before overlap is measured; duplicates never- increase evidence.-- Model cadence, overlap thresholds, and dominance thresholds are named, backend-versioned policy,- not generic manifest tolerances or unexplained literals.-- Sidecar evidence remains word-granular and retains ambiguity candidates and dispositions.-- Existing session JSON remains decodable; no enum case is removed or renamed.--## Phase 1 — Chronological turn construction--Replace `mergeCanonicalSegments`' grouping by full merge key with a per-track chronological fold:--1. group only by track;-2. sort each track by `(start, end, id)`;-3. compare each segment only with the immediately preceding output segment on that track;-4. merge only when the full attribution/state key matches, the gap is at most the named- `canonicalTurnMergeGapSeconds = 3`, and total turn duration is at most the named- `canonicalTurnMaximumDurationSeconds = 30`;-5. otherwise append a new turn; and-6. globally sort the completed per-track turns by `(start, end, trackID, id)` for publication.--Add regressions for A → B → A, A → ambiguous → A, overlapping turns, deterministic IDs, adjacent-same-speaker words, maximum gap, maximum duration, and stable global ordering across tracks.--## Phase 2 — Typed product labels--Add an optional, backward-compatible product attribution state and create one shared transcript-speaker-label resolver used by UI rows, accessibility, text export and copy operations:--- known speaker ID / `.assigned`: resolved speaker name;-- `.overlappingSpeakers`: `Overlapping speakers`;-- `.unassigned`: `Unassigned`;-- `.timingUncertain`: `Timing uncertain`.--Row label visibility compares the resolved label, not only `speakerID`, so adjacent nil-speaker rows-with different meanings each show their label. JSON export keeps `speakerID: nil` and the existing-overlap field, preserving machine-readable meaning without a schema break.--Older segments without the field fall back to the existing speaker-ID/overlap interpretation.-Timing-uncertain text remains nil-speaker but changes from `.ambiguous` to `.none`; it is not-evidence of simultaneous speakers and stays distinguishable from ordinary unassigned text.--## Phase 3 — Preserve the existing outside-activity safety policy--Keep `.outsideActivity` text suppressed in this change. Surfacing it could expose silence/noise ASR-hallucinations and requires a separate evidence policy. Echo-suppressed, outside-activity,-inadmissible and invalid-timing units remain excluded and fully accounted for in the sidecar.--## Phase 4 — Backend-specific overlap dominance--Replace token-presence assignment with union-overlap scoring for each word:--1. clip activity intervals to the word and union intervals per speaker token;-2. calculate coverage seconds and coverage fraction for every token;-3. use Nemotron's documented 80 ms output cadence as a named maximum boundary-noise duration;-4. scale the boundary-noise threshold for short words as- `min(80 ms, 20% of the word duration)`, so 80 ms can never be discarded from a 150 ms word;-5. if every candidate is at or below that threshold, return `.unassigned` rather than creating a- confident assignment from near-zero evidence;-6. assign the sole candidate above the threshold;-7. with multiple candidates, assign the leader only when it covers at least 50% of the word, the- runner-up covers at most 20%, and the leader has at least twice the runner-up coverage;-8. otherwise return `.ambiguous` with deterministically sorted above-threshold candidates; and-9. keep whole-epoch utterance fallback conservative: multiple candidates remain ambiguous.--The ratios are conservative initial product policy, isolated in a configuration value and covered-at exact boundaries. Add DEBUG-only structured measurements for multi-candidate words—duration,-leader overlap, runner-up overlap and decision—without transcript text or participant identity.--Increment the Parakeet+Nemotron backend version to `2` and the meeting pipeline version to `12` so-new attribution and turn semantics have explicit lineage.--## Phase 5 — Verification--Required focused tests:--- `MeetingParakeetNemotronBackendTests`: one-frame sliver, sole sub-frame activity, 60/40 overlap,- full overlap, exact thresholds, duplicate intervals, deterministic ties and utterance fallback;-- `MeetingTranscriptAssemblerTests`: ambiguous, unassigned and timing-uncertain attribution states,- while outside-activity text remains suppressed;-- canonical merge tests: A/B/A, ambiguous breaker, adjacency, bounds and cross-track order;-- exporter/UI projection tests: Speaker N, Overlapping speakers, Unassigned, alias resolution and- label transitions; and-- golden replay assertions derived from the latest session: no turn contains an intervening- same-track turn, product text order matches sidecar word order, and all accepted words appear once.--Run the focused suites, full integration `build-for-testing`, signed Debug build, stable-identity-install preflight, and a real Chrome replay. Existing incorrectly merged sessions require Retry to-re-run backend version 2 scoring and rebuild turn rows from word evidence; label improvements apply-immediately to their retained ambiguous rows through the backward-compatible fallback.--## Explicit non-goals--- Naming anonymous slots from calendar or accessibility metadata.-- Merging speaker identity across epochs.-- Changing Nemotron model weights or quality measurements.-- Reopening timeline normalization, PCM retention, or compression work.diff --git a/MEETING_TRANSCRIPTION_BACKEND_ARCHITECTURE_PLAN.md b/MEETING_TRANSCRIPTION_BACKEND_ARCHITECTURE_PLAN.mddeleted file mode 100644index 01f7bad7..00000000--- a/MEETING_TRANSCRIPTION_BACKEND_ARCHITECTURE_PLAN.md+++ /dev/null@@ -1,843 +0,0 @@-# 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.mddeleted file mode 100644index dc5ff7b8..00000000--- a/MEETING_TRANSCRIPTION_BRANCH_CODE_REVIEW_2026-09-14.md+++ /dev/null@@ -1,245 +0,0 @@-# 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.mddeleted file mode 100644index 5778d28a..00000000--- a/MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md+++ /dev/null@@ -1,449 +0,0 @@-# 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/MEETING_TRANSCRIPTION_PRD.md b/MEETING_TRANSCRIPTION_PRD.mddeleted file mode 100644index a4f22966..00000000--- a/MEETING_TRANSCRIPTION_PRD.md+++ /dev/null@@ -1,930 +0,0 @@-# FluidVoice Meeting Transcription PRD--**Status:** Draft for product alignment-**Last updated:** 2026-08-05-**Target:** FluidVoice for macOS 15+-**Initial release:** English, local recording, offline transcription after Stop-**Long-term direction:** Optional meeting detection, remembered speaker identities, and live progressive transcription-------## 1. How to use this document--Every tracked requirement has a checkbox and one of these tags:--- **[MUST · FOUNDATION]** — Must be designed correctly before implementation because later milestones depend on it.-- **[MUST · V1]** — Release blocker for the first trustworthy offline meeting-transcription release.-- **[OPTIONAL · V1]** — Valuable, but may move behind the first release without invalidating the core experience.-- **[MUST · Mx]** — Required for that named milestone; M1 is the first working vertical slice, M2 is the trustworthy V1 gate, and M3–M5 are staged follow-ups.-- **[OPTIONAL · Mx]** — Valuable within that milestone but safe to defer.-- **[CONDITIONAL MUST · Mx]** — Mandatory only if its parent optional capability is enabled.-- **[OPTIONAL · SECURITY]** — Security hardening that must not be claimed until implemented and verified.-- **[FUTURE · LIVE]** — Explicitly outside V1; the V1 architecture must leave a clean path for it.--Checkboxes should be checked only when the requirement and its acceptance criteria are complete. A compiling implementation alone is not completion.--### Document map--- [Confirmed decisions](#3-confirmed-product-decisions)-- [Goals and non-goals](#4-goals-and-non-goals)-- [High-level milestones](#5-high-level-milestones)-- [User experience and canvas states](#7-user-experience-and-canvas-states)-- [Session lifecycle](#8-session-lifecycle)-- [Target architecture](#9-target-architecture)-- [Audio capture](#11-audio-capture-design)-- [Offline transcription](#12-offline-english-transcription-pipeline)-- [Speaker identity](#13-speaker-identity-and-correction)-- [Supported platforms](#14-supported-meeting-platforms)-- [Meeting detection](#15-meeting-detection-and-suggestion-prompt)-- [Menu-bar lifecycle](#16-menu-bar-lifecycle-and-notifications)-- [Privacy and retention](#17-permissions-consent-privacy-and-retention)-- [Acceptance gates](#21-acceptance-and-release-gates)-- [Follow-up bugs](#22-follow-up-bugs)-- [Open decisions](#23-open-decisions-for-alignment)-------## 2. Product summary--FluidVoice should let someone record an online or in-room meeting locally, stop recording, and receive an English transcript organized by speaker. Online meetings should preserve the user's microphone separately from meeting-app audio so clean speech from a confirmed personal microphone can be labeled **You** while remote participants are diarized. Shared microphones, leakage, and ambiguous overlap must remain explicitly unknown.--The initial release deliberately records first and transcribes after Stop. This protects recording reliability and resource use. The underlying session and transcript models must still support provisional, revisable segments so a future live mode can progressively fill the same transcript canvas without a rewrite.--Speaker diarization answers **who spoke when**, but it does not inherently know real names. FluidVoice may propose a name using visible meeting UI and confirmed local voice profiles, but the user remains the authority through a compact confirmation:--```text-Speaker 2 · Was this Erik? [Yes] [No]-```-------## 3. Agreed product requirements — implementation status--The direction below is agreed. Its checkboxes remain open until the corresponding behavior is implemented and verified.--- [ ] **[MUST · V1] DEC-001 — English-only initial release.**- - Persist `languageCode = "en"` in the session, processing request, history, and exports.- - Do not scatter hard-coded English assumptions through capture or transcript models.--- [ ] **[MUST · V1] DEC-002 — Local-first data path.**- - V1 capture and processing never upload meeting audio, transcripts, participant names, or voice embeddings.- - Network activity is limited to model downloads and exports explicitly initiated by the user.- - Analytics and diagnostics must exclude their contents.--- [ ] **[MUST · V1] DEC-003 — Explicit recording action.**- - FluidVoice never begins recording automatically.- - A meeting-detection prompt may suggest recording, but the user must click **Record**.--- [ ] **[MUST · V1] DEC-004 — Offline-first processing.**- - V1 records during the meeting and begins ASR/diarization only after Stop.- - The recording path remains useful even when transcription models are not yet ready.--- [ ] **[MUST · FOUNDATION] DEC-005 — Live-ready schema.**- - Segments have stable IDs, revisions, and provisional/final state from the start.--- [ ] **[MUST · V1] DEC-006 — Separate online-call tracks.**- - Meeting/application audio and microphone audio remain separate and timestamped.- - They are never irreversibly mixed before transcription and identity processing.--- [ ] **[MUST · V1] DEC-007 — Two capture modes.**- - **Online call:** selected application audio plus selected microphone.- - **In-room meeting:** selected microphone only; the microphone is not automatically labeled **You**.--- [ ] **[MUST · V1] DEC-008 — Persistent global state.**- - Recording and processing are app-level activities, not owned by the sidebar tab or main window.--- [ ] **[MUST · V1] DEC-009 — Honest hardware capability.**- - Apple Silicon receives speaker diarization and identity features.- - Intel may record and produce a plain transcript, but must not promise remote-speaker separation until supported.--- [ ] **[MUST · V1] DEC-010 — Honest platform claims.**- - Zoom, Google Meet, and Microsoft Teams are planned optimized targets, not marketed as optimized until their acceptance matrix passes.-------## 4. Goals and non-goals--### 4.1 Goals--- [ ] **[MUST · V1] GOAL-001 — Trustworthy capture.** Preserve usable meeting audio across long sessions, device changes, window closure, and recoverable failures.-- [ ] **[MUST · V1] GOAL-002 — Useful offline transcript.** Produce a timestamped English transcript with truthful speaker attribution and clear fallbacks.-- [ ] **[MUST · V1] GOAL-003 — Clear local identity.** Label clean speech from a confirmed personal online-call microphone as the configured local user or **You**; preserve uncertainty otherwise.-- [ ] **[MUST · V1] GOAL-004 — Correctable speaker model.** Support global rename, individual reassignment, merge, and undo.-- [ ] **[MUST · M3] GOAL-005 — Reusable identities.** Suggest previously confirmed speakers across meetings without silently assigning names.-- [ ] **[MUST · M4] GOAL-006 — Helpful meeting awareness.** Suggest recording at the right time without stealing focus or creating false confidence.-- [ ] **[FUTURE · LIVE] GOAL-007 — Progressive transcript.** Fill the same canvas during a meeting and reconcile it after Stop.--### 4.2 Non-goals for V1--- [ ] **[MUST · V1] NONGOAL-001 — No automatic recording.**-- [ ] **[MUST · V1] NONGOAL-002 — No live transcription requirement.**-- [ ] **[MUST · V1] NONGOAL-003 — No automatic summaries, action items, calendar integration, or meeting bots.**-- [ ] **[MUST · V1] NONGOAL-004 — No claim of legal compliance or consent determination.** Recording laws and workplace policies vary.-- [ ] **[MUST · V1] NONGOAL-005 — No promise of perfect name identification.** Voice and visual matching produce candidates, not facts.-- [ ] **[MUST · V1] NONGOAL-006 — No tab-specific browser audio claim.** ScreenCaptureKit audio filtering is application-level.-- [ ] **[MUST · V1] NONGOAL-007 — No echo-cancellation claim.** Speaker leakage may be detected or reduced later, but is not solved in V1.-- [ ] **[MUST · V1] NONGOAL-008 — No reuse of dictation capture as the meeting recorder.** Meeting capture has different lifecycle, durability, and ownership requirements.-------## 5. High-level milestones--### Milestone delivery policy--Each milestone is implemented on a stacked branch targeting `1.6.8/meeting`; only the integration branch targets `main`. A milestone is not complete when code merely compiles.--- [ ] **[MUST · FOUNDATION] DELIVERY-001** Define the milestone's deterministic tests, real-system proof, performance/resource checks, and regression boundaries before implementation is called complete.-- [ ] **[MUST · FOUNDATION] DELIVERY-002** Assign independent architecture/reliability and UX/accessibility reviewers who did not own the implementation.-- [ ] **[MUST · FOUNDATION] DELIVERY-003** Resolve every blocking finding and record deferred non-blockers against a named later milestone.-- [ ] **[MUST · FOUNDATION] DELIVERY-004** Merge the reviewed milestone PR into `1.6.8/meeting`; open one final integration PR from `1.6.8/meeting` to `main` after the intended milestone set is complete.--### Milestone 0 — Decisions and durable foundations--- [ ] **[MUST · FOUNDATION] M0-EXIT-001** Resolve FOUNDATION and V1 open decisions in Section 22; M3/M4 decisions remain gated by their own milestones.-- [ ] **[MUST · FOUNDATION] M0-EXIT-002** Approve the session, track, speaker, identity, and transcript models.-- [ ] **[MUST · FOUNDATION] M0-EXIT-003** Approve the capture/recovery format and app-wide state machine.-- [ ] **[MUST · FOUNDATION] M0-EXIT-004** Approve privacy, retention, platform-support, and Intel fallback copy.--### Milestone 1 — Working vertical slice (not yet a release)--Goal: prove the complete path before polishing secondary automation.--- [ ] **[MUST · M1] M1-EXIT-001** A new Meeting Transcription tab can manually start an online or in-room recording.-- [ ] **[MUST · M1] M1-EXIT-002** Online mode writes separate system/application and microphone tracks.-- [ ] **[MUST · M1] M1-EXIT-003** Stop ends capture, runs offline English transcription, and displays a timestamped result.-- [ ] **[MUST · M1] M1-EXIT-004** Apple Silicon output includes remote speaker labels and, for a confirmed personal microphone with clean speech, a **You** track; uncertain microphone speech remains unknown.-- [ ] **[MUST · M1] M1-EXIT-005** The menu-bar menu shows **Stop Meeting Recording** first while capture is active.-- [ ] **[MUST · M1] M1-EXIT-006** Window closure and sidebar navigation do not stop the session.--#### Milestone 1 test and review gate--- [ ] **[MUST · M1] M1-TEST-001** Deterministic tests cover legal state transitions, concurrent/repeated Start and Stop, stale-generation callbacks, and exactly one finalization/processing job.-- [ ] **[MUST · M1] M1-TEST-002** A real online-call capture proves separate non-empty application/system and microphone files with timestamps inside one session manifest. Dual-track separation, gap, drift, and skew figures are measured in Appendix A; this item still needs the same proof through the app's own writer and manifest, not only the harness.-- [ ] **[MUST · M1] M1-TEST-003** A real in-room capture proves microphone-only recording does not request Screen/System Audio permission solely for that mode.-- [ ] **[MUST · M1] M1-TEST-004** Stop proves the complete offline English path: finalized audio → transcription/diarization → timestamped canvas result.-- [ ] **[MUST · M1] M1-TEST-005** Apple Silicon fixtures cover remote speaker separation, clean confirmed personal-mic **You**, and ambiguous/leaked microphone speech remaining unknown.-- [ ] **[MUST · M1] M1-TEST-006** UI proof covers menu item order and Stop action, menu-bar recording mark, sidebar navigation, main-window close/reopen, and the four canvas states.-- [ ] **[MUST · M1] M1-REVIEW-001** An independent audio/architecture reviewer approves capture ownership, track separation, timestamp handling, provider serialization, and no dictation first-PCM regression.-- [ ] **[MUST · M1] M1-REVIEW-002** An independent UX/accessibility reviewer approves sidebar placement, state clarity, menu-bar behavior, keyboard/VoiceOver labels, and low-resource rendering.-- [ ] **[MUST · M1] M1-REVIEW-003** Every blocking review finding is fixed or explicitly recorded as a later-milestone item before the M1 stacked PR merges.--### Milestone 2 — Trustworthy offline V1--Goal: make the working slice safe to ship.--- [ ] **[MUST · V1] M2-EXIT-001** Recoverable chunking, atomic manifests, source-health monitoring, and relaunch recovery pass.-- [ ] **[MUST · V1] M2-EXIT-002** Transcript correction, history, export, deletion, and retention behavior pass.-- [ ] **[MUST · V1] M2-EXIT-003** Permissions, menu-bar lifecycle, notifications, accessibility, and multi-display behavior pass.-- [ ] **[MUST · V1] M2-EXIT-004** Zoom, Meet, Teams, generic-source, headphone, speaker, device-change, and one-hour capture matrices pass at their claimed tiers.-- [ ] **[MUST · V1] M2-EXIT-005** Apple Silicon and Intel capabilities are accurately gated and described.--#### Milestone 2 test and review gate--Written 2026-08-10 per DELIVERY-001, before M2 implementation. Numeric budgets referenced here are set in §21.7.--- [x] **[MUST · M2] M2-TEST-001 — Relaunch recovery, deterministic.** Sessions left in `recording`, `stopping`, or `processing` are detected on launch; finalized chunks are salvaged; exactly one recovery offer appears per session; Resume produces a transcript from the salvaged chunks; Delete removes chunks, manifests, and checkpoints. Covered by tests that construct the on-disk states directly (automated: `Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swift`).-- [x] **[MUST · M2] M2-TEST-002 — Real crash proof.** `kill -9` the app during a real recording at three points (first minute, mid-session, during processing). After relaunch, recovery succeeds and audio loss is bounded by the active chunk (≤ one chunk duration). Repeated for force-quit. (Verified live 2026-08-11 on real hardware: `kill -9` during recording — recovered, ~15 s loss, under one chunk; `kill -9` during processing — recovered with the processing-specific message, retry completed; `kill -9` with a checkpoint present — resume confirmed by the log line "Meeting processing resuming from checkpoint after application track", checkpoint auto-deleted on success. Also observed: capture-source loss handled cleanly when the captured app quit mid-recording.)-- [x] **[MUST · M2] M2-TEST-003 — Transcript correction, deterministic.** On a fixture transcript: global rename updates every segment of that speaker without changing segment IDs; single-segment reassignment; merge of two speakers; undo restores the exact prior state after each operation; export reflects corrections. (Automated tests; merge keeps the source speaker as an alias so embeddings survive.)-- [x] **[MUST · M2] M2-TEST-004 — History, export, deletion, retention.** Text and JSON exports exclude embeddings, model fingerprints, and internal confidence data (UX-RESULT-010). Delete Audio preserves the transcript; Delete Meeting removes chunks, manifests, checkpoints, and recovery remnants (PRIV-015). The chosen retention policy demonstrably deletes on schedule. (Automated tests cover the eligibility matrix and the export key allowlist.)-- [ ] **[MUST · M2] M2-TEST-005 — Permission lifecycle.** For microphone and Screen/System Audio independently: first grant, denial, return from System Settings, revocation mid-recording (typed interruption per REL-017 with all finalized audio preserved), regrant, relaunch. Still open: needs manual TCC revocation mid-recording.-- [ ] **[MUST · M2] M2-TEST-006 — Platform matrix at claimed tiers.** Real Zoom desktop, Google Meet in Chrome, and Teams desktop each: join, record ≥10 minutes, switch audio device mid-call (AirPods connect), stop, and produce a transcript with remote speakers separated. Run once with headphones and once with laptop speakers; the speaker run must show leaked speech labeled Unknown, never You. Still open: only a 5-minute Zoom call has been run; needs ≥10 min on Zoom, Meet in Chrome, and Teams, plus one run on laptop speakers.-- [ ] **[MUST · M2] M2-TEST-007 — One-hour capture through the app.** A 60-minute recording through the app's own writer meets the §21.7 budgets: no unexplained gap, drift within budget, all chunk files playable, capture CPU and memory within budget, and both track manifests consistent with the audio on disk. Still open: in progress.-- [ ] **[MUST · M2] M2-TEST-008 — Display and window failure family.** TEST-FAIL-007 (display sleep, screen lock, monitor switch) and TEST-FAIL-008 (capture-window loss) executed through the app runtime, verified by continued buffer delivery — Appendix A results re-confirmed on the release build. Still open: display-sleep half automatable, screen-lock half manual.-- [x] **[MUST · M2] M2-TEST-009 — Dictation coexistence.** Dictation hotkey during meeting recording shows the REL-009 message and does not open a competing session; meeting processing serializes model access (REL-010); with meeting idle, dictation first-PCM latency is unchanged from baseline (REL-011). (Deterministic slice only: arbiter double-acquire and the processing serialization gate, including cancellation, are covered by automated tests. REL-009 hotkey messaging and REL-011 latency remain manual.)-- [ ] **[MUST · M2] M2-TEST-010 — Intel honesty.** On real Intel hardware (TEST-REPO-006): recording and plain transcription work; no speaker labels are produced or promised; the capability difference is visible in the UI before recording starts (UX-SETUP-008). Still open: needs Intel hardware.-- [ ] **[MUST · M2] M2-REVIEW-001** Independent architecture/reliability reviewer approves the recovery design, deletion coverage, permission-lapse handling, and the processing checkpoint/resume path. Still open: independent sign-off owed; multi-model adversarial reviews were run but are not a substitute unless the owner accepts them.-- [ ] **[MUST · M2] M2-REVIEW-002** Independent UX/accessibility reviewer approves the recovery UX, correction flows (keyboard and VoiceOver complete), menu-bar lifecycle states, and capability copy. Still open: independent sign-off owed; multi-model adversarial reviews were run but are not a substitute unless the owner accepts them.-- [ ] **[MUST · M2] M2-REVIEW-003** Every blocking finding fixed or explicitly recorded against a later milestone before the M2 stacked PR merges.--#### Known limits--- Speaker-bleed echo detection covers the diarized path only; microphone whole-chunk-fallback segments are never classified.-- Echo suppression thresholds are calibrated against a single real call and are not yet validated per CAP-023; echo lines are hidden by default but revealable via a "Show probable echo" control.-- Word-timestamp alignment (one ASR pass per chunk, words assigned to turns by timing) engages only on providers that expose token timings and only when nothing can rewrite the text; every other case falls back to per-turn transcription. Up to 25% of words may be unplaceable before the chunk falls back — below that, stragglers are dropped and logged. Two consequences are accepted for now: vocabulary boosting disables alignment outright, and enrolled pronunciation corrections do not apply to the aligned path, because their matcher is gated to clips under 15s and meeting chunks are 60s.-- Retry restarts processing from preserved audio; it resumes only at the application-audio track boundary (checkpoint), not mid-track.-- Audio deletion is best-effort on APFS; no secure-erase claim (PRIV-015).--### Milestone 3 — Speaker identity--**Direction changed 2026-08-12 — voice profiles withdrawn.** See `MEETING_M3_SPEAKER_IDENTITY.md`-for the research and the revised design. Voiceprints are a biometric identifier under Illinois BIPA-(private right of action, statutory damages) and GDPR Article 9; two directly comparable products-(Fireflies, Otter) are in active litigation for profiling non-consenting meeting participants, and-on-device storage is not an established safe harbour. Identity now comes from calendar attendees-plus transcript inference, which is not biometric data.--- [ ] **[MUST · M3] M3-EXIT-001** Sessions match a calendar event where one exists, producing a- closed candidate set of attendee names; no invite falls back cleanly to manual naming.-- [ ] **[MUST · M3] M3-EXIT-002** 1:1 meetings auto-assign the single remaining speaker, and any- proposed name — auto-assigned or inferred — requires **Yes/No** confirmation before it sticks.-- [ ] **[MUST · M3] M3-EXIT-003** Rename, reassign, merge and undo pass (shipped in M2); no name is- ever applied without confirmation, and an attendee list is never assumed to be a speaker list.-- [ ] **[MUST · M3] M3-EXIT-004** Diarization embeddings are no longer persisted to disk;- within-session clustering keeps them in memory only.--### Milestone 4 — Platform intelligence and meeting suggestions--- [ ] **[MUST · M4] M4-EXIT-001** Versioned platform adapters power detection and capability reporting.-- [ ] **[MUST · M4] M4-EXIT-002** Opt-in multi-signal meeting detection passes false-positive and cooldown checks.-- [ ] **[MUST · M4] M4-EXIT-003** Notch and top-center prompts remain nonactivating and accessible.-- [ ] **[OPTIONAL · M4] M4-EXIT-004** In-memory active-speaker visuals improve name candidates without affecting recording reliability.--### Milestone 5 — Live progressive transcription--- [ ] **[FUTURE · LIVE] M5-EXIT-001** Bounded live processing emits provisional segments while durable recording remains independent.-- [ ] **[FUTURE · LIVE] M5-EXIT-002** The canvas remains stable during revisions, selection, and scrolling.-- [ ] **[FUTURE · LIVE] M5-EXIT-003** Stop performs final offline reconciliation without losing user corrections.-------## 6. Information architecture--- [ ] **[MUST · V1] IA-001 — Sidebar placement.** Add **Meeting Transcription** directly below **File Transcription** in the existing **Use** group.-- [ ] **[MUST · V1] IA-002 — Separate product concepts.** File Transcription imports existing media; Meeting Transcription records and owns meeting sessions.-- [ ] **[MUST · FOUNDATION] IA-003 — Shared transcript domain.** Imported files and captured meetings should eventually use the same stable transcript/speaker model even if their orchestration remains separate.-- [ ] **[MUST · V1] IA-004 — One state-driven meeting canvas.** The tab renders setup, recording, processing, result, interrupted, and recovery states from the app-level coordinator.-- [ ] **[MUST · V1] IA-005 — Recent meetings.** Recent sessions appear in the Meeting tab and reopen the same canvas.-- [ ] **[MUST · V1] IA-006 — Stable window behavior.** Changing tabs, minimizing, or closing the main window does not stop recording or processing.-- [ ] **[MUST · V1] IA-007 — Mac command access.** Stop, open meeting, copy, find, export, and settings actions are reachable by keyboard and appropriate menus.-------## 7. User experience and canvas states--### 7.1 Idle/setup--```text-Meeting Transcription Stored on this Mac--[ Online call ] [ In-room meeting ]--Meeting audio Zoom / Google Chrome / Choose application… Ready-Microphone MacBook Microphone Ready-Language English-Speaker separation Automatic on Apple Silicon--Headphones recommended for the cleanest speaker separation.-- [ Start recording ]--Recent meetings-Design sync · Today · 42 min · 4 speakers-```--- [ ] **[MUST · V1] UX-SETUP-001** Show mode, meeting source, microphone, English, permission status, model readiness, and storage readiness.-- [ ] **[MUST · V1] UX-SETUP-002** Show separate meeting-audio and microphone meters before Start when sources can be sampled safely.-- [ ] **[MUST · V1] UX-SETUP-003** Recommend headphones without blocking speaker use.-- [ ] **[MUST · V1] UX-SETUP-004** Default the editable title to platform plus date/time.-- [ ] **[MUST · V1] UX-SETUP-005** Disable Start with a plain explanation when required permission, source, or disk readiness is missing.-- [ ] **[MUST · V1] UX-SETUP-006** Model unavailability must not prevent recording; it must clearly defer processing until models are available.-- [ ] **[OPTIONAL · V1] UX-SETUP-007** Allow an expected in-room speaker count.-- [ ] **[MUST · V1] UX-SETUP-008** Show an Apple Silicon/Intel capability explanation before recording, not only after processing.--### 7.2 Recording--```text-● Recording · 24:18 Zoom · MacBook Microphone--Meeting audio ▂▅▃▆ Healthy-Microphone ▃▂▅▃ Healthy--The transcript will appear after the meeting.-- [ Stop & Transcribe ]-```--- [ ] **[MUST · V1] UX-REC-001** Show elapsed time, meeting source, microphone source, and independent track health.-- [ ] **[MUST · V1] UX-REC-002** Make **Stop & Transcribe** the primary action.-- [ ] **[MUST · V1] UX-REC-003** Stop immediately without confirmation because it preserves the session and begins processing.-- [ ] **[MUST · V1] UX-REC-004** Put **Discard Recording** behind a destructive confirmation and keep it visually secondary.-- [ ] **[MUST · V1] UX-REC-005** Show recording state in the tab, sidebar, and menu bar without relying on color alone.-- [ ] **[MUST · V1] UX-REC-006** Warn immediately when a source disappears and preserve the healthy source.-- [ ] **[OPTIONAL · V1] UX-REC-007** Pause/resume. If deferred, omit it rather than creating a misleading pseudo-pause.--### 7.3 Processing--- [ ] **[MUST · V1] UX-PROC-001** Present explicit stages: **Saving → Identifying speakers → Transcribing → Finalizing**.-- [ ] **[MUST · V1] UX-PROC-002** Remove the recording indicator as soon as capture actually stops; use a visually distinct processing state.-- [ ] **[MUST · V1] UX-PROC-003** Continue processing when the main window closes.-- [ ] **[MUST · V1] UX-PROC-004** Resume safely at a persisted phase/chunk boundary after relaunch.-- [ ] **[MUST · V1] UX-PROC-005** Preserve audio on failure and offer **Retry**, **Reveal Recording**, and **Export Audio**.-- [ ] **[MUST · V1] UX-PROC-006** Preserve a partial transcript when useful and label it incomplete.-- [ ] **[OPTIONAL · V1] UX-PROC-007** Populate finalized transcript sections before the entire offline job completes.--### 7.4 Result--```text-Design sync 42:16-[ Barath (You) ] [ Speaker 1 · Rename ] [ Speaker 2 · Rename ]--00:04 Barath (You)- Let's start with the onboarding changes.--00:11 Speaker 1- I pushed the updated flow yesterday.--[ Copy ] [ Export ] [ Reveal Recording ] [ New Meeting ]-```--- [ ] **[MUST · V1] UX-RESULT-001** Show timestamped, speaker-grouped, selectable transcript text.-- [ ] **[MUST · V1] UX-RESULT-002** Global speaker rename updates every segment referencing that speaker ID.-- [ ] **[MUST · V1] UX-RESULT-003** Support Copy, Find, text export, JSON export, reveal recording, delete audio, and new meeting.-- [ ] **[MUST · V1] UX-RESULT-004** Deleting audio may preserve the transcript.-- [ ] **[MUST · V1] UX-RESULT-005** Allow individual segment reassignment.-- [ ] **[MUST · V1] UX-RESULT-006** Allow merging mistaken duplicate speakers.-- [ ] **[OPTIONAL · V1] UX-RESULT-007** Split one wrongly combined speaker into two.-- [ ] **[MUST · V1] UX-RESULT-008** Support undo for speaker rename, reassignment, merge, and identity confirmation.-- [ ] **[MUST · V1] UX-RESULT-009** **Export Audio…** offers authoritative separate tracks and an optional mixed convenience file generated on demand; it never silently replaces the originals.-- [ ] **[MUST · V1] UX-RESULT-010** Text/JSON exports omit embeddings, model fingerprints, internal confidence vectors, and private profile metadata.-------## 8. Session lifecycle--```mermaid-stateDiagram-v2- [*] --> Idle- Idle --> Preparing: Start or Set up- Preparing --> Recording: Permissions and sources ready- Preparing --> Idle: Cancel or failure- Recording --> Stopping: Stop and transcribe- Recording --> RecordingDegraded: One source becomes unhealthy- RecordingDegraded --> Recording: Source recovered on a new chunk boundary- RecordingDegraded --> Stopping: Stop and transcribe available tracks- Recording --> Interrupted: Capture-wide stoppage- Stopping --> Processing: Durable chunks finalized- Interrupted --> Processing: Recover available audio- Interrupted --> Recording: Safe resume when supported- Processing --> Completed- Processing --> ProcessingFailed- ProcessingFailed --> Processing: Retry- Completed --> Idle: New meeting-```--- [ ] **[MUST · FOUNDATION] STATE-001** Implement an app-wide state machine: `idle`, `preparing`, `recording`, `recordingDegraded`, `stopping`, `processing`, `completed`, `interrupted`, `failed`.-- [ ] **[MUST · FOUNDATION] STATE-002** Persist every durable state transition atomically.-- [ ] **[MUST · V1] STATE-003** Treat source loss, app exit, permission revocation, disk exhaustion, sleep/wake, and clock discontinuity as typed events rather than one generic error.-- [ ] **[MUST · V1] STATE-004** Keep capture and processing failure domains separate.-- [ ] **[MUST · V1] STATE-005** Never delete the source recording automatically because transcription failed.-- [ ] **[MUST · V1] STATE-006** Define termination behavior: closing the window continues; quitting presents a clear choice and never implies background survival after process exit. **Stop & Quit** persists `processingPending` and says transcription resumes next launch.-- [ ] **[MUST · V1] STATE-007** Allow only one active meeting capture session at a time.-- [ ] **[MUST · V1] STATE-008** If an older meeting is processing when a new recording starts, checkpoint and queue/pause processing so durable capture receives priority; resume processing after recording stops.-------## 9. Target architecture--```mermaid-flowchart TD- UI[Meeting Tab / Menu Bar / Prompt] --> COORD[MeetingSessionCoordinator]- COORD --> ARB[Audio Activity Arbiter]- COORD --> CAP[MeetingCaptureEngine]- CAP --> SYS[Application Audio Track]- CAP --> MIC[Microphone Track]- SYS --> STORE[Rolling Chunks + Atomic Manifest]- MIC --> STORE- STORE --> PIPE[Offline Meeting Pipeline]- PIPE --> DIAR[Remote Diarization]- PIPE --> ASR[English ASR]- DIAR --> ID[Speaker Identity Resolver]- ASR --> TIMELINE[Timestamped Transcript Timeline]- ID --> TIMELINE- TIMELINE --> SESSION[MeetingSessionStore]- SESSION --> UI-```--### 9.1 Required components--- [ ] **[MUST · FOUNDATION] ARCH-001 — `MeetingSessionCoordinator`.** App-wide `@MainActor` owner exposed through `AppServices`; coordinates UI state without owning real-time audio callbacks.-- [ ] **[MUST · FOUNDATION] ARCH-002 — `MeetingCaptureEngine`.** Actor/queue-backed ScreenCaptureKit capture owner with bounded callback work.-- [ ] **[MUST · FOUNDATION] ARCH-003 — `MeetingSessionStore`.** Disk-backed, versioned meeting/session index; do not extend the file-transcription UserDefaults store.-- [ ] **[MUST · FOUNDATION] ARCH-004 — `MeetingProcessingPipeline`.** Resumable offline orchestration for track preparation, diarization, ASR, timeline merge, and finalization.-- [ ] **[MUST · FOUNDATION] ARCH-005 — `MeetingPlatformRegistry`.** Local registry of platform detection/capture/name capabilities and caveats.-- [ ] **[MUST · M3] ARCH-006 — `SpeakerProfileStore`.** Versioned local person/profile database independent of meeting deletion.-- [ ] **[MUST · M4] ARCH-007 — `MeetingDetectionService`.** Opt-in sustained multi-signal detector.-- [ ] **[MUST · M4] ARCH-008 — `MeetingSuggestionPresenter`.** Separate from the latency-sensitive dictation notch/bottom-overlay state machine.-- [ ] **[MUST · FOUNDATION] ARCH-009 — Audio activity arbiter.** Explicitly owns conflicts among dictation, command/edit capture, dictionary recording, and meeting capture.--### 9.2 Current code integration--- [ ] **[MUST · FOUNDATION] CODE-001** Add the meeting coordinator lazily to `AppServices`; extend termination shutdown to flush capture without relying on graceful exit for recovery.-- [ ] **[MUST · V1] CODE-002** Add a distinct sidebar destination and menu-bar navigation destination for Meeting Transcription.-- [ ] **[MUST · FOUNDATION] CODE-003** Rename the current file-oriented `MeetingTranscriptionView`/service concept to File Transcription before adding the real meeting view, avoiding two meanings for “meeting transcription.”-- [ ] **[MUST · FOUNDATION] CODE-004** Replace rename-unstable segment IDs. The current file segment ID derives from speaker text and timestamp.-- [ ] **[MUST · FOUNDATION] CODE-005** Return rich diarization output instead of discarding FluidAudio cluster embeddings and quality metadata.-- [ ] **[MUST · V1] CODE-006** Keep meeting sessions out of `FileTranscriptionHistoryStore`; it uses UserDefaults, caps entries, and lacks recovery/audio state.-- [ ] **[MUST · V1] CODE-007** Add an appropriate Screen & System Audio usage description and explicit permission-state handling.-- [ ] **[MUST · V1] CODE-008** Extend the existing `MenuBarManager` rather than creating a second status item.-- [ ] **[MUST · V1] CODE-009** Do not call `ASRService.start()` for meeting recording; reuse only safe file/provider APIs during offline processing.-- [ ] **[MUST · V1] CODE-010** Ensure existing view disappearance and ASR shutdown paths cannot stop the meeting coordinator.-------## 10. Meeting session and data model--### 10.1 Meeting session--- [ ] **[MUST · FOUNDATION] MODEL-001** Define a versioned `MeetingSession` containing:- - schema version and session UUID;- - title and `languageCode`;- - online/in-room capture mode;- - platform profile and captured application identity;- - selected microphone identity;- - started/ended timestamps and monotonic timebase metadata;- - session state and typed interruption/failure history;- - audio track manifests;- - session speakers and transcript segment IDs;- - retention/deletion state;- - processing checkpoints.--### 10.2 Audio tracks and chunks--- [ ] **[MUST · FOUNDATION] MODEL-002** Define `MeetingAudioTrack` with stable ID, kind (`applicationAudio` or `microphone`), source/device metadata, format, shared timebase mapping, health, and ordered chunks.-- [ ] **[MUST · FOUNDATION] MODEL-003** Define `MeetingAudioChunk` with stable ID, sequence, file URL, presentation start/end, discontinuity metadata, checksum, and finalization state.-- [ ] **[MUST · V1] MODEL-004** Make every finalized chunk independently recoverable.--### 10.3 Speakers and transcript segments--- [ ] **[MUST · FOUNDATION] MODEL-005** Define stable `SessionSpeakerID` separately from editable display name and source diarization cluster.-- [ ] **[MUST · FOUNDATION] MODEL-006** Define transcript segments with stable UUID, start/end, source track, speaker ID, text, revision, `provisional/final`, overlap state, and completeness state.-- [ ] **[MUST · FOUNDATION] MODEL-007** Preserve simultaneous speech instead of forcing overlapping sources into a false single-speaker order.-- [ ] **[MUST · FOUNDATION] MODEL-008** Keep identity candidates and confirmations separate from the final display name.--### 10.4 Person profiles--- [ ] **[MUST · M3] MODEL-009** Define stable `PersonID`, editable display name, multiple confirmed embeddings/prototypes, source quality, microphone/room context, model fingerprint, created/updated dates, and consent state.-- [ ] **[MUST · M3] MODEL-010** Invalidate or migrate embeddings when the speaker-embedding model/version changes.-------## 11. Audio capture design--### 11.1 Online call mode--- [ ] **[MUST · V1] CAP-001** Capture selected meeting-application audio through ScreenCaptureKit `.audio` output.-- [ ] **[MUST · V1] CAP-002** Capture the selected microphone as a separate `.microphone` output on the macOS 15 baseline.-- [ ] **[MUST · V1] CAP-003** Resolve the microphone using the identifier type ScreenCaptureKit expects; do not assume the existing Core Audio UID is directly interchangeable with `AVCaptureDevice.uniqueID`.-- [ ] **[MUST · V1] CAP-004** Use media presentation timestamps as the synchronization source, not callback arrival time or wall-clock `Date`.-- [ ] **[MUST · V1] CAP-005** Exclude FluidVoice audio where supported so cues/notifications are not written into meeting audio.-- [ ] **[MUST · V1] CAP-006** Preserve remote/system and microphone tracks separately through processing and audio export.-- [ ] **[MUST · FOUNDATION] CAP-024** Decide whether V1 source selection uses Apple's `SCContentSharingPicker` or a custom application picker, and document the privacy, control, and maintenance reason for that choice.-- [ ] **[MUST · V1] CAP-025** Consume `.audio` and `.microphone` sample buffers into separate writers; do not use a convenience recording output that mixes away track identity on the macOS 15 baseline.--### 11.2 In-room mode--- [ ] **[MUST · V1] CAP-007** Record the selected microphone through a mic-only Core Audio/AVFoundation backend sharing the durable writer, without requiring Screen/System Audio permission solely for in-room mode.-- [ ] **[MUST · V1] CAP-008** Diarize all detected room speakers, including the local user.-- [ ] **[MUST · V1] CAP-009** Never label the whole in-room microphone as **You**.--### 11.3 Durability and resource behavior--- [ ] **[MUST · V1] CAP-010** Write rolling finalized chunks plus an atomically replaced manifest under Application Support.-- [ ] **[MUST · V1] CAP-011** Bound memory regardless of meeting duration; sample buffers must not accumulate in RAM.-- [ ] **[MUST · V1] CAP-012** Keep capture callbacks minimal and file writes on dedicated serial queues.-- [ ] **[MUST · V1] CAP-013** Use compressed archival tracks or another measured format that avoids multi-gigabyte-per-hour PCM while preserving ASR quality.-- [ ] **[MUST · V1] CAP-014** Normalize/downsample for ASR during offline processing, not on the critical capture callback.-- [ ] **[MUST · V1] CAP-015** Preflight available space and continue monitoring storage while recording.-- [ ] **[MUST · V1] CAP-016** Record explicit chunk boundaries for device changes, sleep/wake, source-app reconnection, and format changes.-- [ ] **[MUST · V1] CAP-017** Losing one source must not silently terminate the healthy source.-- [ ] **[MUST · V1] CAP-018** A crash may lose the unfinalized active chunk, but must preserve all finalized chunks.--### 11.4 Headphones, Bluetooth, and leakage--- [ ] **[MUST · V1] CAP-019** Recommend headphones for online meetings because system audio remains digital and remote speech is less likely to leak into the microphone.-- [ ] **[MUST · V1] CAP-020** Allow AirPods/Bluetooth microphones but warn that using a Bluetooth headset microphone can switch macOS to a lower-quality two-way mode.-- [ ] **[MUST · V1] CAP-021** Recommend built-in/USB microphone plus Bluetooth headphones output when appropriate, without overriding user choice.-- [ ] **[MUST · V1] CAP-022** Detect/report probable duplicate remote speech across the microphone and system tracks; do not claim automatic echo cancellation.-- [ ] **[OPTIONAL · V1] CAP-023** Add timestamp/acoustic duplicate suppression only after evaluation proves it does not remove real overlapping speech.-- [ ] **[MUST · V1] CAP-026** Ask whether the selected online-call microphone is personal or shared. Only a confirmed personal mic may support the default **You** attribution.--### 11.5 Capture API and filter scope--Decided 2026-08-10 from measured evidence on macOS 26.5.1; see Appendix A.--- [ ] **[MUST · FOUNDATION] CAP-027 — ScreenCaptureKit is the V1 capture API.** A one-hour dual-track soak recorded zero gaps, zero backwards timestamps, zero format changes, ~14 ppm clock drift, and a constant 87.6 ms inter-track skew. FB13847291 (`EXC_BAD_ACCESS` on long audio-only capture) did not reproduce. Reliability does not justify migrating to Core Audio process taps.-- [ ] **[MUST · FOUNDATION] CAP-028 — Scope the content filter to a window, never a display.** `SCContentFilter(display:...)` terminates with `SCStreamErrorDomain -3815` on any display power transition, including a one-second blackout, and never recovers. `SCContentFilter(desktopIndependentWindow:)` survives the same event with audio delivery uninterrupted, and still scopes audio to the owning application.-- [ ] **[MUST · V1] CAP-029 — Pin the capture window at Start.** Resolve the selected meeting application's main window once when recording begins and hold it for the session. Never follow keyboard focus; the user will switch apps mid-meeting.-- [ ] **[MUST · V1] CAP-030 — Filter the window candidate list.** `SCShareableContent.windows` includes WindowServer backstops, Dock wallpaper surfaces, menubar strips, and untitled entries. Require an owning application, a non-empty title, a minimum size, and `isOnScreen`. Selecting an unowned system window aborts the process.-- [ ] **[MUST · V1] CAP-031 — Hold a display-sleep power assertion while recording.** Take `kIOPMAssertionTypePreventUserIdleDisplaySleep` for the capture duration and release it on stop and on termination. Do not rely on the implicit assertion Core Audio takes; the system revokes it mid-session.-- [ ] **[MUST · V1] CAP-032 — Treat window loss as a first-class capture risk.** Window scoping trades a display dependency for a window dependency. A browser-hosted meeting binds to the browser window, which the user may close or recreate mid-call. This is why REL-015 is mandatory.-------## 12. Offline English transcription pipeline--- [ ] **[MUST · V1] PIPE-001** Process the dual-track session manifest rather than pretending a captured meeting is one imported file.-- [ ] **[MUST · V1] PIPE-002** Remote/application track: diarize, preserve cluster IDs/embeddings/quality, and transcribe turn-bounded text — either per turn, or by assigning word timings from a single chunk pass back to the turns.-- [ ] **[MUST · V1] PIPE-003** Microphone track: detect speech turns and correlate them against remote/system speech. Label clean personal-mic speech as **You**; mark probable leakage, shared-mic speech, or ambiguous overlap as **Microphone / Unknown** rather than misattributing it.-- [ ] **[MUST · V1] PIPE-004** Merge tracks chronologically from their shared timestamp mapping while preserving overlaps.-- [ ] **[MUST · V1] PIPE-005** Preserve raw meeting speech; do not automatically apply dictation filler removal, spoken-punctuation rewriting, or AI enhancement.-- [ ] **[MUST · V1] PIPE-006** Reuse the selected safe file-transcription provider/model path to avoid duplicate model memory, with explicit serialization against dictation.-- [ ] **[MUST · V1] PIPE-007** Checkpoint processing at track/chunk/phase boundaries so relaunch can resume.-- [ ] **[MUST · V1] PIPE-008** Batch turns carefully; avoid one expensive ASR startup per tiny diarization segment.-- [ ] **[MUST · V1] PIPE-009** Treat no-speech, incomplete-track, diarization failure, and ASR failure as distinct outcomes.-- [ ] **[MUST · V1] PIPE-010** Fall back to a complete unlabeled transcript when speaker attribution cannot be completed safely.-- [ ] **[MUST · V1] PIPE-011** On Intel, produce plain remote transcript plus track-origin distinction where possible; do not invent remote speaker labels.-- [ ] **[MUST · FOUNDATION] PIPE-012** Every ASR request reads `languageCode` from its session; adding a future transcription-language picker requires no session-schema migration. Product UI localization remains separate.-- [ ] **[MUST · V1] PIPE-013** Stitch remote speaker clusters across writer rotation, sleep/reconnect, device/format boundaries, and processing chunks using session-wide embeddings so the same person retains one speaker ID.-- [ ] **[MUST · V1] PIPE-014** Pin ASR provider/model/version, diarization model fingerprint, normalization settings, and pipeline version to each processing attempt/checkpoint.-- [ ] **[MUST · V1] PIPE-015** Dictation may preempt/pause meeting processing at a safe checkpoint; prove no concurrent provider mutation, model unload, or partial-result corruption.-------## 13. Speaker identity and correction--### 13.1 V1 session identity--- [ ] **[MUST · V1] ID-001** Clean speech from a confirmed personal online-call microphone is labeled the configured local name plus **(You)**, or simply **You**; shared/ambiguous/leaked speech is not.-- [ ] **[MUST · V1] ID-002** Remote speakers begin as stable generic labels ordered by first appearance.-- [ ] **[MUST · V1] ID-003** Renaming a speaker changes display metadata, not segment IDs or cluster identity.-- [ ] **[MUST · V1] ID-004** Global rename, segment reassignment, speaker merge, and undo remain available without voice profiles.--### 13.2 Compact candidate confirmation--- [ ] **[MUST · M3] ID-005** Show one unresolved confirmation per unique session speaker, not beside every passage.-- [ ] **[MUST · M3] ID-006** **Yes** renames all linked segments and records an explicit confirmation event.-- [ ] **[MUST · M3] ID-007** **No** rejects only that candidate for that session and does not permanently poison either profile.-- [ ] **[MUST · M3] ID-008** No answer leaves the generic speaker label intact.-- [ ] **[MUST · M3] ID-009** Use wording such as “Was this Erik?” rather than uncalibrated percentages.--### 13.3 Cross-meeting voice profiles--- [ ] **[MUST · M3] ID-010** Persistent profiles are explicit opt-in before the first embedding is stored.-- [ ] **[MUST · M3] ID-011** Learn only from user-confirmed, sufficiently long, clean, non-overlapping speech.-- [ ] **[MUST · M3] ID-012** Store several representative samples/prototypes per person across microphones and rooms.-- [ ] **[MUST · M3] ID-013** Suggest a match only when it clears an evaluated absolute threshold and a margin over the second-best person.-- [ ] **[MUST · M3] ID-014** Preserve an unknown-person outcome; never force the nearest profile.-- [ ] **[MUST · M3] ID-015** Require confirmation again in each meeting until reliability evidence supports a different policy.-- [ ] **[MUST · M3] ID-016** Support same-name people through distinct stable person IDs.-- [ ] **[MUST · M3] ID-017** Provide rename, unlink, forget-one-person, and delete-all-profile controls.-- [ ] **[OPTIONAL · M3] ID-018** Remember aliases by recurring meeting series after a separate product decision.--### 13.4 Visual active-speaker assistance--- [ ] **[OPTIONAL · M4] ID-019** Use platform UI as a candidate-name signal, never as the basis of diarization.-- [ ] **[CONDITIONAL MUST · M4] ID-020** Prefer accessibility-exposed participant labels before OCR where reliable.-- [ ] **[CONDITIONAL MUST · M4] ID-021** Sample low-frequency frames only around remote speech activity and crop to likely participant regions.-- [ ] **[CONDITIONAL MUST · M4] ID-022** Keep frames in memory only; persist only candidate name, time interval, confidence, and platform-rule version.-- [ ] **[CONDITIONAL MUST · M4] ID-023** Require agreement across multiple frames and align the visual interval with the diarized cluster.-- [ ] **[CONDITIONAL MUST · M4] ID-024** Suppress suggestions during overlap, screen sharing, minimized/hidden UI, ambiguous highlights, or voice/visual disagreement.-- [ ] **[CONDITIONAL MUST · M4] ID-025** Fall back silently to voice/manual identity when visual extraction is unavailable.-- [ ] **[CONDITIONAL MUST · M4] ID-026** Obtain separate opt-in before examining the selected meeting window; restrict analysis to that window and likely participant/name regions, and skip shared-screen content.-------## 14. Supported meeting platforms--### 14.1 Capability model--- [ ] **[MUST · V1] PLATFORM-001** Track support separately for **Recording**, **Meeting Detection**, **Visual Name Suggestions**, and **Voice Recognition**.-- [ ] **[MUST · V1] PLATFORM-002** Define tiers:- - **Optimized:** claimed capabilities validated against the release matrix.- - **Compatible:** reliable manual recording/transcription with limited automation.- - **Beta:** expected to work but not sufficiently validated.- - **Unsupported:** known capture failure.-- [ ] **[MUST · V1] PLATFORM-003** A platform UI change may downgrade name suggestions without disabling recording.-- [ ] **[MUST · V1] PLATFORM-004** Expose exact tested native app/browser variants rather than one broad platform claim.--### 14.2 Planned initial matrix--| Target | Initial planned claim | Capture | Detection | Name suggestions | Required caveat |-|---|---|---:|---:|---:|---|-| Zoom Workplace desktop | Planned target | Planned—validation required | Planned | Planned | Validate helper/subprocess capture and UI variants |-| Google Meet in Chrome | Planned target | Planned—validation required | Planned | Planned | Same-browser audio may be included |-| Microsoft Teams desktop | Planned target | Planned—validation required | Planned | Planned | Validate current Teams helper/subprocess behavior |-| Google Meet in Safari/Edge/Firefox | Planned compatible target | Planned—validation required | Best effort | Planned voice/manual | Treat each browser as its own variant |-| Webex desktop | Planned compatible target | Planned—validation required | Best effort | Planned voice/manual | UI adapter must pass separately |-| Slack desktop Huddles | Planned compatible target | Planned—validation required | Best effort | Planned voice/manual | Browser Huddles are separate variants |-| FaceTime | Planned beta target | Planned—validation required | Best effort | Planned voice/manual | Validate capture/protected-content behavior first |-| Other app/browser | Manual fallback target | Unknown until selected and checked | No promise | Planned voice/manual | Never imply compatibility before source health is proven |--- [ ] **[MUST · V1] PLATFORM-005** Provide **Choose application…** for unrecognized meeting software.-- [ ] **[MUST · V1] PLATFORM-006** Warn that ScreenCaptureKit exposes no browser-tab audio selector, so unrelated audio from the same browser may be included; do not claim identical behavior across all browsers without validation.-- [ ] **[MUST · V1] PLATFORM-007** Validate Zoom/Teams helper processes; bundle-name matching alone must not earn an optimized claim.-- [ ] **[MUST · V1] PLATFORM-008** Keep platform capture configuration separate from ASR/diarization configuration unless measurements prove an app-specific transcription benefit.-- [ ] **[MUST · M4] PLATFORM-009** Version platform profiles by native/browser variant and known UI generation.-- [ ] **[OPTIONAL · M4] PLATFORM-010** Store last-validated version/date in diagnostics without reporting meeting contents.-- [ ] **[MUST · V1] PLATFORM-011** Show **Works best with** only for validated recording targets, followed by detailed per-capability status. Never present a planned capability as currently supported.-------## 15. Meeting detection and suggestion prompt--- [ ] **[OPTIONAL · V1] DETECT-001** Ship detection only after manual capture is trustworthy; default milestone is M4.-- [ ] **[MUST · M4] DETECT-002** Make detection opt-in globally and suppressible per application.-- [ ] **[MUST · M4] DETECT-003** Require sustained multi-signal evidence, never a window title alone.- - Candidate signals: known app/window, process audio input/output activity, active duration, and platform-specific context.-- [ ] **[MUST · M4] DETECT-004** Debounce startup and show at most one prompt per meeting lifecycle.-- [ ] **[MUST · M4] DETECT-005** **Not now** suppresses until that meeting ends.-- [ ] **[MUST · M4] DETECT-006** Offer **Don't suggest for this app**.-- [ ] **[MUST · M4] DETECT-007** Use **Set up** instead of **Record** when permission or source configuration is incomplete.-- [ ] **[MUST · M4] DETECT-008** Merely presenting the suggestion never activates FluidVoice or steals keyboard focus. An explicit **Set up** action may activate the Meeting tab.-- [ ] **[MUST · M4] DETECT-009** Notch Macs use a compact notch expansion.-- [ ] **[MUST · M4] DETECT-010** Non-notch Macs use a top-center HUD on the meeting window's display, not literal screen center or pointer location.-- [ ] **[MUST · M4] DETECT-011** Prompt timeout pauses for hover, keyboard focus, and VoiceOver interaction.-- [ ] **[MUST · M4] DETECT-012** Meeting prompts yield to active dictation/command overlays and never delay dictation's first PCM.-- [ ] **[OPTIONAL · M4] DETECT-013** Leave a subtle Meeting sidebar badge after timeout.-- [ ] **[MUST · M4] DETECT-014** Use concise platform-aware copy:- - Normal: **“Looks like you're in a Zoom meeting. Record locally?”** with **Record** and **Not now**.- - First use: the same context with **Set up** and **Not now**.- - Include the detected app icon without implying FluidVoice has already begun capture.-- [ ] **[MUST · M4] DETECT-015** Provide a keyboard-complete alternative through the FluidVoice menu-bar menu or Meeting tab. The nonactivating HUD may expose pointer and VoiceOver actions without pretending it accepts normal keyboard focus.-- [ ] **[MUST · M4] DETECT-016 — Primary signal is bidirectional per-process audio, and it costs no permission.** Poll `kAudioHardwarePropertyProcessObjectList` for `kAudioProcessPropertyIsRunningInput` and `IsRunningOutput`. A known meeting application holding both concurrently for 10–15 s is a call. Input alone is dictation; output alone is media. Verified permission-free on macOS 26.5.1. Poll rather than listen: the change listeners for these properties are reported not to fire.-- [ ] **[MUST · M4] DETECT-017 — Exclude `com.apple.replayd` and FluidVoice's own bundles from detection.** ScreenCaptureKit microphone capture is attributed to `replayd`, not to the requesting process, so an unguarded detector fires on FluidVoice's own meeting recording.-- [ ] **[MUST · M4] DETECT-018 — Gate the audio signal on process identity.** FluidVoice ships dictation, so an audio-activity signal without an application allowlist will fire on the user's own voice notes. Bidirectionality already excludes that case; do not loosen it without a replacement guard.-- [ ] **[MUST · M4] DETECT-019 — Do not require a calendar match.** Calendar-only detection structurally misses Slack huddles, unscheduled calls, and meetings that start late. A current event with a parsed conferencing URL raises confidence and supplies a default title, but its absence must never veto detection.-- [ ] **[OPTIONAL · M4] DETECT-020 — Handle the muted-mic case as lower confidence.** Participants who join muted produce no input signal. Fall back to a known meeting application with output audio plus a matching window title, camera in use, or an active calendar event, and label the match as weaker rather than folding it into the primary path.-- [ ] **[MUST · M4] DETECT-021 — Prefer Accessibility over Screen Recording for window titles.** `CGWindowListCopyWindowInfo` omits `kCGWindowName` without the Screen Recording grant. `AXUIElement` returns the same information for a cheaper permission.-------## 16. Menu-bar lifecycle and notifications--### 16.1 Recording--```text-● Stop Meeting Recording- Recording Zoom · 24:18- Open Meeting Transcription-────────────────────────────- Existing FluidVoice menu…-```--- [ ] **[MUST · V1] MENU-001** Extend the existing FluidVoice status item; do not create a second menu-bar icon.-- [ ] **[MUST · V1] MENU-002** Show the FV icon with a recording mark that does not rely on red alone.-- [ ] **[MUST · V1] MENU-003** Make **Stop Meeting Recording** the first enabled menu item while capture is active.-- [ ] **[MUST · V1] MENU-004** Show platform/source, elapsed time, and **Open Meeting Transcription** next.-- [ ] **[MUST · V1] MENU-005** Compute elapsed time when the menu opens; do not run a permanent one-second UI timer.-- [ ] **[MUST · V1] MENU-006** Stop ends recording immediately and begins processing.--### 16.2 Processing, interruption, and completion--- [ ] **[MUST · V1] MENU-007** Replace the red recording state immediately after audio capture stops.-- [ ] **[MUST · V1] MENU-008** Use a distinct amber/processing mark and first row **Transcribing meeting…**.-- [ ] **[MUST · V1] MENU-009** Interrupted capture changes the first action to **Recording interrupted — Open Meeting**.-- [ ] **[MUST · V1] MENU-010** Completion restores the normal icon and posts **Meeting transcript ready**.-- [ ] **[MUST · V1] MENU-011** Temporarily expose **Open Latest Meeting Transcript** first after completion.-- [ ] **[MUST · V1] MENU-012** Provide meaningful accessibility values for Recording, Processing, Interrupted, and Ready.-- [ ] **[MUST · V1] MENU-013** Warn on Quit while recording with two clear choices: cancel Quit and keep recording, or **Stop & Quit — Transcribe Next Launch**, which persists `processingPending` for relaunch.-- [ ] **[OPTIONAL · V1] MENU-014** Add a global Stop Meeting Recording shortcut after conflict review.-------## 17. Permissions, consent, privacy, and retention--- [ ] **[MUST · V1] PRIV-001** Track microphone and Screen/System Audio permission independently: unknown, granted, denied, restricted, and action required.-- [ ] **[MUST · V1] PRIV-002** Explain why each permission is needed before presenting the system flow.-- [ ] **[MUST · V1] PRIV-003** Keep a visible FluidVoice recording indicator for the complete capture duration; it supplements rather than replaces macOS privacy indicators.-- [ ] **[MUST · V1] PRIV-004** Offer concise pre-start copy reminding the user to ensure participants know the meeting is being recorded.-- [ ] **[MUST · V1] PRIV-005** Do not claim FluidVoice determines recording legality.-- [ ] **[MUST · V1] PRIV-006** Exclude audio, transcript text, participant names, meeting titles, and embeddings from analytics/logs/uploads.-- [ ] **[MUST · V1] PRIV-007** Define retention before release: delete after transcription, 7 days, 30 days, or never.-- [ ] **[MUST · V1] PRIV-008** Distinguish **Delete Audio**, **Delete Meeting**, **Forget Person**, and **Delete All Meeting Data**.-- [ ] **[MUST · V1] PRIV-009** Keep transcript usable after audio-only deletion.-- [ ] **[MUST · V1] PRIV-010** Store sensitive files with owner-only permissions and accurate local-storage copy.-- [ ] **[MUST · V1] PRIV-011** Do not claim app-managed encryption unless authenticated encryption and Keychain-backed key management are actually implemented.-- [ ] **[OPTIONAL · SECURITY] PRIV-012** Add app-managed at-rest encryption after defining streaming/recovery behavior and migration.-- [ ] **[MUST · M3] PRIV-013** Voice-profile opt-in and deletion are independent of meeting retention.-- [ ] **[MUST · V1] PRIV-014** Warn that exported text, JSON, or audio leaves FluidVoice's storage controls and follows the destination's permissions/sync behavior.-- [ ] **[MUST · V1] PRIV-015** Deletion covers active/partial chunks, finalized tracks, manifests, checkpoints, visual candidates, and recovery remnants in the selected scope; do not promise secure erase on APFS.-- [ ] **[MUST · M3] PRIV-016** Complete a separate biometric/privacy review before remembered third-party voice profiles ship; require explicit opt-in, local-only storage, no sync, and dedicated disclosure.-- [ ] **[MUST · M3] PRIV-017** Protect persisted voice profiles with authenticated encryption using a Keychain-held key, or explicitly re-review and approve the weaker storage risk before M3.-------## 18. Reliability, recovery, and conflicts--- [ ] **[MUST · V1] REL-001** On launch, scan sessions left in recording/stopping/processing states.-- [ ] **[MUST · V1] REL-002** Salvage finalized chunks, mark unexpected capture termination as interrupted, and never auto-delete evidence.-- [ ] **[MUST · V1] REL-003** Offer **Resume Processing**, **Reveal/Export Audio**, and **Delete** for recoverable sessions.-- [ ] **[MUST · V1] REL-004** Handle force quit, power loss, sleep/wake, selected-app exit/relaunch, permission revocation, and disk exhaustion. **Display power transitions are a separate and far more frequent event than system sleep** and must be handled explicitly: idle display sleep, lid close, screen lock, monitor input switch, display unplug, and resolution change, each occurring mid-capture.-- [ ] **[MUST · V1] REL-005** Handle microphone unplug/reconnect, Bluetooth route changes, and sample-rate changes without corrupting prior chunks.-- [ ] **[MUST · V1] REL-006** Handle waiting room → meeting, breakout room/window, browser refresh, and source subprocess changes without silent loss.-- [ ] **[MUST · V1] REL-007** Surface independent last-sample time, level, discontinuity, and failure for each track.-- [ ] **[MUST · V1] REL-008** Meeting recording receives an explicit audio-activity lease.-- [ ] **[MUST · V1] REL-009** V1 dictation hotkeys during meeting recording show a clear “Stop meeting recording first” message rather than opening a competing microphone session.-- [ ] **[MUST · V1] REL-010** Meeting processing serializes safe access to shared ASR models and never corrupts dictation state.-- [ ] **[MUST · V1] REL-011** No meeting prompt, menu update, or indicator adds latency to normal dictation capture when meeting recording is inactive.-- [ ] **[MUST · V1] REL-012** Start, Stop, menu Stop, Quit, and late ScreenCaptureKit/writer callbacks are idempotent and generation-checked; repeated Stop enters disabled **Stopping…** and creates exactly one finalization/processing job.-- [ ] **[MUST · V1] REL-013** Critical-low-disk behavior safely stops and finalizes capture before exhausting the reserve, then notifies the user without deleting audio.-- [ ] **[MUST · V1] REL-014** Processing settings/provider changes cannot mutate an in-flight attempt; a deliberate retry creates a new pinned attempt while preserving prior checkpoints/results.-- [ ] **[MUST · V1] REL-015 — Capture interruption is recoverable, not terminal.** `SCStreamDelegate.stream(_:didStopWithError:)` currently ends the session. It must instead rebuild the stream and resume on a new chunk boundary, with bounded retries and honest degraded state. A transient loss costs a chunk boundary, never a meeting.-- [ ] **[MUST · V1] REL-016 — Do not trust the stop callback alone.** Run a buffer-silence watchdog per track and restart proactively on stall. The delegate callback is not guaranteed to fire, and is reported to arrive with an invalid error object in some teardown races.-- [ ] **[MUST · V1] REL-017 — Screen Recording consent can lapse mid-recording.** macOS re-confirms the grant on a roughly monthly cadence, so revocation during an active capture will eventually happen. Treat it as a typed interruption that preserves all finalized audio and explains what to do, not as a generic failure.-------## 19. Performance, accessibility, and macOS behavior--### 19.1 Performance--- [ ] **[MUST · V1] PERF-001** Capture CPU, memory, and disk queues remain bounded for a one-hour session.-- [ ] **[MUST · V1] PERF-002** Offline models remain unloaded during capture unless already needed elsewhere.-- [ ] **[MUST · V1] PERF-003** Visual-name assistance, when enabled, runs at a bounded low rate and never competes with audio writes.-- [ ] **[MUST · V1] PERF-004** Transcript rendering remains responsive with hours of segments; do not render an unbounded monolithic SwiftUI tree.-- [ ] **[OPTIONAL · M4] PERF-005** Reduce or pause visual sampling under thermal or Low Power Mode pressure.--### 19.2 Accessibility and Mac conventions--- [ ] **[MUST · V1] A11Y-001** Every primary action is keyboard reachable.-- [ ] **[MUST · V1] A11Y-002** Speaker identity uses explicit **Yes/No** text buttons, not icon-only controls.-- [ ] **[MUST · V1] A11Y-003** VoiceOver has a logical focus order and concise recording/processing/error announcements.-- [ ] **[MUST · V1] A11Y-004** Recording, processing, and failures never rely on color alone.-- [ ] **[MUST · V1] A11Y-005** Respect Reduce Motion, Increase Contrast, and Reduce Transparency.-- [ ] **[MUST · V1] A11Y-006** Transcript text supports standard selection, copy, find, context menus, and undo behavior.-- [ ] **[MUST · V1] A11Y-007** Prompt/HUD behavior works across full screen, Spaces, and multiple displays without focus theft.-- [ ] **[MUST · V1] A11Y-008** The menu-bar workflow remains complete when the main window is closed.-- [ ] **[MUST · V1] A11Y-009** Reuse existing FluidVoice theme typography, cards, buttons, spacing, and control heights; avoid one-off chrome.-------## 20. Future live-mode seam--- [ ] **[MUST · FOUNDATION] LIVE-001** Coordinator supports transcript mode `.offlineAfterStop` now and `.live` later.-- [ ] **[MUST · FOUNDATION] LIVE-002** Transcript canvas accepts append, revise, finalize, merge, reassignment, and identity-change events for stable IDs.-- [ ] **[MUST · FOUNDATION] LIVE-003** Capture and processing communicate through bounded streams with backpressure; live failure cannot stop durable recording.-- [ ] **[FUTURE · LIVE] LIVE-004** Feed downsampled chunks to a live ASR pipeline while archival writes remain independent.-- [ ] **[FUTURE · LIVE] LIVE-005** Show provisional text/speaker state without excessive visual noise.-- [ ] **[FUTURE · LIVE] LIVE-006** Auto-scroll only while the user is already at the bottom.-- [ ] **[FUTURE · LIVE] LIVE-007** Revisions preserve reading position, selection, and manual corrections.-- [ ] **[FUTURE · LIVE] LIVE-008** Stop runs final offline reconciliation and atomically finalizes provisional segments.-- [ ] **[FUTURE · LIVE] LIVE-009** Apply thermal/memory backpressure and disable live mode clearly on unsupported hardware.-------## 21. Acceptance and release gates--### 21.1 Platform matrix--- [ ] **[MUST · V1] TEST-PLATFORM-001** For every claimed platform/variant: waiting room, join/rejoin, mute, meeting end, app quit/relaunch, screen share, window resize, minimized/occluded window, breakout room, and app update.-- [ ] **[MUST · V1] TEST-PLATFORM-002** Browser test documents unrelated-tab audio behavior and verifies the warning is accurate.-- [ ] **[MUST · V1] TEST-PLATFORM-003** Zoom/Teams tests prove actual meeting/helper audio reaches the saved system track.-- [ ] **[MUST · V1] TEST-PLATFORM-004** No individual capability receives **Optimized** until that capability's own matrix passes; unavailable detection/name features do not block an independently validated Recording status.--### 21.2 Audio matrix--- [ ] **[MUST · V1] TEST-AUDIO-001** Built-in mic, USB mic, wired headphones, AirPods output, AirPods microphone, device unplug/reconnect, and route change.-- [ ] **[MUST · V1] TEST-AUDIO-002** Headphones and laptop speakers with at least two remote speakers, overlap, silence, and notification/music interference.-- [ ] **[MUST · V1] TEST-AUDIO-003** A long-session test proves both tracks remain within the numeric drift and unexplained-gap budgets set by TEST-BUDGET-001/002.-- [ ] **[MUST · V1] TEST-AUDIO-004** Source meter/health UI agrees with the audio actually written to disk.--### 21.3 Failure and recovery matrix--- [ ] **[MUST · V1] TEST-FAIL-001** Force quit, crash-equivalent termination, sleep/wake, source app quit/relaunch, microphone removal, capture permission revocation, and disk exhaustion.-- [ ] **[MUST · V1] TEST-FAIL-002** Every finalized chunk before failure is recoverable.-- [ ] **[MUST · V1] TEST-FAIL-003** Processing failure preserves audio and retry resumes from a durable checkpoint.-- [ ] **[MUST · V1] TEST-FAIL-004** Window close, tab navigation, and menu-bar-only use do not stop recording.-- [ ] **[MUST · V1] TEST-FAIL-005** Permission lifecycle covers first grant, denial, return from System Settings, revocation, regrant, and relaunch for microphone and Screen/System Audio independently.-- [ ] **[MUST · V1] TEST-FAIL-006** Duplicate Start/Stop/menu/Quit actions and stale callbacks produce exactly one session, one finalized manifest, and one queued processing job.-- [ ] **[MUST · V1] TEST-FAIL-007 — Display power transitions during capture.** Capture must survive a forced `pmset displaysleepnow`, an idle display sleep, a screen lock, and a monitor input switch. Each is verified by continued buffer delivery on both tracks, not merely by the absence of an error.-- [ ] **[MUST · V1] TEST-FAIL-008 — Capture-window loss during capture.** Close and recreate the captured application's window mid-session. Recording either continues or resumes on a new chunk boundary; all finalized chunks survive.-- [ ] **[MUST · V1] TEST-FAIL-009 — One-hour stability run.** A full-hour dual-track capture reports zero gaps, zero backwards timestamps, zero format changes, and drift within the TEST-BUDGET-002 limits.--### 21.4 Speaker and identity matrix--- [ ] **[MUST · V1] TEST-ID-001** Remote speaker labels remain stable through rename, merge, export, persistence, and reopen.-- [ ] **[MUST · M3] TEST-ID-002** Establish a minimum precision target before beta; optimize for fewer trustworthy suggestions rather than broad incorrect coverage.-- [ ] **[MUST · M3] TEST-ID-003** Test unknown people, same-name people, different microphones/rooms, overlapping speech, and visually ambiguous names.-- [ ] **[MUST · M3] TEST-ID-004** **No** does not alter stored profiles; only explicit **Yes** may enroll clean samples.-- [ ] **[MUST · M3] TEST-ID-005** Forget Person removes the profile without corrupting historical transcript display.-- [ ] **[MUST · V1] TEST-ID-006** A remote speaker appearing across multiple processing chunks retains one session-scoped speaker identity unless the evidence is genuinely ambiguous.--### 21.5 Privacy and accessibility matrix--- [ ] **[MUST · V1] TEST-PRIV-001** Inspect storage, analytics, logs, diagnostics, and network traffic for audio/transcript/name leakage.-- [ ] **[MUST · M4 if visual enabled] TEST-PRIV-002** Confirm no meeting screenshots/video frames persist.-- [ ] **[MUST · V1] TEST-A11Y-001** Complete the core workflow with keyboard only and VoiceOver.-- [ ] **[MUST · V1] TEST-A11Y-002** Verify high contrast, reduced motion, reduced transparency, multiple displays, Spaces, and fullscreen meetings.--### 21.6 Repository and release proof--- [ ] **[MUST · V1] TEST-REPO-001** Run SwiftFormat and strict SwiftLint before commit-ready feature work.-- [ ] **[MUST · V1] TEST-REPO-002** Validate implementation builds with `sh build_with_FI_incremental.sh` and inspect the installed `/Applications/FluidVoice.app`.-- [ ] **[MUST · V1] TEST-REPO-003** Do not treat Debug/XCTest-host runs as release proof; use focused logic checks plus installed-app, real-meeting evidence.-- [ ] **[MUST · V1] TEST-REPO-004** Verify the minimum supported macOS path and low-resource Apple Silicon behavior; describe Intel as reduced capability until separately proven.-- [ ] **[MUST · V1] TEST-REPO-006** Run real Intel capture plus plain English transcription before claiming Intel meeting support; universal build slices alone are insufficient.-- [ ] **[MUST · V1] TEST-REPO-005** Update the requested release-notes version locally, credit contributors as required, and never commit ignored release notes.--### 21.7 Measurable budgets to set before implementation--- [x] **[MUST · FOUNDATION] TEST-BUDGET-001** Maximum supported meeting duration: **3 hours**. Long-session validation duration: **60 minutes** (M2-TEST-007); one 3-hour run before claiming the maximum.-- [x] **[MUST · FOUNDATION] TEST-BUDGET-002** Accumulated track drift: **≤ 1 s/hour** (measured ~0.05 s/hour, Appendix A; budget leaves 20× headroom). Unexplained audio gap: **≤ 1 s total per session** (discontinuity-marked gaps from recovered interruptions excluded). Source-loss alert latency: **≤ 10 s** from last delivered sample to visible degraded state. Maximum recoverable loss from the active chunk: **≤ the configured chunk duration** (60 s floor in code).-- [x] **[MUST · FOUNDATION] TEST-BUDGET-003** Disk reserve: **512 MB** preflight minimum (matches the existing `preflightStorage` check); warn at **1 GB** free during recording; safe-stop and finalize at **256 MB**.-- [x] **[MUST · FOUNDATION] TEST-BUDGET-004** On the lowest supported Apple Silicon (M1, 8 GB): capture-only CPU **≤ 10% average**, app memory during capture **≤ 400 MB**, no unbounded buffer growth across the 60-minute run, disk writes **≤ 100 MB/hour** per track at the chosen AAC bitrate.-- [x] **[MUST · FOUNDATION] TEST-BUDGET-005** Diarization: **≤ 30% DER** on speaker-playback (far-field/leakage) fixtures, **≤ 20% DER** on headphone-clean fixtures — set from published far-field meeting-corpus results (AMI ≈ 21% for strong systems); tighter targets are aspiration, not gate. Cross-chunk continuity: in a 10-minute two-speaker fixture spanning ≥ 3 chunks, the same voice keeps one session speaker ID in **≥ 90%** of its speech time.-- [ ] **[MUST · M3] TEST-BUDGET-006** Set identity-candidate precision, unknown rejection, and false-enrollment targets before M3 beta.-- [ ] **[CONDITIONAL MUST · M4] TEST-BUDGET-007** Set visual sampling rate, CPU budget, candidate agreement window, and false-name target before visual assistance ships.-------## 22. Follow-up bugs--- [ ] **[P0 · CAPTURE] BUG-001 — Meeting transcription can freeze during voice-processing startup.**- - Formal analysis and evidence plan: [`MEETING_AUDIO_START_FREEZE_RCA.md`](MEETING_AUDIO_START_FREEZE_RCA.md).- - Reproduced twice on 2026-08-25. During VPIO aggregate-device teardown, main remained parked in an- AVFoundation listener-removal wait while HAL remained parked in synchronous notification dispatch.- The exact closing queue edge is not yet proven.- - Fix boundary: first isolate AVFoundation materialization, FluidVoice main-queue listeners, and idle- dictation prewarm. Ship every independently proven curative slice, then complete async topology- ownership for start, stop, recovery, and VPIO↔SCK switching.- - Verification: instrumented isolation matrix, no listener add/remove on main or its delivery queue,- zero topology-owner overlap, and zero failures in at least 2,995 targeted post-fix cycles. A timeout,- retry, forced restart, or timing-only guard is not an acceptable fix.-------## 23. Open decisions for alignment--These do not block writing the PRD. They must be resolved before their associated milestone begins.--- [ ] **[MUST · FOUNDATION] OPEN-001 — Default audio retention.**- - Recommendation: 7 days, with Delete after transcription, 30 days, and Never.--- [ ] **[MUST · FOUNDATION] OPEN-002 — Dictation during recording.**- - Recommendation for V1: keep meeting recording healthy and explain that dictation is unavailable until the meeting stops.--- [ ] **[MUST · M3] OPEN-003 — Voice-profile opt-in scope.**- - Recommendation: explicit first-use explanation plus a per-person **Remember this voice** choice; never infer consent from rename alone.--- [ ] **[MUST · M4] OPEN-004 — Detection release timing.**- - Recommendation: after trustworthy manual recording, not in the first vertical slice.--- [ ] **[MUST · M4] OPEN-005 — Visual active-speaker release timing.**- - Recommendation: experimental after voice/manual identity works; platform UI analysis must never block capture.--- [ ] **[MUST · V1] OPEN-006 — Exact optimized variants.**- - Recommendation: begin with Zoom desktop, Google Meet in Chrome, and current Teams desktop; add browsers/versions only after matrix proof.--- [ ] **[MUST · V1] OPEN-007 — Intel product copy.**- - Recommendation: recording plus plain English transcript, with **You** versus **Meeting audio** when track origin permits, but no remote-speaker labels.--- [ ] **[OPTIONAL · V1] OPEN-008 — Pause/resume.**- - Recommendation: defer unless user research makes it essential.--- [ ] **[MUST · V1] OPEN-009 — Stop cue.**- - Recommendation: no audible cue routed into meeting/application audio; use visual state and optional haptic-equivalent UI only.--- [ ] **[MUST · V1] OPEN-010 — Quit behavior.**- - Recommendation: closing the window continues; quitting prompts **Keep Recording** (cancel Quit), **Stop & Quit**, or Cancel.--- [ ] **[MUST · V1] OPEN-011 — Local display name source.**- - Recommendation: a meeting-specific preferred name stored in FluidVoice, editable from the transcript participant chip.--- [ ] **[MUST · V1] OPEN-012 — Backup policy.**- - Decide whether recordings, transcripts, and voice profiles participate in FluidVoice backup/export independently.-------## 24. Highest-risk implementation traps--- [ ] **[MUST · FOUNDATION] RISK-001** ScreenCaptureKit microphone identifiers may not equal the current Core Audio device UID.-- [ ] **[MUST · FOUNDATION] RISK-002** The current diarization wrapper discards the embeddings needed for remembered identity.-- [ ] **[MUST · FOUNDATION] RISK-003** Current speaker-segment IDs change when the speaker name changes.-- [ ] **[MUST · FOUNDATION] RISK-004** Current file-history/UserDefaults storage is unsuitable for long recordings and crash recovery.-- [ ] **[MUST · FOUNDATION] RISK-005** A whole-file local-mic transcript cannot be accurately merged with remote turns without speech timestamps.-- [ ] **[MUST · FOUNDATION] RISK-006** Reusing `ASRService.start()` would entangle meeting capture with dictation streaming, media pausing, and teardown.-- [ ] **[MUST · FOUNDATION] RISK-007** Existing menu-bar `isRecording` means dictation only, and the current template icon does not actually draw the requested red dot.-- [ ] **[MUST · FOUNDATION] RISK-008** Changing a ScreenCaptureKit stream/device configuration mid-session can create interruption; represent it as a chunk boundary.-- [ ] **[MUST · V1] RISK-009** Browser capture is application-wide, and Zoom/Teams helper-process behavior needs real proof.-- [ ] **[MUST · V1] RISK-010** Meeting recovery cannot depend on the existing graceful shutdown timeout.-- [ ] **[MUST · M4] RISK-011** Active-speaker visuals are brittle across layout changes, sharing, overlap, and minimized windows.-- [ ] **[MUST · M3] RISK-012** Incorrect profile enrollment compounds future errors; only confirmed clean speech may update a profile.-- [ ] **[MUST · V1] RISK-013 — A display-scoped ScreenCaptureKit filter dies on any display power transition.** Measured, not theoretical: a one-second display blackout terminates the stream with `-3815` and it never recovers. The user sees the display return and the meeting continue while the transcript has silently stopped. Mitigated by CAP-028 and REL-015.-- [ ] **[MUST · V1] RISK-014 — The two SCK audio outputs are not on one clock.** `.audio` and `.microphone` arrive with different format descriptions (measured 48 kHz stereo versus 48 kHz mono) and independent presentation-timestamp epochs, offset by a per-session constant (measured 87–98 ms). Feeding both into one writer corrupts the container. Use one writer per track and take each track's own first-buffer timestamp as its origin.-- [ ] **[OPTIONAL · SECURITY] RISK-015 — Screen Recording is a heavy consent ask for an audio feature.** The system dialog says FluidVoice can record screen contents, and macOS re-confirms roughly monthly. Core Audio process taps use `NSAudioCaptureUsageDescription` instead, with no periodic re-consent, but require solving per-process audio attribution for multi-process apps such as Chrome, Zoom, and Electron clients. Revisit after the capture layer is stable; not a V1 blocker.-------## Appendix A — Capture reliability measurements (2026-08-10)--Host: macOS 26.5.1 (25F80), Apple Silicon. Harness mirrored the `1.6.8/meeting-m1` `SCStreamConfiguration` exactly.--| Experiment | Configuration | Result |-|---|---|---|-| 60-minute soak | Display-scoped filter | Terminated at 20:18 with `-3815` when the display slept. Screen lock excluded: lock delay was 300 s and the session stayed unlocked. |-| 60-minute soak | Display-scoped filter, display held awake | Ran the full 3600 s. Zero gaps, zero backwards timestamps, zero format changes, ~14 ppm drift, 30 ms track differential over the hour, constant 87.6 ms skew. FB13847291 did not reproduce. |-| Trigger isolation | Display-scoped filter, forced `displaysleepnow` | Died within one second of display-off and did not recover when the display returned one second later. |-| Filter comparison | Window-scoped filter, forced `displaysleepnow`, three runs | Survived every time. Audio delivery continuous through the blackout. App-track silence 2.8% against an emitting app, 100% against a silent app, confirming audio remains scoped to the owning application. |--Both follow-ups closed 2026-08-10 on the implemented branch:--| Follow-up | Result |-|---|---|-| Screen lock during window-scoped capture | Survived. 92 s run with the session locked mid-capture: zero gaps, continuous app-audio delivery through lock and unlock. |-| Captured window closed, replacement opened 2 s later | No interruption through the app runtime: no `sourceLost`, app audio kept flowing, and a subsequent forced display sleep produced zero events — confirming the stream remained window-scoped. A standalone harness had shown stream death ~17 s after window close, so both outcomes exist in the wild; the death path is covered by REL-015's rebuild (verified live: `sourceLost` → `sourceRecovered` in 1 s). |-------## 25. Primary references--- Apple ScreenCaptureKit: <https://developer.apple.com/documentation/screencapturekit>-- Apple `SCContentFilter`: <https://developer.apple.com/documentation/screencapturekit/sccontentfilter>-- Apple ScreenCaptureKit application-level audio discussion: <https://developer.apple.com/videos/play/wwdc2022/10155/>-- Apple ScreenCaptureKit introduction: <https://developer.apple.com/videos/play/wwdc2022/10156/>-- Apple Core Audio process input activity: <https://developer.apple.com/documentation/coreaudio/kaudioprocesspropertyisrunninginput>-- Apple Bluetooth headset quality behavior: <https://support.apple.com/en-us/102217>-- Google Meet requirements: <https://support.google.com/meet/answer/7317473>-- Google Meet layouts: <https://support.google.com/meet/answer/9292748>-- Zoom Workplace desktop app: <https://support.zoom.com/hc/en/article?id=zm_kb&sysparm_article=KB0064516>-- Slack Huddles: <https://slack.com/help/articles/4402059015315-Use-huddles-in-Slack>-- Webex system requirements: <https://help.webex.com/en-us/article/nk90t65/Webex-App-System-Requirements-and-Support-Policy>diff --git a/MIC_CAPTURE_MIGRATION_PLAN.md b/MIC_CAPTURE_MIGRATION_PLAN.mddeleted file mode 100644index 0903e5ca..00000000--- a/MIC_CAPTURE_MIGRATION_PLAN.md+++ /dev/null@@ -1,272 +0,0 @@-# Microphone capture migration — SCStream → AVAudioEngine with Voice Processing I/O--Status: **v4, planned, not started.** v1–v3 were each rejected by two independent reviewers. v4 is-smaller than v3, per the reviewers' closing instruction. Written 2026-08-15.--## 1. What v4 changes from v3--v3 was rejected mainly for three self-inflicted errors. Each is corrected by *narrowing a claim*, not-by adding machinery:--| v3 error | v4 |-|---|---|-| "No diarization, no clustering" | **Keep the diarizer.** It is the *segmenter*, not a labeller (`MeetingProcessingPipeline.swift:1385-1391`); every turn boundary, `transcribeTurns`, word alignment, `turnLoudness` and the empty-turn guard depend on it. Deleting it leaves only whole-chunk transcription — the hallucination path fixed earlier today. v4 keeps diarization and **merges its mic clusters into "You"**. |-| "No fallback" | **Pre-flight capability decision, not mid-meeting fallback.** VPIO viability is decided *before* capture starts; the session then runs one way for its whole life. No mixed provenance, and no lost meeting. |-| "Session surfaces a degraded microphone track" | False — capture start is atomic (`MeetingCaptureEngine.swift:88-95`) and a runtime failure stops all writers. v4 does not claim a state the code lacks. |--## 2. Measurements--| question | result |-|---|---|-| Does AEC cancel the far end? | raw mic −23.7 dBFS / 62 words of far-end text; VPIO mic −63.6 dBFS / **zero words** |-| Cancellation vs ducking | ~40 dB total, ~7 dB of it ducking → **~33 dB genuine cancellation** |-| Double-talk | raw: 8 words of mush; VPIO: **51 words of the user's passage, no far-end content** |-| Effect on the user's own voice | ~14.5% WER either way; VPIO ran 12 dB hotter (AGC) |-| Ducking cost at `.min` | −6.9 dB mean on **all** other audio, swing 9.2 → 16.9 dB |-| Downlink-DSP faults | 2066 during the successful run — **not root-caused** |--Shipping config (`VoiceProcessingAsrQualityTests.swift:54-57`). **One machine, one room, built-in mic-and speakers.** Not measured: quiet interjections under a loud far end; any other hardware or macOS-build.--**Competitor precedent is weaker than v3 claimed.** The surveyed competitor ships a thin capture-client with no local models; segmentation and diarization happen server-side, so their client never-had an election to delete. What genuinely transfers: separate dictation/meeting audio configs, source-attribution as the live default, no AEC fallback, logging the *settled* audio constraint rather than-the requested one, and accepting the ducking with no mitigation.--## 3. Activation conditions--VPIO is used only when **all** hold, decided before capture starts:--1. Mode is `.onlineCall` and the microphone role is `.personal`.-2. **Output is not headphones.** With headphones there is no bleed to cancel, so VPIO delivers zero- benefit and the full ducking cost — pumping the audio the user is hearing the call on. v3 applied- VPIO unconditionally; the user's accepted trade (§4) was measured on speakers only.-3. The selected microphone can be bound and verified (§6).--Otherwise the session runs today's SCStream path unchanged, with full echo machinery. This is a-**capability decision, not a fallback**: homogeneous for the session's lifetime.--Mid-session output changes (speakers → AirPods) are a known limitation, not handled in v4.--## 4. Product decision — accepted, with a stated boundary--Enabling VPIO ducks **all** other audio by ~7 dB with ±8 dB of pumping that increases while the user-speaks, audible live. **Accepted by the user, 2026-08-15**, after being shown the measured figures and-told it affects live listening rather than only the recording.--That acceptance was given for the **speakers** case and does not extend to headphones — hence §3.2.--## 5. Attribution--For a VPIO session, on the microphone track:--- Diarization runs exactly as today (it is the segmenter), and **the election runs unchanged**.-- VPIO turns are marked **scored clean** — `echoScored` is widened to `true` on every turn, forced- after the existing text-detector loop runs — because that is what they are: AEC-clean by hardware.- They therefore count as supporting evidence in `localSpeakerEvidence`- (`MeetingProcessingPipeline.swift:357`) exactly as a text-examined clean turn does today.-- **This is the whole change.** No branch on cluster count, no bypass. AEC does not make diarization- unnecessary — it makes it work, by removing the echo clusters that competed with the user's own- voice and defeated the 1.75× margin rule in the observed failure. A second voice in the room is then- handled by the election as it always was, which matters because misattribution is- **uncorrectable in-product**: `mergeSpeakers` refuses any speaker with `isLocalUser`- (`MeetingModels.swift:542`).-- ~~The text echo detector is not consulted; the signal veto is not applied.~~ **Superseded by Phase 4- measurement:** a healthy VPIO gate session produced zero `.echo` verdicts (7 `containsLocalSpeech` /- 1 `unknown` / 0 `echo`) — the veto had nothing to veto. Suppressing it bought nothing on working- hardware and risked bleed-as-"You" on degraded hardware. Phase 4 ships with **both kept**: the text- detector still runs wherever remote text exists, and the signal veto still demotes- `signalVerdict == .echo` turns exactly as it does for non-VPIO tracks.-- `MeetingEchoSignalScorer` still runs as a **monitor**: its verdicts are recorded, never applied- beyond the (retained) veto. This is the only field evidence that AEC worked on hardware we have not- measured; without it a silently-degraded canceller yields bleed labelled "You", forever undetected.- Phase 4 adds a per-session log-only summary (verdict breakdown, real scoreable coverage, delay-lock- info) plus a WARN when coverage is ~0 while the application track carried speech.-- `MeetingLiveEchoFilter` is disabled for VPIO sessions (`MeetingLiveTranscriptionCoordinator.swift:150`).-- The decider now also requires `role == .personal` — the election and near-field gate already did,- so a role-blind VPIO session captured cleanly but could never attribute.-- `pipelineVersion` bumps; attribution rules changed.--Unchanged: `.inRoom` (`AVCaptureSession`, not SCStream — `MeetingCaptureEngine.swift:624`), non-VPIO-sessions, and the near-field gate.--## 6. Device selection--`kAudioOutputUnitProperty_CurrentDevice` fails for Bluetooth and aggregate devices, and the existing-binder falls back to the system default on **any** non-zero status (`ASRService.swift:2569-2584`).-SCStream honours `microphoneCaptureDeviceID` exactly today, so this is a real regression.--Order of attempts:-1. Bind, then **read the device back and compare** after voice processing is enabled and the engine is- running — a successful status is not proof, since enabling VPIO can replace the I/O unit.-2. If binding fails but the **system default input is already the requested device**, proceed unbound:- identity is correct even though binding is not. This covers most AirPods users, who selected the- device in System Settings precisely because they are on a call.-3. Otherwise VPIO is not viable → §3, session runs today's path.--Binding order relative to `setVoiceProcessingEnabled` is a **Phase 1 measurement**, not an assumption.-Unresolved: `AVCaptureDevice.uniqueID` → `AudioObjectID` mapping is by display name and yields nil on-collision (`MeetingCaptureEngine.swift:855-866`).--## 7. Provenance--No-fallback removes *mixed* provenance, not provenance itself. A **track-level** `captureMethod` is-required, describing verified capture rather than intended configuration, and read by: batch-attribution (§5), the live coordinator's echo-filter decision, retry after relaunch, checkpoint-resume, and reprocessing of sessions recorded before this change (absence = legacy).--## 8. Timeline--Cross-track timing survives for transcript ordering (batch `MeetingProcessingPipeline.swift:1100-1104`-and live `MeetingLiveModels.swift:39-44`), the `.overlapsOtherTrack` badge, and live origin-establishment. Echo reference alignment is gone.--- Microphone PTS is the tap's `AVAudioTime.hostTime` — acquisition, first frame — as dictation already- does (`ASRService.swift:4617-4620`). Never `mach_absolute_time()` at callback time.-- Invalid `hostTime`: extrapolate from the last valid stamp plus output duration, **capped at 500 ms**;- beyond that, record a discontinuity and resync.-- **Resolved by Phase 0 (see §9): same clock domain.** SCStream PTS regressed against mach at- −0.133 ppm ± 0.628 over 24k samples — the offset is effectively identity and no drift model is- needed. The ~6.4 ppm drift this repo previously measured (`MeetingProcessingPipeline.swift:722-724`)- was between the two *audio device* clocks through their samples, not between SCStream's stamps and- mach; it remains real for echo-reference alignment, which VPIO sessions no longer perform.--**Budget: ±50 ms**, justified by turn ordering alone. Stated as a claim to be tested, not derived —-v3 wrongly cited the 0.15 s `overlapsRemote` threshold, which is a minimum-overlap predicate.--## 9. Phases and gates--**Phase 0 — clock domain. DONE, 2026-08-15.** Regressed SCStream audio PTS against mach host time-over 8 minutes, 24,027 samples (`ClockDomainProbeTests`, `FLUIDVOICE_CLOCK_PROBE`): slope-**−0.133 ppm, 95% CI ±0.628** — statistically zero, 150× inside the 20 ppm gate. SCStream PTS is-mach-anchored, so both capture paths already share a clock domain: **constant offset only; the-linear model in §8 is not needed.** Residual std 6.9 ms is arrival jitter, confirming that per-sample-arrival deltas would have been the wrong instrument. Caveats: one machine, and the probe needs an-unlocked display in a foreground session (`SCShareableContent` reports zero displays otherwise).--**Phase 1 — `MeetingMicrophoneCapture`, standalone. DONE, 2026-08-15.** Formal gate passed on the-built-in mic, 8 minutes: 4800 buffers, **100%** valid `hostTime`, 48 kHz mono Float32 delivered,-8 chunks at exact 60 s cadence, zero discontinuities / backpressure / live-copy rejections, device-bound and read back verified, non-silence confirmed. Measured findings, each of which changed the-design:--- **Binding and read-back live on element 1.** `kAudioOutputUnitProperty_CurrentDevice` on element 0- addresses the I/O unit's *render* side — read-back returned the AirPods output (85) against a- requested built-in mic (78). Element 0 would also have *moved the AEC reference*.-- **The tap must be installed before `start()`.** A tap added to an unconnected input node after the- active graph is built sits on an inactive node: measured as 10 minutes of zero callbacks with all- other telemetry healthy. Post-start format renegotiation is handled by reinstalling the tap.-- **VPIO delivers no input when its render route is Bluetooth.** AirPods as output: zero callbacks;- speakers: perfect stream, same code and mic. §3.2 (VPIO only on speaker routes) is therefore- enforced by the hardware, not just chosen — and the Bluetooth-mic leg resolves to "structurally- unsupported; such sessions use the SCStream path".-- The §6.2 escape hatch fired correctly in production (`defaultMatchesRequested` when the AirPods- bind failed), and `AVCaptureDevice.uniqueID` **equals** the CoreAudio UID for Bluetooth devices- (`EC-46-54-41-33-11:input`) — the name-collision mapping problem largely retires.-- VPIO exposes a **9-channel** input format on the built-in mic; explicit downmix (never converter- channel mapping) handled it.-- Open tuning note for Phase 2: the PTS clock's 1-frame anchor-correction tolerance trips on ~97% of- buffers (device-clock vs mach jitter); widen it — corrections are currently telemetry noise, though- emitted PTS stayed monotonic and the writer accepted everything.--**Phase 2 — timeline. DONE, 2026-08-15, gate honestly FAILED — with the remedy designed.**--The Phase 1 "corrections on 97% of buffers" finding was a **misdiagnosis**: not HAL jitter but a-latch bug — the correction re-baselined one full accumulation window off (post- vs pre-increment-frame count), so every subsequent stamp re-corrected forever. Reproduced by simulation (drift-only-run predicts first fire at window ~32; field data showed 31 and 34), fixed with one line, and the-first-fire index back-derives the built-in mic's drift as ~6.4 ppm — matching the repo's old-echo-path measurement from an entirely different method.--Cross-path drift gate (8 min, dual capture, guards all zero):-`mic +6.693 ppm (CI ±0.635) | app −0.081 ppm (CI ±0.627) | Δ 6.774, CI_Δ 0.892` → the-budget-derived gate (Δ+CI < 6.9 ppm = ±50 ms over 2 h) **failed by 0.77 ppm**. The mic's sample-clock genuinely runs ~6.7 ppm fast vs mach: 24 ms/hour of skew, 48.8 ms at 2 h — inside budget at-the point estimate, over it with CI, and per-device physics that another machine or a USB mic could-triple.--**Remedy (Phase 3, consumer side):** the clock's correction stream is now a live drift meter-(`cumulativeAbsorbedCorrectionSeconds`, one correction per ~3.2 s, each ≤20.8 µs). The batch-pipeline applies a linear de-drift to mic PTS when mapping onto the shared timeline — one multiply —-holding the budget with ~10× margin for **any** device, which also retires the USB-microphone-concern structurally. Capture-side PTS stays sample-count truth (the invariant: `anchorPTS` is never-moved mid-stream; corrections adjust only the divergence reference and are a no-op on output).--Also built: divergence **step detector** (10 ms threshold; drift moves 0.64 ns/window and cannot-fire it — verified over a simulated 2 h), resync clamp so a backlogged invalid burst can never step-PTS behind emitted audio, timeline reset on `AVAudioEngineConfigurationChange`, and real timebase-values in the probe's track metadata. Absolute cross-path offset remains unmeasured (AEC removes-acoustic stimuli, as reviewed) and is Phase 3's first real-call validation item.--**Phase 3 — integrate behind a flag, default off. DONE 2026-08-17, gate PASSED on a real call.**-Shipped behind `meetingVPIOMicCapture` (Settings → experimental, off): pre-flight capability-decision (pure decision table; flag + `.onlineCall` + CoreAudio UID + built-in-speaker output route,-every decline reason logged to session events); `VoiceProcessingMeetingRuntime` with a commit gate —-mic audio and events buffer in a ring until viability + first-buffer-within-2s + app-only SCStream-are all confirmed, so an aborted attempt leaves writers byte-clean and the fallback needs no-re-stamp (provenance is pessimistic `.screenCaptureKit`, durably promoted to `.voiceProcessing`-before the first flushed byte; flush is serialized ahead of passthrough so PTS order holds); one-10s total start deadline, expiry during fallback fails cleanly; mid-session surface = emitted-only-10s watchdog + output-route listener (same predicate as pre-flight, service-restart re-registration)-+ defaultInputChanged UID check, all mapping to the existing interruption flow. Batch de-drift-(`MeetingMicrophoneDeDrift`, k = 1 + cumulative/elapsed — sign verified against the clock: a fast-mic accumulates NEGATIVE corrections) applies to emitted turn boundaries only, gated on a persisted-eligibility bit (zero resyncs/steps/config-changes), 5ms materiality, 100ppm sanity. No-pipelineVersion bump (no pre-flag `.voiceProcessing` tracks can exist; checkpoints snapshot the-application pass only). Live echo filter untouched — deferred to Phase 4 as an attribution change.-Reviewed adversarially over three rounds (two independent reviewers from BLOCK to PROCEED /-PROCEED WITH CHANGES, all findings folded); 36 new unit tests.-*Gate results (2026-08-17, 15.5-min Zoom call, built-in mic/speakers):* VPIO engaged-(`boundVerified` device 78, settled output BuiltInSpeakerDevice); live mic stream carried ONLY the-user's speech while far-end played on speakers (previously a verbatim mirror of the app stream);-double-talk captured the user cleanly as "You" mid-far-end-monologue; zero drops both streams.-Batch: 53 segments — You 20 (all genuinely the user, `isLocalUser` elected), far end 32 across-Speaker 1-5, ONE 2-word "Microphone / Unknown" fragment ("code and") — a non-local-diarization cluster; deliberately NOT forced into "You" by Phase 4 (indistinguishable from a second-voice's interjection). Drift record: −5.24 ms over 957 s (−5.5 ppm, matching the bench-+6.7 ppm fast-mic sign analysis), eligible, materiality crossed → de-drift executed on a real-session. AirPods-at-start declined correctly ("The output device is Bluetooth", session ran-SCStream path); AirPods mid-recording → route listener fired instantly with the designed message,-clean interrupted state, audio preserved, retry offered. Post-meeting dictation normal.-Not yet measured: start latency p50/p95, `silentForSeconds` under AGC over a long quiet stretch.--**Phase 4 — attribution. DONE 2026-08-17, gate PASSED (v7 reprocess elected the same You with an-identical transcript; two-voice-in-room abstained correctly with both voices labeled; monitor-echo=0 with real coverage 67.6s and 4/15 delay locks).**--**Flag removed 2026-08-17 (product decision):** echo cancellation is not a setting — the pre-flight-decision table is the only gate (mode, role, output route, bindable mic). VPIO engages-automatically whenever viable; otherwise the session runs the SCStream path and logs the decline-reason. The `meetingVPIOMicCapture` toggle and backup key are gone.--**Phase 4 detail:** Marks VPIO turns scored-clean-(`echoScored` widened to every turn, forced after the existing text-classification loop) and lets the-existing election run; text detector and signal veto both kept (measurement-driven reversal of the-original "not consulted / not applied" plan, see §5). Decider now requires `role == .personal`-(`MeetingCapturePathDecider.decide`, decline reason "Microphone role is not set to personal").-`logLocalSpeakerElection` gained `captureMethod` and a widened-turns counter (count + seconds forced-scored with no remote text to examine), since `unscoredOverlap` pins to 0.0s under VPIO. New log-only-per-session echo-monitor summary (verdict breakdown, real scoreable seconds — never fabricated from-turn duration, extended `EchoScoringOutcome`/`computeEchoVerdicts` — delay-lock chunks/confidence) plus-a WARN on ~0 coverage while the app track carried speech. Live: `MeetingLiveTranscriptionCoordinator`-gained `setMicrophoneCaptureMethod`, called from `MeetingSessionCoordinator` right after-`capture.start()` returns; `.voiceProcessing` skips `shouldSuppress`, nil (fail-safe default) keeps it-on, bracketed by `[live/ECHO]` log lines so pre-setter suppressions are countable.-`pipelineVersion` 6 → 7 (checkpoint invalidation only). The classification block was extracted to a-`nonisolated static` pure function, `classifyMicrophoneTurns`, so it and the election are unit-tested-directly; non-VPIO path is byte-identical by construction (the widening branch never executes).-*Gate (attended, not yet run):* a single-voice VPIO session elects "You" with no-`Microphone / Unknown`; a **two-voice** session still elects the owner and demotes the second speaker;-a non-VPIO session produces a transcript identical to today's. The first alone proves nothing — the-second is the real test, and it is only possible because the diarizer was kept.--## 10. Not claimable unattended--Quiet interjections under a loud far end (**a release blocker, not a footnote**); AirPods selection and-mid-session profile switching; the ducking experience; permission prompts; real-call ordering under-load; post-meeting dictation and Bluetooth restoration; AEC on any untested hardware or macOS build;-the 2066 downlink faults, which remain un-root-caused and gate nothing today.--Phases 0–2 are unattended-safe. **Phases 3–4 are not, and have no owner or schedule yet.**diff --git a/Tests/ClipboardBackupReproduction.md b/Tests/ClipboardBackupReproduction.mddeleted file mode 100644index 5cecd753..00000000--- a/Tests/ClipboardBackupReproduction.md+++ /dev/null@@ -1,40 +0,0 @@-# Clipboard backup regression tests--Run with a full Xcode toolchain (without changing the system-wide selection):--```sh-DEVELOPER_DIR=/Applications/Xcode-beta6.app/Contents/Developer sh Tests/run_clipboard_backup_reproduction.sh-DEVELOPER_DIR=/Applications/Xcode-beta6.app/Contents/Developer sh scripts/test_dictation_target.sh-```--The backup runner compiles production `PasteDeliveryCoordinator.swift`, including-`SystemPasteboardManager`, and `DictationTargetPolicy.swift`. Each case uses an isolated-named macOS pasteboard. Injected command posters send no keys; optional I/O failures-are injected at the pasteboard boundary. Logging and unused keyboard constants are-standalone adapters. The general clipboard, preferences, microphone, and installed app-are not accessed by this runner.--31 cases cover:--- Backup off/on with successful posting, failed snapshots, failed writes before and- after touching the clipboard, failed command posting, and newer user copies during- failed writes/posts or before settlement.-- Both experimental-toggle positions, with external focus present or missing, using- the production preparation boundary and an injected unsuccessful focus restoration.-- A backup queued behind an active paste, with backup off/on and newer user copies.-- Stale failed preparation after a newer user copy, paste delivery, or standalone copy.--Checks include delivery results, final clipboard text, permanent-copy call counts,-absence of duplicate backup writes, zero commands after failed preparation, and no-clipboard mutation for disabled backup when insertion is skipped. Successful posting-is a simulated command-post result, not proof that a destination app consumed text.--Before the fix, the first 10 cases had three failures: with backup enabled,-snapshot/write/command failure retained the old clipboard instead of the transcript.-The runner now expects all cases to pass and exits nonzero on a regression. The-existing XCTest assertion for command failure with backup enabled is also updated.--The separate destination-policy suite covers 10 app/field-switch and missing-target-cases. These tests do not perform live Accessibility restoration, record speech, or-exercise ContentView/history persistence end to end. Failed preparation is injected-into the same production coordinator boundary used by ContentView.diff --git a/docs/design/dictionary-learning-api.md b/docs/design/dictionary-learning-api.mddeleted file mode 100644index d8321c5f..00000000--- a/docs/design/dictionary-learning-api.md+++ /dev/null@@ -1,143 +0,0 @@-# Reusable dictionary learning API--Status: broader proposed contract. The September 20 backend implementation and measured limits are documented in [original-audio-learning-implementation.md](original-audio-learning-implementation.md). The descriptions below record the September 19 baseline and future design, not the current implementation status. Reviewed against the local FluidVoice long-recording implementation and companion FluidAudio pronunciation-streaming worktree on 2026-09-19. UI entry points and automatic-add policy can be implemented independently after this contract.--## Outcome--A user correction should associate the intended spelling with the actual pronunciation from that dictation. A confirmed, well-aligned original occurrence can supply one real example; the application should not automatically ask for three fresh recordings. Save audio evidence and its derived embedding together, so the spelling, text variants and sound all refer to the same occurrence. These are personalization examples, not acoustic-model weight training.--Manual entry, correction approval, explicit voice enrollment and future automatic additions all call the same learning service. They choose how an addition is initiated; they do not each implement extraction, embedding, persistence or matching rules. No new HTTP server is needed: the internal Swift service is the canonical API, with optional adapters for the existing Local API later.--## What exists today, and review findings--| Path | Current result | Missing for correction-based learning |-|---|---|---|-| Manual dictionary entry | Intended spelling and text triggers | No audio exists unless linked to a spoken occurrence |-| Basic voice training / correction popup training | Text variants collected from new recordings | Popup ignores pronunciationEnrollment; original correction audio is not linked |-| Advanced voice training in dictionary page | Text aliases and model-specific embedding examples | No persisted audio reference; requires three examples |-| Detected correction / Add Only | heardText and correctedText become text replacement | Candidate lacks recording ID, original token span and audio evidence |-| Long-recording matching | Matches existing trained profiles during dictation | Discards encoder features after producing hits; cannot learn an unknown word from those hits alone |--Source anchors: AutomaticDictionaryCorrectionCandidate in AutomaticDictionaryCorrectionTracker.swift; AutomaticDictionaryTrainingSession.persist/addOnlyCorrection; PronunciationEnrollmentCapture and PronunciationDictionaryStore; FluidAudioProvider.pronunciationProfiles/transcribeFinalResult; CustomDictionaryView.finishTrainingSampleStop.--Two runtime gates still require enrollments.count >= 3. Merely saving one embedding would not activate it. They must eventually consume a common eligibility policy, not be changed independently to accept everything.--ASRService retains completed audio only when history and history-audio saving are enabled. That snapshot is consumed by other flows. It is not a reliable learning-evidence API. Also, correction observation starts with inserted text and target PID; inserted text may already contain alias replacements, formatting or AI rewriting. Searching that text for a word is not sufficient to select the correct audio occurrence.--The existing save paths update UserDefaults text entries and a separate JSON pronunciation store. They cannot provide a single atomic learning commit, especially once audio files are added. The shared service must own a recoverable commit boundary before its clients claim success.--## Service boundaries--```swift-// Contract sketch, not compiled production declarations.-protocol DictionaryLearning {- func prepare(_ request: LearningRequest) async throws -> LearningProposal- func commit(_ proposal: ProposalID, decision: LearningDecision,- idempotencyKey: UUID) async throws -> LearningReceipt- func discard(_ proposal: ProposalID) async- func retract(_ learningEvent: LearningEventID) async throws- func snapshot(for model: AcousticModelIdentity) async throws -> DictionaryMatchingSnapshot-}-```--`prepare` resolves evidence, checks eligibility, stages the clip/embedding and produces a reviewable proposal. It must not change active dictionary rules, microphone state, boosting, history settings or UI selection. `commit` activates exactly the prepared content under the current learning policy. A retry with the same idempotency key returns the original receipt. `retract` removes that event's contributions, not an entire word's unrelated examples or aliases.--The service actor coordinates independent components:--- `DictationEvidenceStore`: immutable recording receipts, ephemeral audio ownership and bounded evidence leases.-- `CorrectionAlignmentResolver`: maps the corrected delivered-text span back to the original ASR token occurrence, with explicit ambiguity results.-- `PronunciationEvidenceExtractor`: creates a focal audio example and an embedding using a versioned acoustic backend. No UI or dictionary writes.-- `DictionaryLearningPolicy`: determines confirmation requirements, alias scope and whether an example is eligible for matching.-- `DictionaryLearningRepository`: atomic metadata commits, staged audio files, recovery, migrations and immutable matching snapshots.--FluidAudio owns feature extraction and scoring. FluidVoice owns user intent, text-edit provenance, policy, retention and persistence. A model/search-library swap changes the extractor implementation, not each UI caller.--## Request and evidence identity--`LearningRequest` contains:--- Request/event UUID and optional existing dictionary entry UUID/revision.-- Intended spelling; observed original ASR text when known.-- Source: explicit correction, manual word, fresh voice example or automatic proposal. Source is provenance, not permission to bypass policy.-- Evidence input: a dictation receipt plus delivered-text span, a fresh recording receipt plus focal span, or no audio.-- Confirmation/policy context supplied by the trusted adapter. Reuse must not allow arbitrary callers to assert automatic approval.--A `DictationReceipt` contains a recording UUID, generation, ASR model identity, raw transcript revision, original token timings, delivery ID and the transformation mapping to delivered text. Each edit stage records span mappings where reliable. Rewritten or ambiguous regions are explicitly unmappable. Ranges use named coordinate systems: UTF-16 for text, integer sample offsets for audio, global encoder-frame offsets for features. Never pass a bare range with an assumed unit.--An accepted `PronunciationExample` contains:--- Stable example/event/entry IDs, source recording and original token span.-- Audio asset reference, sample rate/channel format, focal sample range and context range.-- Embedding values/dimension, acoustic model revision, feature-extraction/pooling version and normalization convention.-- Actual heard text and intended spelling, provenance and alignment/quality measurements.-- Policy state and creation time. Quality measurements are not mislabeled probabilities.--Keep distinct examples; do not count retry copies or the same source occurrence as multiple independent recordings. A computed prototype is a cache derived from examples and versioned by entry revision/model identity. Do not persist only its average and throw away its provenance.--## Reusing the actual recording efficiently--1. Capture starts immediately through the existing pipeline. Learning adds no wait before the first PCM.-2. During dictation, existing pronunciation matching continues to reuse each ASR chunk's encoder output. This matching is independent of enrollment.-3. When correction tracking is enabled, finalize a bounded temporary recording receipt without awaiting disk work on the insert path. The receipt covers earlier words too: keeping only the newest 15 seconds cannot learn a correction near the start of a two-minute recording.-4. Retain temporary evidence for the correction-observation window under explicit age, count and byte budgets. A short lease protects an accepted operation from eviction. Budget exhaustion/expiry returns evidenceUnavailable, never waits indefinitely. History recording remains a separate preference and consumer; do not steal its consume-once snapshot.-5. On a confirmed correction, resolve the exact source occurrence and crop its word/phrase with the context needed by the encoder. Prefer compatible retained features when available. Otherwise run one bounded encoder-only pass on the original context window in the background. No second encoder pass is required on every dictation.-6. Persist the accepted focal clip plus necessary bounded context and focal boundaries. The context and extractor identity matter: embedding a tiny isolated crop can differ from embedding that word in its original sentence. Store enough evidence to reproduce the chosen extraction. Do not retain an entire dictation permanently for a single word.-7. Discard temporary recording evidence when the bounded observation/lease ends. Removing an example deletes its audio when no other example references it.--Retention limits must be explicit configuration and tested; the service may not silently remove earlier audio and then attach a same-spelled later occurrence. Sensitive source audio must not appear in logs or ordinary dictionary text exports. Existing audio-history opt-out must not be silently reinterpreted as agreement to permanent full-recording storage; learning retention is an explicit product policy.--## Results and one-example eligibility--Prepare/commit outcomes are explicit, with no permanently pending branches:--| Outcome | Meaning |-|---|---|-| learned | Spelling, accepted sound example and configured text evidence are durably saved and eligible |-| savedTextOnly | Spelling/rule saved; there was no usable audio; never present this as pronunciation learned |-| savedPendingEvidence | Example retained but not eligible yet; include a concrete reason and next action |-| needsConfirmation | Proposed spelling/meaning needs approval before activation |-| needsAudio | Evidence expired, missing or could not be aligned; user may optionally speak once |-| rejected | Unsupported evidence, conflict or invalid request; no active partial writes |-| cancelled | No new active rule; staged artifacts released |--The API accepts one confirmed occurrence. Activation from one example must be justified by evaluation and quality/alignment checks, not by duplicating it three times or replacing the current count gate with a permissive threshold. Strong evidence can activate without three repeats once calibrated; uncertain evidence requests one additional example or remains pending. Existing three-example profiles remain supported during migration.--Text variants and acoustic evidence complement each other. A newly observed alias can be ambiguous common speech, so evidence storage is separate from granting a global unconditional text replacement. Preserve explicitly authored global rules; learned aliases can require acoustic/context support. Never learn from the system's own automatic replacement as if it were a fresh user correction. Homophones require intent/context, not a claim that embeddings can distinguish identical sounds.--## Persistence and event contract--Use a canonical transactional learning repository with versioned entries/examples/alias provenance/learning events. Migrate legacy text entries and pronunciation JSON once with an idempotent version marker; do not leave two independently writable sources of truth. Preserve legacy entry IDs and track missing audio as an explicit legacy state. Use a temporary migration fallback only with a bounded exit and visible failure result.--Stage audio in the same app-support volume, validate content, then atomically rename to its final asset before committing a database reference. A crash before metadata commit leaves an orphan that recovery can remove; an active entry must never point to an uncommitted/missing staged file. Commit the word, examples, alias policy and event receipt together. Startup recovery resolves interrupted transactions and staged/orphan files under a bounded cleanup policy.--Publish a narrow `dictionaryLearningCommitted(revision, changedEntryIDs)` event once after durable success. Its consumers rebuild text-match caches and pronunciation snapshots, coalescing updates. Do not reuse `.parakeetVocabularyDidChange` as the learning event: it has ASR/configuration/UI consumers. Enrolling pronunciation must not implicitly enable boosting, reload unrelated audio hardware or switch the selected model. Trace existing producers/consumers when adapting legacy setters.--Model changes do not compare incompatible vectors. Re-embedding from retained audio is an explicit background migration with a policy/result state; unavailable model/audio keeps the text entry usable without falsely marking acoustic matching ready.--## Implementation sequence--1. Evidence receipt and span-coordinate types; ownership/expiry contract; no automatic additions yet.-2. Extractor API with original context and one-occurrence example storage. Extend ASR/delivery plumbing to retain reliable mappings; keep insertion fast.-3. Transactional learning service and policy results; migrate legacy profile/alias adapters. Replace duplicated three-count gates with the common eligibility result only after one-example evaluation.-4. Route user-approved correction through the API; use the original audio when mapped, with truthful fallback when unavailable.-5. Route fresh voice/manual entry through the same service. Fresh voice becomes an optional source of extra evidence; manual text without a recording cannot manufacture a pronunciation example.-6. Add automatic proposal/approval rules as another adapter after precision validation. Its trigger and UI can evolve without changing extraction/storage contracts.--## Review and verification gates--Long-recording review: source confirms stable matches are retained once, tail candidates replace earlier tail candidates, global offsets reach final token reconciliation, old recording generations cannot publish, and cancelled current preview state is cleared without resetting newer state. Existing evidence is in `scratch/pronunciation-streaming-benchmark/RESULTS.md`: boundary parity, repeated-word/overlap checks, two-minute provider regression and multilingual batch parity. This review does not prove false-positive safety for every accent; previous 34 ms is remaining library processing, not end-to-end insertion latency.--Before enabling correction-based learning, test:--- Same evidence through different UI/API callers produces the same entry/example; retry produces no duplicate example.-- A correction at the first minute and the same word at the second minute binds to the selected occurrence only.-- Formatting, AI rewriting and multiword-to-one-word corrections preserve a known mapping or reject acoustic learning; never guess.-- Missing/expired audio yields a truthful text-only or needsAudio result.-- Saving without audio never reports learned; saving one genuine example never counts it as three.-- Persist failure/crash/restart, stale proposal revision, cancel, delete during preparation and retraction leave no partial active entry or lost unrelated examples.-- Model mismatch, duplicate events, incompatible embeddings and rejected proposals cannot become active matches.-- Both approved correction and future automatic adapters pass the same conformance suite; neither changes boosting, microphone lifecycle, history preferences, live text or other entries as a side effect.-- Original recorded speech is tested against target-present, target-absent/confusable and already-correct speech across accents. Report recall AND false substitutions before selecting activation thresholds.-- Measure correction preparation separately from dictation stop latency, and repeat long-recording tests after adding evidence retention. Test bounded memory/disk, expiry and cleanup during rapid new recordings.--No automatic-learning behavior or audio-retention change was implemented as part of this design review.diff --git a/docs/design/original-audio-learning-implementation.md b/docs/design/original-audio-learning-implementation.mddeleted file mode 100644index 947e13ae..00000000--- a/docs/design/original-audio-learning-implementation.md+++ /dev/null@@ -1,82 +0,0 @@-# Original-audio correction learning--Implementation work, September 20, 2026. The existing correction UI now schedules original-audio learning after an approved Add Only or trained-replacement save. The broader API proposal in `dictionary-learning-api.md` remains a future contract, not a claim that every proposed migration or UI adapter is implemented.--## Implemented path--1. Parakeet returns original word timings separately from rewritten output. Normal dictation retains an immutable PCM receipt only when correction learning is enabled. History audio ownership is independent. Boosted output cannot supply trustworthy provenance and falls back to text-only learning.-2. External delivery gives the correction tracker that exact receipt. The selected UTF-16 edit maps to its original occurrence; unchanged lexical content maps by ordinal, while edited text requires unique surrounding anchors. Ambiguous rewrites, invalid timing and expired evidence are rejected.-3. The tracker crops up to 14.88 seconds of original context on a utility task before presenting the existing popup. It never searches for a same-spelled occurrence elsewhere after alignment fails.-4. The existing approval saves the text rule immediately. `DictionaryAudioLearningService.learn(entry:evidenceID:evidence:)` schedules optional encoder-only extraction, reusing the loaded matching Parakeet encoder when available and loading the recorded model only as a fallback. This API accepts immutable evidence, not UI views or microphone controls.-5. The bounded worker cancels when an exclusive audio activity starts and retries after it ends. Four pending clips, a 120-second deadline and one active extraction bound memory and work. Unsupported, expired, failed or over-budget work leaves the approved text correction intact. Logs never contain dictated text or audio.-6. `PronunciationDictionaryStore.learnOriginalAudio` writes local PCM metadata before atomically activating its embedding in the profile index. It links entry/event/recording IDs, original occurrence, observed text, model and extractor version. Repeated event IDs and repeated source occurrences do not count as additional examples. A retry reports whether it inserted anything, so cancellation cannot retract an older successful event.-7. Entry snapshots and store revisions reject stale completion. Deletion removes associated audio. Retraction removes only the corresponding example. Valid-index startup cleanup removes aged unreferenced audio left by interrupted writes. Raw clips are excluded from ordinary dictionary exports; profile backups preserve embeddings and provenance, not clip files.-8. One original approved occurrence is eligible through the same policy used by both short and incremental dictation. Existing manual enrollment still requires three examples. No sample is copied to satisfy that count.--The temporary receipt accepts recordings up to 15 minutes and expires after 120 seconds. This is a memory bound, not the model's 15-second input limit. Longer recordings currently retain text-only correction learning. Stored context clips are Float32 little-endian, 16 kHz mono. At most ten examples per profile are retained; there is no global disk quota yet.--## Combining evidence--Known observed variants retain their approved text fallback. Acoustic matches for original-audio profiles require cosine score 0.70 when the recognized phrase matches a known variant, or 0.85 for a new variant. These are conservative experimental thresholds, not probabilities or universally calibrated guarantees. A near tie between different intended labels within 0.05 is rejected. The two strongest labels per word are indexed so conflict checks do not compare every candidate with every other candidate. Changed intended meanings cannot reuse original-audio evidence by merely retaining the entry UUID.--An initial experiment required acoustic confirmation before applying a learned text alias. Real-speech tests showed a substantial recall regression, so that design was removed. A weak acoustic score does not establish that a familiar text correction is wrong. The current combination allows either mechanism to recover a miss by the other. Global text-alias ambiguity is not solved by this change.--## Evidence and limits--- 62 affected app tests passed together, including the real two-minute streaming regression, real-audio save/reuse, repeated-occurrence alignment, cancellation/retry, expiry, invalid evidence, deletion, imports and conflicting matches. All eleven learning tests passed again after review, followed by focused retry/encoder-reuse and stale-meaning checks.-- Encoder-only extraction reproduces the normal encoder's embedding exactly on the same real audio context and releases prepared handles after success/cancellation. Two XCTest cases plus eleven matcher/index tests passed.-- Controlled ASR-error injection verifies that text recovers an acoustic miss, audio recovers an unseen text variant, and unrelated speech stays unchanged. This is wiring regression evidence, not a speech-accuracy benchmark.-- Real FLEURS evaluation: 27 available clips, eight languages, 536 timed words. Eleven repeated targets produced 26 cross-clip trials; five longer clips were excluded. Reference-to-ASR word alignment supplies evaluation labels. Full search, using a separate context re-encode for enrollment, scored text-only 19 true/2 false substitutions, acoustic-only at 0.70 scored 3 true/1 false, and the current combination scored 19 true/2 false. There were 21 target and 547 non-target word opportunities. The combined method preserved text recall but did not beat it on this small set.-- Most repeated targets in that set are common words, not personalized names. Speakers were not constrained to match enrollment. It cannot establish same-user accent robustness or general custom-name accuracy. More realistic held-out corrections are still required before claiming superiority or tuning the novel-variant threshold.-- Isolated reconciliation on a ten-minute/1,200-token fixture averaged 1.42 ms for one profile, 1.46 ms for ten, and 6.50 ms for 1,000. It measures cached matches to text, not ASR/search or whole Stop latency. The real original-audio background round trip took about 120 ms, including model loading/persistence and up to 10 ms polling granularity; it is outside the delivery path. Reusing the already-loaded encoder measured 40.7 ms for the same ten-second context, returned identical vectors, and preserved the next transcription.-- Earlier paired ten-minute streaming benchmark remains 46.109 ms off versus 62.467 ms on with 1,000 profiles, a 16.358 ms mean difference. The new end-to-end live-microphone overhead has not been remeasured. See `scratch/pronunciation-stage-profile/ON_OFF_STOP_OVERHEAD.md`.--Evaluation scripts and raw outputs: `scratch/original-audio-learning/evaluation/`. They are local research artifacts, not production app assets. There is no guarantee of perfect accuracy, no new UI, no model-weight training, no enabling of vocabulary boosting, and no migration of every legacy voice-training adapter in this patch.--Validation status: scoped service lint is clean. Full-source format and strict lint ran; restoring unrelated formatting left 623 pre-existing lint findings, with none on the changed tracked code lines. The signed private FI build is the local packaging check; it is not a production bridge/release gate.--## Composition regression follow-up--A verified failure showed that `fluid -> Fluid Voice` expanded an already-correct acoustic output into `Fluid Voice Voice`. The text matcher now protects completed occurrences of a rule's own output when that output contains a partial trigger. Ordinary rules retain the existing fast path. Tests cover independent uncorrected occurrences, capitalization, word boundaries, literal replacement text, and a combined sentence where text-only and acoustic-only each miss a different occurrence. This is deterministic composition proof, not a new field-accuracy claim. All 65 affected app tests passed, and the signed private FI build succeeded.---## Approved-path and same-speaker follow-up--The production correction detector, original-occurrence resolver, existing Add Only session, background encoder and isolated durable store now run together in a real-audio integration test. Detection alone creates no pronunciation profile; approval saves the text rule and then exactly one linked enrollment. Dependency injection leaves the existing UI call unchanged. All 67 affected app tests passed together with no failures or skipped tests.--A separate real 60-second speech experiment enrolled the first occurrence and excluded its entire 14.88-second window from subsequent searches. Later NVIDIA and AI occurrences scored 0.877 and 0.914. A later Jensen occurrence scored 0.779, showing that the 0.85 novel-variant threshold can still miss useful matches; the known text fallback remains necessary. A broad, poorly aligned NVIDIA span scored 0.754 and correctly failed the novel-variant threshold. These labels are ASR-derived, not independent human ground truth, so this is diagnostic evidence rather than word-error-rate proof.--The experiment also found a concrete false edit: Jensen's scored 0.884 against Jensen and could lose its possessive. Original-audio matching now preserves straight or curly apostrophe possessives unless an approved observed variant explicitly taught their removal. Existing possessive labels are not doubled. This is a narrow English possessive safeguard, not a general inflection model. Tests cover both preservation and explicit removal.--Raw experiment: scratch/original-audio-learning/evaluation/personal-trials.json and Sources/PersonalProof/main.swift. No thresholds were relaxed from this small sample.---## Automatic activation follow-up--The final consumer audit found that saved original-audio profiles were still gated by Advanced Preview. Approved original-audio profiles now participate automatically while automatic dictionary learning is enabled, even with Advanced Preview off. Manual-only acoustic profiles remain behind Advanced Preview. Pinned offline options and meeting policy do not inherit automatic matching.--The provider takes a bounded profile snapshot from the store actor on the first transcription call of a recording, after microphone capture has started. Recording reset invalidates that snapshot so a newly approved word is available next time. Empty or ineligible profiles do not switch dictation to the pronunciation path. Short, word-timing and long incremental paths share profile selection; original evidence with a changed intended label is rejected before search, rather than relabelled.--The real-audio approval regression now starts with an empty profile snapshot, approves and learns the correction, resets for the next recording, and verifies actual replacement in short, word-timed and 60-second incremental dictation with Advanced Preview off. It also checks that disabling automatic learning and Advanced Preview restores baseline ASR. This repeated-recording proof is functional validation, not held-out recognition accuracy.--Validation: 76 dictionary/pronunciation and meeting-policy tests passed together, plus the separate production meeting-provider isolation test. Scoped provider lint is clean; full-source formatting and strict lint ran with existing repository violations preserved. The signed private FI build succeeded. Debug pronunciation timings are not treated as optimized latency measurements.---## Reproducible evaluation--The evaluation executables, comparison script, commands and machine-readable baseline now live in tools/DictionaryLearningEvaluation. A fresh Release run of both executables reproduced the saved results exactly. Model files, audio and large acoustic vectors remain external local inputs.--The later real Huang occurrence was transcribed as Hong Kong and produced no acoustic hit above 0.70 from its earlier enrollment. This is an important unresolved example of the mean-pooled encoder's limitations; no threshold was lowered to make it pass. The multilingual combined result still equals text-only (19 true, 2 false substitutions) rather than exceeding it. Improvement on held-out personalized names remains an open acceptance gate, despite functional approval-to-reuse and composition regression tests passing.---## Local model loading safety--Fallback extraction now uses AsrModels.loadLocalOnly rather than the normal recoverable model loader. The normal loader can remove a cache and re-download after a load error; optional background correction learning must not do that. The new API accepts only local file URLs, validates installed files, checks cancellation between loads, and propagates missing/corrupt-model errors without repairing the installation. The existing text correction survives failure.--Forty library tests passed, including missing-file preservation, remote-URL rejection and real-audio embedding equivalence. Offline evaluation tools use the same local-only API. This changes model loading behavior, not embeddings or acceptance thresholds.--The Huang diagnostic isolated the miss: searching every window length from 1 to 24 frames kept the best score at 0.681. Trimming the enrollment to 60 percent raised it to 0.707, still below the 0.85 novel-variant gate, and narrowed the match to part of the ASR phrase. Neither adjustment is shipped; the evidence does not support a safe general accuracy improvement.--App validation after the loader change: all 68 affected app tests passed, scoped learning-service lint is clean, and the Release interview evaluation output exactly matches the preceding loader. Both dependency lockfiles and both manifests now reference the same companion revision.--The signed private FI build also passed after local-only loading, and the installed app passed strict deep signature verification. Unrelated Feedback work and local dependency overrides remain untouched.diff --git a/docs/dictionary-correction-filter.md b/docs/dictionary-correction-filter.mddeleted file mode 100644index 25a33e14..00000000--- a/docs/dictionary-correction-filter.md+++ /dev/null@@ -1,27 +0,0 @@-# Automatic correction identification--Automatic learning now requires one word on each side of the edit. Manual dictionary entry and existing replacements are unchanged.--The observer still collects edits and waits for a pause. `AutomaticDictionaryCorrectionDetector` expands the accumulated edit to token boundaries; `DictionaryCorrectionEditPolicy` checks eligibility before suggestion frequency counting, audio preparation, or either learning prompt. The negative evidence resolver also checks this policy directly before validating the original accepted match.--## Policy--- Reject whitespace-separated phrases and punctuation-separated text such as `bar,baz` or `bar/baz`.-- Keep internal apostrophes and hyphens for names.-- Reject symmetric English inflection patterns: `s`, sibilant `es`, consonant `y` to `ies`, possessive `'s`, and regular `ed`/`ing` for stems of at least four letters, including final-e removal.-- Preserve insertion-only spelling repairs, substantially different single words, accents, other scripts, and deliberate capitalization. Existing negative learning still rejects case-only changes.-- No dictionary lookup, model inference, network work, new observation, or persisted settings.--## Limits and false negatives--Text alone cannot distinguish a plural from every name repair: `Luca` to `Lucas` looks like a plural and is suppressed. Short stems are exempt to retain repairs such as `Jo` to `Jos`. This is not complete morphology: irregular changes, doubled consonants, and other languages are not inferred. No general edit-distance threshold is used because recognition can produce very different spellings of names. Manual entry remains available for filtered corrections.--The word boundary is lexical, not language-specific segmentation: unspaced scripts are preserved. Compound names with hyphens are allowed. A user pausing mid-edit can still produce an ambiguous single-word candidate; explicit confirmation remains necessary.--## Verification and replacement--`Tests/run_dictionary_correction_tests.sh` compiles the production detector and policy against isolated surrounding data types. It checks rejection and retention examples, observer endpoint eligibility, accumulated typing, undo, punctuation, and edits outside the dictated range. It does not simulate Accessibility notifications or timers.--`Tests/run_dictionary_matcher_experiment_tests.sh` additionally exercises real negative evidence provenance and confirms phrase/plural changes cannot create negatives.--To change filtering, replace `DictionaryCorrectionEditPolicy.allows`. To remove this policy, remove its calls from the detector and negative resolver; the observer, timers, existing dictionary, and matcher remain independent. The detector retains the separate single-word requirement.diff --git a/docs/dictionary-matcher-experiments.md b/docs/dictionary-matcher-experiments.mddeleted file mode 100644index 7c3ed063..00000000--- a/docs/dictionary-matcher-experiments.md+++ /dev/null@@ -1,62 +0,0 @@-# Dictionary matcher experiments--All options live under **Settings → Experimental → Dictionary matching experiments**, are searchable, and default to off. This is an optional test implementation, not a production accuracy claim.--## Correction flow--1. Parakeet accepts an acoustic match and actually replaces a spoken word with a dictionary label.-2. The provider attaches the accepted occurrence's entry ID, source word range, model/profile identity, and normalized audio features to that dictation's short-lived learning context.-3. After external text delivery, the existing correction observer sees the user edit the inserted label.-4. Only a unique, complete label in unchanged delivered text can be linked. No mapping means no negative example. Repeated labels, expired contexts, AI rewrites, partial edits, case-only edits and punctuation-only edits are ignored. Ordinary edits to a dictionary entry are not evidence of a spoken false positive.-5. The correction overlay asks **Was this a wrong match?** Choose **That Was a Wrong Match** only when a different word was spoken. A spelling/style edit is not automatically a false positive.-6. Confirmation stores only that occurrence's audio features. It does not add a text replacement, modify a positive enrollment, or enroll the corrected text as a new word.-7. With negative comparison enabled, future matching can veto a close match to the confirmed mistake. A single negative does not necessarily generalize to other mistakes.--Collection works with the positive whole-pronunciation experiment or the existing legacy edge matcher, and only for occurrences that reach the acoustic replacement path. It does not watch arbitrary edits or retroactively mine history. The existing correction observer requires Accessibility support in the receiving app. Internal dictionary playground edits are not automatically connected to this external correction observer.--## Independent switches--| Switch | Behavior |-|---|---|-| Compare the whole pronunciation | Original three positive training recordings; normalized frames, ordered alignment, calibrated mean and lower-quartile checks. Missing reference audio falls back to existing matching. |-| Learn from confirmed wrong matches | Offers the wrong-match confirmation after an attributable correction. Does not itself change acceptance decisions. |-| Use saved wrong-match examples | Optional veto after an otherwise accepted candidate. No examples is a no-op. It never creates a new acceptance. |-| Clear wrong-match examples | Deletes the separate example store and invalidates older pending saves. Leaves dictionary entries and positive recordings untouched. |--Turning all three switches off restores the pre-existing matcher configuration. The existing independent `DictionaryEdgeMatchingEnabled` preference is preserved. No preferences are enabled by this implementation.--With experiments enabled, new voice enrollments retain their original training audio locally so the positive frames can be rebuilt. Existing words without that audio keep their prior matcher until re-recorded. Negative correction learning itself persists features only, not PCM or corrected text. When automatic positive learning is off, the correction observer does not retain the full dictation PCM for negative learning.--## Algorithm and compatibility--- Positive matcher: existing Parakeet encoder, exact-length inputs, RMS .05/peak .95 normalization with gain cap 32. Reference-frame-weighted DTW, .25 time band and .05 stretch penalty. Best-reference calibrated mean ≥ .70 and lower quartile ≥ .55. These are research-selected values, with known noise/timing limitations.-- Negative veto: symmetric temporal similarity to the saved mistake ≥ .75 and greater than the best positive by > .05. This is deliberately conservative for one-example learning; it is not the earlier larger, labeled-example-bank research result.-- Reference identity includes model, extractor version, label, enrollment audio identities and vectors. Renaming, retraining or changing models makes old negatives ineligible.-- At most 6 negative examples per word and 32 total; file size ≤ 32 MB. Duplicate confirmation IDs are ignored. Corrupt optional banks produce no veto; saving reports failure rather than silently overwriting corrupt data.-- Confirmation checks the entry/profile before and after the store write. Cancellation, disabling collection, changed profiles, expiry, and clearing invalidate stale work.-- Separate store: `~/Library/Application Support/FluidVoice/dictionary-negative-examples-v1.plist`.-- Existing loaded Core ML models are reused. No dependency edits, new model downloads, decoder pass, or opening-audio delays. Frame extraction and comparison run off the main actor. Reference caches are bounded to 8 profiles; candidate cuts retain the existing 3-per-word/24-total bound.-- Candidate discovery and ambiguity handling remain in the existing pipeline. Temporal acceptance is passed separately from the original score, preserving ranking rather than replacing every score with a constant.-- Only supported Parakeet/Apple Silicon paths run the encoder. Other providers and missing evidence retain existing behavior. Cross-speaker accuracy and older-device runtime have not been established.--## Replace or remove--The independent decision layer is `DictionaryExperimentalMatcher.swift`. The encoder adapter is `DictionaryTemporalEncoder.swift`. Negative provenance/resolution/storage is isolated in `DictionaryNegativeExamples.swift`; settings are in `DictionaryMatcherExperimentSettings.swift`.--Integration points are the final and incremental refinement paths in `FluidAudioProvider`, learning context transport in `DictionaryLearningEvidence`/`ASRService`, and the existing correction tracker/session/overlay. `DictionaryPronunciationExperiment.enabled` enables the edge discovery path only for the positive comparator, not for collection alone. Remove these hooks and the four modules to remove the feature; no positive-store migration is required. The optional negative file can be cleared independently.--## Validation and manual test--Run `DEVELOPER_DIR=/path/to/Xcode.app/Contents/Developer sh Tests/run_dictionary_matcher_experiment_tests.sh`. An optional research-artifact directory argument additionally compares all 392 retained research cut decisions against the production scorer. Tests use only temporary storage and do not change real preferences or recordings.--Build with `INSTALL_APP=0 LAUNCH_APP=0 sh build_with_FI_incremental.sh` (appropriate installed Xcode selected, development signing preserved). This work has not installed or launched a replacement app.--Manual test after installing a test build:--1. Enable whole-pronunciation matching and wrong-match learning. Use a word with three saved training recordings. Keep negative comparison off to collect without changing rejection.-2. Dictate into an external editor with Accessibility support. Correct an actual dictionary replacement to another word and leave the edited word. Confirm **That Was a Wrong Match** in the overlay.-3. Enable negative comparison and try the same mistake plus genuine pronunciations of the dictionary word. Check both rejected mistakes and unintended missed correct words.-4. Toggle comparison off to compare behavior; clear the examples to reset. Rename/retrain a word and verify old negatives no longer affect it.-5. Check the overlay at narrow widths and Settings in light/dark appearances. These visible flows and live Accessibility delivery have not been manually verified in this change.--Verified for this change: private FI Release build passed with install/launch disabled; 816 isolated component/parity checks passed; production scorer matched all 392 archived cut decisions; production encoder frames matched all six original enrollment extractions exactly; strict lint passed for the four new implementation files. Nineteen unrelated tracked WIP patches were unchanged. Full app XCTest, installed UI, live correction observation and older-Mac testing were not run. Existing replay diagnostics remain the original matcher and now show that limitation when experiments are enabled.diff --git a/docs/research/pronunciation-long-recording-stage-costs.md b/docs/research/pronunciation-long-recording-stage-costs.mddeleted file mode 100644index 4ceb89dd..00000000--- a/docs/research/pronunciation-long-recording-stage-costs.md+++ /dev/null@@ -1,25 +0,0 @@-# Long-recording finalization stage review — 2026-09-19--Measured the actual 120-second all-after-stop path with one pronunciation prototype, Parakeet v3, no vocabulary boosting, on Apple M5 Max / 128 GiB. Fixture: public jensen-60s.wav repeated twice, 1,920,000 samples at 16 kHz, 1,571 transcript characters. Nine stable windows plus one tail window. Two warmup runs, seven measured Release runs. Instrumentation is in a scratch copy of the exact companion library source; production sources were not instrumented. All profiled runs produced identical text.--| Stage | Median milliseconds |-|---|---:|-| preprocessor | 12.48 |-| encoder | 245.48 |-| decode | 277.84 |-| pronunciation | 8.20 |-| mergeAndText | 0.32 |-| other | 0.78 |-| Full finalization | 545.73 |--Pronunciation includes 1.26 ms copying existing encoder features across all ten windows; that is nested, not an extra additive stage. The remainder builds/scans pronunciation candidates. Encoder and decoder together account for roughly 96% of this workload. No second acoustic encoder is run for matching. Stage medians are separately aggregated, so their sum can differ slightly from the median total.--Preprocessor includes mel/input preparation; encoder includes acoustic feature inference and its prepared-buffer management. Decode includes token prediction, extraction and associated buffer release. Merge/text covers overlap merging and final result construction. Other is per-run residual bookkeeping, PCM append/copy/chunk preparation and actor-call overhead. Model initialization is outside the measurement.--The earlier 546 ms to 34 ms result compares all work after stop with reusing stable windows already processed during dictation. It is not a 16x reduction in total compute, and it is not microphone-to-keystroke latency. Raw app delivery, dictionary text regexes and AI cleanup are outside this library benchmark. The prior 100-prototype workload used duplicate durations/vectors; diverse dictionary durations can cost more.--Evidence: scratch/pronunciation-stage-profile/results.json and results.log; scratch/pronunciation-stage-profile/Sources/Profile/main.swift; instrumented library under FluidAudioProfiled. The unchanged baseline and lifecycle/accuracy limitations are documented in scratch/pronunciation-streaming-benchmark/RESULTS.md.--Review checks already run on the implementation: two-minute app parity and stale-recording regression, repeated-word/overlap unit checks, 14 library unit tests, eight-language/three-pattern batch parity, Release boundary/cancellation assertions, signed FI install. Scoped lint has zero violations. Required whole-repo format/lint was run: unrelated formatter edits were restored; full lint reports 623 existing violations outside these two source files. No unrelated Feedback edits are included in the dictionary commits.--Companion FluidAudio commit: 97ed23265098a78a09378659063d52dee908f9e0. The app commit pins that revision; the local working tree retains a development override. The library commit must be published before a fresh machine can resolve the app pin. No pushes performed.diff --git a/tools/MEETING_ADMISSION_B3_DEVELOPMENT_EVAL.md b/tools/MEETING_ADMISSION_B3_DEVELOPMENT_EVAL.mddeleted file mode 100644index 16cdc9aa..00000000--- a/tools/MEETING_ADMISSION_B3_DEVELOPMENT_EVAL.md+++ /dev/null@@ -1,118 +0,0 @@-# B3 development ablation — existing recordings--Date: 2026-09-08 (local), updated 2026-09-09 with five controlled recordings. Status: **insufficient for threshold selection**.--## Outcome--The available evidence does not support enabling microphone admission. The current temporal detector produces no supported duplicate windows, so its ablation is identical to accepting every measured frame. Speech activity shows a tradeoff but cannot establish near-end speech: settings that preserve nearly all frames in the coarse scripted region admit hundreds of known-negative frames, while stricter settings still admit negative frames and reject many frames inside that coarse region.--No threshold was selected or frozen. The installed app, runtime configuration, original recordings, transcripts and speaker profiles were not changed. This evaluator reads existing saved text locally only to count words and never emits text, speaker identifiers, segment identifiers, audio or embeddings.--## Controlled-recording update--Five user-directed development recordings were captured with the installed app and analyzed locally: playback only; normal and quiet speech without playback; normal speech over playback; and two sequences of quiet replies over playback. The user confirmed that playback used speakers, their speech entered through the microphone, and nobody else was speaking nearby. No headphones were used. All ten audio tracks completed without a dropped sample, discontinuity or recorded failure. The longer playback-only recording produced four visible microphone-attributed segments containing 49 words even though the user reported staying silent. This is a controlled acoustic-playback failure example; it does not by itself identify the exact hardware/software leakage path.--The B1 temporal detector found no `duplicateSupported` window in any controlled recording. The playback-only recording produced three isolated `duplicateCandidate` windows, but never the required stable three-window sequence. Temporal-only admission therefore still accepts every measured negative frame.--At the existing diagnostic speech threshold of 0.85, the controlled playback-only recording admitted 10/600 measured negative frames. The coarse positive regions admitted 137/445 measured frames: 24/42 in clean normal speech, 16/36 in clean quiet speech, 63/135 in normal speech over playback, and 34/232 in the whole-recording quiet-replies-over-playback region. These positive denominators include pauses and, for the overlap recordings, playback-only time; their acceptance is not recall. The transcript localized the three normal-over-playback repetitions into coarse regions, but this is not independent ground truth. The quiet-over-playback recording remains recording-level coarse truth.--Across all eight development recordings, threshold 0.04 admitted 681/2,291 known-negative frames and 507/606 coarse-region frames. Threshold 0.85 admitted 41/2,291 known-negative frames and 258/606 coarse-region frames. This is a real tradeoff, not a calibration result: frames are correlated, coarse regions contain pauses, and there are still zero independently frame-labelled positive recordings. No threshold is selected and suppression remains off.--Current aggregate result after recording the corrected speaker/microphone provenance: `/private/tmp/fv-admission-b3-controlled-v3.json`. The five numeric-only sidecars are `/private/tmp/fv-speech-control-{playback,normal,quiet,normal-overlap,quiet-overlap}-v1.json`. Audio and transcript content stayed local and no installed app was changed.--## Ground truth that is actually available--The development annotation manifest is `meeting_admission_b3_annotations.json`:--- `3774ED4C…`: user reported no near-end speech for the recording.-- `3B9AC1A8…`: user reported playback-only for the recording.-- `88E3BD44…`: user reported speaking only the supplied script near the end. The 0–208 s interval is treated as known-negative. The 208–250 s interval is only a **coarse script region**; its individual speech and pause frames are not labelled. The remaining tail is unlabelled.--These are failure-selected, post-hoc development recordings. There are two pure-negative recordings, one recording containing both a negative interval and a coarse script region, and zero independently frame-labelled positive recordings. The cohort counts intentionally overlap where one recording supplies both kinds of interval.--## Current saved transcript inventory--For microphone segments fully contained in annotated intervals:--| Annotation | Segments | All words | Currently visible words | Visible speaker slots per session |-| --- | ---: | ---: | ---: | ---: |-| Known-negative intervals | 21 | 331 | 324 | 4 |-| Coarse script region | 3 | 89 | 89 | 1 |--“Visible” reuses the saved pipeline's own `isLikelyEcho` output and is reported only as current-output inventory, not as independent validation. The 89 coarse-region words are not verified for correctness. Full-containment is used to avoid assigning a boundary-crossing segment wholesale; boundary/outside exclusions are separately counted in the JSON result. This dataset happened to have no excluded microphone transcript segments.--## Frame evidence and descriptive sweep--There are 1,691 measured 256 ms frames in known-negative intervals and 161 measured frames in the coarse script region. Another 21 labelled frames have explicit unknown speech evidence; two frames straddle annotation boundaries and 39 fall outside annotations. All denominators and exclusions are present in the result.--| Diagnostic VAD threshold | Known-negative frames accepted | Negative acceptance | Coarse-region frames accepted | Coarse-region acceptance |-| ---: | ---: | ---: | ---: | ---: |-| 0.01 | 1,078 / 1,691 | 63.7% | 161 / 161 | 100% |-| 0.04 | 549 / 1,691 | 32.5% | 160 / 161 | 99.4% |-| 0.05 | 464 / 1,691 | 27.4% | 158 / 161 | 98.1% |-| 0.10 | 282 / 1,691 | 16.7% | 145 / 161 | 90.1% |-| 0.50 | 66 / 1,691 | 3.9% | 123 / 161 | 76.4% |-| 0.85 | 31 / 1,691 | 1.8% | 121 / 161 | 75.2% |-| 0.95 | 20 / 1,691 | 1.2% | 121 / 161 | 75.2% |--Coarse-region acceptance is **not speech recall**: some rejected frames can be pauses, and some accepted frames can be leaked playback. Frame observations are recurrent and temporally correlated, so 1,691 frames are not 1,691 independent trials. Recording-level uncertainty cannot be meaningfully estimated from two pure-negative recordings and no independently labelled positive recording.--The “speech plus no supported duplicate” ablation equals speech-only on these inputs because B1 produced zero supported locks. The accept-all control and current temporal-only policy both accept all 1,691 measured negative frames. The full sweep is included for diagnosis only; it does not rank candidates or publish a selection gate. It does not project frame decisions into word removal, WER or speaker identity changes.--## Evaluator integrity--`meeting_admission_b3_eval.py` validates:--- canonical session IDs and safe sidecar basenames;-- session-byte hash agreement with each sidecar;-- pinned B1/B2 versions, 4,096/16 kHz frame geometry, 0.85 diagnostic threshold and identical cached model file hashes;-- finite probabilities, explicit reasons for every unknown probability, known temporal states and annotation ends within recorded duration;-- non-overlapping, finite annotation intervals and exclusive output creation.--It reports measured/unknown/boundary/outside frames explicitly. Transcript segments crossing boundaries or outside annotation are counted separately rather than silently disappearing. Empty sessions/annotations are rejected. The cached model artifact dictionary is pinned to fingerprint `259aec29878cbca1118f4e4fa1db126676286c90b65903266545f50e9ac4512d`, and sidecar duration must agree with an independent calculation from session audio-chunk PTS. Eleven unit tests cover interval containment, overlap/traversal/empty-input rejection, confusion counts, privacy, threshold inventory, unknown probability handling, duration calculation and transcript boundary accounting.--The original three-recording aggregate was `/private/tmp/fv-admission-b3-dev-v7.json`. The controlled eight-recording aggregate `/private/tmp/fv-admission-b3-controlled-v3.json` supersedes it for current development analysis. Reproduce from the repository root:--```sh-python3 tools/meeting_admission_b3_eval.py \- --annotations tools/meeting_admission_b3_annotations.json \- --sessions-root "$HOME/Library/Application Support/FluidVoice/Meetings" \- --sidecar-root /private/tmp \- --output /private/tmp/fv-admission-b3-dev-new.json-```--The command above is documentation for a human shell; the evaluator itself never expands or emits the sessions path. Use a fresh output filename because overwrite is refused.--## Next evidence gate--The next useful input is an independently timed controlled recording with frame-level labels for:--1. clean normal and quiet speech without playback;-2. playback-only intervals;-3. short quiet replies during playback;-4. sustained normal speech during playback;-5. deliberate pauses and missing/reference-transition intervals.--This first positive must remain development data. After any feature/threshold changes, separate recordings by speaker/device/environment are required for held-out evaluation. Until then, suppression and profile filtering remain off. If a stronger temporal feature or model dependency is proposed, that is a separate reviewed scope.--## Review and artifact identity--Kimi K3 adversarially reviewed the annotation/evaluator/test source in read-only mode. Its first pass found silent denominator drift, hard-coded frame duration, unreported boundary exclusions, overlapping cohort-count ambiguity and selection-flavored output. All were fixed: unknowns/exclusions are counted, frame geometry is schema-derived and pinned, cohort fields explicitly describe overlap, and candidate lists were removed. A second pass found empty annotations, consistency-only model hashes and sidecar-only duration bounds; all were fixed with nonempty-input checks, a pinned model fingerprint and independent session-duration verification. The final post-fix verification returned **no findings**. No audio, transcript content, model weights or secrets were sent to the reviewer.--Original three-recording SHA-256 values are retained below for audit history:--```text-annotations 95a0a11bf12400e22ec8d00de36397d491e90520fcc5b7e61dc3135fa0b4e955-evaluator 886187f58085207802cae8f713d72206f70272d767a9dbb3d15fe16ec7e301b1-tests 93dfb7673a9dbf60775e8e351d5781f4cd940b1a5a09f88eb2e202430d58b5a5-result 26d01f04a558ee88c26bb105451e42a74987048f7b3c923dc3635f98d5ef0c9e-```--Controlled-update SHA-256:--```text-annotations 0837a3d5935a7ca945217c2fe869863ad39268a2ac7a1ce9ea0fbe8b400280cb-evaluator cc4bfa8647a60c5d7cd3422f0defe8959ffe9fd59a24485fc6f10d0b80d2a108-tests 93dfb7673a9dbf60775e8e351d5781f4cd940b1a5a09f88eb2e202430d58b5a5-result 875437729970fbc763d589a49961cd2045a30153f1a0dc9ea8d72df368e7655d-```diff --git a/tools/MEETING_ADMISSION_CONTROLLED_RECORDING.md b/tools/MEETING_ADMISSION_CONTROLLED_RECORDING.mddeleted file mode 100644index e1b6f7f4..00000000--- a/tools/MEETING_ADMISSION_CONTROLLED_RECORDING.md+++ /dev/null@@ -1,63 +0,0 @@-# Simple controlled microphone-admission recordings--Make five separate FluidVoice meeting recordings. Each should last roughly 20–30 seconds and test only one condition. Exact timing is unnecessary.--Use the currently installed app and your normal microphone settings. Use speakers if that is how the false captions occurred. For playback tests, use the same speech-heavy podcast or video each time.--## Recording 1 — playback only--1. Start the podcast or video through your speakers.-2. Start a new FluidVoice meeting recording.-3. Stay completely silent for about 20–30 seconds.-4. Stop the recording.--## Recording 2 — normal speech, no playback--1. Stop all playback.-2. Start a new recording.-3. In your normal voice, read this twice:-- “The blue lantern is beside the window. I will review the document after lunch.”--4. Stop the recording.--## Recording 3 — quiet speech, no playback--1. Keep playback stopped.-2. Start a new recording.-3. In a naturally quiet meeting voice, read this twice:-- “A small silver key rests under the green notebook.”--4. Stop the recording.--## Recording 4 — normal speech over playback--1. Start the podcast or video through your speakers.-2. Start a new recording.-3. In your normal voice, read this twice:-- “The blue lantern is beside the window. I will review the document after lunch.”--4. Stop the recording, then stop playback.--## Recording 5 — quiet replies over playback--1. Start the podcast or video through your speakers.-2. Start a new recording.-3. In a naturally quiet voice, say these phrases with a short pause between them:-- “Yes.” “Not yet.” “I agree.” “Please continue.” “That is correct.”--4. Repeat the five phrases once, then stop the recording and playback.--## When finished--Tell Codex:--- approximately when you completed the five recordings;-- whether you used speakers or headphones;-- whether anyone else spoke nearby;-- whether any recording differed from the instructions.--Codex will locate the five local sessions and analyze them offline. No recording will be sent to an external reviewer. These are development recordings; separate held-out recordings are still required before enabling suppression.diff --git a/tools/MEETING_AEC3_DIRECT_IMPLEMENTATION_PLAN.md b/tools/MEETING_AEC3_DIRECT_IMPLEMENTATION_PLAN.mddeleted file mode 100644index 18af41a9..00000000--- a/tools/MEETING_AEC3_DIRECT_IMPLEMENTATION_PLAN.md+++ /dev/null@@ -1,599 +0,0 @@-# Direct WebRTC AEC3 implementation plan--Status: implementation-ready; adversarial review passed with no P0/P1. This is a local planning artifact and-must remain untracked. It does not authorize a commit, a new recording, or generated evidence.--## Outcome--Ship WebRTC Audio Processing Module's AEC3 directly in the pre-production macOS app for the-explicitly classified speaker-route ScreenCaptureKit online-call path. The application-audio-callback is the far-end/render stream;-the paired microphone callback is the near-end/capture stream. On speaker routes, only the-AEC-processed microphone reaches the microphone writer or live microphone ASR. If AEC cannot-provide an ordered, valid output, recording continues with the raw microphone marked-`unprotected`, and microphone transcription stays closed.--This is not another evidence stage or a shadow deployment. The implementation is enabled by-default on the applicable, positively identified speaker ScreenCaptureKit path once its source,-tests, and build checks pass. An ambiguous/settling route remains raw and unprotected; it does not-enter AEC on the assumption that “unknown” means speaker.-The existing VoiceProcessingIO path and in-room recording path remain unchanged.--## Non-negotiable decisions--1. **Process before both consumers.** `ScreenCaptureMeetingRuntime` may continue to write and tee- the original application track immediately, but it must never write or tee a speaker-route- microphone callback before the AEC pipeline decides that callback's output. Persisted mic audio- and live mic ASR therefore see the same processed/bypass decision.-2. **Preserve original timestamps.** AEC output carries the source microphone PTS and duration.- AEC algorithmic/acoustic delay is not subtracted from the recording timeline. No zero padding,- extrapolated audio, or retimestamping is used to manufacture a pair.-3. **One serial owner.** Extraction, format conversion, render/capture joining, APM calls, resets,- and output ordering have one serial executor. `ProcessReverseStream` always precedes- `ProcessStream` for a 10 ms pair, and no APM call is concurrent with another APM call.-4. **Physical protection and software processing are different facts.** Add- `MeetingMicrophoneEchoProtection.softwareEchoCancelled`; do not relabel AEC output as- `acousticallyClosed` or `voiceProcessed`. Existing values keep their meanings.-5. **Fail closed for speech evidence.** An unmeasured/late render region, invalid PCM, discontinuity,- format change, queue/resource bound, bridge error, metadata persistence failure, or stream- rebuild immediately closes live mic admission and starts/preserves an `unprotected` era.- Raw audio may still be recorded in timestamp order; it may not reach live or batch transcript.-6. **No optimistic startup.** A speaker-route era starts `unprotected`. It can be promoted to- `softwareEchoCancelled` only after a fresh engine has completed the warm-up contract below and- the new era has been durably written. Every reset repeats this process.-7. **No shadow product path.** Do not retain a parallel raw mic file, dual-ASR path, analytics- upload, user-media fixture, remote flag, or default-off feature flag. A DEBUG-only environment- bypass is acceptable for diagnosis, and must degrade to the existing raw/unprotected behavior.-8. **Attest the clock contract at runtime.** Being outputs of one `SCStream` is necessary but not- sufficient evidence that numeric PTS values are sample-accurately interchangeable. Before a- speaker epoch can promote, both streams must pass the continuing common-clock attestation in- Phase 3. PTS equality alone never opens transcript admission.-9. **No scope creep.** Do not change microphone election, VPIO recovery, diarization, speaker- identity, text echo heuristics, admission thresholds, or the offline Stage 0/0.5 analyzers.--## Runtime data flow--```text-one SCStream, one shared serial callback queue- .audio callback --------+--> original application writer + application live ASR- |- +--> extract/downmix 48 kHz render PCM --+- |- .microphone callback --> extract/downmix 48 kHz capture PCM -----+--> bounded PTS joiner- |- render 10 ms -> AEC3 <- capture 10 ms- |- timestamped processed or raw mic output- |- ordered provenance/output committer- | |- microphone writer gated microphone live ASR-```--The application writer remains byte-for-byte on its current path. The AEC branch receives a copy.-The microphone writer moves behind the AEC output committer. There is no second persisted raw mic-track.--## Change map--Expected production changes (names may be refined without changing ownership):--- `Vendor/WebRTCAudioProcessing/`- - pinned, minimal upstream source snapshot;- - upstream `LICENSE`, `PATENTS`, `AUTHORS`, and all required third-party notices;- - a local Swift package containing the upstream C++ and the C bridge;- - a machine-readable revision/source-file hash manifest and a deterministic refresh script.-- `Sources/Fluid/Services/Meeting/AEC/FluidAECBridge.h/.cc`- - preferably live inside the vendor package's bridge target, not the app target;- - C ABI only; Swift never imports WebRTC C++ headers.-- `Sources/Fluid/Services/Meeting/AEC/MeetingAECModels.swift`- - frame, format, state, failure, reset, provenance, and bounded diagnostics values.-- `Sources/Fluid/Services/Meeting/AEC/MeetingAECPCMAdapter.swift`- - immediate `CMSampleBuffer` copy/extraction, explicit mono downmix, and output synthesis.-- `Sources/Fluid/Services/Meeting/AEC/MeetingAECStreamJoiner.swift`- - the bounded common-PTS 10 ms slicer and discontinuity detector.-- `Sources/Fluid/Services/Meeting/AEC/MeetingAECProcessor.swift`- - single-owner bridge lifecycle, warm-up, resets, and processed/bypass output.-- `Sources/Fluid/Services/Meeting/AEC/MeetingAECOutputCommitter.swift`- - ordered writer/provenance/live-ASR handoff and fail-closed persistence.-- `Sources/Fluid/Services/Meeting/MeetingCaptureEngine.swift`- - attach both SCK audio outputs to one serial callback queue; integrate lifecycle and route reset.-- `Sources/Fluid/Services/Meeting/MeetingModels.swift`- - add `softwareEchoCancelled` and optional AEC provenance to capture eras.-- focused tests in `Tests/FluidDictationIntegrationTests/` and C++ package tests.-- `Package.swift` and `Fluid.xcodeproj/project.pbxproj` only for the local package/product and new- Swift production/test sources.--Do not turn `MeetingReferenceSynchronizer`, `MeetingStage05SCKFrameAdapter`, or-`MeetingStage05MockAECSeam` into production streaming code. They are bounded offline/DEBUG seams-with different ownership and memory contracts. Reuse their tested vocabulary and invariants, not-their whole-array implementation.--## Phase 1 — pin and integrate the dependency--Use Google's WebRTC source, not an unpinned third-party binary. Select one exact upstream git-commit that is current when implementation begins and record the full commit hash. Never track a-moving branch, semantic range, Homebrew path, system-installed dylib, or downloaded binary without-a checksum.--The implementation agent should first build a tiny standalone bridge executable against that-commit for both `arm64` and `x86_64`. Use WebRTC's GN dependency graph to identify the complete-transitive source set for the built-in Audio Processing Module/AEC3. Then vendor the exact required-source and license set as a local Swift package so a clean repository build does not depend on a-developer's WebRTC checkout or network access. Avoid shipping the rest of libwebrtc.--The package contract is:--- static linkage only;-- macOS 15 minimum matching FluidVoice;-- C++17 or the exact newer standard required by the pinned revision;-- exceptions and RTTI configured exactly as required by upstream, recorded in the manifest;-- AEC dump/file output, tests, and examples absent; peer-connection, codecs, video, and network- targets are absent only when they are not members of the pinned APM/AEC3 target's actual GN- closure. Never call a manually subtracted graph the complete closure;-- use the pinned revision's actual GN closure as truth for protobuf: set the supported build option- that removes protobuf when the closure permits it; if an otherwise required APM target retains a- protobuf runtime dependency, vendor that exact minimal source and its notices while compiling- out and unlinking every dump/write entry point. A runtime-disabled file API is not sufficient;- verify the forbidden dump/write symbols are absent from the final binary. Never delete a- required edge merely to claim “no protobuf”;-- no public C++ headers outside the package;-- no duplicate Abseil/field-trial symbols exported by the final app;-- reproducible source hashes and deterministic architecture settings;-- clean `arm64` and `x86_64` compile/link checks, plus a universal app linkage check;-- attribution copied into the app's shipped third-party notices if the app already has such a- surface; otherwise add the smallest compliant bundled notice resource.--If a minimal source package cannot be made cleanly reproducible, stop at this phase and report the-dependency blocker. Do not silently substitute an old CocoaPod, a full unsigned WebRTC framework,-or an ad-hoc local archive.--## Phase 2 — C ABI around APM/AEC3--Expose an opaque engine with a narrow, allocation-free hot-path ABI. A representative interface is:--```c-typedef struct FVAEC3Engine FVAEC3Engine;--typedef enum {- FV_AEC3_OK = 0,- FV_AEC3_INVALID_ARGUMENT,- FV_AEC3_INITIALIZATION_FAILED,- FV_AEC3_PROCESSING_FAILED,- FV_AEC3_NONFINITE_OUTPUT-} FVAEC3Status;--typedef struct {- uint64_t render_frames;- uint64_t capture_frames;- uint64_t resets;- int32_t estimated_delay_ms; /* -1 when unavailable */- float residual_echo_likelihood; /* NaN when unavailable */-} FVAEC3Stats;--FVAEC3Engine *fv_aec3_create_48k_mono(void);-void fv_aec3_destroy(FVAEC3Engine *engine);-FVAEC3Status fv_aec3_reset(FVAEC3Engine *engine);-FVAEC3Status fv_aec3_process_10ms(- FVAEC3Engine *engine,- const float render[480],- const float capture[480],- float output[480],- FVAEC3Stats *stats);-const char *fv_aec3_upstream_revision(void);-const char *fv_aec3_configuration_id(void);-```--Implementation requirements:--- build with `BuiltinAudioProcessingBuilder` and enable only `config.echo_canceller.enabled`;-- explicitly keep preamp, capture-level adjustment, AGC1/2, high-pass, noise suppression,- transient suppression, and voice detection disabled for the first integration;-- configure mono capture and mono render at 48 kHz; float samples are deinterleaved and clamped to- `[-1, 1]` only after rejecting NaN/infinity;-- invoke `ProcessReverseStream` before `ProcessStream` inside the single function so Swift cannot- invert the order;-- do not provide `set_stream_delay_ms` from callback arrival time or the offline synchronizer's- configured lag. Only add a delay hint later if it can be derived from the actual render/capture- hardware timing definition required by WebRTC;-- rebuild/reinitialize the APM object on reset rather than assuming `Initialize()` erases every- adaptive state relevant to a route/stream epoch;-- return standard processed capture audio. `GetLinearAecOutput()` can be exposed in C++ fixture- tests, but it must not create a second product path or silently substitute a 16 kHz signal;-- allocate scratch buffers at creation. No heap allocation, logging, file I/O, lock acquisition,- callback into Swift, or exception may cross the process function;-- make destroy/reset/process idempotence and invalid-pointer/length behavior explicit and tested.--## Phase 3 — streaming PCM and PTS joiner--Use one serial `DispatchQueue` as the `sampleHandlerQueue` for both `.audio` and `.microphone` on a-given `SCStream`. That establishes one callback-arrival order without claiming that arrival time is-media time. Every accepted callback is copied before return; application writer/live delivery may-still happen immediately after that copy.--Normalize each AEC input to non-interleaved mono Float32 at exactly 48 kHz:--- application audio uses an explicit arithmetic channel average;-- microphone input uses explicit downmix too, even though current paired SCK is observed as mono;-- require valid numeric PTS, positive frame count/duration, internally consistent ASBD geometry,- finite samples, and duration within 1.5 source samples of `frames / sampleRate`;-- support the PCM layouts ScreenCaptureKit actually emits using `AVAudioPCMBuffer` copying. Any- sample-rate change or unsupported layout is a reset/bypass boundary, not a reinterpret cast;-- if conversion is ever needed, keep one converter per input format and account for its complete- algorithmic delay. The initial SCK configuration requests 48 kHz, so a non-48-kHz callback may- conservatively bypass rather than introduce an unmeasured resampler.--The joiner first locks both sources to 48 kHz; any other rate is absent/unknown and resets. It then-chooses `T` as an actual first common source-sample PTS, never a rounded wall-clock boundary, and-maps later PTS onto a 48 kHz integer grid relative to `T`. Rounding error may be at most one sample.-It stores bounded per-stream interval queues and emits only complete common 480-sample windows. A-per-generation `MeetingAECClockAttestor` must establish and then continuously check all of the-following without looking at audio content or callback arrival time:--- both buffers came from the same accepted `SCStream` object and explicit runtime generation;-- both use valid numeric `CMTime` values with the same epoch and 48 kHz sample geometry;-- each source is independently monotonic and contiguous on its own PTS/sample-count line;-- over the half-open span `[T, T + 96_000/48_000)`, valid original render and capture callback- intervals provide every one of the 96,000 source samples exactly once. Starting at the same `T`,- those samples form exactly 200 adjacent 480-sample slots without edge rounding or loss. Received- callback count and native callback block size are not coverage substitutes;-- each source keeps one epoch anchor and cumulative sample count. For every callback boundary, its- actual PTS must be within one 48 kHz sample of `anchorPTS + cumulativeSamples / 48000`; error is- always measured against the anchor, never accumulated from individually tolerated deltas;-- the inter-source grid residual stays within one sample for the whole attestation interval and on- every later frame. A change in timescale alone is harmless after exact `CMTime` conversion, but- an epoch, slope, intercept, coverage, or residual failure demotes and resets.--This is a runtime contract check inside the direct implementation, not a Stage 0.5 evidence gate.-It neither estimates acoustic delay nor calls `set_stream_delay_ms`. A generation that cannot-attest stays raw/unprotected for its lifetime; it does not “succeed” merely by processing 200 API-calls. “Exact common 10 ms pairs” always means adjacent covered timeline slots, not 200 successful-calls collected across holes. For each output window after the current grid is attested:--1. take the exact render interval for `[n, n + 480)`;-2. take the exact capture interval for `[n, n + 480)`;-3. call the bridge once, which consumes render then capture;-4. synthesize a fresh mono Float32 `CMSampleBuffer` with the capture window's original PTS and a- 1/48000 per-sample duration;-5. submit processed and original-capture forms to the output committer so it can make a durable- protection decision without losing the raw fallback.--For a slice beginning `k` samples inside an original callback, derive its PTS exactly as-`callbackPTS + CMTime(value: k, timescale: 48000)` and require its entire coverage to come from the-original callback interval(s). Never mint a 10 ms timestamp from an output ordinal, callback-arrival time, or an assumed continuous counter.--Distinguish measured digital silence from missing data. A render callback whose actual PCM samples-are zero is valid far-end silence and is fed to APM normally; an interval not covered by any valid-render callback is unknown and must never be zero-filled merely because microphone PTS continued.-Unknown capture is emitted raw/unprotected. A true render or capture PTS gap, overlap, backward-step, format change, stream identity change, source sequence gap, non-finite input, or bound breach-ends the current epoch. Flush complete older windows, classify incomplete capture as-raw/unprotected, reset the APM, and start a new grid/attestation at the next well-formed pair. If a-macOS/SCK revision suppresses zero-valued render callbacks, the affected mic spans correctly stay-unprotected rather than converting absence into invented evidence. At stop, emit any retained-capture tail as raw/unprotected; do not pad it to 10 ms.--Initial hard bounds (constants with unit tests):--- at most 64 callback blocks or 24,000 samples (500 ms at 48 kHz) retained per input;-- at most 100 ms of capture waits for matching render PTS;-- at most one sample of PTS quantization disagreement;-- zero tolerance for overlapping accepted samples or non-finite PCM;-- the hot path must not enqueue onto an unbounded dispatch queue.--If the shared callback queue plus synchronous 10 ms processing cannot meet the performance gate,-move APM work to a bounded worker with explicit capacity and an ordered raw-fallback handoff. Do not-replace the bounds with an ordinary unbounded `queue.async` backlog.--## Phase 4 — durable provenance and ordered output--Extend `MeetingCaptureEra` with optional, backwards-compatible AEC provenance:--```swift-struct MeetingAECProvenance: Codable, Equatable, Sendable {- var upstreamRevision: String- var bridgeConfigurationID: String- var sampleRateHz: Int- var frameDurationMilliseconds: Int-}-```--`softwareEchoCancelled` admits transcript; `unprotected` does not. Old manifests continue to-decode exactly as they do now, and no migration rewrites a historical era as software-protected.--The output committer is the sole component allowed to pair a microphone sample with an era change.-It preserves this ordering:--```text-close live gate synchronously- -> enqueue/persist era transition on the microphone writer's serial order- -> enqueue the corresponding mic sample(s)- -> open live gate only after successful promotion persistence- -> offer only protected sample(s) to live mic ASR-```--Add a writer API that accepts an era transition and sample in the same writer-queue transaction, or-an equivalent sequenced command API. Do not race the current async `updateTrackMetadata` against a-separate `enqueue`. A demotion persistence failure is handled like the existing fail-closed route-metadata failure: keep in-memory state unprotected, keep live closed, emit one terminal interruption,-and stop capture so the returned track cannot resurrect optimistic provenance.--On speaker routes, a fresh AEC epoch has a two-second warm-up: 200 consecutive successful paired-10 ms calls, a passing common-clock attestation spanning those frames, no-discontinuity/reset/bound failure, and finite output. Warm-up output is persisted as processed audio-but its era remains `unprotected` and it is not sent to live mic ASR. The first post-warm-up frame-begins a durably persisted `softwareEchoCancelled` era. This is an engineering stabilization rule,-not a claim that optional APM statistics prove privacy.--On a positively classified headphone route, preserve the existing raw `acousticallyClosed` path;-do not construct or route through the AEC processor/committer, and verify byte-identical sample and-era behavior against today's `ScreenCaptureMeetingRuntime`. The VPIO runtime is a separate class-and likewise never constructs or calls the AEC components; verify its `voiceProcessed` samples and-eras are byte-identical at the integration seam. On all other ScreenCaptureKit routes, raw/bypass-output is `unprotected`.--## Phase 5 — `ScreenCaptureMeetingRuntime` integration and lifecycle--Add a pure `MeetingAECOutputRouteClassifier` with three dispositions:--- `physicallyClosed`: the existing positive headphone test returns `acousticallyClosed`;-- `supportedSpeaker`: two matching snapshots separated by the existing 0.75 s settle positively- identify the built-in speaker (`deviceExists && isBuiltIn && !isHeadphonesDataSource`, no- headphone terminal, not Bluetooth). Additional external speaker types require their own future- positive test; they are not inferred from absence of a headphone flag;-- `ambiguous`: missing, changing, aggregate, Bluetooth, virtual, external-unknown, or otherwise- unclassified. This stays byte-identical raw and `unprotected` and never constructs AEC.--Arm route observation before settling/classifying and before `startCapture`. Snapshot the route-revision with the first route value, wait, then accept the second value only if it matches and the-revision is unchanged. Under `stateLock`, reserve `.constructingAEC(routeGeneration:)`; build the-candidate outside the lock; commit it only if the generation and reservation still match. Any-route callback invalidates the reservation synchronously. A successful commit enters `.aecReady`,-not `.aecActive`. Recheck the route/stream/lifecycle token immediately before `startCapture`; while-the async start is in flight, every callback still takes the raw/unprotected path. Recheck again-after `startCapture` returns and enter `.aecArmedAwaitingFormats` only if the token and ready state-are unchanged. The shared callback queue keeps all mic raw/unprotected while it validates the first-actual render and capture format/CMTime observations. Only after both validate and the token remains-current may it atomically enter `.aecActive` and begin a fresh joiner/attestation with subsequent-samples. Thus no concurrent first frame can observe an active state before the first-format gate.-A failure at either recheck or first-format gate atomically clears `.aecReady`/armed state to-`.rawUnprotected`, detaches the candidate, and then destroys it serially; it must not leave a ready-shell pointing at an object pending destruction. A stale candidate is never called. An AEC object-may therefore become active only for the same route generation that produced both stable snapshots-and survived the whole start/first-format interval.-Physically closed and ambiguous paths preserve the original microphone bytes from their first-accepted callback.--Pin startup invalidation to a finite event set: output/input route revision, SCStream generation or-replacement, runtime stop/teardown generation, and the first accepted callback's format/CMTime-validation. Unit-test each event immediately before and after snapshot two, reservation, candidate-creation, commit, pre-start recheck, callbacks during async start, start completion, post-start-recheck, both first-format observations, and active transition. Format/CMTime failure while armed-demotes before calling the candidate and destroys/resets in serial order.--At construction:--- create the shared callback queue before attaching outputs;-- settle/classify the route; initialize the AEC pipeline before `startCapture` only for- `supportedSpeaker`, while keeping transcript state unprotected;-- for `physicallyClosed` and `ambiguous`, keep the existing direct mic writer/gate path and do not- create an AEC committer, joiner, or engine;-- route both output registrations to the same queue;-- provide the pipeline with the exact current stream generation, writers, event handler, and live- handler. It must not retain application/window names or other PII.--In `didOutputSampleBuffer`:--- `.audio`: copy/feed render to AEC first, then preserve the current original application writer- and live tee;-- `.microphone`: offer only to the AEC pipeline; remove the current direct microphone writer and- direct live tee;-- keep the current stream-identity/stopping check before either action.--On output-route notification:--- close live admission synchronously at the existing conservative boundary;-- synchronously set the disposition to `ambiguous` so every callback during settling takes the- byte-identical raw/unprotected path, then destroy/reset the old AEC in serial order;-- persist `unprotected` during settling; a newly supported speaker then creates a fresh engine and- repeats attestation/warm-up, while an ambiguous route stays raw/unprotected;-- retain the existing 0.75 s settling and require two matching snapshots before selecting either- `physicallyClosed` or `supportedSpeaker`; a nonmatching/unknown result remains ambiguous;-- do not allow the old raw-route code to reopen a speaker route merely because AEC exists;-- reset on both input and output route changes, because either invalidates the adaptive path.--On unexpected `SCStream` stop/rebuild:--- demote and reset before starting the replacement stream;-- use a new stream generation and reject callbacks from old/pending streams;-- do not carry render FIFO, capture FIFO, warm-up count, delay estimate, or APM state across the- rebuild;-- promote only after the replacement stream's own warm-up;-- retain existing bounded rebuild attempts and interruption events.--On normal stop:--1. mark the runtime stopping and stop route observation;-2. stop SCK capture;-3. drain the shared callback queue;-4. flush complete pairs, emit capture tails raw/unprotected, and drain pending era commits;-5. destroy APM and return from runtime stop;-6. only then may `MeetingCaptureEngine` stop the writers and the live coordinator.--No pipeline task or callback may reference a writer after runtime stop returns.--## Phase 6 — tests before app installation--### C++ bridge tests--- create/destroy/reset and wrong pointer/geometry cases;-- silence, render-only, capture-only, finite maximum-amplitude, and non-finite rejection;-- deterministic delayed/attenuated linear echo after warm-up;-- near-end-only preservation and double-talk preservation;-- exact render-before-capture counters and reset clearing adaptive state;-- upstream revision/configuration strings match the vendored manifest.--For a deterministic 10-second synthetic fixture (`capture = nearEnd + delayedGain * render`), use-disjoint warm-up and measurement regions. In the final measurement region require at least 6 dB-echo reduction relative to raw capture, no NaN/infinity, no output beyond `[-1, 1]`, and no more-than 3 dB near-end RMS attenuation during double-talk. Treat these as regression floors, not a-claim about real-room performance.--### Swift unit tests--- stereo planar/interleaved render downmix and mono capture extraction;-- invalid ASBD, nonnumeric PTS, duration mismatch, NaN/infinity, rate/layout changes;-- arbitrary callback sizes split/reassembled into exact 480-sample frames;-- mic-first and render-first arrival produce identical PTS-ordered output;-- gaps, overlaps, backward PTS, one-sample boundary tolerance, >1-sample rejection;-- continuously delivered zero-valued render PCM is processed as measured far-end silence without- demotion, reset, or warm-up restart;-- missing/late render coverage never becomes synthesized silence or protected mic;-- common-clock attestation locks 48 kHz and chooses an actual common sample PTS `T`; exactly 96,000- original samples per source cover `[T, T+2)` once and form 200 adjacent slots, with each callback- checked against one fixed anchor/cumulative-count equation within one sample for the whole span- and continuously afterward;-- native 512-frame (and other non-480) callback blocks reblock without rounding `T`, losing edge- samples, or satisfying coverage through callback counts;-- a 20 ms missing render interval cannot hide inside a percentage allowance or promote after 200- nonadjacent successful calls;-- equal-looking PTS from different epochs/generations and stable-but-skewed/drifting grids cannot- promote even after 200 successful bridge calls;-- every eligible frame records render then capture and never crosses an epoch;-- reset on route, format, stream generation, and discontinuity;-- 64-block/24,000-sample/100-ms bounds and deterministic overflow behavior;-- incomplete stop tail is raw/unprotected with its original PTS;-- processed and raw fallback buffers own their bytes beyond the callback lifetime.--### Provenance/output integration tests--- speaker startup writes an initial `unprotected` era;-- exactly 199 good frames do not promote; frame 201 begins only after the 200-frame warm-up;-- 200 calls without a passing clock attestation remain unprotected;-- persistence completion precedes first live mic offer;-- processed samples, never raw source samples, reach writer/live after promotion;-- a bridge failure atomically closes live, begins `unprotected`, writes raw in order, and resets;-- a persistence failure stops capture and the final in-memory track remains unprotected;-- route notification cuts admission conservatively and stale settle tasks cannot reopen it;-- headphones stay byte-identical/raw `acousticallyClosed` and never instantiate AEC; VPIO remains- byte-identical/`voiceProcessed`; speaker return creates a fresh engine and attestation/warm-up;-- startup and route-change decision tables keep missing/changing/Bluetooth/aggregate/virtual/- external-unknown routes raw/unprotected and prevent AEC construction until two settled snapshots- positively identify the supported speaker;-- route/stream/lifecycle/first-format token tests invalidate candidate construction before/after- snapshot two, reservation, candidate creation, commit, pre-start recheck, callbacks during async- start, start completion, post-start recheck, each first-format observation, and active transition;- `.aecReady`/`.aecArmedAwaitingFormats` callbacks stay raw/unprotected, two validated formats are- required before active, and every failure clears the state before detached candidate destruction;-- stream rebuild rejects stale callbacks and cannot reuse old APM/FIFO/warm-up state;-- batch admission rejects every turn intersecting warm-up/bypass eras and admits only wholly- protected eras under the existing indivisible-turn rule;-- legacy manifests and all existing VPIO/in-room tests remain unchanged.--### Build and runtime checks--- top-level Swift package build/test where supported;-- focused integration test target, then the complete meeting test suite;-- Debug and Release app builds for the active architecture;-- explicit `x86_64` compile/link build even on Apple Silicon, followed by `lipo -info`/`file` and- `nm` checks proving both slices and no unresolved/duplicate WebRTC symbols;-- Release binary scan proving the DEBUG bypass/diagnostic harness is absent or inert;-- Instruments/signpost benchmark in Release: after warm-up, p99 bridge time below 5 ms per 10 ms- pair, no single frame at or above 10 ms, bounded retained sample/block counts, and no monotonic- memory growth over a 30-minute synthetic stream;-- `git diff --check`, source/license manifest verification, and a forbidden-artifact scan.--Do not create or use a new user recording to pass these checks. If a later real-room listening or-ASR evaluation is wanted, request it as a separate task after this code implementation.--## Phase 7 — direct enablement, rollback, and commit discipline--After all checks pass, the normal ScreenCaptureKit online-call speaker path constructs AEC3 by-default. There is no shadow mode and no release cohort. Keep one DEBUG-only-`FLUIDVOICE_DISABLE_AEC3=1` escape hatch that selects raw/unprotected recording for local diagnosis;-it must never mark the mic protected.--Rollback is one code revert: restore direct mic writer/gate handling in-`ScreenCaptureMeetingRuntime`, remove the local package/product and AEC sources, and leave the-existing VPIO/headphone/in-room behavior untouched. Existing manifests with-`softwareEchoCancelled` remain decodable even if a later build no longer produces that value.--The implementation commit allowlist is production source, tests, Xcode/Swift package wiring, the-vendored source/revision manifest, and legally required notices. Explicitly exclude this plan,-router transcripts, generated reports, WAV/audio/video, DerivedData, `.build`, profiler data, and-all pre-existing unrelated dirty-tree files. Do not stage or commit anything automatically unless-the user separately asks.--## GPT-5.3-Codex-Spark execution protocol--Implementation may be delegated through the local Codex CLI with:--```sh-codex exec \- -m gpt-5.3-codex-spark \- --approve-for-me \- -C /Users/shreeram/Projects/FluidVoice \- "Implement only Phase N of the reviewed direct AEC3 plan. Preserve the dirty tree. Do not commit."-```--Run one bounded phase per session, review its diff locally, and test it before sending the next-phase. The agent may edit only the phase's allowlisted source/tests/package files. It may not edit-this plan or existing Stage 0/0.5 artifacts, install/launch the app, create a recording, access-secrets, publish, or commit. Dependency network fetches and any app install remain explicit host-operations under the repository's normal approval/signing policy.--Before implementation starts, capture a path-specific `git status --short` baseline. After every-agent turn, compare the status and diff to that baseline, revert no user files, and reject any-out-of-scope output rather than staging it.--## Definition of done--Implementation is complete only when:--- the pinned source and legal provenance rebuild cleanly without an ambient WebRTC install;-- the APM bridge performs one render-before-capture 48 kHz mono call for each eligible 10 ms pair;-- every protected epoch has a continuously passing common-clock attestation; numeric PTS equality- or successful APM return codes alone can never promote it;-- the speaker-route microphone writer and live ASR never receive raw audio during a protected era;-- no missing data, reset, warm-up frame, failure frame, or stale callback is marked protected;-- route/rebuild/stop transitions are durably ordered with samples and leave no background owner;-- synthetic echo/double-talk, all bounds, failure-injection, legacy, and batch-admission tests pass;-- arm64 and x86_64 Debug/Release linkage and the Release real-time/memory gates pass;-- adversarial review has no unresolved P0/P1 finding; and-- only the explicit implementation allowlist is eligible for a later user-requested commit.--## Adversarial review disposition--The standard router served Grok 4.6 read-only and reported `editedTree=false` on every completed-attempt. The initial repository-reading attempt and the first self-contained retry reached the-router's primary time limit; the latter still returned a usable partial `REVISE` verdict. Bounded-delta rechecks then completed normally.--The review's blocking findings and dispositions were:--- **Missing render versus silence:** the first draft risked continuous demote/reset behavior if SCK- omitted far-end callbacks. The final contract distinguishes zero-valued samples delivered inside- valid callbacks (measured silence) from uncovered time (unknown). Unknown is never fabricated as- zeros or protected. The suggestion to infer zeros solely from continuing mic PTS was rejected as- unsafe; tests cover both cases.-- **PTS was not a clock proof:** successful APM calls and numerically equal PTS can no longer- promote. The final contract adds the fixed-anchor, same-generation `CMTime` attestation with- complete original-sample coverage over `[T,T+2)`, exact adjacent reblocking, one-sample total- residual, and continuing checks.-- **Warm-up coverage ambiguity:** the draft's 99% allowance was removed. All 96,000 render and- capture samples must be present exactly once in 200 adjacent slots; non-480 native callbacks and- missing-slot cases are explicit tests.-- **Headphone/startup races:** AEC is constructed only for a positively settled supported speaker.- Ambiguous and physically closed routes remain byte-identical raw. A route-generation reservation,- pre/post-`startCapture` checks, an armed first-format state, and atomic clear-before-destroy rules- close snapshot, construction, async-start, and first-callback races.-- **Dependency closure:** the pinned GN graph, not an aspirational subsystem list, defines the- vendored source. Required protobuf is retained with notices if the pin cannot remove it, while- AEC dump/write code must be compiled out, unlinked, and absent from the final symbol scan.-- **Timestamp provenance:** every 10 ms slice derives its PTS from the original callback plus the- exact source-sample offset; ordinal/arrival/synthetic timestamps are forbidden.--The final delta review returned **PASS**, `P0: none`, `P1: none`, and `editedTree=false`. Its sole P2-was incorporated: post-start state remains armed/raw until both first formats validate, and every-failed recheck clears the ready/armed state before serially destroying the detached candidate.diff --git a/tools/MEETING_DIARIZATION_EVAL.md b/tools/MEETING_DIARIZATION_EVAL.mddeleted file mode 100644index a70974f2..00000000--- a/tools/MEETING_DIARIZATION_EVAL.md+++ /dev/null@@ -1,41 +0,0 @@-# Meeting diarization evaluation--This Phase 0 tool establishes a repeatable local baseline before diarization behavior changes. It-never uploads, rewrites, or copies meeting recordings. User audio, annotations, hypotheses, and-generated reports must stay under the gitignored `benchmark_reports/` directory.--## Set up the corpus--Copy `tools/meeting_diarization_eval_manifest.example.json` to-`benchmark_reports/meeting-diarization/manifest.json`. Add development and held-out fixtures before-tuning. `inventory` fixtures reserve the split without claiming that they are ground truth; change a-fixture to `annotated` only after adding both `referenceRTTM` and `hypothesisRTTM`. An inventory-fixture may record `expectedSpeakerCount`, `observedRemoteSpeakerCount`, a generated-`hypothesisRTTM`, and `runReport`; these reproduce a count defect and fingerprint its artifacts but-remain explicitly unscored until a human reference timeline exists.--RTTM rows use the standard form:--```text-SPEAKER meeting 1 12.340 1.250 <NA> <NA> speaker-1 <NA> <NA>-```--Optional `referenceSpeakerText` and `hypothesisSpeakerText` files are JSON objects mapping speaker-labels to transcript text. When present, the report includes cpWER.--## Run--```bash-python3 tools/meeting_diarization_eval.py self-test-python3 tools/meeting_diarization_eval.py validate benchmark_reports/meeting-diarization/manifest.json-python3 tools/meeting_diarization_eval.py score benchmark_reports/meeting-diarization/manifest.json \- --output benchmark_reports/meeting-diarization/baseline.json-```--Each scored fixture reports primary merge/split and speaking-duration recovery metrics plus DER, JER,-speaker-count error, coverage, and purity. The `comparable` score uses a 250 ms collar and ignores-reference overlap; the `strict` score uses no collar and scores overlap.--Reports contain aggregate metrics and SHA-256 fingerprints of RTTM inputs, not audio or transcript-content. Record ASR provider/model, pipeline version, and normalization configuration in the manifest-for every baseline run.diff --git a/tools/MEETING_MICROPHONE_ADMISSION_PLAN_REVIEW.md b/tools/MEETING_MICROPHONE_ADMISSION_PLAN_REVIEW.mddeleted file mode 100644index 13a1f204..00000000--- a/tools/MEETING_MICROPHONE_ADMISSION_PLAN_REVIEW.md+++ /dev/null@@ -1,75 +0,0 @@-# Kimi K3 review of microphone-admission plan revision 2--Disposition: revision 3 addresses the six plan findings. A subsequent read-only Stage A code-review request in the same OpenCode session timed out at 180 seconds without findings; do not interpret it as approval. Local Stage A validation passed 20 tests.--Read-only review through OpenCode; amended implementation has not been signed off by this review. The tool's dirty-tree listing includes pre-existing work, not a claim the reviewer authored it.--status: success-sessionID: ses_f7bec653effeM3RqWBphVhxcRv-model: fireworks-ai/accounts/fireworks/models/kimi-k3-agent: plan-elapsed: 211.0s-tokens: {"total":74870,"input":1633,"output":1374,"reasoning":8383,"cache":{"write":0,"read":63480}}-cost: $0.448019-changed files:-Fluid.xcodeproj/project.pbxproj | 367 +++++++++++++++++++++- MEETING_AUDIO_PHASE0_RUNBOOK.md | 14 +-- Sources/Fluid/Persistence/KeychainService.swift | 8 +-- Sources/Fluid/Services/FileLogger.swift | 6 +- Sources/Fluid/Services/FluidAudioProvider.swift | 144 +++++++-- .../LiveTranscription/MeetingLiveTrackEngine.swift | 133 +++++++-- .../MeetingMicrophoneCaptureTests.swift | 78 ++++-- 7 files changed, 714 insertions(+), 36 deletions(-)-?? Fluid.xcodeproj/xcshareddata/xcschemes/FluidASRBaseline.xcscheme-?? MEETING_DIARIZATION_V2_IMPLEMENTATION_PLAN.md-?? MEETING_MICROPHONE_ADMISSION_IMPLEMENTATION_PLAN.md-?? MEETING_RELIABILITY_IMPLEMENTATION_PLAN.md-?? MEETING_RELIABILITY_P0_BASELINE.md-?? Sources/Fluid/Services/Meeting/MeetingASRPreparationOwner.swift-?? Sources/Fluid/Services/Meeting/MeetingProcessingConfiguration.swift-?? Tests/FluidASRBaselineHost/-?? Tests/FluidASRBaselineTests/-?? Tests/FluidDictationIntegrationTests/MeetingASRPreparationOwnerTests.swift-?? Tests/FluidDictationIntegrationTests/MeetingProcessingConfigurationTests.swift-?? Tests/FluidDictationIntegrationTests/MeetingProviderOptionsTests.swift-?? fluid_pico_cutB_wingbeat_51s.mp4-?? fluid_pico_cutB_wingbeat_53s.mp4-?? fluid_pico_false_start_10s_prompt.md-?? fluid_pico_false_start_74s.mp4-?? fluid_pico_false_start_prompt.md-?? fluid_pico_false_start_v3.mp4-?? fluid_pico_hero_76s.mp4-?? fluid_pico_sprinter.mp4-?? render_pico.py-?? render_pico_split.py-?? render_pico_v2.py-?? tools/MEETING_DIARIZATION_EVAL.md-?? tools/MEETING_RELIABILITY_P0_ADVERSARIAL_REVIEW.md-?? tools/meeting_reliability_baseline.py-?? tools/test_meeting_reliability_baseline.py--Review complete. Plan rev 2 read against the five permitted source files; findings below, Stage A blockers first.--## Stage A blockers--**1. [High] "Shadow disabled AND enabled" is untestable as written — Stage A defines no enablement mechanism or call site.**-Stage A item 4 specifies a pure shadow decision function with injected evidence, and the exit gate requires behavior unchanged "with shadow disabled AND enabled" — but the `off`/`shadow`/`enforce` mode flag is explicitly Stage D (item 3), and no Stage A item names where the shadow function is invoked (tests only? a debug gate? unconditionally inside `processMicrophoneChunk`?). An implementer must invent the switch, and the cheapest invention is evaluating unconditionally in the live per-chunk path — adding per-turn work and a new failure surface in production alongside the echo scoring `do/catch` at pipeline :1972-2002. Same gap covers the fake temporal-detector implementation (A3): "fake" is undefined, so it could end up wired into the real path returning constants. Minimal correction: state in Stage A that the shadow function and fake detector are invoked only from tests (or a named debug-only gate), are side-effect-free, never persisted, never logged with transcript content, and that any runtime mode flag is out of scope until Stage D.--**2. [High] The legacy-mapping boundary is ambiguous exactly where the dangerous semantics live: the rescue inside `verdict()`.**-A1/A2 say "rename" plus "a clearly named legacy mapping" without stating whether the mapping wraps the existing `verdict()` output or reimplements the decision. The behavior that must survive is not just the `effectiveEcho` truth table (pinned by `testEffectiveEchoMatrix`); it is the scorer-internal rescue, which (a) runs *before* the coverage gate, so it fires even when `scoreableFraction < 0.5` (scorer :285-289); (b) lets NaN gaps under 0.75 s accumulate through without breaking a low run (:262-267); and (c) is denied only by the conjunctive trivial-run test (scoreable coverage AND median ≥ 0.8 AND lowRunFraction < 0.15, :280-283). A mapping written at the segment/`effectiveEcho` level cannot reproduce (a)-(c); a reimplementation can silently drop one. Minimal correction: mandate that Stage A is a mechanical rename of the enum case with zero logic edits to `verdict()`/`effectiveEcho`, and add characterization tests pinning (a), (b), and (c) before the rename lands.--**3. [Medium] The evidence contract omits the identity keys Stage C's shared-centroid exclusion needs.**-The evidence field list (§3) has interval coverage and embedding provenance but no turn/segment key and no diarization observation key. The contamination unit is the chunk-level label cluster: one `Observation` per `microphone:<chunkID>:<label>`, one centroid, shared by every turn with that label (pipeline :1937-1964, :2027), admitted today by text-only `isLikelyEcho` (:720-726). Turn-granular evidence without the observation key cannot express "rejected sibling ⇒ shared centroid ineligible" (C2), and since the contract is Stage A's deliverable, omitting the keys means reworking a test-pinned contract later. Minimal correction: add mandatory identity fields to the Stage A contract — turn key (`microphone:<chunkID>:<index>`), observation key (`microphone:<chunkID>:<label>`), and capture-epoch identifier — noting the one-to-many observation→turn relationship.--**4. [Medium] Adversarial unit cases (A5) have unspecified expected outcomes.**-"Identical real repetition of playback" is scored `echo` and hidden by the *current* code — that is today's behavior, which Stage A must preserve. If the new tests assert the aspirational outcome, they change behavior; if they assert the current outcome as the policy target, they entrench it. Rule 2 ("low explanation never rescues") deliberately inverts the live rescue, so shadow and legacy disagree by construction on every rescued turn. Minimal correction: each A5 case asserts two explicit expectations — legacy-mapping output equals pre-change output, shadow output marked experimental with its own reason code — and the rescue-removal delta gets a dedicated reason code so Stage B's would-suppress accounting isn't dominated by the deliberate inversion.--## Later-stage concerns--**5. [Medium] The temporal detector's "capture epoch" is undefined relative to existing staleness machinery.**-The plan requires freshness/reset on discontinuities but never binds "capture epoch" to `epochBoundaries` (either-track discontinuities, pipeline :1110-1118) or to the ±`blockSeconds` guard intervals the scorer zeroes/masks (:998-1047). If the detector's epoch is narrower than the delay consensus's, duplicate state can survive the clock jump that invalidated the delay estimate — cross-jump correlation presented as fresh support. Minimal correction (Stage B1): define the detector epoch as the intervals between `epochBoundaries`, mandate state reset plus evidence invalidation at those boundaries, and state whether the scorer's guard-interval policy is reused or replaced.--**6. [Low] "Never scored" and "scored but inconclusive" are collapsed today and will pollute Stage B's unknown reporting.**-`computeEchoVerdicts` returns an empty verdicts dict when no delay resolves (:1199-1201), and the call site folds absence into `.unknown` (`signalVerdictByIndex[index] ?? .unknown`, :2041) — indistinguishable from a fully scored inconclusive turn. Stage A's typed evidence can carry the distinguished values in parallel with the legacy-collapsed one, but the plan doesn't require them as separate reason codes; without that, Stage B's "complete unknown/fallback reporting" exit cannot tell a blind scorer (no lock, no reference) from an inconclusive one. Minimal correction: name distinct reason codes for `noDelayLock`, `referenceUnavailable`, `unscoredCoverage`, and `scoredInconclusive` in the Stage A contract, with the legacy mapping defined as their collapse into `.unknown`.--No findings on the evidence calibration claims themselves; per scope, nothing here asserts the detector will work — finding 5's note that the observed 55-70 ms lag is "a hypothesis to test" is the correct posture.diff --git a/tools/MEETING_PLAYBACK_ATTRIBUTION_V2_ADVERSARIAL_REVIEW.md b/tools/MEETING_PLAYBACK_ATTRIBUTION_V2_ADVERSARIAL_REVIEW.mddeleted file mode 100644index 92d329cf..00000000--- a/tools/MEETING_PLAYBACK_ATTRIBUTION_V2_ADVERSARIAL_REVIEW.md+++ /dev/null@@ -1,87 +0,0 @@-# Adversarial review — reference-aware playback attribution plan--Date: 2026-09-09 (local)-Reviewed artifact: `MEETING_PLAYBACK_ATTRIBUTION_V2_IMPLEMENTATION_PLAN.md` revision 1-Result: revision 2 incorporates the supported findings below. No implementation or production approval is claimed.--## Review execution--All reviewers were instructed to operate read-only and were limited to the plan and relevant FluidVoice capture/scoring source. No recordings, transcript content, logs, model weights, credentials, secrets, or unrelated files were included. The dirty-tree summaries printed by the tools describe the pre-existing shared worktree; all successful review results reported no reviewer edits.--| Requested reviewer | Successful result | Notes |-| --- | --- | --- |-| Claude Opus 5 | Orchestrate heavy route reported `claude · opus`; the response identified `claude-opus-5`; 294.5 s; `editedTree=false` | The first broad call hit the orchestration transport's 300 s timeout. A narrower retry completed. |-| Kimi K3 | `fireworks-ai/accounts/fireworks/models/kimi-k3`; 219.7 s; OpenCode plan mode | Completed on the first call. |-| Grok 4.6 | `grok-4.6`; xAI Grok CLI session `9e315fa8-069f-4ef7-9713-a985e2e01a9c` | Two bounded turns ended at their tool-turn limits; a read-only continuation in the same session returned the final review. |--Timeouts and turn-limit exits contained no review findings and were not counted as approval. The completed responses were reconciled against local source and Apple/WebRTC primary documentation.--## Convergent blockers and dispositions--### 1. Test the VPIO render side before adding WebRTC — accepted--Claude and Grok identified that `MeetingMicrophoneCapture` binds/read-backs audio-unit element 1 (input) but not element 0 (output), has no explicit application render source, and persists `voiceProcessingEnabled: true` as a literal after the setter rather than a readback. Kimi independently asked for exact public property IDs before the AGC/bypass trial.--Revision 2 now makes these the first probe: input/output current-device properties, graph/render activity, `isVoiceProcessingEnabled`, bypass, AGC, mute, and ducking state with exact property/scope/element/`OSStatus`. Element-0 force binding is diagnostic-only until route behavior is understood. The plan still treats missing render reference as a hypothesis until hardware results exist.--### 2. Evaluate the existing SCK paired microphone path before AEC3 — accepted--All three reviewers found that the repository already implements one `SCStream` producing selected-application `.audio` plus `.microphone`. This can provide a rawer microphone input and potentially a simpler clock relationship, but neither property is guaranteed by the public API.--Revision 2 adds this as Phase 0 trial C2 and the leading software-AEC input. It requires measurement of processing, clock relationship, latency, and jitter. It also records the critical product constraint: on speaker routes this path is currently `.unprotected`, so it cannot be called behavior-unchanged shadow mode and needs a separately reviewed capture migration before production.--### 3. A selected-application reference is incomplete — accepted with a privacy boundary--All reviewers noted that the microphone hears the full acoustic output while the current reference contains only the selected window/application and excludes FluidVoice. Other processes, notifications, helper processes, volume changes, and output DSP may be missing or transformed. AEC cannot cancel an absent source.--Revision 2 adds explicit reference scope and `referenceScopeLimited` / `referenceCompletenessUnobservable` outcomes, concurrent-other-process and volume-change trials, corpus cases, and fail-open semantics. It also refuses to make a broader full-system reference an automatic product default: full-mix diagnostic capture must be explicitly authorized, ephemeral, not transcribed, and separately reviewed for scope/retention/privacy. Without it, the feature promises only selected-scope playback suppression.--### 4. Do not prefer VPIO output plus AEC3 — accepted--All reviewers agreed that cascading AEC3 after Apple's nonlinear AEC/NS/AGC is the least identifiable path. Low-level intelligible leakage can have little stable linear coherence, so AEC3 may remain inert or damage quiet overlap.--Revision 2 orders the candidates as Apple configuration repair, SCK-paired mic plus AEC3, exclusive raw diagnostic if it adds information, and VPIO plus AEC3 only as a fallback. It adds convergence/ERLE/inertness rejection criteria and forbids tuning around a non-learnable VPIO residual.--### 5. Export both linear and suppressed AEC3 outputs — accepted--Claude and Grok noted that listening-optimized nonlinear suppression can damage quiet double-talk and that `EchoCanceller3` can expose a linear-filter output separately. Revision 2 requires both outputs, pins suppressor/comfort-noise/high-pass/field-trial configuration, and makes the linear output the first ASR-preservation candidate. Neither output is assumed safe until the bake-off.--### 6. Residual speech is not automatically near-end speech — accepted--Grok required the independent multi-band attribution candidate (or equivalent guard) for enforcement rather than making it optional. Revision 2 adopts that requirement. VAD, residual energy, AEC validity, or ASR text alone cannot produce a playback-only/near-end conclusion.--### 7. Restore the parent reliability gates — accepted--Kimi and Claude found that revision 1's suggested 95% reduction and five-point WER margin weakened the existing reliability plan. Revision 2 restores the binding parent gates: zero false accepted mic words/identities on the curated negative regression set, one-point missed-speech/WER non-inferiority margins, 12 negative sessions, 30 annotated minutes per populated positive condition, 100 short replies, recording/device/speaker splits, and recording-level uncertainty. Unscored/fail-open intervals remain in leak totals so abstention cannot pass.--### 8. Time-box and front-load AEC3 build feasibility — accepted--All reviewers warned that a “minimal AEC3 subset” still pulls substantial WebRTC infrastructure. Revision 2 names expected dependency families, requires an out-of-tree reproducible two-architecture smoke artifact before in-tree code, pins field-trial behavior, and defines failure to produce it within an approved time box as an abort outcome rather than permission to vendor the full tree or fetch a mutable binary.--### 9. Tighten synchronizer semantics — accepted--The reviews called out three distinct clocks/timelines, signed acoustic delay, ppm drift, codec priming/remainder, converter delay, multi-channel render policy, and valid samples with synthesized timing. Revision 2 explicitly models those, freezes adaptation across synthesized-timing spans, preserves masks instead of zero-fill, and scopes deterministic equality to the same binary/architecture/configuration.--### 10. Avoid residual-embedding domain drift — accepted with a safer first-release rule--Claude noted that AEC residual embeddings may be out-of-domain relative to existing natural-speech profiles. Revision 2 adds an embedding-domain metric, but does not make a residual embedding the first-release default. Profile learning is limited to independently admitted, verified no-playback intervals using original microphone PCM; overlap residuals do not enroll profiles.--## Findings adopted with modification--### Original-versus-residual ASR disagreement--Kimi proposed retaining an interval when original ASR has words and residual ASR is empty. Applied literally, that would restore the exact playback words a successful canceller removed. Revision 2 instead degrades to `mixedOrUncertain` only when the empty residual conflicts with residual-side speech activity, independent attribution, or timing evidence. Original/residual ASR remains a diagnostic pair; neither wins solely because it emitted words.--### Full-system reference--Claude suggested a second full-system SCK stream as the better AEC reference. Technically it may improve completeness, but silently capturing unrelated applications would expand user-authorized scope. Revision 2 includes an opt-in diagnostic comparison and requires a separate privacy/product decision before any production use. The selected-app-only limitation remains visible rather than being hidden by implementation convenience.--### SCK paired streams and clock sharing--Reviewers described the paired stream as the topology most likely to share a useful clock. Revision 2 does not promote that expectation to fact; Phase 0 measures PTS relationship, latency, drift, and jitter.--## Overall disposition--The three reviews agree on the durable design principles: preserve originals, run post-capture first, fail open, never use VAD/text as source identity, do not lower the B1 correlation threshold, keep live processing out of the first release, and gate speaker-profile learning more strictly than transcript fallback.--They also agree that revision 1 moved to AEC3 too quickly. Revision 2 therefore approves only the Apple/SCK reference probe, synchronizer harness, and conditional out-of-tree AEC3 feasibility spike. It does **not** approve an AEC3 dependency, raw-microphone capture migration, production suppression, profile enforcement, or app reinstall.diff --git a/tools/MEETING_PLAYBACK_ECHO_CANCELLATION_ADVERSARIAL_REVIEW.md b/tools/MEETING_PLAYBACK_ECHO_CANCELLATION_ADVERSARIAL_REVIEW.mddeleted file mode 100644index f9033953..00000000--- a/tools/MEETING_PLAYBACK_ECHO_CANCELLATION_ADVERSARIAL_REVIEW.md+++ /dev/null@@ -1,141 +0,0 @@-# Adversarial review — playback echo-cancellation execution plan--Date: 2026-09-10 (local)-Reviewed artifact: `MEETING_PLAYBACK_ECHO_CANCELLATION_EXECUTION_PLAN.md` revision 1-Current artifact: revision 3 incorporates the completed Grok 4.6 and Claude Opus 5 findings below-Status: both requested adversarial reviews completed and reconciled. No implementation or production approval is claimed.--## Review execution--Reviewers were instructed to remain read-only and not access recordings, transcripts, secrets, hardware, or unrelated files.--| Requested reviewer | Result | Disposition |-| --- | --- | --- |-| Grok 4.6 | Initial Orchestrate run ended before findings. Direct xAI Grok session `fe468faa-c9ff-435d-aee8-554a54654f49` reached its first turn cap; a no-more-tools continuation completed with a structured `REVISE` review. | Counted as a completed adversarial review. The CLI's “changed files” listing was the pre-existing dirty worktree inventory, not reviewer edits. |-| Claude Opus 5 | The first dispatch was rejected by the repository provider boundary. After the user explicitly authorized Anthropic disclosure with that conflict disclosed, a broad run ended after 281.3 s with no findings; a plan-only retry completed in 167.9 s through `heavy (claude · opus)`, returned `REVISE`, and reported `editedTree=false`. | Counted only the completed plan-only result. No recordings, transcripts, embeddings, secrets, or unrelated files were sent. |--Timeouts, partial work logs, and rejected dispatches are not reviews or approvals.--## Grok 4.6 verdict--`REVISE`: do not begin AEC3 dependency work until the paired-SCK signal domain is proven learnable and the delay/admission ownership boundaries are executable gates.--## Findings and revision-2 dispositions--### P0. Paired-SCK delivery is not acoustic learnability — accepted--The draft promoted paired-SCK plus AEC3 even though C2 measured delivery metadata only. Revision 2 makes AEC3 conditional and adds Stage 0.5 before dependency work. That stage requires real paired render/capture evidence for signed delay, drift, jitter, frequency-dependent coherence, path stability, excitation, and likely preprocessing. C2 metadata and synthetic FIR fixtures explicitly cannot satisfy the gate.--### P0. Bulk-delay ownership was ambiguous — accepted--The synchronizer and AEC3 could otherwise compensate the same delay or leave it unowned. Revision 2 assigns clock/epoch/mask mapping to `MeetingReferenceSynchronizer` without acoustic time-shifting. AEC3 alone owns acoustic bulk delay; chronological render precedes capture and at most one bounded measured hint seeds the engine.--### P0. An empty residual could erase genuine speech — accepted--Revision 2 adds the same rule to replay and enforcement: residual-empty plus original speech activity, mixed attribution, exact repetition, or timing disagreement becomes `mixedOrUncertain`; it cannot become playback-only merely because the canceller emitted silence. Original text/audio remains recoverable.--### P0. Capture protection and offline admission could diverge — accepted--Revision 2 forbids rewriting an original `.unprotected` capture era. Successful processing is immutable derived provenance. Before migration, the implementation must inventory capture-era admission, live admission, offline interval admission, retries, whole-chunk fallback, trusted observations, stitching, all transcript consumers, and profile persistence. Offline consumers must share one persisted interval decision.--### P1. Selected-app reference incompleteness was not operational — accepted with scoped semantics--Revision 2 distinguishes reference-scope provenance from interval ownership. Known helper/out-of-scope playback and route/volume/DSP transitions cannot become accepted near-end speech. The signal-domain and corpus stages now include helper-process, other-process, and volume-change cases. The plan retains the privacy boundary: it does not silently broaden to full-system capture, and its selected-app guarantee remains explicitly scoped.--### P1. Combined bake-off preceded the independent guard — accepted--The observational multiband attribution guard is now Stage 4; corpus acquisition and combined bake-off are Stage 5. The existing B1 detector remains a fixed baseline rather than being tuned until it appears useful.--### P1. Abstention could game the acceptance metric — accepted without inventing speech thresholds--Revision 2 counts accepted, uncertain, scope-limited, and fail-open original microphone words in playback-only leak totals. It adds a pre-registered 99% eligible-session timing/reference coverage floor, individual-session enforcement, identity-coverage reporting, and rejection of empty-residual conflicts. It deliberately does not set one global cap on `mixedOrUncertain`, because legitimate double-talk populates that outcome; condition-specific caps must be registered before tuning.--### P1. AEC3 extraction can become an unbounded dependency project — accepted--The spike remains out-of-tree and abortable. Revision 2 explicitly pins suppressor, comfort noise, high-pass, field trials, SIMD policy, and every APM submodule. Failure of the time/size/maintenance gate leaves the speaker-route microphone `.unprotected`; it does not authorize a home-grown canceller or mutable prebuilt binary.--### P1. Historical centroid and fallback bypasses were missing — accepted--Revision 2 requires quarantine of pre-existing centroids without clean provenance and tests original-PCM retries/fallbacks, shared observations, global stitching, and every transcript/profile consumer against the same interval decision. First-release profiles remain restricted to independently accepted no-playback original-microphone intervals.--### P1/P2. Route and channel policies were underspecified — accepted--The first enforcement matrix is now exactly built-in output plus built-in microphone. Every route/device change ends the era and resets synchronizer, AEC, and guard state. Headphones, Bluetooth, HDMI, aggregate, external, and mixed routes are separate domains. The wrapper stage now freezes and measures a versioned stereo/multichannel render-downmix policy.--### P2. Frozen invalid VPIO evidence should not permanently close Apple paths — accepted narrowly--Revision 2 keeps current VPIO plus an external reference as a last comparison only when existing valid evidence shows a coherent, learnable residual. It does not reopen generic Trial B or reinterpret the frozen invalid runs as proof either way.--## Missing evidence retained as gates--- Real paired-SCK acoustic learnability with excited reference and microphone capture.-- Executable render-before-capture and single-delay-owner behavior.-- Residual-empty conflict cases covering exact repetition, quiet double-talk, and path changes.-- One-consumer-matrix proof across transcript, UI, export, summary, search, retry, stitching, and profiles.-- Helper/out-of-scope playback and volume/DSP transition behavior.-- AEC3 dependency feasibility, sanitizers, universal build/signing, and resource bounds.-- Topology-matched development and held-out corpus results.--None of these is represented as completed evidence.--## Invariants retained unchanged--- Original application and microphone tracks are immutable.-- Captured application audio is never played back by FluidVoice.-- AEC transforms samples; it does not decide identity or visibility.-- VAD, ASR text, ERLE, residual energy, and voice-processing flags cannot prove near-end speech.-- Invalid or missing samples never become silence; adaptation freezes and the result is explicit.-- Default is `off`; shadow mode changes no user-visible output or profile.-- Raw paired-SCK live admission remains closed in the first release.-- Profile enrollment uses only independently accepted, no-playback original microphone intervals.-- Failed AEC3 feasibility means no AEC3 and no improvised substitute.--## Claude Opus 5 verdict--`REVISE`: Stage 0/0.5 may proceed after tightening causality and gate semantics; later stages were internally gameable or unreachable until the findings below were resolved.--## Opus findings and revision-3 dispositions--### P0. Negative/out-of-range delay could make AEC3 non-causal — accepted--Revision 3 permits one measured, constant render-lead pre-roll owned by the synchronizer, while AEC3 remains the sole adaptive acoustic-delay owner. Stage 0.5 now requires p50/p95/p99 signed-delay distributions, a frozen lead budget and safety margin, and a causal p99 inside the pinned candidate's buffer/search range. Out-of-range eras are `unscored`.--### P0. Recoverable uncertain text could game both leak and recall metrics — accepted--Revision 3 defines one default final-transcript projection for every outcome. `mixedOrUncertain`, `unscored`, and `scopeLimited` fail open visibly; only `likelyPlaybackOnly` is hidden. Playback leak, missed-speech, and WER are computed from that same artifact, with condition-specific uncertain-duration ceilings frozen before tuning.--### P0. First-release profile enrollment was structurally starved — accepted by splitting releases--Revision 3 does not relax the verified-no-playback original-microphone rule. New profile enrollment from cleaned paired-SCK speaker eras is deferred to a separately gated later stage. First transcript enforcement keeps profile matching read-only and gates identity output against the existing baseline without mutating profiles to pass.--### P1. Eligibility and zero-defect gates were gameable — accepted--Stage 0.5 must pre-register the exact eligibility predicate, allowed reasons, maximum ineligible fraction, minimum exposure, and per-condition ceilings. Stage 5/8 require a one-sided upper confidence bound on leakage per exposure-hour; zero observations without sufficient independent exposure returns `insufficientEvidence`.--### P1. Runtime SIMD invalidated replay/cache identity — accepted--Revision 3 pins a portable SIMD baseline, forbids uncontrolled fast-math/FP contraction, and records CPU features, ABI, compiler, deployment target, and native/Rosetta mode in engine and cache identity. Bit identity is required only on a declared reference configuration; supported cross-machine runs require tolerance-bounded metrics and identical interval decisions.--### P1. Clock drift was measured but unowned — accepted--Continuous versioned de-drift resampling belongs to the synchronizer and is explicitly separate from constant render lead and AEC3 adaptive delay. The manifest freezes ppm/cumulative-offset budgets. A one-hour synthetic ramp must prove de-drift and AEC delay do not oscillate or repeatedly reconverge.--### P1. Profile quarantine contradicted rollback — accepted--Quarantine is now reversible and non-destructive. Stage 0 hashes profile/centroid state, retains original embeddings, binds quarantine to provenance, and requires the kill switch to restore the exact baseline hash.--### P1. Evaluation PCM privacy was underspecified — accepted--No report, diagnostic, crash, or sanitizer artifact may contain PCM, text, embeddings, absolute paths, window titles, or speaker labels. The opt-in derived-audio workspace is mode 0700, backup/index excluded, protected at least like source recordings, defaults to a 24-hour TTL with a seven-day maximum, and is destroyed when the gate closes or is cancelled. Corpus admission requires per-recording consent provenance.--### P2. Guard and held-out sequencing was circular — accepted--Stage 4 exits only on development evidence and structural invariants. Stage 5 records a one-time held-out unlock; any earlier access reclassifies the affected data as development and requires a fresh held-out split.--### P2. Comfort noise and asymmetric gaps corrupted evidence — accepted--Energy/coherence attribution and residual-empty conflict checks use original/reference/linear-filter signals only. The suppressed output is ASR-only and its comfort-noise floor is measured separately. One render block is required per capture block; asymmetric gaps beyond the frozen tolerance reset the engine and produce `unscored`, never zero-filled adaptation.--## Combined disposition--Both reviewers rejected immediate AEC3 implementation. Revision 3 therefore authorizes no dependency or production change. The first executable unit is Stage 0/0.5 only: freeze baseline/profile state and establish a real, causal, drift-bounded, learnable paired-SCK signal domain. Failure leaves the current speaker-route microphone `.unprotected`; it does not authorize threshold relaxation or a home-grown canceller.diff --git a/tools/MEETING_PLAYBACK_STAGE05_SIGNAL_DOMAIN_GATE.md b/tools/MEETING_PLAYBACK_STAGE05_SIGNAL_DOMAIN_GATE.mddeleted file mode 100644index 7afb33f0..00000000--- a/tools/MEETING_PLAYBACK_STAGE05_SIGNAL_DOMAIN_GATE.md+++ /dev/null@@ -1,83 +0,0 @@-# Stage 0.5 signal-domain gate--`meeting_playback_stage05_signal_gate.py` is an offline, fail-closed pre-dependency check. It is-not a capture path, AEC, ASR evaluator, or proof of speaker ownership. Run it only against a-private, topology-matched paired ScreenCaptureKit corpus with explicit consent:--```sh-python3 tools/meeting_playback_stage05_signal_gate.py \- --manifest /private/corpus/manifest.json \- --sessions-root /private/corpus \- --output /private/corpus/stage05-report.json-```--The report destination must already exist under a real, non-symlink directory. Reports are-created exclusively with mode `0600`; an existing report is never overwritten.--The manifest must declare `schemaVersion: 1`, `topology: pairedScreenCaptureKit`,-`route: builtInSpeakerMicrophone`, `consentConfirmed: true`, and exactly two lossless PCM-artifacts per session (`render` and `capture`). AAC, VPIO, synthetic fixtures, metadata-only-inputs, unsafe paths, symlinks escaping the corpus root, hash mismatches, and incomplete reference-scope are excluded. Artifact data is used transiently for numeric measurements and is never-written to the report.--The session entries must also carry render/capture block timing (`presentationSeconds`,-`durationSeconds`, `frameCount`, and `arrivalSeconds`). A WAV header alone cannot establish-chronology, delivery jitter, or drift, so such input is explicitly unscored. At least three timing-blocks and three distributed acoustic-delay observations are required by default. The bounded-analyzer accepts at most 1,000,000 mono PCM samples per track; a larger artifact is reported as-outside the registered analysis resource limit rather than silently truncated.--The report is aggregate and privacy-safe: it contains only schema/outcome, numeric distributions,-bounded reason counts, and numeric session ordinals. It contains no PCM, transcript text, labels,-window titles, URLs, absolute paths, or source identities. `rawPCMRetained`, `transcriptRetained`,-and `pathsRetained` are always false.--The executable delay contract is represented by `MeetingAECDelayContract` in the meeting service:-the synchronizer owns clock/epoch mapping and one frozen render lead; chronological render is-queued before capture; the future candidate engine is the sole adaptive delay owner and may receive-one bounded hint. This stage never enables that engine.--An outcome of `proceedToCandidate` only means that at least one eligible session satisfies the-fully persisted threshold snapshot and every required metric is scored. The delay estimator first-uses the entire common span's non-overlapping 4 ms energy envelope for a coarse vote, then a-mean-removed/first-differenced signal at no more than 4 kHz for a narrow fine search, followed by-native-rate refinement. Every one of five-to-eight scheduled local windows across the analyzable-span must resolve with the registered score and prominence; a weak, ambiguous, boundary, or-outlying window fails the whole track rather than disappearing from a convenient cluster.--Drift uses only multiple long-baseline acoustic-observation pairs. Each pair carries native-sample-lag uncertainty, and its complete uncertainty interval must remain inside the configured drift-ceiling. Missing or unresolved delay, drift, alignment, coverage, or path evidence always prevents-`proceedToCandidate`. Callback PTS and render lead are applied exactly once after acoustic evidence-exists; they cannot fabricate a delay.--Alignment follows the measured affine acoustic lag and retains only contiguous sample-backed-support. It never zero-pads, repeats, or clamps an edge, and valid coverage is the minimum of that-support and both callback timing coverages. RMS and clipping continue to use the original inputs;-complex multiband coherence and path scoring use the same aligned support. The bounded 64 ms path-uses three fixed train-only NLMS passes, then reports the worse normalized residual from disjoint-validation and final held-out regions. A high residual means only that this bounded linear model-did not generalize, not that nonlinear preprocessing has been proven.--This acoustic result is not AEC authorization. `rejected` or `unscored` stops AEC3 dependency work-for the topology. A pair that has no bounded, evidence-bearing correlation is reported as-`delayUnresolved`, not as a zero-delay measurement. Synthetic fixtures exercise the analyzer but-can never satisfy the real evidence gate.--The analyzer accepts an empty top-level `artifacts` array when the Codable manifest uses explicit-`sessions`; a nonempty top-level array remains invalid in that form. Delay observations must have-a bounded, non-boundary, prominent correlation peak. Weak or periodic ambiguity is unresolved,-not adverse delay/drift evidence. Drift stays unscored when its native-sample uncertainty cannot-substantiate the registered ceiling. Per-frequency render power uses window-local mean-square-normalization, so merely extending a recording does not make its excitation shrink.--Private provenance accepts exactly two pinned fixture digests: the original controlled broadband-fixture and the checked-in operator-media descriptor. The latter binds the separately consented-operator-controlled web-speech mode; it is not a wildcard for arbitrary media. A syntactically-valid but unknown 64-hex digest remains `invalidManifest`. This allowlist changes no acoustic,-timing, path, or eligibility threshold.--The implementation and its frozen execution order are described in-`MEETING_STAGE05_DELAY_ESTIMATOR_IMPLEMENTATION_PLAN.md`. Even a passing acoustic replay remains-insufficient while the separately retained callback-adapter result is structurally ineligible.diff --git a/tools/MEETING_PLAYBACK_STAGE0_BASELINE.md b/tools/MEETING_PLAYBACK_STAGE0_BASELINE.mddeleted file mode 100644index 9aa1f377..00000000--- a/tools/MEETING_PLAYBACK_STAGE0_BASELINE.md+++ /dev/null@@ -1,65 +0,0 @@-# Playback echo cancellation — frozen Stage 0 baseline--Date: 2026-09-10 (local). Status: Stage 0 inventory is frozen; one controlled raw paired-SCK session was acquired and the Stage 0.5 acoustic gate **rejected it**. No AEC dependency, capture migration, suppression, profile quarantine, or runtime behavior is enabled.--## Frozen inventory--`meeting_playback_stage0_baseline_manifest.json` is the checked-in, privacy-reduced baseline. It identifies the eight existing development recordings from `meeting_admission_b3_annotations.json`, their immutable session/chunk hashes, capture topology and format, bounded annotation counts, current legacy evaluator-output hashes, and a canonical digest of the current session-speaker/profile state.--The freeze found:--- eight development-only dual-track recordings;-- selected-application ScreenCaptureKit audio plus a separate VPIO microphone in every recording;-- AAC-LC on both tracks in every recording, so none is a lossless raw paired-SCK fixture;-- five speaker-route recordings established only by the user's controlled-recording report and three whose output route was not persisted;-- zero recorded capture drops, with every retained chunk byte count and SHA-256 matching its session manifest;-- 126 source session manifests in the profile-state snapshot domain, containing 326 session-speaker records and 221 256-dimensional embeddings; private values never enter the checked-in manifest.--The profile baseline is reversible by construction. Stage 0 does not copy or mutate the original session profile state. Any future quarantine must be a separate overlay: the kill switch removes that overlay and verifies the frozen canonical digest. A second artifact containing names, IDs, embeddings, or transcript content was deliberately not created.--The hashes of the nine existing numeric-only development outputs were present and frozen. They may later expire from temporary storage without invalidating the frozen hashes; re-supplying the temporary output root asks the verifier to re-hash them.--## Current production truth table--This table records current source behavior, not an acoustic-quality claim.--| Recording case | Microphone provenance | Live microphone admission | Offline microphone transcript | Speaker-profile eligibility |-| --- | --- | --- | --- | --- |-| Online call, built-in speakers, VPIO starts and settles | `voiceProcessed` era; selected app is a separate app-only SCK stream | Open only after the VPIO commit and route-protection gate | Admitted for protected eras | Existing echo/quality gates may use admitted turns; this is not proof that playback was removed |-| Online call, positively identified headphone route using paired SCK fallback | `acousticallyClosed` raw-mic era after the route listener settles | Open while the closed route remains stable | Admitted for closed eras | Existing echo/quality gates may use admitted turns |-| Online call, built-in speakers with raw paired-SCK microphone fallback or DEBUG C2 force | `unprotected` | Closed | Turns/chunk fallbacks intersecting the era are excluded | No microphone prototype/profile contribution from excluded turns |-| Online call, unknown/Bluetooth/HDMI/aggregate/external/unverified output | `unprotected` unless headphones are positively identified | Closed | Excluded for intersecting eras | Excluded |-| Route/device transition | New conservative era; admission closes before/at the observed boundary and reopens only after a positively safe commit | Closed during unsafe/unsettled eras | Any diarized turn or whole-chunk fallback intersecting an unprotected era is excluded | Same protected-era boundary applies before prototype construction |-| Legacy online session without capture-era metadata | VPIO maps to `voiceProcessed`; other legacy methods map to `legacyUnclassified` | Historical data only | Admitted for backward compatibility, never reclassified as verified | Existing historical behavior; not new positive protection evidence |-| In-room recording | AVCapture microphone; online echo protection is not required | Admitted | Admitted | Existing in-room diarization/profile behavior |--The authoritative implementations are `MeetingCapturePathDecider`, `MeetingRawMicrophoneProtection`, `MeetingMicrophoneTranscriptGate`, `VoiceProcessingMeetingRuntime`, `ScreenCaptureMeetingRuntime`, and `MeetingProcessingPipeline.microphoneIntervalIsAdmitted`. The synchronizer/contracts/replay code remains production-inert.--## Stage 0.5 disposition--The exit gate does not pass. All eight frozen historical recordings are the wrong microphone topology and are lossy. Exact built-in route facts, independent excitation labels, signal-domain corpus consent provenance, and cryptographically bound recording builds are also absent from that inventory.--A separate safety-reviewed DEBUG harness then acquired one five-second, lossless, raw paired-SCK session on the built-in speaker/microphone route. Hashes, consent, native 48 kHz mono float geometry, callback timing, stable route/volume, and capture provenance validated. The privacy-safe result is frozen in `meeting_playback_stage05_builtin_2026-09-10.json`: the only session was excluded for `lowExcitation`, `driftUnscored`, and `linearPathUnlearnable`. The user reported that incidental noise may have occurred, so this session is evidence that the gate did not pass—not a topology-wide claim that paired SCK can never work.--Therefore:--- no current recording passes paired-SCK acoustic learnability analysis;-- C2 delivery metadata, synthetic FIR fixtures, the VPIO recordings, frozen Trial B, and unexcited Trial A are not substitutes;-- the five-second session cannot resolve the frozen 100-ppm drift bound at the registered tracker resolution, and its held-out linear path did not generalize;-- AEC3 dependency work remains unauthorized.--Any next evidence step must be separately safety-reviewed and pre-register a longer, persistently broadband but still low-level stimulus plus enough duration to resolve the frozen drift bound. It must also control incidental microphone noise. Threshold relaxation or AEC3 work is not an allowed response to this rejection.--## Verify--From the repository root, while the frozen source sessions are still available locally:--```sh-python3 tools/meeting_playback_stage0_baseline.py \- --repo . \- --sessions-root "$HOME/Library/Application Support/FluidVoice/Meetings" \- --annotations tools/meeting_admission_b3_annotations.json \- --verify-manifest tools/meeting_playback_stage0_baseline_manifest.json-```--To re-hash the still-present legacy numeric sidecars too, add `--legacy-output-root /private/tmp`. The verifier fails closed on path escape, malformed/non-finite input, unknown track shape, non-finalized or non-contiguous chunks, byte/hash mismatch, capture-drop schema loss, profile-state drift, private-field leakage, or any attempt by the manifest to authorize AEC3.diff --git a/tools/MEETING_RELIABILITY_P0_ADVERSARIAL_REVIEW.md b/tools/MEETING_RELIABILITY_P0_ADVERSARIAL_REVIEW.mddeleted file mode 100644index 3b41381e..00000000--- a/tools/MEETING_RELIABILITY_P0_ADVERSARIAL_REVIEW.md+++ /dev/null@@ -1,53 +0,0 @@-# Orchestrate P0 adversarial review--Captured before amendments; see MEETING_RELIABILITY_P0_BASELINE.md for disposition. Reviewer output is analysis, not implementation instructions or final sign-off.--served-by: standard (grok · grok-4.6)-attempt: standard · ok · 274.8s · editedTree=false--I'll review only the five named files and produce an adversarial pass on production behavior, decoder-proof claims, model-loading network safety, and report schema accuracy.**Verdict:** RELEASE live policy looks unchanged (diagnostics compile out / force off). These files do **not** prove decoder reset, live-pipeline recovery, or a passed negative screen.--### 1. High — Green XCTest is not a negative-screen pass-`Tests/FluidASRBaselineTests/MeetingReliabilityNegativeScreenTests.swift` (`testSyntheticSilenceAndLowNoiseNegativeScreen`, `NegativeScreenReport.status`, class comment).--The opt-in test never asserts on `nonempty` / `whitespaceWordCount`. Any finished run sets `status = "complete"` and the test succeeds.--**Counterexample:** Silence/noise both emit captions every segment → `runs[].nonempty = true`, `status = "complete"`, XCTest green. That is the hallucination case, not a pass.--**Correction:** Keep measurements non-gating, but add an explicit `verdict: "measured_only"` (never `pass`) and refuse to treat XCTest success as evidence. Gate only on schema/host/artifact checks.--### 2. High — Reset/process KPIs are proof-shaped, not decoder-true-`Sources/Fluid/Services/Meeting/LiveTranscription/MeetingLiveTrackEngine.swift` `resetRecognizer()` (generation / `firstPartialAfterResetSeconds` / `diagnosticResetUptime` **before** `await manager.reset()`, `resetCompletions` **after** return). `MeetingLiveP0DiagnosticsTests.testThrownProcessIsNotCountedAsCompletion` still asserts `resetCompletions == 1`.--**Counterexample:** FluidAudio swallows a failed internal decoder reset (the protocol comment already says this) → `resetInvocations == resetCompletions`, `generation` bumped, later `processCompletions` keep rising (`testForcedBoundaryThen38SecondsWithoutPartialDoesNotRecover`). That is wrapper return, not a new decoder epoch. `firstPartialAfterResetSeconds` also includes reset wait: a 2s hung `reset()` then an immediate partial reports `2`, not `0`.--**Correction:** Rename to `recognizerResetReturned` / `wrapperGeneration`. Start the partial-after-reset clock after `reset()` returns. Never export `resetCompletions` as health.--### 3. Medium — Same model tree, two hash semantics-Python `model_manifest_inventory()` (`tools/meeting_reliability_baseline.py`) vs Swift `validateArtifacts` (`MeetingReliabilityNegativeScreenTests.swift`).--Swift: enumerator, reject symlinks, `actual == Set(paths)`. Python: hash listed artifacts only; extra files do not flip `allHashesMatch`.--**Counterexample:** Manifest-listed files match, plus `Decoder.mlmodelc` sibling `Extra.mlmodelc` → inventory `allHashesMatch: true`; negative screen `ScreenError.invalidInputs`.--**Correction:** Inventory should fail (or set `exactTreeMatch: false`) unless the repository file set equals the manifest, same as the screen.--### 4. Medium — “Local-only” is sandbox + constructors, not a FluidAudio offline proof; live load is still HF-Screen: `MLModel(contentsOf:)` + `AsrManager.initialize` / `transcribe` (`MeetingReliabilityNegativeScreenTests.swift` ~47–90, `networkPolicy`). Host check only rejects `network.client/server` and mic entitlements. Live: `StreamingEouAsrManager.prepareModels()` → `loadModelsFromHuggingFace()` (`MeetingLiveTrackEngine.swift`).--**Counterexample:** Opt-in screen stays sandbox-offline while production live still downloads on cache miss. Comment “Each transcribe resets decoder state” is unverified here; one `AsrManager` is reused for 60s then 3s over the **same** samples — if `transcribe` does not reset, short-turn rows are not independent exposures. `AsrManager` is also not `MeetingLiveTrackEngine` / `StreamingEouAsrManager`.--**Correction:** State in the report that FluidAudio initialize/transcribe internals were not inspected; recreate or explicitly `reset` per segment; never cite this screen for live HF load or live EOU stalls.--### 5. Medium — Session inventory is fail-open on drop schema-`session_inventory()` in `tools/meeting_reliability_baseline.py`: `captureDrops` is `health.droppedSampleCount` via `.get`; missing key → `null`. `sourceTrackID` is fail-closed. `visibleSpeakerCount` is `len({speakerID})`, so a missing id counts as one speaker (`None`).--**Counterexample:** Drops stored as `droppedFrames` (or omitted) → `captureDrops: null` next to real chunk hashes; readers treat it as “unknown/zero drops.” Two visible segments with no `speakerID` → `visibleSpeakerCount: 1`.--**Correction:** Fail if `health.droppedSampleCount` is absent (same as `sourceTrackID`). Count only non-null `speakerID`, or emit `speakerIdPresentCount` separately.-------**Production preservation (this file):** `#else diagnosticsEnabled = false`; diagnostic APIs are `#if DEBUG`. `consume` / rotate / HF load / reset policy are not altered when diagnostics are off. `uptime` is injectable in RELEASE (default still `systemUptime`) — watchdog clock is no longer a closed production constant.--**Unverified (out of allowed files):** `AsrManager.initialize`/`transcribe` network and reset; `DebugLogger` timestamp vs `FLOW` regex; `BaselinePathSafety` / `ASRBaselineHost` entitlements at runtime.diff --git a/tools/MEETING_SCK_PAIRED_C2_DIAGNOSTICS.md b/tools/MEETING_SCK_PAIRED_C2_DIAGNOSTICS.mddeleted file mode 100644index 8299e48f..00000000--- a/tools/MEETING_SCK_PAIRED_C2_DIAGNOSTICS.md+++ /dev/null@@ -1,81 +0,0 @@-# Phase 0 C2 — ScreenCaptureKit paired-output diagnostics--This slice characterizes the existing one-`SCStream` topology that emits selected-application-`.audio` and `.microphone` outputs. It is DEBUG-only and opt-in with:--```text-FLUIDVOICE_C2_DIAGNOSTICS=1-```--In a DEBUG build, this explicit gate also forces the online-call path to use the paired-ScreenCaptureKit topology when the output route is otherwise eligible for voice processing. The-decision detail and debug log identify this as `C2 diagnostic forced paired ScreenCaptureKit`; it-is not a production fallback. Release builds and DEBUG runs without the exact `=1` value retain the-normal voice-processing decision.--The one-shot signed hardware test additionally requires `FLUIDVOICE_C2_HARDWARE=1` and-`FLUIDVOICE_C2_TARGET_BUNDLE_ID=<currently-running-bundle>`. It creates one selected-application-display filter with `.audio` and `.microphone` outputs, runs for five seconds (bounded below the-15-second ceiling), stops cleanly, and prints the sorted numeric report JSON. It skips without all-three explicit values and never launches an application or writes PCM/transcript data.--For an installed DEBUG app, set `FLUIDVOICE_C2_AUTORUN=1` as the fourth exact gate. The app-launch-hook returns before normal topology observers, logging, AppServices, or UI startup, performs the-same no-prompt Screen Recording and microphone preflight, runs the five-second metadata-only stream,-prints one sorted `[C2_AUTORUN]` success/failure JSON line, and exits with status 0/1. All other-launches, including Release builds or any missing/alternate gate value, follow the normal app path.--`MeetingSCKPairedDiagnosticCollector` accepts only callback-boundary metadata: output kind,-presentation timestamp, duration, frame count, sample rate, channel count, and an optional monotonic-arrival timestamp. It retains aggregate numbers in a lock-protected bounded collector. It never-accepts or stores PCM, transcript text, device names, window titles, paths, URLs, or identities.--The report measures per-output sample counts, malformed/non-finite timestamps, format changes,-timestamp gaps/overlaps/backwards movement, delivery jitter, coverage, first/last PTS offset, and-the relative observed timestamp-span difference. The cross-output offset is explicitly-`microphone PTS - application PTS`; it is not an acoustic or processing latency. Independent-ScreenCaptureKit PTS origins mean the report does not establish a shared clock, estimate oscillator-drift, evaluate AEC, or authorize suppression. Timestamp continuity uses a sample-rate-derived-half-sample tolerance, so sub-sample floating-point noise is not reported as a gap or overlap;-missing or malformed data is fail-open and remains numeric.--The DEBUG ScreenCaptureKit runtime now calls the collector at the callback boundary for the selected-application `.audio` and paired `.microphone` outputs. The callback path first checks the explicit-environment gate, copies only numeric metadata, and requires a scope/provenance assertion derived-from the active selected-application filter. At deterministic runtime stop, the bounded report is-serialized with sorted JSON keys and emitted through the DEBUG logger. A provenance/scope mismatch-is rejected, counted in the report, and logged once; it is never silently combined with another-capture scope. The unit tests retain a deterministic harness for synthetic metadata and exercise-the callback seam without hardware.--No production capture, transcription, persistence, profile learning, or installed app behavior is-changed by C2.--## 2026-09-10 built-in-route attempt--The signed installed-app autorun reached both no-prompt privacy preflights, but-`SCShareableContent.current` returned no display. It therefore exited before creating or starting-an `SCStream`; no browser stimulus played and no PCM or transcript was retained. The numeric result-is frozen in `meeting_sck_paired_c2_builtin_2026-09-10.json` as invalid evidence. It neither supports-nor rejects the paired topology. A later rerun requires resolving the macOS ScreenCaptureKit display-availability/permission state; the diagnostic must not request or bypass that permission itself.--## 2026-09-10 unlocked rerun--After the interactive display session was unlocked, the same signed installed-app autorun completed-one bounded five-second capture against the controlled Chrome stimulus. Both selected-application-audio and microphone outputs produced samples; every callback had valid timestamps and stable-formats, with zero collector-bound drops, malformed metadata, backwards timestamps, or provenance-rejections. The application and microphone spans each reported full coverage. The exact reduced-report is frozen in `meeting_sck_paired_c2_builtin_unlocked_2026-09-10.json`; it retains no PCM or-transcript. That sidecar predates the continuity-tolerance and report-field correction (schema 3),-so its nanosecond-scale gap/overlap counts and `relativeSpanDriftPPM` key are historical artifacts,-not current measurements.--This establishes that the selected-application paired topology is viable on this host when a display-session is available. It does not establish a common capture clock or evaluate AEC: ScreenCaptureKit-reported independent PTS origins, a first-PTS offset of approximately 154 ms, a last-PTS offset of-approximately 42 ms, and a pre-correction observed-span difference of approximately -21,538 ppm over-this short window. The unequal start/stop delivery boundaries account for that span difference, so it-must not be interpreted as oscillator drift. These values are diagnostic timing evidence, not acoustic-delay or cancellation scores.diff --git a/tools/MEETING_SPEECH_SHADOW_B2.md b/tools/MEETING_SPEECH_SHADOW_B2.mddeleted file mode 100644index a745b882..00000000--- a/tools/MEETING_SPEECH_SHADOW_B2.md+++ /dev/null@@ -1,97 +0,0 @@-# B2 offline speech activity and playback comparison--Date: 2026-09-08 (local). Experimental evidence collection, not production admission.--## Result--The cached speech-activity model runs locally and produces useful diagnostic variation, but activity still occurs in user-reported playback-only recordings. The B1 matcher still produces no supported locks on these fixtures. **This combination does not establish a safe local-speech classifier.** Every combined proposal remains explicitly uncertain; nothing hides text or filters speaker profiles.--No installed app, original recording, saved transcript or speaker profile was changed. No model was downloaded and no audio/text/embedding was sent to a reviewer. The default CLI path has speech collection off; an explicit fourth argument selects a local compiled model for this standalone run. No app runtime enablement was introduced.--## Model/API audit--The pinned FluidAudio source (`3fd63887eef1dc25edea8263ce4b44aa854d898b`) uses Silero v6's unified 256 ms model: 4,096 new mono 16 kHz samples plus 64 context samples; hidden/cell states each have 128 values. `VadManager`'s normal and directory initializers call download helpers, while its preloaded-MLModel initializer avoids them. Its whole-array helper pads short final chunks by repeating the final sample.--This evaluator instead uses a small direct CoreML adapter with the audited exact feature names/shapes and CPU-only execution. It cannot invoke FluidAudio download helpers. It submits only complete valid frames, with no fabricated tail padding. It keeps the 64-sample context and recurrent state across contiguous valid frames, and resets after invalid coverage, gaps, epoch/route/session changes or model failure. The first valid frame after reset is marked warmup/unknown; this one-frame warmup is an explicit experimental convention, not a validated convergence guarantee.--The cached `model.mil` combines eight internal 32 ms probabilities as `1 - product(1 - p_i)`. Consequently the exported scalar is **not** mean speech probability, voiced duration, near-end confidence or eight independent pieces of evidence. The dependency's 0.85 default is retained only as a diagnostic activity threshold. No gain normalization, energy rescue, segmentation padding or speech suppression was added.--The local FluidAudio repository declares Apache-2.0. The model publisher declares MIT in its [model card](https://huggingface.co/FluidInference/silero-vad-coreml/blob/main/README.md); no new model redistribution/package is performed here. Cached artifact identity is separately fingerprinted rather than assuming the current remote card establishes byte identity.--Cached model: `silero-vad-unified-256ms-v6.0.0.mlmodelc`. Sidecars record hashes of all five files; hashes are checked again after inference. Key SHA-256 values:--```text-model.mil 4f93e2b5920e851fbc0be1c21a2a76e170124467ed7b01125190aa32e795f8af-weights/weight.bin 853cf34740d3f5061f977ebe2976f7c921b064261c9c4753b3a1196f2dba42b4-```--## Evidence, coverage and safety--- The existing B1 paired-audio analysis remains a separate signal. Speech frames join its windows by full interval overlap in the same capture epoch; 256 ms frames crossing the two-second grid are not dropped. Mixed support remains explicit. Missing temporal coverage is not a reliable negative match.-- New combined reason categories distinguish activity with a supported duplicate, activity without a reliable match, negative activity with/without duplicate evidence, and unavailable speech evidence. None establishes near-end speech or absence. The legacy echo score is explicitly `notMeasured` in this CLI; this is not the full three-signal/B3 ablation.-- Original capture PTS, overlapping-chunk rejection, 50 ms conservative decoded edges and ±2 s either-track recorded discontinuity guards are retained. Invalid samples remain unavailable, not silence. Unrecorded route changes and accurate AAC priming remain limitations from B1.-- One model instance and synchronous frame inference; cancellation checked before/after prediction. A CoreML prediction cannot be forcibly preempted. A 100 ms per-frame engineering budget discards over-budget results; three consecutive failures disable the contribution within the session. Unknown frames clear pre-disable strikes; a new session resets the latch. Model load is synchronous and is not covered by the per-frame inference budget.-- The offline runner is capped at 600 seconds/32 chunks and keeps a bounded session raster in memory; it is not a streaming capture implementation. A missing model emits explicit unavailable status and full unmeasured duration, with no network fallback.-- Detailed reports are numeric-only, exclusively created outside original sessions under temporary storage. They are not application logs or persisted admission decisions. Retain only for development review; no automatic deletion/retention automation was created.--## Local measurements--Final reports: `/private/tmp/fv-speech-{3774,88e3,3b9a}-v2.json`. V1 reports predate the improved temporal-grid join and are superseded. All counts below are **256 ms windows**, not speech duration.--| Development recording | Full frames | Measured | Activity ≥0.85 | Unknown full frames | Unknown duration including tail |-| --- | ---: | ---: | ---: | ---: | ---: |-| `3774ED4C…` user-reported no speech | 385 | 380 | 6 | 5 | 1.476 s |-| `88E3BD44…` scripted speech near end | 1,016 | 1,004 | 141 | 12 | 3.299 s |-| `3B9AC1A8…` user-reported playback-only | 515 | 508 | 6 | 7 | 1.822 s |--In the previously identified coarse 208–250 s scripted interval, 121 of 161 measured windows were active (163 total). There were also 19 active windows wholly before 208 s. These boundaries come from prior diagnosis, not independent sample-level annotations; pauses and exact speech onset are unlabelled. The ratio is **not speech recall**, and earlier windows cannot all be labelled individually from this coarse boundary.--The playback-only recordings demonstrate that activity can be leaked speech rather than near-end speech. Conversely, a negative activity window cannot establish absence of a quiet reply. Synthetic tests explicitly retain this distinction. All 1,916 combined frame proposals stay uncertain: 153 activity-without-reliable-match, 1,739 negative-activity-not-absence, and 24 missing-speech-evidence. There are zero supported temporal locks.--Final end-to-end local CPU-only runs took 1.10, 1.48 and 0.77 seconds, with maximum resident sizes about 62.3, 80.9 and 64.7 MB. No model, budget or inference failures occurred in these runs. These are development profiles, not capture-load or held-out acceptance results.--`/private/tmp/fv-speech-3774-off.json` confirms off mode has the same input fingerprint and temporal state counts. `/private/tmp/fv-speech-3774-unavailable.json` confirms a missing model reports all 98.756 seconds unavailable without a fallback download. This does not replace a full baseline/echo/VAD/combined end-to-end admission ablation.--## Adversarial review and dispositions--Three scoped Kimi K3 reviews completed through OpenCode in read-only mode: B1 core, B2 adapter/evaluator, and Stage A evidence seam. Earlier timeouts are historical, not the current review result. Findings were addressed as follows:--1. B1 floating-point lag-spread boundary: fixed using integer-sample comparison; exact 12 ms spread regression added.-2. B1 failure latch/counter scope: new sessions reset the latch; unavailable windows clear pre-disable consecutive strikes. Within-session disabled state intentionally remains latched.-3. B1 release counters: no code change. `released` records the transition; zero supporting windows accurately represents current evidence. Retaining former support in those fields would be misleading.-4. B2 failure reset issues: fixed consistently with B1 and covered by session/unknown-frame tests.-5. B2 256 ms / two-second grid mismatch: replaced single-containing-window lookup with overlap/coverage join and explicit mixed/unavailable state, with boundary tests. The reviewer incorrectly attributed the old nil temporal match to the missing-*speech* reason; that reason depends on missing VAD activity. The temporal coverage problem itself was real.-6. Short-session shifted controls: explicitly report `controlUnavailable` when neither ±8 s control fits. No fabricated fallback. Some later short-session windows can use the backward control, contrary to the review's broader claim; missing control remains an acknowledged measurement limit.-7. Stage A unknown playback context: added `missingPlaybackContext` instead of labelling a valid temporal measurement invalid, with a regression test.-8. Stage A exact interval/observation equality: retained intentionally. This test-only contract binds to an immutable evidence snapshot, not an approximate audio match; callers must reuse/rebind that snapshot explicitly. Two cases pin rejection of a one-ULP interval change and observation change. A future runtime projection must define its own timeline conversion rather than silently relaxing binding. `staleTemporalEvidence` currently includes snapshot mismatch, not just expired epochs.--The scopes above were reviewed; post-fix implementation was locally verified, not independently re-reviewed in full. No claim of production approval, calibration approval or enforcement sign-off is made.--## Verification--Final isolated `FluidASRBaseline` build succeeded and **46 targeted tests passed**, zero failures/skips: 11 speech tests, 13 temporal tests, 17 Stage A contract tests and five existing live diagnostic tests. Result bundle: `/private/tmp/fv-speech-b2-v3.xcresult`. The earlier v1 test attempt failed before tests could launch because the generated CTranscribe framework had an invalid version layout/signature; displaced framework files were retained in temporary backups, the isolated host was repaired/re-signed and deep/strict verified, then v2 (44 tests) and final v3 passed. No installed-app replacement occurred.--The optimized CLI compiled and ran all three local fixtures, speech-off mode and missing-model mode. Source inspection confirms no production caller of the speech adapter or either shadow policy. `git diff --check` passed. The full application integration suite, Release build, hour-long capture load, independently annotated positives, calibrated recall and held-out gates were not run.--## Reproduce / next gate--From the repository root:--```sh-swiftc -module-cache-path /private/tmp/fv-reliability-swift-cache -O \- Sources/Fluid/Services/Meeting/MeetingPlaybackDuplicateDetector.swift \- Sources/Fluid/Services/Meeting/MeetingSpeechActivityDetector.swift \- tools/meeting_temporal_shadow.swift -o /private/tmp/fv-speech-shadow-```--Run with `session.json`, a fresh output path outside the session directory, and the explicitly chosen cached `.mlmodelc` directory. Omit the model argument for speech-off mode. Native codec/CoreML access may require host execution approval; this does not upload audio or grant new application privacy permissions.--Next is annotated development evaluation and feature/calibration work, not enabling suppression. Stronger temporal evidence may be needed for weak nonlinear residuals. Quiet replies, double talk, no-reference speech, multiple near-end speakers and held-out quality remain unvalidated. Any new detector/model dependency needs a separately reviewed scope. B3, app shadow integration and enforcement remain outstanding.--Source SHA-256 for the final fixture runs:--```text-speech adapter 751dea98435493b2c2c3792a6965ed2e3d7eb301634bcd92a71728ec4cba12bb-temporal 429111cce7a90ffec42e84b7f9e7bd9fece6b0c21c8790616de52fc180389d95-evaluator d254f1e0c309f485d50e93ab146c245ea3457245881a4ff2a1f772ded7465e07-```diff --git a/tools/MEETING_STAGE05_DELAY_ESTIMATOR_IMPLEMENTATION_PLAN.md b/tools/MEETING_STAGE05_DELAY_ESTIMATOR_IMPLEMENTATION_PLAN.mddeleted file mode 100644index e8af0f97..00000000--- a/tools/MEETING_STAGE05_DELAY_ESTIMATOR_IMPLEMENTATION_PLAN.md+++ /dev/null@@ -1,361 +0,0 @@-# Stage 0.5 offline delay-estimator and path-model implementation plan--## Decision--Replace the current single-scale, 1 kHz delay tracker with a bounded two-stage estimator and-make the held-out linear-path check consume the resulting affine delay model. Implement and lock-the estimator against synthetic fixtures before replaying the one retained private corpus.--This is an offline analyzer change only. It does not record audio, change the capture harness,-install an app, add AEC3/WebRTC, alter production Swift, loosen a registered gate threshold, or-turn an ambiguous correlation into a zero-delay observation.--## Why this is the next step--The 2026-09-11 controlled paired-SCK run passed capture provenance, native PCM, callback timing,-route, volume, excitation, clipping, and low/mid/high coherence checks. Its signal gate still-failed closed because the existing delay tracker found no peak with enough prominence, could not-score drift, and aligned the held-out path model with no resolved delay. The resulting linear-residual was 0.777411 against the frozen 0.75 ceiling.--The current tracker downsamples to 1 kHz and independently searches roughly one-second windows-across the full +/-500 ms range. The controlled stimulus contains fixed tones plus seeded-broadband noise. The tones create many strong aliases; the noise is intended to identify the-physical peak, but short, wide-search windows do not accumulate enough of it to distinguish that-peak. Merely trimming the WAVs cannot fix this because the analyzer already uses the common PCM-span.--The retained evidence remains a rejection. These changes are an investigation of whether a-strict estimator can resolve the registered evidence without changing the evidence or its gates.--## Frozen safety and decision boundaries--The following values and meanings stay unchanged:--| Gate | Frozen value |-| --- | ---: |-| Valid timing coverage | at least 0.99 |-| Acoustic delay observations | at least 3 |-| Maximum drift | 100 ppm |-| Maximum uncorrected delay range | 20 ms |-| Acoustic search range | +/-500 ms |-| Search-boundary safety margin | 20 ms |-| Path stability | at least 0.5 |-| Held-out linear residual | at most 0.75 |-| Excitation RMS | at least 0.001 |-| Per-band coherence | at least 0.10 |-| Clipping | at most 0.01 |-| PCM resource ceiling | 1,000,000 samples per track |--Additional estimator confidence checks may only make the result stricter. The implementation must-not tune confidence constants against the retained corpus. Freeze them through synthetic tests-first, then replay the corpus once.--An acoustic `proceedToCandidate` result is necessary but not sufficient for AEC work. The final-authorization predicate is the conjunction of:--1. a fully scored Stage 0.5 acoustic result that passes every frozen threshold;-2. a structurally eligible callback-adapter result; and-3. a separate reviewed implementation decision.--The retained callback-adapter result is currently ineligible because four terminal frames were-masked/frozen around a 555-sample microphone-only stop tail. This plan does not reinterpret that-edge or override it. Therefore even a passing offline acoustic replay cannot authorize AEC3 by-itself.--## Implementation scope--Modify only:--- `tools/meeting_playback_stage05_signal_gate.py`;-- `tools/test_meeting_playback_stage05_signal_gate.py`;-- `tools/MEETING_PLAYBACK_STAGE05_SIGNAL_DOMAIN_GATE.md`;-- `tools/MEETING_STAGE05_EVIDENCE.md`; and-- one new privacy-safe aggregate sidecar, only after all synthetic gates pass and the private- analyzer report passes a forbidden-key scan.--Do not modify Swift sources, the capture fixture, manifests, WAVs, threshold snapshots, runtime-gates, project dependencies, app signing, or the installed app.--## Design--### 1. Separate estimation facts--Introduce private, immutable analyzer records with explicit units:--- `DelayObservation`: window-center seconds, acoustic array lag seconds, lag-uncertainty seconds,- absolute correlation, competitor correlation, and prominence;-- `DelayEstimate`: coarse lag, fine intercept, drift slope in ppm, quantization bound, accepted- observations, fit residual, and a fixed failure category; and-- `AlignedSpan`: render/capture samples plus an explicit valid-support fraction.--Keep three concepts separate:--- **acoustic array lag** aligns the two decoded sample arrays;-- **PTS offset** maps their independently started callback timelines; and-- **render lead** is the already bounded synchronizer contract input.--Only `array lag + PTS offset + render lead` may become the reported signed delay. PTS metadata may-transform and sign-check an acoustic observation, but it must never fabricate one. An unresolved-estimate returns no signed delay, no drift, and no path score—not numeric zero.--### 2. Build a global anchor without letting tones vote repeatedly--Use the entire bounded common span to establish one coarse-to-fine anchor:--1. Remove the mean independently from each input using finite bounded arithmetic.-2. Form a deterministic non-overlapping 4 ms short-time energy envelope at the native rate.- Center and normalize that envelope, then search the full frozen +/-500 ms range. This makes- seeded broadband energy variation carry the coarse vote while stationary tones contribute- little timing identity, without allowing overlapping envelope windows to inflate adjacent- peak correlation.-3. Require the coarse peak to be non-boundary, have absolute correlation at least 0.10, and exceed- every competitor outside one coarse bin by at least 0.05. These equal the existing minimum- correlation and prominence requirements; they are not relaxed.-4. Anti-alias and decimate the mean-removed PCM to at most 4 kHz, first-difference the result, and- search only +/-12 ms around the coarse anchor. Require the same score/prominence checks, a- non-boundary result, and agreement with the coarse anchor within one 4 ms envelope bin.-5. Refine the accepted 4 kHz peak at the native rate over the centered local window, within three- 4 kHz samples. A three-second window at the accepted drift ceiling can spread a box-decimated- physical peak across adjacent bins; a one-bin refinement was demonstrated to reject the- registered +/-50 ppm synthetic cases. Use a three-point parabolic interpolation only for a- finite, strictly concave interior peak; otherwise retain the integer native-sample lag. Bound- the lag uncertainty by at least half a native sample and carry it into every later drift/range- decision. The wider native refinement does not weaken ambiguity rejection: the preceding 4 kHz- search still owns the unchanged global score/prominence checks.--The work stays bounded: at most 250 envelope samples per second over 251 coarse lags, at most 4 kHz-PCM over 97 fine lags, and one native-rate search no wider than three 4 kHz samples on either side-over a maximum three-second window. If any level is weak, ambiguous, contradictory, or at its-search boundary, return `delayUnresolved`.--### 3. Track local delay and drift around the anchor--After the global anchor passes, schedule five to eight evenly distributed windows across the-entire analyzable common support. The first and last windows must touch the earliest and latest-possible full-window positions. Use `min(3 seconds, half the common span)` as the window duration,-subject to the minimum correlation geometry. Search each window within +/-24 ms of the global-fine anchor: the frozen 20 ms uncorrected-range allowance plus one 4 ms coarse bin.--Every scheduled window must resolve, satisfy the unchanged 0.10 absolute-correlation and 0.05-prominence requirements, and remain off the local search boundary. A weak, ambiguous, or boundary-peak fails the track; it is not dropped so that a convenient middle cluster can pass. The first-and last observations must span the complete scheduled support. Refine each accepted local peak-at native rate within three 4 kHz samples and carry its conservative lag uncertainty into the fit.--Fit delay versus window-center time using a deterministic Theil-Sen slope over long-baseline-pairs. Exclude pair slopes whose time separation is less than half of the scheduled observation-span; short-baseline quantization must not masquerade as drift. Require:--- every scheduled observation to resolve, with at least five distributed observations even though- the existing report threshold remains three;-- at least three qualifying long-baseline slopes;-- a one-native-sample-over-total-span quantization bound no greater than the configured drift- ceiling;-- every retained long-baseline slope's worst-case interval, including both endpoint lag- uncertainties, wholly within the configured drift ceiling;-- detrended delay residuals within the existing 20 ms uncorrected-offset bound; and-- the existing path-stability fraction after subtracting the fitted drift trend.--Report drift percentiles from the qualifying long-baseline slopes. Do not derive drift from SCK-callback PTS or adjacent quantized delay bins. Do not discard an outlying resolved observation or-its long-baseline slopes: any slope or residual outside the frozen bounds rejects the whole track.--Missing evidence is always ineligible. A null delay, null drift, `driftUnscored`, null alignment,-null coverage, or null path score must prevent `proceedToCandidate`. A recording that is too short-to satisfy its configured drift-resolution bound fails closed; it does not skip the drift gate.-An estimate near the ceiling whose uncertainty crosses the ceiling also fails closed rather than-rounding into acceptance.--### 4. Align only measured, valid support--Map render samples onto capture time with the estimated affine acoustic lag (intercept plus drift)-using deterministic linear interpolation at the native rate. Do not pad either edge with zeros,-repeat samples, or silently clamp source indices. Return only the common supported region and its-coverage fraction.--Combine this acoustic support fraction conservatively with the existing callback-timing coverage;-the reported `validCoverageFraction` is their minimum. A large delay or drift that leaves less-than 0.99 valid support therefore fails the existing coverage gate even if correlation is strong.--Use the same aligned span for band coherence and the linear-path check. RMS and clipping continue-to describe the original bounded inputs. Causal/range checks continue to use the signed delay-after PTS offset and render lead are applied. Perform that signed-clock contract check before-candidate alignment/path scoring; a non-causal or search-margin-violating sum leaves all dependent-candidate metrics unscored.--### 5. Make the path check converge without weakening it--Keep the existing maximum 4 kHz analysis rate, 64 ms/256-tap ceiling, disjoint chronology, and-0.75 residual threshold. Change only the deterministic fitting discipline:--- derive centering constants from the training region and apply those same constants to later- regions;-- train NLMS for three fixed passes with step sizes 0.50, 0.25, and 0.125;-- never train on validation or held-out samples;-- score one middle validation region and the existing final held-out region; and-- return the worse normalized residual as `heldOutLinearResidualFraction`.--Both regions must have at least 64 scored samples and nontrivial target energy. Otherwise the path-is unscored. This makes convergence more reliable while making acceptance stricter: a model that-works only in one late segment cannot pass.--No tap-length search, threshold search, corpus-specific learning rate, nonlinear model, frequency-domain suppression, or test-set refit is allowed.--### 6. Emit bounded diagnostics without private traces--Keep the existing report free of PCM, paths, hashes, titles, labels, identities, and transcripts.-If implementation diagnosis requires new output, bump the report schema and add only bounded-per-session scalar summaries: coarse/fine score and prominence, accepted observation count,-quantization ppm, fit residual, acoustic support fraction, validation residual, and held-out-residual. Do not emit candidate arrays, observation timestamps, per-window lag traces, filter taps,-or sample-derived fingerprints.--The analyzer output remains exclusive-create mode `0600` under the private evidence root and never-overwrites an earlier result. It is not committed. After the forbidden-key/privacy scan, a-separately constructed aggregate numeric-only sidecar may be added under `tools/`; it must contain-no paths, hashes, candidate arrays, per-window values, filter taps, or source identities. Existing-reports remain immutable.--## Deterministic test matrix--Add pure synthetic tests before touching the retained corpus:--### Delay identity and sign--- seeded broadband plus all registered tones through a fixed 64 ms FIR at known integer and- fractional delays;-- positive and negative acoustic array lags, with independent positive/negative PTS offsets;-- zero acoustic lag that is genuinely evidenced, distinct from an unresolved estimate;-- delays just inside and outside the frozen search/safety boundaries;-- combinations where acoustic lag is safe but PTS offset or render lead makes the final signed sum- non-causal, within the negative 20 ms safety margin, or inside the positive search-boundary- margin;-- evidenced acoustic zero combined with nonzero PTS offset and render lead, proving that every- term participates exactly once in the final signed check;-- reversed polarity and ordinary fixed gain/DC offset; and-- unequal decoded lengths where only explicit common support may be scored.--### Ambiguity and failure closure--- pure 1 kHz and multi-tone periodic signals remain unresolved;-- two equal competing broadband peaks remain unresolved;-- weak broadband under unrelated capture noise remains unresolved;-- a dominant peak at either search boundary remains unresolved;-- low excitation, clipping, non-finite input, empty input, and resource overflow fail closed; and-- changing PTS offset without acoustic evidence never creates an observation.--### Drift--- deterministic affine delays at 0, +50, and -50 ppm score within quantified error;-- +99 and -99 ppm pass only in fixtures whose carried uncertainty remains wholly inside 100 ppm;- otherwise they fail closed as unscored rather than being rounded inward;-- +101 and -101 ppm are rejected without rounding into the allowed range;-- short recordings whose quantization bound exceeds 100 ppm remain `driftUnscored`;-- every scheduled window, including the first and last, must resolve; an unresolved/boundary window- fails instead of shrinking the observation span;-- one resolved local alias/outlier rejects through its long-baseline slope or detrended residual- rather than being discarded or moving the robust intercept/slope into acceptance; and-- non-affine delay jumps fail stability or the 20 ms delay-range check.--### Linear path--- stable short and 64 ms FIRs pass both validation and held-out scoring;-- gain changes, moving delays, time-varying FIRs, late-only corruption, and unrelated microphone- noise fail the unchanged residual ceiling when appropriate;-- the final held-out samples are never used to choose or update coefficients; and-- deterministic replay is byte-identical at the JSON layer.--### Existing contracts--- retain every current manifest, privacy, hash, symlink, geometry, timing, no-overwrite, codec,- threshold, and report-shape test;-- verify report numbers are finite and the forbidden-key/privacy scan still passes; and-- verify the legacy stable delayed fixture still passes without changing its manifest thresholds.--## Execution order and gates--1. Add records and preprocessing helpers with unit tests; do not alter `measure` yet.-2. Add the global anchor and ambiguity fixtures. Stop if periodic/equal-peak cases can pass.-3. Add local observations and robust drift. Stop if +/-101 ppm can pass or a short fixture can- produce scored drift under the default 100 ppm gate. Stop if any scheduled window can disappear- while the remaining cluster still passes.-4. Add affine valid-support alignment and the stricter path fit. Stop on any zero padding, hidden- clamp, train/test overlap, or non-determinism.-5. Integrate with `measure`, preserving every frozen manifest and gate threshold.-6. Run the complete Python Stage 0 and Stage 0.5 suites, bytecode compilation, `git diff --check`,- and an unsigned Release build to verify that this tools-only change does not affect the app.- The Release step is build-only: never install or launch that artifact.-7. Route the implementation diff for adversarial review. Resolve every P0/P1 finding and rerun the- full offline matrix.-8. Freeze the analyzer source hash and test result, then replay the retained private manifest once- into a new exclusive mode-0600 report inside the private root. Do not copy, transcribe, play,- upload, expose PCM, or commit that private report.-9. Run the forbidden-key/privacy scan, construct a separate bounded numeric-only sidecar, compare- it with the frozen 2026-09-11 report, and document the disposition.--## Acceptance criteria--Implementation is complete only when:--- all synthetic identity, ambiguity, drift, path, privacy, and legacy tests pass;-- pure periodic and equally competing peaks still produce no delay observation;-- +/-50 ppm is scored, +/-101 ppm is rejected, and any +/-99 ppm acceptance proves its complete- uncertainty interval stays inside the unchanged 100 ppm ceiling;-- every scheduled window resolves across the complete scheduled support, at least five- observations and three long-baseline slopes exist, and no outlier is silently discarded;-- an unresolved estimate cannot populate delay, drift, alignment, or path metrics;-- null/unscored drift, alignment, coverage, or path always prevents `proceedToCandidate`;-- all alignment output is backed by measured samples and combined valid coverage is at least 0.99;-- the path metric is the worse of disjoint validation and held-out residuals and is at most 0.75;-- the analyzer remains bounded, deterministic, dependency-free, and privacy-safe;-- adversarial review returns no P0/P1 blocker; and-- the retained corpus is replayed no more than once after the implementation and tests are frozen.--If the replay still fails, record the unchanged blocker and stop. The next possible step would be a-separately planned fixture redesign; no new capture follows automatically. If it passes, report-only that the acoustic half of the gate is satisfied. The current false callback-adapter-eligibility and a separate reviewed implementation decision still block AEC3.--## Adversarial review disposition--The standard router served Grok 4.6 with the plan text only and reported `editedTree=false`. Its-first review returned `BLOCK` on four gate-integrity issues: the original local search could miss-part of the frozen delay range and pass on a surviving middle cluster; null drift was not stated as-a hard candidate failure; three observations/one long pair could not support the claimed outlier-robustness; and the summed acoustic/PTS/render-lead boundary tests were incomplete.--This revision addresses those findings with mandatory full-span scheduled windows, a +/-24 ms-local search, five-to-eight required observations, three or more long-baseline pairs, uncertainty--bounded all-pair drift rejection, explicit null-is-ineligible semantics, and signed-clock boundary-fixtures. It also adopts the non-blocking recommendations for non-overlapping energy windows,-standard-library-only implementation, `max(validation, held-out)` scoring, a private uncommitted-mode-0600 replay report, and build-only Release verification.--Two delta-only plan rechecks reached the router's Grok time limit without a verdict and again-reported `editedTree=false`; no unauthorized fallback was used. After implementation, a bounded-contract review containing the exact estimator, alignment, path, test, privacy, and Release-properties was served by Grok 4.6. It returned PASS with no P0/P1 finding and `editedTree=false`.-Its P2 observation that the frozen 0.75 residual ceiling is weak does not change that registered-threshold and does not authorize AEC.--The frozen analyzer and tests were hashed after the full offline matrix passed. The retained-private corpus was then replayed exactly once. It remained `rejected`: delay stayed unresolved,-so drift, aligned coverage, and path evidence remained unscored. The bounded privacy-safe summary-is `meeting_playback_stage05_delay_estimator_builtin_2026-09-11.json`. Per the stop condition,-there is no second replay, threshold change, new capture, or AEC3 work in this phase.--A later, separately authorized operator-media capture is documented in `MEETING_STAGE05_EVIDENCE.md`-and `meeting_stage05_operator_media_2026-09-11.json`. Its first analyzer invocation stopped on an-unrecognized pinned descriptor before signal scoring. After a narrow two-digest provenance-allowlist fix, the corrected invocation performed the corpus's only signal analysis and preserved-the same ambiguity stop. That follow-up neither reopens this plan's retained-corpus replay nor-changes any estimator, path model, threshold, or AEC decision.--## Rollback--This phase is isolated to offline Python and documentation. Rollback removes the new estimator-records/helpers, restores the original `measure` path, and deletes only the newly generated replay-report. It never touches the retained WAVs, manifest, installed app, production runtime, profile-state, or frozen earlier reports.diff --git a/tools/MEETING_STAGE05_EVIDENCE.md b/tools/MEETING_STAGE05_EVIDENCE.mddeleted file mode 100644index 8e4ca594..00000000--- a/tools/MEETING_STAGE05_EVIDENCE.md+++ /dev/null@@ -1,261 +0,0 @@-# Stage 0.5 paired ScreenCaptureKit evidence--This is a DEBUG-only, one-shot capture harness for the signal-domain gate. It is not a-production capture path and it does not start unless all of the following are set:--```text-FLUIDVOICE_STAGE05_EVIDENCE=1-FLUIDVOICE_STAGE05_EVIDENCE_AUTORUN=1-FLUIDVOICE_STAGE05_TARGET_BUNDLE_ID=com.google.Chrome-FLUIDVOICE_STAGE05_EVIDENCE_CONSENT=I_CONFIRM_STAGE05_RECORDING_CONSENT-FLUIDVOICE_STAGE05_EVIDENCE_ROOT=/private/tmp/fv-stage05-evidence.<unique-suffix>-FLUIDVOICE_STAGE05_FIXTURE_PATH=<absolute path to the checked-in stimulus HTML>-```--For the separately consented operator-media variant, the fixture path instead identifies the-checked-in operator-media descriptor and this additional exact token is required:--```text-FLUIDVOICE_STAGE05_OPERATOR_MEDIA_CONSENT=I_CONFIRM_OPERATOR_CONTROLLED_WEB_MEDIA-```--That variant selects exactly one live Chrome window with a nonzero ScreenCaptureKit window ID and-a finite frame of at least 640 by 360 points. It retains the exact Chrome bundle/PID and selected--window filter checks, but neither reads nor persists a page title or URL. Zero or multiple eligible-windows fail before capture. The same route, volume, duration, format, privacy, cleanup, and hard-watchdog gates apply.--Open the controlled Chrome stimulus in its `FluidVoice C2 Diagnostic Stimulus — READY` state.-After the harness emits the generic `{"status":"ready"}` line, click Start; it then requires-that same window/owner/PID to transition to exactly one matching-`FluidVoice C2 Diagnostic Stimulus — PLAYING — 22s` (or greater) window and a unique display-intersection.-The READY-to-PLAYING operator-response window is limited to thirty seconds; no stream or audio-capture exists during that wait. Once playback starts, the exact title must still report at least-22 seconds remaining. A separate 56-second hard process-watchdog leaves margin around the declared start/stop budgets without changing the fourteen-second-target or twenty-second frame ceiling. Fixed-name emergency cleanup is registered before either WAV is created.-It requires Screen Recording and microphone permission, the default built-in speakers, and the-default built-in microphone; exact input/output UIDs and the route are rechecked after capture.-It captures one fourteen-second `SCStream` with `.audio` and-`.microphone`, requesting mono at 48 kHz. Every callback is checked against its actual native-ASBD; no resampling, downmixing, or float-to-integer conversion is performed. The runtime accepts-only little-endian mono packed IEEE float32 at 48 kHz. Float samples must all be finite. A format-change, stereo/non-PCM callback, missing timing, gap, overlap, or-resource bound failure invalidates the run.--On success the private root contains `render.wav`, `capture.wav`, `provenance.json`, and `manifest.json`. WAV payload-bytes preserve the native callback bytes. The manifest stores relative artifact names, SHA-256-hashes, codec/geometry, and per-callback presentation time, duration, frame count, and monotonic-arrival time. The provenance sidecar contains only hashes (including the exact capture executable-and fixture), build/configuration identity, the validated route and volume, peaks, and counts; it contains no PCM, transcript text, window title, URL,-device name, UID, or absolute path. The output line is only a generic status. Existing-`MeetingSignalDomainGate.loadManifest(from:)` and `evaluate(manifest:sessions:)` consume this-manifest; no AEC dependency or production behavior is enabled by the harness.--The root must be a uniquely suffixed `/private/tmp/fv-stage05-evidence.*` path to a new or empty-mode-0700 directory and must not contain the-fixed artifact names. Failed runs-remove partial WAV/manifest artifacts. Do not point the harness at a production recording store,-cloud-synced directory, or a corpus without consent from every participant.--## Observed run — 2026-09-10--One controlled run completed successfully at the capture layer. The private mode-0700 root-contained four mode-0600 artifacts. Numeric provenance recorded 280 render blocks / 268,800-frames and 521 microphone blocks / 266,752 frames; output volume remained 0.25, render peak was-0.036000002, and microphone peak was 0.06660158. Hash, schema, route, format, consent, and timing-validation passed. PCM was not played, transcribed, or copied into the repository.--The privacy-safe gate result is `meeting_playback_stage05_builtin_2026-09-10.json`. The session-was rejected for `lowExcitation`, `driftUnscored`, and `linearPathUnlearnable`. Five seconds at the-registered 1 kHz delay-tracker resolution cannot substantiate the frozen 100-ppm drift bound. The-user also reported possible incidental noise, so the result does not establish a general failure-of paired SCK; it establishes only that this session cannot authorize candidate/AEC3 work.--## Longer clean calibration — 2026-09-10--A stationary broadband fixture was tried in a user-confirmed quiet window. The first longer run-failed closed at the 960,000-frame ceiling because repeated relative sleeps accumulated scheduler-delay. The harness now uses an absolute monotonic deadline, targets fourteen seconds, and reports-only fixed privacy-safe finalization categories. The corrected run reached-`finalizeRenderTiming`: the selected-window render callbacks did not satisfy the frozen contiguous-timing invariant over the longer window. Both failed runs removed every partial artifact; no PCM,-manifest, or report was retained.--This result does not establish that acoustic echo cancellation is impossible. It establishes that-the raw selected-window ScreenCaptureKit reference cannot yet authorize an echo-canceller trial:-an explicitly tested synchronizer would first need to preserve and handle the observed render-timing discontinuity without flattening or inventing samples.--The offline synchronizer follow-up replays 1,400 ten-millisecond render and microphone blocks-with a two-millisecond reference PTS jump at the midpoint. The test initially exposed that the-gap mask was correct but the adaptation-freeze and resynchronization-boundary controls were not-set. The synchronizer now freezes adaptation for incomplete coverage or a reset boundary, marks-the PTS-jump boundary explicitly, keeps the 32 missing analysis samples invalid, and resumes in a-new epoch. The full 47-test synchronizer suite and combined 61-test Stage 0.5 suite pass. This is-offline evidence only; it does not authorize or enable a production echo canceller.--## DEBUG callback adapter and mock seam — 2026-09-11--`MeetingStage05SCKFrameAdapter` is a DEBUG-only, bounded bridge for native ScreenCaptureKit-`CMSampleBuffer` callbacks. It keeps callback PTS, monotonic arrival time, and independent-per-track arrival sequence as separate facts. It maps render callbacks to reference PTS and maps-microphone callback PTS to source sample time; it never derives either clock from concatenated WAV-length. Unsupported formats/rates, non-finite samples, invalid geometry, and resource overruns are-rejected. Gaps, overlaps, backward timestamps, discontinuities, and rejected-callback sequence-holes remain visible to the pure synchronizer.--`MeetingStage05MockAECSeam` is an identity contract checker, not an echo canceller. It returns the-synchronized sample arrays unchanged, authorizes nothing for failed-open, empty, or structurally-invalid results, resets once per epoch boundary, freezes every incomplete/reset hop, and emits an-eligible hop's render event before its capture event. A boundary that falls partway through a hop-cannot cause a second reset when the integer epoch label advances on the next hop.--The synthetic 48 kHz matrix covers contiguous callbacks; one-sample, 2 ms, 10 ms, and 100 ms-gaps; repeated gaps; overlaps and backward timestamps; discontinuities; rejected callbacks;-format/rate failures; bounds; drift; deterministic replay; and native `CMSampleBuffer` extraction.-A 2 ms internal hole maps to exactly 32 invalid samples at 16 kHz. Unmatched leading or trailing-track coverage remains separately invalid and is not miscounted as part of that internal hole.--For a completed `renderTiming` or `captureTiming` finalization failure only, the DEBUG evidence-collector now deletes both WAVs plus manifest/provenance and may retain one exclusive mode-0600-`timing.json`. That versioned record contains numeric callback timing/geometry and derived counts-only—no PCM, peaks, hashes, UIDs, PIDs, titles, paths, labels, transcripts, or provenance. All-other failures, cancellation, abort, and watchdog cleanup retain nothing. The existing contiguous-WAV success gate is unchanged.--This implementation has not run another browser, speaker, or microphone capture and does not add-AEC3 or any production meeting-runtime behavior. The separately reviewed implementation plan is-`MEETING_STAGE05_LIVE_ADAPTER_IMPLEMENTATION_PLAN.md`.--Final offline verification passed on 2026-09-11: 89 signed Swift tests (47 synchronizer, 14-evidence-harness, 4 timing-record, and 24 adapter/mock-seam), 19 Python signal-gate tests, Python-bytecode compilation, and the unsigned Release build. A symbol/string scan of the Release binary-found none of the Stage 0.5 adapter, mock seam, timing-record, autorun, or diagnostic-gate symbols.-The final read-only Grok 4.6 adversarial review returned PASS with no P0/P1 finding after verifying-the DEBUG isolation, resynchronization naming/gating, bounded `Int64` conversion, fail-open mock-behavior, and timing-only artifact lifecycle.--## Real callback attachment — 2026-09-11--The DEBUG-only Stage 0.5 evidence stream now feeds each real ScreenCaptureKit `.audio` and-`.microphone` callback to both the existing WAV collector and `MeetingStage05SCKFrameAdapter`.-It samples the monotonic arrival clock exactly once at the callback boundary and shares that value-between both consumers. Other SCStream output types are ignored without sampling the clock.--After `stopCapture`, the dedicated render and microphone queues are both drained synchronously.-Only then is the adapter drained and synchronized once and the identity/mock AEC seam processed-once. A structural synchronization or ordering failure deletes all PCM and returns the fixed-`adapterGate` failure. Gaps that are safely masked and frozen remain valid diagnostic evidence but-cannot set `eligibleForAECTrial`.--The one-shot stdout outcome now includes a bounded `adapter` object containing integers, Booleans,-and one finite drift value only. It reports callback anomaly counts, synchronizer resource and mask-counts, and mock reset/freeze/order counts. It contains no callback timestamps, PCM, peaks,-identifiers, hashes, PIDs, titles, paths, labels, transcripts, or provenance. This does not create a-new file or weaken the mutually exclusive WAV-success and timing-only-failure artifact states.--Offline verification passed 94 signed Swift tests: 47 synchronizer, 14 evidence-harness, 4 timing-record, 24 adapter/mock-seam, and 5 real-callback/summary tests. Grok 4.6's read-only adversarial-review returned PASS with no P0/P1 blocker for one separately cued controlled calibration. No live-capture, stimulus, app reinstall, or AEC was performed as part of this implementation step.--## Controlled real-callback calibration — 2026-09-11--One separately cued fourteen-second run completed the strict PCM collector successfully. The-private mode-0700 root contains four original mode-0600 evidence artifacts plus the mode-0600-offline report; PCM was not played, transcribed, or copied into the repository. Numeric provenance-recorded 702 render callbacks / 673,920 native frames and 1,313 microphone callbacks / 672,256-native frames. Output volume remained 0.25, render peak was 0.037170984, and microphone peak was-0.03196026.--The privacy-safe callback result is `meeting_stage05_live_adapter_builtin_2026-09-11.json`.-Every callback was accepted with zero reported gap, overlap, backward-timestamp, discontinuity,-or format-change events. The synchronizer and mock seam remained structurally closed and preserved-render-before-capture ordering. The simultaneous stop left 555 unmatched 16 kHz microphone-tail-samples, so four edge analysis frames were masked and frozen; `eligibleForAECTrial` is therefore-false despite collector success.--The frozen signal-gate result is `meeting_playback_stage05_builtin_2026-09-11.json`. It rejects-this session for `delayUnresolved`, `driftUnscored`, `unstablePath`, and-`linearPathUnlearnable`. Common-span diagnostics found healthy excitation RMS (0.0110116), zero-clipping, strong low/mid/high band coherence (0.956881 / 0.916681 / 0.515547), but no sufficiently-prominent delay observation and a held-out linear residual of 0.777411 against the frozen 0.75-ceiling. The analyzer already uses the common render/capture span, so merely copying or trimming-the WAVs would not change this result. Grok 4.6's read-only result review returned BLOCK for any-AEC3 dependency or live trial. The retained corpus is suitable for offline delay-estimator and-path-model investigation only; no additional capture is authorized by this result.--## Offline delay-estimator implementation — 2026-09-11--The offline analyzer now separates acoustic array lag, callback PTS offset, and render lead. A-whole-span non-overlapping energy-envelope anchor narrows a mean-removed/first-differenced 4 kHz-search, followed by native-rate refinement. Five-to-eight local windows cover the complete-analyzable span; every scheduled window must resolve, and all long-baseline slope uncertainty-intervals must remain inside the frozen drift ceiling. Missing delay, drift, alignment, coverage,-or path evidence is ineligible rather than zero-valued.--The native refinement uses a maximum three-bin 4 kHz neighborhood. A one-bin neighborhood was-tested and rejected because ordinary +/-50 ppm affine fixtures spread the three-second-box-decimated peak across adjacent bins and falsely failed at the final scheduled window. The-wider native search remains downstream of the unchanged score/prominence ambiguity gate and still-requires an interior maximum with at least half-native-sample uncertainty.--Aligned samples now come only from the measured affine common support; no edge is padded, repeated,-or clamped. Coherence and path scoring share that support. The 64 ms/256-tap path remains bounded,-uses fixed train-only NLMS passes, and reports the worse of disjoint validation and final held-out-residuals against the unchanged 0.75 ceiling.--Offline regression coverage now includes periodic and equal-peak ambiguity, full-span required-windows, resolved late outliers, +/-50 ppm drift, outside-limit drift, signed acoustic/PTS/render--lead combinations, measured-support coverage, short-resolution failure, a fixed 64 ms FIR, and all-existing manifest/privacy/no-overwrite contracts. The frozen implementation passed 8 Stage 0 and-21 Stage 0.5 Python tests, bytecode compilation, whitespace checks, and an unsigned Release build.-Grok 4.6's final routed implementation-contract review returned PASS with no P0/P1 finding.--The retained private corpus was then replayed exactly once into a new exclusive mode-0600 report.-The privacy-safe repository summary is-`meeting_playback_stage05_delay_estimator_builtin_2026-09-11.json`. The new estimator preserved-the ambiguity stop: it resolved no delay, so drift, measured-support alignment, coverage, and path-metrics remained unscored. The aggregate outcome is `rejected`, with one count each for-`delayUnresolved`, `driftUnscored`, `insufficientCoverage`, `unstablePath`,-`linearPathUnscored`, and `noEligibleSessions`. The analyzer source SHA-256 was-`3379f9a36fdda278e47ac64af8fe7c7e3fc0fd583bb8518e25e793d85cbf7336`; the Stage 0.5 test SHA-256-was `602f6c85632e3cdc90fd539f056d8dd3a1f4b587599311f51dea580b2897e313`.--No PCM was played, transcribed, copied to the repository, or captured again. The one-replay stop-condition is now closed. The acoustic gate and the separate callback-adapter gate are both false,-so AEC3 remains blocked. Any next evidence attempt requires a separately reviewed fixture redesign-and a newly authorized capture; it is not an automatic continuation of this phase.--## Operator-controlled speech capture — 2026-09-11--After separate user authorization, one fourteen-second operator-media capture completed. Earlier-selection and setup refusals retained no artifacts; one out-of-bounds finalization attempt also-aborted and removed its partial corpus. The successful private mode-0700 root contains only the-four original mode-0600 evidence files and two immutable mode-0600 analyzer reports. Playback was-paused immediately afterward, and the temporary system-volume reduction was restored.--The successful callback stream had 703 accepted render callbacks and 1,313 accepted microphone-callbacks, with no rejected callback, gap, overlap, backward timestamp, discontinuity, format-change, resource failure, late/duplicate frame, non-finite sample, synthesized microphone frame,-or failed-open state. Synchronization produced 224,960 samples per track; all render samples and-224,085 microphone samples were valid. Six edge analysis frames were frozen, so the separate-callback-adapter `eligibleForAECTrial` value remains false even though the mock identity contract-processed 1,400 frames with render-before-capture ordering.--The first offline invocation produced an immutable `invalidManifest` report because the analyzer-recognized only the original broadband fixture digest. The narrow fix replaces that equality with-an immutable two-entry allowlist containing the broadband fixture and the exact checked-in-operator-media descriptor; an unknown valid-looking digest is still rejected. The corrected-invocation accepted the manifest and performed the only signal analysis of this corpus. It rejected-the session for `delayUnresolved`, `driftUnscored`, `insufficientCoverage`, `unstablePath`, and-`linearPathUnscored`, with `noEligibleSessions` at the aggregate level. No metric was fabricated-after the acoustic delay remained ambiguous.--The bounded repository record is `meeting_stage05_operator_media_2026-09-11.json`. The analyzer-and its 21-test suite passed locally after the allowlist change. No PCM was played back by the-analyzer, transcribed, copied, uploaded, or committed; the record contains no title, URL, identity,-path, or content. Both the acoustic gate and callback-adapter gate are false, so AEC3 remains-blocked and no further live capture follows from this result.diff --git a/tools/MEETING_STAGE05_LIVE_ADAPTER_IMPLEMENTATION_PLAN.md b/tools/MEETING_STAGE05_LIVE_ADAPTER_IMPLEMENTATION_PLAN.mddeleted file mode 100644index 66709f47..00000000--- a/tools/MEETING_STAGE05_LIVE_ADAPTER_IMPLEMENTATION_PLAN.md+++ /dev/null@@ -1,129 +0,0 @@-# Stage 0.5 live-callback adapter implementation plan--## Decision--Implement a DEBUG-only bridge from bounded ScreenCaptureKit callback buffers into the existing-offline `MeetingReferenceSynchronizer`, followed by an identity/mock AEC contract checker. This-phase does not add an echo canceller, alter production capture, or run a live microphone test.--The previous long controlled capture failed because the selected-window render callback timeline-was discontinuous. Concatenating those callback bytes would erase the gap and create a false clock.-The adapter therefore places every block from its presentation timestamp, preserves discontinuity-evidence, and lets the synchronizer produce explicit invalid masks, epochs, freezes, and resets.--## Scope and order--### 1. Add a testable ScreenCaptureKit frame adapter--Add `MeetingStage05SCKFrameAdapter.swift` behind `#if DEBUG`.--- Validate callback PCM and ASBD without writing files: native packed mono Float32, finite samples,- finite nonnegative timing, bounded geometry, and an exact supported sample rate.-- Map render callbacks to `MeetingReferencePCMFrame` using callback PTS as `presentationTime`.-- Map microphone callbacks to `MeetingMicrophonePCMFrame` using PTS converted to the sample-rate- timescale as `sampleTime`; never use cumulative samples written.-- Record callback arrival time separately as microphone `hostTime`.-- Maintain independent render and microphone sequence spaces because callbacks arrive on separate- serial queues.-- Detect one-sample-or-larger PTS gaps, overlaps/backward timestamps, explicit discontinuity- attachments, and format/rate transitions. Preserve overlapping/late blocks as synchronizer inputs- and diagnostics; the synchronizer remains responsible for first-arrival-wins rejection.-- Inject a route identifier from the caller. The adapter must not infer or log a device identity.-- Collect bounded arrays and call the pure synchronizer only after both callback queues are drained.--### 2. Add an identity/mock AEC seam--Add `MeetingStage05MockAECSeam.swift` behind `#if DEBUG`.--- Consume `MeetingSynchronizationResult` and return audio arrays unchanged.-- Emit only numeric observations plus `MeetingAECDelayContractEvent` ordering events.-- For each synchronized hop, handle an epoch change or resynchronization boundary before any normal- processing, freeze on every incomplete mask or `adaptationFrozen` hop, and emit render before- capture for eligible hops.-- Never resample, delay, scale, suppress, synthesize, or replace audio.-- Treat a failed-open, empty, or structurally invalid synchronization result as a no-op that- cannot authorize processing.--### 3. Retain privacy-safe timing evidence only on completed timing failures--Extend the DEBUG Stage 0.5 collector with a separate versioned timing-failure record.--- The successful WAV path remains unchanged and continues to reject any timing gap or overlap.-- Only completed `.renderTiming` or `.captureTiming` finalization may retain `timing.json`.-- Before writing it, close and unlink both WAV files, manifest, and provenance.-- Create `timing.json` atomically/exclusively with mode `0600` inside the existing validated private- `/private/tmp/fv-stage05-evidence.*` root.-- Store numeric callback timing and derived counts only: schema, fixed failure category, track,- presentation time, duration, frame count, arrival time, and gap/overlap/backward/format-change- counts. Do not store PCM, peaks, hashes of PCM, UIDs, PIDs, titles, paths, labels, transcripts, or- executable/fixture provenance.-- All non-timing failures retain nothing. Cancellation, timeout, watchdog, and emergency cleanup- must delete `timing.json` as well as the existing artifacts.-- Enforce mutual exclusion: either successful WAV evidence exists or a timing-only failure record- exists, never both.--### 4. Add deterministic offline tests--Use synthetic `CMSampleBuffer` values or constructed adapter frames only. Tests must never create an-`SCStream`, open Chrome, access a microphone, or install an app.--Cover:--- contiguous paired callbacks and causal render-before-capture events;-- render and microphone gaps of 1 sample, 2 ms, 10 ms, 100 ms, and multiple hops;-- repeated gaps separated by a valid island;-- 1-sample, half-frame, and duplicate-timestamp overlaps;-- sequence disorder and forward sequence with backward PTS;-- explicit discontinuity with otherwise contiguous timing;-- sample-rate/format and route transitions;-- bounded drift cases already supported by the synchronizer configuration, including fail-open and- failed-open thresholds without estimating drift from SCK callback PTS;-- exact invalid-sample masks, adaptation freezes, resynchronization boundaries, epoch changes, and- deterministic replay;-- mock-seam audio equality and event ordering;-- timing-only retention, non-timing cleanup, watchdog cleanup, file modes, schema validation, and a- forbidden-key/privacy scan.--### 5. Document and verify--- Update `MEETING_STAGE05_EVIDENCE.md` to distinguish contiguous WAV evidence from timing-only- failure characterization and to state that the mock seam performs no cancellation.-- Add any explicit test file references required by `Fluid.xcodeproj/project.pbxproj`.-- Run the focused synchronizer, Stage 0.5 evidence, adapter, and mock-seam tests; run a signed DEBUG- build and an unsigned Release compile check; run `git diff --check`.-- Do not reinstall the app and do not run live audio in this phase.--## Non-negotiable invariants--1. Callback PTS, callback arrival time, sequence order, and sample placement remain distinct facts.-2. Gaps become invalid masks and reasons, never valid zero-valued silence.-3. First arrival wins; overlaps and late blocks cannot overwrite accepted samples.-4. Epoch/reset and a missing interval are separate concepts; a contiguous discontinuity may reset- without inventing a gap.-5. Exactly one component owns each operation: the adapter validates/places callbacks, the- synchronizer maps clocks and masks coverage, and the mock seam checks AEC-facing ordering.-6. No component in this phase owns acoustic delay or estimates clock drift from paired SCK PTS.-7. Resource limits remain bounded by the existing 2,000-block and 960,000-frame ceilings.-8. Release and normal runtime behavior do not change.--## Acceptance criteria--- New adapter and mock seam are DEBUG-only and absent from Release compilation symbols.-- An adapter-driven 2 ms render jump yields exactly 32 invalid 16 kHz render samples inside the- internal gap (independent unmatched track tails remain separately invalid), freezes adaptation,- creates a resynchronization boundary/new epoch, and resumes valid output.-- Contiguous mock events validate as render then capture; gaps/resets never produce capture-first- processing; all input/output audio arrays compare equal.-- A timing-finalization failure leaves only a valid mode-`0600` numeric `timing.json`; every PCM,- manifest, and provenance artifact is absent. Other failures leave no timing artifact.-- Existing synchronizer and Stage 0.5 tests remain green, the WAV success gate remains contiguous,- and no AEC/WebRTC dependency or production path is added.--## Explicitly out of scope--- Live microphone, browser stimulus, ScreenCaptureKit capture, app installation, or privacy prompts.-- AEC3/WebRTC or any audio-transforming canceller.-- Acoustic delay measurement, render-lead tuning, or shared-clock calibration.-- Treating gapped/metadata-only evidence as a successful signal-domain gate.-- Production meeting-runtime wiring, streaming synchronization, or changes to ASR, export,- attribution, speaker profiles, or user-visible behavior.diff --git a/tools/MEETING_TEMPORAL_SHADOW_B1.md b/tools/MEETING_TEMPORAL_SHADOW_B1.mddeleted file mode 100644index bcb09b3d..00000000--- a/tools/MEETING_TEMPORAL_SHADOW_B1.md+++ /dev/null@@ -1,70 +0,0 @@-# Temporal shadow detector B1 — development evaluation--Date: 2026-09-08 (local). Offline experimental implementation, not a caption fix or release gate pass.--Follow-up: B2 completed the previously pending scoped reviews, fixed temporal lag/budget issues, and added local activity comparison. See `MEETING_SPEECH_SHADOW_B2.md` for current review dispositions and results; historical B1 hashes/measurements below identify the earlier run.--## Outcome--The first normalized-waveform operating point produced **zero duplicate-supported windows** on all three development recordings. This is a negative feasibility result for this particular feature/operating point, not proof that the microphone contains no playback or that speech is safe to accept. Thresholds were not lowered to fit these recordings.--The installed app, legacy admission behavior, saved transcripts, speaker profiles and original audio were not modified. The detector has no production caller; the only executable caller outside tests is the explicitly invoked local evaluator. No new runtime flag, model, network call or persistence schema was added.--## Implementation and limits--- `MeetingPlaybackDuplicateDetector.swift` consumes explicitly resampled mono 2 kHz windows with original PTS and validity masks. Positive lag means microphone follows playback. It searches ±0.5 seconds in 1 ms increments, measures mean-centered absolute normalized correlation and compares its peak with an eight-second-shifted reference control and separated competing peaks.-- Support requires three consecutive two-second windows whose lag spread is at most 12 ms. History is capped at three windows by default (configuration capped at 16). Epoch/session/route changes, gaps, unavailable coverage and failed support clear accumulated evidence. No stale supported state survives reference loss.-- There is no release hangover in this first experiment. Updates still have two-second resolution; zero hold does **not** mean zero detection/release latency. Synthetic perfect-copy lock requires six seconds of observations. Reports do not backdate support into earlier windows or claim sub-window onset precision.-- The 0.25 correlation, 0.08 control margin, 0.025 competing-peak margin, 1e-5 RMS floor and timing settings are experimental engineering constants. Configuration is captured in sidecars. They are neither probabilities nor calibrated speech-admission thresholds.-- The caller uses AVAudioConverter anti-aliased resampling, clips decoded samples to recorded chunk end, linearly maps fractional PTS to a common grid and invalidates overlapping chunk coverage. It masks either-track recorded discontinuities by ±2 seconds, matching the existing pipeline guard. It additionally masks 50 ms at decoded/chunk edges conservatively; this is not an independently verified AAC priming model. Missing-PTS discontinuities fail the offline run rather than invent an epoch.-- Only recorded discontinuities can be reconstructed. Unrecorded route/sample-clock changes remain a limitation; lag instability can reset support but is not a verified clock-drift correction. No live reuse or source-rate-change guarantees are claimed.-- Low-energy mic/reference/control windows remain insufficient evidence. A missing control is not a zero-valued negative control. Periodic signals and equal control matches cannot lock in the synthetic tests.-- A synthetic quiet local signal added while playback is already supported **still leaves a supported match**. This explicitly demonstrates why temporal evidence alone must never hide speech. Nonlinear residual separation, near-end activity and interval admission are not implemented here.-- The evaluator is capped at 600 seconds, 32 chunks, two tracks, 65 seconds per decoded chunk, bounded formats/file sizes and one synchronous job. Per-window scoring has an injectable 0.5-second budget, checked each lag; three repeated budget failures disable the contribution for that detector instance. These local measurements do not constitute an hour-long capture-load test or a hard real-time deadline guarantee.--## Local numeric results--Final sidecars are `/private/tmp/fv-temporal-{3774,88e3,3b9a}-v2.json`; earlier v1 sidecars precede the explicit silent-reference/control check and are superseded. Input session and audio hashes are in each sidecar; no text, embeddings or raw audio is emitted. Durations below are recorded audio PTS spans, not UI session durations.--| Development session | Audio span | Windows | Scored/inconclusive | Invalid coverage | Low energy | Supported | Median diagnostic lag | Median peak correlation |-| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |-| `3774ED4C…` | 98.756 s | 49 | 44 | 5 | 0 | 0 | +70 ms | 0.104 |-| `88E3BD44…` | 260.323 s | 130 | 98 | 18 | 14 | 0 | +86 ms | 0.129 |-| `3B9AC1A8…` | 131.870 s | 65 | 54 | 11 | 0 | 0 | +62 ms | 0.075 |--Unwindowed tails are respectively 0.756, 0.323 and 1.870 seconds and remain unmeasured. Invalid/low-energy windows contribute another 10, 64 and 22 seconds of unknown coverage. Even the scored windows are inconclusive, not negative speech evidence. Diagnostic best-lag ranges are respectively −500…+350, −491…+479 and −491…+469 ms; their medians are **not delay locks**. Peak correlations never reached 0.25 (maxima 0.190, 0.2495 and 0.175).--Maximum measured optimized scoring time per window was 4.72 ms. End-to-end local runs took 0.67, 0.58 and 0.31 seconds, with maximum resident sizes about 40.5, 42.7 and 41.1 MB. These are single-machine development profiles, not frozen acceptance budgets.--No real lock-onset, hold/release error, missed-speech or false-word rate can be estimated from these runs: there were no locks and no independent interval annotations. The scripted portion remains development material. Detector-disabled comparison is structurally unchanged because no production code consumes the reports; an end-to-end policy ablation belongs to B3.--## Reproduce safely--Compile from the repository root:--```sh-swiftc -module-cache-path /private/tmp/fv-reliability-swift-cache -O \- Sources/Fluid/Services/Meeting/MeetingPlaybackDuplicateDetector.swift \- Sources/Fluid/Services/Meeting/MeetingSpeechActivityDetector.swift \- tools/meeting_temporal_shadow.swift -o /private/tmp/fv-temporal-shadow-```--Invoke with an explicitly selected `session.json` and a new output path outside that session directory. Output creation is exclusive. Local macOS codec access may require the normal host execution permission; no network permission or audio upload is involved. Sidecars are temporary development artifacts, not new session data; keep only for the review and remove explicitly when no longer needed (there is no automatic cleanup job).--## Next gate--Do not connect this operating point to suppression or speaker-profile eligibility. B2 needs independently validated speech activity and combined/mixed-interval evidence; B3 needs annotated controls and calibration/ablations. A more robust temporal feature may be needed for nonlinear low-correlation residuals. This document does not broaden implementation scope to a new model or dependency.--## Verification and review status--Final isolated `FluidASRBaseline` build succeeded. All 31 targeted tests passed with zero failures/skips: 11 new detector tests, 15 Stage A contract tests and five existing live diagnostic tests. Result: `/private/tmp/fv-temporal-b1-v3.xcresult`. Tests cover lag sign/shift, repeated support, periodic/wrong/control references, quiet-double-talk confounding, epoch/route/gap resets, masked/missing reference, no-hold release, delay jumps, silent reference, invalid inputs and injected budget exhaustion. Broader app/Release and held-out evaluations were not run.--Kimi K3's code-review call and continuation timed out (180/300 seconds); the scoped Grok 4.6 fallback also timed out (180 seconds). No findings were returned and **external code sign-off is still pending**. Only authorized FluidVoice source was sent; no audio, transcript, embedding, secret or competitor code was sent. The local checks above are not a substitute for the outstanding review.--Source SHA-256 at evaluation:--```text-detector f580cb5857d7b1917e1569f15b10efafc2637740fbe3f72b4f922d0046dcc166-evaluator c607e67e408eb89532ea69f072dd5eec7c64591b2d595795847a8b0502020f48-tests d8ca22c8a759924dc7be6430a424c900ad5a0f4cf9e7540370c5d30a40710520-```diff --git a/tools/MEETING_TRIAL_A_EXTERNAL_REFERENCE.md b/tools/MEETING_TRIAL_A_EXTERNAL_REFERENCE.mddeleted file mode 100644index c916870d..00000000--- a/tools/MEETING_TRIAL_A_EXTERNAL_REFERENCE.md+++ /dev/null@@ -1,77 +0,0 @@-# Phase 0 Trial A — external Chrome reference--Trial A is a DEBUG-only, one-shot diagnostic. It captures selected `com.google.Chrome` audio from-one ScreenCaptureKit stream as a reference while the existing VPIO microphone capture runs in the-same short-lived signed process. It does not play audio, start ASR, retain transcripts, write-sessions, or change production capture behavior.--All three exact gates are required:--```text-FLUIDVOICE_TRIAL_A=1-FLUIDVOICE_TRIAL_A_AUTORUN=1-FLUIDVOICE_TRIAL_A_TARGET_BUNDLE_ID=com.google.Chrome-```--The launch hook performs Screen Recording and microphone permission checks, confirms the live-default input is built-in and the live default output is built-in speakers, reads output volume,-and applies the controlled fixture's 0.08 peak bound. It captures for at most five seconds, has a-12-second operation timeout and a 14-second process watchdog, stops the stream and VPIO on every-path, emits one sorted numeric `[TRIAL_A_AUTORUN]` line, and exits.--The report retains PCM only in memory during the bounded run and releases it immediately after RMS,-peak, timestamp, coverage, gap, overlap, format, and synthesized-timing reduction. It records the-selected Chrome PID and scope. ScreenCaptureKit PTS and the VPIO host-derived PTS are not treated as-a shared clock: acoustic delay, AEC, and attribution remain `unknown` unless a separately validated-clock bridge is added. No C2 or Trial B gate is consulted or triggered.--The deterministic offline harness tests exact gating, numeric-only output, and fail-closed timing-for gaps, overlaps, synthesized timing, malformed geometry, and unknown clock mapping.--## Stimulus readiness and launch order--The browser fixture is now a required readiness handshake. Its window title is `... — READY` until-the Start button is clicked and the `AudioContext` is successfully resumed; it changes to-`... — PLAYING` only while the 12-second fixture is active, then to `... — COMPLETE`. Trial A-requires a selected Chrome window whose title contains the PLAYING marker before it starts VPIO or-ScreenCaptureKit. It also resolves the display from that exact window by maximum positive frame-intersection and fails closed for no-intersection or equal-area multi-display ties. This makes a-not-yet-clicked or already-finished tab, or a window whose audio would be associated with the wrong-display, fail immediately instead of consuming the one-shot capture window. The PLAYING window's-owning `SCRunningApplication` is authoritative; duplicate/stale same-bundle application records are-not consulted for readiness or filtering.--Use this order for any separately authorized future run: open the localhost fixture, click Start,-confirm the browser title says PLAYING, then launch the signed DEBUG app promptly. Launching the app-first and clicking later is intentionally rejected.--## Unlocked built-in-route run — 2026-09-10--One safety-audited signed run completed on the built-in microphone and speakers at system volume-0.25. Route, volume, VPIO readback, selection, process stability, callback timing, and full interval-coverage all passed. The microphone delivered 53 valid callbacks with RMS 0.001411 and peak-0.007458. ScreenCaptureKit delivered 264 structurally valid reference callbacks, but every sample-was silent (RMS and peak 0). Therefore reference excitation was not confirmed and `captureValid`-and `acousticMeasurementValid` are both false. This result establishes microphone-side capture-health only; it provides no AEC, attenuation, delay, or topology-ranking evidence. Do not rerun-Trial A without a fresh safety review. The exact report is preserved in-`meeting_external_reference_trial_a_builtin_unlocked_2026-09-10.json`.--The zero-valued reference in that run is most consistent with fixture readiness/order, not a-ScreenCaptureKit timing or filtering failure: the selected Chrome stream delivered 264 callbacks-with complete, gap-free timing and no stream errors, but every sample was numerically zero. The-filter explicitly enables application audio, selects Chrome, and excludes only FluidVoice's own-process audio. Because the page click occurred after app launch and the old harness had no-cross-process PLAYING handshake, the run did not establish that Chrome was actively rendering the-fixture during the five-second window. A future zero reference would still be an invalid result,-but the readiness gate now prevents spending a run when that precondition is visibly absent.--Run only from the signed DEBUG app/process boundary after Chrome is already showing the controlled-0.08 localhost stimulus:--```sh-FLUIDVOICE_TRIAL_A=1 \-FLUIDVOICE_TRIAL_A_AUTORUN=1 \-FLUIDVOICE_TRIAL_A_TARGET_BUNDLE_ID=com.google.Chrome \-"/Applications/FluidVoice Debug.app/Contents/MacOS/FluidVoice Debug"-```diff --git a/tools/MEETING_VPIO_REFERENCE_PROBE.md b/tools/MEETING_VPIO_REFERENCE_PROBE.mddeleted file mode 100644index a151f01c..00000000--- a/tools/MEETING_VPIO_REFERENCE_PROBE.md+++ /dev/null@@ -1,195 +0,0 @@-# Meeting VPIO reference probe--Status: read-back slice implemented and exercised on 2026-09-10. This is configuration evidence,-not an acoustic AEC result.--## Scope and routing boundary--The normal meeting architecture is unchanged. Selected-application audio remains captured by-ScreenCaptureKit and is not rendered through VPIO. The probe only inspects the already-running-microphone VPIO. A later, explicitly diagnostic Trial B may render known local PCM through the-same engine; that will not reroute arbitrary application audio and is not part of this slice.--No production capture metadata, transcription, suppression, scoring, or speaker-profile policy is-changed by this probe. The installed app was not replaced.--## Read-back schema--`MeetingVoiceProcessingProbeSnapshot` records:--- input and output `kAudioOutputUnitProperty_CurrentDevice` values;-- each Audio Unit property ID, scope, element, `OSStatus`, and value for VPIO bypass, AGC, output- mute, and other-audio ducking;-- the corresponding `AVAudioInputNode` voice-processing getters;-- input/output node formats, presentation latencies, last-render host/sample times, engine running- state, and the input node's explicit output-connection count.--An unsuccessful Audio Unit read serializes its nonzero status and omits its value, preventing a-zero-initialized buffer from masquerading as a successful read. The JSON schema is versioned and-covered by a round-trip test.--## First built-in-route observation--Environment:--- MacBook Pro `Mac17,9`, macOS 26.6.2 (25G83), arm64;-- signed Debug test host using the existing stable Apple Development identity;-- built-in microphone to built-in speakers;-- 3-second capture, no deliberate playback stimulus.--Numeric sidecar:-[`meeting_vpio_reference_probe_builtin_2026-09-10.json`](meeting_vpio_reference_probe_builtin_2026-09-10.json)--Observed configuration:--- CurrentDevice input element 1 read back device 82; output element 0 read back device 87. Both- reads returned `OSStatus == 0`. The requested and settled UIDs independently identified those as- the built-in microphone and built-in speaker.-- Voice processing was enabled and not bypassed. AGC was enabled, input/output mute was off, and- advanced ducking was disabled at the minimum level (raw 10). The AVFoundation getters and raw- Audio Unit reads agreed.-- The VPIO input-side node format was 48 kHz, 9 channels; the capture tap delivered canonical- 48 kHz mono. The output-side node format was 48 kHz stereo.-- Both I/O nodes had valid last-render host and sample times. The input node had zero explicit- output connections, consistent with the current graph having no app-owned render source.-- Capture health for the short run was clean: 30 emitted buffers, 100% valid host time, zero- synthesized timestamps, conversion failures, continuity breaks, writer discontinuities,- backpressure events, or live-copy failures.--The system VoiceProcessor also logged repeated downlink errors saying its audio timestamp lacked a-valid sample time, followed by downlink DSP I/O faults, before the final snapshot showed valid node-render times. This is actionable configuration evidence, but it does not prove whether other-process-speaker audio is or is not available to Apple's echo reference. The acoustic A/B trials remain-required.--## Isolated harness and teardown finding--The `FluidVPIOProbe` scheme sets `FLUIDVOICE_MIC_PHASE1=0.05`. In that environment only, Debug-startup avoids normal FluidVoice UI/audio-service initialization so the app-hosted XCTest does not-create competing audio activity.--Reading the live output node exposed a macOS 26.6 AVFAudio teardown crash when the diagnostic then-called `setVoiceProcessingEnabled(false)` after stopping the engine. The crash was in-`AVAudioIONodeImpl::AUI()` during that explicit replacement. The probe now skips only that explicit-replacement and lets process exit release the diagnostic VPIO. Ordinary product `stop()` keeps the-existing explicit teardown behavior unchanged.--## Reproduce--Run the hardware-free schema tests:--```sh-xcodebuild -project Fluid.xcodeproj -scheme Fluid -configuration Debug \- -destination 'platform=macOS' -derivedDataPath /private/tmp/fv-vpio-probe test \- -only-testing:FluidDictationIntegrationTests/MeetingVoiceProcessingProbeTests-```--Run the 3-second signed built-in-route probe:--```sh-xcodebuild -project Fluid.xcodeproj -scheme FluidVPIOProbe -configuration Debug \- -destination 'platform=macOS' -derivedDataPath /private/tmp/fv-vpio-probe test \- -only-testing:FluidDictationIntegrationTests/MeetingMicrophoneCaptureTests/testPhase1HardwareGate-```--Use the repository's stable signing settings for the hardware command. Changing the value of-`FLUIDVOICE_MIC_PHASE1` in the diagnostic scheme changes the duration in minutes. Do not install the-test product over `/Applications/FluidVoice Debug.app`.--## Remaining Phase 0 work--This result establishes that VPIO is enabled, which devices its two elements use, and that an output-side is rendering despite no explicit app source. It does not establish echo attenuation or a usable-reference path. Next work is:--1. run the controlled external-stimulus Trial A and compare it with the engine-local Trial B below;-2. persist the printed numeric timing, delay, band-coherence, RMS, attenuation, and uncertainty sidecar;-3. compare bypass/AGC variants without changing production defaults;-4. only then compare the paired ScreenCaptureKit topology and decide whether an Apple-only graph fix- is sufficient.--## Controlled engine-local Trial B--The DEBUG-only `MeetingVPIOAcousticTrialB` renders a deterministic log-sweep plus speech-like-stimulus through an `AVAudioPlayerNode` attached to the existing VPIO engine mixer. A mixer tap is-the engine-local render reference; the microphone tap is the VPIO capture. The probe runs three-short, exclusive variants: default processing, AGC disabled, and voice processing bypassed (a-variant is marked invalid if a public setter/read-back cannot be applied). The signed delay-convention is `capture time - render time`: positive means the VPIO capture lags the local render.--Run it only from the isolated signed Debug scheme. Both explicit environment gates are mandatory:-`FLUIDVOICE_VPIO_ACOUSTIC=1` and a finite `FLUIDVOICE_MIC_PHASE1` duration strictly above zero and-at most 0.25 minutes (15 seconds); the process must be built with `DEBUG`:--```sh-xcodebuild -project Fluid.xcodeproj -scheme FluidVPIOProbe -configuration Debug \- -destination 'platform=macOS' -derivedDataPath /private/tmp/fv-vpio-probe test \- -only-testing:FluidDictationIntegrationTests/MeetingMicrophoneCaptureTests/testPhase1HardwareGate-```--The test prints one JSON result containing only the stimulus descriptor and, per variant, property-read-backs plus render/capture valid counts, overlap, signed delay, correlation, render/capture RMS,-attenuation in dB, five frequency-band coherence/support values, output-render confirmation, output-connection count, and explicit uncertainty reasons. PCM arrays are not Codable and are released after-reduction; the Trial B collector does not write audio, invoke ASR, or retain a transcript. The current-process does not automatically persist this output, so redirect only the numeric test output to a-local sidecar after inspecting it.--Limits and caveats:--- The stimulus is generated from fixed seed and segment durations, has a peak limit of 0.35, RMS- bounds of 0.02–0.15, and the player volume is limited to 0.6. These are safe diagnostic bounds,- not a calibrated speaker level.-- Correlation searches at most ±0.5 seconds and reports split-half delay uncertainty; low excitation,- mismatched controls, incomplete capture coverage, and unsupported properties carry explicit reason- codes. Frequency coherence/support is evidence about coupling, not an echo-cancellation score.-- A successful mixer tap/read-back confirms an engine-local render, not that an arbitrary other- process or selected-app ScreenCaptureKit stream reaches VPIO. Trial B is informational and cannot- productize ownership of another app's render path.-- The acoustic probe requires DEBUG plus both explicit environment gates: `FLUIDVOICE_VPIO_ACOUSTIC=1`- and finite `FLUIDVOICE_MIC_PHASE1` with `0 < minutes <= 0.25`. Before rendering, the read-only- output preflight requires a live output route whose actual device matches the current default,- a readable nonzero system volume no higher than 0.6, and a combined digital/output peak no higher- than 0.15; an unsafe or unreadable route refuses the render.- It intentionally avoids `setVoiceProcessingEnabled(false)` during teardown because macOS 26.6- can crash in `AVAudioIONode` after a live output read-back; ordinary product teardown is unchanged.-- This slice makes no AEC claim and does not alter normal capture, transcription, profile, export,- or installed-app behavior. A positive local correlation is evidence about this controlled graph- only; it is not proof that Apple's VPIO reference contains system-wide output.--### Built-in-device run on 2026-09-10--The first signed, one-shot Trial B run completed without installing an app. The built-in microphone-and built-in output route were confirmed, system volume was 0.25, the bounded combined peak was-0.03125, and the mixer tap confirmed all 139,200 scheduled frames with valid host timestamps. All-three VPIO control variants also matched their raw and high-level read-backs.--Every acoustic result is nevertheless **invalid/unknown**. The capture collector covered only-93.29–94.74% of each requested shared-clock window, with no overlap and no synthesized timing, so-the strict completeness gate correctly withheld delay, correlation, band, and attenuation values.-Apple's VPIO also logged repeated downlink DSP I/O/state faults. This run is evidence of a probe-window-alignment defect and an unstable VPIO graph, not evidence for or against echo cancellation.-The exact reduced report is in `meeting_vpio_acoustic_trial_b_builtin_2026-09-10.json`; it contains-no PCM or transcript.--An audited rerun after adding collector warm-up remained invalid/unknown, with 92.76–93.18%-coverage. That ruled out insufficient pre-render accumulation and exposed a separate 200 ms origin-error: the capture window used the first non-silent mixer sample as stimulus sample zero even though-the generated stimulus begins with 9,600 silent frames. The rerun is preserved in-`meeting_vpio_acoustic_trial_b_builtin_rerun1_2026-09-10.json`. The window-origin correction is a-code change only until it receives a fresh safety review; no additional acoustic result is implied.--After that correction passed a fresh safety review, one final signed rerun improved the two active-VPIO windows to 98.45% and 97.82% coverage, but both still failed the strict gap gate while Apple-logged repeated downlink DSP I/O/state faults. The bypassed VPIO variant reached exactly 100%-coverage with no overlap or synthesized timing, yet its acoustic measurement was also invalid: the-two delay halves disagreed (approximately 0.00002 s versus 0.05285 s), only one frequency band was-coherent, and captured RMS was only 1.20 dB above the measured noise floor. Consequently none of-the three variants provides a valid AEC result. The exact report is-`meeting_vpio_acoustic_trial_b_builtin_rerun2_2026-09-10.json`.--This is enough to stop repeating Trial B on this host: active VPIO is associated with incomplete-capture windows and framework DSP faults, while the complete bypass arm is not sufficiently-delay-locked or broadband-coherent to support a cancellation claim. The remaining Phase 0 evidence-must come from the external-process Trial A and paired ScreenCaptureKit Trial C2 rather than further-engine-local playback.