@audiofool/moondog 0.4.0-beta.3 → 0.4.0-beta.4

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.
Files changed (93) hide show
  1. package/README.md +19 -8
  2. package/package.json +1 -1
  3. package/scripts/moondog.mjs +95 -103
  4. package/src/core/apple-library-source-status.mjs +64 -18
  5. package/src/core/apple-projection-domain-services.mjs +63 -52
  6. package/src/core/capability-catalog.mjs +18 -2
  7. package/src/core/import-source-history.mjs +28 -0
  8. package/src/core/library-draft.mjs +16 -0
  9. package/src/core/library-names.mjs +12 -0
  10. package/src/core/library-store.mjs +361 -23
  11. package/src/core/listener-avoids.mjs +31 -0
  12. package/src/core/listening-action.mjs +41 -0
  13. package/src/core/listening-moment.mjs +67 -0
  14. package/src/core/listening-now.mjs +69 -28
  15. package/src/core/listening-profile-domain-services.mjs +28 -18
  16. package/src/core/listening-scope.mjs +119 -0
  17. package/src/core/moondog-application.mjs +1003 -267
  18. package/src/core/play-follower.mjs +73 -37
  19. package/src/core/portable-playlist.mjs +125 -0
  20. package/src/core/profile-discovery-draft.mjs +35 -0
  21. package/src/core/track-title.mjs +70 -4
  22. package/src/i18n/import-history.mjs +647 -0
  23. package/src/i18n/messages/de.mjs +3 -3
  24. package/src/i18n/messages/en.mjs +3 -3
  25. package/src/i18n/messages/es.mjs +3 -3
  26. package/src/i18n/messages/fr.mjs +3 -3
  27. package/src/i18n/messages/it.mjs +3 -3
  28. package/src/i18n/messages/ja.mjs +3 -3
  29. package/src/i18n/messages/ko.mjs +3 -3
  30. package/src/i18n/messages/pt.mjs +3 -3
  31. package/src/i18n/messages/zh-Hant.mjs +3 -3
  32. package/src/i18n/messages/zh.mjs +3 -3
  33. package/src/i18n/screen/es.mjs +89 -26
  34. package/src/i18n/screen/ja.mjs +88 -25
  35. package/src/i18n/screen/pt.mjs +89 -26
  36. package/src/i18n/screen/zh.mjs +88 -25
  37. package/src/importers/apple-music-library/import-batch.mjs +64 -32
  38. package/src/importers/apple-music-library/normalize.mjs +36 -6
  39. package/src/importers/apple-music-library/save-time.mjs +17 -0
  40. package/src/importers/zip-reader.mjs +24 -2
  41. package/src/integrations/apple-music/catalog-playlist-reader.mjs +111 -0
  42. package/src/integrations/apple-music/catalog.mjs +84 -25
  43. package/src/integrations/apple-music/song-id.mjs +13 -0
  44. package/src/integrations/apple-music/terminal-preview-player.mjs +154 -44
  45. package/src/integrations/listenbrainz/history-file.mjs +63 -35
  46. package/src/integrations/netease/ncm-cli-player.mjs +355 -68
  47. package/src/integrations/netease/queue-occurrence.mjs +138 -0
  48. package/src/integrations/playlist-links.mjs +93 -30
  49. package/src/integrations/public-playlists.mjs +21 -15
  50. package/src/integrations/spotify/account-data-history.mjs +9 -10
  51. package/src/integrations/spotify/account-data-profile.mjs +1 -0
  52. package/src/integrations/spotify/extended-streaming-history.mjs +57 -52
  53. package/src/integrations/spotify/history-archive.mjs +8 -18
  54. package/src/integrations/spotify/library-snapshot.mjs +2 -1
  55. package/src/integrations/spotify/service.mjs +29 -11
  56. package/src/integrations/spotify/web-api-client.mjs +2 -2
  57. package/src/integrations/stable-audio/local-generator.mjs +13 -5
  58. package/src/integrations/youtube-music/takeout.mjs +12 -8
  59. package/src/memory/local-memory-store.mjs +479 -27
  60. package/src/memory/reflection-worker.mjs +1 -0
  61. package/src/profile/apple-library-import.mjs +56 -2
  62. package/src/profile/history-import.mjs +58 -27
  63. package/src/profile/listener-corrections.mjs +2 -4
  64. package/src/profile/listener-profile-build.mjs +128 -45
  65. package/src/profile/listener-profile-store.mjs +25 -4
  66. package/src/profile/listener-profile-verification.mjs +11 -5
  67. package/src/profile/listener-profile-worker.mjs +24 -8
  68. package/src/profile/listening-history-store.mjs +944 -367
  69. package/src/profile/listening-profile-projection.mjs +123 -156
  70. package/src/profile/local-file-import.mjs +172 -0
  71. package/src/profile/moondog-suggestions.mjs +40 -11
  72. package/src/profile/profile-exploration.mjs +36 -6
  73. package/src/profile/recorded-measures.mjs +5 -0
  74. package/src/profile/spotify-archive-taste.mjs +41 -65
  75. package/src/runtime/pi/agent-runtime.mjs +360 -215
  76. package/src/runtime/pi/custom-endpoints.mjs +30 -8
  77. package/src/runtime/pi/memory-agent-runtime.mjs +43 -3
  78. package/src/runtime/pi/playback-rules.mjs +100 -0
  79. package/src/runtime/pi/profile-build-runtime.mjs +81 -24
  80. package/src/surfaces/cli/brand-components.mjs +9 -6
  81. package/src/surfaces/cli/command-completions.mjs +8 -1
  82. package/src/surfaces/cli/format-output.mjs +207 -34
  83. package/src/surfaces/cli/history-import-view.mjs +130 -21
  84. package/src/surfaces/cli/listenbrainz-command.mjs +7 -2
  85. package/src/surfaces/cli/listener-profile-command.mjs +67 -10
  86. package/src/surfaces/cli/listening-menu.mjs +3 -0
  87. package/src/surfaces/cli/profile-command.mjs +1 -0
  88. package/src/surfaces/cli/spotify-command.mjs +17 -25
  89. package/src/surfaces/cli/taste-period.mjs +22 -0
  90. package/src/surfaces/cli/taste-profile-model.mjs +52 -32
  91. package/src/surfaces/cli/tui.mjs +557 -170
  92. package/src/surfaces/html/tasteprint.mjs +181 -93
  93. package/src/surfaces/import-source-history.mjs +80 -0
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  <h1 align="center">Moondog</h1>
6
6
 
