From 41ac8f90c47c9e2fab8b7c5b80b29633a14c62fe Mon Sep 17 00:00:00 2001 From: troylefevre65 <126133953+troylefevre65@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:59:19 -0700 Subject: [PATCH 1/2] Score tracks by their real boundaries and measure Music's own queue notices Comparison view - track_formats selects the decoder report by when it was logged, which is the audible boundary, instead of by when Music began buffering the item. - A track runs from its estimated start to the next one's. The view had taken the collector's late observation of a track change for the boundary and credited the next track's first RateCue snapshot to the track that had just ended: 194 of 427 plays reported unknown and 6 mismatched, where RateCue had ended 139 of 399 without a depth and had published no wrong lossless depth. - Leave out two kinds of row that are not plays of their own: Music showing the previous track with the new position for a moment at a boundary, and one play recorded twice. - A report with a rate and no depth is a lossy rendition. Displaying no depth for it is a match; displaying one is a mismatch. Collector - queue_prediction_metrics scores Music's advance notice of a queue item's format, at queueing and at buffering, against the item's first report. A database that predates the table is scored once from raw_log. - A same-track restart is recorded once a second poll confirms it. - Read the displayed format from the explicit fields RateCue 0.2 publishes, and understand both the new and the earlier menu title. Gate and agent - Allow RateCue's read-only decoder-status command. - Describe the new semantics and tables in the agent's schema notes. Adds SPDX license identifiers to every source file. Co-Authored-By: Claude Fable 5.2 --- llm-box/agent.py | 17 ++- llm-box/model_eval_seed.py | 1 + llm-box/model_smoke_test.py | 1 + llm-box/provision.sh | 1 + llm-box/start-model-host.ps1 | 1 + mac/authorize-key.sh | 1 + mac/collector.py | 216 ++++++++++++++++++++++++++---- mac/install.sh | 1 + mac/readonly_gate.py | 3 +- tests/test_streamwatch.py | 249 +++++++++++++++++++++++++++++++++++ 10 files changed, 465 insertions(+), 26 deletions(-) diff --git a/llm-box/agent.py b/llm-box/agent.py index 538642e..3750f4e 100755 --- a/llm-box/agent.py +++ b/llm-box/agent.py @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only """StreamWatch research agent (runs on the LLM box). Mission: improve RateCue's sample-rate/bit-depth detection. Each cycle it: @@ -103,11 +104,14 @@ stream_sample_rate_hz, stream_bit_depth (decoder report, else best other log source), format_sources, codec_hints, decoder_rate_hz, decoder_bit_depth, decoder_audio_format, decoder_lifecycle, decoder_start_offset_s, - decoder_report_delay_s, decoder_competing (lifecycles starting within 3 s of the nearest), decoder_competing_depths - -- RateCue's method: fpfs report of the lifecycle that started nearest est_start (+/-30 s) + decoder_report_delay_s, decoder_competing (lifecycles starting within 3 s of the selected one), decoder_competing_depths + -- RateCue's method: the fpfs report logged nearest est_start (3 s before to 8 s after). Music logs it at the + -- audible boundary; the lifecycle can start buffering much earlier (decoder_start_offset_s, often -10 to -25). + -- decoder_rate_hz set with decoder_bit_depth NULL = Music reported a lossy rendition (no source depth). ls_rate_hz, ls_bit_depth, ls_codec_hint -- LosslessSwitcher's method: nearest 'audioCapabilities' line (+/-20 s) ratecue_title, ratecue_rate_hz, ratecue_depth, ratecue_publication, ratecue_posterior24, ratecue_log_status, - ratecue_depth_ms -- what the RateCue menu app displayed at the end of the track + ratecue_depth_ms -- the last RateCue snapshot taken while this track was current + -- (between its est_start and the next track's est_start) ratecue_vs_decoder ('match'|'MISMATCH'|'ratecue_unknown'|'no_ratecue'|'no_decoder'), ls_vs_decoder ('match'|'MISMATCH'|'ls_no_depth'|'ls_none'|'no_decoder'), device_sample_rate_hz, device_transport, device_sample_age_s @@ -125,6 +129,13 @@ sequence_hits, sequence_misses, rate_hits, rate_misses, depth_hits, depth_misses, mean_sequence_confidence, mean_observed_after_s. No track ID, exact time or per-play row is exposed. Predictions are best-effort queue-sequence measurements; they never authorize a RateCue or device action. +- queue_prediction_metrics (VIEW, aggregate only): metric_date, stage ('queued' = highest eligible lossless variant, + logged when Music queues an item | 'prebuffered' = the variant Music chose, logged when it starts buffering the + item), prediction_count, unresolved_count (item never reported), format_hits, format_misses, rate_misses, + depth_misses, played_lossy, lead_under_1s (skips: notice and report arrive together), mean_lead_s, min_lead_s. + Music's own advance notice of a queue item's format, scored against that item's first decoder report. +- queue_predictions: id, ts, lifecycle, stage, sample_rate_hz, bit_depth (the notices themselves; join + lifecycle_events on lifecycle for the reports) - raw_log: id, ts, subsystem, category, message (audio-related unified-log lines from the Music process, 30-day retention) - collector_health: ts, component, message diff --git a/llm-box/model_eval_seed.py b/llm-box/model_eval_seed.py index a1f73d1..50fdc4d 100644 --- a/llm-box/model_eval_seed.py +++ b/llm-box/model_eval_seed.py @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only """Clone an archived agent database and seed the fixed model-comparison leads.""" import argparse import os diff --git a/llm-box/model_smoke_test.py b/llm-box/model_smoke_test.py index 969801a..307c600 100644 --- a/llm-box/model_smoke_test.py +++ b/llm-box/model_smoke_test.py @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only """Verify an OpenAI-compatible endpoint can run a StreamWatch tool cycle.""" import argparse import json diff --git a/llm-box/provision.sh b/llm-box/provision.sh index c3cc5c9..d11b768 100755 --- a/llm-box/provision.sh +++ b/llm-box/provision.sh @@ -1,4 +1,5 @@ #!/usr/bin/env bash +# SPDX-License-Identifier: GPL-3.0-only # Provisions the dedicated Linux model host for StreamWatch. # Run from the llm-box folder: sudo MAC_SSH=@ LAN_CIDR= ./provision.sh # Re-run after the reboot that follows the NVIDIA driver install. The script is safe to run repeatedly. diff --git a/llm-box/start-model-host.ps1 b/llm-box/start-model-host.ps1 index 0f9a675..b772b9f 100644 --- a/llm-box/start-model-host.ps1 +++ b/llm-box/start-model-host.ps1 @@ -1,3 +1,4 @@ +# SPDX-License-Identifier: GPL-3.0-only [CmdletBinding()] param( [Parameter(Mandatory)] diff --git a/mac/authorize-key.sh b/mac/authorize-key.sh index ccc41d4..b059e15 100755 --- a/mac/authorize-key.sh +++ b/mac/authorize-key.sh @@ -1,4 +1,5 @@ #!/bin/bash +# SPDX-License-Identifier: GPL-3.0-only # Install an LLM-box public key behind StreamWatch's forced read-only command. set -euo pipefail diff --git a/mac/collector.py b/mac/collector.py index d700108..5b62ed1 100755 --- a/mac/collector.py +++ b/mac/collector.py @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only """StreamWatch collector for the macOS streaming appliance. Continuously records, into one SQLite database: @@ -112,6 +113,14 @@ CREATE INDEX IF NOT EXISTS prediction_events_anchor ON prediction_events(anchor_playback_id); +-- What Music itself logged about a queue item before it played. stage 'queued' is the highest eligible +-- lossless variant, logged when the item is queued; 'prebuffered' is the variant Music chose, logged when it +-- starts buffering the item (seconds before a natural track change). Scored against the item's first report. +CREATE TABLE IF NOT EXISTS queue_predictions( + id INTEGER PRIMARY KEY, ts REAL NOT NULL, lifecycle TEXT NOT NULL, stage TEXT NOT NULL, + sample_rate_hz REAL, bit_depth INTEGER); +CREATE INDEX IF NOT EXISTS queue_predictions_lc ON queue_predictions(lifecycle, ts); + CREATE TABLE IF NOT EXISTS device_state( id INTEGER PRIMARY KEY, ts REAL NOT NULL, name TEXT, sample_rate_hz REAL, transport TEXT, output_channels INTEGER, raw_json TEXT); @@ -120,25 +129,45 @@ CREATE TABLE IF NOT EXISTS collector_health(ts REAL NOT NULL, component TEXT, message TEXT); -- One row per observed track start comparing three methods for the same play: --- decoder_* RateCue's method: the fpfs report whose lifecycle started nearest the estimated playback start --- (est_start = observed time - player position), within 30 s; decoder_competing > 1 means other --- lifecycles started within 3 s of the nearest one (RateCue's ambiguity margin). +-- decoder_* RateCue's method: the fpfs report logged nearest the estimated playback start +-- (est_start = observed time - player position), from 3 s before to 8 s after it. Music logs the +-- report at the audible boundary; the lifecycle itself can start buffering minutes earlier, so its +-- start time does not place the track. A report with a rate but no depth is a lossy rendition. +-- decoder_competing > 1 means other lifecycles started within 3 s of the selected one's start. -- ls_* LosslessSwitcher's method: nearest Music 'audioCapabilities' line within 20 s. --- ratecue_* what the RateCue menu app displayed when the track ended (or now, for the current track). +-- ratecue_* the last thing the RateCue menu app displayed while this track was current: the latest snapshot +-- taken between this track's est_start and the next track's est_start. RateCue stamps a snapshot +-- to the whole second, so both ends are a second early: a snapshot within a second of a boundary +-- is nearly always the new track's first, and a later one in the same track supersedes it. +-- A track runs from its est_start to the next one's. The collector sees a track change up to a poll late, so +-- its own observation time is not the boundary: using it credits the next track's first snapshot to this one. +-- Two rows are not plays of their own: Music showing the previous track with the new position for a moment +-- (a start within 3 s of the next one, for a different track), and one play recorded twice. Tracks are told +-- apart by duration, which is not private; a track skipped within 3 s is dropped by the same rule. -- stream_* prefers the decoder report, then the best other log source. None of these is independent ground truth. -- (SQLite cannot reference the outer row in a correlated subquery's ORDER BY, hence the window functions.) DROP VIEW IF EXISTS track_formats; CREATE VIEW track_formats AS -WITH starts AS ( - SELECT p.id, p.ts, p.duration, p.position, p.track_class, - p.ts - CASE WHEN p.position BETWEEN 0 AND 86400 THEN p.position ELSE 0 END AS est_start, - min(coalesce(lead(p.ts) OVER (ORDER BY p.ts), 1e12), p.ts + coalesce(p.duration, 600) + 10) AS end_ts +WITH observed AS ( + SELECT p.id, p.ts, p.duration, p.position, p.track_class, coalesce(p.duration, -1) AS track, + p.ts - CASE WHEN p.position BETWEEN 0 AND 86400 THEN p.position ELSE 0 END AS est_start FROM playback_events p WHERE p.kind = 'track_start'), +neighbors AS ( + SELECT o.*, lead(o.est_start) OVER (ORDER BY o.ts) AS next_est, lead(o.track) OVER (ORDER BY o.ts) AS next_track, + lag(o.est_start) OVER (ORDER BY o.ts) AS prev_est, lag(o.track) OVER (ORDER BY o.ts) AS prev_track + FROM observed o), +starts AS ( + SELECT n.id, n.ts, n.duration, n.position, n.track_class, n.est_start, + min(coalesce(lead(n.est_start) OVER (ORDER BY n.ts), 1e12), + n.est_start + coalesce(n.duration, 600) + 10) AS end_ts + FROM neighbors n + WHERE NOT (n.next_est IS NOT NULL AND abs(n.next_est - n.est_start) < 3 AND n.next_track <> n.track) + AND NOT (n.prev_est IS NOT NULL AND abs(n.prev_est - n.est_start) < 3 AND n.prev_track = n.track)), dec AS ( SELECT s.id AS pid, r.lifecycle, r.sample_rate_hz, r.bit_depth, r.audio_format, r.ts AS report_ts, - r.start_ts, abs(r.start_ts - s.est_start) AS dist + r.start_ts, abs(r.ts - s.est_start) AS dist FROM starts s JOIN lifecycle_events r - ON r.kind = 'report' AND r.start_ts BETWEEN s.est_start - 30 AND s.est_start + 30), + ON r.kind = 'report' AND r.ts BETWEEN s.est_start - 3 AND s.est_start + 8), dec_rank AS ( SELECT d.*, row_number() OVER (PARTITION BY pid ORDER BY dist, report_ts DESC) AS rn, min(dist) OVER (PARTITION BY pid) AS mind FROM dec d), @@ -181,8 +210,11 @@ FROM near GROUP BY pid), joined AS ( SELECT s.*, - (SELECT r.id FROM ratecue_status r WHERE r.ts <= s.end_ts - 1 AND r.ts >= s.ts - 3600 - ORDER BY r.ts DESC LIMIT 1) AS rc_id, + (SELECT r.id FROM ratecue_status r + WHERE r.ts BETWEEN s.est_start - 1 AND s.end_ts + 10 + AND coalesce(r.snapshot_ts, r.ts) >= s.est_start - 1 + AND coalesce(r.snapshot_ts, r.ts) < s.end_ts - 1 + ORDER BY coalesce(r.snapshot_ts, r.ts) DESC, r.id DESC LIMIT 1) AS rc_id, (SELECT d.id FROM device_state d WHERE d.ts BETWEEN s.ts - 30 AND s.ts + 5 ORDER BY d.ts DESC LIMIT 1) AS dev_id @@ -214,12 +246,15 @@ rc.posterior24 AS ratecue_posterior24, rc.log_evidence_status AS ratecue_log_status, rc.depth_detection_ms AS ratecue_depth_ms, - CASE WHEN dr.bit_depth IS NULL THEN 'no_decoder' + CASE WHEN dr.pid IS NULL THEN 'no_decoder' WHEN rc.id IS NULL OR rc.publication_status = 'stale' THEN 'no_ratecue' + -- A lossy rendition has no source depth: showing one is a mismatch, showing none is right. + WHEN dr.bit_depth IS NULL THEN CASE WHEN rc.display_depth IS NULL THEN 'match' ELSE 'MISMATCH' END WHEN rc.display_depth IS NULL THEN 'ratecue_unknown' WHEN rc.display_depth = dr.bit_depth THEN 'match' ELSE 'MISMATCH' END AS ratecue_vs_decoder, - CASE WHEN dr.bit_depth IS NULL THEN 'no_decoder' + CASE WHEN dr.pid IS NULL THEN 'no_decoder' WHEN l.pid IS NULL THEN 'ls_none' + WHEN dr.bit_depth IS NULL THEN CASE WHEN l.bit_depth IS NULL THEN 'match' ELSE 'MISMATCH' END WHEN l.bit_depth IS NULL THEN 'ls_no_depth' WHEN l.bit_depth = dr.bit_depth THEN 'match' ELSE 'MISMATCH' END AS ls_vs_decoder, dv.sample_rate_hz AS device_sample_rate_hz, @@ -264,6 +299,46 @@ FROM prediction_events p LEFT JOIN track_formats tf ON tf.playback_id = p.resolved_playback_id GROUP BY metric_date, p.horizon; + +-- Music's own advance notice of a queue item's format, scored against that item's first decoder report. +-- One prediction per lifecycle and stage (the first). lead_s is how long before the report it was logged: +-- a 'prebuffered' lead under a second is a skip, where the notice and the report arrive together. +-- No track identity is involved; a hit is historical evidence, never permission to change audio hardware. +DROP VIEW IF EXISTS queue_prediction_metrics; +CREATE VIEW queue_prediction_metrics AS +WITH first_report AS ( + SELECT lifecycle, min(ts) AS ts FROM lifecycle_events WHERE kind = 'report' GROUP BY lifecycle), +actual AS ( + SELECT f.lifecycle, f.ts, max(e.sample_rate_hz) AS sample_rate_hz, max(e.bit_depth) AS bit_depth + FROM first_report f JOIN lifecycle_events e + ON e.kind = 'report' AND e.lifecycle = f.lifecycle AND e.ts = f.ts + GROUP BY f.lifecycle, f.ts), +first_prediction AS ( + SELECT lifecycle, stage, min(ts) AS ts FROM queue_predictions GROUP BY lifecycle, stage), +scored AS ( + SELECT q.ts, q.stage, q.sample_rate_hz, q.bit_depth, a.ts AS report_ts, + a.sample_rate_hz AS actual_rate_hz, a.bit_depth AS actual_bit_depth + FROM first_prediction f + JOIN queue_predictions q ON q.lifecycle = f.lifecycle AND q.stage = f.stage AND q.ts = f.ts + LEFT JOIN actual a ON a.lifecycle = q.lifecycle AND a.ts >= q.ts AND a.ts - q.ts <= 3600) +SELECT date(ts, 'unixepoch', 'localtime') AS metric_date, + stage, + count(*) AS prediction_count, + sum(CASE WHEN report_ts IS NULL THEN 1 ELSE 0 END) AS unresolved_count, + sum(CASE WHEN report_ts IS NOT NULL AND abs(actual_rate_hz - sample_rate_hz) < 0.5 + AND actual_bit_depth IS bit_depth THEN 1 ELSE 0 END) AS format_hits, + sum(CASE WHEN report_ts IS NOT NULL AND NOT (abs(actual_rate_hz - sample_rate_hz) < 0.5 + AND actual_bit_depth IS bit_depth) THEN 1 ELSE 0 END) AS format_misses, + sum(CASE WHEN report_ts IS NOT NULL AND abs(actual_rate_hz - sample_rate_hz) >= 0.5 + THEN 1 ELSE 0 END) AS rate_misses, + sum(CASE WHEN report_ts IS NOT NULL AND actual_bit_depth IS NOT bit_depth + THEN 1 ELSE 0 END) AS depth_misses, + sum(CASE WHEN report_ts IS NOT NULL AND actual_bit_depth IS NULL THEN 1 ELSE 0 END) AS played_lossy, + sum(CASE WHEN report_ts - ts < 1 THEN 1 ELSE 0 END) AS lead_under_1s, + round(avg(CASE WHEN report_ts - ts >= 1 THEN report_ts - ts END), 3) AS mean_lead_s, + round(min(CASE WHEN report_ts - ts >= 1 THEN report_ts - ts END), 3) AS min_lead_s +FROM scored +GROUP BY metric_date, stage; """ # Columns added after the first release; ALTER is skipped when they already exist. @@ -340,7 +415,9 @@ class FormatParser: ALAC_BD = re.compile(r"from\s+(\d+)-bit source") AQ_SR = re.compile(r"sampleRate:\s*([\d.]+)") LIFECYCLE = re.compile(r"<([^<>]*\|I/[A-Z0-9.]+)>") - REPORT = re.compile(r"\[SampleRate ([0-9]{5,6})\] \[BitDepth (8|16|20|24|32)\]") + REPORT = re.compile(r"\[SampleRate ([0-9]{4,6})\] \[BitDepth ([0-9]{1,2})\]") + LOSSLESS_DEPTHS = (16, 20, 24, 32) + LOSSLESS_VARIANT = re.compile(r"AudioGroup audio-alac-stereo-([0-9]{5,6})-(16|20|24|32)\]") REPORT_FORMAT = re.compile(r"\[AudioFormat (\w+)") REPORT_RENDITION = re.compile(r"\[Rendition ([^\]]+)\]") AUDIO_GROUP = re.compile(r"AudioGroup audio-([a-z0-9]+)-([a-z0-9]+)-([0-9]{5,6})(?:-(8|16|20|24|32)(?![0-9]))?") @@ -360,6 +437,9 @@ def _lifecycle(self, ts, message): del self.starts[key] kind = "render" if "ordered rendering" in message else "start" rows.append(("lifecycle_events", dict(lifecycle=lifecycle, kind=kind, raw_message=message[:1000]))) + prediction = self.queue_prediction(message, lifecycle) + if prediction: + rows.append(("queue_predictions", prediction)) report = self.REPORT.search(message) if "fpfs_ReportAudioPlaybackThroughFigLog" in message else None if report and lifecycle: start = self.starts.get(lifecycle) @@ -367,7 +447,9 @@ def _lifecycle(self, ts, message): start = None fmt = self.REPORT_FORMAT.search(message) rendition = self.REPORT_RENDITION.search(message) + # Music reports a zero depth for a lossy rendition: the rate stands, there is no source depth. rate, depth = float(report.group(1)), int(report.group(2)) + depth = depth if depth in self.LOSSLESS_DEPTHS else None rows.append(("lifecycle_events", dict( lifecycle=lifecycle, kind="report", start_ts=start, sample_rate_hz=rate, bit_depth=depth, audio_format=fmt.group(1) if fmt else None, rendition=rendition.group(1) if rendition else None, @@ -383,6 +465,23 @@ def _lifecycle(self, ts, message): codec_hint=f"{group.group(1)}-{group.group(2)}", raw_message=message[:2000]))) return rows + @classmethod + def queue_prediction(cls, message, lifecycle): + """The lossless variant Music logged for a queue item before it played, if this line carries one.""" + if not lifecycle: + return None + if "fpfsi_logHighestEligibleAlternate" in message: + stage = "queued" + elif "fpfs_StartTrackPlaying" in message and "playback switches" in message: + stage = "prebuffered" + else: + return None + variant = cls.LOSSLESS_VARIANT.search(message) + if not variant: + return None + return dict(lifecycle=lifecycle, stage=stage, + sample_rate_hz=float(variant.group(1)), bit_depth=int(variant.group(2))) + def feed(self, ts, message): rows = self._lifecycle(ts, message) events = [] @@ -597,13 +696,15 @@ def observe_start(self, playback_id, persistent_id, at): def parse_menu_title(title): - """RateCue's menu title, e.g. '≈96k / 24', '44.1k / 16', '≈96k / —', '⚠ — / —', 'RateCue'.""" + """RateCue's menu title: '96 kHz / 24-bit', '≈44.1 kHz / —', '44.1 kHz / lossy', '⚠ — / —', 'RateCue'. + + Before RateCue 0.2 it read '≈96k / 24'. Both are understood, for snapshots without explicit fields.""" rate = depth = None if title: - m = re.search(r"([\d.]+)k\b", title) + m = re.search(r"([\d.]+)\s?k(?:Hz)?\b", title) if m: rate = float(m.group(1)) * 1000.0 - m = re.search(r"/\s*(\d{1,2})\b", title) + m = re.search(r"/\s*(\d{1,2})(?:-bit)?\b", title) if m: depth = int(m.group(1)) return rate, depth @@ -618,6 +719,12 @@ def parse_iso(text): def ratecue_row(snapshot): rate, depth = parse_menu_title(snapshot.get("menuTitle")) + if snapshot.get("certaintyLevel") is not None: + # RateCue 0.2 states the displayed format as numbers; a lossy or unknown depth is null. + shown = snapshot.get("displayRateHz") + rate = float(shown) if isinstance(shown, (int, float)) else None + shown = snapshot.get("displayBitDepth") + depth = int(shown) if isinstance(shown, (int, float)) else None return dict( snapshot_ts=parse_iso(snapshot.get("snapshotAt")), pid=snapshot.get("processIdentifier"), menu_title=snapshot.get("menuTitle"), display_rate_hz=rate, display_depth=depth, @@ -649,10 +756,67 @@ def is_track_start(state, name, key, position, last_key, last_position, last_sta ) +class RestartDebounce: + """Music can show the previous track with the next track's position for a moment at a boundary. + + A restart of the same track is therefore recorded only once a second poll still shows that track, with + the time and fields of the first poll, so its estimated start is unchanged. A different track is + recorded at once.""" + + def __init__(self): + self.pending = None + + @property + def holding(self): + return self.pending is not None + + def observe(self, started, same_track, now, fields): + """Returns (ts, fields) for a track start to record now, else None.""" + if not started: + self.pending = None + return None + if not same_track: + self.pending = None + return now, fields + if self.pending is None: + self.pending = (now, fields) + return None + first, self.pending = self.pending, None + return first + + +def backfill_queue_predictions(store): + """Scores Music's advance notices already kept in raw_log, once, for a database that predates the table.""" + with store.lock: + if store.conn.execute("SELECT 1 FROM queue_predictions LIMIT 1").fetchone(): + return 0 + rows = store.conn.execute( + "SELECT ts, message FROM raw_log WHERE message LIKE '%fpfs_StartTrackPlaying%' " + "OR message LIKE '%fpfsi_logHighestEligibleAlternate%' ORDER BY ts").fetchall() + added = 0 + for ts, message in rows: + lifecycle = FormatParser.LIFECYCLE.search(message or "") + prediction = FormatParser.queue_prediction(message or "", lifecycle.group(1) if lifecycle else None) + if prediction: + store.conn.execute( + "INSERT INTO queue_predictions(ts, lifecycle, stage, sample_rate_hz, bit_depth) VALUES(?,?,?,?,?)", + (ts, prediction["lifecycle"], prediction["stage"], prediction["sample_rate_hz"], + prediction["bit_depth"])) + added += 1 + store.conn.commit() + return added + + class Collector: def __init__(self, store): self.store = store self.prediction = PredictionModel(store) + try: + added = backfill_queue_predictions(store) + if added: + store.health("prediction", f"scored {added} queue notices already in raw_log") + except sqlite3.Error as e: + store.health("prediction", e) self.stop = threading.Event() self.procs = [] @@ -718,6 +882,7 @@ def now_playing(): def nowplaying_loop(self): last_key, last_position, last_state, last_beat, last_error = None, None, None, 0.0, None + restart = RestartDebounce() while not self.stop.is_set(): try: info = self.now_playing() @@ -728,17 +893,24 @@ def nowplaying_loop(self): fields = {k: info.get(k) for k in ("name", "artist", "album", "persistent_id", "duration", "position", "track_class")} position = info.get("position") - if is_track_start( + started = is_track_start( state, info.get("name"), key, position, last_key, last_position, last_state - ): + ) + record = restart.observe(started, key == last_key, now, fields) + if record: + start_ts, start_fields = record playback_id = self.store.insert( - "playback_events", ts=now, kind="track_start", state=state, **fields + "playback_events", ts=start_ts, kind="track_start", state=state, **start_fields ) last_key, last_beat = key, now try: - self.prediction.observe_start(playback_id, info.get("persistent_id"), now) + self.prediction.observe_start(playback_id, start_fields.get("persistent_id"), start_ts) except Exception as prediction_error: self.store.health("prediction", prediction_error) + elif restart.holding: + # Keep the earlier position so the next poll can still tell a restart from a track change. + self.stop.wait(NOWPLAYING_INTERVAL) + continue elif state != last_state: self.store.insert("playback_events", ts=now, kind="state", state=state, **fields) if state in ("stopped", "not_running"): diff --git a/mac/install.sh b/mac/install.sh index f9f029c..70e2f4e 100755 --- a/mac/install.sh +++ b/mac/install.sh @@ -1,4 +1,5 @@ #!/bin/bash +# SPDX-License-Identifier: GPL-3.0-only # Installs the StreamWatch collector on the macOS appliance. # Usage: ./install.sh # collector only # ./install.sh "ssh-ed25519 AAAA... streamwatch-agent" # also authorize the LLM box's key diff --git a/mac/readonly_gate.py b/mac/readonly_gate.py index bcea34e..c0458bf 100755 --- a/mac/readonly_gate.py +++ b/mac/readonly_gate.py @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only """Forced-command SSH gate for the StreamWatch agent. The LLM box's SSH key is installed with command="... readonly_gate.py",restrict so it can only @@ -38,7 +39,7 @@ } # RateCue CLI subcommands that only return format diagnostics without preferences or device identifiers. RATECUE_READONLY = [["--version"], ["version"], ["--help"], ["menu-status"], ["log-format"], - ["first-track-trace", "export"]] + ["decoder-status"], ["first-track-trace", "export"]] LOG_TIME_FORMATS = ("%Y-%m-%d %H:%M:%S%z", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f%z", "%Y-%m-%d %H:%M:%S.%f") SENSITIVE_COLUMNS = { "name", "artist", "album", "persistent_id", "raw_json", diff --git a/tests/test_streamwatch.py b/tests/test_streamwatch.py index 03dbd2e..9a0a5f5 100644 --- a/tests/test_streamwatch.py +++ b/tests/test_streamwatch.py @@ -1,3 +1,4 @@ +# SPDX-License-Identifier: GPL-3.0-only import importlib.util import json import pathlib @@ -202,6 +203,254 @@ def test_view_counts_reportless_competing_start_and_bounds_device_age(self): store.conn.close() +class RateCueSnapshotTests(unittest.TestCase): + def test_menu_title_is_read_in_both_formats(self): + self.assertEqual(collector.parse_menu_title("96 kHz / 24-bit"), (96000.0, 24)) + self.assertEqual(collector.parse_menu_title("≈44.1 kHz / —"), (44100.0, None)) + self.assertEqual(collector.parse_menu_title("44.1 kHz / lossy"), (44100.0, None)) + self.assertEqual(collector.parse_menu_title("⚠ 176.4 kHz / 24-bit"), (176400.0, 24)) + self.assertEqual(collector.parse_menu_title("⚠ — / —"), (None, None)) + self.assertEqual(collector.parse_menu_title("RateCue"), (None, None)) + # Before RateCue 0.2. + self.assertEqual(collector.parse_menu_title("≈96k / 24"), (96000.0, 24)) + self.assertEqual(collector.parse_menu_title("44.1k / 16"), (44100.0, 16)) + self.assertEqual(collector.parse_menu_title("≈96k / —"), (96000.0, None)) + + def test_explicit_display_fields_win_over_the_title(self): + row = collector.ratecue_row({ + "menuTitle": "24-bit", "certainty": "Confirmed by Music's decoder", "certaintyLevel": "decoderConfirmed", + "displayRateHz": 96000, "displayBitDepth": 24, "displayLossy": False, "publicationStatus": "published", + }) + self.assertEqual((row["display_rate_hz"], row["display_depth"]), (96000.0, 24)) + self.assertEqual(row["certainty"], "Confirmed by Music's decoder") + lossy = collector.ratecue_row({ + "menuTitle": "44.1 kHz / lossy", "certaintyLevel": "decoderConfirmed", + "displayRateHz": 44100, "displayBitDepth": None, "displayLossy": True, + }) + self.assertEqual((lossy["display_rate_hz"], lossy["display_depth"]), (44100.0, None)) + # A snapshot from an earlier RateCue has only the title. + old = collector.ratecue_row({"menuTitle": "≈44.1k / 16", "publicationStatus": "published"}) + self.assertEqual((old["display_rate_hz"], old["display_depth"]), (44100.0, 16)) + + +class TrackBoundaryTests(unittest.TestCase): + """track_formats credits each RateCue snapshot and decoder report to the track that was playing.""" + + @staticmethod + def start(store, ts, position, duration, track="track"): + return store.insert( + "playback_events", ts=ts, kind="track_start", state="playing", name=track, artist="a", album="b", + persistent_id=track, duration=duration, position=position, track_class="track", + ) + + @staticmethod + def report(store, ts, lifecycle, depth, start_ts=None, rate=44100.0): + store.insert( + "lifecycle_events", ts=ts, lifecycle=lifecycle, kind="report", start_ts=start_ts, + sample_rate_hz=rate, bit_depth=depth, audio_format="qlac", rendition="Lossless", raw_message="report", + ) + + @staticmethod + def snapshot(store, ts, depth, status="published"): + store.insert( + "ratecue_status", ts=ts + 0.6, snapshot_ts=float(int(ts)), menu_title="title", + display_rate_hz=44100.0, display_depth=depth, publication_status=status, + ) + + @staticmethod + def rows(store): + cursor = store.conn.execute("SELECT * FROM track_formats ORDER BY started") + names = [column[0] for column in cursor.description] + return [dict(zip(names, row)) for row in cursor.fetchall()] + + def test_next_tracks_first_snapshot_is_not_credited_to_the_previous_track(self): + with tempfile.TemporaryDirectory() as temp: + store = collector.Store(str(pathlib.Path(temp) / "streamwatch.db")) + # The collector polls every 2 s, so it sees each track 2.6 s after it began. + first = self.start(store, 1002.6, 2.6, 240.0, "first") + second = self.start(store, 1242.6, 2.6, 200.0, "second") + self.report(store, 999.97, "A|I/AAA.01", 16, start_ts=980.0) + self.report(store, 1239.97, "B|I/BBB.01", 24, start_ts=1221.0) + # RateCue: unknown for a second, then the depth, for each track. + self.snapshot(store, 1000.3, None, "priorOnly") + self.snapshot(store, 1001.2, 16) + self.snapshot(store, 1240.3, None, "priorOnly") + self.snapshot(store, 1241.2, 24) + rows = {row["playback_id"]: row for row in self.rows(store)} + # The second track's first, still-unknown snapshot was taken before the collector saw that track. + self.assertEqual(rows[first]["ratecue_depth"], 16) + self.assertEqual(rows[first]["ratecue_vs_decoder"], "match") + self.assertEqual(rows[second]["ratecue_depth"], 24) + self.assertEqual(rows[second]["ratecue_vs_decoder"], "match") + # The decoder report is found by its own time, however early the lifecycle began buffering. + self.assertEqual(rows[first]["decoder_start_offset_s"], -20.0) + self.assertEqual(rows[first]["decoder_report_delay_s"], -0.03) + store.conn.close() + + def test_depth_lost_mid_track_is_what_ratecue_displayed_at_the_end(self): + with tempfile.TemporaryDirectory() as temp: + store = collector.Store(str(pathlib.Path(temp) / "streamwatch.db")) + first = self.start(store, 1000.5, 0.5, 240.0, "first") + self.start(store, 1240.5, 0.5, 200.0, "second") + self.report(store, 1000.0, "A|I/AAA.01", 16) + self.snapshot(store, 1001.2, 16) + self.snapshot(store, 1100.0, None, "priorOnly") + row = next(row for row in self.rows(store) if row["playback_id"] == first) + self.assertEqual(row["ratecue_vs_decoder"], "ratecue_unknown") + store.conn.close() + + def test_report_without_a_recorded_start_and_lossy_reports_are_scored(self): + with tempfile.TemporaryDirectory() as temp: + store = collector.Store(str(pathlib.Path(temp) / "streamwatch.db")) + lossless = self.start(store, 1000.5, 0.5, 240.0, "lossless") + lossy_shown = self.start(store, 1240.5, 0.5, 200.0, "lossy shown as 16") + lossy_blank = self.start(store, 1440.5, 0.5, 210.0, "lossy shown blank") + silent = self.start(store, 1650.5, 0.5, 180.0, "no report") + self.report(store, 1000.0, "A|I/AAA.01", 24) # the poll missed its start line + self.report(store, 1240.0, "B|I/BBB.01", None) # Music reported a zero depth + self.report(store, 1440.0, "C|I/CCC.01", None) + self.snapshot(store, 1001.0, 24) + self.snapshot(store, 1241.0, 16) + self.snapshot(store, 1441.0, None, "priorOnly") + self.snapshot(store, 1651.0, 16) + rows = {row["playback_id"]: row for row in self.rows(store)} + self.assertEqual(rows[lossless]["ratecue_vs_decoder"], "match") + self.assertEqual(rows[lossless]["decoder_bit_depth"], 24) + # A lossy rendition has no source depth: displaying one is wrong, displaying none is right. + self.assertEqual(rows[lossy_shown]["decoder_rate_hz"], 44100.0) + self.assertIsNone(rows[lossy_shown]["decoder_bit_depth"]) + self.assertEqual(rows[lossy_shown]["ratecue_vs_decoder"], "MISMATCH") + self.assertEqual(rows[lossy_blank]["ratecue_vs_decoder"], "match") + self.assertEqual(rows[silent]["ratecue_vs_decoder"], "no_decoder") + store.conn.close() + + def test_previous_track_shown_with_the_new_position_is_not_a_play_of_its_own(self): + with tempfile.TemporaryDirectory() as temp: + store = collector.Store(str(pathlib.Path(temp) / "streamwatch.db")) + first = self.start(store, 1000.5, 0.5, 278.0, "first") + # At the boundary Music showed the first track with the second track's position... + ghost = self.start(store, 1279.2, 0.7, 278.0, "first") + second = self.start(store, 1283.0, 4.5, 240.0, "second") + # ...and after a collector restart the same play was recorded again. + again = self.start(store, 1340.0, 61.5, 240.0, "second") + third = self.start(store, 1520.5, 2.0, 200.0, "third") + ids = [row["playback_id"] for row in self.rows(store)] + self.assertEqual(ids, [first, second, third]) + self.assertNotIn(ghost, ids) + self.assertNotIn(again, ids) + store.conn.close() + + def test_same_track_restart_is_recorded_only_once_a_second_poll_confirms_it(self): + fields = {"persistent_id": "first", "position": 0.7} + later = {"persistent_id": "first", "position": 2.7} + other = {"persistent_id": "second", "position": 2.9} + # Music moved on to another track: only that track is recorded. + debounce = collector.RestartDebounce() + self.assertIsNone(debounce.observe(True, True, 100.0, fields)) + self.assertTrue(debounce.holding) + self.assertEqual(debounce.observe(True, False, 102.0, other), (102.0, other)) + self.assertFalse(debounce.holding) + # The track really restarted: it is recorded with the time and position of the first poll. + debounce = collector.RestartDebounce() + self.assertIsNone(debounce.observe(True, True, 100.0, fields)) + self.assertEqual(debounce.observe(True, True, 102.0, later), (100.0, fields)) + self.assertFalse(debounce.holding) + # A different track is never held back, and a poll without a start clears a pending restart. + self.assertEqual(debounce.observe(True, False, 200.0, other), (200.0, other)) + self.assertIsNone(debounce.observe(True, True, 300.0, fields)) + self.assertIsNone(debounce.observe(False, True, 302.0, later)) + self.assertFalse(debounce.holding) + + +class QueuePredictionTests(unittest.TestCase): + """Music's own advance notice of a queue item's format, scored against the item's first report.""" + + QUEUED = ("<<<< FigStreamPlayer >>>> fpfsi_logHighestEligibleAlternate: [QE Critical][0x7ba4dfe400|P/ZA]: " + "<0x7bb5e55c00|I/DSN.01>: Highest peak bitrate Alternate\n") + START = ("<<<< FigStreamPlayer >>>> fpfs_StartTrackPlaying: [QE Critical][0x7ba4dfe400|P/ZA]: " + "<0x7bb5e55c00|I/DSN.01>: (2171): playback switches; startTime nan desiredRate is 1.000000 " + "rate 0.000000 at currentTime 0.000000 track 1 first image 0 Variant []") + REPORT = ("<<<< FigStreamPlayer >>>> fpfs_ReportAudioPlaybackThroughFigLog: [QE Critical]" + "[0x7ba4dfe400|P/ZA]: <0x7bb5e55c00|I/DSN.01>: [AudioFormat qlac is decodable] [AudioChannels 2] " + "[Rendition Lossless] [SampleRate 48000] [BitDepth 24] [Immersive rendering no]") + + def predictions(self, parser, ts, message): + return [row for table, row in parser.feed(ts, message) if table == "queue_predictions"] + + def test_parser_records_the_queued_and_the_chosen_variant(self): + parser = collector.FormatParser() + self.assertEqual(self.predictions(parser, 10.0, self.QUEUED), [dict( + lifecycle="0x7bb5e55c00|I/DSN.01", stage="queued", sample_rate_hz=192000.0, bit_depth=24)]) + self.assertEqual(self.predictions(parser, 200.0, self.START), [dict( + lifecycle="0x7bb5e55c00|I/DSN.01", stage="prebuffered", sample_rate_hz=48000.0, bit_depth=24)]) + self.assertEqual(self.predictions(parser, 218.0, self.REPORT), []) + # A lossy variant, a video item and the variant-less second start line predict nothing. + self.assertEqual(self.predictions(parser, 1.0, self.START.replace( + "audio-alac-stereo-48000-24] [alac]", "audio-stereo-256] [mp4a.40.2]")), []) + self.assertEqual(self.predictions(parser, 1.0, self.START.split(" Variant ")[0]), []) + self.assertEqual(self.predictions( + parser, 1.0, "fpfs_StartTrackPlaying: <0x7bb5e55c00|I/DSN.01> ordered rendering for track 1"), []) + + def test_parser_keeps_a_lossy_report_as_a_rate_without_a_depth(self): + parser = collector.FormatParser() + rows = parser.feed(5.0, self.REPORT.replace("[BitDepth 24]", "[BitDepth 0]")) + report = next(row for table, row in rows if table == "lifecycle_events") + self.assertEqual(report["sample_rate_hz"], 48000.0) + self.assertIsNone(report["bit_depth"]) + + def test_metrics_score_each_stage_against_the_first_report(self): + with tempfile.TemporaryDirectory() as temp: + path = str(pathlib.Path(temp) / "streamwatch.db") + store = collector.Store(path) + parser = collector.FormatParser() + # The item was queued as 192 kHz, buffered as 48 kHz and played at 48 kHz. + lines = [(1000.0, self.QUEUED), (1200.0, self.START), (1218.5, self.REPORT)] + # A skipped-to item: the notice and the report arrive together. + skipped = "<0x7bb7289c00|I/AFT.01>" + lines += [ + (1300.00, self.START.replace("<0x7bb5e55c00|I/DSN.01>", skipped)), + (1300.04, self.REPORT.replace("<0x7bb5e55c00|I/DSN.01>", skipped)), + # An item that was buffered but never played. + (1400.0, self.START.replace("<0x7bb5e55c00|I/DSN.01>", "<0x7bb9f48e00|I/SPD.01>")), + ] + for ts, message in lines: + for table, row in parser.feed(ts, message): + store.insert(table, ts=ts, **row) + store.insert("raw_log", ts=ts, subsystem="com.apple.coremedia", category="player", message=message) + cursor = store.conn.execute("SELECT * FROM queue_prediction_metrics ORDER BY stage") + names = [column[0] for column in cursor.description] + metrics = {row[1]: dict(zip(names, row)) for row in cursor.fetchall()} + self.assertEqual(metrics["queued"]["prediction_count"], 1) + self.assertEqual(metrics["queued"]["format_misses"], 1) + self.assertEqual(metrics["queued"]["rate_misses"], 1) + self.assertEqual(metrics["prebuffered"]["prediction_count"], 3) + self.assertEqual(metrics["prebuffered"]["format_hits"], 2) + self.assertEqual(metrics["prebuffered"]["format_misses"], 0) + self.assertEqual(metrics["prebuffered"]["unresolved_count"], 1) + self.assertEqual(metrics["prebuffered"]["lead_under_1s"], 1) + self.assertEqual(metrics["prebuffered"]["mean_lead_s"], 18.5) + + # A database that predates the table is scored once from the lines it already kept. + store.conn.execute("DELETE FROM queue_predictions") + store.conn.commit() + self.assertEqual(collector.backfill_queue_predictions(store), 4) + self.assertEqual(collector.backfill_queue_predictions(store), 0) + self.assertEqual(store.conn.execute( + "SELECT format_hits FROM queue_prediction_metrics WHERE stage='prebuffered'").fetchone()[0], 2) + store.conn.close() + + # The aggregate and the notices are readable through the SQL gate; they hold no track identity. + with mock.patch.object(gate, "DB_PATH", path): + result = gate.run_sql("SELECT stage, format_hits FROM queue_prediction_metrics ORDER BY stage") + self.assertTrue(result["ok"], result.get("error")) + self.assertEqual([list(row) for row in result["rows"]], [["prebuffered", 2], ["queued", 0]]) + self.assertTrue(gate.run_sql("SELECT lifecycle, stage FROM queue_predictions LIMIT 1")["ok"]) + + class GateTests(unittest.TestCase): def test_installer_replaces_existing_unrestricted_key(self): with tempfile.TemporaryDirectory() as temp: From d892bd0a5c3a2b836b4e020a782945e00417b49d Mon Sep 17 00:00:00 2001 From: troylefevre65 <126133953+troylefevre65@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:59:19 -0700 Subject: [PATCH 2/2] Prepare StreamWatch 0.2.0: license, attribution and contributor guides - License StreamWatch under GPL-3.0-only, matching RateCue. - NOTICE: copyright and warranty statement, attribution to RateCue and to LosslessSwitcher for the log patterns the collector follows, the licenses of the Python packages the agent installs, and trademarks. - Contribution guidelines, code of conduct, issue and pull request templates. - Changelog, in Keep a Changelog form. - README: introduction and badges, the corrected comparison, the queue notice metrics, a project guide, and license and credits. Co-Authored-By: Claude Fable 5.2 --- .github/ISSUE_TEMPLATE/bug_report.yml | 35 ++ .github/ISSUE_TEMPLATE/config.yml | 8 + .github/ISSUE_TEMPLATE/feature_request.yml | 25 + .github/pull_request_template.md | 14 + CHANGELOG.md | 33 + CODE_OF_CONDUCT.md | 9 + CONTRIBUTING.md | 45 ++ LICENSE | 674 +++++++++++++++++++++ NOTICE | 54 ++ README.md | 47 +- 10 files changed, 939 insertions(+), 5 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml create mode 100644 .github/pull_request_template.md create mode 100644 CHANGELOG.md create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 NOTICE diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..6adc04d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,35 @@ +name: Bug report +description: The collector, the gate or the agent does something wrong. +labels: [bug] +body: + - type: markdown + attributes: + value: | + Redact track titles, artists, albums, persistent IDs, device names, hostnames, addresses, paths and credentials. Do not attach a database, a capture or an environment file. + - type: dropdown + id: component + attributes: + label: Component + options: [Collector, Read-only gate, Research agent, Installation or provisioning, Documentation] + validations: + required: true + - type: textarea + id: what + attributes: + label: What happened, and what did you expect? + validations: + required: true + - type: textarea + id: evidence + attributes: + label: Smallest query, log excerpt or command that shows it + render: text + validations: + required: true + - type: input + id: versions + attributes: + label: macOS, StreamWatch revision and RateCue version + placeholder: macOS 15.5, StreamWatch 0.2.0 (abc1234), RateCue 0.2.0 + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..49129cc --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,8 @@ +blank_issues_enabled: false +contact_links: + - name: Report a vulnerability + url: https://github.com/troylefevre65/StreamWatch/security/policy + about: Report security problems privately, as the security policy describes. Do not open a public issue. + - name: RateCue + url: https://github.com/troylefevre65/RateCue/issues + about: Problems with the RateCue app itself, including what it displays, belong in the RateCue repository. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..0424b00 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,25 @@ +name: Feature request +description: Something StreamWatch should observe, compare or report. +labels: [enhancement] +body: + - type: textarea + id: question + attributes: + label: What question about Apple Music playback or RateCue would this answer? + validations: + required: true + - type: textarea + id: evidence + attributes: + label: What would be observed, and how could the result be checked or proven wrong? + validations: + required: true + - type: checkboxes + id: boundaries + attributes: + label: Boundaries + options: + - label: It only observes. It does not control playback, write audio hardware or change preferences. + required: true + - label: It keeps track metadata and device identity in the local database. + required: true diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..c82e194 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,14 @@ +## Purpose + + + +## Validation + +- [ ] `python3 -m unittest discover -s tests` passes +- [ ] A focused test covers a changed pattern, view, gate rule or agent tool +- [ ] Nothing the agent can read or send carries track metadata, device identity, paths or credentials +- [ ] StreamWatch still only observes: no playback control, device writes or preference changes + +## Not exercised on a live system + + diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..3fea7dd --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,33 @@ +# Changelog + +Notable changes to StreamWatch. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow [Semantic Versioning](https://semver.org/). + +## [0.2.0] - 2026-11-29 + +Works with RateCue 0.2.0 and earlier. + +### Added + +- `queue_prediction_metrics`: Music's own advance notice of a queue item's format, when it queues the item and when it starts buffering it, scored against the item's first decoder report. A database that predates the table is scored once from the log lines it already holds. +- The gate allows RateCue's read-only `decoder-status` command. +- The collector reads the displayed format from the explicit fields RateCue 0.2 publishes, and understands both the new (`96 kHz / 24-bit`) and the earlier (`96k / 24`) menu title. +- A license (GPL-3.0-only), a notice with attribution and dependency licenses, contribution guidelines, a code of conduct, issue and pull request templates, SPDX identifiers in every source file, and this changelog. + +### Changed + +- `track_formats` selects the decoder report by when it was logged, which is the audible boundary, instead of by when Music began buffering the item. +- `ratecue_*` is the last snapshot taken while the track was current. +- A decoder report with a rate and no depth is recorded as a lossy rendition. For such a play, displaying no depth is a `match` and displaying one is a `MISMATCH`. + +### Fixed + +- `track_formats` credited the next track's first RateCue snapshot to the track that had just ended, because it took the collector's late observation of a track change for the boundary. Over two days it reported 194 of 427 plays as unknown and 6 as mismatches, where RateCue had ended 139 of 399 plays without a depth and had published no wrong lossless depth. +- Two track starts recorded for one play: Music showing the previous track with the new position for a moment at a boundary, and a play recorded again after a collector restart. +- A same-track restart is recorded once a second poll confirms it, with the time of the first. + +## [0.1.0] - 2026-11-27 + +First public release: the collector, the read-only SSH gate, the research agent, the three-way comparison, and best-effort sequence prediction metrics. + +[0.2.0]: https://github.com/troylefevre65/StreamWatch/compare/df856e0...main +[0.1.0]: https://github.com/troylefevre65/StreamWatch/commits/df856e0 diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..5dfad1d --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,9 @@ +# Code of conduct + +StreamWatch welcomes listeners, developers, and hardware reviewers of every background and experience level. + +- Be respectful and assume good faith. Critique evidence and code, not people. +- Keep discussion on topic. Support claims about formats or hardware with reproducible observations. +- Do not harass, insult, or share anyone's private information. Playback databases, captures and agent environments are private; never post them. + +The maintainer may edit or remove contributions and restrict participation that violates this code. Report concerns privately to the maintainer through the contact options on the [maintainer's GitHub profile](https://github.com/troylefevre65). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..3d73a73 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,45 @@ +# Contributing to StreamWatch + +The checks need Python 3.9 or later and nothing else: no Music subscription, model server, SSH access or audio hardware. + +1. Create a topic branch: `git switch -c your-topic`. +2. Add a focused test in [`tests/test_streamwatch.py`](tests/test_streamwatch.py) when you change parsing, the comparison views, the gate, or the agent's tools. Use a captured log line as the fixture when you add or change a pattern. +3. Run the checks from the repository root: + + ```sh + python3 -m compileall -q llm-box mac tests + bash -n llm-box/provision.sh mac/install.sh mac/authorize-key.sh + python3 -m unittest discover -s tests -v + ``` + + The agent's tests stub the `openai` package when it is not installed. The [workflow](.github/workflows/check.yml) runs the same commands on every push and pull request. +4. Share the change with its purpose, the test results, and anything you could not exercise on a live system. + +## Code map + +| Path | Responsibility | +| --- | --- | +| [`mac/collector.py`](mac/collector.py) | The always-on collector: log polling, playback observation, RateCue snapshots, device state, and the comparison views. Standard library only. | +| [`mac/readonly_gate.py`](mac/readonly_gate.py) | The forced SSH command: read-only SQL with private columns denied, and an allowlist of diagnostics. | +| [`llm-box/agent.py`](llm-box/agent.py) | The research agent: observation, leads, tools, findings, and proposal drafts. | +| [`mac/install.sh`](mac/install.sh), [`llm-box/provision.sh`](llm-box/provision.sh) | Installation on the Mac and on the model host. | +| [`tests/`](tests) | Unit tests for all of the above. | + +## Boundaries that changes must keep + +Read the [charter](CHARTER.md) and the [security model](SECURITY.md) first. In short: + +- StreamWatch observes. Nothing in it may control playback, write audio hardware, or set RateCue or Music preferences. +- Track titles, artists, albums, persistent IDs, device names and raw snapshots stay in the local database. Anything the agent can read through the gate, and anything sent to a model, GitHub or a search engine, must be free of them. A new table, view or column needs a gate test. +- A log record, a RateCue snapshot and a device row each describe one thing. Do not present any of them, or a prediction, as ground truth. +- The agent drafts proposals. It does not file issues, open pull requests, or deploy code. + +## Reporting + +For a bug or a result from a live system, include the macOS version, the StreamWatch and RateCue revisions, and the smallest query or log excerpt that shows it. Redact track metadata, device identifiers, hostnames, addresses, paths and credentials. Do not commit databases, captures, proposals, logs or environment files; [`.gitignore`](.gitignore) excludes them. + +Report a vulnerability privately, as [SECURITY.md](SECURITY.md) describes. + +## License + +StreamWatch contributions use the repository's [GPL-3.0-only license](LICENSE). Submit only work you have the right to license, and keep third-party names and notices with any material you add. See [NOTICE](NOTICE) for the RateCue and LosslessSwitcher attribution and the dependency licenses. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..e77a0d6 --- /dev/null +++ b/NOTICE @@ -0,0 +1,54 @@ +StreamWatch +Copyright (C) 2026 the StreamWatch contributors + +StreamWatch is free software: you can redistribute it and/or modify it under +the terms of the GNU General Public License, version 3 only (GPL-3.0-only), as +published by the Free Software Foundation. It is distributed in the hope that +it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty +of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE for the +complete license text. + +Source: https://github.com/troylefevre65/StreamWatch + +Related work and attribution + +RateCue is the macOS menu bar app that StreamWatch observes and researches. +The collector's decoder-lifecycle patterns follow RateCue's parser. + +Project: https://github.com/troylefevre65/RateCue +License: GPL-3.0-only + +LosslessSwitcher, by Vincent Neo and the LosslessSwitcher contributors, +established the method of reading Apple Music's format from the macOS unified +log. The collector's audioCapabilities, ALAC decoder and AudioQueue patterns +follow the ones LosslessSwitcher uses (Quality/CMPlayerStuff.swift), so that +StreamWatch can compare that method with RateCue's on the same playback. + +Project: https://github.com/vincentneo/LosslessSwitcher +License: GPL-3.0 (https://github.com/vincentneo/LosslessSwitcher/blob/main/LICENSE) +Contributors: https://github.com/vincentneo/LosslessSwitcher/graphs/contributors + +StreamWatch is a separate project, not a fork or an official release of +either. It does not include LosslessSwitcher source files, binaries, or +artwork, and the credit does not attribute StreamWatch's implementation to +Vincent Neo or the LosslessSwitcher contributors. + +Third-party components + +StreamWatch bundles no third-party code. The agent installs these Python +packages, each under its own license, from llm-box/requirements.txt: + + openai Apache-2.0 https://github.com/openai/openai-python + ddgs MIT https://github.com/deedy5/ddgs + trafilatura Apache-2.0 https://github.com/adbar/trafilatura + +The collector and the read-only gate use only the Python standard library. +A model server and its model weights are chosen and installed by the operator +and are not part of StreamWatch. + +Trademarks + +Apple, Apple Music and macOS are trademarks of Apple Inc. GitHub and +DuckDuckGo are trademarks of their owners. StreamWatch is not affiliated with, +sponsored by, or endorsed by any of them, or by the LosslessSwitcher project. +Product names are used only to describe compatibility. diff --git a/README.md b/README.md index b24b713..bd23834 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,15 @@ # StreamWatch -StreamWatch is an autonomous local-LLM research agent built to improve [RateCue](https://github.com/troylefevre65/RateCue). It watches Apple Music on a dedicated appliance over long playback sessions. For every track it compares three ways of determining sample rate and bit depth, then researches each disagreement on the appliance, in the RateCue and LosslessSwitcher code, on GitHub and through DuckDuckGo. It writes up what it finds as draft RateCue issues. +

