diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3d73a73..e5a39da 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -17,6 +17,8 @@ The checks need Python 3.9 or later and nothing else: no Music subscription, mod ## Code map +The [developer and engineer guide](DEVELOPER-ENGINEER.md) describes how these parts work and what crosses between them. + | 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. | diff --git a/DEVELOPER-ENGINEER.md b/DEVELOPER-ENGINEER.md new file mode 100644 index 0000000..1337375 --- /dev/null +++ b/DEVELOPER-ENGINEER.md @@ -0,0 +1,258 @@ +# StreamWatch for developers and engineers + +This is the technical companion to the [README](README.md). The README says what StreamWatch is and how to install it. This page says how it works: what the collector records and how often, how one play is compared three ways, exactly what can cross the SSH gate, how the agent spends a research cycle, and what is kept from leaving the machine. + +The [charter](CHARTER.md) remains the authority on what StreamWatch may do. StreamWatch observes. Nothing in it controls playback, writes audio hardware, or changes a RateCue or Music preference. + +**Contents** + +- [Architecture](#architecture) +- [The collector](#the-collector) +- [The collector database](#the-collector-database) +- [The three-way comparison](#the-three-way-comparison) +- [Next-track prediction metrics](#next-track-prediction-metrics) +- [The SSH gate](#the-ssh-gate) +- [The agent](#the-agent) +- [What is kept from leaving](#what-is-kept-from-leaving) +- [Tests and checks](#tests-and-checks) +- [Related documents](#related-documents) + +## Architecture + +StreamWatch is three programs. Two run on the Mac that plays the music, one runs wherever the model is reachable, and the only connection between the two sides is one SSH key locked to one command. + +| Program | Runs on | Started by | What it does | +| --- | --- | --- | --- | +| [`mac/collector.py`](mac/collector.py) | The Mac | The LaunchAgent `com.streamwatch.collector` | Observes Music's log, playback, the output device and RateCue's snapshot, and writes `~/streamwatch/streamwatch.db`. Standard library only. It needs no model. | +| [`mac/readonly_gate.py`](mac/readonly_gate.py) | The Mac | `sshd`, as the forced command of the agent's key | Answers one request per connection: a read-only SQL query, or one diagnostic from an allowlist. | +| [`llm-box/agent.py`](llm-box/agent.py) | The model host | The systemd unit `streamwatch-agent` | Runs the research loop against a model, and keeps its own `agent.db`, `report.md` and `proposals/`. | + +In the temporary single-Mac arrangement the agent runs on the Mac as the LaunchAgent `com.streamwatch.agent` and still reaches the collector's data through the gate, over SSH to the same machine. See [OPERATIONS.md](OPERATIONS.md#temporary-agent-on-the-mac). + +[RateCue](https://github.com/troylefevre65/RateCue) is observed, not driven. The collector reads the `menu-status.json` snapshot RateCue writes, and the gate can run a few of RateCue's read-only commands. + +## The collector + +The collector is five threads around one SQLite database. + +| Loop | Every | Reads | Writes | +| --- | --- | --- | --- | +| `log_loop` | 3 s | `log show --last 8s --style ndjson` with the predicate below | `lifecycle_events`, `format_events`, `queue_predictions`, `raw_log` | +| `nowplaying_loop` | 2 s | Music, through `osascript`: state, name, artist, album, persistent ID, duration, position and class | `playback_events`, and the private prediction tables | +| `device_loop` | 10 s | `system_profiler SPAudioDataType -json` | `device_state` | +| `ratecue_loop` | 1 s | RateCue's `~/Library/Application Support/RateCue/menu-status.json` | `ratecue_status`, one row per change | +| `prune_loop` | 6 h | Nothing | Deletes `raw_log` rows older than 30 days | + +The intervals, the lookback, the retention and the paths can be changed with `STREAMWATCH_*` environment variables; the names are at the top of the file. + +**Overlapping polls, not a stream.** Each log poll reads the last 8 seconds, and a record already seen, by timestamp and message, is skipped. That costs a few seconds of latency and avoids the sustained load of a continuous `log stream`, which suits a collector that only has to be complete. RateCue makes the opposite choice, because it has to be prompt. + +**The predicate** is wider than RateCue's, so that the methods can be compared and a change in Music's logging can be investigated afterwards: + +``` +process == "Music" AND ( + eventMessage CONTAINS "fpfs_StartTrackPlaying" OR + eventMessage CONTAINS "fpfs_ReportAudioPlaybackThroughFigLog" OR + eventMessage CONTAINS "audioCapabilities" OR + eventMessage CONTAINS "asbd" OR + eventMessage CONTAINS "sdBit" OR + eventMessage CONTAINS "ACAppleLosslessDecoder" OR + eventMessage CONTAINS "Creating AudioQueue" OR + eventMessage CONTAINS "AudioGroup audio-" OR + eventMessage CONTAINS "Rendition") +``` + +A matching message is kept in `raw_log` only when it also matches a keep-list of audio-format terms. It is cut to 4,000 characters and its title is redacted first. + +**The RateCue snapshot.** The file is read only when its modification time changes, and a file larger than 64 KiB is ignored. A row is written when anything other than the snapshot's own timestamp differs from the last row. When the file is more than five seconds old, one row with the publication status `stale` marks RateCue as not running. + +**Titles.** Music logs a track's title inside its `mediaFormatinfo` record. macOS writes `` there unless a log-privacy profile is installed. It is the only track metadata in the records StreamWatch reads, and the collector replaces it with `` before storing the line. + +## The collector database + +`~/streamwatch/streamwatch.db` is SQLite. Timestamps are Unix seconds. + +| Table | One row per | Private | +| --- | --- | --- | +| `raw_log` | Matching Music log message, kept 30 days | No | +| `lifecycle_events` | Decoder lifecycle record: `start`, `render` or `report`, with the lifecycle tag and, for a report, the rate and depth | No | +| `format_events` | Parsed format line, including the `audioCapabilities` lines LosslessSwitcher's method uses | No | +| `queue_predictions` | Notice from Music about a queue item before it played: `queued` or `prebuffered` | No | +| `playback_events` | Observed playback change | `name`, `artist`, `album`, `persistent_id` | +| `ratecue_status` | Change in what RateCue displayed | `raw_json` | +| `device_state` | Sample of the default output device | `name`, `raw_json` | +| `track_format_cache`, `track_transitions`, `prediction_events` | Private prediction state, keyed by persistent ID | The whole table | +| `collector_health` | Message from the collector about itself | No | + +| View | What it gives | +| --- | --- | +| `track_formats` | One row per play, with the three methods side by side. It is the agent's main source. | +| `prediction_metrics` | Daily aggregates of the private prediction tables. It is the only way their contents cross the gate. | +| `queue_prediction_metrics` | Per day and stage, how often Music's own notice about the next item matched its first decoder report. | + +"Private" means the SSH gate refuses to return it. The operator, reading the database on the Mac, can see everything. + +## The three-way comparison + +For each track start, the `track_formats` view on the Mac puts three answers side by side: + +| Columns | Method | Source | +|---|---|---| +| `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 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`. 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 README's [caveats](README.md#caveats) apply to every number that comes out of this view. + +## Next-track prediction metrics + +The collector also learns private local playback transitions and a format cache +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 +database. The agent receives daily aggregate `prediction_metrics`, without +playback IDs, exact times or individual queue entries. A hit is historical +evidence, never permission to change audio hardware. + +## The SSH gate + +The agent's key is installed in `authorized_keys` as `command="…readonly_gate.py",restrict`. Whatever the client asks for, `sshd` runs the gate, and `restrict` turns off forwarding and terminal allocation. Installing the same key again replaces an older, unrestricted entry for it ([`mac/authorize-key.sh`](mac/authorize-key.sh)). + +**Protocol.** The request is one base64-encoded JSON object, passed as the SSH command. The answer is one line of JSON. + +```sh +ssh -i <key> <mac-user>@<mac-host> "$(echo '{"op":"ping"}' | base64)" +ssh -i <key> <mac-user>@<mac-host> "$(echo '{"op":"sql","query":"SELECT COUNT(*) FROM track_formats"}' | base64)" +ssh -i <key> <mac-user>@<mac-host> "$(echo '{"op":"cmd","argv":["sw_vers"]}' | base64)" +``` + +**`sql`** accepts a single `SELECT` or `WITH` statement with no semicolon inside it. The database is opened read-only, with `PRAGMA query_only` on, and a SQLite authorizer refuses: + +- any read of a column named `name`, `artist`, `album`, `persistent_id`, `raw_json`, `from_persistent_id`, `to_persistent_id` or `predicted_persistent_id`. The check is on the column actually read, so an alias does not get around it; +- any read of the private tables, except through the `prediction_metrics` view; +- every write and schema action, `ATTACH` and `DETACH`; +- the functions `load_extension`, `readfile` and `writefile`. + +A query is stopped after 20 seconds and returns at most 200 rows. Titles are redacted in the result as well, because rows stored by an older collector can still hold them. + +**`cmd`** runs one of these and nothing else, with a 90-second timeout and output cut to 20,000 characters: + +| Command | Accepted form | +| --- | --- | +| `log` | `log show` only, with `--predicate 'process == "Music"'` exactly, and either `--last` of at most 3 hours or `--start` and `--end` at most 3 hours apart. No archive and no file. | +| `system_profiler` | `SPAudioDataType -json` only. Five fields of the report are returned: whether a device is the default output, its output channels, sample rate, transport and type. | +| `sw_vers` | No arguments. | +| `pmset` | `-g` forms only. | +| `ratecue` | `--version`, `version`, `--help`, `menu-status`, `log-format`, `decoder-status` and `first-track-trace export`. | + +The gate cannot give a shell, write a file, read an arbitrary preference domain, change a RateCue setting or control Music. The [security model](SECURITY.md) says what that does and does not protect against: the gate and the collector run as the same user. + +## The agent + +### How the agent runs + +1. **Sync.** It refreshes the git mirrors (at most hourly) and notes new RateCue commits. +2. **Observe.** It pulls new rows from `track_formats`, updates the scorecard, and flags `RC_MISMATCH`, `RC_UNKNOWN`, `LS_MISMATCH`, `AMBIGUOUS` (competing lifecycles), `no_format` and `resampled?` (stream rate differs from device rate). Flagged plays and new format/device combinations become leads automatically. +3. **Investigate.** It picks the highest-priority open lead. The LLM gets a brief: scorecard, new observations, existing proposals, findings so far, searches already run, recently closed leads, and the focus lead. It then works with its tools for up to `MAX_STEPS` steps, recording findings, drafting proposals and spawning follow-up leads. +4. **Close.** It marks the lead `done` or `dead_end`. A lead still open after 4 attempts is closed automatically. +5. **Exhaustion.** When no leads remain, it brainstorms new avenues. After 3 brainstorms that produce nothing new, it idles: it keeps watching for new observations and brainstorms again once a day. + +A new `agent.db` starts with 9 seed leads, written as questions to verify: +- decoder lifecycle coverage and timing on this Mac; +- the cause in RateCue's code of RateCue/decoder disagreements; +- the open questions in RateCue's `MCP-PLAN.md` (the 9.5 s report delay, the 106 s gap, the unattributed-previous-track hazard); +- LosslessSwitcher's method and its GitHub issues; +- other projects that parse these logs; +- device rate switching and resampling; +- AAC, Atmos and Hi-Res cases; +- physical device format; +- long-session anomalies. + +An existing `agent.db` keeps its leads. Delete it, or add leads by hand, to switch to the RateCue focus. + +### Inside one cycle + +- **The conversation is rebuilt every cycle** from the agent's database: the system prompt, then a brief with the scorecard, new observations, existing proposals, findings so far, searches already run, recently closed leads and the focus lead. Nothing is carried over in the model's context, which is why the agent can run for weeks. +- **Steps.** The model gets up to `MAX_STEPS` tool steps (12 by default). Then the research tools are withdrawn for two wrap-up steps, in which it can only record findings, add or update leads, add a proposal and finish. +- **Context budget.** Before each model call, a tool result longer than 2,000 characters is cut, and while the conversation is over `CONTEXT_CHAR_BUDGET` (32,000 characters by default) the oldest exchanges are dropped. +- **Stalls.** A reply with no tool call gets one reminder, and a second one ends the cycle. A reply that hits the output limit before any tool call is asked for a shorter turn. `<think>` blocks are removed from replies. +- **Bookkeeping.** Each cycle is recorded with its steps, tool calls, repeated tool calls and whether the model finished on its own. A lead still open after `MAX_LEAD_ATTEMPTS` (4) is closed as a dead end. + +### Tools + +The model has 14 tools. + +| Group | Tools | +| --- | --- | +| The Mac, through the gate | `query_playback_db`, `run_mac_command` | +| The web | `ddg_search`, `fetch_url` | +| GitHub and local git mirrors | `github_search`, `github_read`, `repo_grep`, `repo_history` | +| Its own knowledge base | `add_finding`, `search_findings`, `add_lead`, `update_lead`, `add_proposal`, `finish_cycle` | + +| Tool | What it does | Limits | +|---|---|---| +| `repo_grep` | `git grep -E` across local mirrors of `WATCH_REPOS` (default: RateCue and LosslessSwitcher) | none (local) | +| `repo_history` | `git log` filtered by message (`grep`), code change (`pickaxe`, i.e. `-S`) or path; `show` a commit | none (local) | +| `github_read` | A file or directory from any public repo (the local mirror for watched repos), or an issue/PR with its comments | 60 requests/h without a token, 5000 with one | +| `github_search` | GitHub search: `code`, `repositories`, `issues`, `commits`, with qualifiers such as `repo:` and `language:swift` | Code search **requires a token**; about 10 requests/min. The agent waits `GITHUB_MIN_INTERVAL` seconds between calls and backs off on rate limits | + +The mirrors live in `/opt/streamwatch/repos` and are refreshed hourly. When RateCue gets new commits, the agent lists them in its brief and opens a lead to check whether they change the observed behaviour. Public searches use pseudonymous `playback_id` values; track names, artists, albums, persistent IDs and device names are not exposed by the default SSH SQL view. + +### The agent's database + +`agent.db` is SQLite and belongs to the agent alone: `findings`, `leads`, `searches` and `pages` (caches of what it has already looked up), `observations` (one row per play it has pulled, with its flags), `prediction_daily_observations`, `cycles`, `proposals` and a small key-value table. `report.md` and the files in `proposals/` are written from it. + +## What is kept from leaving + +Private data is stopped at each hop, on the assumption that the hop before may be older or misconfigured. + +- **At the collector.** Titles are redacted before a log line is stored. +- **At the gate.** Track names, artists, albums, persistent IDs, device names and raw snapshots cannot be read, and titles are redacted again in every result. +- **At the agent, before the model.** Titles are redacted a third time. When the model endpoint is not local, a `log show` result is also reduced to the `com.apple.coremedia`, `com.apple.coreaudio` and `com.apple.audio` subsystems, and URL query strings in it are replaced. Music logs store, account and network activity too, and on a Mac with a log-privacy profile those lines hold account identifiers and addresses. An endpoint counts as local when it is a loopback, private, link-local or carrier-grade NAT address, `localhost`, a `.local` name or a bare host name. `LOG_SCOPE=all` or `LOG_SCOPE=playback` overrides the choice. +- **Search queries.** A DuckDuckGo or GitHub search is refused if the query contains a local file URL, a path under `/Users` or `/home`, a UUID-like identifier, an IP address or an email address. +- **Fetches.** Only public `http` and `https` URLs are fetched. The host name is resolved first, and the fetch is refused if any address is private, loopback, link-local, reserved or multicast. The connection is then made to the resolved address, so a second DNS answer cannot redirect it. No proxy is used. A redirect is not followed automatically: each hop is checked the same way, up to five. A page is limited to 3 MB. +- **Credentials.** A model key lives only in the agent's environment. With `LLM_AUTH=anthropic-login` the agent asks the Anthropic CLI for a short-lived token instead, and nothing secret is written to the environment file. + +A fetched page is evidence, not instruction: the agent's system prompt tells the model to treat it that way, and nothing a page says can widen what the gate allows. + +## Tests and checks + +The checks need Python 3.9 or later and nothing else: no Music subscription, model server, SSH access or audio hardware. + +```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 +``` + +[`tests/test_streamwatch.py`](tests/test_streamwatch.py) covers repeated-track detection, report association, competing lifecycle starts, stale device state, SQL privacy authorization, the agent-readable `track_formats` view, the log and CLI allowlists, forced-key replacement, redirect checks, external-query redaction and transcript trimming. The agent's tests stub the `openai` package when it is not installed. + +The [workflow](.github/workflows/check.yml) runs the same three commands on every push and pull request, on Ubuntu with Python 3.11, after installing the pinned dependencies in [`llm-box/requirements.txt`](llm-box/requirements.txt). + +When you change a parser pattern, use a captured log line as the fixture. A new table, view or column needs a gate test, as [CONTRIBUTING](CONTRIBUTING.md#boundaries-that-changes-must-keep) says. + +## Related documents + +- [Charter](CHARTER.md): the mission, the allowed authority and the evidence doctrine. +- [Security model](SECURITY.md): trust boundaries, same-user limits, hosted models and private data. +- [Operations](OPERATIONS.md): smoke tests, service commands, upgrades and troubleshooting. +- [Model selection](MODEL-SELECTION.md): choosing and switching an OpenAI-compatible model host. +- [Contributing](CONTRIBUTING.md): the workflow and the boundaries a change must keep. +- [RateCue for developers and engineers](https://github.com/troylefevre65/RateCue/blob/main/DEVELOPER-ENGINEER.md): the app StreamWatch observes, and how it detects and confirms a format. diff --git a/README.md b/README.md index bd23834..d45e3ac 100644 --- a/README.md +++ b/README.md @@ -44,55 +44,19 @@ For selecting and switching an OpenAI-compatible model host, use ## The three-way comparison -For each track start, the `track_formats` view on the Mac puts three answers side by side: - -| Columns | Method | Source | -|---|---|---| -| `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 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`. 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. +For every track start, StreamWatch puts three answers to "what format is this?" side by side: what Music's decoder reported, which is RateCue's method; what Music's `audioCapabilities` lines said, which is LosslessSwitcher's method; and what the RateCue menu app actually displayed. Each play is classified, and each mismatch, each unknown depth that had decoder evidence and each missing decoder report becomes a research lead. **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. -## Best-effort next-track prediction metrics +The collector also measures how well the next track's format could have been predicted, both from its own playback history and from what Music logs about a queue item before it plays. These are measurements only. A hit is historical evidence, never permission to change audio hardware. -The collector also learns private local playback transitions and a format cache -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`. +[The three-way comparison](DEVELOPER-ENGINEER.md#the-three-way-comparison) defines each column and class, and [next-track prediction metrics](DEVELOPER-ENGINEER.md#next-track-prediction-metrics) covers the prediction scoring. -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. +## What the agent does -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 -database. The agent receives daily aggregate `prediction_metrics`, without -playback IDs, exact times or individual queue entries. A hit is historical -evidence, never permission to change audio hardware. +The agent works in cycles. It refreshes its local mirrors of the RateCue and LosslessSwitcher code, pulls the new plays and flags the disagreements, picks the highest-priority open lead, and investigates it with its tools for a bounded number of steps: read-only queries on the Mac, the mirrors, GitHub and web search. It records findings and may draft a proposal. When no leads remain it brainstorms new ones, and then idles, still watching for new plays. -## GitHub and git tools - -| Tool | What it does | Limits | -|---|---|---| -| `repo_grep` | `git grep -E` across local mirrors of `WATCH_REPOS` (default: RateCue and LosslessSwitcher) | none (local) | -| `repo_history` | `git log` filtered by message (`grep`), code change (`pickaxe`, i.e. `-S`) or path; `show` a commit | none (local) | -| `github_read` | A file or directory from any public repo (the local mirror for watched repos), or an issue/PR with its comments | 60 requests/h without a token, 5000 with one | -| `github_search` | GitHub search: `code`, `repositories`, `issues`, `commits`, with qualifiers such as `repo:` and `language:swift` | Code search **requires a token**; about 10 requests/min. The agent waits `GITHUB_MIN_INTERVAL` seconds between calls and backs off on rate limits | - -The mirrors live in `/opt/streamwatch/repos` and are refreshed hourly. When RateCue gets new commits, the agent lists them in its brief and opens a lead to check whether they change the observed behaviour. Public searches use pseudonymous `playback_id` values; track names, artists, albums, persistent IDs and device names are not exposed by the default SSH SQL view. - -To enable code search, create a [fine-grained token](https://github.com/settings/personal-access-tokens) with **Public repositories (read-only)** access and no other permissions. Put it in `GITHUB_TOKEN=` in `/etc/streamwatch/agent.env` (or the equivalent agent environment in a temporary deployment). Never commit that value. +[The agent](DEVELOPER-ENGINEER.md#the-agent) has the cycle in detail, the tools and their limits, and the seed leads. ## RateCue proposals @@ -181,27 +145,6 @@ ollama ps # should show 100% GPU For a temporary remote model, use `systemctl status streamwatch-agent` and the agent log instead of `ollama ps`. A healthy endpoint alone is insufficient: verify that a request can return a tool call. -## How the agent runs - -1. **Sync.** It refreshes the git mirrors (at most hourly) and notes new RateCue commits. -2. **Observe.** It pulls new rows from `track_formats`, updates the scorecard, and flags `RC_MISMATCH`, `RC_UNKNOWN`, `LS_MISMATCH`, `AMBIGUOUS` (competing lifecycles), `no_format` and `resampled?` (stream rate differs from device rate). Flagged plays and new format/device combinations become leads automatically. -3. **Investigate.** It picks the highest-priority open lead. The LLM gets a brief: scorecard, new observations, existing proposals, findings so far, searches already run, recently closed leads, and the focus lead. It then works with its tools for up to `MAX_STEPS` steps, recording findings, drafting proposals and spawning follow-up leads. -4. **Close.** It marks the lead `done` or `dead_end`. A lead still open after 4 attempts is closed automatically. -5. **Exhaustion.** When no leads remain, it brainstorms new avenues. After 3 brainstorms that produce nothing new, it idles: it keeps watching for new observations and brainstorms again once a day. - -A new `agent.db` starts with 9 seed leads, written as questions to verify: -- decoder lifecycle coverage and timing on this Mac; -- the cause in RateCue's code of RateCue/decoder disagreements; -- the open questions in RateCue's `MCP-PLAN.md` (the 9.5 s report delay, the 106 s gap, the unattributed-previous-track hazard); -- LosslessSwitcher's method and its GitHub issues; -- other projects that parse these logs; -- device rate switching and resampling; -- AAC, Atmos and Hi-Res cases; -- physical device format; -- long-session anomalies. - -An existing `agent.db` keeps its leads. Delete it, or add leads by hand, to switch to the RateCue focus. - ## Configuration (`/etc/streamwatch/agent.env`) | Variable | Default | Notes | @@ -230,6 +173,8 @@ An existing `agent.db` keeps its leads. Delete it, or add leads by hand, to swit After editing a dedicated-box service: `sudo systemctl restart streamwatch-agent`. Confirm the effective model and host in the first log line after restart; environment files are not re-read until restart. +To enable code search, create a [fine-grained token](https://github.com/settings/personal-access-tokens) with **Public repositories (read-only)** access and no other permissions. Put it in `GITHUB_TOKEN=` in `/etc/streamwatch/agent.env` (or the equivalent agent environment in a temporary deployment). Never commit that value. + ## Caveats - **The decoder report is not ground truth.** It is what Music says it decoded. Whether the device receives it bit-perfect depends on the device's rate and Core Audio, which the `resampled?` flag and the device seed lead cover. @@ -251,6 +196,7 @@ See [OPERATIONS.md](OPERATIONS.md) for service smoke tests, troubleshooting, upg ## Project guide - [Charter](CHARTER.md): the mission, what the collector and the agent may and may not do, and the evidence doctrine. +- [For developers and engineers](DEVELOPER-ENGINEER.md): the collector's loops and database, the comparison view, the SSH gate's protocol and limits, the agent's cycle and tools, and what is kept from leaving the machine. - [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.