7
- <p align="center">Version 0.4.0-beta.3</p>
7
+ <p align="center">Version 0.4.0-beta.4</p>
8
8
 
9
9
  <p align="center"><strong>On the air, just for you.</strong></p>
10
10
 
@@ -92,7 +92,8 @@ Moondog shows you what is inside before anything is saved, and the original file
92
92
 
93
93
  The [terminal guide](docs/TERMINAL_GUIDE.md#import-and-inspect-listening-history) has every format.
94
94
 
95
- With a model connected, Moondog writes a reading of everything you imported, usually in a few minutes.
95
+ With a model connected, choose **Build reading** in the desktop Taste page or enter `/profile build` in the terminal.
96
+ Moondog writes a reading of the imported evidence, usually in a few minutes.
96
97
  It names the threads in your listening, keeps what you played apart from what you saved, and marks its interpretations as interpretations.
97
98
  A second pass checks the draft for contradictions and invented claims, and the build fixes what it finds before saving.
98
99
 
@@ -112,6 +113,18 @@ Find a song or artist, see why it is there, and choose **I like this** or **Keep
112
113
  You can also say it to the host, for example “never play this again”.
113
114
  `/taste report` walks the years one song at a time and ends on what play counts can never tell anyone; you can keep it as a private page that works offline.
114
115
 
116
+ ## What it learns
117
+
118
+ Moondog also learns a small set of working practices from finished conversations.
119
+ A practice is a procedure, not a taste claim: for example, how you asked for the first picks in an open request.
120
+ Only an explicit instruction, quoted exactly from your own words, can become one automatically.
121
+ It is kept in the same local database as memory, with every revision, and never grants a new capability or permission.
122
+
123
+ A new conversation sees only the practice names and descriptions.
124
+ The full instructions load when the current request needs one.
125
+ Open them with `moondog skills list` and `moondog skills show <name>`, turn one off with `moondog skills archive <name>`, and bring it back with `moondog skills restore <name>`.
126
+ The learned practices note records the transaction, validation, and limits.
127
+
115
128
  ## On the air
116
129
 
117
130
  Ask for music in your own words, in any of ten languages.
@@ -120,7 +133,9 @@ What it reads about the wider music world stays separate from what it knows abou
120
133
  Under a set of songs, one line names the mix: how many you know well, how many come back after a while, and how many are new to you.
121
134
 
122
135
  - **Up next.** The desktop player shows the queue: play a song now, or take one out. When it runs low, the host offers a few picks.
123
- - **Your library.** Saved songs, your playlists, and the tracks Moondog made sit side by side. Import a Spotify, Apple Music, NetEase Music, or QQ Music playlist by its link, and export a playlist to Spotify.
136
+ - **Your library.** Saved songs, your playlists, and the tracks Moondog made sit side by side.
137
+ Import a playlist from Spotify, Apple Music, NetEase Music, or QQ Music by its link.
138
+ Export a copy to Spotify, or choose **Export playlist files…** to keep an M3U8, a JSON playlist, and the available audio for tracks Moondog made.
124
139
  - **Music it makes.** Ask for an instrumental and Moondog can write a score and play it on its built-in synthesizer.
125
140
  For Stable Audio 3, powered by Stability AI, choose Medium or Small Music in Settings › Playback or use `/generation download medium`.
126
141
  After you accept the licenses and download a model, it runs offline on Apple silicon, Windows x64, or Linux x64 or ARM64.
@@ -145,7 +160,7 @@ Tab on an empty input steps onto the tracklist, and Ctrl+P searches every comman
145
160
  | `/import` | Bring your history. |
146
161
  | `/library` | Your saved songs and playlists. |
147
162
  | `/onair` | Go on air, or come off it. |
148
- | `/skip`, `/stop` | Skip to the next song or stream track, or stop. |
163
+ | `/skip`, `/stop` | Skip the current track or stop playback. On Spotify, `/stop` pauses the active device. |
149
164
  | `/resume`, `/new` | Pick up a saved conversation, or start a fresh one. |
150
165
  | `/rewind`, `/branch` | Change an earlier message, or go on in a new conversation. |
151
166
  | `/home` | Back to the sleeve, without clearing the conversation. |
@@ -169,10 +184,6 @@ Read the [connection and data details](docs/TERMINAL_GUIDE.md) before you connec
169
184
  - [Project page](site/README.md): how the page plays the scene in the app's real window, in a browser, on made-up data.
170
185
  - [Private Tasteprint](docs/PRIVATE_TASTEPRINT.md): what the evidence can support, and what a report reveals about you.
171
186
  - [Product charter](docs/PRODUCT_CHARTER.md) and [public roadmap](docs/ROADMAP.md): where Moondog is headed, and what it will not do.
172
- - [Voice](docs/VOICE.md): how Moondog talks, and where Pink Floyd shows up.
173
- - [The listening loop](docs/LISTENING_LOOP.md): how the agent keeps your choices, your recent listening, and its own picks apart.
174
- - [The agent harness](docs/AGENT_HARNESS.md): how the tools keep the model's part small, so every supported model can play what you ask.
175
- - [Runtime architecture](docs/ADR_0001_AGENT_RUNTIME_AND_CLI.md) and [data contracts](contracts/README.md): how the pieces fit together.
176
187
  - [Contribution guide](CONTRIBUTING.md): local setup, checks, and how private data is kept out.
177
188
  - [Release status](docs/PUBLIC_RELEASE_READINESS.md): what is published, and what the checks cover.
178
189
  - [Translating Moondog](docs/TRANSLATING.md): how replies choose a language, and how to add one.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@audiofool/moondog",
3
- "version": "0.4.0-beta.3",
3
+ "version": "0.4.0-beta.4",
4
4
  "type": "module",
5
5
  "description": "A local-first AI radio host, just for you.",
6
6
  "license": "Apache-2.0",
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ import { randomUUID } from "node:crypto";
3
4
  import { createApplicationUpdater } from "../src/core/application-update.mjs";
4
5
  import { openInDefaultBrowser } from "../src/core/host.mjs";
5
6
  import { runUpdateCommand } from "../src/surfaces/cli/update-command.mjs";
@@ -19,8 +20,11 @@ import { createModelSettings } from "../src/runtime/pi/model-settings.mjs";
19
20
  import { createToolTrace } from "../src/runtime/pi/tool-trace.mjs";
20
21
  import { watchRuntimeSettings, writePiRuntimeSelection } from "../src/runtime/pi/runtime-settings.mjs";
21
22
  import {
23
+ collectionCoverageLines,
22
24
  formatLocalResult,
23
25
  formatDemoResult,
26
+ formatLearnedSkill,
27
+ formatLearnedSkills,
24
28
  formatMemoryReflection,
25
29
  helpText,
26
30
  sanitizeTerminalText,
@@ -36,7 +40,6 @@ import { createWebResearch } from "../src/integrations/web/web-research.mjs";
36
40
  import { runModelRolesCommand } from "../src/surfaces/cli/model-roles-command.mjs";
37
41
  import { runWebCommand } from "../src/surfaces/cli/web-command.mjs";
38
42
  import { openSpotifyConnection } from "../src/integrations/spotify/connection.mjs";
39
- import { preferredIdleDevice, thisComputerName } from "../src/integrations/spotify/service.mjs";
40
43
  import {
41
44
  openSpotifyResolutionCache,
42
45
  } from "../src/integrations/spotify/resolution-cache.mjs";
@@ -45,17 +48,18 @@ import {
45
48
  } from "../src/integrations/spotify/settings.mjs";
46
49
  import { runSpotifyCommand } from "../src/surfaces/cli/spotify-command.mjs";
47
50
  import { runListenBrainzCommand } from "../src/surfaces/cli/listenbrainz-command.mjs";
48
- import { openListeningHistoryStore } from "../src/profile/listening-history-store.mjs";
51
+ import { openListeningHistoryStore, readListeningImportSubject } from "../src/profile/listening-history-store.mjs";
49
52
  import { createMusicAppListening, projectMusicAppPlays } from "../src/integrations/apple-music/music-app-listening.mjs";
50
53
  import { musicHash, prepareMusicBundle } from "../src/profile/music-import-bundle.mjs";
51
- import { commitSpotifyQuickImport, prepareHistoryImport, prepareSpotifyQuickImport } from "../src/profile/history-import.mjs";
52
- import { persistAppleLibraryImport, refreshAppleLibraryImport } from "../src/profile/apple-library-import.mjs";
54
+ import { prepareListeningImport } from "../src/profile/local-file-import.mjs";
55
+ import { refreshAppleLibraryImport } from "../src/profile/apple-library-import.mjs";
53
56
  import { IMPORT_GUIDE_URLS } from "../src/surfaces/cli/import-guides.mjs";
54
57
  import { readLastfmConfiguration, writeLastfmConfiguration } from "../src/integrations/lastfm/settings.mjs";
55
58
  import { runMoondogTui } from "../src/surfaces/cli/tui.mjs";
56
59
  import { createLyricService } from "../src/core/lyric-service.mjs";
57
60
  import { startListeningUpkeep } from "../src/core/listening-upkeep.mjs";
58
61
  import { createAppleMusicCatalog } from "../src/integrations/apple-music/catalog.mjs";
62
+ import { readCatalogPlaylist } from "../src/integrations/apple-music/catalog-playlist-reader.mjs";
59
63
  import { createTerminalPreviewPlayer } from "../src/integrations/apple-music/terminal-preview-player.mjs";
60
64
  import { createNeteasePlayer } from "../src/integrations/netease/ncm-cli-player.mjs";
61
65
  import { createAtmosphereStream, createLocalGenerator } from "../src/integrations/stable-audio/local-generator.mjs";
@@ -372,51 +376,12 @@ async function runListenBrainzSurface(options) {
372
376
  }
373
377
 
374
378
  async function prepareTuiHistoryImport(filePath, { recentPage, librarySnapshot, libraryUnavailable, provider, onProgress, signal } = {}) {
375
- const historyStore = await openListeningHistoryStore();
376
- try {
377
- const appleSubjectId = await optionalAppleMusicSubjectId();
378
- const subjectId = historyStore.localSubjectId({
379
- ...(appleSubjectId ? { preferredSubjectId: appleSubjectId } : {}),
380
- create: true,
381
- });
382
- const prepared = recentPage ? prepareSpotifyQuickImport({ page: recentPage, librarySnapshot, libraryUnavailable, subjectId }) : await prepareHistoryImport({
383
- filePath, subjectId, provider, capturedAt: new Date().toISOString(), onProgress, signal,
384
- });
385
- let closed = false;
386
- let committed = false;
387
- return {
388
- provider: prepared.provider,
389
- preview: prepared.preview,
390
- async commit() {
391
- if (closed || committed) throw new Error("That preview is gone. Open it again before importing.");
392
- const options = { args: ["import-history", filePath], stdout: { write() {} }, subjectId };
393
- // Commit the exact inspected bundle, even if the source file later changes.
394
- const receipt = prepared.provider === "spotify-quick"
395
- ? commitSpotifyQuickImport(historyStore, prepared)
396
- : prepared.provider === "apple-music-library"
397
- ? await persistAppleLibraryImport(prepared.bundle)
398
- : prepared.provider === "spotify"
399
- ? await runSpotifyCommand({
400
- ...options, recentActivityStore: historyStore,
401
- historyArchiveImporter: async () => prepared.bundle,
402
- })
403
- : prepared.provider === "listenbrainz" ? await runListenBrainzCommand({
404
- ...options, historyStore,
405
- historyFileImporter: async () => prepared.bundle,
406
- }) : { ...historyStore.ingestImport(prepared.bundle), provider: prepared.provider };
407
- committed = true;
408
- return receipt;
409
- },
410
- close() {
411
- if (closed) return;
412
- closed = true;
413
- historyStore.close();
414
- },
415
- };
416
- } catch (error) {
417
- historyStore.close();
418
- throw error;
419
- }
379
+ signal?.throwIfAborted();
380
+ const preferredSubjectId = await optionalAppleMusicSubjectId();
381
+ const subjectId = await readListeningImportSubject({ preferredSubjectId: preferredSubjectId ?? undefined }) ?? randomUUID();
382
+ signal?.throwIfAborted();
383
+ return prepareListeningImport({ filePath, subjectId, provider, capturedAt: new Date().toISOString(),
384
+ recentPage, librarySnapshot, libraryUnavailable, onProgress, signal });
420
385
  }
421
386
 
422
387
  async function openImportHelp(destination) {
@@ -426,11 +391,16 @@ async function openImportHelp(destination) {
426
391
  }
427
392
 
428
393
  function tasteCoverage(profile) {
394
+ const coverage = profile.coverage ?? {};
429
395
  return {
430
- effective_listening_events:
431
- profile.coverage?.effective_listening_events ?? null,
432
- listening_hours: profile.coverage?.listening_hours ?? null,
433
- distinct_tracks: profile.coverage?.listening_tracks ?? null,
396
+ effective_listening_events: coverage.effective_listening_events ?? null,
397
+ listening_hours: coverage.effective_listening_events === 0 || coverage.events_with_played_duration === 0
398
+ ? null : coverage.listening_hours ?? null,
399
+ distinct_tracks: coverage.listening_tracks ?? null,
400
+ ...(coverage.tracks_observed > 0 ? { apple_library_tracks: coverage.tracks_observed } : {}),
401
+ ...(coverage.collection_tracks > 0 ? { collection_tracks: coverage.collection_tracks } : {}),
402
+ ...(coverage.collection_sources?.length ? { collection_sources: coverage.collection_sources } : {}),
403
+ ...(coverage.profile_evidence_records > 0 ? { profile_evidence_records: coverage.profile_evidence_records } : {}),
434
404
  };
435
405
  }
436
406
 
@@ -464,12 +434,24 @@ async function emitTasteprintArtifact(
464
434
  if (json) {
465
435
  process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
466
436
  } else {
437
+ const { effective_listening_events: plays, distinct_tracks: tracks, listening_hours: hours } = result.coverage;
438
+ const collections = collectionCoverageLines(profile.coverage);
439
+ const counts = [];
440
+ if (plays > 0) {
441
+ counts.push(`${plays.toLocaleString("en-US")} ${plays === 1 ? "play" : "plays"}`);
442
+ if (hours !== null) {
443
+ const amount = hours === 0 && profile.coverage?.events_with_played_duration > 0 ? "<0.1" : hours.toLocaleString("en-US");
444
+ counts.push(`${amount} ${hours === 1 ? "hour" : "hours"}`);
445
+ }
446
+ if (tracks !== null) counts.push(`${tracks.toLocaleString("en-US")} ${tracks === 1 ? "track" : "tracks"}`);
447
+ }
467
448
  const lines = [
468
449
  format === "card"
469
450
  ? "Your recap card is ready."
470
- : "Your listening report is ready.",
451
+ : plays === 0 && collections.length ? "Your collection report is ready." : "Your listening report is ready.",
471
452
  `Saved to ${artifact.path}`,
472
- `Read from ${(result.coverage.effective_listening_events ?? 0).toLocaleString("en-US")} plays, ${(result.coverage.listening_hours ?? 0).toLocaleString("en-US")} hours, ${(result.coverage.distinct_tracks ?? 0).toLocaleString("en-US")} tracks.`,
453
+ ...(counts.length ? [`Read from ${counts.join(", ")}.`] : []),
454
+ ...collections,
473
455
  ];
474
456
  if (source?.persistent_import === false) {
475
457
  lines.push(
@@ -540,29 +522,6 @@ function watchMusicAppForStream(stream, { musicApp, interval = STREAM_MUSIC_APP_
540
522
  };
541
523
  }
542
524
 
543
- // Whether a /spotify command starts Spotify on this Mac: play on the device it resumes on (the active one,
544
- // or with none active the one it would pick), or a move onto this Mac with --play or while Spotify plays (a
545
- // move keeps playing what plays). A command its own checks refuse, or reads that fail, start nothing here.
546
- async function spotifyStartsHere(application, args, { signal } = {}) {
547
- if (!application.spotifyReady?.()) return false;
548
- // A trailing --json changes only how the result is written.
549
- if (args.at(-1) === "--json") args = args.slice(0, -1);
550
- const play = args[0] === "play" && args.length <= 2;
551
- const transfer = args[0] === "transfer" && args.length >= 2 && args.length <= 3 && (args.length === 2 || args[2] === "--play");
552
- if (!play && !transfer) return false;
553
- const service = application.requireSpotifyService();
554
- const [listed, player] = await Promise.all([service.devices({ signal }).catch(() => null), service.currentPlayer({ signal }).catch(() => null)]);
555
- const devices = listed?.devices ?? [];
556
- if (transfer) {
557
- const device = devices.find((entry) => entry.id === args[1]);
558
- const playing = player?.state === "available" && player.is_playing === true;
559
- return Boolean(device) && application.spotifyOnThisMac(device) && (args[2] === "--play" || playing);
560
- }
561
- const active = player?.device?.is_active === true ? player.device : devices.find((device) => device.is_active === true);
562
- const device = active ?? preferredIdleDevice(devices, { thisComputer: await thisComputerName() });
563
- return Boolean(device) && application.spotifyOnThisMac(device);
564
- }
565
-
566
525
  async function main() {
567
526
  const updater = createApplicationUpdater();
568
527
  const argv = process.argv.slice(2);
@@ -770,6 +729,13 @@ async function main() {
770
729
  );
771
730
  }
772
731
 
732
+ if (options.command === "sources") {
733
+ const [offset = "0", ...extra] = options.rest;
734
+ if (extra.length || !/^\d+$/u.test(offset) || !Number.isSafeInteger(Number(offset))) {
735
+ throw new Error("Usage: moondog sources [offset] [--json].");
736
+ }
737
+ }
738
+
773
739
  if (options.command === "auth") {
774
740
  await runAuthCommand({
775
741
  args: options.rest,
@@ -835,6 +801,36 @@ async function main() {
835
801
  return;
836
802
  }
837
803
 
804
+ if (options.command === "skills") {
805
+ const [action, name, ...extra] = options.rest;
806
+ if (!["list", "show", "archive", "restore"].includes(action) ||
807
+ (action === "list" && (name !== undefined || options.dryRun || options.offline)) ||
808
+ (action !== "list" && (typeof name !== "string" || name.length === 0 || extra.length > 0 ||
809
+ options.dryRun || options.offline))) {
810
+ throw new Error("Usage: moondog skills <list|show <name>|archive <name>|restore <name>> [--json].");
811
+ }
812
+ const memoryStore = await openLocalMemoryStore();
813
+ try {
814
+ let value;
815
+ if (action === "list") {
816
+ value = memoryStore.listLearnedSkills();
817
+ process.stdout.write(`${options.json ? JSON.stringify(value, null, 2) : formatLearnedSkills(value)}\n`);
818
+ } else if (action === "show") {
819
+ value = memoryStore.readLearnedSkill(name, { includeArchived: true });
820
+ process.stdout.write(`${options.json ? JSON.stringify(value, null, 2) : formatLearnedSkill(value)}\n`);
821
+ } else if (action === "archive") {
822
+ value = memoryStore.archiveLearnedSkill(name);
823
+ process.stdout.write(`${options.json ? JSON.stringify(value, null, 2) : `Archived learned practice: ${value.name}.\n`}`);
824
+ } else {
825
+ value = memoryStore.restoreLearnedSkill(name);
826
+ process.stdout.write(`${options.json ? JSON.stringify(value, null, 2) : `Restored learned practice: ${value.name}.\n`}`);
827
+ }
828
+ } finally {
829
+ memoryStore.close();
830
+ }
831
+ return;
832
+ }
833
+
838
834
  if (options.command === "memory" && options.rest[0] === "reflect") {
839
835
  if (options.rest.length !== 1) {
840
836
  throw new Error("Usage: moondog memory reflect [--dry-run] [--json].");
@@ -1012,12 +1008,6 @@ async function main() {
1012
1008
  // The listener's model menu, shared by the window, the terminal and a model asked for in words.
1013
1009
  const modelSettings = createModelSettings({ environment: process.env });
1014
1010
  const modelSwitch = createModelSwitch({ list: () => modelSettings.list() });
1015
- // The terminal and the window each run this core on one playback.json. A service chosen on the
1016
- // other side reaches this side's picker and agents, and stops the Apple Music songs this side plays.
1017
- // Moondog's stream is not a service: its made tracks play on.
1018
- const unwatchPlayback = watchPlaybackPreference(playbackSelection, {
1019
- onChange: (service) => { if (service !== "apple_music" && previewPlayer?.holdsCatalogSongs?.() !== false) previewPlayer?.stop?.(); },
1020
- });
1021
1011
  // The main application and every conversation the window opens beside it are built from
1022
1012
  // this one list, so they cannot drift apart. Each passes in what may change after launch:
1023
1013
  // its domain services, the Spotify connection, the language and the music service.
@@ -1026,6 +1016,7 @@ async function main() {
1026
1016
  const applicationOptions = ({ domainServices, domainServicesError, spotifyConnection, locale, playbackService }) => ({
1027
1017
  domainServices, domainServicesError, spotifyConnection, locale, playbackService, playbackSelection, languageSelection, modelSwitch,
1028
1018
  webResearch, memoryStore, musicCatalog, musicPreviewPlayer: previewPlayer, neteasePlayer, localGenerator, atmosphereStream, musicSimilarity, artistIdentityResolver,
1019
+ appleCatalogPlaylistReader: readCatalogPlaylist,
1029
1020
  spotifyTopArtists, musicApp, libraryStore,
1030
1021
  // A playlist that shapes the taste reloads the profile services at once, so the evidence counts in this session.
1031
1022
  playlistTaste: async (found) => { const receipt = await addPlaylistToTaste(found); replaceDomainServices(await loadDomainServices()); return receipt; },
@@ -1033,6 +1024,15 @@ async function main() {
1033
1024
  const application = new MoondogApplication(applicationOptions({
1034
1025
  ...domainState, spotifyConnection, locale: await resolveListenerLocale(), playbackService,
1035
1026
  }));
1027
+ // The terminal and the window share playback.json. Switching away in the other
1028
+ // client also stops this client's Apple lookups and songs. Made tracks keep playing.
1029
+ const unwatchPlayback = watchPlaybackPreference(playbackSelection, {
1030
+ onChange: (service) => {
1031
+ if (service === "apple_music") return;
1032
+ application.cancelPendingMusicPreviews();
1033
+ if (previewPlayer?.holdsCatalogSongs?.() !== false) previewPlayer?.stop?.();
1034
+ },
1035
+ });
1036
1036
  // The conversations the window runs beside the main one, each with its own application and agent.
1037
1037
  const conversations = new Set();
1038
1038
  // An import replaces the domain services under the main application and every open
@@ -1074,6 +1074,7 @@ async function main() {
1074
1074
  const value = await application.runLocalCommand(
1075
1075
  options.command,
1076
1076
  runtimeStatus,
1077
+ options.command === "sources" ? { offset: Number(options.rest[0] ?? 0) } : undefined,
1077
1078
  );
1078
1079
  process.stdout.write(
1079
1080
  `${options.json ? JSON.stringify(value, null, 2) : formatLocalResult(options.command, value)}\n`,
@@ -1142,20 +1143,12 @@ async function main() {
1142
1143
  listeningUpkeep = startListeningUpkeep({
1143
1144
  run: async ({ signal }) => {
1144
1145
  const spotify = application.spotifyReady() ? application.spotifyConnection : null;
1145
- const granted = (scope) => spotify !== null && !spotify.missingScopes?.().includes(scope);
1146
- if (granted("user-read-recently-played")) {
1146
+ if (spotify && !spotify.missingScopes?.().includes("user-read-recently-played")) {
1147
1147
  const synced = await syncRecentSpotifyListening({ signal }).catch(() => null);
1148
1148
  // Open domain services read new plays as they land; only a first history needs opening.
1149
1149
  if (synced?.inserted_events > 0 && !application.domainServices) replaceDomainServices(await loadDomainServices());
1150
1150
  }
1151
- if (granted("user-top-read")) {
1152
- const top = await spotify.service.topItems({ type: "artists", timeRange: "short_term", limit: 10 }, { signal })
1153
- .catch(() => null);
1154
- if (top) {
1155
- spotifyTopArtists.read_at = new Date().toISOString();
1156
- spotifyTopArtists.artists = top.items.flatMap((artist) => typeof artist.name === "string" ? [artist.name.slice(0, 256)] : []);
1157
- }
1158
- }
1151
+ await application.refreshSpotifyTopArtists({ signal }).catch(() => null);
1159
1152
  signal.throwIfAborted();
1160
1153
  // Completed conversations become durable memory a batch at a time, before the longer rebuild.
1161
1154
  await runMemoryReflectionIfDue({ application }).catch(() => null);
@@ -1215,18 +1208,18 @@ async function main() {
1215
1208
  checkUpdates: options => updater.startupCheck(options),
1216
1209
  runUpdate: (args, options) => runUpdateCommand({ args, updater, deferInstall: true, ...options }),
1217
1210
  prepareImport: prepareTuiHistoryImport,
1218
- prepareRecentImport: async ({ onProgress } = {}) => {
1219
- const recentPage = await runSpotifySurface({ args: ["recent", "--limit", "50"], stdout: { write() {} } });
1211
+ prepareRecentImport: async ({ onProgress, signal } = {}) => {
1212
+ const recentPage = await runSpotifySurface({ args: ["recent", "--limit", "50"], stdout: { write() {} }, signal });
1220
1213
  let librarySnapshot = null;
1221
1214
  let libraryUnavailable = null;
1222
1215
  try {
1223
- librarySnapshot = await runSpotifySurface({ args: ["library"], stdout: { write() {} }, onProgress });
1216
+ librarySnapshot = await runSpotifySurface({ args: ["library"], stdout: { write() {} }, onProgress, signal });
1224
1217
  } catch (error) {
1225
1218
  // An older recent-plays-only sign-in can still import recent plays.
1226
1219
  if (error?.code !== "spotify_scope_insufficient") throw error;
1227
1220
  libraryUnavailable = "missing_permission";
1228
1221
  }
1229
- return prepareTuiHistoryImport(undefined, { recentPage, librarySnapshot, libraryUnavailable });
1222
+ return prepareTuiHistoryImport(undefined, { recentPage, librarySnapshot, libraryUnavailable, onProgress, signal });
1230
1223
  },
1231
1224
  openImportHelp,
1232
1225
  // Local generation: what the room shows and the switch the listener turns, in Settings or with /generation.
@@ -1330,9 +1323,6 @@ async function main() {
1330
1323
  return json ? `\`\`\`json\n${output.trim()}\n\`\`\`` : output.trim();
1331
1324
  },
1332
1325
  runSpotify: async (args, { signal, stderr } = {}) => {
1333
- // /spotify play, and a move onto this Mac that plays there, start Spotify here: the other players go
1334
- // quiet first. A command its own checks will refuse, or a move to another device, quiets nothing.
1335
- if (await spotifyStartsHere(application, args, { signal })) await application.quietOtherPlayers("spotify", { signal });
1336
1326
  let output = "";
1337
1327
  const capture = {
1338
1328
  write(value) {
@@ -1342,6 +1332,7 @@ async function main() {
1342
1332
  await runSpotifySurface({
1343
1333
  args,
1344
1334
  signal,
1335
+ onPlaybackStarted: application.spotifyPlaybackStarted,
1345
1336
  stdout: capture,
1346
1337
  stderr: stderr ?? (args[0] === "login" ? host?.terminalStreams?.output ?? process.stderr : capture),
1347
1338
  resolutionCache: await spotifyResolutionCacheIfConfigured(),
@@ -1350,8 +1341,9 @@ async function main() {
1350
1341
  replaceDomainServices(await loadDomainServices());
1351
1342
  }
1352
1343
  const connection = await loadSpotifyConnection();
1353
- application.setSpotifyConnection(connection);
1354
- for (const conversation of conversations) conversation.application.setSpotifyConnection(connection);
1344
+ const sameAuthorization = !["login", "logout", "configure"].includes(args[0]);
1345
+ application.setSpotifyConnection(connection, { sameAuthorization });
1346
+ for (const conversation of conversations) conversation.application.setSpotifyConnection(connection, { sameAuthorization });
1355
1347
  return output.trim();
1356
1348
  },
1357
1349
  });
@@ -2,6 +2,7 @@ import { lstat, readFile, readdir } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
 
4
4
  import { resolveMoondogStateDirectory } from "./state-directory.mjs";
5
+ import { readAppleImportSaveTime } from "../importers/apple-music-library/save-time.mjs";
5
6
 
6
7
  export function defaultAppleMusicImportsRootFor(environment = process.env) {
7
8
  return path.join(resolveMoondogStateDirectory(environment), "apple-music-library", "imports");
@@ -19,6 +20,7 @@ export function resolveAppleMusicImportsRoot(environment = process.env) {
19
20
  const uuidDirectoryPattern =
20
21
  /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
21
22
  const maximumManifestBytes = 256 * 1024;
23
+ const isSourceDigest = value => typeof value === "string" && /^[0-9a-f]{64}$/u.test(value);
22
24
 
23
25
  function missingStatus() {
24
26
  return {
@@ -77,7 +79,7 @@ function sanitizeManifest(manifest) {
77
79
  return {
78
80
  subject_id: manifest.subject_id.toLowerCase(),
79
81
  captured_at: new Date(capturedAt).toISOString(),
80
- tracks: requireCount(manifest.counts, "source_tracks"),
82
+ tracks: requireCount(manifest.counts, manifest.warning_counts?.non_music_media_excluded ? "track_refs" : "source_tracks"),
81
83
  playlists: requireCount(manifest.counts, "source_playlists"),
82
84
  playlist_item_references: requireCount(
83
85
  manifest.counts,
@@ -103,7 +105,7 @@ function sanitizeManifest(manifest) {
103
105
  };
104
106
  }
105
107
 
106
- async function readPrivateManifest(batchDirectory) {
108
+ async function readPrivateManifest(batchDirectory, includeIdentity) {
107
109
  const directoryMetadata = await lstat(batchDirectory);
108
110
  if (!directoryMetadata.isDirectory() || directoryMetadata.isSymbolicLink()) {
109
111
  throw new Error("batch_directory_invalid");
@@ -119,45 +121,58 @@ async function readPrivateManifest(batchDirectory) {
119
121
  throw new Error("manifest_file_invalid");
120
122
  }
121
123
 
122
- return sanitizeManifest(JSON.parse(await readFile(manifestPath, "utf8")));
124
+ const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
125
+ if (manifest.import_batch_id !== undefined && manifest.import_batch_id !== path.basename(batchDirectory)) {
126
+ throw new Error("manifest_identity_invalid");
127
+ }
128
+ const summary = sanitizeManifest(manifest);
129
+ if (includeIdentity) {
130
+ if (!manifest.import_batch_id ||
131
+ !isSourceDigest(manifest.source.sha256) || !isSourceDigest(manifest.source.library_fingerprint_sha256)) {
132
+ throw new Error("manifest_identity_invalid");
133
+ }
134
+ return {
135
+ ...summary,
136
+ batchId: manifest.import_batch_id,
137
+ sourceHash: manifest.source.sha256,
138
+ libraryFingerprint: manifest.source.library_fingerprint_sha256,
139
+ trackCount: requireCount(manifest.counts, "track_refs"),
140
+ };
141
+ }
142
+ return summary;
123
143
  }
124
144
 
125
- export async function readAppleMusicSourceStatus(
126
- importsRoot = resolveAppleMusicImportsRoot(),
127
- operations = { lstat, readdir },
128
- ) {
145
+ async function scanAppleMusicManifests(importsRoot, operations, { includeSaveTimes = false, includeIdentity = false } = {}) {
146
+ const valid = [];
147
+ let invalidBatches = 0;
129
148
  let rootMetadata;
130
149
  try {
131
150
  rootMetadata = await operations.lstat(importsRoot);
132
151
  } catch (error) {
133
- if (error?.code === "ENOENT") return missingStatus();
134
- return { ...missingStatus(), state: "invalid", error: "source_unreadable" };
152
+ return { valid, invalidBatches, error: error?.code === "ENOENT" ? null : "source_unreadable" };
135
153
  }
136
154
 
137
155
  if (!rootMetadata.isDirectory() || rootMetadata.isSymbolicLink()) {
138
- return { ...missingStatus(), state: "invalid", error: "source_root_invalid" };
156
+ return { valid, invalidBatches, error: "source_root_invalid" };
139
157
  }
140
158
 
141
159
  let entries;
142
160
  try {
143
161
  entries = await operations.readdir(importsRoot, { withFileTypes: true });
144
162
  } catch (error) {
145
- if (error?.code === "ENOENT") return missingStatus();
146
- return { ...missingStatus(), state: "invalid", error: "source_unreadable" };
163
+ return { valid, invalidBatches, error: error?.code === "ENOENT" ? null : "source_unreadable" };
147
164
  }
148
165
  const candidateNames = entries
149
166
  .filter((entry) => uuidDirectoryPattern.test(entry.name))
150
167
  .map((entry) => entry.name)
151
168
  .sort();
152
169
 
153
- const valid = [];
154
- let invalidBatches = 0;
155
-
156
170
  for (const candidateName of candidateNames) {
157
171
  try {
158
- valid.push(
159
- await readPrivateManifest(path.join(importsRoot, candidateName)),
160
- );
172
+ const directory = path.join(importsRoot, candidateName);
173
+ const manifest = await readPrivateManifest(directory, includeIdentity);
174
+ if (includeSaveTimes) manifest.first_imported_at = await readAppleImportSaveTime(directory);
175
+ valid.push(manifest);
161
176
  } catch {
162
177
  invalidBatches += 1;
163
178
  }
@@ -166,6 +181,37 @@ export async function readAppleMusicSourceStatus(
166
181
  valid.sort((left, right) =>
167
182
  left.captured_at.localeCompare(right.captured_at),
168
183
  );
184
+ return { valid, invalidBatches };
185
+ }
186
+
187
+ export function listAppleLibraryComparisonSources(importsRoot) {
188
+ return scanAppleMusicManifests(importsRoot, { lstat, readdir }, { includeIdentity: true, includeSaveTimes: true });
189
+ }
190
+
191
+ export async function listAppleLibraryImportHistory({ importsRoot = resolveAppleMusicImportsRoot(), subjectId } = {}) {
192
+ if (subjectId != null && (typeof subjectId !== "string" || !uuidDirectoryPattern.test(subjectId))) {
193
+ throw new TypeError("An Apple library subject must be a UUID.");
194
+ }
195
+ const { valid, invalidBatches, error } = await scanAppleMusicManifests(importsRoot, { lstat, readdir }, { includeSaveTimes: true });
196
+ const selected = subjectId == null ? valid : valid.filter(manifest => manifest.subject_id === subjectId.toLowerCase());
197
+ if (error || (!selected.length && invalidBatches)) {
198
+ throw Object.assign(new Error("Apple library import history could not be read."), { code: "apple_library_history_unavailable" });
199
+ }
200
+ if (subjectId == null && new Set(valid.map(manifest => manifest.subject_id)).size > 1) {
201
+ throw Object.assign(new Error("Choose a local listening subject to read Apple library imports."), { code: "apple_library_multiple_subjects" });
202
+ }
203
+ return selected.map(manifest => ({
204
+ kind: "collection", sourceKey: "apple_music_library_xml", sourceFormat: "apple-music-library",
205
+ observedAt: manifest.captured_at, importedAt: manifest.first_imported_at, trackCount: manifest.aggregate_track_snapshots,
206
+ })).sort((left, right) => (right.importedAt ?? right.observedAt).localeCompare(left.importedAt ?? left.observedAt));
207
+ }
208
+
209
+ export async function readAppleMusicSourceStatus(
210
+ importsRoot = resolveAppleMusicImportsRoot(),
211
+ operations = { lstat, readdir },
212
+ ) {
213
+ const { valid, invalidBatches, error } = await scanAppleMusicManifests(importsRoot, operations);
214
+ if (error) return { ...missingStatus(), state: "invalid", error };
169
215
  const latest = valid.at(-1) ?? null;
170
216
 
171
217
  if (new Set(valid.map((manifest) => manifest.subject_id)).size > 1) {