diff --git a/CLAUDE.md b/CLAUDE.md index 653e513..d8a15a3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,6 +1,6 @@ # NeuralCompose -Privacy-first, fully on-device macOS prototype for **EEG-driven communication**. A Muse headband streams brain signals through BrainFlow, a Core ML classifier on the Apple Neural Engine detects intent (jaw clench / blink / rest / select), and a local MLX LLM suggests next words. The user "types" by letting a cycling 3-token carousel highlight a candidate, then committing with a brain-signal selection. **No network at runtime. No cloud. No telemetry.** +Privacy-first, fully on-device macOS prototype for **EEG-driven communication**. A Muse headband streams brain signals through BrainFlow, a Core ML classifier on the Apple Neural Engine detects intent (jaw clench / blink / rest / select), and a local MLX LLM suggests next words. The user "types" by letting a cycling 3-token carousel highlight a candidate, then committing with a brain-signal selection. **No cloud. No telemetry. Network egress only through the three registered exceptions (registry entries 8, 9, and 10).** ## Stack - Swift 6.0, macOS 14+, SwiftPM (no Xcode project needed for the default build) @@ -22,6 +22,7 @@ Only the non-obvious constraints; the directory tree speaks for itself otherwise - `Sources/BCIBridge/` — Obj-C++ shim for BrainFlow. Default builds with `BCI_BRIDGE_STUB`; define `BCI_BRAINFLOW_AVAILABLE` + `-lBrainflow` to wire in the real library. - `Sources/BCICore/` — pure-Swift, **no third-party deps** (protocols, models, ring buffer, intent FSM) - `Sources/BCILLM/` — **isolated MLX adapter**; ONLY target that imports MLX/transformers +- `Sources/BCIBiofeedback/` : biofeedback egress (ADR-011): `BandPowerEstimator` -> `BiofeedbackFrame` -> `FeatureMapper` (health-gated mappings) / `MindMonitorMirror` (Mind Monitor-compatible OSC) -> `BiofeedbackSink` conformers (`OSCUDPSender`, `CoreMIDIVirtualSource`, recording/null stubs). Off by default; derived features only, never raw EEG unless the explicit raw toggle is on - `WorldModel/` — **decoupled research spike** (PyTorch, not MLX; no dependency on `Sources/`) — constraints live in `WorldModel/CLAUDE.md` (auto-loads when working there) - `HARDWARE_SETUP.md`, `MODEL_SETUP.md`, `CALIBRATION.md`, `TROUBLESHOOTING.md` — operational docs (keep up to date) diff --git a/Evaluation/reports/decision_registry.md b/Evaluation/reports/decision_registry.md index cc55cb5..ff76d57 100644 --- a/Evaluation/reports/decision_registry.md +++ b/Evaluation/reports/decision_registry.md @@ -101,3 +101,13 @@ Each entry: - **Confidence:** Medium — the engineering mirrors an already-reviewed quarantine pattern (entry 8) and the wire format was fixed and agreed by both sessions before either wrote code; the *experiment's* statistical power is explicitly low (3 runs/arm, pre-registered as showing a large effect or nothing reliable) and is out of scope for this entry, which covers the bridge mechanism only. - **Status:** Accepted for the experimental, opt-in bridge only. Network egress is now possible in the runtime through exactly two quarantined, independently-gated paths — `BCICloudBridge` (entry 8) and `BCIPeerBridge` (this entry) — both opt-in and off by default; the invariant otherwise stands. + +### 10. Biofeedback egress (ADR-011) : scoped network-egress exception, derived features only + +- **Decision:** A new `BCIBiofeedback` target may emit EEG-derived features (per-channel band powers in Bels, per-channel health, Track A blink/clench events, IMU) over two transports: a CoreMIDI virtual source (in-machine, not network) and OSC/UDP to a user-chosen host, loopback `127.0.0.1:7000` by default. This is a deliberate exception to the "No network at runtime" invariant (CLAUDE.md line 3 / PRINCIPLES.md Principle 5) alongside entries 8 (`BCICloudBridge`) and 9 (`BCIPeerBridge`), and the only one that carries EEG-derived numbers. Accepted 2026-11-07; status follows ADR-011. +- **Evidence / rationale:** (a) The inbound half of the Muse-to-DAW chain already exists (`MindMonitorOSCStream`, ADR-004); the outbound half is what makes NeuralCompose usable as an open biofeedback instrument alongside Mind Monitor + Muse Port. (b) The egress is **tightly scoped**: one target, dependencies `BCICore` + `BCIEEG` only, imported only by `NeuralComposeApp`, never a dependency of another `BCI*` target. (c) **Raw EEG never reaches a frame**: the egress boundary is `BiofeedbackFrame`, a function of band powers, health, events and IMU; raw `/muse/eeg` re-broadcast is a separate explicit toggle through the one named helper `MindMonitorMirror.rawEEG(_:)`. (d) **Health gating is mandatory**: every `BiofeedbackMapping` carries a `HealthPolicy` (default `holdLast`); Mind Monitor's behaviour is available only as the explicit `passthrough` policy. (e) **Deterministic**: pure-Swift periodogram and a clock-free mapper, so a recording through a mapping set yields byte-identical outputs for the replay regression. (f) Off by default; while off the app wires `NullBiofeedbackSink`. (g) No third-party dependency; Network and CoreMIDI are system frameworks behind `canImport`. +- **Scope guard - what this does NOT do:** it does **not** touch `BCICloudBridge` or `BCIPeerBridge` or widen entries 8 and 9; cloud egress stays exclusively in `BCICloudBridge`. It adds no HTTP client. It does not enable macOS Network MIDI (an OS feature the user controls in Audio MIDI Setup). It does not expose World Model or Laya latents as features; that waits for a benchmarked encoder and its own amendment. The `MindMonitorMirror` compatibility output is ungated by design and says so; gating is the mapper's job. +- **Supporting benchmark(s):** `Tests/BCIBiofeedbackTests/BandPowerEstimatorTests.swift` (A^2/2 physical-unit checks, FFT vs naive DFT), `FeatureMapperTests.swift` (all four health policies, smoothing, rate limit, MIDI quantisation, note gates, determinism), `MindMonitorMirrorTests.swift` (address scheme, payload shapes, bundle round trip through `MuseOSCDecoder`), `Tests/BCIEEGTests/OSCEncoderTests.swift`. Golden-recording replay fixture is a follow-up issue and gates live validation. +- **Confidence:** High for the egress core: the design is isolated and all 64 unit tests across `BCIBiofeedbackTests` and `OSCEncoderTests` (including `OSCUDPSender` and `CoreMIDIVirtualSource` compilation) compiled and passed on M4 under Swift 6.0; the `AppContainer` wiring, settings and privacy-indicator strings are follow-up PRs. +- **Status:** Accepted. Network egress of derived features is possible **exclusively** through `BCIBiofeedback` once wired and enabled; raw EEG egress only through the explicit raw toggle; the invariant otherwise stands. + diff --git a/Package.swift b/Package.swift index f8bf649..355abe1 100644 --- a/Package.swift +++ b/Package.swift @@ -36,6 +36,7 @@ let package = Package( .library(name: "BCIVoice", targets: ["BCIVoice"]), .library(name: "BCICloudBridge", targets: ["BCICloudBridge"]), .library(name: "BCIPeerBridge", targets: ["BCIPeerBridge"]), + .library(name: "BCIBiofeedback", targets: ["BCIBiofeedback"]), .library(name: "WorldModelDemo", targets: ["WorldModelDemo"]), .executable(name: "EmbeddingBench", targets: ["EmbeddingBench"]), .executable(name: "SemanticEval", targets: ["SemanticEval"]), @@ -167,6 +168,29 @@ let package = Package( swiftSettings: strictConcurrency ), + // -- Biofeedback egress (OSC + virtual MIDI out) ------------------- + // ADR-011. Turns per-channel band powers, channel health and the + // Track A events into health-gated OSC and MIDI for DAWs and + // patchers (Ableton via Max for Live or MIDI Learn, Logic, Reaper, + // Bitwig, Max, TouchDesigner, SuperCollider). Depends on BCICore + // (frames, health) and BCIEEG (OSCMessage + OSCEncoder) only; no + // MLX, no third-party deps. Network (UDP to a user-chosen host, + // loopback by default) and CoreMIDI (in-machine) are system + // frameworks behind `canImport`. This is a scoped network-egress + // exception after BCICloudBridge and BCIPeerBridge, and the only one + // that emits derived EEG features; decision_registry.md entry 10. + // Imported only by NeuralComposeApp; must never become a dependency + // of any other BCI* target. + .target( + name: "BCIBiofeedback", + dependencies: ["BCICore", "BCIEEG"], + path: "Sources/BCIBiofeedback", + swiftSettings: strictConcurrency, + linkerSettings: [ + .linkedFramework("CoreMIDI", .when(platforms: [.macOS])), + ] + ), + // ── World Model demo (synthetic-task JEPA+MPC, CoreML/ANE) ──────── // Deliberately NOT a `BCI*`-prefixed name: every `BCI*` target is a // real production-pipeline stage; this is a synthetic-task research @@ -364,6 +388,13 @@ let package = Package( dependencies: ["BCIPeerBridge", "BCICore"], path: "Tests/BCIPeerBridgeTests" ), + .testTarget( + name: "BCIBiofeedbackTests", + // BCIEEG for the OSCMessage type and MuseOSCDecoder, which the + // encoder round-trip and mirror tests decode against. + dependencies: ["BCIBiofeedback", "BCICore", "BCIEEG"], + path: "Tests/BCIBiofeedbackTests" + ), .testTarget( name: "WorldModelDemoTests", dependencies: ["WorldModelDemo", "BCICore"], diff --git a/Sources/BCIBiofeedback/BandPowerEstimator.swift b/Sources/BCIBiofeedback/BandPowerEstimator.swift new file mode 100644 index 0000000..c4da9be --- /dev/null +++ b/Sources/BCIBiofeedback/BandPowerEstimator.swift @@ -0,0 +1,183 @@ +import Foundation +import BCICore + +/// Per-channel band powers for one window, in linear units (µV²). +/// +/// `bels(_:)` is the Mind Monitor convention: the base-10 logarithm of +/// the band power, so 0 Bel is 1 µV² and each Bel is a factor of ten. +/// Mind Monitor's own absolute values are computed from its PSD scaling +/// and will not match these numerically; what matches is the unit, the +/// band edges and the address scheme, which is all a downstream patch +/// can depend on. +public struct BandPowers: Sendable, Hashable { + public let power: [EEGBand: Float] + + public init(power: [EEGBand: Float]) { + self.power = power + } + + public subscript(band: EEGBand) -> Float { + power[band] ?? 0 + } + + /// Sum of all band powers present. + public var total: Float { + power.values.reduce(0, +) + } + + /// Fraction of total band power in `band`, 0 when the total is 0. + public func relative(_ band: EEGBand) -> Float { + let t = total + return t > 0 ? self[band] / t : 0 + } + + /// log10 of the band power, floored so a silent channel reads as a + /// large negative number instead of -inf. + public func bels(_ band: EEGBand) -> Float { + BandPowers.bels(self[band]) + } + + public static let powerFloor: Float = 1e-9 + + public static func bels(_ linearPower: Float) -> Float { + log10(max(linearPower, powerFloor)) + } +} + +/// Welch-style single-segment periodogram band power estimator. +/// +/// Pure Swift, deterministic, no Accelerate: the same bytes in give the +/// same floats out on every machine, which is what the replay fixtures +/// in `BCIBiofeedbackTests` and the golden-recording regression need. +/// If this ever shows up in a profile, a vDSP path can be added behind +/// the same signature with the fixtures as its acceptance test. +/// +/// Method, per channel: subtract the mean (Muse carries an ~800 µV DC +/// offset), apply a Hann window, zero-pad to the next power of two, FFT, +/// one-sided PSD scaled by `2 / (fs * sum(w^2))` so that the integral of +/// the PSD equals the signal's mean-square value, then sum the PSD bins +/// inside each band's half-open range times the bin width. A pure +/// sinusoid of amplitude A therefore reports a band power of about A²/2. +/// +/// This is a different estimator from `FeatureExtractor.bandEnergies`, +/// on purpose: that one is a lag-difference proxy summed over channels +/// for the mock classifier; this one is per channel and in physical +/// units, because it is what leaves the machine. +public struct BandPowerEstimator: Sendable { + + public let bands: [EEGBand] + + public init(bands: [EEGBand] = EEGBand.allCases) { + self.bands = bands + } + + /// Band powers for each channel of `window`. `channels` names the + /// window's rows in order; rows beyond `channels.count` are ignored + /// and channels beyond the row count are omitted from the result. + public func powers(for window: EEGWindow, channels: [EEGChannel] = EEGChannel.allCases) -> [EEGChannel: BandPowers] { + var result: [EEGChannel: BandPowers] = [:] + for (index, channel) in channels.enumerated() where index < window.samples.count { + result[channel] = powers(for: window.samples[index], sampleRate: window.sampleRate) + } + return result + } + + /// Band powers for one channel's samples. + public func powers(for samples: [Float], sampleRate: Double) -> BandPowers { + guard samples.count >= 4, sampleRate > 0 else { + return BandPowers(power: Dictionary(uniqueKeysWithValues: bands.map { ($0, 0) })) + } + + // Demean. + var mean = 0.0 + for v in samples { mean += Double(v) } + mean /= Double(samples.count) + + // Hann window and its energy. + let n = samples.count + var windowed = [Double](repeating: 0, count: n) + var windowEnergy = 0.0 + for i in 0.. 0 && (n & (n - 1)) == 0, "fft size must be a power of two") + + // Bit-reversal permutation. + var j = 0 + for i in 1..> 1 + while j & bit != 0 { + j ^= bit + bit >>= 1 + } + j |= bit + if i < j { + re.swapAt(i, j) + im.swapAt(i, j) + } + } + + // Butterflies. + var length = 2 + while length <= n { + let angle = -2.0 * Double.pi / Double(length) + let wRe = cos(angle) + let wIm = sin(angle) + var start = 0 + while start < n { + var curRe = 1.0 + var curIm = 0.0 + let half = length / 2 + for k in 0.. { + switch self { + case .bandAbsolute(_, let channel), .bandRelative(_, let channel), .bandRatio(_, _, let channel): + if let channel { return [channel] } + return Set(EEGChannel.allCases) + case .channelQuality, .blink, .jawClench, .accel, .gyro: + return [] + } + } + + /// Whether the frame is healthy enough for this feature to be trusted. + /// Single-channel features require that channel healthy; averaged + /// features require at least one healthy channel present; non-EEG + /// features are always healthy. + public func isHealthy(in frame: BiofeedbackFrame) -> Bool { + switch self { + case .bandAbsolute(_, let channel), .bandRelative(_, let channel), .bandRatio(_, _, let channel): + if let channel { return frame.status(of: channel) == .healthy } + return !frame.healthyChannels.isEmpty + case .channelQuality, .blink, .jawClench, .accel, .gyro: + return true + } + } + + /// Evaluate the feature on `frame`. Returns `nil` when the frame does + /// not carry what the feature needs (channel absent, no IMU sample), + /// never a made-up default. `healthyOnly` restricts channel-averaged + /// features to healthy channels when any exist. + public func evaluate(in frame: BiofeedbackFrame, healthyOnly: Bool = true) -> Float? { + switch self { + case .bandAbsolute(let band, let channel): + return average(over: channel, in: frame, healthyOnly: healthyOnly) { $0.bels(band) } + + case .bandRelative(let band, let channel): + return average(over: channel, in: frame, healthyOnly: healthyOnly) { $0.relative(band) } + + case .bandRatio(let numerator, let denominator, let channel): + return average(over: channel, in: frame, healthyOnly: healthyOnly) { powers in + let d = powers[denominator] + guard d > 0 else { return nil } + return powers[numerator] / d + } + + case .channelQuality(let channel): + switch frame.status(of: channel) { + case .healthy: return 1 + case .unknown: return 0.5 + case .saturated, .dead, .stale: return 0 + } + + case .blink: + return frame.blink ? 1 : 0 + + case .jawClench: + return frame.jawClench ? 1 : 0 + + case .accel(let axis): + guard let sample = frame.accel else { return nil } + return component(axis, of: sample) + + case .gyro(let axis): + guard let sample = frame.gyro else { return nil } + return component(axis, of: sample) + } + } + + private func average( + over channel: EEGChannel?, + in frame: BiofeedbackFrame, + healthyOnly: Bool, + _ read: (BandPowers) -> Float? + ) -> Float? { + if let channel { + guard let powers = frame.bandPowers[channel] else { return nil } + return read(powers) + } + var channels = healthyOnly ? frame.healthyChannels : frame.presentChannels + if channels.isEmpty { channels = frame.presentChannels } + var sum: Float = 0 + var count = 0 + for channel in channels { + guard let powers = frame.bandPowers[channel], let value = read(powers) else { continue } + sum += value + count += 1 + } + return count > 0 ? sum / Float(count) : nil + } + + private func component(_ axis: Axis, of sample: MovementSample) -> Float { + switch axis { + case .x: return sample.x + case .y: return sample.y + case .z: return sample.z + } + } +} diff --git a/Sources/BCIBiofeedback/BiofeedbackFrame.swift b/Sources/BCIBiofeedback/BiofeedbackFrame.swift new file mode 100644 index 0000000..d9ba05d --- /dev/null +++ b/Sources/BCIBiofeedback/BiofeedbackFrame.swift @@ -0,0 +1,109 @@ +import Foundation +import BCICore + +/// One tick of everything the biofeedback egress is allowed to know: +/// per-channel band powers, per-channel health, the two Track A events, +/// and the IMU readings when the transport carries them. +/// +/// This is the egress boundary. Nothing downstream of a `BiofeedbackFrame` +/// sees raw EEG samples, and the frame carries no identity, no text, no +/// transcript. What leaves the machine over OSC or MIDI is a function of +/// this struct and nothing else, which is what makes ADR-011's privacy +/// claim checkable: audit `MindMonitorMirror` and `FeatureMapper`, and +/// you have audited the egress. +/// +/// Raw EEG re-broadcast (`/muse/eeg`) is the one deliberate exception and +/// is not reachable from a frame at all; see `MindMonitorMirror.rawEEG`. +public struct BiofeedbackFrame: Sendable, Hashable { + + /// Stream-relative seconds, same clock as `EEGSample.timestamp`. + public let timestamp: TimeInterval + + /// Linear band power per channel, µV². Channels absent from the + /// dictionary were not in the window. + public let bandPowers: [EEGChannel: BandPowers] + + /// Health per channel. Channels absent from the dictionary are + /// treated as `.unknown` by every consumer. + public let health: [EEGChannel: ChannelHealthStatus] + + /// Track A blink event (single or double) present in this tick. + public let blink: Bool + + /// Track A jaw-clench event present in this tick. + public let jawClench: Bool + + /// Most recent accelerometer reading, if the transport carries one. + public let accel: MovementSample? + + /// Most recent gyroscope reading, if the transport carries one. + public let gyro: MovementSample? + + public init( + timestamp: TimeInterval, + bandPowers: [EEGChannel: BandPowers], + health: [EEGChannel: ChannelHealthStatus], + blink: Bool = false, + jawClench: Bool = false, + accel: MovementSample? = nil, + gyro: MovementSample? = nil + ) { + self.timestamp = timestamp + self.bandPowers = bandPowers + self.health = health + self.blink = blink + self.jawClench = jawClench + self.accel = accel + self.gyro = gyro + } + + /// Convenience constructor from the pipeline's own types. `intent` is + /// the Track A classifier's decision for this window, if any; blinks + /// and clenches are derived from it rather than re-detected here, so + /// the egress never disagrees with the typing path about what + /// happened. + public init( + window: EEGWindow, + channels: [EEGChannel] = EEGChannel.allCases, + health: [ChannelHealthState], + intent: IntentClass? = nil, + accel: MovementSample? = nil, + gyro: MovementSample? = nil, + estimator: BandPowerEstimator = BandPowerEstimator() + ) { + self.timestamp = window.endTimestamp + self.bandPowers = estimator.powers(for: window, channels: channels) + var healthByChannel: [EEGChannel: ChannelHealthStatus] = [:] + for state in health { healthByChannel[state.channel] = state.status } + self.health = healthByChannel + switch intent { + case .singleBlink, .doubleBlink: + self.blink = true + self.jawClench = false + case .jawClench: + self.blink = false + self.jawClench = true + default: + self.blink = false + self.jawClench = false + } + self.accel = accel + self.gyro = gyro + } + + /// Health lookup with the documented default. + public func status(of channel: EEGChannel) -> ChannelHealthStatus { + health[channel] ?? .unknown + } + + /// Channels present in `bandPowers` whose health is `.healthy`, in + /// `EEGChannel.allCases` order. + public var healthyChannels: [EEGChannel] { + EEGChannel.allCases.filter { bandPowers[$0] != nil && status(of: $0) == .healthy } + } + + /// Channels present in `bandPowers`, in `EEGChannel.allCases` order. + public var presentChannels: [EEGChannel] { + EEGChannel.allCases.filter { bandPowers[$0] != nil } + } +} diff --git a/Sources/BCIBiofeedback/BiofeedbackMapping.swift b/Sources/BCIBiofeedback/BiofeedbackMapping.swift new file mode 100644 index 0000000..6e96572 --- /dev/null +++ b/Sources/BCIBiofeedback/BiofeedbackMapping.swift @@ -0,0 +1,126 @@ +import Foundation +import BCICore + +/// One user-defined route from a feature to an output, with the shaping +/// and the health policy that make it safe to drive a synthesizer with. +/// +/// Every mapping has a `HealthPolicy`; there is no way to construct one +/// without deciding what happens when the electrode under the feature is +/// dead, saturated or stale. That is the design difference from passing +/// Mind Monitor straight into a DAW: there the horseshoe shows bad +/// contact while the band powers keep streaming whatever the amplifier +/// saw, and the music follows the artifact. +/// +/// The struct is `Codable` so a user's mapping set persists as JSON and +/// so a replay fixture can pin a mapping set alongside its expected +/// output. +public struct BiofeedbackMapping: Sendable, Hashable, Codable, Identifiable { + + /// Where the shaped value goes. + public enum Target: Sendable, Hashable, Codable { + /// One float argument, the shaped value in 0 to 1, at `address`. + /// For Mind Monitor-compatible raw-unit addresses use + /// `MindMonitorMirror`, not a mapping. + case osc(address: String) + + /// Control change on `channel` (0 to 15). `fourteenBit` sends the + /// MSB/LSB pair on `controller` and `controller + 32` and requires + /// `controller < 32`. + case midiControl(controller: UInt8, channel: UInt8, fourteenBit: Bool) + + /// Note gate: note on when the shaped value crosses 0.5 upward, + /// note off when it drops below 0.5 or `gate` seconds elapse, + /// whichever first. Meant for `.blink` and `.jawClench`. + case midiNote(note: UInt8, channel: UInt8, velocity: UInt8, gate: TimeInterval) + } + + /// How the raw feature value is normalised into 0 to 1 before any + /// smoothing. `inputLow` and `inputHigh` are in the feature's own + /// units for `.linear`, and are log10'd for `.log10` (so pass + /// positive linear values, not Bels, when using `.log10`). + public enum Curve: String, Sendable, Hashable, Codable { + case linear + case log10 + } + + /// What to do on ticks where the feature's channels are not healthy. + public enum HealthPolicy: Sendable, Hashable, Codable { + /// Emit whatever the feature evaluates to, if anything. Equivalent + /// to Mind Monitor behaviour; exists so the difference is a user + /// choice, not a hidden default. + case passthrough + /// Keep emitting the last value seen while healthy. Nothing is + /// emitted until a healthy value has been seen once. + case holdLast + /// Glide from the last healthy value toward `rest` with time + /// constant `tau` seconds. + case decayToRest(rest: Float, tau: TimeInterval) + /// Emit nothing. Open note gates are closed on the first unhealthy + /// tick. + case mute + } + + public let id: UUID + public let feature: BiofeedbackFeature + public let target: Target + public let inputLow: Float + public let inputHigh: Float + public let curve: Curve + + /// Exponential smoothing time constant in seconds; 0 disables. + public let smoothingTau: TimeInterval + + /// Minimum seconds between emissions; 0 emits on every tick. MIDI + /// controls additionally emit only when the quantised value changes. + public let minInterval: TimeInterval + + public let healthPolicy: HealthPolicy + + public init( + id: UUID = UUID(), + feature: BiofeedbackFeature, + target: Target, + inputLow: Float, + inputHigh: Float, + curve: Curve = .linear, + smoothingTau: TimeInterval = 0, + minInterval: TimeInterval = 0, + healthPolicy: HealthPolicy = .holdLast + ) { + precondition(inputHigh != inputLow, "inputLow and inputHigh must differ") + if curve == .log10 { + precondition(inputLow > 0 && inputHigh > 0, "log10 curve needs positive input bounds") + } + if case .midiControl(let controller, _, let fourteenBit) = target, fourteenBit { + precondition(controller < 32, "14-bit control change needs controller < 32") + } + self.id = id + self.feature = feature + self.target = target + self.inputLow = inputLow + self.inputHigh = inputHigh + self.curve = curve + self.smoothingTau = max(0, smoothingTau) + self.minInterval = max(0, minInterval) + self.healthPolicy = healthPolicy + } + + /// Normalise a raw feature value into 0 to 1 along the curve, clamped. + public func normalise(_ raw: Float) -> Float { + let low: Float + let high: Float + let x: Float + switch curve { + case .linear: + low = inputLow + high = inputHigh + x = raw + case .log10: + low = log10(inputLow) + high = log10(inputHigh) + x = log10(max(raw, BandPowers.powerFloor)) + } + let t = (x - low) / (high - low) + return min(1, max(0, t)) + } +} diff --git a/Sources/BCIBiofeedback/BiofeedbackOutput.swift b/Sources/BCIBiofeedback/BiofeedbackOutput.swift new file mode 100644 index 0000000..53d3a0d --- /dev/null +++ b/Sources/BCIBiofeedback/BiofeedbackOutput.swift @@ -0,0 +1,21 @@ +import Foundation +import BCIEEG + +/// One thing the egress wants delivered. Transports pick the cases they +/// can carry and ignore the rest: an OSC sender drops `.midi`, a MIDI +/// source drops `.osc`. A sink that records everything (tests, the +/// replay fixture) keeps both. +public enum BiofeedbackOutput: Sendable, Equatable { + case osc(OSCMessage) + case midi(MIDIEvent) + + public var oscMessage: OSCMessage? { + if case .osc(let message) = self { return message } + return nil + } + + public var midiEvent: MIDIEvent? { + if case .midi(let event) = self { return event } + return nil + } +} diff --git a/Sources/BCIBiofeedback/BiofeedbackSink.swift b/Sources/BCIBiofeedback/BiofeedbackSink.swift new file mode 100644 index 0000000..24abbe0 --- /dev/null +++ b/Sources/BCIBiofeedback/BiofeedbackSink.swift @@ -0,0 +1,58 @@ +import Foundation + +/// Where biofeedback outputs go. The egress has exactly two production +/// conformers (`OSCUDPSender`, `CoreMIDIVirtualSource`) and two for tests +/// and offline work (`RecordingBiofeedbackSink`, `NullBiofeedbackSink`). +/// A sink receives already-shaped outputs and never sees EEG, a frame or +/// a mapping; it is a dumb pipe by design so the privacy audit stops at +/// `FeatureMapper` and `MindMonitorMirror`. +/// +/// Conformers may drop the cases they cannot carry. They must not block +/// the caller on network or device I/O; `emit` is `async` so an actor +/// conformer can serialise its own sends. +/// +/// **API stability.** Frozen with this signature per Principle 4: new +/// capabilities (batching hints, timestamps) arrive as new optional +/// methods with default implementations, never as changes to `emit`. +public protocol BiofeedbackSink: Sendable { + func emit(_ outputs: [BiofeedbackOutput]) async +} + +/// Fan-out to several sinks in order. +public struct CompositeBiofeedbackSink: BiofeedbackSink { + public let sinks: [any BiofeedbackSink] + + public init(_ sinks: [any BiofeedbackSink]) { + self.sinks = sinks + } + + public func emit(_ outputs: [BiofeedbackOutput]) async { + for sink in sinks { + await sink.emit(outputs) + } + } +} + +/// Keeps everything it is given, for tests and for building replay +/// fixtures. +public actor RecordingBiofeedbackSink: BiofeedbackSink { + public private(set) var outputs: [BiofeedbackOutput] = [] + + public init() {} + + public func emit(_ outputs: [BiofeedbackOutput]) async { + self.outputs.append(contentsOf: outputs) + } + + public func clear() { + outputs.removeAll() + } +} + +/// Discards everything. The stub that ships with the protocol, and the +/// sink the app uses while the egress feature is disabled so the mapper +/// path stays exercised without anything leaving the process. +public struct NullBiofeedbackSink: BiofeedbackSink { + public init() {} + public func emit(_ outputs: [BiofeedbackOutput]) async {} +} diff --git a/Sources/BCIBiofeedback/CoreMIDIVirtualSource.swift b/Sources/BCIBiofeedback/CoreMIDIVirtualSource.swift new file mode 100644 index 0000000..8181a23 --- /dev/null +++ b/Sources/BCIBiofeedback/CoreMIDIVirtualSource.swift @@ -0,0 +1,68 @@ +#if canImport(CoreMIDI) +import Foundation +import CoreMIDI + +/// A CoreMIDI virtual source that other apps see as a MIDI input port +/// named "NeuralCompose Biofeedback". Ableton Live, Logic, Reaper and +/// Bitwig list it in their MIDI preferences with nothing else to set up; +/// no IAC bus, no third-party driver. Not a network transport: MIDI stays +/// inside the machine (Network MIDI sessions are a separate macOS feature +/// this type never enables). +/// +/// Sends MIDI 1.0 channel-voice events wrapped as Universal MIDI Packets +/// through `MIDIReceivedEventList`, the non-deprecated path on macOS 11+. +/// One event per list, which keeps the fixed-size `MIDIEventList` Swift +/// imports well within capacity. +/// +/// `@unchecked Sendable` invariant: `client` and `source` are created +/// once in `init`, never reassigned, and `MIDIReceivedEventList` is +/// documented as callable from any thread. No other state. +public final class CoreMIDIVirtualSource: BiofeedbackSink, @unchecked Sendable { + + public enum Error: Swift.Error, Equatable { + case clientCreateFailed(OSStatus) + case sourceCreateFailed(OSStatus) + } + + public let name: String + private let client: MIDIClientRef + private let source: MIDIEndpointRef + + public init(name: String = "NeuralCompose Biofeedback") throws { + self.name = name + + var client = MIDIClientRef() + let clientStatus = MIDIClientCreateWithBlock("NeuralCompose" as CFString, &client, nil) + guard clientStatus == noErr else { throw Error.clientCreateFailed(clientStatus) } + + var source = MIDIEndpointRef() + let sourceStatus = MIDISourceCreateWithProtocol(client, name as CFString, ._1_0, &source) + guard sourceStatus == noErr else { + MIDIClientDispose(client) + throw Error.sourceCreateFailed(sourceStatus) + } + + self.client = client + self.source = source + } + + deinit { + MIDIEndpointDispose(source) + MIDIClientDispose(client) + } + + public func emit(_ outputs: [BiofeedbackOutput]) async { + for event in outputs.compactMap(\.midiEvent) { + send(event) + } + } + + private func send(_ event: MIDIEvent) { + var word = event.umpWord + var list = MIDIEventList() + let packet = MIDIEventListInit(&list, ._1_0) + _ = MIDIEventListAdd(&list, MemoryLayout.size, packet, 0, 1, &word) + _ = MIDIReceivedEventList(source, &list) + } +} +#endif diff --git a/Sources/BCIBiofeedback/EEGBand.swift b/Sources/BCIBiofeedback/EEGBand.swift new file mode 100644 index 0000000..4721671 --- /dev/null +++ b/Sources/BCIBiofeedback/EEGBand.swift @@ -0,0 +1,46 @@ +import Foundation + +/// The five conventional EEG frequency bands, with the edge frequencies +/// Mind Monitor documents for its `/muse/elements/*_absolute` streams. +/// Using Mind Monitor's edges (not a textbook's) is deliberate: the +/// biofeedback egress advertises itself as a drop-in for Mind Monitor's +/// OSC output, so the band definitions must match what downstream +/// patches were tuned against. Note the documented theta/alpha overlap +/// at 7.5 to 8 Hz; it is reproduced, not corrected. +/// +/// Source: Mind Monitor FAQ, "Absolute Band Powers" table +/// (https://mind-monitor.com/FAQ.php). +public enum EEGBand: String, Sendable, Hashable, Codable, CaseIterable { + case delta + case theta + case alpha + case beta + case gamma + + /// Half-open band edges in Hz: a PSD bin at frequency `f` belongs to + /// the band when `lowHz <= f < highHz`. + public var lowHz: Double { + switch self { + case .delta: return 1.0 + case .theta: return 4.0 + case .alpha: return 7.5 + case .beta: return 13.0 + case .gamma: return 30.0 + } + } + + public var highHz: Double { + switch self { + case .delta: return 4.0 + case .theta: return 8.0 + case .alpha: return 13.0 + case .beta: return 30.0 + case .gamma: return 44.0 + } + } + + /// The Mind Monitor OSC address for this band's absolute power. + public var mindMonitorAbsoluteAddress: String { + "/muse/elements/\(rawValue)_absolute" + } +} diff --git a/Sources/BCIBiofeedback/FeatureMapper.swift b/Sources/BCIBiofeedback/FeatureMapper.swift new file mode 100644 index 0000000..458dc40 --- /dev/null +++ b/Sources/BCIBiofeedback/FeatureMapper.swift @@ -0,0 +1,163 @@ +import Foundation +import BCICore +import BCIEEG + +/// Turns a stream of `BiofeedbackFrame`s into OSC and MIDI outputs +/// according to a set of `BiofeedbackMapping`s. Deterministic: the same +/// frames in the same order produce the same outputs, which is what lets +/// `BCIBiofeedbackTests` pin behaviour as fixtures and what the golden +/// recording replay (follow-up issue) will regress against. +/// +/// Pure value type with explicit state, no I/O, no clock of its own: time +/// comes from `frame.timestamp`. Transports (`OSCUDPSender`, +/// `CoreMIDIVirtualSource`) receive the outputs through `BiofeedbackSink` +/// and never see a frame. Mappings are processed in array order and +/// outputs are appended in that order, so a fixture is stable across +/// runs. +/// +/// Health gating lives here and nowhere else. Each mapping's +/// `HealthPolicy` decides what is emitted on ticks where +/// `feature.isHealthy(in:)` is false; `MindMonitorMirror`, by contrast, +/// deliberately emits ungated compatibility values plus the horseshoe, +/// because that is what a Mind Monitor consumer expects. +public struct FeatureMapper: Sendable { + + private struct State: Sendable { + var smoothed: Float? + var lastGood: Float? + var unhealthySince: TimeInterval? + var lastTimestamp: TimeInterval? + var lastEmit: TimeInterval? + var lastQuantised: Int? + var noteOpen = false + var noteOpenUntil: TimeInterval = 0 + } + + public private(set) var mappings: [BiofeedbackMapping] + private var states: [UUID: State] + + public init(mappings: [BiofeedbackMapping] = []) { + self.mappings = mappings + self.states = [:] + } + + /// Replace the mapping set. State is kept for mappings whose `id` + /// survives and dropped for the rest, so editing one row in a UI does + /// not reset every smoother. + public mutating func replaceMappings(_ newMappings: [BiofeedbackMapping]) { + let keep = Set(newMappings.map(\.id)) + states = states.filter { keep.contains($0.key) } + mappings = newMappings + } + + /// Forget all state (smoothers, gates, rate limiters). + public mutating func reset() { + states = [:] + } + + /// Process one frame and return everything to emit for it. + public mutating func step(_ frame: BiofeedbackFrame) -> [BiofeedbackOutput] { + var outputs: [BiofeedbackOutput] = [] + let now = frame.timestamp + + for mapping in mappings { + var state = states[mapping.id] ?? State() + let dt = state.lastTimestamp.map { max(0, now - $0) } ?? 0 + let healthy = mapping.feature.isHealthy(in: frame) + let raw = mapping.feature.evaluate(in: frame, healthyOnly: true) + + var value: Float? + if healthy, let raw { + let target = mapping.normalise(raw) + state.smoothed = FeatureMapper.smooth(previous: state.smoothed, target: target, dt: dt, tau: mapping.smoothingTau) + state.lastGood = state.smoothed + state.unhealthySince = nil + value = state.smoothed + } else { + switch mapping.healthPolicy { + case .passthrough: + if let raw { + let target = mapping.normalise(raw) + state.smoothed = FeatureMapper.smooth(previous: state.smoothed, target: target, dt: dt, tau: mapping.smoothingTau) + value = state.smoothed + } + case .holdLast: + value = state.lastGood + case .decayToRest(let rest, let tau): + if let last = state.lastGood { + let since = state.unhealthySince ?? now + state.unhealthySince = since + let elapsed = max(0, now - since) + let decayed: Float + if tau > 0 { + decayed = rest + (last - rest) * Float(exp(-elapsed / tau)) + } else { + decayed = rest + } + state.smoothed = decayed + value = decayed + } + case .mute: + value = nil + } + } + state.lastTimestamp = now + + switch mapping.target { + case .midiNote(let note, let channel, let velocity, let gate): + // Gates run every tick regardless of rate limiting so an + // expired or muted gate always closes. + let on = (value ?? 0) >= 0.5 + if on, !state.noteOpen { + outputs.append(.midi(.noteOn(channel: channel, note: note, velocity: velocity))) + state.noteOpen = true + state.noteOpenUntil = now + gate + state.lastEmit = now + } else if state.noteOpen, !on || now >= state.noteOpenUntil { + outputs.append(.midi(.noteOff(channel: channel, note: note))) + state.noteOpen = false + state.lastEmit = now + } + + case .osc(let address): + if let value, FeatureMapper.rateAllows(state: state, now: now, minInterval: mapping.minInterval) { + outputs.append(.osc(OSCMessage(address: address, arguments: [.float(value)]))) + state.lastEmit = now + } + + case .midiControl(let controller, let channel, let fourteenBit): + if let value, FeatureMapper.rateAllows(state: state, now: now, minInterval: mapping.minInterval) { + let span: Float = fourteenBit ? 16383 : 127 + let quantised = Int((value * span).rounded()) + if quantised != state.lastQuantised { + if fourteenBit { + for event in MIDIEvent.controlChange14(channel: channel, controller: controller, value: UInt16(quantised)) { + outputs.append(.midi(event)) + } + } else { + outputs.append(.midi(.controlChange(channel: channel, controller: controller, value: UInt8(quantised)))) + } + state.lastQuantised = quantised + state.lastEmit = now + } + } + } + + states[mapping.id] = state + } + return outputs + } + + /// Exponential moving average toward `target`. With no previous value + /// or no time constant the target is adopted outright. + static func smooth(previous: Float?, target: Float, dt: TimeInterval, tau: TimeInterval) -> Float { + guard let previous, tau > 0, dt > 0 else { return target } + let alpha = Float(1 - exp(-dt / tau)) + return previous + alpha * (target - previous) + } + + private static func rateAllows(state: State, now: TimeInterval, minInterval: TimeInterval) -> Bool { + guard minInterval > 0, let last = state.lastEmit else { return true } + return now - last >= minInterval + } +} diff --git a/Sources/BCIBiofeedback/MIDIEvent.swift b/Sources/BCIBiofeedback/MIDIEvent.swift new file mode 100644 index 0000000..0c60250 --- /dev/null +++ b/Sources/BCIBiofeedback/MIDIEvent.swift @@ -0,0 +1,56 @@ +import Foundation + +/// A MIDI 1.0 channel-voice event, independent of any transport. +/// +/// Channels are zero-based here (0 to 15) and shown to users one-based +/// (1 to 16), the usual DAW convention. Values are already clamped to 7 +/// bits by the constructors that produce them (`FeatureMapper`); the +/// encoders below mask defensively anyway. +/// +/// Two encodings are provided because CoreMIDI on macOS 11+ prefers the +/// Universal MIDI Packet (`umpWord`, used by `CoreMIDIVirtualSource`), +/// while anything that writes classic MIDI bytes (a file, a serial port, +/// a test fixture) wants `bytes`. Both are pure functions and both are +/// covered by `MIDIEventTests`. +public enum MIDIEvent: Sendable, Hashable, Codable { + case controlChange(channel: UInt8, controller: UInt8, value: UInt8) + case noteOn(channel: UInt8, note: UInt8, velocity: UInt8) + case noteOff(channel: UInt8, note: UInt8) + + /// Classic MIDI 1.0 wire bytes: status, data1, data2. + public var bytes: [UInt8] { + switch self { + case .controlChange(let channel, let controller, let value): + return [0xB0 | (channel & 0x0F), controller & 0x7F, value & 0x7F] + case .noteOn(let channel, let note, let velocity): + return [0x90 | (channel & 0x0F), note & 0x7F, velocity & 0x7F] + case .noteOff(let channel, let note): + return [0x80 | (channel & 0x0F), note & 0x7F, 0] + } + } + + /// The event as one 32-bit Universal MIDI Packet word: message type 2 + /// (MIDI 1.0 channel voice), group 0, then the three classic bytes. + public var umpWord: UInt32 { + let b = bytes + return (0x2 << 28) | (UInt32(b[0]) << 16) | (UInt32(b[1]) << 8) | UInt32(b[2]) + } + + /// A 14-bit control change as the MSB/LSB pair MIDI 1.0 defines: + /// controller `n` (0 to 31) carries the high 7 bits and controller + /// `n + 32` the low 7 bits, MSB first. Controllers 32 and above have + /// no LSB partner and fall back to a single 7-bit message carrying the + /// high bits. + public static func controlChange14(channel: UInt8, controller: UInt8, value: UInt16) -> [MIDIEvent] { + let v = min(value, 16383) + let msb = UInt8((v >> 7) & 0x7F) + let lsb = UInt8(v & 0x7F) + guard controller < 32 else { + return [.controlChange(channel: channel, controller: controller, value: msb)] + } + return [ + .controlChange(channel: channel, controller: controller, value: msb), + .controlChange(channel: channel, controller: controller + 32, value: lsb), + ] + } +} diff --git a/Sources/BCIBiofeedback/MindMonitorMirror.swift b/Sources/BCIBiofeedback/MindMonitorMirror.swift new file mode 100644 index 0000000..054a808 --- /dev/null +++ b/Sources/BCIBiofeedback/MindMonitorMirror.swift @@ -0,0 +1,116 @@ +import Foundation +import BCICore +import BCIEEG + +/// Emits a `BiofeedbackFrame` in Mind Monitor's OSC address scheme, so a +/// consumer written against Mind Monitor (the Muse Port Max for Live +/// device, TouchDesigner and SuperCollider patches, Bitwig's OSC input) +/// can be pointed at NeuralCompose instead and work unchanged. +/// +/// What is mirrored, per the Mind Monitor FAQ table: +/// +/// | Address | Payload | +/// |------------------------------------|-------------------------------------------| +/// | `/muse/elements/_absolute` | 1 float (average) or 4 floats, Bels | +/// | `/muse/elements/horseshoe` | 4 floats, 1 good / 2 medium / 4 bad | +/// | `/muse/elements/blink` | 1 int, sent only on a blink tick | +/// | `/muse/elements/jaw_clench` | 1 int, sent only on a clench tick | +/// | `/muse/acc`, `/muse/gyro` | 3 floats (g, deg/s) when the frame has them | +/// +/// Not mirrored: `/muse/batt` (no battery data reaches the frame) and +/// `/muse/elements/touching_forehead` (Muse's on-head detector is not +/// exposed by the pipeline; the horseshoe carries contact quality). +/// +/// Raw EEG (`/muse/eeg`) is deliberately not derivable from a frame. The +/// static `rawEEG(_:)` helper exists for the explicit raw re-broadcast +/// toggle ADR-011 allows, and takes an `EEGSample`, so the call site that +/// forwards raw samples is greppable and distinct from everything else +/// this type does. +/// +/// Compatibility values are **not** health gated: a Mind Monitor +/// consumer expects band powers alongside a horseshoe and decides for +/// itself. The one concession is `averageOverHealthyChannelsOnly`, which +/// changes what the single averaged value averages over; per-channel +/// output is always all four channels so positions line up. +public struct MindMonitorMirror: Sendable, Hashable, Codable { + + /// Send 4 floats per band (Mind Monitor's "separate values for each + /// sensor" setting) instead of its default single average. + public var perChannel: Bool + + /// When averaging, use only healthy channels if any exist. + public var averageOverHealthyChannelsOnly: Bool + + /// Channel order for 4-float payloads. Mind Monitor's order is + /// TP9, AF7, AF8, TP10, which is `EEGChannel.allCases`. + public static let channelOrder: [EEGChannel] = EEGChannel.allCases + + public init(perChannel: Bool = false, averageOverHealthyChannelsOnly: Bool = true) { + self.perChannel = perChannel + self.averageOverHealthyChannelsOnly = averageOverHealthyChannelsOnly + } + + public static let horseshoeAddress = "/muse/elements/horseshoe" + public static let blinkAddress = "/muse/elements/blink" + public static let jawClenchAddress = "/muse/elements/jaw_clench" + public static let accelAddress = "/muse/acc" + public static let gyroAddress = "/muse/gyro" + public static let eegAddress = "/muse/eeg" + + /// Mind Monitor's horseshoe code for a health status. + public static func horseshoe(_ status: ChannelHealthStatus) -> Float { + switch status { + case .healthy: return 1 + case .unknown: return 2 + case .saturated, .dead, .stale: return 4 + } + } + + /// All messages for one frame, in a fixed order: five bands, then + /// horseshoe, then events, then IMU. + public func messages(for frame: BiofeedbackFrame) -> [OSCMessage] { + var messages: [OSCMessage] = [] + + for band in EEGBand.allCases { + let arguments: [OSCArgument] + if perChannel { + arguments = MindMonitorMirror.channelOrder.map { channel in + .float(frame.bandPowers[channel]?.bels(band) ?? BandPowers.bels(0)) + } + } else { + var channels = averageOverHealthyChannelsOnly ? frame.healthyChannels : frame.presentChannels + if channels.isEmpty { channels = frame.presentChannels } + let values = channels.compactMap { frame.bandPowers[$0]?.bels(band) } + let mean = values.isEmpty ? BandPowers.bels(0) : values.reduce(0, +) / Float(values.count) + arguments = [.float(mean)] + } + messages.append(OSCMessage(address: band.mindMonitorAbsoluteAddress, arguments: arguments)) + } + + messages.append(OSCMessage( + address: MindMonitorMirror.horseshoeAddress, + arguments: MindMonitorMirror.channelOrder.map { .float(MindMonitorMirror.horseshoe(frame.status(of: $0))) } + )) + + if frame.blink { + messages.append(OSCMessage(address: MindMonitorMirror.blinkAddress, arguments: [.int32(1)])) + } + if frame.jawClench { + messages.append(OSCMessage(address: MindMonitorMirror.jawClenchAddress, arguments: [.int32(1)])) + } + if let accel = frame.accel { + messages.append(OSCMessage(address: MindMonitorMirror.accelAddress, arguments: [.float(accel.x), .float(accel.y), .float(accel.z)])) + } + if let gyro = frame.gyro { + messages.append(OSCMessage(address: MindMonitorMirror.gyroAddress, arguments: [.float(gyro.x), .float(gyro.y), .float(gyro.z)])) + } + return messages + } + + /// Raw EEG re-broadcast in Mind Monitor's `/muse/eeg` format: one + /// float per channel in microvolts. Only the explicit raw toggle in + /// the egress configuration should call this; see ADR-011. + public static func rawEEG(_ sample: EEGSample) -> OSCMessage { + OSCMessage(address: eegAddress, arguments: sample.channels.map { .float($0) }) + } +} diff --git a/Sources/BCIBiofeedback/OSCUDPSender.swift b/Sources/BCIBiofeedback/OSCUDPSender.swift new file mode 100644 index 0000000..01a3d0f --- /dev/null +++ b/Sources/BCIBiofeedback/OSCUDPSender.swift @@ -0,0 +1,96 @@ +#if canImport(Network) +import Foundation +import Network +import os +import BCIEEG + +/// Sends `.osc` outputs as UDP datagrams to one host and port. The +/// biofeedback egress's only network transport; see ADR-011 for why it +/// exists next to a codebase whose first invariant is "no network at +/// runtime", and for the three tiers (loopback, LAN, never beyond). +/// +/// Defaults to `127.0.0.1:7000`: the same machine, and the port the Muse +/// Port Max for Live device listens on by default. Any other host is a +/// user's explicit choice and the app surfaces it in the privacy +/// indicator, the same way `MindMonitorOSCStream` surfaces its inbound +/// bind. +/// +/// Framing follows Mind Monitor: every tick's messages go out in one OSC +/// bundle with the immediate timetag (`bundle == true`). Set `bundle` to +/// false for a consumer that cannot unwrap bundles; each message is then +/// its own datagram. +/// +/// Actor-isolated so sends are serialised; `NWConnection` itself calls +/// back on its own queue and those callbacks touch no actor state. +public actor OSCUDPSender: BiofeedbackSink { + + public let host: String + public let port: UInt16 + public let bundle: Bool + + private var connection: NWConnection? + private let logger = Logger(subsystem: "com.neuralcompose.biofeedback", category: "osc-out") + + public init(host: String = "127.0.0.1", port: UInt16 = 7000, bundle: Bool = true) { + self.host = host + self.port = port + self.bundle = bundle + } + + /// True when the destination is the local machine. + public nonisolated var isLoopback: Bool { + host == "127.0.0.1" || host == "localhost" || host == "::1" + } + + /// Open the connection. Idempotent. Logs the destination at `.notice` + /// so a session log always records where features were sent. + public func start() { + guard connection == nil, let nwPort = NWEndpoint.Port(rawValue: port) else { return } + let conn = NWConnection(host: NWEndpoint.Host(host), port: nwPort, using: .udp) + let logger = self.logger + let destination = "\(host):\(port)" + conn.stateUpdateHandler = { state in + switch state { + case .ready: + logger.notice("OSC egress ready -> \(destination, privacy: .public)") + case .failed(let error): + logger.error("OSC egress failed -> \(destination, privacy: .public): \(error.localizedDescription, privacy: .public)") + case .waiting(let error): + logger.notice("OSC egress waiting -> \(destination, privacy: .public): \(error.localizedDescription, privacy: .public)") + default: + break + } + } + conn.start(queue: DispatchQueue(label: "com.neuralcompose.biofeedback.osc-out")) + connection = conn + logger.notice("OSC egress started -> \(destination, privacy: .public) (derived features only; see ADR-011)") + } + + public func stop() { + connection?.cancel() + connection = nil + } + + public func emit(_ outputs: [BiofeedbackOutput]) async { + guard let connection else { return } + let messages = outputs.compactMap(\.oscMessage) + guard !messages.isEmpty else { return } + if bundle { + send(OSCEncoder.encodeBundle(messages), over: connection) + } else { + for message in messages { + send(OSCEncoder.encode(message), over: connection) + } + } + } + + private func send(_ data: Data, over connection: NWConnection) { + let logger = self.logger + connection.send(content: data, completion: .contentProcessed { error in + if let error { + logger.error("OSC egress send error: \(error.localizedDescription, privacy: .public)") + } + }) + } +} +#endif diff --git a/Sources/BCIEEG/OSC/OSCEncoder.swift b/Sources/BCIEEG/OSC/OSCEncoder.swift new file mode 100644 index 0000000..3b5dcd3 --- /dev/null +++ b/Sources/BCIEEG/OSC/OSCEncoder.swift @@ -0,0 +1,78 @@ +import Foundation + +/// Minimal OSC 1.0 message and bundle encoder. The exact mirror of +/// `MuseOSCDecoder`: int32 (`i`), float32 (`f`) and string (`s`) +/// arguments, 4-byte alignment, big-endian numerics. Pure data in, pure +/// bytes out; no networking and no opinion about what an address means. +/// +/// Until ADR-011 NeuralCompose only ever *received* OSC, so the only +/// encoder in the tree was a private test helper in +/// `MuseOSCDecoderTests`. This is that helper promoted to production, +/// because the biofeedback egress (`BCIBiofeedback`) needs to send the +/// same wire format Mind Monitor sends, so that downstream consumers +/// written against Mind Monitor (Max for Live devices, TouchDesigner, +/// SuperCollider patches) work unchanged. +/// +/// Round-trip property, enforced by `OSCEncoderTests`: +/// `MuseOSCDecoder.decode(OSCEncoder.encode(m)) == m` for every message +/// whose arguments are int32 / float32 / string, and +/// `MuseOSCDecoder.decodePacket(OSCEncoder.encodeBundle(ms)) == ms`. +public enum OSCEncoder { + + /// The OSC "immediately" timetag: a 64-bit NTP value of exactly 1. + public static let immediateTimetag: UInt64 = 1 + + /// Encodes one bare message (no bundle framing). + public static func encode(_ message: OSCMessage) -> Data { + var data = paddedString(message.address) + var typeTags = "," + for argument in message.arguments { + switch argument { + case .int32: typeTags.append("i") + case .float: typeTags.append("f") + case .string: typeTags.append("s") + } + } + data.append(paddedString(typeTags)) + for argument in message.arguments { + switch argument { + case .int32(let value): + appendBigEndian(UInt32(bitPattern: value), to: &data) + case .float(let value): + appendBigEndian(value.bitPattern, to: &data) + case .string(let value): + data.append(paddedString(value)) + } + } + return data + } + + /// Encodes one OSC bundle containing `messages`, in order, with the + /// given NTP timetag (default: immediately). Mind Monitor wraps every + /// message it sends in a bundle, so consumers built against it expect + /// this framing; `MuseOSCDecoder.decodePacket` unwraps it. + public static func encodeBundle(_ messages: [OSCMessage], timetag: UInt64 = immediateTimetag) -> Data { + var data = paddedString("#bundle") + appendBigEndian(timetag, to: &data) + for message in messages { + let element = encode(message) + appendBigEndian(UInt32(element.count), to: &data) + data.append(element) + } + return data + } + + /// An OSC string: UTF-8 bytes, a NUL terminator, then NUL padding up + /// to the next multiple of four bytes. + public static func paddedString(_ string: String) -> Data { + var data = Data(string.utf8) + data.append(0) + while data.count % 4 != 0 { data.append(0) } + return data + } + + private static func appendBigEndian(_ value: T, to data: inout Data) { + var bigEndian = value.bigEndian + withUnsafeBytes(of: &bigEndian) { data.append(contentsOf: $0) } + } +} diff --git a/Tests/BCIBiofeedbackTests/BandPowerEstimatorTests.swift b/Tests/BCIBiofeedbackTests/BandPowerEstimatorTests.swift new file mode 100644 index 0000000..24b95fd --- /dev/null +++ b/Tests/BCIBiofeedbackTests/BandPowerEstimatorTests.swift @@ -0,0 +1,110 @@ +import XCTest +import BCICore +@testable import BCIBiofeedback + +/// Physical-unit checks on the periodogram. A sinusoid of amplitude A has +/// mean-square A²/2; with the `2 / (fs * sum(w²))` Hann scaling the band +/// containing it must report that figure, and every other band must be +/// close to zero. These numbers were cross-checked against an +/// independent reimplementation before the tolerances were set. +final class BandPowerEstimatorTests: XCTestCase { + + private let sampleRate = 256.0 + + private func sinusoid(hz: Double, amplitude: Float, offset: Float = 800, count: Int = 256) -> [Float] { + (0.. [Float] { + outputs.compactMap { output -> Float? in + guard let message = output.oscMessage, message.address == address else { return nil } + return message.floatArguments.first + } + } + + private func ccValues(_ outputs: [BiofeedbackOutput]) -> [UInt8] { + outputs.compactMap { output -> UInt8? in + if case .controlChange(_, _, let value)? = output.midiEvent { return value } + return nil + } + } + + // MARK: - Shaping + + func testLinearNormalisationAndClamp() { + // Alpha in Bels; 1 Bel = 10 µV², 2 Bels = 100 µV². + let mapping = BiofeedbackMapping(feature: alphaTP9, target: .osc(address: "/nc/alpha"), inputLow: 1, inputHigh: 2) + var mapper = FeatureMapper(mappings: [mapping]) + + let mid = mapper.step(TestFrames.frame(at: 0, tp9: TestFrames.powers(alpha: Float(pow(10.0, 1.5))))) + XCTAssertEqual(oscValues(mid, address: "/nc/alpha").first ?? -1, 0.5, accuracy: 1e-5) + + let above = mapper.step(TestFrames.frame(at: 1, tp9: TestFrames.powers(alpha: 10_000))) + XCTAssertEqual(oscValues(above, address: "/nc/alpha").first, 1, "clamped high") + + let below = mapper.step(TestFrames.frame(at: 2, tp9: TestFrames.powers(alpha: 0.001))) + XCTAssertEqual(oscValues(below, address: "/nc/alpha").first, 0, "clamped low") + } + + func testLog10CurveOnLinearRatio() { + // theta/beta ratio from 0.1 to 10 on a log curve: ratio 1 is the midpoint. + let feature = BiofeedbackFeature.bandRatio(numerator: .theta, denominator: .beta, channel: .tp9) + let mapping = BiofeedbackMapping(feature: feature, target: .osc(address: "/nc/tb"), inputLow: 0.1, inputHigh: 10, curve: .log10) + var mapper = FeatureMapper(mappings: [mapping]) + let out = mapper.step(TestFrames.frame(at: 0, tp9: TestFrames.powers(beta: 20, theta: 20))) + XCTAssertEqual(oscValues(out, address: "/nc/tb").first ?? -1, 0.5, accuracy: 1e-5) + } + + func testInvertedRangeIsAllowed() { + // inputLow > inputHigh flips the direction: more alpha, smaller output. + let mapping = BiofeedbackMapping(feature: alphaTP9, target: .osc(address: "/nc/inv"), inputLow: 2, inputHigh: 1) + var mapper = FeatureMapper(mappings: [mapping]) + let out = mapper.step(TestFrames.frame(at: 0, tp9: TestFrames.powers(alpha: 10_000))) + XCTAssertEqual(oscValues(out, address: "/nc/inv").first, 0, "4 Bels is past the inverted range, clamps to 0") + } + + // MARK: - Smoothing + + func testExponentialSmoothingFollowsTimeConstant() { + let mapping = BiofeedbackMapping(feature: alphaTP9, target: .osc(address: "/nc/s"), inputLow: 1, inputHigh: 2, smoothingTau: 1.0) + var mapper = FeatureMapper(mappings: [mapping]) + // First frame seeds the smoother at 0 (alpha = 10 µV² = 1 Bel). + _ = mapper.step(TestFrames.frame(at: 0, tp9: TestFrames.powers(alpha: 10))) + // Step to 1.0 (100 µV²) one time constant later: 1 - e^-1 of the way. + let out = mapper.step(TestFrames.frame(at: 1, tp9: TestFrames.powers(alpha: 100))) + XCTAssertEqual(oscValues(out, address: "/nc/s").first ?? -1, 1 - Float(exp(-1.0)), accuracy: 1e-5) + } + + func testZeroTauIsNoSmoothing() { + let mapping = BiofeedbackMapping(feature: alphaTP9, target: .osc(address: "/nc/s"), inputLow: 1, inputHigh: 2, smoothingTau: 0) + var mapper = FeatureMapper(mappings: [mapping]) + _ = mapper.step(TestFrames.frame(at: 0, tp9: TestFrames.powers(alpha: 10))) + let out = mapper.step(TestFrames.frame(at: 0.1, tp9: TestFrames.powers(alpha: 10_000))) + XCTAssertEqual(oscValues(out, address: "/nc/s").first, 1) + } + + // MARK: - Rate limiting + + func testMinIntervalSuppressesIntermediateTicks() { + let mapping = BiofeedbackMapping(feature: alphaTP9, target: .osc(address: "/nc/r"), inputLow: 1, inputHigh: 2, minInterval: 0.1) + var mapper = FeatureMapper(mappings: [mapping]) + var emitted = 0 + for i in 0..<10 { + let t = Double(i) * 0.025 // 40 Hz frames + emitted += oscValues(mapper.step(TestFrames.frame(at: t, tp9: TestFrames.powers(alpha: 30))), address: "/nc/r").count + } + // t = 0, 0.1, 0.2 pass; 0.225 is the last frame. + XCTAssertEqual(emitted, 3) + } + + // MARK: - MIDI + + func testControlChangeQuantisesAndEmitsOnlyOnChange() { + let mapping = BiofeedbackMapping(feature: alphaTP9, target: .midiControl(controller: 1, channel: 0, fourteenBit: false), inputLow: 1, inputHigh: 2) + var mapper = FeatureMapper(mappings: [mapping]) + let first = mapper.step(TestFrames.frame(at: 0, tp9: TestFrames.powers(alpha: Float(pow(10.0, 1.25))))) + XCTAssertEqual(ccValues(first), [32], "0.25 * 127 = 31.75 rounds to 32") + let same = mapper.step(TestFrames.frame(at: 0.1, tp9: TestFrames.powers(alpha: Float(pow(10.0, 1.25))))) + XCTAssertTrue(same.isEmpty, "unchanged quantised value is not re-sent") + let changed = mapper.step(TestFrames.frame(at: 0.2, tp9: TestFrames.powers(alpha: 10_000))) + XCTAssertEqual(ccValues(changed), [127]) + } + + func testFourteenBitControlEmitsPair() { + let mapping = BiofeedbackMapping(feature: alphaTP9, target: .midiControl(controller: 1, channel: 0, fourteenBit: true), inputLow: 1, inputHigh: 2) + var mapper = FeatureMapper(mappings: [mapping]) + let out = mapper.step(TestFrames.frame(at: 0, tp9: TestFrames.powers(alpha: 10_000))) + XCTAssertEqual(out.compactMap(\.midiEvent), [ + .controlChange(channel: 0, controller: 1, value: 127), + .controlChange(channel: 0, controller: 33, value: 127), + ]) + } + + func testNoteGateOpensOnBlinkAndClosesAfterGate() { + let mapping = BiofeedbackMapping(feature: .blink, target: .midiNote(note: 60, channel: 0, velocity: 100, gate: 0.2), inputLow: 0, inputHigh: 1) + var mapper = FeatureMapper(mappings: [mapping]) + + XCTAssertTrue(mapper.step(TestFrames.frame(at: 0)).isEmpty, "no blink, nothing") + XCTAssertEqual(mapper.step(TestFrames.frame(at: 0.1, blink: true)).compactMap(\.midiEvent), [.noteOn(channel: 0, note: 60, velocity: 100)]) + XCTAssertTrue(mapper.step(TestFrames.frame(at: 0.15, blink: true)).isEmpty, "already open") + XCTAssertTrue(mapper.step(TestFrames.frame(at: 0.2, blink: true)).isEmpty, "held while blink persists and gate not expired") + XCTAssertEqual(mapper.step(TestFrames.frame(at: 0.35, blink: true)).compactMap(\.midiEvent), [.noteOff(channel: 0, note: 60)], "gate expired") + } + + func testNoteGateClosesWhenEventClearsEarly() { + let mapping = BiofeedbackMapping(feature: .jawClench, target: .midiNote(note: 62, channel: 0, velocity: 100, gate: 5), inputLow: 0, inputHigh: 1) + var mapper = FeatureMapper(mappings: [mapping]) + XCTAssertEqual(mapper.step(TestFrames.frame(at: 0, jawClench: true)).compactMap(\.midiEvent), [.noteOn(channel: 0, note: 62, velocity: 100)]) + XCTAssertEqual(mapper.step(TestFrames.frame(at: 0.1, jawClench: false)).compactMap(\.midiEvent), [.noteOff(channel: 0, note: 62)]) + } + + // MARK: - Health policies + + func testHoldLastKeepsLastHealthyValueWhileChannelIsDead() { + let mapping = BiofeedbackMapping(feature: alphaTP9, target: .osc(address: "/nc/h"), inputLow: 1, inputHigh: 2, healthPolicy: .holdLast) + var mapper = FeatureMapper(mappings: [mapping]) + _ = mapper.step(TestFrames.frame(at: 0, tp9: TestFrames.powers(alpha: Float(pow(10.0, 1.5))))) + // TP9 goes dead and its "power" collapses; output must not follow. + let dead = mapper.step(TestFrames.frame(at: 1, tp9: TestFrames.powers(alpha: 0.01), health: [.tp9: .dead, .af7: .healthy, .af8: .healthy, .tp10: .healthy])) + XCTAssertEqual(oscValues(dead, address: "/nc/h").first ?? -1, 0.5, accuracy: 1e-5) + // Recovery resumes tracking. + let back = mapper.step(TestFrames.frame(at: 2, tp9: TestFrames.powers(alpha: 10_000))) + XCTAssertEqual(oscValues(back, address: "/nc/h").first, 1) + } + + func testHoldLastEmitsNothingBeforeFirstHealthyValue() { + let mapping = BiofeedbackMapping(feature: alphaTP9, target: .osc(address: "/nc/h"), inputLow: 1, inputHigh: 2, healthPolicy: .holdLast) + var mapper = FeatureMapper(mappings: [mapping]) + let out = mapper.step(TestFrames.frame(at: 0, health: TestFrames.health(af7: .healthy).merging([.tp9: .unknown]) { $1 })) + XCTAssertTrue(out.isEmpty) + } + + func testPassthroughFollowsTheArtifact() { + let mapping = BiofeedbackMapping(feature: alphaTP9, target: .osc(address: "/nc/p"), inputLow: 1, inputHigh: 2, healthPolicy: .passthrough) + var mapper = FeatureMapper(mappings: [mapping]) + _ = mapper.step(TestFrames.frame(at: 0, tp9: TestFrames.powers(alpha: Float(pow(10.0, 1.5))))) + let dead = mapper.step(TestFrames.frame(at: 1, tp9: TestFrames.powers(alpha: 0.01), health: [.tp9: .dead])) + XCTAssertEqual(oscValues(dead, address: "/nc/p").first, 0, "Mind Monitor behaviour, by explicit choice") + } + + func testMuteEmitsNothingAndClosesOpenGate() { + let osc = BiofeedbackMapping(feature: alphaTP9, target: .osc(address: "/nc/m"), inputLow: 1, inputHigh: 2, healthPolicy: .mute) + let note = BiofeedbackMapping(feature: alphaTP9, target: .midiNote(note: 64, channel: 0, velocity: 90, gate: 10), inputLow: 1, inputHigh: 2, healthPolicy: .mute) + var mapper = FeatureMapper(mappings: [osc, note]) + let healthy = mapper.step(TestFrames.frame(at: 0, tp9: TestFrames.powers(alpha: 10_000))) + XCTAssertEqual(oscValues(healthy, address: "/nc/m").first, 1) + XCTAssertEqual(healthy.compactMap(\.midiEvent), [.noteOn(channel: 0, note: 64, velocity: 90)]) + let saturated = mapper.step(TestFrames.frame(at: 1, tp9: TestFrames.powers(alpha: 10_000), health: [.tp9: .saturated])) + XCTAssertTrue(oscValues(saturated, address: "/nc/m").isEmpty) + XCTAssertEqual(saturated.compactMap(\.midiEvent), [.noteOff(channel: 0, note: 64)]) + } + + func testDecayToRestGlidesWithTimeConstant() { + let mapping = BiofeedbackMapping(feature: alphaTP9, target: .osc(address: "/nc/d"), inputLow: 1, inputHigh: 2, healthPolicy: .decayToRest(rest: 0, tau: 1)) + var mapper = FeatureMapper(mappings: [mapping]) + _ = mapper.step(TestFrames.frame(at: 0, tp9: TestFrames.powers(alpha: 10_000))) // value 1 (clamped) + let dead: [EEGChannel: ChannelHealthStatus] = [.tp9: .dead] + let t0 = mapper.step(TestFrames.frame(at: 1, tp9: TestFrames.powers(alpha: 10_000), health: dead)) + XCTAssertEqual(oscValues(t0, address: "/nc/d").first ?? -1, 1, accuracy: 1e-6, "decay starts at the first unhealthy tick") + let t1 = mapper.step(TestFrames.frame(at: 2, tp9: TestFrames.powers(alpha: 10_000), health: dead)) + XCTAssertEqual(oscValues(t1, address: "/nc/d").first ?? -1, Float(exp(-1.0)), accuracy: 1e-5) + let t3 = mapper.step(TestFrames.frame(at: 4, tp9: TestFrames.powers(alpha: 10_000), health: dead)) + XCTAssertEqual(oscValues(t3, address: "/nc/d").first ?? -1, Float(exp(-3.0)), accuracy: 1e-5) + // Recovery jumps back to tracking with no smoothing configured. + let back = mapper.step(TestFrames.frame(at: 5, tp9: TestFrames.powers(alpha: 10_000))) + XCTAssertEqual(oscValues(back, address: "/nc/d").first, 1) + } + + func testStaleCountsAsUnhealthy() { + let mapping = BiofeedbackMapping(feature: alphaTP9, target: .osc(address: "/nc/st"), inputLow: 1, inputHigh: 2, healthPolicy: .holdLast) + var mapper = FeatureMapper(mappings: [mapping]) + _ = mapper.step(TestFrames.frame(at: 0, tp9: TestFrames.powers(alpha: 10_000))) + let stale = mapper.step(TestFrames.frame(at: 1, tp9: TestFrames.powers(alpha: 1), health: [.tp9: .stale])) + XCTAssertEqual(oscValues(stale, address: "/nc/st").first, 1, "held") + } + + // MARK: - Mapping set management and determinism + + func testReplaceMappingsKeepsStateForSurvivingIds() { + let keep = BiofeedbackMapping(feature: alphaTP9, target: .midiControl(controller: 1, channel: 0, fourteenBit: false), inputLow: 1, inputHigh: 2) + let drop = BiofeedbackMapping(feature: alphaTP9, target: .midiControl(controller: 2, channel: 0, fourteenBit: false), inputLow: 1, inputHigh: 2) + var mapper = FeatureMapper(mappings: [keep, drop]) + XCTAssertEqual(ccValues(mapper.step(TestFrames.frame(at: 0, tp9: TestFrames.powers(alpha: 10_000)))), [127, 127]) + mapper.replaceMappings([keep]) + XCTAssertTrue(mapper.step(TestFrames.frame(at: 1, tp9: TestFrames.powers(alpha: 10_000))).isEmpty, "kept mapping remembers its last value") + mapper.replaceMappings([keep, drop]) + XCTAssertEqual(ccValues(mapper.step(TestFrames.frame(at: 2, tp9: TestFrames.powers(alpha: 10_000)))), [127], "re-added mapping starts fresh") + } + + func testOutputsAreOrderedByMappingThenByTarget() { + let a = BiofeedbackMapping(feature: alphaTP9, target: .osc(address: "/a"), inputLow: 1, inputHigh: 2) + let b = BiofeedbackMapping(feature: .blink, target: .midiNote(note: 60, channel: 0, velocity: 100, gate: 1), inputLow: 0, inputHigh: 1) + let c = BiofeedbackMapping(feature: alphaTP9, target: .osc(address: "/c"), inputLow: 1, inputHigh: 2) + var mapper = FeatureMapper(mappings: [a, b, c]) + let out = mapper.step(TestFrames.frame(at: 0, tp9: TestFrames.powers(alpha: 10_000), blink: true)) + XCTAssertEqual(out, [ + .osc(OSCMessage(address: "/a", arguments: [.float(1)])), + .midi(.noteOn(channel: 0, note: 60, velocity: 100)), + .osc(OSCMessage(address: "/c", arguments: [.float(1)])), + ]) + } + + func testSameInputSequenceGivesIdenticalOutputs() { + let mappings = [ + BiofeedbackMapping(feature: alphaTP9, target: .osc(address: "/a"), inputLow: 1, inputHigh: 2, smoothingTau: 0.5), + BiofeedbackMapping(feature: .bandRelative(.beta, channel: nil), target: .midiControl(controller: 7, channel: 0, fourteenBit: true), inputLow: 0, inputHigh: 1, smoothingTau: 0.3), + ] + func run() -> [BiofeedbackOutput] { + var mapper = FeatureMapper(mappings: mappings) + var all: [BiofeedbackOutput] = [] + for i in 0..<50 { + let t = Double(i) * 0.1 + let alpha = 10 + 90 * Float(0.5 + 0.5 * sin(t)) + let health: [EEGChannel: ChannelHealthStatus] = i % 7 == 0 ? [.tp9: .dead] : TestFrames.allHealthy + all += mapper.step(TestFrames.frame(at: t, tp9: TestFrames.powers(alpha: alpha, beta: Float(i)), health: health)) + } + return all + } + XCTAssertEqual(run(), run()) + } + + func testMappingIsCodableRoundTrip() throws { + let mappings = [ + BiofeedbackMapping(feature: alphaTP9, target: .osc(address: "/a"), inputLow: 1, inputHigh: 2, curve: .linear, smoothingTau: 0.5, minInterval: 0.1, healthPolicy: .holdLast), + BiofeedbackMapping(feature: .blink, target: .midiNote(note: 60, channel: 1, velocity: 100, gate: 0.2), inputLow: 0, inputHigh: 1, healthPolicy: .mute), + BiofeedbackMapping(feature: .bandRatio(numerator: .theta, denominator: .beta, channel: nil), target: .midiControl(controller: 1, channel: 0, fourteenBit: true), inputLow: 0.1, inputHigh: 10, curve: .log10, healthPolicy: .decayToRest(rest: 0.5, tau: 2)), + ] + let decoded = try JSONDecoder().decode([BiofeedbackMapping].self, from: JSONEncoder().encode(mappings)) + XCTAssertEqual(decoded, mappings) + } +} diff --git a/Tests/BCIBiofeedbackTests/MIDIEventTests.swift b/Tests/BCIBiofeedbackTests/MIDIEventTests.swift new file mode 100644 index 0000000..9c60f70 --- /dev/null +++ b/Tests/BCIBiofeedbackTests/MIDIEventTests.swift @@ -0,0 +1,54 @@ +import XCTest +@testable import BCIBiofeedback + +final class MIDIEventTests: XCTestCase { + + func testControlChangeBytes() { + XCTAssertEqual(MIDIEvent.controlChange(channel: 0, controller: 1, value: 64).bytes, [0xB0, 0x01, 0x40]) + XCTAssertEqual(MIDIEvent.controlChange(channel: 15, controller: 74, value: 127).bytes, [0xBF, 0x4A, 0x7F]) + } + + func testNoteBytes() { + XCTAssertEqual(MIDIEvent.noteOn(channel: 1, note: 60, velocity: 100).bytes, [0x91, 0x3C, 0x64]) + XCTAssertEqual(MIDIEvent.noteOff(channel: 1, note: 60).bytes, [0x81, 0x3C, 0x00]) + } + + func testOutOfRangeValuesAreMasked() { + XCTAssertEqual(MIDIEvent.controlChange(channel: 16, controller: 200, value: 255).bytes, [0xB0, 0x48, 0x7F]) + } + + func testUMPWordIsMessageTypeTwoGroupZero() { + let word = MIDIEvent.controlChange(channel: 0, controller: 1, value: 64).umpWord + XCTAssertEqual(word, 0x20B0_0140) + XCTAssertEqual(MIDIEvent.noteOn(channel: 2, note: 0x3C, velocity: 0x64).umpWord, 0x2092_3C64) + } + + func testFourteenBitSplitsMSBThenLSB() { + let events = MIDIEvent.controlChange14(channel: 0, controller: 1, value: 0x1FFF) // 8191 + XCTAssertEqual(events, [ + .controlChange(channel: 0, controller: 1, value: 0x3F), + .controlChange(channel: 0, controller: 33, value: 0x7F), + ]) + XCTAssertEqual(MIDIEvent.controlChange14(channel: 0, controller: 1, value: 16383), [ + .controlChange(channel: 0, controller: 1, value: 127), + .controlChange(channel: 0, controller: 33, value: 127), + ]) + XCTAssertEqual(MIDIEvent.controlChange14(channel: 0, controller: 1, value: 0), [ + .controlChange(channel: 0, controller: 1, value: 0), + .controlChange(channel: 0, controller: 33, value: 0), + ]) + } + + func testFourteenBitClampsAndFallsBackAbove31() { + XCTAssertEqual(MIDIEvent.controlChange14(channel: 0, controller: 1, value: 60000).first, + .controlChange(channel: 0, controller: 1, value: 127)) + XCTAssertEqual(MIDIEvent.controlChange14(channel: 3, controller: 74, value: 8192), + [.controlChange(channel: 3, controller: 74, value: 64)]) + } + + func testCodableRoundTrip() throws { + let events: [MIDIEvent] = [.controlChange(channel: 0, controller: 1, value: 2), .noteOn(channel: 1, note: 60, velocity: 90), .noteOff(channel: 1, note: 60)] + let decoded = try JSONDecoder().decode([MIDIEvent].self, from: JSONEncoder().encode(events)) + XCTAssertEqual(decoded, events) + } +} diff --git a/Tests/BCIBiofeedbackTests/MindMonitorMirrorTests.swift b/Tests/BCIBiofeedbackTests/MindMonitorMirrorTests.swift new file mode 100644 index 0000000..10811c3 --- /dev/null +++ b/Tests/BCIBiofeedbackTests/MindMonitorMirrorTests.swift @@ -0,0 +1,108 @@ +import XCTest +import BCICore +import BCIEEG +@testable import BCIBiofeedback + +/// Pins the Mind Monitor-compatible address scheme and payload shapes +/// against the FAQ table, and checks the whole set survives the trip +/// through `OSCEncoder` and `MuseOSCDecoder`, which is the path a real +/// consumer sees. +final class MindMonitorMirrorTests: XCTestCase { + + private func message(_ messages: [OSCMessage], _ address: String) -> OSCMessage? { + messages.first { $0.address == address } + } + + func testAveragedModeSendsFiveBandsWithOneFloatEach() { + let frame = TestFrames.frame(at: 0, tp9: TestFrames.powers(alpha: 100), af7: TestFrames.powers(alpha: 100), af8: TestFrames.powers(alpha: 1), tp10: TestFrames.powers(alpha: 1)) + let messages = MindMonitorMirror(perChannel: false).messages(for: frame) + for band in EEGBand.allCases { + let m = message(messages, "/muse/elements/\(band.rawValue)_absolute") + XCTAssertNotNil(m, band.rawValue) + XCTAssertEqual(m?.floatArguments.count, 1) + } + // Mean of 2, 2, 0, 0 Bels. + XCTAssertEqual(message(messages, "/muse/elements/alpha_absolute")?.floatArguments.first ?? -9, 1, accuracy: 1e-6) + } + + func testPerChannelModeSendsFourFloatsInMuseOrder() { + let frame = TestFrames.frame(at: 0, tp9: TestFrames.powers(alpha: 1), af7: TestFrames.powers(alpha: 10), af8: TestFrames.powers(alpha: 100), tp10: TestFrames.powers(alpha: 1000)) + let messages = MindMonitorMirror(perChannel: true).messages(for: frame) + let alpha = message(messages, "/muse/elements/alpha_absolute")?.floatArguments ?? [] + XCTAssertEqual(alpha.count, 4) + XCTAssertEqual(alpha[0], 0, accuracy: 1e-6) // TP9 + XCTAssertEqual(alpha[1], 1, accuracy: 1e-6) // AF7 + XCTAssertEqual(alpha[2], 2, accuracy: 1e-6) // AF8 + XCTAssertEqual(alpha[3], 3, accuracy: 1e-6) // TP10 + } + + func testAverageSkipsUnhealthyChannelsButPerChannelDoesNot() { + let frame = TestFrames.frame(at: 0, tp9: TestFrames.powers(alpha: 100), af7: TestFrames.powers(alpha: 1), af8: TestFrames.powers(alpha: 100), tp10: TestFrames.powers(alpha: 100), health: TestFrames.health(af7: .dead)) + let averaged = MindMonitorMirror(perChannel: false, averageOverHealthyChannelsOnly: true).messages(for: frame) + XCTAssertEqual(message(averaged, "/muse/elements/alpha_absolute")?.floatArguments.first ?? -9, 2, accuracy: 1e-6) + let ungated = MindMonitorMirror(perChannel: false, averageOverHealthyChannelsOnly: false).messages(for: frame) + XCTAssertEqual(message(ungated, "/muse/elements/alpha_absolute")?.floatArguments.first ?? -9, 1.5, accuracy: 1e-6) + let perChannel = MindMonitorMirror(perChannel: true).messages(for: frame) + XCTAssertEqual(message(perChannel, "/muse/elements/alpha_absolute")?.floatArguments[1] ?? -9, 0, accuracy: 1e-6, "dead AF7 still occupies its slot") + } + + func testHorseshoeCodes() { + XCTAssertEqual(MindMonitorMirror.horseshoe(.healthy), 1) + XCTAssertEqual(MindMonitorMirror.horseshoe(.unknown), 2) + XCTAssertEqual(MindMonitorMirror.horseshoe(.saturated), 4) + XCTAssertEqual(MindMonitorMirror.horseshoe(.dead), 4) + XCTAssertEqual(MindMonitorMirror.horseshoe(.stale), 4) + + let frame = TestFrames.frame(at: 0, health: [.tp9: .healthy, .af7: .dead, .af8: .unknown, .tp10: .saturated]) + let horseshoe = message(MindMonitorMirror().messages(for: frame), "/muse/elements/horseshoe") + XCTAssertEqual(horseshoe?.floatArguments, [1, 4, 2, 4]) + } + + func testEventsAreSentOnlyWhenTrue() { + let quiet = MindMonitorMirror().messages(for: TestFrames.frame(at: 0)) + XCTAssertNil(message(quiet, "/muse/elements/blink")) + XCTAssertNil(message(quiet, "/muse/elements/jaw_clench")) + let busy = MindMonitorMirror().messages(for: TestFrames.frame(at: 0, blink: true, jawClench: true)) + XCTAssertEqual(message(busy, "/muse/elements/blink")?.arguments, [OSCArgument.int32(1)]) + XCTAssertEqual(message(busy, "/muse/elements/jaw_clench")?.arguments, [OSCArgument.int32(1)]) + } + + func testIMUIsForwardedWhenPresent() { + let accel = MovementSample(timestamp: 0, kind: .accel, x: 0.1, y: 0.2, z: 0.3) + let gyro = MovementSample(timestamp: 0, kind: .gyro, x: -1, y: -2, z: -3) + let messages = MindMonitorMirror().messages(for: TestFrames.frame(at: 0, accel: accel, gyro: gyro)) + XCTAssertEqual(message(messages, "/muse/acc")?.floatArguments, [0.1, 0.2, 0.3]) + XCTAssertEqual(message(messages, "/muse/gyro")?.floatArguments, [-1, -2, -3]) + XCTAssertNil(message(MindMonitorMirror().messages(for: TestFrames.frame(at: 0)), "/muse/acc")) + } + + func testMessageOrderIsStable() { + let messages = MindMonitorMirror().messages(for: TestFrames.frame(at: 0, blink: true)) + XCTAssertEqual(messages.map(\.address), [ + "/muse/elements/delta_absolute", + "/muse/elements/theta_absolute", + "/muse/elements/alpha_absolute", + "/muse/elements/beta_absolute", + "/muse/elements/gamma_absolute", + "/muse/elements/horseshoe", + "/muse/elements/blink", + ]) + } + + func testRawEEGHelperUsesMindMonitorAddressAndChannelOrder() { + let sample = EEGSample(timestamp: 0, channels: [801, 802, 803, 804]) + let message = MindMonitorMirror.rawEEG(sample) + XCTAssertEqual(message.address, "/muse/eeg") + XCTAssertEqual(message.floatArguments, [801, 802, 803, 804]) + } + + func testWholeTickSurvivesBundleRoundTrip() throws { + let accel = MovementSample(timestamp: 0, kind: .accel, x: 0, y: 0, z: 1) + let frame = TestFrames.frame(at: 0, blink: true, accel: accel, gyro: nil) + let messages = MindMonitorMirror(perChannel: true).messages(for: frame) + let decoded = try MuseOSCDecoder.decodePacket(OSCEncoder.encodeBundle(messages)) + XCTAssertEqual(decoded, messages) + // And the existing inbound decoder still recognises the IMU message. + XCTAssertNotNil(MindMonitorDecoder.movement(from: decoded.last!, timestamp: 0)) + } +} diff --git a/Tests/BCIBiofeedbackTests/TestFrames.swift b/Tests/BCIBiofeedbackTests/TestFrames.swift new file mode 100644 index 0000000..1e41ec9 --- /dev/null +++ b/Tests/BCIBiofeedbackTests/TestFrames.swift @@ -0,0 +1,51 @@ +import Foundation +import BCICore +@testable import BCIBiofeedback + +/// Frame builders shared by the mapper, mirror and feature tests. Band +/// powers are given in linear µV² per channel; health defaults to all +/// healthy. +enum TestFrames { + + static func powers(alpha: Float = 10, beta: Float = 10, theta: Float = 10, delta: Float = 10, gamma: Float = 10) -> BandPowers { + BandPowers(power: [.alpha: alpha, .beta: beta, .theta: theta, .delta: delta, .gamma: gamma]) + } + + static func frame( + at t: TimeInterval, + tp9: BandPowers? = powers(), + af7: BandPowers? = powers(), + af8: BandPowers? = powers(), + tp10: BandPowers? = powers(), + health: [EEGChannel: ChannelHealthStatus] = allHealthy, + blink: Bool = false, + jawClench: Bool = false, + accel: MovementSample? = nil, + gyro: MovementSample? = nil + ) -> BiofeedbackFrame { + var bandPowers: [EEGChannel: BandPowers] = [:] + if let tp9 { bandPowers[.tp9] = tp9 } + if let af7 { bandPowers[.af7] = af7 } + if let af8 { bandPowers[.af8] = af8 } + if let tp10 { bandPowers[.tp10] = tp10 } + return BiofeedbackFrame( + timestamp: t, + bandPowers: bandPowers, + health: health, + blink: blink, + jawClench: jawClench, + accel: accel, + gyro: gyro + ) + } + + static let allHealthy: [EEGChannel: ChannelHealthStatus] = [ + .tp9: .healthy, .af7: .healthy, .af8: .healthy, .tp10: .healthy, + ] + + static func health(af7: ChannelHealthStatus) -> [EEGChannel: ChannelHealthStatus] { + var h = allHealthy + h[.af7] = af7 + return h + } +} diff --git a/Tests/BCIEEGTests/OSCEncoderTests.swift b/Tests/BCIEEGTests/OSCEncoderTests.swift new file mode 100644 index 0000000..28b8535 --- /dev/null +++ b/Tests/BCIEEGTests/OSCEncoderTests.swift @@ -0,0 +1,70 @@ +import XCTest +@testable import BCIEEG + +/// The encoder is the mirror of `MuseOSCDecoder`, so the property that +/// matters is the round trip through the decoder that already guards the +/// inbound path. A few byte-exact checks pin the wire format against the +/// OSC 1.0 spec independently of the decoder. +final class OSCEncoderTests: XCTestCase { + + // MARK: - Byte-exact + + func testPaddedStringAppendsNULAndPadsToFourBytes() { + XCTAssertEqual(Array(OSCEncoder.paddedString("/a")), [0x2F, 0x61, 0x00, 0x00]) + // Exactly three characters needs one NUL to reach four bytes. + XCTAssertEqual(Array(OSCEncoder.paddedString("abc")), [0x61, 0x62, 0x63, 0x00]) + // Exactly four characters needs a NUL and then three more of padding. + XCTAssertEqual(OSCEncoder.paddedString("abcd").count, 8) + } + + func testSingleFloatMessageBytes() { + let data = OSCEncoder.encode(OSCMessage(address: "/a", arguments: [.float(1.0)])) + // "/a\0\0" + ",f\0\0" + 0x3F800000 big-endian + XCTAssertEqual(Array(data), [0x2F, 0x61, 0x00, 0x00, 0x2C, 0x66, 0x00, 0x00, 0x3F, 0x80, 0x00, 0x00]) + } + + func testBundleHeaderAndElementSize() { + let message = OSCMessage(address: "/a", arguments: [.int32(7)]) + let data = OSCEncoder.encodeBundle([message]) + let bytes = Array(data) + XCTAssertEqual(Array(bytes[0..<8]), Array("#bundle".utf8) + [0x00]) + XCTAssertEqual(Array(bytes[8..<16]), [0, 0, 0, 0, 0, 0, 0, 1], "immediate timetag") + let element = OSCEncoder.encode(message) + XCTAssertEqual(Array(bytes[16..<20]), [0, 0, 0, UInt8(element.count)]) + XCTAssertEqual(Array(bytes[20...]), Array(element)) + } + + // MARK: - Round trip + + func testBareMessageRoundTrip() throws { + let message = OSCMessage(address: "/muse/elements/alpha_absolute", arguments: [ + .float(0.25), .float(-1.5), .float(0), .float(2.0), + ]) + let decoded = try MuseOSCDecoder.decode(OSCEncoder.encode(message)) + XCTAssertEqual(decoded, message) + } + + func testMixedArgumentRoundTrip() throws { + let message = OSCMessage(address: "/nc/test", arguments: [ + .int32(1), .float(3.5), .string("hello"), .int32(-2), .string("four"), + ]) + let decoded = try MuseOSCDecoder.decode(OSCEncoder.encode(message)) + XCTAssertEqual(decoded, message) + } + + func testBundleRoundTripPreservesOrder() throws { + let messages = [ + OSCMessage(address: "/muse/elements/alpha_absolute", arguments: [.float(0.5)]), + OSCMessage(address: "/muse/elements/horseshoe", arguments: [.float(1), .float(2), .float(4), .float(1)]), + OSCMessage(address: "/muse/elements/blink", arguments: [.int32(1)]), + ] + let decoded = try MuseOSCDecoder.decodePacket(OSCEncoder.encodeBundle(messages)) + XCTAssertEqual(decoded, messages) + } + + func testBareMessageAlsoDecodesThroughPacketPath() throws { + let message = OSCMessage(address: "/muse/acc", arguments: [.float(0.1), .float(-0.9), .float(0.0)]) + let decoded = try MuseOSCDecoder.decodePacket(OSCEncoder.encode(message)) + XCTAssertEqual(decoded, [message]) + } +} diff --git a/docs/architecture/decision-log/ADR-011-biofeedback-egress.md b/docs/architecture/decision-log/ADR-011-biofeedback-egress.md new file mode 100644 index 0000000..7b74997 --- /dev/null +++ b/docs/architecture/decision-log/ADR-011-biofeedback-egress.md @@ -0,0 +1,209 @@ +# ADR-011: Biofeedback egress: derived features out over MIDI and OSC, health gated, off by default + +**Status**: Accepted +**Date**: 2026-11-06 + +## Context + +NeuralCompose already consumes the first half of the "Muse controls a +DAW" chain that Mind Monitor users build: `MindMonitorOSCStream` receives +`/muse/eeg`, `/muse/acc` and `/muse/gyro` over UDP (ADR-004), the +pipeline windows it, and `ChannelHealthThresholds` classifies every +electrode as healthy, saturated, dead or stale. What the codebase lacks +is the second half: a way for anything outside the process to react to +what the pipeline computed. The pipeline terminates at text, speech and +the 3D workspace. + +The community chain is Muse to Mind Monitor (paid phone app) to OSC on +UDP 7000 to the Muse Port Max for Live device (Live Suite only, licensed +CC BY-NC-SA) to mapped Live parameters, with a second device for MIDI +notes. It has a property worth fixing rather than copying: Muse Port +displays contact quality (Mind Monitor's "horseshoe") but keeps mapping +band powers while an electrode is bad, so the music follows the +artifact. NeuralCompose's own AF7 pad is a live example of why that +matters. + +Adding egress collides with the project's first invariant, "No network +at runtime" (CLAUDE.md, PRINCIPLES.md Principle 5). ADR-004 made the +inbound OSC listener an explicit, indicated exception. Decision registry +entry 8 made `BCICloudBridge` the first deliberate exception for +outbound traffic, scoped to the opt-in hypnagogic loop, and entry 9 added +`BCIPeerBridge` for the opt-in two-machine Tailscale dialectic bridge. +Egress of EEG-derived numbers is a new kind of outbound traffic and needs +its own decision (entry 10), not a quiet widening of entries 8 or 9. + +Two more constraints shape the design. CONTRIBUTING requires a protocol +to ship with only a stub, and concrete adapters in follow-up PRs. And the +project's evidence discipline (ADR-002, Principle 3) wants deterministic +replay before live validation: anything that drives a synthesizer must be +reproducible from a recording. + +## Decision + +1. **A new target, `BCIBiofeedback`, owns the egress.** It depends on + `BCICore` and `BCIEEG` only, is imported only by `NeuralComposeApp`, + and may never become a dependency of another `BCI*` target. Network + (`Network.framework`) and CoreMIDI are system frameworks used behind + `canImport`; no third-party dependency is added. + +2. **Only derived features leave the process.** The egress boundary is + `BiofeedbackFrame`: per-channel band powers (µV², emitted as Bels), + per-channel health, the two Track A events, and IMU readings when the + transport has them. No raw EEG, no text, no transcript, no identity is + reachable from a frame. Raw EEG re-broadcast in Mind Monitor's + `/muse/eeg` format exists as a separate, explicit toggle implemented + by `MindMonitorMirror.rawEEG(_:)`, which takes an `EEGSample`, so the + one call site that forwards raw samples is greppable. + +3. **Three transport tiers, each a separate user choice:** + - *MIDI virtual source* (`CoreMIDIVirtualSource`): in-machine IPC, not + network. The default transport when the feature is enabled. + - *OSC to loopback* (`OSCUDPSender` with host `127.0.0.1`): UDP, but + the datagrams never leave the machine. Default OSC destination. + - *OSC to a LAN host*: any other host. Surfaced in the privacy + indicator with the destination, and logged at `.notice` on start, + mirroring what ADR-004 requires of the inbound listener. + The feature as a whole is off by default; while off, the app wires + `NullBiofeedbackSink` so the mapper path stays exercised with nothing + leaving the process. + +4. **Health gating is mandatory and lives in one place.** Every + `BiofeedbackMapping` carries a `HealthPolicy` (`holdLast` by default, + plus `decayToRest`, `mute`, and an explicit `passthrough` that + reproduces Mind Monitor behaviour by choice rather than by omission). + `FeatureMapper` applies it; transports never see health. The one + deliberate exception is `MindMonitorMirror`, whose job is wire + compatibility: it emits ungated band powers alongside the horseshoe, + because that is what a Mind Monitor consumer expects, with an option + to average only over healthy channels. + +5. **Speak Mind Monitor's protocol, copy nothing from Muse Port.** The + address scheme and payload shapes come from Mind Monitor's published + FAQ table and are reproduced exactly, including its band edges and its + theta/alpha overlap, so existing patches work unchanged. Muse Port is + CC BY-NC-SA and nothing from it enters this MIT repository. + +6. **Deterministic by construction.** `BandPowerEstimator` is pure Swift + (Hann, radix-2 FFT, physical-unit PSD scaling) with no Accelerate, and + `FeatureMapper` takes time from frame timestamps, never from a clock. + The same recording through the same mapping set yields byte-identical + OSC and MIDI, which is what the golden-recording regression (follow-up + issue) pins. + +7. **Protocol first.** `BiofeedbackSink` ships with `NullBiofeedbackSink` + (the stub), `RecordingBiofeedbackSink` (tests and fixtures) and + `CompositeBiofeedbackSink`. The two production adapters are in the + tree behind `canImport` but are wired into `AppContainer` only in the + follow-up PRs that add their settings and privacy-indicator strings. + +## Alternatives Considered + +**Add OSC output to `BCIEEG` next to the inbound stream.** Smallest +diff, but it puts egress in the acquisition module and makes "does this +target send anything?" a per-file question. A dedicated target keeps the +answer to the egress audit a `grep` over one directory. Rejected. + +**Reuse `BCICloudBridge` as the egress home.** It is already the sanctioned +outbound module. But its contract is cloud text through the `claude` +CLI, and mixing in LAN UDP of EEG features would blur the one thing +entry 8 kept sharp. Separate targets, separate registry entries. +Rejected. + +**MIDI only, no OSC.** Avoids the network question entirely and covers +every DAW. But the installed base of brain-to-music patches is OSC +(Max, TouchDesigner, SuperCollider, Bitwig), and the Mind Monitor +compatibility story is OSC. Loopback OSC is the compromise: UDP without +leaving the machine. Rejected as the only path; kept as the default +transport. + +**Gate inside the transports.** Would let `MindMonitorMirror` be gated +too. But then a transport knows about health, and the mapper's policy +would be duplicated in two places. Gating in one pure function that +tests can drive is worth the mirror being ungated by design. Rejected. + +**Stream raw EEG by default for maximum compatibility.** Mind Monitor +sends `/muse/eeg` at 256 Hz and some patches consume it. But raw EEG is +the one payload with real privacy weight, and nothing in the music use +case needs it. Explicit toggle, off by default. Rejected as default. + +**Accelerate (vDSP) for the FFT.** Faster, and macOS-only is already the +platform. But the fixtures need bit-stable results across machines and +toolchain versions, and the window sizes here (256 samples at 10 Hz) do +not need the speed. Pure Swift now; vDSP later behind the same signature +with the fixtures as acceptance. Rejected for now. + +## What this prevents + +- A patch or synthesizer driven by a tarnished electrode: the default + policy holds the last healthy value, and the user has to choose + `passthrough` to get the Mind Monitor behaviour. +- Egress creeping into other targets: the only `NWConnection` sender and + the only CoreMIDI client in `Sources/` live in `BCIBiofeedback`, and + the Package.swift comment forbids other `BCI*` targets from depending + on it. +- Raw EEG leaving the machine by accident: it is not derivable from a + frame, and the one helper that produces it is named for what it does. +- Silent widening of the network invariant: registry entry 10 records + this exception with the same scope guard language as entries 8 and 9. +- Untestable music mappings: every behaviour in `FeatureMapper` has a + fixture-style test, and the replay path makes a recording the unit of + validation. + +## When this rule does not apply + +- **Inbound OSC** is ADR-004's domain. Nothing here changes how + `MindMonitorOSCStream` binds or what it accepts. +- **Cloud egress** stays exclusively in `BCICloudBridge` under entry 8. + `BCIBiofeedback` has no HTTP client and must not grow one; a future + "send features to a web service" idea is a new ADR, not a new host + string. +- **Research exports** (CSV, JSON written to disk for analysis) are not + egress in this sense and are governed by ADR-005's local logging + rules. +- **Network MIDI sessions** (macOS's RTP-MIDI) are a system feature a + user can enable in Audio MIDI Setup, which would carry the virtual + source over the network. This ADR does not enable it and the app does + not detect it; the privacy indicator describes what the app does, not + what the OS might forward. +- **The World Model and Laya latents** are not features yet. Exposing a + learned state vector as a control signal is attractive and is listed + as a follow-up, but it waits for a benchmarked encoder; nothing here + pre-commits to it. + +## Related implementation + +- `Sources/BCIBiofeedback/EEGBand.swift`: Mind Monitor band edges. +- `Sources/BCIBiofeedback/BandPowerEstimator.swift`: periodogram in µV², + `BandPowers` with Bels and relative helpers. +- `Sources/BCIBiofeedback/BiofeedbackFrame.swift`: the egress boundary. +- `Sources/BCIBiofeedback/BiofeedbackFeature.swift`: the mappable scalars + and their health semantics. +- `Sources/BCIBiofeedback/BiofeedbackMapping.swift`: targets, curves, + smoothing, rate limit, `HealthPolicy`. +- `Sources/BCIBiofeedback/FeatureMapper.swift`: deterministic shaping and + gating; the only place health policy is applied. +- `Sources/BCIBiofeedback/MindMonitorMirror.swift`: compatibility + output and the explicit `rawEEG` helper. +- `Sources/BCIBiofeedback/MIDIEvent.swift`: classic bytes and UMP words. +- `Sources/BCIBiofeedback/BiofeedbackSink.swift`: protocol, null, + recording and composite sinks. +- `Sources/BCIBiofeedback/OSCUDPSender.swift`, + `CoreMIDIVirtualSource.swift`: the two transports. +- `Sources/BCIEEG/OSC/OSCEncoder.swift`: the production encoder, mirror + of `MuseOSCDecoder`. +- Tests: `Tests/BCIBiofeedbackTests/*`, `Tests/BCIEEGTests/OSCEncoderTests.swift`. +- `Evaluation/reports/decision_registry.md` entry 10. + +## Change protocol for this ADR + +- Adding a transport (a file writer, a WebSocket, anything) requires + amending section 3 and registry entry 10, and the new transport must + conform to `BiofeedbackSink` without touching `FeatureMapper`. +- Adding a feature case to `BiofeedbackFeature` is additive (Principle + 4) and needs: its units in the doc comment, its `requiredChannels` and + `isHealthy` semantics, and tests in `BiofeedbackFeatureTests`. +- Changing a band edge breaks Mind Monitor compatibility and needs a + version note in `MindMonitorMirror`'s doc comment plus a fixture + update. +- Any change that lets raw EEG reach a frame, or any payload that is not + a function of a frame, supersedes this ADR rather than amending it.