@astrofoundry/pi-astro 0.40.67 → 0.40.69

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/agents/media.md CHANGED
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: media
3
- description: Manages the movie and series library through the media tool (trendarr), covering weekly trending with IMDb ratings, recommendations from the library, title search, adds to Radarr and Sonarr, the SABnzbd queue pause state, and imports stuck in the Radarr and Sonarr queues. Use for what is trending, adding a movie or series by name, pausing or resuming downloads, and clearing a stuck import.
3
+ description: Manages the movie and series library through the media tool (trendarr), covering weekly trending with IMDb ratings, recommendations from the library, title search, adds to Radarr and Sonarr, the SABnzbd queue pause state, imports stuck in the Radarr and Sonarr queues, Jellyfin's "date added" after a rename, and Bazarr's health. Use for what is trending, adding a movie or series by name, pausing or resuming downloads, clearing a stuck import, repairing Jellyfin's latest-added dates, and checking the subtitle service.
4
4
  tools: read, media, subagent
5
5
  skills: media
6
6
  systemPromptMode: replace
@@ -10,7 +10,7 @@ maxSubagentDepth: 1
10
10
  model: openai-codex/gpt-6-astra
11
11
  thinking: xhigh
12
12
  ---
13
- You are the media specialist. The `media` tool, which runs the `trendarr` CLI, is your only way to reach TMDB, OMDb, Radarr, Sonarr, and SABnzbd. You have no shell, no web, and no file access; if a task needs anything else, say so and stop.
13
+ You are the media specialist. The `media` tool, which runs the `trendarr` CLI and reads Jellyfin and Bazarr directly, is your only way to reach TMDB, OMDb, Radarr, Sonarr, SABnzbd, Jellyfin, and Bazarr. You have no shell, no web, and no file access; if a task needs anything else, say so and stop.
14
14
 
15
15
  Rules:
16
16
 
@@ -21,5 +21,6 @@ Rules:
21
21
  - Pause or resume downloads only when the task asks for it, then report the returned state. Adding never implies a queue change.
22
22
  - Keep replies short: canonical title and year, and the outcome. When an add returned `sabnzbd_paused: true`, end with "Downloads are paused."; say nothing about the queue otherwise. Outside failures, name no tool or service (SABnzbd, Radarr, Sonarr, trendarr, TMDB, OMDb): say downloads, library, search.
23
23
  - Remove a queue record only with `queue-remove` after `queue` shows it and its reason, following the skill's stuck-import rules; the tool asks an owner for approval.
24
- - Library settings, quality profiles, Radarr and Sonarr configuration, and deletions other than a stuck queue record are operator tasks; say so and stop.
24
+ - Repair Jellyfin's dates only with `jellyfin date-repair` after `jellyfin date-check` shows what it would change, following the skill's rename rules; the tool asks an owner for approval.
25
+ - Library settings, quality profiles, Radarr, Sonarr, Jellyfin, and Bazarr configuration, library scans, and deletions other than a stuck queue record are operator tasks; say so and stop.
25
26
  - Delegate through `subagent` only to another specialist (`astro.arcane` for the media containers on the Arcane VM) and only for that specialist's own area.
