@astrofoundry/pi-astro 0.39.1 → 0.40.0

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/README.md CHANGED
@@ -68,7 +68,7 @@ pi # launch; confirm [Extensions] lists astro-subagents, grimoire
68
68
  - `multi-edit` - registers the enhanced `edit` tool
69
69
  - `gemini-image` - registers `gemini_image` tool (requires a Gemini API key; prompts and saves on first use)
70
70
  - `security-guard` - blocks/prompts destructive bash commands and sensitive file access; configure at `~/.pi/agent/security-guard.json` (example written on first run); `/security-guard status|reload|test`
71
- - `astro-discord` - Discord access to the specialists: in the configured channels, `<specialist> <task>` runs `astro.<specialist>` and posts the answer as a reply (⏳ running, 🔒 waiting for an owner's approval of a risky call, ✅ done, ❌ failed). Owners may use every specialist and approve risky calls with buttons; other users only the specialists listed for them; everyone else is ignored. Where the `media` specialist is present, `/trending`, `/search`, and `/downloads` answer without a model, with an Add button beside each title. Scheduled reports (`reports` in its config): the Arcane Daily Report, with a release-notes verdict on major versions and an Update button per stack that only owners can press, the Cortex Tools Report, which lists every tool on Cortex with a newer version, a release-notes verdict for the tools the specialists build on, and an Update button that only owners can press, and the Security Daily and Weekly Reports (CrowdSec, Wazuh, vulnerabilities, patches, health, backups), whose channel also gets urgent Wazuh alerts within two minutes, with Investigate (the security specialist answers in a thread) and Acknowledge buttons for owners. Inert unless the headless host sets `ASTRO_DISCORD=1`; setup with `d=$(mktemp -d) && cp ~/.pi/agent/npm/node_modules/@astrofoundry/pi-astro/extensions/astro-discord/*.ts "$d" && node --disable-warning=ExperimentalWarning "$d/setup.ts"` (Node refuses to strip types inside `node_modules`, hence the copy), which prompts for the bot token and ids, checks them against Discord, and writes the LaunchAgent. See [specialists/README.md](specialists/README.md#discord).
71
+ - `astro-discord` - Discord access to the specialists: in the configured channels, `<specialist> <task>` runs `astro.<specialist>` and posts the answer as a reply (⏳ running, 🔒 waiting for an owner's approval of a risky call, ✅ done, ❌ failed). Owners may use every specialist and approve risky calls with buttons; other users only the specialists listed for them; everyone else is ignored. Where the `media` specialist is present, `/trending`, `/search`, and `/downloads` answer without a model, with an Add button beside each title. Scheduled reports (`reports` in its config): the Arcane Daily Report, with a release-notes verdict on major versions and an Update button per stack that only owners can press, the Cortex Tools Report, which lists every tool on Cortex with a newer version, a release-notes verdict for the tools the specialists build on, and an Update button that only owners can press, and the Security Daily and Weekly Reports (CrowdSec, Wazuh, vulnerabilities, patches, health, backups), whose channel also gets urgent Wazuh alerts within two minutes, with Investigate (the security specialist answers in a thread) and Acknowledge buttons for owners, and the weekly media picks (Fridays: three movies and three series that TMDB recommends for your library, IMDb 7.0 or higher, each with Add and Not interested buttons; an ignored pick may return after six months, a dismissed one never). Inert unless the headless host sets `ASTRO_DISCORD=1`; setup with `d=$(mktemp -d) && cp ~/.pi/agent/npm/node_modules/@astrofoundry/pi-astro/extensions/astro-discord/*.ts "$d" && node --disable-warning=ExperimentalWarning "$d/setup.ts"` (Node refuses to strip types inside `node_modules`, hence the copy), which prompts for the bot token and ids, checks them against Discord, and writes the LaunchAgent. See [specialists/README.md](specialists/README.md#discord).
72
72
  - `specialist-gate` - gives each specialist agent (`astro.arcane`, `astro.identity`, `astro.network`, `astro.dns`, `astro.edge`, `astro.security`, `astro.backup`, `astro.proxmox`, `astro.inference`, `astro.media`) its single tool, which runs the matching CLI wrapper as a dedicated macOS user through `sudo`, and blocks every other agent from calling those CLIs or reading their credentials. Inactive until the host has `~/.pi/agent/specialists.json`. `/specialists` prints the status. Host setup is described in [specialists/README.md](specialists/README.md).
73
73
  - `notify-on-stop` - runs a shell command when the agent finishes a turn (sound, voice, desktop notification). **Default: off.** Enable with `/notify on` (state persists in `~/.pi/agent/notify-on-stop.json`); disable with `/notify off`. macOS default command: plays the Glass system sound and speaks "Agent done" via `say` using the **`Samantha (Enhanced)`** voice. Linux default: `notify-send "pi" "Agent done"`. Override the voice with `PI_STOP_NOTIFY_VOICE=<voice-name>` (macOS only; e.g. `Alex`, `Karen`, `Daniel (Enhanced)`). Replace the full command with `PI_STOP_NOTIFY='afplay /System/Library/Sounds/Glass.aiff && say "Done"'`. Hard-kill (overrides `/notify on`) with `PI_STOP_NOTIFY_OFF=1`. Commands: `/notify [on|off|status|test]`. See [extensions/notify-on-stop/README.md](extensions/notify-on-stop/README.md) for full details.
74
74
  - **macOS voice install (required once for the default):** open **System Settings, Accessibility, Spoken Content, System Voice, Manage Voices...**, expand **English**, check **Samantha (Enhanced)**, click **Done** to download (~500 MB to 1 GB). Verify with `say -v "Samantha (Enhanced)" hi`. If the voice is missing, `say` errors silently and you'll only hear the Glass sound.
@@ -80,7 +80,7 @@ pi # launch; confirm [Extensions] lists astro-subagents, grimoire
80
80
 
81
81
  **Bundled subagents** (call them as `astro.<name>`):
82
82
  - General-purpose: `code-reviewer`, `google-tech-lead`, `spec-writer`, `tester-api`, `tester-ui`, `ui-architect`, `ui-design-system`, `ui-frontend-developer`
83
- - Specialists (one homelab area each, need the host setup in [specialists/README.md](specialists/README.md)): `arcane` (Arcane container platform, GitOps first; sanitized host checks, Mealie and Paperless dumps, stack image updates with rollback, and the documented manager upgrade, both with buttons on the daily report), `identity` (Zitadel, Pomerium routes through the homelab repository, certificates), `network` (UniFi reads and firewall policies, FreeRADIUS, Tailscale), `dns` (Technitium resolvers, Cloudflare zones), `edge` (Frontdoor VPS over IAP, nginx SNI allowlist through the homelab repository, public route checks), `security` (Wazuh, CrowdSec, log archive, read-only), `backup` (vzdump, Restic layers, GCS offsite, restore tests), `proxmox` (guest lifecycle, snapshots, resources; no create or destroy), `inference` (llama.cpp on Nexus, Europa health), `media` (trendarr: trending titles, Radarr and Sonarr adds, SABnzbd pause)
83
+ - Specialists (one homelab area each, need the host setup in [specialists/README.md](specialists/README.md)): `arcane` (Arcane container platform, GitOps first; sanitized host checks, Mealie and Paperless dumps, stack image updates with rollback, and the documented manager upgrade, both with buttons on the daily report), `identity` (Zitadel, Pomerium routes through the homelab repository, certificates), `network` (UniFi reads and firewall policies, FreeRADIUS, Tailscale), `dns` (Technitium resolvers, Cloudflare zones), `edge` (Frontdoor VPS over IAP, nginx SNI allowlist through the homelab repository, public route checks), `security` (Wazuh, CrowdSec, log archive, read-only), `backup` (vzdump, Restic layers, GCS offsite, restore tests), `proxmox` (guest lifecycle, snapshots, resources; no create or destroy), `inference` (llama.cpp on Nexus, Europa health), `media` (trendarr: trending titles, recommendations from the library, Radarr and Sonarr adds, SABnzbd pause)
84
84
  - Release notes: `release-reviewer` (no tools; judges whether an update could break how we use a tool or image, for the Cortex Tools Report and the Arcane Daily Report)
85
85
  - Supervision: `foreman` (read only; diagnoses an unattended update that failed its check, through the specialists)
86
86
  - Flourish pipeline: `flourish-input-vision` (image to spec), `flourish-input-narrative` (text to spec), `flourish-input-codebase` (HTML to spec), `flourish-architect` (spec to plan), `flourish-template-developer` (plan to SDK template, needs `@flourish/sdk`), `flourish-example-builder` (template to realistic example), `flourish-preview-runner` (multi-breakpoint preview + screenshots, needs `@flourish/sdk`), `flourish-reviewer` (audit)
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, title search, adds to Radarr and Sonarr, and the SABnzbd queue pause state. Use for what is trending, adding a movie or series by name, and pausing or resuming downloads.
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, and the SABnzbd queue pause state. Use for what is trending, adding a movie or series by name, and pausing or resuming downloads.
4
4
  tools: read, media, subagent
5
5
  skills: media
6
6
  systemPromptMode: replace
@@ -14,7 +14,7 @@ You are the media specialist. The `media` tool, which runs the `trendarr` CLI, i
14
14
 
15
15
  Rules:
16
16
 
17
- - Search before you add, and add only IMDb IDs that a `search` or `trending` result returned in this conversation. Never invent or guess an ID.
17
+ - Search before you add, and add only IMDb IDs that a `search`, `trending`, or `recommend` result returned in this conversation. Never invent or guess an ID.
18
18
  - Resolve the title with the rules in the skill. A named film or series with one clear match: add it without asking. Ask one short question only when several plausible works remain and the choice changes what gets added.
19
19
  - Movies go to `add-movies`, series to `add-series`; batch independent IDs in one call.
20
20
  - Success needs an explicit `added` or `already_exists` in `results`; `already_exists` means it was already there, not newly added. Report every ID of a batch.
@@ -34,12 +34,14 @@ export interface DiscordConfig {
34
34
  * Reports the bridge can post on a schedule, without a model. `security` is the
35
35
  * daily report and also turns on the urgent-alert check in its channel;
36
36
  * `security-weekly` posts on Mondays only, in place of that day's daily report.
37
- * `daily` is the morning run: at its time it posts the other reports in their
38
- * own channels (their `time` is then unused), applies the updates, reads every
39
- * specialist's status, and posts the summary in its channel.
37
+ * `daily` is the morning run: at its time it posts the `MORNING_REPORTS` in
38
+ * their own channels (their `time` is then unused), applies the updates, reads
39
+ * every specialist's status, and posts the summary in its channel.
40
+ * `media-weekly` posts the media picks on Fridays, on its own time.
40
41
  */
41
- export const REPORT_NAMES = ["arcane", "tools", "security", "security-weekly", "daily"] as const;
42
+ export const REPORT_NAMES = ["arcane", "tools", "security", "security-weekly", "daily", "media-weekly"] as const;
42
43
  export type ReportName = (typeof REPORT_NAMES)[number];
44
+ export const MORNING_REPORTS: readonly ReportName[] = ["arcane", "tools", "security", "security-weekly"];
43
45
 
44
46
  /** One entry of `reports` in config.json: which report, where, and when. */
45
47
  export interface ReportSchedule {
@@ -11,7 +11,7 @@ import { ApprovalServer, type Ticket } from "./approvals.ts";
11
11
  import { chunkMessage } from "./chunk.ts";
12
12
  import { applyAdminCommand } from "./admin.ts";
13
13
  import { CHANNEL_RULES, helpText, needsPrefixText, parseCommand } from "./commands.ts";
14
- import { ACTIVATION_ENV, type ChannelSettings, type DiscordConfig, type ReportName, type ReportSchedule, allowedSpecialists, canUse, channelSpecialists, isOwner, loadConfig, loadToken, reportSchedule, saveConfig } from "./config.ts";
14
+ import { ACTIVATION_ENV, type ChannelSettings, type DiscordConfig, MORNING_REPORTS, type ReportName, type ReportSchedule, allowedSpecialists, canUse, channelSpecialists, isOwner, loadConfig, loadToken, reportSchedule, saveConfig } from "./config.ts";
15
15
  import { type ConversationState, type ResolvedConversation, forgetStale, loadState, newConversationId, recordAnswer, resolveConversation, saveState, sessionsRoot, startConversation } from "./conversations.ts";
16
16
  import { describeImages, downloadImages, type ImageAttachment, imageAttachments } from "./attachments.ts";
17
17
  import {
@@ -36,7 +36,8 @@ import {
36
36
  import { GatewayClient } from "./gateway.ts";
37
37
  import { type CommandOption, IS_COMPONENTS_V2, KeyedQueue, MEDIA, MEDIA_COMMANDS, type MediaKind, type Outcome, addOutcome, applyOutcome, commandArgs, hasActiveButton, listMessage, mediaAccess, mediaPointer, parseAddButton, parseAddReport, parseMediaList, parseQueueState, queueLine } from "./media.ts";
38
38
  import { cancelledApprovalText, interruptedTaskText, readOpenWork, type OpenWork, type StopReason, writeOpenWork } from "./open-work.ts";
39
- import { isDue, MONDAY, readReportState, writeReportState, zonedWeekday } from "./reports.ts";
39
+ import { DISMISSED, type Picks, parseNoButton, parsePicks, picksArgs, picksFailureText, picksMessage, readPicksState, withDismissed, withSuggested, writePicksState } from "./media-picks.ts";
40
+ import { FRIDAY, isDue, MONDAY, readReportState, writeReportState, zonedWeekday } from "./reports.ts";
40
41
  import { ACTIVITY_COMMAND, type Activity, addRestarts, astrogateActivity, herdrActivity, needsPrompt, type PendingRestart, readRestarts, restartCommand, SERVICE_LABEL, SERVICE_ORDER, writeRestarts } from "./restarts.ts";
41
42
  import {
42
43
  arcaneServerVersion,
@@ -155,6 +156,9 @@ interface MediaRun {
155
156
  const MEDIA_MESSAGE_CACHE = 100;
156
157
  /** Upper bound for one media wrapper call from Discord; a single add or list takes seconds. */
157
158
  const MEDIA_TIMEOUT_MS = 3 * 60_000;
159
+ /** The weekly picks read TMDB recommendations for every library title; the wrapper stops trendarr after 12 minutes. */
160
+ const PICKS_TIMEOUT_MS = 15 * 60_000;
161
+ const PICKS_CALLER = "media-picks";
158
162
  const EPHEMERAL = 64;
159
163
  /** The release Pi has installed: the package this bridge runs from, read from disk so an update shows at once. */
160
164
  const PACKAGE_JSON = fileURLToPath(new URL("../../package.json", import.meta.url));
@@ -485,26 +489,63 @@ class Bridge {
485
489
  const daily = reportSchedule(this.config, "daily");
486
490
  for (const schedule of this.config.reports) {
487
491
  if (this.reportsRunning.has(schedule.report)) continue;
488
- if (daily && schedule.report !== "daily") continue;
489
- const { due, date } = isDue(schedule, readReportState(schedule.report), new Date(), schedule.report === "security-weekly" ? MONDAY : undefined);
492
+ if (daily && MORNING_REPORTS.includes(schedule.report)) continue;
493
+ const weekday = schedule.report === "security-weekly" ? MONDAY : schedule.report === "media-weekly" ? FRIDAY : undefined;
494
+ const { due, date } = isDue(schedule, readReportState(schedule.report), new Date(), weekday);
490
495
  if (!due) continue;
491
496
  this.reportsRunning.add(schedule.report);
492
497
  const run: Promise<unknown> =
493
498
  schedule.report === "daily"
494
499
  ? this.dailyRun(schedule, date)
495
- : schedule.report === "arcane"
496
- ? this.arcaneReport(schedule, date)
497
- : schedule.report === "tools"
498
- ? this.toolsReport(schedule, date)
499
- : schedule.report === "security"
500
- ? this.security.dailyReport(schedule, date)
501
- : this.security.weeklyReport(schedule, date);
500
+ : schedule.report === "media-weekly"
501
+ ? this.mediaPicks(schedule, date)
502
+ : schedule.report === "arcane"
503
+ ? this.arcaneReport(schedule, date)
504
+ : schedule.report === "tools"
505
+ ? this.toolsReport(schedule, date)
506
+ : schedule.report === "security"
507
+ ? this.security.dailyReport(schedule, date)
508
+ : this.security.weeklyReport(schedule, date);
502
509
  void run
503
510
  .catch((err) => log(`${schedule.report} report ${date}: ${err instanceof Error ? err.message : String(err)}`))
504
511
  .finally(() => this.reportsRunning.delete(schedule.report));
505
512
  }
506
513
  }
507
514
 
515
+ /**
516
+ * The weekly media picks through the media wrapper, without a model: TMDB
517
+ * recommendations for the library that pass the IMDb thresholds, never a
518
+ * dismissed title nor one shown in the last six months. The owners are
519
+ * tagged when there are picks.
520
+ */
521
+ private async mediaPicks(schedule: ReportSchedule, date: string): Promise<void> {
522
+ if (!this.specialists().names.includes(MEDIA)) {
523
+ log("media picks: the media specialist is not configured; no picks");
524
+ return;
525
+ }
526
+ log(`media picks ${date}: running media recommend`);
527
+ let picks: Picks | null = null;
528
+ try {
529
+ picks = parsePicks(JSON.parse(await this.runEntry(MEDIA, PICKS_CALLER, picksArgs(readPicksState(), date), PICKS_TIMEOUT_MS)));
530
+ if (!picks) throw new Error("recommend returned an unexpected answer");
531
+ } catch (err) {
532
+ log(`media picks ${date}: check failed: ${err instanceof Error ? err.message.slice(0, 500) : String(err)}`);
533
+ }
534
+ if (this.stopping) return;
535
+ const label = new Intl.DateTimeFormat("en-GB", { timeZone: schedule.timeZone, weekday: "short", day: "numeric", month: "short" }).format(new Date());
536
+ writeReportState("media-weekly", { date, status: "sending" });
537
+ if (!picks) {
538
+ const posted = await this.rest.createMessage(schedule.channelId, { content: picksFailureText(label) });
539
+ writeReportState("media-weekly", { date, status: "failed", messageId: posted.id });
540
+ return;
541
+ }
542
+ const tagged = picks.movies.length + picks.series.length > 0;
543
+ const posted = await this.rest.createComponentsMessage(schedule.channelId, picksMessage(picks, label, this.config.owners), tagged ? this.config.owners : undefined);
544
+ writePicksState(withSuggested(readPicksState(), picks, date));
545
+ writeReportState("media-weekly", { date, status: "sent", messageId: posted.id });
546
+ log(`media picks ${date}: ${picks.movies.length} movie(s), ${picks.series.length} series`);
547
+ }
548
+
508
549
  /**
509
550
  * The Arcane Daily Report through the specialist wrapper, without a model:
510
551
  * one section per stack with updates, a release-notes review for every
@@ -1377,6 +1418,31 @@ class Bridge {
1377
1418
  .finally(() => this.untrackMedia(interaction));
1378
1419
  }
1379
1420
 
1421
+ /** Not interested on a weekly pick: the title never comes back, unlike an ignored one, and only that button changes. */
1422
+ private async onDismissButton(interaction: Interaction, customId: string): Promise<void> {
1423
+ const target = parseNoButton(customId);
1424
+ const message = interaction.message;
1425
+ if (!target || !message) {
1426
+ await this.rest.ephemeralReply(interaction.id, interaction.token, "This button is no longer active.");
1427
+ return;
1428
+ }
1429
+ const userId = interaction.member?.user?.id ?? interaction.user?.id ?? "";
1430
+ if (!(await this.mediaAllowed(interaction, userId))) return;
1431
+ await this.rest.deferUpdate(interaction.id, interaction.token);
1432
+ const app = this.config.applicationId;
1433
+ await this.mediaClicks
1434
+ .run(message.id, async () => {
1435
+ const current = this.mediaMessages.get(message.id) ?? message.components ?? [];
1436
+ if (!hasActiveButton(current, customId)) return;
1437
+ writePicksState(withDismissed(readPicksState(), target.imdbId, new Date().toISOString().slice(0, 10)));
1438
+ const next = applyOutcome(current, customId, DISMISSED);
1439
+ await this.rest.editOriginal(app, interaction.token, { components: next });
1440
+ this.rememberMediaMessage(message.id, next);
1441
+ log(`media picks: ${target.imdbId} dismissed by ${userId}`);
1442
+ })
1443
+ .catch((err) => log(`media picks: dismissing ${target.imdbId} failed: ${err instanceof Error ? err.message : String(err)}`));
1444
+ }
1445
+
1380
1446
  /** Replied-to and forwarded messages to show the specialist; a bot message only when the resumed conversation does not already hold it. */
1381
1447
  private quotesFor(message: IncomingMessage, inContext: (id: string) => boolean): Quote[] {
1382
1448
  const quotes: Quote[] = [];
@@ -1559,6 +1625,10 @@ class Bridge {
1559
1625
  }
1560
1626
  if (interaction.type !== 3) return;
1561
1627
  const customId = interaction.data?.custom_id ?? "";
1628
+ if (customId.startsWith("media:no:")) {
1629
+ await this.onDismissButton(interaction, customId);
1630
+ return;
1631
+ }
1562
1632
  if (customId.startsWith("media:")) {
1563
1633
  await this.onMediaButton(interaction, customId);
1564
1634
  return;
@@ -0,0 +1,94 @@
1
+ import { mkdtempSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
5
+ import { validateReports } from "./config.ts";
6
+ import { applyOutcome, countComponents, hasActiveButton } from "./media.ts";
7
+ import { DISMISSED, type Pick, parseNoButton, parsePicks, pickText, picksArgs, picksMessage, readPicksState, withDismissed, withSuggested, writePicksState } from "./media-picks.ts";
8
+ import { FRIDAY, isDue } from "./reports.ts";
9
+
10
+ const OWNER = "178096425509453824";
11
+
12
+ function pick(over: Partial<Pick>): Pick {
13
+ return { title: "Arrival", year: 2016, imdb_rating: "7.9", imdb_votes: "812,345", imdb_id: "tt2543164", matches: 4, because: ["Dune", "Interstellar", "Contact"], ...over };
14
+ }
15
+
16
+ describe("weekly picks", () => {
17
+ it("keeps only well-formed picks with an IMDb id, three per kind", () => {
18
+ const raw = { movies: [pick({}), { title: "No id", imdb_id: null, matches: 1, because: [] }, pick({ imdb_id: "tt1" }), pick({ imdb_id: "tt2" }), pick({ imdb_id: "tt3" })], series: [], warnings: ["Sonarr slow", 3] };
19
+ const picks = parsePicks(raw);
20
+ expect(picks?.movies.map((p) => p.imdb_id)).toEqual(["tt2543164", "tt1", "tt2"]);
21
+ expect(picks?.warnings).toEqual(["Sonarr slow"]);
22
+ expect(parsePicks({ movies: [] })).toBeNull();
23
+ });
24
+
25
+ it("excludes dismissed titles and titles shown in the last six months", () => {
26
+ expect(picksArgs({ suggested: {}, dismissed: {} }, "2026-10-30")).toEqual(["recommend", "--max-entries", "3"]);
27
+ expect(picksArgs({ suggested: { tt2: "2026-10-30", tt1: "2026-10-30" }, dismissed: { tt1: "2026-10-31", bad: "x" } }, "2026-10-30")).toEqual(["recommend", "--max-entries", "3", "--exclude", "tt1,tt2"]);
28
+ const old = { suggested: { tt3: "2026-04-30", tt4: "2026-05-02" }, dismissed: { tt5: "2025-01-01" } };
29
+ expect(picksArgs(old, "2026-10-30")).toEqual(["recommend", "--max-entries", "3", "--exclude", "tt4,tt5"]);
30
+ });
31
+
32
+ it("writes the reason from the library titles", () => {
33
+ expect(pickText(1, pick({}))).toBe("1. [Arrival (2016)](<https://www.imdb.com/title/tt2543164/>) — IMDb 7.9 · 812,345 votes\n-# because you have Dune, Interstellar, Contact and 1 more");
34
+ expect(pickText(2, pick({ matches: 2, because: ["Dune", "Contact"], imdb_votes: null }))).toBe("2. [Arrival (2016)](<https://www.imdb.com/title/tt2543164/>) — IMDb 7.9\n-# because you have Dune and Contact");
35
+ expect(pickText(3, pick({ matches: 1, because: ["Blade_Runner"], year: null }))).toContain("[Arrival](<");
36
+ expect(pickText(3, pick({ matches: 1, because: ["Blade_Runner"] }))).toContain("because you have Blade\\_Runner");
37
+ });
38
+
39
+ it("lays out both kinds with Add and Not interested, tagging the owners only when there are picks", () => {
40
+ const picks = { movies: [pick({}), pick({ imdb_id: "tt1" }), pick({ imdb_id: "tt2" })], series: [pick({ imdb_id: "tt3" }), pick({ imdb_id: "tt4" }), pick({ imdb_id: "tt5" })], warnings: ["Radarr slow"] };
41
+ const message = picksMessage(picks, "Fri 30 Oct", [OWNER]);
42
+ expect(message[0]).toEqual({ type: 10, content: `**🍿 Weekly picks** · Fri 30 Oct · <@${OWNER}>` });
43
+ expect(message[3]).toEqual({
44
+ type: 1,
45
+ components: [
46
+ { type: 2, style: 1, label: "Add", custom_id: "media:add:movie:tt2543164:1" },
47
+ { type: 2, style: 2, label: "Not interested", custom_id: "media:no:movie:tt2543164" },
48
+ ],
49
+ });
50
+ expect(JSON.stringify(message)).toContain("media:add:series:tt5:3");
51
+ expect(countComponents(message)).toBe(28);
52
+ expect(picksMessage({ movies: [], series: [], warnings: [] }, "Fri 30 Oct", [OWNER])).toEqual([{ type: 10, content: "**🍿 Weekly picks** · Fri 30 Oct · nothing new this week" }]);
53
+ expect(JSON.stringify(picksMessage({ movies: [pick({})], series: [], warnings: [] }, "Fri 30 Oct", [OWNER]))).toContain("_none this week_");
54
+ });
55
+
56
+ it("turns only the clicked Not interested button into a disabled one", () => {
57
+ const message = picksMessage({ movies: [pick({})], series: [], warnings: [] }, "Fri 30 Oct", [OWNER]);
58
+ expect(parseNoButton("media:no:movie:tt2543164")).toEqual({ kind: "movie", imdbId: "tt2543164" });
59
+ expect(parseNoButton("media:no:movie:tt2543164:1")).toBeNull();
60
+ const next = applyOutcome(message, "media:no:movie:tt2543164", DISMISSED);
61
+ expect(hasActiveButton(next, "media:no:movie:tt2543164")).toBe(false);
62
+ expect(hasActiveButton(next, "media:add:movie:tt2543164:1")).toBe(true);
63
+ });
64
+
65
+ it("posts on Fridays only", () => {
66
+ const schedule = { time: "06:00", timeZone: "Europe/Paris" };
67
+ expect(isDue(schedule, null, new Date("2026-10-30T05:00:00Z"), FRIDAY)).toEqual({ due: true, date: "2026-10-30" });
68
+ expect(isDue(schedule, null, new Date("2026-10-30T04:59:00Z"), FRIDAY).due).toBe(false);
69
+ expect(isDue(schedule, null, new Date("2026-10-31T05:00:00Z"), FRIDAY).due).toBe(false);
70
+ const errors: string[] = [];
71
+ expect(validateReports([{ report: "media-weekly", channelId: "1549868953323573409", time: "06:00", timeZone: "Europe/Paris" }], errors)).toHaveLength(1);
72
+ expect(errors).toEqual([]);
73
+ });
74
+ });
75
+
76
+ describe("picks state", () => {
77
+ let dir = "";
78
+ beforeEach(() => {
79
+ dir = mkdtempSync(join(tmpdir(), "astro-picks-"));
80
+ process.env.ASTRO_DISCORD_DIR = dir;
81
+ });
82
+ afterEach(() => {
83
+ delete process.env.ASTRO_DISCORD_DIR;
84
+ rmSync(dir, { recursive: true, force: true });
85
+ });
86
+
87
+ it("keeps the last date a title was shown and the first date it was dismissed", () => {
88
+ expect(readPicksState()).toEqual({ suggested: {}, dismissed: {} });
89
+ const picks = { movies: [pick({})], series: [pick({ imdb_id: "tt3" })], warnings: [] };
90
+ writePicksState(withDismissed(withSuggested(readPicksState(), picks, "2026-10-30"), "tt3", "2026-10-30"));
91
+ const again = withDismissed(withSuggested(readPicksState(), picks, "2026-11-06"), "tt3", "2026-11-06");
92
+ expect(again).toEqual({ suggested: { tt2543164: "2026-11-06", tt3: "2026-11-06" }, dismissed: { tt3: "2026-10-30" } });
93
+ });
94
+ });
@@ -0,0 +1,156 @@
1
+ import { readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { configDir } from "./config.ts";
4
+ import { escapeDiscord, type MediaKind, type Outcome } from "./media.ts";
5
+ import type { MessageComponent } from "./rest.ts";
6
+
7
+ /** Picks per kind: the header, two kinds of 1 + 3 × 4 components, and a warning line make 28 of Discord's 40 components. */
8
+ export const PICKS = 3;
9
+
10
+ const IMDB_ID = /^tt\d{1,12}$/;
11
+ const PRIMARY = 1;
12
+ const SECONDARY = 2;
13
+
14
+ /** One entry of trendarr's `recommend` answer. */
15
+ export interface Pick {
16
+ title: string;
17
+ year: number | null;
18
+ imdb_rating: string | null;
19
+ imdb_votes: string | null;
20
+ imdb_id: string;
21
+ /** How many library titles TMDB recommends it for. */
22
+ matches: number;
23
+ /** Some of those library titles, for the reason line. */
24
+ because: string[];
25
+ }
26
+
27
+ export interface Picks {
28
+ movies: Pick[];
29
+ series: Pick[];
30
+ warnings: string[];
31
+ }
32
+
33
+ /** A pick nobody acted on may come back after this many days; a dismissed one never does. */
34
+ export const SUGGESTED_HOLD_DAYS = 182;
35
+
36
+ /** Titles the weekly picks showed (last local date) or an owner dismissed (first local date), by IMDb id. */
37
+ export interface PicksState {
38
+ suggested: Record<string, string>;
39
+ dismissed: Record<string, string>;
40
+ }
41
+
42
+ function isPick(value: unknown): value is Pick {
43
+ const p = value as Partial<Pick> | null;
44
+ return !!p && typeof p.title === "string" && typeof p.imdb_id === "string" && IMDB_ID.test(p.imdb_id) && typeof p.matches === "number" && Array.isArray(p.because) && p.because.every((b) => typeof b === "string");
45
+ }
46
+
47
+ /** The media wrapper's `recommend` answer, or null when it is not one. */
48
+ export function parsePicks(value: unknown): Picks | null {
49
+ const r = value as { movies?: unknown; series?: unknown; warnings?: unknown } | null;
50
+ if (!r || !Array.isArray(r.movies) || !Array.isArray(r.series)) return null;
51
+ const warnings = Array.isArray(r.warnings) ? r.warnings.filter((w): w is string => typeof w === "string") : [];
52
+ return { movies: r.movies.filter(isPick).slice(0, PICKS), series: r.series.filter(isPick).slice(0, PICKS), warnings };
53
+ }
54
+
55
+ /** Wrapper arguments: dismissed titles and titles shown in the last six months stay out. */
56
+ export function picksArgs(state: PicksState, today: string): string[] {
57
+ const cutoff = Date.parse(today) - SUGGESTED_HOLD_DAYS * 86_400_000;
58
+ const recent = Object.entries(state.suggested).filter(([, date]) => Date.parse(date) > cutoff).map(([id]) => id);
59
+ const seen = [...new Set([...recent, ...Object.keys(state.dismissed)])].filter((id) => IMDB_ID.test(id)).sort();
60
+ return ["recommend", "--max-entries", String(PICKS), ...(seen.length > 0 ? ["--exclude", seen.join(",")] : [])];
61
+ }
62
+
63
+ function becauseLine(pick: Pick): string {
64
+ const names = pick.because.map(escapeDiscord);
65
+ const more = pick.matches - names.length;
66
+ if (names.length === 0) return "recommended from your library";
67
+ if (more > 0) return `because you have ${names.join(", ")} and ${more} more`;
68
+ return `because you have ${names.length === 1 ? names[0] : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`}`;
69
+ }
70
+
71
+ export function pickText(rank: number, pick: Pick): string {
72
+ const label = escapeDiscord(`${pick.title}${pick.year === null ? "" : ` (${pick.year})`}`);
73
+ const rating = pick.imdb_rating === null ? "" : ` — IMDb ${pick.imdb_rating}`;
74
+ const votes = pick.imdb_votes === null ? "" : ` · ${pick.imdb_votes} votes`;
75
+ return `${rank}. [${label}](<https://www.imdb.com/title/${pick.imdb_id}/>)${rating}${votes}\n-# ${becauseLine(pick)}`;
76
+ }
77
+
78
+ function pickRow(kind: MediaKind, rank: number, pick: Pick): MessageComponent {
79
+ return {
80
+ type: 1,
81
+ components: [
82
+ { type: 2, style: PRIMARY, label: "Add", custom_id: `media:add:${kind}:${pick.imdb_id}:${rank}` },
83
+ { type: 2, style: SECONDARY, label: "Not interested", custom_id: `media:no:${kind}:${pick.imdb_id}` },
84
+ ],
85
+ };
86
+ }
87
+
88
+ /**
89
+ * The weekly message: a header that tags the owners when there is something
90
+ * new, then the movies and the series, each with its reason line, an Add
91
+ * button (the same as `/trending`), and a Not interested button.
92
+ */
93
+ export function picksMessage(picks: Picks, date: string, owners: readonly string[]): MessageComponent[] {
94
+ const any = picks.movies.length + picks.series.length > 0;
95
+ const head = any ? `**🍿 Weekly picks** · ${date} · ${owners.map((id) => `<@${id}>`).join(" ")}` : `**🍿 Weekly picks** · ${date} · nothing new this week`;
96
+ const components: MessageComponent[] = [{ type: 10, content: head }];
97
+ if (!any) return withWarnings(components, picks.warnings);
98
+ for (const [kind, title, list] of [["movie", "**🎬 Movies**", picks.movies], ["series", "**📺 Series**", picks.series]] as const) {
99
+ components.push({ type: 10, content: title });
100
+ if (list.length === 0) components.push({ type: 10, content: "_none this week_" });
101
+ list.forEach((pick, i) => components.push({ type: 10, content: pickText(i + 1, pick) }, pickRow(kind, i + 1, pick)));
102
+ }
103
+ return withWarnings(components, picks.warnings);
104
+ }
105
+
106
+ function withWarnings(components: MessageComponent[], warnings: readonly string[]): MessageComponent[] {
107
+ if (warnings.length > 0) components.push({ type: 10, content: `-# ⚠️ ${warnings.join(" · ").slice(0, 500)}` });
108
+ return components;
109
+ }
110
+
111
+ export function picksFailureText(date: string): string {
112
+ return `**🍿 Weekly picks** · ${date} · the recommendation check failed, so there are no picks this week. The bridge log on Cortex has the reason.`;
113
+ }
114
+
115
+ /** What Not interested turns into; the record in media-picks.json keeps the title out for good. */
116
+ export const DISMISSED: Outcome = { label: "Not interested", style: SECONDARY, disabled: true };
117
+
118
+ const NO_ID = /^media:no:(movie|series):(tt\d{1,12})$/;
119
+
120
+ export function parseNoButton(customId: string): { kind: MediaKind; imdbId: string } | null {
121
+ const m = NO_ID.exec(customId);
122
+ return m ? { kind: m[1] as MediaKind, imdbId: m[2] } : null;
123
+ }
124
+
125
+ export function emptyPicksState(): PicksState {
126
+ return { suggested: {}, dismissed: {} };
127
+ }
128
+
129
+ function statePath(): string {
130
+ return join(configDir(), "media-picks.json");
131
+ }
132
+
133
+ export function readPicksState(): PicksState {
134
+ try {
135
+ const raw = JSON.parse(readFileSync(statePath(), "utf-8")) as Partial<PicksState>;
136
+ return { suggested: raw.suggested ?? {}, dismissed: raw.dismissed ?? {} };
137
+ } catch {
138
+ return emptyPicksState();
139
+ }
140
+ }
141
+
142
+ export function writePicksState(state: PicksState): void {
143
+ const path = statePath();
144
+ writeFileSync(`${path}.tmp`, `${JSON.stringify(state)}\n`, { mode: 0o600 });
145
+ renameSync(`${path}.tmp`, path);
146
+ }
147
+
148
+ export function withSuggested(state: PicksState, picks: Picks, date: string): PicksState {
149
+ const suggested = { ...state.suggested };
150
+ for (const pick of [...picks.movies, ...picks.series]) suggested[pick.imdb_id] = date;
151
+ return { ...state, suggested };
152
+ }
153
+
154
+ export function withDismissed(state: PicksState, imdbId: string, date: string): PicksState {
155
+ return { ...state, dismissed: { ...state.dismissed, [imdbId]: state.dismissed[imdbId] ?? date } };
156
+ }
@@ -19,6 +19,7 @@ export function zonedNow(timeZone: string, now: Date): { date: string; minutes:
19
19
 
20
20
  const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
21
21
  export const MONDAY = 1;
22
+ export const FRIDAY = 5;
22
23
 
23
24
  /** Local day of the week in a time zone, 0 for Sunday. */
24
25
  export function zonedWeekday(timeZone: string, now: Date): number {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrofoundry/pi-astro",
3
- "version": "0.39.1",
3
+ "version": "0.40.0",
4
4
  "description": "Personal pi customizations (extensions, subagents, skills, prompts, themes) for the pi coding agent.",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -14,6 +14,7 @@ description: How the media specialist finds trending titles, resolves and adds m
14
14
  | `["trending"]` | TMDB weekly trending, movies and series, 10 each, IMDb rating, `in_library` |
15
15
  | `["trending", "--type", "movies", "--min-rating", "7", "--max-entries", "20"]` | options: `--type movies|series`, `--min-rating 0..10` (default 6.5, movies only; `0` keeps all), `--max-entries 1..50` |
16
16
  | `["search", "breaking bad", "--type", "series"]` | title search, full or partial, ordered by TMDB relevance; `--type`, `--max-entries` |
17
+ | `["recommend", "--max-entries", "3"]` | titles TMDB recommends for the most library titles, not in the library, released, IMDb 7.0+ with 5,000 votes (movies) or 2,000 (series); `--type`, `--max-entries`, `--exclude tt1,tt2`. Reads every library title, so it takes minutes |
17
18
  | `["add-movies", "tt1160419", "tt0468569"]` | add to Radarr and search (at most 20 IDs) |
18
19
  | `["add-series", "tt0903747"]` | IMDb → TVDB through TMDB, add to Sonarr and search |
19
20
  | `["sabnzbd", "status"]`, `["sabnzbd", "pause"]`, `["sabnzbd", "resume"]` | queue pause state; `pause` and `resume` act, then report the new state |
@@ -21,6 +22,7 @@ description: How the media specialist finds trending titles, resolves and adds m
21
22
  ## Output
22
23
 
23
24
  - `trending`, `search`: `{ "movies": [...], "series": [...], "warnings": [...] }`. Each item: `rank`, `title`, `year`, `imdb_rating`, `imdb_votes`, `rotten_tomatoes`, `metascore`, `genres`, `imdb_id`, `tmdb_id`, `tvdb_id`, `in_library`; trending items also `popularity`. Ratings are strings or null.
25
+ - `recommend`: the same shape plus `matches` (how many library titles lead to it) and `because` (up to three of them), ordered by `matches`.
24
26
  - `in_library: null` means Radarr or Sonarr could not answer or the series has no TVDB mapping: it is uncertainty, not absence. Try the add; its result decides.
25
27
  - `add-movies`, `add-series`: `{ "results": [{ "imdb_id", "title", "status", "detail" }], "sabnzbd_paused": true|false|null, "warnings": [...] }`. `status` is `added` (search started), `already_exists`, `not_found` (nothing added), or `error` (read `detail`). The tool succeeds even when an ID fails; always read each status.
26
28
  - `sabnzbd`: `{ "sabnzbd_paused": true|false }`.
@@ -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 | API token: `guests`, `guest`, `get <path>`, `tasks`; `start`, `shutdown|reboot|stop --confirm`; snapshots create, delete, rollback; `set` of CPU, memory, options, network. Pulsar key: `host-status`, `host-journal`, `updates`, `guest-exec <vmid> <status|journal|df|updates>` |
15
15
  | `astro.inference` | llama.cpp on Nexus, Europa health | `nexus-status|start|stop|restart|log|disk`; `europa-health` |
16
- | `astro.media` | trendarr over TMDB, OMDb, and the `media` project on VM 100 (Radarr, Sonarr, SABnzbd) | `trending`, `search`, `add-movies`, `add-series` (at most 20 IMDb IDs), `sabnzbd status|pause|resume`; always trendarr's JSON plus its warnings |
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`; always trendarr's JSON plus its warnings |
17
17
 
18
18
  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.
19
19
 
@@ -141,7 +141,7 @@ Check: `sudo -n -u specialist -H /usr/local/bin/specialist-cli arcane --caller t
141
141
  The `astro-discord` extension gives Discord users access to the specialists from a channel. It runs in a headless Pi host on Cortex (LaunchAgent `com.astrofoundry.astro-discord`, user `cortex`), never in interactive sessions.
142
142
 
143
143
  - Channels are configured one by one (`channels.<id>`): `trigger` is `always` (every message that names a specialist counts) or `mention` (only messages that start with `@Cortex` or reply to the bot); `specialists` is `*` or a list. A channel with one specialist needs no prefix: every message there is a task for it. In a channel with several, `dns list the zones` names the specialist; an addressed message without a name gets a reply asking for one. Threads inherit their parent channel's entry; unlisted channels are ignored. The bot replies at once with "<specialist> is working on your task" and shows the typing indicator until the answer replaces that reply. Reactions on your message: ⏳ running, 🔒 waiting for an owner's approval, ✅ done, ❌ failed. `help` shows the specialists you may use in that channel and the commands (`status` lists running tasks; owners in the admin channel also see the `config` commands). Each channel and specialist has one conversation: a reply to the bot's answer, or another task for that specialist within 30 minutes, continues it with everything the specialist saw before; otherwise a new one starts, and a task beginning with `new` forces that. Replied-to and forwarded messages (text, embeds, attachment names) travel with the task, so "check this" on a forwarded alert works. Image attachments on the message or on what it quotes (up to 4, 8 MiB each) are downloaded and passed to the specialist, which sees them; other file types are named only. Sessions live under `~/.config/astro-discord/sessions/<specialist>/` and are deleted after 7 days. Long answers arrive as a `.md` attachment. When the bridge restarts, open approval requests are marked cancelled and running tasks interrupted in Discord; ask again. Scheduled reports are a list in the config, one entry per report: `"reports": [{ "report": "arcane", "channelId": "<id>", "time": "06:00", "timeZone": "Europe/Madrid" }, { "report": "tools", "channelId": "<admin channel id>", "time": "06:00", "timeZone": "Europe/Madrid" }]` (the earlier single `dailyReport` key is refused; move it into the list). The Arcane report posts an "Arcane Daily Report:" message every morning from a fresh `update-report`: one section per stack with updates, each service as current to target version with the kind of change, a release-notes verdict on every major version, and an Update button per stack that only owners can press (it runs `arcane stack-update <stack>`; the button turns into the outcome and the reason arrives as a note only the clicker sees). Stacks held in `update-holds.json` at the root of the arcane GitOps repository (`{ "supabase": "coordinated release: review first" }`) show the reason and get no button. Replying to the report asks the arcane specialist with the report as context. The tools report posts "Cortex Tools Report:": every tool on Cortex with a newer version (Homebrew packages installed on request and casks, Pi, pi-astro, and through `specialist-install` the wrappers, arcane-cli at the Arcane server's version, trendarr, and the specialist Node at the latest LTS), a release-notes verdict from `astro.release-reviewer` for the tools the specialists build on, an Update button per line, and one Upgrade everything for Homebrew. Only owners can press them; nothing is installed otherwise. After an update that needs it, the bridge, herdr, or Astrogate restarts as soon as nothing runs on it; after a day of waiting, a Restart now button appears. The bridge calls `sudo -n /usr/local/sbin/specialist-install` through the sudoers rule from step 4.
144
- - Media: where the `media` specialist is present (`config channel <#channel> always media`), `/trending [type] [min_rating] [count]`, `/search <title> [type]`, and `/downloads <status|pause|resume|unpause>` run the wrapper without a model. Lists arrive as two messages, Movies and Series, each title with a button beside it: **Add** adds it at once and turns into Added, In library, or Not found (Retry after a failure); a greyed-out In library or No IMDb ID button needs nothing. Notes such as "downloads are paused" go only to the user who clicked. Owners and `access.media` users may use them; anyone else gets a refusal only they see, and in a channel without `media` the bot names the channels that have it. Plain messages in the channel still go to the agent, for requests by name ("add the new Dune"). At startup the bridge sets the three commands as the application's global commands (servers only).
144
+ - Media: where the `media` specialist is present (`config channel <#channel> always media`), `/trending [type] [min_rating] [count]`, `/search <title> [type]`, and `/downloads <status|pause|resume|unpause>` run the wrapper without a model. Lists arrive as two messages, Movies and Series, each title with a button beside it: **Add** adds it at once and turns into Added, In library, or Not found (Retry after a failure); a greyed-out In library or No IMDb ID button needs nothing. Notes such as "downloads are paused" go only to the user who clicked. Owners and `access.media` users may use them; anyone else gets a refusal only they see, and in a channel without `media` the bot names the channels that have it. Plain messages in the channel still go to the agent, for requests by name ("add the new Dune"). A `media-weekly` report entry posts the weekly picks there every Friday at its time: three movies and three series from `recommend`, each with the library titles that led to it, an Add button, and a Not interested button; the owners are tagged when there is something new. A pick nobody acts on stays out for six months; Not interested keeps it out for good (`media-picks.json`). At startup the bridge sets the three commands as the application's global commands (servers only).
145
145
  - Arcane manager: when the morning Arcane Daily Report shows a newer manager release, the `arcane` section carries an **Upgrade Arcane to vX** button. Only an owner's click on the newest report runs `arcane manager-upgrade <version>` through the entry point (one at a time, counted as open work so no bridge restart interrupts it); the button turns into the outcome, a reply gives the result, and a successful upgrade installs the matching `arcane-cli` with `specialist-install`.
146
146
  - Access: `owners` may use every specialist and decide approvals; `access.<specialist>` lists extra users for that specialist; everyone else gets no reply. Owners change the configuration from the admin channel (`adminChannelId`) without a shell: `config show`, `config channel <#channel> <always|mention> <*|dns,edge>`, `config channel <#channel> remove`, `config access <specialist> add|remove <@user>`; the bot writes `~/.config/astro-discord/config.json` on Cortex, which is also editable by hand and re-read on every message. Deny the bot's role View Channel on channels it must never read; that is the boundary the map cannot provide.
147
147
  - Approvals: a risky call (anything with `--confirm`, plus writes such as record or zone deletes, Zitadel changes, Pomerium deploys, service restarts, and on Arcane destructive actions: `down`, deletes, prunes, image, volume, or network removal, `system upgrade`, `gitops delete`, plus `manager-upgrade`, `manager-rollback`, `host db-restore`, and the Radarr host-config reads; `stack-update` asks only across a major version, through its `--confirm`; an owner's Update click on the report needs no approval; help lookups never ask) pauses the specialist and posts Approve/Deny buttons; only owners' clicks count; no decision within `approvalTimeoutMinutes` denies it. The specialist then reports the denial. Ambiguous tasks get a question back instead of an action.
@@ -79,6 +79,8 @@ function readMediaSecrets(): MediaSecrets {
79
79
 
80
80
  /** Most IDs one add call takes; a batch runs one Radarr or Sonarr lookup and add per ID. */
81
81
  export const MAX_ADD_IDS = 20;
82
+ /** Most IDs `recommend --exclude` takes: the weekly picks pass every title they ever showed or the owner dismissed. */
83
+ export const MAX_EXCLUDE_IDS = 5000;
82
84
  const MAX_ENTRIES = 50;
83
85
  const MAX_QUERY = 200;
84
86
  const MINUTE = 60_000;
@@ -99,6 +101,9 @@ const HELP = `media specialist (trendarr: TMDB trending, OMDb ratings, Radarr an
99
101
  TMDB weekly trending with IMDb ratings and in_library; movies under 6.5 are dropped unless --min-rating 0
100
102
  search <query> [--type movies|series] [--max-entries N]
101
103
  title search, ordered by relevance; use imdb_id from here or from trending for adds
104
+ recommend [--type movies|series] [--max-entries N] [--exclude tt1,tt2]
105
+ titles TMDB recommends for the most library titles, not in the library, released, IMDb 7.0+
106
+ with 5,000 votes (movies) or 2,000 (series); each with matches and because (library titles)
102
107
  add-movies <imdbId...> add to Radarr monitored and start a search (at most ${MAX_ADD_IDS} IDs)
103
108
  add-series <imdbId...> add to Sonarr monitored and start a search (at most ${MAX_ADD_IDS} IDs)
104
109
  sabnzbd status|pause|resume read or toggle the SABnzbd queue pause state
@@ -164,6 +169,15 @@ export function parseImdbIds(args: string[]): string[] {
164
169
  return ids;
165
170
  }
166
171
 
172
+ /** IMDb IDs for `recommend --exclude`, comma separated; duplicates collapse. */
173
+ export function parseExclude(value: string): string[] {
174
+ const ids = [...new Set(value.split(",").map((p) => p.trim()).filter((p) => p.length > 0))];
175
+ const bad = ids.find((id) => !IMDB_ID.test(id));
176
+ if (bad !== undefined) throw new UsageError(`not an IMDb id: ${bad.slice(0, 40)} (expected tt followed by digits)`);
177
+ if (ids.length > MAX_EXCLUDE_IDS) throw new UsageError(`--exclude takes at most ${MAX_EXCLUDE_IDS} IDs`);
178
+ return ids;
179
+ }
180
+
167
181
  /** The trendarr argv for one wrapper call, with `--json` always last. */
168
182
  export function buildTrendarrCall(args: string[]): TrendarrCall {
169
183
  const [name, ...rest] = args;
@@ -181,6 +195,21 @@ export function buildTrendarrCall(args: string[]): TrendarrCall {
181
195
  if (/\p{Cc}/u.test(query)) throw new UsageError("query must not contain control characters");
182
196
  return { argv: ["search", query, ...flags, "--json"], kind: "list", timeoutMs: 2 * MINUTE };
183
197
  }
198
+ if (name === "recommend") {
199
+ const listArgs: string[] = [];
200
+ let exclude: string[] = [];
201
+ for (let i = 0; i < rest.length; i++) {
202
+ if (rest[i] === "--exclude") {
203
+ exclude = parseExclude(option(rest, i, "--exclude"));
204
+ i++;
205
+ } else {
206
+ listArgs.push(rest[i]);
207
+ }
208
+ }
209
+ const { flags, words } = parseListFlags(listArgs, false);
210
+ if (words.length > 0) throw new UsageError(`recommend takes no words: ${words.join(" ").slice(0, 60)}`);
211
+ return { argv: ["recommend", ...flags, ...(exclude.length > 0 ? ["--exclude", exclude.join(",")] : []), "--json"], kind: "list", timeoutMs: 12 * MINUTE };
212
+ }
184
213
  if (name === "add-movies" || name === "add-series") {
185
214
  return { argv: [name, ...parseImdbIds(rest), "--json"], kind: "add", timeoutMs: 10 * MINUTE };
186
215
  }
@@ -8,7 +8,7 @@ import { parseParams, parseRecordFilters, technitiumRequest, command as dnsComma
8
8
  import { buildVpsRemote, command as edgeCommand, isTransientSshFailure, PUBLIC_ROUTES, routeProbe } from "./edge/run.ts";
9
9
  import { API_PREFIXES, buildDmzRemote, validateApiPath, command as identityCommand } from "./identity/run.ts";
10
10
  import { buildInferenceRemote, command as inferenceCommand } from "./inference/run.ts";
11
- import { MAX_ADD_IDS, buildTrendarrCall, interpretRun, parseImdbIds, trendarrConfig, trendarrError, trendarrWarnings, command as mediaCommand } from "./media/run.ts";
11
+ import { MAX_ADD_IDS, MAX_EXCLUDE_IDS, buildTrendarrCall, interpretRun, parseImdbIds, trendarrConfig, trendarrError, trendarrWarnings, command as mediaCommand } from "./media/run.ts";
12
12
  import { ServiceError, UsageError } from "./lib/errors.ts";
13
13
  import { safeRepoPath, safeWritePath } from "./lib/repo.ts";
14
14
  import { POLICY_REQUIRED, buildPulsarRemote, parseQuery, policyWrite, unifiPath, command as networkCommand } from "./network/run.ts";
@@ -594,6 +594,8 @@ describe("media wrapper", () => {
594
594
  expect(buildTrendarrCall(["add-series", "tt0903747"]).argv).toEqual(["add-series", "tt0903747", "--json"]);
595
595
  expect(buildTrendarrCall(["sabnzbd", "unpause"])).toMatchObject({ argv: ["sabnzbd", "resume", "--json"], kind: "queue" });
596
596
  expect(buildTrendarrCall(["sabnzbd", "status"]).argv).toEqual(["sabnzbd", "status", "--json"]);
597
+ expect(buildTrendarrCall(["recommend", "--max-entries", "3", "--exclude", "tt1,tt2, tt1"])).toEqual({ argv: ["recommend", "--max-entries", "3", "--exclude", "tt1,tt2", "--json"], kind: "list", timeoutMs: 720_000 });
598
+ expect(buildTrendarrCall(["recommend", "--type", "series"]).argv).toEqual(["recommend", "--type", "series", "--json"]);
597
599
  });
598
600
 
599
601
  it("refuses anything trendarr would not accept or should not run", () => {
@@ -613,6 +615,11 @@ describe("media wrapper", () => {
613
615
  expect(() => buildTrendarrCall(["sabnzbd", "delete"])).toThrow(/status\|pause\|resume/);
614
616
  expect(() => buildTrendarrCall(["sabnzbd"])).toThrow(/status\|pause\|resume/);
615
617
  expect(() => buildTrendarrCall(["delete-movie", "tt1"])).toThrow(/unknown command/);
618
+ expect(() => buildTrendarrCall(["recommend", "dune"])).toThrow(/no words/);
619
+ expect(() => buildTrendarrCall(["recommend", "--min-rating", "7"])).toThrow(/unknown option/);
620
+ expect(() => buildTrendarrCall(["recommend", "--exclude", "tt1,-rf"])).toThrow(/not an IMDb id/);
621
+ expect(() => buildTrendarrCall(["recommend", "--exclude"])).toThrow(/needs a value/);
622
+ expect(() => buildTrendarrCall(["recommend", "--exclude", Array.from({ length: MAX_EXCLUDE_IDS + 1 }, (_, i) => `tt${i + 1}`).join(",")])).toThrow(/at most/);
616
623
  expect(() => parseImdbIds(["tt12x"])).toThrow(UsageError);
617
624
  expect(() => parseImdbIds([" , "])).toThrow(/at least one/);
618
625
  expect(() => parseImdbIds(Array.from({ length: MAX_ADD_IDS + 1 }, (_, i) => `tt${i + 1}`))).toThrow(/at most/);