A patient listener for Apple Music: it watches every track, compares what each method says it is, and researches the disagreements.

+ +

+ checks + License: GPL-3.0-only + Python 3.9 or later + Version 0.2.0 +

+ +StreamWatch is an autonomous local-LLM research agent built to improve [RateCue](https://github.com/troylefevre65/RateCue), the macOS menu bar app that shows Apple Music's sample rate and bit depth. It watches Apple Music on a dedicated appliance over long playback sessions. For every track it compares three ways of determining sample rate and bit depth, then researches each disagreement on the appliance, in the RateCue and LosslessSwitcher code, on GitHub and through DuckDuckGo. It writes up what it finds as draft RateCue issues. See the [StreamWatch charter](CHARTER.md) for the authoritative mission, allowed authority, evidence doctrine, prohibited actions and human approval boundary. The agent's own system prompt implements the research subset of that charter; operations and security documentation describe the deployment boundaries. @@ -39,11 +48,13 @@ For each track start, the `track_formats` view on the Mac puts three answers sid | Columns | Method | Source | |---|---|---| -| `decoder_*` | **RateCue's method.** Music logs `fpfs_StartTrackPlaying` with a per-play lifecycle tag (`<0x…\|I/NDR.01>`), then `fpfs_ReportAudioPlaybackThroughFigLog … [SampleRate 96000] [BitDepth 24]` for the same lifecycle. The collector picks the lifecycle that started nearest the estimated playback start (observed time − player position, ±30 s). `decoder_competing` counts start/render lifecycles within 3 s, including ones that never produced a report. | `lifecycle_events` | +| `decoder_*` | **RateCue's method.** Music logs `fpfs_StartTrackPlaying` with a per-play lifecycle tag (`<0x…\|I/NDR.01>`) when it starts buffering an item, then `fpfs_ReportAudioPlaybackThroughFigLog … [SampleRate 96000] [BitDepth 24]` for the same lifecycle when the item starts to render. The collector picks the report logged nearest the estimated playback start (observed time − player position), from 3 s before to 8 s after it. Buffering can begin minutes before the boundary, so the lifecycle's start time (`decoder_start_offset_s`, typically −10 to −25 s on a natural track change) does not place the track. A report with a rate and no depth is a lossy rendition. `decoder_competing` counts start/render lifecycles within 3 s of the selected lifecycle's start, including ones that never produced a report. | `lifecycle_events` | | `ls_*` | **LosslessSwitcher's method.** The nearest Music `audioCapabilities` lines (`asbdSampleRate`, `sdBitDepth`) within ±20 s. | `format_events` | -| `ratecue_*` | **What RateCue displayed**, read from its `menu-status.json` snapshot at the end of the track: title, publication status, posterior, log-evidence status, detection time. | `ratecue_status` | +| `ratecue_*` | **What RateCue displayed**, read from the last `menu-status.json` snapshot taken while the track was current: title, publication status, posterior, log-evidence status, detection time. | `ratecue_status` | + +A track runs from its estimated start to the next track's. The collector notices a track change up to a poll late, so its own observation time is not the boundary: scoring by it credits the next track's first, still-unknown RateCue snapshot to the track that just ended. An earlier version of the view did that, and reported 194 of 427 plays as `ratecue_unknown` and 6 as `MISMATCH` over two days in which RateCue had never published a wrong lossless depth and had ended 139 of 399 plays without one. Two kinds of row are not plays of their own and are left out: Music showing the previous track with the new position for a moment at a boundary, and one play recorded twice. -`ratecue_vs_decoder` and `ls_vs_decoder` classify every play as `match`, `MISMATCH`, `ratecue_unknown`/`ls_no_depth`, `no_ratecue`/`ls_none` or `no_decoder`. The agent keeps a running scorecard of these classes. Each `MISMATCH`, each unknown depth that had decoder evidence, and each missing decoder report becomes a research lead. The lead names the playback, the lifecycle, the timing and the code file to examine. +`ratecue_vs_decoder` and `ls_vs_decoder` classify every play as `match`, `MISMATCH`, `ratecue_unknown`/`ls_no_depth`, `no_ratecue`/`ls_none` or `no_decoder`. For a lossy rendition, displaying no depth is a `match` and displaying one is a `MISMATCH`. The agent keeps a running scorecard of these classes. Each `MISMATCH`, each unknown depth that had decoder evidence, and each missing decoder report becomes a research lead. The lead names the playback, the lifecycle, the timing and the code file to examine. **The decoder report is Music's own statement, not independent ground truth.** The agent treats it as the reference because it is the most direct evidence available. It is not the bit depth leaving the DAC. @@ -54,6 +65,15 @@ from already-resolved tracks. When enough history exists, it predicts one and two track starts ahead and records queue sequence confidence, predicted rate and depth, the resolved outcome, and the actual format from `track_formats`. +Music also announces formats itself, and the collector scores those announcements without any track +identity. About a second into a track Music logs the highest eligible lossless variant of the next queue +item (`queued`); when it starts buffering the item, typically 11–24 seconds before a natural track change, +it logs the variant it chose (`prebuffered`). `queue_prediction_metrics` compares each with the item's first +decoder report, per day and stage: hits, misses, items that played lossy, and how long before the report +the notice was logged. Over the first two days of this deployment the chosen variant matched for all 321 +items that reported; the queued variant was wrong for 2 of 386. On a database that predates the table, the +collector scores the lines already in `raw_log` once at startup. + The deterministic engine is best-effort measurement only. Music does not expose an authoritative "Up Next" format API, so the collector cannot claim it knows a queued rendition in advance. Persistent IDs remain only in the local collector @@ -143,7 +163,7 @@ The agent's key is locked to `readonly_gate.py` (`command=...,restrict` in `auth - run read-only SQL against the collector database; SQLite authorization blocks track names, artists, albums, persistent IDs and raw JSON snapshots, including aliases; - run `log show` for the exact Music-process predicate (with `--last` up to 3 h, or `--start`/`--end` up to 3 h apart; no archives or files); - run `system_profiler SPAudioDataType -json` (with identity-bearing fields removed), `pmset -g` and `sw_vers`; -- run these RateCue CLI commands: `menu-status`, `log-format`, `--version` and `first-track-trace export`. +- run these RateCue CLI commands: `menu-status`, `log-format`, `decoder-status`, `--version` and `first-track-trace export`. It cannot get a shell, write files, inspect arbitrary preference domains, change RateCue settings, or control Music. Reinstalling with the same public key replaces any older unrestricted entry with the forced read-only command. @@ -227,3 +247,20 @@ After editing a dedicated-box service: `sudo systemctl restart streamwatch-agent Run `python3 -m unittest discover -s tests -v` after a change. The tests cover repeated-track detection, report association, competing lifecycle starts, stale device state, SQL privacy authorization, the agent-readable `track_formats` view, log/CLI allowlists, forced-key replacement, redirect checks, external-query redaction and transcript trimming. GitHub Actions runs these tests plus Python and shell syntax validation. Python dependencies are pinned in `llm-box/requirements.txt`. See [OPERATIONS.md](OPERATIONS.md) for service smoke tests, troubleshooting, upgrades and a 72-hour evidence capture, and [SECURITY.md](SECURITY.md) for trust boundaries and reporting. + +## Project guide + +- [Charter](CHARTER.md): the mission, what the collector and the agent may and may not do, and the evidence doctrine. +- [Operations](OPERATIONS.md): installation checks, smoke tests, service commands and troubleshooting. +- [Security model](SECURITY.md): trust boundaries, private data, and how to report a vulnerability. +- [Model selection](MODEL-SELECTION.md): choosing and switching an OpenAI-compatible model host. +- [Contributing](CONTRIBUTING.md) and [code of conduct](CODE_OF_CONDUCT.md): the development workflow and the boundaries a change must keep. +- [Changelog](CHANGELOG.md): what each version adds and fixes. + +## License and credits + +Copyright © 2026 the StreamWatch contributors. StreamWatch is free software, licensed under the [GNU General Public License, version 3 only](LICENSE) (`GPL-3.0-only`), and comes with no warranty. Every source file carries an SPDX identifier. + +StreamWatch observes [RateCue](https://github.com/troylefevre65/RateCue) and follows its decoder-lifecycle patterns. Its comparison with the log-reading method follows the patterns of [LosslessSwitcher](https://github.com/vincentneo/LosslessSwitcher), by **Vincent Neo and the LosslessSwitcher contributors**. See [NOTICE](NOTICE) for the full attribution and the licenses of the Python packages the agent installs. + +StreamWatch is not affiliated with or endorsed by Apple, GitHub, DuckDuckGo or the LosslessSwitcher project. Apple Music is a trademark of Apple Inc.