@@ -14,6 +14,9 @@ describe("approvals", () => {
14
14
  expect(isRisky("dns", ["technitium", "node", "technitium2.dns.home.arpa", "cluster-state"])).toBe(false);
15
15
  expect(isRisky("dns", ["technitium", "join", "http://10.1.40.53:5380", "10.1.40.53"])).toBe(true);
16
16
  expect(isRisky("identity", ["zitadel", "GET", "/v2/users"])).toBe(false);
17
+ expect(isRisky("media", ["jellyfin", "date-repair"])).toBe(true);
18
+ expect(isRisky("media", ["jellyfin", "date-check"])).toBe(false);
19
+ expect(isRisky("media", ["bazarr", "status"])).toBe(false);
17
20
  expect(isRisky("identity", ["zitadel", "DELETE", "/v2/users/1"])).toBe(true);
18
21
  expect(isRisky("identity", ["dmz", "deploy-config"])).toBe(true);
19
22
  expect(isRisky("identity", ["dmz", "pomerium-upgrade", "v0.33.6"])).toBe(true);
@@ -47,8 +47,9 @@ export const RISKY: Readonly<Record<string, readonly RegExp[]>> = {
47
47
  inference: [/^(nexus-restart|nexus-start)\b/],
48
48
  // A person solves the challenge in the live view; the Approve button means it is solved.
49
49
  research: [/^captcha-help\b/],
50
- // Adds and queue pauses run on the caller's request; removing a queue record deletes its download.
51
- media: [/^queue-remove\b/],
50
+ // Adds and queue pauses run on the caller's request; removing a queue record deletes its download,
51
+ // and a date repair rewrites Jellyfin's "date added" on every item it finds late.
52
+ media: [/^queue-remove\b/, /^jellyfin\s+date-repair\b/],
52
53
  };
53
54
 
54
55
  export function isRisky(service: string, args: readonly string[]): boolean {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrofoundry/pi-astro",
3
- "version": "0.40.67",
3
+ "version": "0.40.69",
4
4
  "description": "Personal pi customizations (extensions, subagents, skills, prompts, themes) for the pi coding agent.",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -1,11 +1,11 @@
1
1
  ---
2
2
  name: media
3
- description: How the media specialist finds trending titles, resolves and adds movies and series, controls the SABnzbd queue through the media tool (trendarr), and clears imports stuck in the Radarr and Sonarr queues.
3
+ description: How the media specialist finds trending titles, resolves and adds movies and series, controls the SABnzbd queue through the media tool (trendarr), clears imports stuck in the Radarr and Sonarr queues, repairs Jellyfin's "date added" after a library rename, and reads Bazarr's health.
4
4
  ---
5
5
 
6
6
  # Media specialist
7
7
 
8
- `trendarr` is a CLI over TMDB (trending and search), OMDb (IMDb ratings), Radarr (movies), Sonarr (series), and SABnzbd (downloads). Radarr, Sonarr, and SABnzbd run in the `media` project on the Arcane VM (`10.0.40.30`). The `media` tool runs trendarr with its configuration for one call; new titles are added monitored, with the quality profile, root folder, and Sonarr monitor mode set by the operator, and a search starts at once. `["--help"]` lists the commands.
8
+ `trendarr` is a CLI over TMDB (trending and search), OMDb (IMDb ratings), Radarr (movies), Sonarr (series), and SABnzbd (downloads). Radarr, Sonarr, and SABnzbd run in the `media` project on the Arcane VM (`10.0.40.30`). The `media` tool runs trendarr with its configuration for one call; new titles are added monitored, with the quality profile, root folder, and Sonarr monitor mode set by the operator, and a search starts at once. Jellyfin (the player, `10.0.40.30:8096`) and Bazarr (subtitles) run in the same project; the tool reads them directly. `["--help"]` lists the commands.
9
9
 
10
10
  ## Commands
11
11
 
@@ -20,6 +20,10 @@ description: How the media specialist finds trending titles, resolves and adds m
20
20
  | `["sabnzbd", "status"]`, `["sabnzbd", "pause"]`, `["sabnzbd", "resume"]` | queue pause state; `pause` and `resume` act, then report the new state |
21
21
  | `["queue"]` | Radarr and Sonarr queue records that wait for a person: an import pending, blocked, or failed |
22
22
  | `["queue-remove", "radarr", "7", "--confirm"]` | remove that record and delete its download from SABnzbd, without blocklisting the release; asks an owner for approval |
23
+ | `["jellyfin", "status"]` | Jellyfin's version, library scan state, item counts, and the newest days items were added |
24
+ | `["jellyfin", "date-check"]` | movies, episodes, seasons, and series whose "date added" is more than a day after their first import; changes nothing; takes about a minute |
25
+ | `["jellyfin", "date-repair", "--confirm"]` | set those dates back; asks an owner for approval; takes a few minutes for hundreds of items |
26
+ | `["bazarr", "status"]` | Bazarr's version, the Sonarr and Radarr versions it reads, and its health issues |
23
27
 
24
28
  ## Output
25
29
 
@@ -30,12 +34,20 @@ description: How the media specialist finds trending titles, resolves and adds m
30
34
  - `sabnzbd`: `{ "sabnzbd_paused": true|false }`.
31
35
  - `queue`: `{ "records": [{ "app", "id", "title", "state", "status", "messages", "added", "size" }], "warnings": [...] }`; `state` is `importPending`, `importBlocked`, or `failedPending`, `messages` are Radarr's or Sonarr's reasons. An app that did not answer is a warning, not an empty queue.
32
36
  - `queue-remove`: `{ "status": "removed", "app", "id" }`.
37
+ - `jellyfin status`: `{ "version", "scan": { "state", "lastStart", "lastEnd", "status" }, "counts": { "movies", "series", "episodes" }, "addedByDay": { "movies": [{ "day", "items" }], "episodes": [...] } }`, the three newest days each.
38
+ - `jellyfin date-check`: `{ "changes": { "movies", "episodes", "seasons", "series" }, "examples": [{ "type", "name", "from", "to" }], "unmatched", "unmatchedExamples" }`; `examples` holds up to two per type. `unmatched` counts movies and episodes that Radarr or Sonarr has no file for, such as a leftover copy; they keep their date.
39
+ - `jellyfin date-repair`: `{ "status": "repaired" | "nothing to repair" | "stopped", "changed": { ... }, "left", "failed": [{ "name", "error" }] }`. `stopped` means five updates failed and the rest of the plan waits; report `failed` and do not repeat it at once.
40
+ - `bazarr status`: `{ "version", "sonarr_version", "radarr_version", "issues": [{ "object", "issue" }] }`. A version Bazarr reads from Sonarr or Radarr shows that it reaches that app; `issues` is Bazarr's own health list.
33
41
 
34
42
  ## Stuck imports
35
43
 
36
44
  The morning run lists each queue record older than a day under Media, with its reason and the `queue-remove` it needs; the owner's reply to that message comes to you. Run `queue` first and check that the record still exists and its reason. When the reason says the download is not an upgrade of the file already in the library (a lower custom format score, the same quality), removing it loses nothing: say so, then run `queue-remove` with `--confirm`, which asks an owner for approval. For any other reason (a wrong match, an unknown file, a missing episode), report it and ask what the owner wants before removing anything; never import by hand.
37
45
  - `warnings` carries trendarr's own warnings, such as an unreachable Radarr; mention them when they change the answer.
38
46
 
47
+ ## Date added after a rename
48
+
49
+ Jellyfin adds a renamed or moved file as a new item, so after Radarr or Sonarr renames files or folders, those titles show as added today and fill the latest-added rows. `jellyfin status` shows it: one day with hundreds of items in `addedByDay`. Run `jellyfin date-check`, report its counts and a few examples, then run `jellyfin date-repair --confirm` when the owner asked for the repair; the tool asks an owner for approval. The repair sets each movie and episode to its earliest successful import in Radarr or Sonarr (without an import record: the earliest of the file's own import date and its rename or deletion records), each season and series to its earliest episode, and an empty season to its series. It only moves a date back, never forward, and it uses Jellyfin's own item update, so Jellyfin keeps running. A movie that was upgraded more than a day after its first import also counts as late; say so when movies appear in a check after an episode rename.
50
+
39
51
  ## Resolving a title
40
52
 
41
53
  1. Search the title, with `--type` when the user said film or series.
@@ -66,5 +78,6 @@ Short and factual. Example: `Added **Dune: Part Three (2026)**. Search started.`
66
78
 
67
79
  ## When to stop and report
68
80
 
69
- - The task asks to delete, unmonitor, re-search, change quality profiles, root folders, or indexers, or to fix an import: those are Radarr, Sonarr, or SABnzbd operator tasks (the Arcane `media` project and its README).
70
- - Radarr, Sonarr, or SABnzbd is unreachable on repeated calls: report which one; container health is `astro.arcane`'s area.
81
+ - The task asks to delete, unmonitor, re-search, rename, change quality profiles, root folders, naming, or indexers, or to fix an import: those are Radarr, Sonarr, or SABnzbd operator tasks (the Arcane `media` project and its README).
82
+ - The task asks for a Jellyfin library scan, a metadata refresh, or any Jellyfin or Bazarr setting: operator tasks too. Never suggest a scan while the media share may be unavailable.
83
+ - Radarr, Sonarr, SABnzbd, Jellyfin, or Bazarr is unreachable on repeated calls: report which one; container health is `astro.arcane`'s area.
@@ -62,7 +62,7 @@ Wrappers ship as TypeScript and run under Node 24 type stripping: erasable synta
62
62
  - `arcane host <command>` runs over the forced-command key of user `spc-arcane` on VM 100. `HOST_COMMANDS` in `lib/arcane-host.ts` must list exactly the operations of `entry/remote/spc-arcane-op.py` (a test compares them); the tracked copies live in the arcane repository's `host/` (`spc-arcane-host-entry`, `spc-arcane-op`, `spc-arcane-sudoers`, `spc-arcane-install.sh`) with the probes in `host/spc-arcane-probes/`. The entry only splits words (letters, digits, space, `._:/+-`) and hands them to `sudo -n /usr/local/sbin/spc-arcane-op`, the one command its sudoers line allows; the op checks the name and every argument and runs the reviewed arcane-ops probes, which print only allowlisted fields. Manager steps (`manager-*`) are internal to `manager-upgrade`/`manager-rollback` and refused through `host`. Nothing on the host deletes data: a manager rollback restores the image and Compose file, not the data volume (R3 stays manual), `db-restore` only fills an empty database, and dumps are never pruned by the tool. `supabase-backup` writes the pre-change backup of `supabase/AGENTS.md` (both databases with `pg_dump -Fc`, each listed and fully decoded by `pg_restore`, `pg_dumpall --globals-only`, and the `supabase-db-config` volume, which must hold `pgsodium_root.key`) into `/var/backups/supabase-upgrades/<UTC>`, the folder of the earlier manual backups. `host-audit` compares the host's hashes with `host/<name>` of the `arcane-gitops` checkout after a pull. The `bigcapital-*` commands run the base-image upgrade of `bigcapital/README.md`: an online backup, a rehearsal on an internal Docker network (restore into the current MariaDB, upgrade with the build's, migrations, server health, Envoy validation; everything it created removed afterwards), the owner-approved switch (stop, quiescent dump, Redis `SAVE`, volume copies compared entry by entry, the stack left stopped for the GitOps commit, the old volumes untouched), and a verify against the switch's row counts and ledger totals.
63
63
  - `arcane manager-upgrade <version>` (`lib/arcane-manager.ts`) follows arcane/AGENTS.md "Manager upgrades": the official image's revision label must equal the release tag's commit (GitHub API), `manager-prepare` records `compose.before.yaml` and every container before the pin commit, the pin goes through the `arcane-gitops` checkout (`git` is exported from `lib/repo.ts` for this), the wait polls `gitops list` and the deployed Compose hash every 30 s for up to 30 minutes, then pull, cold backup, `up -d --no-deps --pull never`, and checks. Any failure before the restart reverts the pin (`stopped`); a failed check after it reverts the pin and runs `manager-rollback` (`rolled back`). The answer always exits 0 with `status`, so the bridge and the agent both see it.
64
64
  - `research` is a pure forced-command wrapper: every call is one JSON request on stdin to `request` on VM 110 (`10.1.100.10`, user `spc-research`, key `SSH_KEY_SANDBOX`), whose entry hands it to `spc-research-op` as `researcher` (tracked in the homelab repository's `06-space-x-proxmox/research/system/`). The op attaches one playwright-cli session per Discord thread (`t<id>`) to the shared Chrome over CDP on `127.0.0.1:9222` and opens its own tab; cookie, storage, `run-code`, and browser lifecycle commands are refused. `script` runs the agent's code in the thread folder as `researcher` (5 minutes), on a VM that reaches only the internet (Mira's Sandbox zone plus the VM's own nftables). Defaults stay on Cortex in `work/research/defaults.json`, out of the sandbox's reach. `captcha-help` is in `RISKY`, so its owner approval is the moment the owner solved the challenge in the live view (`research-browser.37pla.net`); the bridge renders that ticket with the channel's `liveView` link.
65
- - `media` runs trendarr unchanged: `trendarrCli` in `media.json` is its `dist/cli.js`, started with `process.execPath` because sudo's PATH has no node. Each call gets `HOME` set to a fresh `0700` directory under `~/.specialists/work/media/` that holds only `.trendarr/config.json` (`0600`, trendarr's own schema, built from the note fields and `media.json`) and is removed in `finally`; trendarr reads no environment variables and has no config flag, and Node's `os.homedir()` follows `$HOME` on POSIX. Every call passes `--json`; `init` is refused. An add prints trendarr's per-ID `results` and exits 0 even when trendarr exits 1 for a failed ID, because the gate shows only stderr on failure; other failures carry trendarr's stderr without its `warning:` lines, which go into the JSON as `warnings`. The bridge's slash commands and Add buttons call the same wrapper through the entry point (`extensions/astro-discord/media.ts`). `queue` and `queue-remove` (since 0.40.66) skip trendarr, which has no queue records: the wrapper calls `/api/v3/queue` of Radarr and Sonarr itself with the note's keys in the `X-Api-Key` header and prints only `stuckRecords` fields (no paths or download ids); `queue-remove` sends `DELETE /api/v3/queue/<id>?removeFromClient=true&blocklist=false`, needs `--confirm`, and is in `RISKY`.
65
+ - `media` runs trendarr unchanged: `trendarrCli` in `media.json` is its `dist/cli.js`, started with `process.execPath` because sudo's PATH has no node. Each call gets `HOME` set to a fresh `0700` directory under `~/.specialists/work/media/` that holds only `.trendarr/config.json` (`0600`, trendarr's own schema, built from the note fields and `media.json`) and is removed in `finally`; trendarr reads no environment variables and has no config flag, and Node's `os.homedir()` follows `$HOME` on POSIX. Every call passes `--json`; `init` is refused. An add prints trendarr's per-ID `results` and exits 0 even when trendarr exits 1 for a failed ID, because the gate shows only stderr on failure; other failures carry trendarr's stderr without its `warning:` lines, which go into the JSON as `warnings`. The bridge's slash commands and Add buttons call the same wrapper through the entry point (`extensions/astro-discord/media.ts`). `queue` and `queue-remove` (since 0.40.66) skip trendarr, which has no queue records: the wrapper calls `/api/v3/queue` of Radarr and Sonarr itself with the note's keys in the `X-Api-Key` header and prints only `stuckRecords` fields (no paths or download ids); `queue-remove` sends `DELETE /api/v3/queue/<id>?removeFromClient=true&blocklist=false`, needs `--confirm`, and is in `RISKY`. The `jellyfin` commands (since 0.40.68, pure parts in `lib/media-dates.ts`) exist because Jellyfin adds a renamed or moved file as a new item: the library rename of 2026-11-10 turned 873 of 875 episodes into "added today". `date-check` reads every movie, episode, season, and series from `/Items` (one request per type without a limit, because pages of an unsorted list can overlap), Radarr's and Sonarr's files, and each app's whole history from `/api/v3/history/since`; files match by their last path segments (`pathKey`: two for a movie, three for an episode), so the mount points may differ. `planDates` follows the arcane repository's `media/AGENTS.md`: a movie or episode gets its earliest successful import (`firstArrival`; without an import record the earliest of the file's own import date and its rename and deletion records, since a file a disk scan found has none), a season and a series their earliest episode, an empty season its series; only a date more than a day late changes, so a date only ever moves back, and an item Radarr or Sonarr has no file for is reported as unmatched and left alone. `date-repair --confirm` applies the plan through Jellyfin's own `POST /Items/<id>`, the call behind its metadata editor: the item as `GET /Items/<id>?userId=<an administrator>` returns it (without a user id an API key gets 400) with only `DateCreated` changed and `People` left out, because Jellyfin rewrites people only when the request carries them; a test on one episode showed only `DateCreated` and `Etag` differing afterwards. Jellyfin keeps running, and five failed updates stop the run. The API key travels as `Authorization: MediaBrowser Token="<key>"`, the scheme of the server's own `/api-docs/openapi.json` (12.4.0). `bazarr status` reads `/api/system/status` and `/api/system/health` with `X-API-KEY` and prints versions and issues only; the Sonarr and Radarr versions Bazarr reports show that it reaches them. Both read their own config shape (`jellyfinUrl`, `bazarrUrl`), so the trendarr commands run without those keys.
66
66
  - `arcane release-notes <stack>[/<service>]` is `lib/releases.ts`: a single-image check and `resolveRef` give the running and latest versions, `HttpRegistry.labels` reads `org.opencontainers.image.source` from the latest image (index to linux/amd64 manifest to config blob), and the anonymous GitHub releases API (60 requests an hour, up to 3 pages of 100) gives the releases in between, oldest first. `condenseNotes` keeps each release under 12,000 characters by section priority; `capTotal` drops the oldest releases past 40,000 characters in total.
67
67
 
68
68
  ## Gate
@@ -13,7 +13,7 @@ A specialist is a Pi subagent that is the only way to operate one area of the ho
13
13
  | `astro.backup` | vzdump, the shared Restic repository (Pulsar host config, Arcane app backups), GCS offsite from LXC 102 | Status, journals, and manual runs of every layer; `restic-snapshots|stats|ls`, `restic-restore` into `/var/tmp/spc-restore` on Pulsar, `restore-clean` |
14
14
  | `astro.proxmox` | Proxmox VE on Pulsar (37) and SPACE-X (Mira) | API token: `guests`, `guest`, `get <path>`, `tasks`; `start`, `shutdown|reboot|stop --confirm`; snapshots create, delete, rollback; `set` of CPU, memory, options, network. Host key: `host-status`, `host-journal`, `updates`, `host-upgrade` (apt full-upgrade; a new Proxmox VE major is held), `host-reboot --confirm`, `guest-exec <vmid> <status|journal|df|updates>`, `nightly-journal <days>`; `nightly [days]` combines the vzdump tasks with that journal into a table of nightly run times. Every command runs on Pulsar, or on SPACE-X with the `space-x` prefix |
15
15
  | `astro.inference` | MLX embedding and reranking servers on Nexus, Europa health | `nexus-status|start|stop|restart|log|disk`, `macos-updates`; `europa-health` |
16
- | `astro.media` | trendarr over TMDB, OMDb, and the `media` project on VM 100 (Radarr, Sonarr, SABnzbd) | `trending`, `search`, `recommend`, `add-movies`, `add-series` (at most 20 IMDb IDs), `sabnzbd status|pause|resume`, `queue`, `queue-remove <radarr|sonarr> <id> --confirm`; trendarr's JSON plus its warnings, the queue commands straight from Radarr and Sonarr |
16
+ | `astro.media` | trendarr over TMDB, OMDb, and the `media` project on VM 100 (Radarr, Sonarr, SABnzbd, Jellyfin, Bazarr) | `trending`, `search`, `recommend`, `add-movies`, `add-series` (at most 20 IMDb IDs), `sabnzbd status|pause|resume`, `queue`, `queue-remove <radarr|sonarr> <id> --confirm`, `jellyfin status|date-check`, `jellyfin date-repair --confirm`, `bazarr status`; trendarr's JSON plus its warnings, the queue, Jellyfin, and Bazarr commands straight from those apps |
17
17
  | `astro.research` | the research sandbox, VM 110 at Mira (Chrome on a virtual screen, scripts, thread folders), through the forced-command key of user `spc-research`; defaults in `~/.specialists/work/research/defaults.json` | `browser <session> <playwright-cli args>`, `captcha`, `captcha-help` (owner approval: solved in the live view), `script`, `read`, `files`, `toolbox`, `defaults list|set|unset`; the sandbox's JSON |
18
18
 
19
19
  Call one with `/run astro.<name> -- <task>` or through the `subagent` tool (both from the bundled `astro-subagents` extension). `/run` saves the specialist's session under `~/.pi/agent/subagent-sessions/<agent>/`; `/run astro.<name> --continue -- <task>` resumes the last one started from the same directory, so the specialist keeps what it saw. Sessions older than 7 days are deleted. Specialists may call each other once (`maxSubagentDepth: 1`). They run on `openai-codex/gpt-6-astra` with `xhigh` thinking, set by `model` and `thinking` in each `agents/<name>.md`; an agent without these fields inherits the caller's model and thinking. Each tool takes `args`, an array of strings; `["--help"]` lists the subcommands.
@@ -43,7 +43,7 @@ Host: Cortex (macOS on Apple silicon; Homebrew git; the specialists' Node, trend
43
43
  - `backup`: `SSH_KEY_PULSAR_B64`, `SSH_KEY_ARCANE_B64`.
44
44
  - `proxmox`: `PVE_TOKEN_ID` (plain, `spc-proxmox@pve!cortex`), `PVE_TOKEN_SECRET`, `PVE_SPACEX_TOKEN_ID` and `PVE_SPACEX_TOKEN_SECRET` (the same user on SPACE-X), `SSH_KEY_PULSAR_B64` (trusted by Pulsar and SPACE-X). `proxmox.json` also needs `spacexApiUrl`, `spacexCertSha256`, `spacexNode`, `spacexHost`, `spacexUser`, and `known_hosts` the SPACE-X host key.
45
45
  - `inference`: `SSH_KEY_NEXUS_B64`.
46
- - `media`: `TMDB_ACCESS_TOKEN` (TMDB API Read Access Token), `OMDB_API_KEY`, `RADARR_API_KEY`, `SONARR_API_KEY` (Settings, General, Security; each app has one), `SABNZBD_API_KEY` (the API key, not the NZB key, which can only add NZBs and cannot read or pause the queue).
46
+ - `media`: `TMDB_ACCESS_TOKEN` (TMDB API Read Access Token), `OMDB_API_KEY`, `RADARR_API_KEY`, `SONARR_API_KEY` (Settings, General, Security; each app has one), `SABNZBD_API_KEY` (the API key, not the NZB key, which can only add NZBs and cannot read or pause the queue), `JELLYFIN_API_KEY` (Jellyfin's Dashboard, API Keys, New API Key; only the `jellyfin` commands read it), `BAZARR_API_KEY` (Bazarr's Settings, General, Security, API Key; only `bazarr status` reads it).
47
47
  2. **Identities.** Zitadel (`https://auth.37pla.net/ui/console`): service user `spc-arcane` with Access Token Type JWT and a JSON key; service user `spc-identity` with a Personal Access Token and the Instance Owner role. Technitium (cluster primary): user `spc-dns` in the Administrators group with an API token; the cluster syncs the user to every node. Cloudflare: an account-owned API token with `Zone:Read` and `DNS:Edit` on both zones. GCP project `frontdoor-1337`: service account `spc-edge` with `roles/iap.tunnelResourceAccessor` and `roles/compute.viewer`, JSON key. Proxmox (`ssh pulsar`): user `spc-proxmox@pve`, role `SpecialistGuest` = `VM.Audit VM.PowerMgmt VM.Snapshot VM.Snapshot.Rollback VM.Config.CPU VM.Config.Memory VM.Config.Options VM.Config.Network VM.Config.CDROM VM.GuestAgent.Audit`, ACLs `PVEAuditor` on `/` and `SpecialistGuest` on `/vms` for both the user and the token `spc-proxmox@pve!cortex` (`-privsep 1`).
48
48
  3. **Services.** Arcane (Settings, Authentication, Federated Credentials): Issuer `https://auth.37pla.net`, Audience `387825541182390275`, Subject exact = `spc-arcane` user ID, Role Admin, Global, lifetime 300. UniFi: the account key and a local key per console (fields above) and policies on 37 allowing Cortex `10.0.40.37` to TCP 22 on `10.0.20.10`, `10.0.10.37`, `10.0.90.10`, TCP 5380 on `10.0.40.53`, TCP 8006 on `10.0.10.37`, TCP 8081 on `10.0.60.5`, TCP 443 on the Mira console `10.1.60.1`, and TCP 22 and 8006 on SPACE-X `10.1.10.37` (that one also on Mira); the homelab `03-cortex-macmini/README.md` lists them with their ids. GitHub: `spc-arcane-gitops` as a write deploy key on `astronaute77/arcane`, `spc-edge-homelab` and `spc-identity-homelab` as write deploy keys on `astronaute77/homelab`.
49
49
  4. **Sudo and user**, as an administrator:
@@ -87,9 +87,10 @@ Host: Cortex (macOS on Apple silicon; Homebrew git; the specialists' Node, trend
87
87
  { "trendarrCli": "/Users/specialist/.specialists/bin/trendarr/node_modules/@astrofoundry/trendarr/dist/cli.js",
88
88
  "radarrUrl": "http://10.0.40.30:7878", "radarrQualityProfileId": 7, "radarrRootFolderPath": "/media/movies",
89
89
  "sonarrUrl": "http://10.0.40.30:8989", "sonarrQualityProfileId": 7, "sonarrRootFolderPath": "/media/tv", "sonarrMonitor": "all",
90
- "sabnzbdUrl": "http://10.0.40.30:8084", "maxEntries": 10 }
90
+ "sabnzbdUrl": "http://10.0.40.30:8084", "maxEntries": 10,
91
+ "jellyfinUrl": "http://10.0.40.30:8096", "bazarrUrl": "http://10.0.40.30:6767" }
91
92
  ```
92
- The `media` wrapper writes trendarr's `~/.trendarr/config.json` for each call into a private temporary HOME under `~/.specialists/work/media/` and removes it afterwards, so trendarr itself is never configured with `trendarr init`. Cortex reaches the three ports on `10.0.40.30` within its own VLAN.
93
+ The `media` wrapper writes trendarr's `~/.trendarr/config.json` for each call into a private temporary HOME under `~/.specialists/work/media/` and removes it afterwards, so trendarr itself is never configured with `trendarr init`. Cortex reaches the ports on `10.0.40.30` within its own VLAN. `jellyfinUrl` is read only by the `jellyfin` commands and `bazarrUrl` only by `bazarr status`, so the other commands work without them.
93
94
  `sudo /usr/local/sbin/specialist-install trendarr <version>` installs trendarr behind the link `~/.specialists/bin/trendarr`, so that path stays valid across updates. Then `sudo -n -u specialist -H /usr/local/bin/specialist-cli provision`; it lists every note and field.
94
95
 
95
96
  Later updates go through the installer, one component at a time, each checked before and after the switch:
@@ -0,0 +1,114 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { addedByDay, arrivals, changeCounts, exampleChanges, firstArrival, keyDepth, libraryItem, pathKey, planDates } from "./media-dates.ts";
3
+ import type { LibraryItem } from "./media-dates.ts";
4
+
5
+ const ms = (iso: string) => Date.parse(iso);
6
+
7
+ function item(partial: Partial<LibraryItem> & Pick<LibraryItem, "id" | "type">): LibraryItem {
8
+ return { name: partial.id, path: null, added: null, seasonId: null, seriesId: null, ...partial };
9
+ }
10
+
11
+ describe("media dates", () => {
12
+ it("keys a path by its last segments, whatever the mount point", () => {
13
+ expect(pathKey("/media/tv/Show (2020) [imdbid-tt1]/Season 01/a.mkv", keyDepth("Episode"))).toBe("Show (2020) [imdbid-tt1]/Season 01/a.mkv");
14
+ expect(pathKey("/data/movies/Film (1999)/Film.mkv", keyDepth("Movie"))).toBe("Film (1999)/Film.mkv");
15
+ expect(pathKey("/media/tv/Show/", 1)).toBe("Show");
16
+ });
17
+
18
+ it("takes the earliest import, and without one the earliest sign of the file", () => {
19
+ const records = [
20
+ { owner: 1, eventType: "grabbed", date: "2026-01-01T00:00:00Z" },
21
+ { owner: 1, eventType: "episodeFileRenamed", date: "2026-02-01T00:00:00Z" },
22
+ { owner: 1, eventType: "downloadFolderImported", date: "2026-04-01T00:00:00Z" },
23
+ { owner: 1, eventType: "downloadFolderImported", date: "2026-03-01T00:00:00Z" },
24
+ ];
25
+ expect(firstArrival("2026-05-01T00:00:00Z", records)).toBe(ms("2026-03-01T00:00:00Z"));
26
+ expect(firstArrival("2026-05-01T00:00:00Z", records.slice(0, 2))).toBe(ms("2026-02-01T00:00:00Z"));
27
+ expect(firstArrival("2026-01-15T00:00:00Z", records.slice(0, 2))).toBe(ms("2026-01-15T00:00:00Z"));
28
+ expect(firstArrival("2026-05-01T00:00:00Z", records.slice(0, 1))).toBe(ms("2026-05-01T00:00:00Z"));
29
+ expect(firstArrival(null, [])).toBeNull();
30
+ });
31
+
32
+ it("maps each file to its first arrival through its owners' history", () => {
33
+ const map = arrivals(
34
+ [
35
+ { path: "/media/tv/Show/Season 01/a.mkv", added: "2026-06-01T00:00:00Z", owners: [10, 11] },
36
+ { path: "/media/tv/Show/Season 01/b.mkv", added: null, owners: [12] },
37
+ ],
38
+ [
39
+ { owner: 11, eventType: "downloadFolderImported", date: "2026-02-01T00:00:00Z" },
40
+ { owner: 99, eventType: "downloadFolderImported", date: "2020-01-01T00:00:00Z" },
41
+ ],
42
+ 3,
43
+ );
44
+ expect([...map.entries()]).toEqual([["Show/Season 01/a.mkv", ms("2026-02-01T00:00:00Z")]]);
45
+ });
46
+
47
+ it("reads a Jellyfin row and names episodes and seasons by their series", () => {
48
+ expect(libraryItem({ Id: "e1", Type: "Episode", Name: "Pilot", SeriesName: "Show", ParentIndexNumber: 2, IndexNumber: 3, Path: "/m/a.mkv", DateCreated: "2026-11-10T10:41:12.1545518Z", SeasonId: "s1", SeriesId: "x1" })).toEqual({
49
+ id: "e1",
50
+ type: "Episode",
51
+ name: "Show S02E03",
52
+ path: "/m/a.mkv",
53
+ added: ms("2026-11-10T10:41:12.154Z"),
54
+ seasonId: "s1",
55
+ seriesId: "x1",
56
+ });
57
+ expect(libraryItem({ Id: "s1", Type: "Season", Name: "Season 2", SeriesName: "Show" })?.name).toBe("Show, Season 2");
58
+ expect(libraryItem({ Id: "a1", Type: "Audio", Name: "Song" })).toBeNull();
59
+ expect(libraryItem({ Type: "Movie" })).toBeNull();
60
+ });
61
+
62
+ it("moves a date back only when it is more than a day late, and lets seasons and series follow", () => {
63
+ const episodes = new Map([
64
+ ["Show/Season 01/a.mkv", ms("2026-07-01T00:00:00Z")],
65
+ ["Show/Season 01/b.mkv", ms("2026-08-01T00:00:00Z")],
66
+ ]);
67
+ const movies = new Map([
68
+ ["Film/Film.mkv", ms("2026-09-01T00:00:00Z")],
69
+ ["Early/Early.mkv", ms("2026-09-01T00:00:00Z")],
70
+ ]);
71
+ const renamed = ms("2026-11-10T10:00:00Z");
72
+ const plan = planDates(
73
+ [
74
+ item({ id: "show", type: "Series", added: renamed }),
75
+ item({ id: "s1", type: "Season", added: renamed, seriesId: "show" }),
76
+ item({ id: "s2", type: "Season", added: renamed, seriesId: "show" }),
77
+ item({ id: "a", type: "Episode", path: "/media/tv/Show/Season 01/a.mkv", added: renamed, seasonId: "s1", seriesId: "show" }),
78
+ item({ id: "b", type: "Episode", path: "/media/tv/Show/Season 01/b.mkv", added: ms("2026-08-01T10:00:00Z"), seasonId: "s1", seriesId: "show" }),
79
+ item({ id: "c", type: "Episode", path: "/media/tv/Show/Season 01/untracked.mkv", added: renamed, seasonId: "s1", seriesId: "show" }),
80
+ item({ id: "film", type: "Movie", path: "/media/movies/Film/Film.mkv", added: null }),
81
+ item({ id: "early", type: "Movie", path: "/media/movies/Early/Early.mkv", added: ms("2026-01-01T00:00:00Z") }),
82
+ item({ id: "other", type: "Series", added: renamed }),
83
+ ],
84
+ { movies, episodes },
85
+ );
86
+ expect(plan.changes.map((c) => [c.id, c.to])).toEqual([
87
+ ["a", "2026-07-01T00:00:00.000Z"],
88
+ ["film", "2026-09-01T00:00:00.000Z"],
89
+ ["show", "2026-07-01T00:00:00.000Z"],
90
+ ["s1", "2026-07-01T00:00:00.000Z"],
91
+ ["s2", "2026-07-01T00:00:00.000Z"],
92
+ ]);
93
+ expect(plan.changes[0].from).toBe("2026-11-10T10:00:00.000Z");
94
+ expect(plan.changes[1].from).toBeNull();
95
+ expect(plan.unmatched).toEqual([{ type: "Episode", name: "c" }]);
96
+ expect(changeCounts(plan.changes)).toEqual({ movies: 1, episodes: 1, seasons: 2, series: 1 });
97
+ expect(exampleChanges(plan.changes, 1).map((c) => c.id)).toEqual(["film", "a", "s1", "show"]);
98
+ });
99
+
100
+ it("counts the newest days items were added", () => {
101
+ const items = [
102
+ item({ id: "1", type: "Episode", added: ms("2026-11-10T10:00:00Z") }),
103
+ item({ id: "2", type: "Episode", added: ms("2026-11-10T23:00:00Z") }),
104
+ item({ id: "3", type: "Episode", added: ms("2026-07-24T00:00:00Z") }),
105
+ item({ id: "4", type: "Episode", added: ms("2026-01-01T00:00:00Z") }),
106
+ item({ id: "5", type: "Movie", added: ms("2026-11-10T10:00:00Z") }),
107
+ item({ id: "6", type: "Episode" }),
108
+ ];
109
+ expect(addedByDay(items, "Episode", 2)).toEqual([
110
+ { day: "2026-11-10", items: 2 },
111
+ { day: "2026-07-24", items: 1 },
112
+ ]);
113
+ });
114
+ });
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Jellyfin's "date added" against Radarr's and Sonarr's own records. Jellyfin adds a renamed or moved file
3
+ * as a new item, so a library rename turns every file into "added today" (873 episodes on 2026-11-10).
4
+ * The plan follows the rules of the arcane repository's `media/AGENTS.md`: the earliest successful import,
5
+ * the earliest episode for a season, and never a file time.
6
+ */
7
+
8
+ const DAY_MS = 86_400_000;
9
+
10
+ /** History events that record a successful import. */
11
+ const IMPORT_EVENTS = ["downloadFolderImported", "seriesFolderImported", "movieFolderImported"];
12
+ /** Events that prove a file was in the library at that time; a file a disk scan found has no import record. */
13
+ const LIBRARY_EVENTS = [...IMPORT_EVENTS, "episodeFileRenamed", "episodeFileDeleted", "movieFileRenamed", "movieFileDeleted"];
14
+
15
+ export const ITEM_TYPES = ["Movie", "Episode", "Season", "Series"] as const;
16
+ export type ItemType = (typeof ITEM_TYPES)[number];
17
+
18
+ /** One Radarr or Sonarr history record; `owner` is the movie id or the episode id. */
19
+ export interface HistoryRecord {
20
+ owner: number;
21
+ eventType: string;
22
+ date: string;
23
+ }
24
+
25
+ /** One library file in Radarr or Sonarr; `owners` are the movie id or the ids of the file's episodes. */
26
+ export interface ArrFile {
27
+ path: string;
28
+ added: string | null;
29
+ owners: number[];
30
+ }
31
+
32
+ /** One Jellyfin item; `added` is its "date added" in milliseconds. */
33
+ export interface LibraryItem {
34
+ id: string;
35
+ type: ItemType;
36
+ name: string;
37
+ path: string | null;
38
+ added: number | null;
39
+ seasonId: string | null;
40
+ seriesId: string | null;
41
+ }
42
+
43
+ export interface DateChange {
44
+ id: string;
45
+ type: ItemType;
46
+ name: string;
47
+ from: string | null;
48
+ to: string;
49
+ }
50
+
51
+ export interface DatePlan {
52
+ changes: DateChange[];
53
+ /** Movies and episodes Radarr or Sonarr has no file for; they keep their date. */
54
+ unmatched: { type: ItemType; name: string }[];
55
+ }
56
+
57
+ /** The last `depth` segments of a path: what Jellyfin and the Arr apps share whatever their mount point. */
58
+ export function pathKey(path: string, depth: number): string {
59
+ return path
60
+ .split("/")
61
+ .filter((segment) => segment.length > 0)
62
+ .slice(-depth)
63
+ .join("/");
64
+ }
65
+
66
+ /** Path segments that identify a file: `<movie folder>/<file>` or `<series folder>/<season folder>/<file>`. */
67
+ export function keyDepth(type: "Movie" | "Episode"): number {
68
+ return type === "Movie" ? 2 : 3;
69
+ }
70
+
71
+ function times(values: (string | null)[]): number[] {
72
+ return values.map((value) => (value === null ? Number.NaN : Date.parse(value))).filter((ms) => !Number.isNaN(ms));
73
+ }
74
+
75
+ /**
76
+ * When a library file first arrived: its earliest successful import; without one, the earliest of the
77
+ * file's own import date and its rename and deletion records.
78
+ */
79
+ export function firstArrival(fileAdded: string | null, records: HistoryRecord[]): number | null {
80
+ const dated = (events: string[]) => times(records.filter((r) => events.includes(r.eventType)).map((r) => r.date));
81
+ const imports = dated(IMPORT_EVENTS);
82
+ if (imports.length > 0) return Math.min(...imports);
83
+ const others = [...dated(LIBRARY_EVENTS), ...times([fileAdded])];
84
+ return others.length > 0 ? Math.min(...others) : null;
85
+ }
86
+
87
+ /** First arrival of every file, keyed by `pathKey(path, depth)`. */
88
+ export function arrivals(files: ArrFile[], history: HistoryRecord[], depth: number): Map<string, number> {
89
+ const byOwner = new Map<number, HistoryRecord[]>();
90
+ for (const record of history) {
91
+ const records = byOwner.get(record.owner);
92
+ if (records) records.push(record);
93
+ else byOwner.set(record.owner, [record]);
94
+ }
95
+ const out = new Map<string, number>();
96
+ for (const file of files) {
97
+ const arrival = firstArrival(
98
+ file.added,
99
+ file.owners.flatMap((owner) => byOwner.get(owner) ?? []),
100
+ );
101
+ if (arrival !== null) out.set(pathKey(file.path, depth), arrival);
102
+ }
103
+ return out;
104
+ }
105
+
106
+ function text(value: unknown): string | null {
107
+ return typeof value === "string" && value.length > 0 ? value : null;
108
+ }
109
+
110
+ function two(value: unknown): string {
111
+ return typeof value === "number" ? String(value).padStart(2, "0") : "??";
112
+ }
113
+
114
+ /** One row of Jellyfin's `/Items` as a library item; null for any other type or a row without an id. */
115
+ export function libraryItem(row: Record<string, unknown>): LibraryItem | null {
116
+ const id = text(row.Id);
117
+ const type = ITEM_TYPES.find((t) => t === row.Type);
118
+ if (id === null || type === undefined) return null;
119
+ const own = text(row.Name) ?? "?";
120
+ const series = text(row.SeriesName) ?? "?";
121
+ const name = type === "Episode" ? `${series} S${two(row.ParentIndexNumber)}E${two(row.IndexNumber)}` : type === "Season" ? `${series}, ${own}` : own;
122
+ const created = text(row.DateCreated);
123
+ const added = created === null ? Number.NaN : Date.parse(created);
124
+ return { id, type, name, path: text(row.Path), added: Number.isNaN(added) ? null : added, seasonId: text(row.SeasonId), seriesId: text(row.SeriesId) };
125
+ }
126
+
127
+ /**
128
+ * The dates to set. An item changes only when Jellyfin's date is more than a day after the date it should
129
+ * have, so a date is only ever moved back. A season takes its earliest episode, an empty season its series,
130
+ * and a series its earliest episode.
131
+ */
132
+ export function planDates(items: LibraryItem[], known: { movies: Map<string, number>; episodes: Map<string, number> }): DatePlan {
133
+ const plan: DatePlan = { changes: [], unmatched: [] };
134
+ const settled = new Map<string, number>();
135
+ const settle = (item: LibraryItem, wanted: number | undefined) => {
136
+ if (wanted !== undefined && (item.added === null || item.added - wanted > DAY_MS)) {
137
+ plan.changes.push({ id: item.id, type: item.type, name: item.name, from: item.added === null ? null : new Date(item.added).toISOString(), to: new Date(wanted).toISOString() });
138
+ settled.set(item.id, wanted);
139
+ } else if (item.added !== null) {
140
+ settled.set(item.id, item.added);
141
+ }
142
+ };
143
+ for (const item of items) {
144
+ if (item.type !== "Movie" && item.type !== "Episode") continue;
145
+ const wanted = item.path === null ? undefined : (item.type === "Movie" ? known.movies : known.episodes).get(pathKey(item.path, keyDepth(item.type)));
146
+ if (wanted === undefined) plan.unmatched.push({ type: item.type, name: item.name });
147
+ settle(item, wanted);
148
+ }
149
+ const earliestEpisode = (belongs: (episode: LibraryItem) => boolean): number | undefined => {
150
+ const dates = items.filter((i) => i.type === "Episode" && belongs(i)).flatMap((i) => settled.get(i.id) ?? []);
151
+ return dates.length > 0 ? Math.min(...dates) : undefined;
152
+ };
153
+ for (const item of items) if (item.type === "Series") settle(item, earliestEpisode((e) => e.seriesId === item.id));
154
+ for (const item of items) {
155
+ if (item.type !== "Season") continue;
156
+ settle(item, earliestEpisode((e) => e.seasonId === item.id) ?? (item.seriesId === null ? undefined : settled.get(item.seriesId)));
157
+ }
158
+ return plan;
159
+ }
160
+
161
+ /** How many changes the plan holds per item type. */
162
+ export function changeCounts(changes: DateChange[]): Record<"movies" | "episodes" | "seasons" | "series", number> {
163
+ const count = (type: ItemType) => changes.filter((c) => c.type === type).length;
164
+ return { movies: count("Movie"), episodes: count("Episode"), seasons: count("Season"), series: count("Series") };
165
+ }
166
+
167
+ /** Up to `perType` changes of each item type, so a large plan shows more than its first type. */
168
+ export function exampleChanges(changes: DateChange[], perType: number): DateChange[] {
169
+ return ITEM_TYPES.flatMap((type) => changes.filter((c) => c.type === type).slice(0, perType));
170
+ }
171
+
172
+ /** The newest `days` "date added" days of one item type, with the number of items added on each. */
173
+ export function addedByDay(items: LibraryItem[], type: ItemType, days: number): { day: string; items: number }[] {
174
+ const perDay = new Map<string, number>();
175
+ for (const item of items) {
176
+ if (item.type !== type || item.added === null) continue;
177
+ const day = new Date(item.added).toISOString().slice(0, 10);
178
+ perDay.set(day, (perDay.get(day) ?? 0) + 1);
179
+ }
180
+ return [...perDay.entries()]
181
+ .sort((a, b) => b[0].localeCompare(a[0]))
182
+ .slice(0, days)
183
+ .map(([day, count]) => ({ day, items: count }));
184
+ }
@@ -3,6 +3,8 @@ import { join } from "node:path";
3
3
  import { readConfig } from "../lib/config.ts";
4
4
  import { ServiceError, UsageError } from "../lib/errors.ts";
5
5
  import { main } from "../lib/main.ts";
6
+ import { ITEM_TYPES, addedByDay, arrivals, changeCounts, exampleChanges, keyDepth, libraryItem, planDates } from "../lib/media-dates.ts";
7
+ import type { ArrFile, DateChange, DatePlan, HistoryRecord, LibraryItem } from "../lib/media-dates.ts";
6
8
  import { printJson, printRaw } from "../lib/output.ts";
7
9
  import { workDir } from "../lib/paths.ts";
8
10
  import { run } from "../lib/proc.ts";
@@ -38,6 +40,22 @@ const SHAPE = {
38
40
  maxEntries: "number",
39
41
  } as const;
40
42
 
43
+ /** Read by the `jellyfin` commands only, so the other commands work without it. */
44
+ interface JellyfinConfig extends Record<string, string | number> {
45
+ jellyfinUrl: string;
46
+ radarrUrl: string;
47
+ sonarrUrl: string;
48
+ }
49
+
50
+ const JELLYFIN_SHAPE = { jellyfinUrl: "string", radarrUrl: "string", sonarrUrl: "string" } as const;
51
+
52
+ /** Read by `bazarr status` only. */
53
+ interface BazarrConfig extends Record<string, string | number> {
54
+ bazarrUrl: string;
55
+ }
56
+
57
+ const BAZARR_SHAPE = { bazarrUrl: "string" } as const;
58
+
41
59
  export interface MediaSecrets {
42
60
  tmdbAccessToken: string;
43
61
  omdbApiKey: string;
@@ -111,9 +129,15 @@ const HELP = `media specialist (trendarr: TMDB trending, OMDb ratings, Radarr an
111
129
  failedPending): app, id, title, state, status, messages, added, size
112
130
  queue-remove <radarr|sonarr> <id> --confirm
113
131
  remove that record and delete its download from SABnzbd, without blocklisting the release
132
+ jellyfin status Jellyfin's version, library scan state, item counts, and the newest "date added" days
133
+ jellyfin date-check items whose "date added" is more than a day after their first import in Radarr or
134
+ Sonarr (Jellyfin adds a renamed file as new); changes nothing
135
+ jellyfin date-repair --confirm
136
+ set those dates back to the first import; a season and a series take their earliest episode
137
+ bazarr status Bazarr's version, the Sonarr and Radarr versions it reads, and its health issues
114
138
 
115
139
  Output is trendarr's JSON plus "warnings" (trendarr's stderr warnings, such as an unreachable Radarr);
116
- queue and queue-remove call Radarr and Sonarr directly.
140
+ queue, queue-remove, jellyfin, and bazarr call the apps directly.
117
141
  An add exits 0 even when an ID fails: read each results[].status (added, already_exists, not_found, error).
118
142
  trendarr init and its configuration are operator tasks.`;
119
143
 
@@ -337,12 +361,31 @@ export function parseQueueRemove(args: string[]): { app: ArrApp; id: number } {
337
361
  return { app: rest[0], id: Number(rest[1]) };
338
362
  }
339
363
 
340
- async function arrRequest(config: MediaConfig, app: ArrApp, method: "GET" | "DELETE", path: string): Promise<unknown> {
341
- const base = app === "radarr" ? config.radarrUrl : config.sonarrUrl;
364
+ /**
365
+ * One JSON request to an app of the media project. A refusal, a timeout, or a broken answer names the app
366
+ * and the route, never the query or a key.
367
+ */
368
+ async function appRequest(app: string, method: "GET" | "POST" | "DELETE", url: URL, headers: Record<string, string>, timeoutMs: number, body?: unknown): Promise<unknown> {
369
+ const route = `${method} ${url.pathname}`;
370
+ try {
371
+ const res = await fetch(url, {
372
+ method,
373
+ headers: { ...headers, accept: "application/json", ...(body === undefined ? {} : { "content-type": "application/json" }) },
374
+ body: body === undefined ? undefined : JSON.stringify(body),
375
+ signal: AbortSignal.timeout(timeoutMs),
376
+ });
377
+ if (!res.ok) throw new ServiceError(`${app} answered ${res.status} to ${route}`);
378
+ const text = await res.text();
379
+ return text.length === 0 ? null : (JSON.parse(text) as unknown);
380
+ } catch (err) {
381
+ if (err instanceof ServiceError) throw err;
382
+ throw new ServiceError(`${app} gave no usable answer to ${route} within ${Math.round(timeoutMs / 1000)} s: ${err instanceof Error ? err.message.slice(0, 200) : String(err)}`);
383
+ }
384
+ }
385
+
386
+ async function arrRequest(config: { radarrUrl: string; sonarrUrl: string }, app: ArrApp, method: "GET" | "DELETE", path: string, timeoutMs = 30_000): Promise<unknown> {
342
387
  const key = readSecret(SERVICE, app === "radarr" ? "RADARR_API_KEY" : "SONARR_API_KEY");
343
- const res = await fetch(new URL(path, base), { method, headers: { "X-Api-Key": key, accept: "application/json" }, signal: AbortSignal.timeout(30_000) });
344
- if (!res.ok) throw new ServiceError(`${app} answered ${res.status} to ${method} ${path.split("?")[0]}`);
345
- return method === "GET" ? ((await res.json()) as unknown) : null;
388
+ return appRequest(app, method, new URL(path, app === "radarr" ? config.radarrUrl : config.sonarrUrl), { "X-Api-Key": key }, timeoutMs);
346
389
  }
347
390
 
348
391
  /** Both apps' queue records that wait for a person; an app that does not answer becomes a warning. */
@@ -359,6 +402,161 @@ async function queueStatus(config: MediaConfig): Promise<{ records: QueueRecord[
359
402
  return { records, warnings };
360
403
  }
361
404
 
405
+ function rows(value: unknown): Record<string, unknown>[] {
406
+ return Array.isArray(value) ? value.filter((v): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v)) : [];
407
+ }
408
+
409
+ function field(value: unknown, key: string): unknown {
410
+ return typeof value === "object" && value !== null ? (value as Record<string, unknown>)[key] : undefined;
411
+ }
412
+
413
+ function stringOrNull(value: unknown): string | null {
414
+ return typeof value === "string" ? value : null;
415
+ }
416
+
417
+ interface JellyfinServer {
418
+ base: string;
419
+ key: string;
420
+ }
421
+
422
+ async function jellyfinRequest(server: JellyfinServer, method: "GET" | "POST", path: string, body?: unknown): Promise<unknown> {
423
+ return appRequest("jellyfin", method, new URL(path, server.base), { authorization: `MediaBrowser Token="${server.key}"` }, 2 * MINUTE, body);
424
+ }
425
+
426
+ function jellyfinServer(config: JellyfinConfig): JellyfinServer {
427
+ return { base: config.jellyfinUrl, key: readSecret(SERVICE, "JELLYFIN_API_KEY") };
428
+ }
429
+
430
+ /** Every movie, episode, season, and series; one request per type without a limit, because pages of an unsorted list can overlap. */
431
+ async function libraryItems(server: JellyfinServer): Promise<LibraryItem[]> {
432
+ const items: LibraryItem[] = [];
433
+ for (const type of ITEM_TYPES) {
434
+ const page = await jellyfinRequest(server, "GET", `/Items?recursive=true&includeItemTypes=${type}&fields=Path,DateCreated`);
435
+ items.push(...rows(field(page, "Items")).flatMap((row) => libraryItem(row) ?? []));
436
+ }
437
+ return items;
438
+ }
439
+
440
+ const ARR_HISTORY_TIMEOUT_MS = 2 * MINUTE;
441
+
442
+ /** The whole history of one app: `owner` is the movie id in Radarr and the episode id in Sonarr. */
443
+ async function arrHistory(config: JellyfinConfig, app: ArrApp): Promise<HistoryRecord[]> {
444
+ const ownerKey = app === "radarr" ? "movieId" : "episodeId";
445
+ return rows(await arrRequest(config, app, "GET", "/api/v3/history/since?date=2000-01-01T00:00:00Z", ARR_HISTORY_TIMEOUT_MS)).flatMap((r) => {
446
+ const owner = r[ownerKey];
447
+ return typeof owner === "number" && typeof r.eventType === "string" && typeof r.date === "string" ? [{ owner, eventType: r.eventType, date: r.date }] : [];
448
+ });
449
+ }
450
+
451
+ async function radarrFiles(config: JellyfinConfig): Promise<ArrFile[]> {
452
+ return rows(await arrRequest(config, "radarr", "GET", "/api/v3/movie", ARR_HISTORY_TIMEOUT_MS)).flatMap((movie) => {
453
+ const path = field(movie.movieFile, "path");
454
+ return typeof movie.id === "number" && typeof path === "string" ? [{ path, added: stringOrNull(field(movie.movieFile, "dateAdded")), owners: [movie.id] }] : [];
455
+ });
456
+ }
457
+
458
+ async function sonarrFiles(config: JellyfinConfig): Promise<ArrFile[]> {
459
+ const files: ArrFile[] = [];
460
+ for (const series of rows(await arrRequest(config, "sonarr", "GET", "/api/v3/series"))) {
461
+ if (typeof series.id !== "number") continue;
462
+ const episodes = rows(await arrRequest(config, "sonarr", "GET", `/api/v3/episode?seriesId=${series.id}`));
463
+ for (const file of rows(await arrRequest(config, "sonarr", "GET", `/api/v3/episodefile?seriesId=${series.id}`))) {
464
+ if (typeof file.path !== "string") continue;
465
+ const owners = episodes.flatMap((e) => (e.episodeFileId === file.id && typeof e.id === "number" ? [e.id] : []));
466
+ files.push({ path: file.path, added: stringOrNull(file.dateAdded), owners });
467
+ }
468
+ }
469
+ return files;
470
+ }
471
+
472
+ /** Jellyfin's library against the first arrival of each file in Radarr and Sonarr. */
473
+ async function datePlan(config: JellyfinConfig, server: JellyfinServer): Promise<DatePlan> {
474
+ const movies = arrivals(await radarrFiles(config), await arrHistory(config, "radarr"), keyDepth("Movie"));
475
+ const episodes = arrivals(await sonarrFiles(config), await arrHistory(config, "sonarr"), keyDepth("Episode"));
476
+ return planDates(await libraryItems(server), { movies, episodes });
477
+ }
478
+
479
+ /** Examples a date check prints per item type, and of unmatched items. */
480
+ const EXAMPLES_PER_TYPE = 2;
481
+ const UNMATCHED_EXAMPLES = 5;
482
+ /** Failed updates after which a repair stops; the rest of the plan stays for the next run. */
483
+ const MAX_REPAIR_FAILURES = 5;
484
+
485
+ /**
486
+ * Sets each planned date through Jellyfin's own item update, the call behind its metadata editor: the item
487
+ * as Jellyfin returns it, with only `DateCreated` changed. `People` stays out, because Jellyfin rewrites an
488
+ * item's people only when the request carries them.
489
+ */
490
+ async function applyDates(server: JellyfinServer, changes: DateChange[]): Promise<{ done: DateChange[]; failed: { name: string; error: string }[] }> {
491
+ const admin = rows(await jellyfinRequest(server, "GET", "/Users")).find((user) => field(user.Policy, "IsAdministrator") === true);
492
+ if (typeof admin?.Id !== "string") throw new ServiceError("jellyfin lists no administrator to read items as");
493
+ const done: DateChange[] = [];
494
+ const failed: { name: string; error: string }[] = [];
495
+ for (const change of changes) {
496
+ if (failed.length >= MAX_REPAIR_FAILURES) break;
497
+ try {
498
+ const item = await jellyfinRequest(server, "GET", `/Items/${change.id}?userId=${admin.Id}`);
499
+ if (typeof item !== "object" || item === null || field(item, "Id") !== change.id) throw new ServiceError("jellyfin returned another item");
500
+ const body = Object.fromEntries(Object.entries(item).filter(([key]) => key !== "People"));
501
+ await jellyfinRequest(server, "POST", `/Items/${change.id}`, { ...body, DateCreated: change.to });
502
+ done.push(change);
503
+ } catch (err) {
504
+ failed.push({ name: change.name, error: err instanceof Error ? err.message.slice(0, 200) : String(err) });
505
+ }
506
+ }
507
+ return { done, failed };
508
+ }
509
+
510
+ async function jellyfinCommand(args: string[]): Promise<number> {
511
+ const usage = "jellyfin status|date-check|date-repair --confirm";
512
+ const [name, ...rest] = args;
513
+ if (name === "date-repair") {
514
+ if (rest.length !== 1 || rest[0] !== "--confirm") throw new UsageError(`${usage}: date-repair changes Jellyfin's dates, so it needs --confirm`);
515
+ } else if ((name !== "status" && name !== "date-check") || rest.length > 0) {
516
+ throw new UsageError(usage);
517
+ }
518
+ const config = readConfig<JellyfinConfig>(SERVICE, JELLYFIN_SHAPE);
519
+ const server = jellyfinServer(config);
520
+ if (name === "status") {
521
+ const tasks = rows(await jellyfinRequest(server, "GET", "/ScheduledTasks"));
522
+ const scan = tasks.find((task) => task.Key === "RefreshLibrary");
523
+ const last = field(scan, "LastExecutionResult");
524
+ const counts = await jellyfinRequest(server, "GET", "/Items/Counts");
525
+ const items = await libraryItems(server);
526
+ printJson({
527
+ version: field(await jellyfinRequest(server, "GET", "/System/Info"), "Version") ?? null,
528
+ scan: { state: field(scan, "State") ?? null, lastStart: field(last, "StartTimeUtc") ?? null, lastEnd: field(last, "EndTimeUtc") ?? null, status: field(last, "Status") ?? null },
529
+ counts: { movies: field(counts, "MovieCount") ?? null, series: field(counts, "SeriesCount") ?? null, episodes: field(counts, "EpisodeCount") ?? null },
530
+ addedByDay: { movies: addedByDay(items, "Movie", 3), episodes: addedByDay(items, "Episode", 3) },
531
+ });
532
+ return 0;
533
+ }
534
+ const plan = await datePlan(config, server);
535
+ if (name === "date-check") {
536
+ printJson({
537
+ changes: changeCounts(plan.changes),
538
+ examples: exampleChanges(plan.changes, EXAMPLES_PER_TYPE).map(({ type, name, from, to }) => ({ type, name, from, to })),
539
+ unmatched: plan.unmatched.length,
540
+ unmatchedExamples: plan.unmatched.slice(0, UNMATCHED_EXAMPLES),
541
+ });
542
+ return 0;
543
+ }
544
+ const { done, failed } = await applyDates(server, plan.changes);
545
+ const left = plan.changes.length - done.length;
546
+ printJson({ status: plan.changes.length === 0 ? "nothing to repair" : left === 0 ? "repaired" : "stopped", changed: changeCounts(done), left, failed });
547
+ return 0;
548
+ }
549
+
550
+ async function bazarrStatus(): Promise<number> {
551
+ const config = readConfig<BazarrConfig>(SERVICE, BAZARR_SHAPE);
552
+ const key = readSecret(SERVICE, "BAZARR_API_KEY");
553
+ const get = async (path: string): Promise<unknown> => field(await appRequest("bazarr", "GET", new URL(path, config.bazarrUrl), { "X-API-KEY": key }, 30_000), "data");
554
+ const status = await get("/api/system/status");
555
+ const issues = rows(await get("/api/system/health")).map((issue) => ({ object: stringOrNull(issue.object), issue: stringOrNull(issue.issue) }));
556
+ printJson({ version: field(status, "bazarr_version") ?? null, sonarr_version: field(status, "sonarr_version") ?? null, radarr_version: field(status, "radarr_version") ?? null, issues });
557
+ return 0;
558
+ }
559
+
362
560
  export async function command(args: string[]): Promise<number> {
363
561
  if (args.length === 0 || args[0] === "--help" || args[0] === "help") {
364
562
  printRaw(HELP);
@@ -375,6 +573,11 @@ export async function command(args: string[]): Promise<number> {
375
573
  printJson({ status: "removed", app, id });
376
574
  return 0;
377
575
  }
576
+ if (args[0] === "jellyfin") return jellyfinCommand(args.slice(1));
577
+ if (args[0] === "bazarr") {
578
+ if (args.length !== 2 || args[1] !== "status") throw new UsageError("bazarr status");
579
+ return bazarrStatus();
580
+ }
378
581
  const call = buildTrendarrCall(args);
379
582
  const config = readConfig<MediaConfig>(SERVICE, SHAPE);
380
583
  printJson(interpretRun(call, await runTrendarr(config, call)));
@@ -245,11 +245,13 @@ export function deviceNetworkWrite(args: string[]): UnifiWrite {
245
245
  }
246
246
 
247
247
  const CLIENT_FIXED_IP_KEYS = new Set(["use_fixedip", "fixed_ip", "network_id"]);
248
+ /** A client record's `_id`: 24 hex digits, or a UUID (Mira's console returned UUIDs on 2026-11-12). */
249
+ const CLIENT_ID = /^(?:[0-9a-f]{24}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/;
248
250
 
249
251
  /** `client-fixed-ip <clientId> <json>`: only a known client's DHCP reservation, through the application's client records. */
250
252
  export function clientFixedIpWrite(args: string[]): UnifiWrite {
251
253
  const [id, json, ...extra] = args;
252
- if (id === undefined || !NAT_ID.test(id) || json === undefined || extra.length > 0) throw new UsageError("client-fixed-ip <clientId> <json>");
254
+ if (id === undefined || !CLIENT_ID.test(id) || json === undefined || extra.length > 0) throw new UsageError("client-fixed-ip <clientId> <json>");
253
255
  const body = jsonBody(json);
254
256
  const keys = Object.keys(JSON.parse(body) as Record<string, unknown>);
255
257
  if (keys.length === 0 || keys.some((k) => !CLIENT_FIXED_IP_KEYS.has(k))) throw new UsageError(`client-fixed-ip body keys: ${[...CLIENT_FIXED_IP_KEYS].join(", ")}`);
@@ -1,4 +1,7 @@
1
1
  import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
2
+ import { createServer } from "node:http";
3
+ import type { Server } from "node:http";
4
+ import type { AddressInfo } from "node:net";
2
5
  import { tmpdir } from "node:os";
3
6
  import { join } from "node:path";
4
7
  import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -152,6 +155,8 @@ describe("network wrapper", () => {
152
155
  expect(() => portForwardDelete(["../x", "qb"])).toThrow(UsageError);
153
156
  const fixed = JSON.stringify({ use_fixedip: true, fixed_ip: "10.1.50.50", network_id: "0123456789abcdef01234567" });
154
157
  expect(clientFixedIpWrite(["0123456789abcdef01234567", fixed])).toEqual({ method: "PUT", path: "/api/s/default/rest/user/0123456789abcdef01234567", body: fixed });
158
+ expect(clientFixedIpWrite(["071e4027-d2e9-4f61-9fc4-5a92e85cf842", fixed]).path).toBe("/api/s/default/rest/user/071e4027-d2e9-4f61-9fc4-5a92e85cf842");
159
+ expect(() => clientFixedIpWrite(["071e4027-d2e9-4f61-9fc4-5a92e85cf84/..", fixed])).toThrow(/client-fixed-ip/);
155
160
  expect(() => clientFixedIpWrite(["0123456789abcdef01234567", JSON.stringify({ name: "x" })])).toThrow(/body keys/);
156
161
  expect(appGetPath(["/v2/api/site/default/nat"])).toBe("/v2/api/site/default/nat");
157
162
  expect(() => appGetPath(["/api/s/other/stat/device"])).toThrow(UsageError);
@@ -869,6 +874,8 @@ describe("media wrapper", () => {
869
874
  const write = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
870
875
  expect(await mediaCommand(["--help"])).toBe(0);
871
876
  expect(String(write.mock.calls[0][0])).toContain("add-movies <imdbId...>");
877
+ expect(String(write.mock.calls[0][0])).toContain("jellyfin date-repair --confirm");
878
+ expect(String(write.mock.calls[0][0])).toContain("bazarr status");
872
879
  write.mockRestore();
873
880
  });
874
881
 
@@ -923,6 +930,130 @@ describe("media wrapper", () => {
923
930
  rmSync(join(home, ".specialists", "secrets", "media", "OMDB_API_KEY"));
924
931
  await expect(mediaCommand(["trending"])).rejects.toThrow(/OMDB_API_KEY for media is missing/);
925
932
  });
933
+
934
+ describe("jellyfin and bazarr", () => {
935
+ let server: Server;
936
+ let posts: { url: string; body: Record<string, unknown> }[];
937
+ const renamed = "2026-11-10T10:41:12.1545518Z";
938
+ const jellyfin: Record<string, Record<string, unknown>[]> = {
939
+ Movie: [{ Id: "m1", Type: "Movie", Name: "Film", Path: "/media/movies/Film (1999)/Film.mkv", DateCreated: "2026-09-01T00:00:10Z" }],
940
+ Episode: [
941
+ { Id: "e1", Type: "Episode", Name: "Pilot", SeriesName: "Show", ParentIndexNumber: 1, IndexNumber: 1, Path: "/media/tv/Show/Season 01/a.mkv", DateCreated: renamed, SeasonId: "s1", SeriesId: "x1" },
942
+ { Id: "e2", Type: "Episode", Name: "Extra", SeriesName: "Show", ParentIndexNumber: 1, IndexNumber: 2, Path: "/media/tv/Show/Season 1/old.mkv", DateCreated: renamed, SeasonId: "s1", SeriesId: "x1" },
943
+ ],
944
+ Season: [{ Id: "s1", Type: "Season", Name: "Season 1", SeriesName: "Show", DateCreated: renamed, SeriesId: "x1" }],
945
+ Series: [{ Id: "x1", Type: "Series", Name: "Show", DateCreated: "2026-07-01T00:00:00Z" }],
946
+ };
947
+
948
+ beforeEach(async () => {
949
+ posts = [];
950
+ server = createServer((req, res) => {
951
+ const url = new URL(req.url ?? "/", "http://localhost");
952
+ const key = req.headers["x-api-key"];
953
+ const send = (value: unknown) => {
954
+ res.setHeader("content-type", "application/json");
955
+ res.end(JSON.stringify(value));
956
+ };
957
+ if (req.method === "POST") {
958
+ let raw = "";
959
+ req.on("data", (chunk: Buffer) => (raw += chunk.toString()));
960
+ req.on("end", () => {
961
+ posts.push({ url: url.pathname, body: JSON.parse(raw) as Record<string, unknown> });
962
+ res.statusCode = 204;
963
+ res.end();
964
+ });
965
+ return;
966
+ }
967
+ if (url.pathname.startsWith("/api/system/")) {
968
+ if (key !== "bazarr_api_key") return void ((res.statusCode = 401), res.end());
969
+ return send(url.pathname.endsWith("status") ? { data: { bazarr_version: "1.6.2", sonarr_version: "4.0.20", radarr_version: "6.4.4", bazarr_directory: "/app" } } : { data: [{ object: "Sonarr", issue: "unreachable" }] });
970
+ }
971
+ if (url.pathname.startsWith("/api/v3/")) {
972
+ const route = url.pathname.slice("/api/v3/".length);
973
+ if (key === "radarr_api_key") {
974
+ if (route === "movie") return send([{ id: 5, movieFile: { path: "/media/movies/Film (1999)/Film.mkv", dateAdded: "2026-09-01T00:00:00Z" } }, { id: 6 }]);
975
+ return send([{ movieId: 5, eventType: "downloadFolderImported", date: "2026-09-01T00:00:00Z" }]);
976
+ }
977
+ if (route === "series") return send([{ id: 1 }]);
978
+ if (route === "episode") return send([{ id: 10, episodeFileId: 100 }]);
979
+ if (route === "episodefile") return send([{ id: 100, path: "/media/tv/Show/Season 01/a.mkv", dateAdded: "2026-08-01T00:00:00Z" }]);
980
+ return send([{ episodeId: 10, eventType: "downloadFolderImported", date: "2026-07-24T06:43:37Z" }, { episodeId: 10, eventType: "episodeFileRenamed", date: "2026-11-10T10:30:00Z" }]);
981
+ }
982
+ if (req.headers.authorization !== 'MediaBrowser Token="jellyfin_api_key"') return void ((res.statusCode = 401), res.end());
983
+ if (url.pathname === "/Users") return send([{ Id: "u0", Policy: { IsAdministrator: false } }, { Id: "u1", Policy: { IsAdministrator: true } }]);
984
+ if (url.pathname === "/ScheduledTasks") return send([{ Key: "RefreshLibrary", State: "Idle", LastExecutionResult: { StartTimeUtc: "2026-11-09T13:27:07Z", EndTimeUtc: "2026-11-09T13:27:15Z", Status: "Completed" } }]);
985
+ if (url.pathname === "/Items/Counts") return send({ MovieCount: 1, SeriesCount: 1, EpisodeCount: 2 });
986
+ if (url.pathname === "/System/Info") return send({ Version: "12.4.0" });
987
+ if (url.pathname === "/Items") return send({ Items: jellyfin[url.searchParams.get("includeItemTypes") ?? ""] ?? [] });
988
+ const item = Object.values(jellyfin).flat().find((row) => url.pathname === `/Items/${String(row.Id)}`);
989
+ if (item === undefined || url.searchParams.get("userId") !== "u1") return void ((res.statusCode = 400), res.end());
990
+ return send({ ...item, Overview: "kept", People: [{ Name: "Someone" }] });
991
+ });
992
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
993
+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
994
+ for (const field of ["JELLYFIN_API_KEY", "BAZARR_API_KEY"]) writeFileSync(join(home, ".specialists", "secrets", "media", field), `${field.toLowerCase()}\n`, { mode: 0o600 });
995
+ writeFileSync(join(home, ".specialists", "config", "media.json"), JSON.stringify({ jellyfinUrl: base, radarrUrl: base, sonarrUrl: base, bazarrUrl: base }));
996
+ });
997
+
998
+ afterEach(async () => {
999
+ await new Promise((resolve) => server.close(resolve));
1000
+ });
1001
+
1002
+ async function printed(args: string[]): Promise<Record<string, unknown>> {
1003
+ const write = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
1004
+ try {
1005
+ expect(await mediaCommand(args)).toBe(0);
1006
+ return JSON.parse(String(write.mock.calls[0][0])) as Record<string, unknown>;
1007
+ } finally {
1008
+ write.mockRestore();
1009
+ }
1010
+ }
1011
+
1012
+ it("reports Jellyfin's scan, counts, and newest added days", async () => {
1013
+ expect(await printed(["jellyfin", "status"])).toEqual({
1014
+ version: "12.4.0",
1015
+ scan: { state: "Idle", lastStart: "2026-11-09T13:27:07Z", lastEnd: "2026-11-09T13:27:15Z", status: "Completed" },
1016
+ counts: { movies: 1, series: 1, episodes: 2 },
1017
+ addedByDay: { movies: [{ day: "2026-09-01", items: 1 }], episodes: [{ day: "2026-11-10", items: 2 }] },
1018
+ });
1019
+ });
1020
+
1021
+ it("plans dates from the first import and changes nothing on a check", async () => {
1022
+ expect(await printed(["jellyfin", "date-check"])).toEqual({
1023
+ changes: { movies: 0, episodes: 1, seasons: 1, series: 0 },
1024
+ examples: [
1025
+ { type: "Episode", name: "Show S01E01", from: "2026-11-10T10:41:12.154Z", to: "2026-07-24T06:43:37.000Z" },
1026
+ { type: "Season", name: "Show, Season 1", from: "2026-11-10T10:41:12.154Z", to: "2026-07-24T06:43:37.000Z" },
1027
+ ],
1028
+ unmatched: 1,
1029
+ unmatchedExamples: [{ type: "Episode", name: "Show S01E02" }],
1030
+ });
1031
+ expect(posts).toEqual([]);
1032
+ });
1033
+
1034
+ it("repairs through Jellyfin's item update, with only the date changed and no people", async () => {
1035
+ expect(await printed(["jellyfin", "date-repair", "--confirm"])).toEqual({ status: "repaired", changed: { movies: 0, episodes: 1, seasons: 1, series: 0 }, left: 0, failed: [] });
1036
+ expect(posts.map((p) => p.url)).toEqual(["/Items/e1", "/Items/s1"]);
1037
+ expect(posts[0].body).toMatchObject({ Id: "e1", Name: "Pilot", Overview: "kept", Path: "/media/tv/Show/Season 01/a.mkv", DateCreated: "2026-07-24T06:43:37.000Z" });
1038
+ expect(posts[0].body).not.toHaveProperty("People");
1039
+ });
1040
+
1041
+ it("refuses a repair without --confirm and unknown subcommands before reading anything", async () => {
1042
+ await expect(mediaCommand(["jellyfin", "date-repair"])).rejects.toThrow(/needs --confirm/);
1043
+ await expect(mediaCommand(["jellyfin", "scan"])).rejects.toThrow(/status\|date-check\|date-repair/);
1044
+ await expect(mediaCommand(["jellyfin", "status", "now"])).rejects.toThrow(UsageError);
1045
+ await expect(mediaCommand(["bazarr", "restart"])).rejects.toThrow(/bazarr status/);
1046
+ });
1047
+
1048
+ it("reports Bazarr's versions and health issues without its paths", async () => {
1049
+ expect(await printed(["bazarr", "status"])).toEqual({ version: "1.6.2", sonarr_version: "4.0.20", radarr_version: "6.4.4", issues: [{ object: "Sonarr", issue: "unreachable" }] });
1050
+ });
1051
+
1052
+ it("names the app and the route when one refuses the key", async () => {
1053
+ writeFileSync(join(home, ".specialists", "secrets", "media", "JELLYFIN_API_KEY"), "wrong\n", { mode: 0o600 });
1054
+ await expect(mediaCommand(["jellyfin", "status"])).rejects.toThrow(/jellyfin answered 401 to GET \/ScheduledTasks/);
1055
+ });
1056
+ });
926
1057
  });
927
1058
  });
928
1059