@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
@@ -15,7 +15,9 @@ import { FreshCompletionEditor } from "./brand-components.mjs";
15
15
  import { sanitizeTerminalText } from "./format-output.mjs";
16
16
  import { IMPORT_GUIDE_URLS } from "./import-guides.mjs";
17
17
  import { SPOTIFY_LIBRARY_SCOPES } from "../../integrations/spotify/library-snapshot.mjs";
18
- import { screenTranslator } from "../../i18n/index.mjs";
18
+ import { intlLocale, screenTranslator } from "../../i18n/index.mjs";
19
+ import { importHistoryStrings } from "../../i18n/import-history.mjs";
20
+ import { utcDay } from "../import-source-history.mjs";
19
21
 
20
22
  function clean(value) {
21
23
  return sanitizeTerminalText(stripVTControlCharacters(String(value ?? "")))
@@ -34,11 +36,10 @@ function paint(value, width, theme) {
34
36
  }
35
37
 
36
38
  function safeEditorLine(value) {
37
- // Preserve Pi's styling and cursor protocol, but remove controls from paths.
38
- return value.split(CURSOR_MARKER).map((part) => part.split(/(\u001b\[[\d;:]*m)/gu)
39
- .map((segment) => /^\u001b\[[\d;:]*m$/u.test(segment) ? segment
40
- : sanitizeTerminalText(stripVTControlCharacters(segment)).replace(/[\r\n\t]/gu, " "))
41
- .join("")).join(CURSOR_MARKER);
39
+ // Pi resolves the hardware and software cursor markers after this view renders.
40
+ const parts = value.split(/(\u001b_pi:(?:c|\/?fc)\u0007|\u001b\[[\d;:]*m)/gu);
41
+ return parts.map((part, index) => index % 2 === 1 ? part
42
+ : sanitizeTerminalText(stripVTControlCharacters(part)).replace(/[\r\n\t]/gu, " ")).join("");
42
43
  }
43
44
 
44
45
  function day(value) {
@@ -47,11 +48,79 @@ function day(value) {
47
48
  return Number.isFinite(date.getTime()) ? date.toISOString().slice(0, 10) : null;
48
49
  }
49
50
 
51
+ function listeningDates(bounds) {
52
+ const first = utcDay(bounds?.earliest), last = utcDay(bounds?.latest);
53
+ return first && last && first <= last
54
+ ? { first, last, text: first === last ? first : `${first} – ${last}` } : null;
55
+ }
56
+
57
+ function previewImpact(preview, locale) {
58
+ const impact = preview.impact;
59
+ if (!impact) return [];
60
+ const labels = importHistoryStrings(locale);
61
+ const numbers = new Intl.NumberFormat(intlLocale(locale));
62
+ const count = (label, value) => Number.isSafeInteger(value) ? `${label} ${numbers.format(value)}` : null;
63
+ const original = utcDay(impact.firstImportedAt);
64
+ const firstImport = original ? `${labels.first} ${original} (UTC)` : null;
65
+
66
+ if (impact.state === "apple-library") {
67
+ if (impact.status === "legacy-unclassified") return [labels.appleLegacyMedia, firstImport].filter(Boolean);
68
+ if (impact.status === "first") return [labels.firstSnapshot];
69
+ if (impact.status === "same") return [labels.repeatSame, firstImport].filter(Boolean);
70
+ if (impact.status === "changed") {
71
+ const snapshot = (label, tracks, observedAt) => {
72
+ const observed = utcDay(observedAt);
73
+ return [label, count(labels.songs, tracks), observed && `${labels.observed} ${observed} (UTC)`].filter(Boolean).join(" · ");
74
+ };
75
+ return [snapshot(labels.thisFile, preview.tracks, preview.capturedAt),
76
+ snapshot(labels.latestSnapshot, impact.previousTrackCount, impact.previousObservedAt)];
77
+ }
78
+ return [labels.previewUnavailable];
79
+ }
80
+
81
+ const before = listeningDates(impact.before);
82
+ if (impact.state === "partial") {
83
+ const parts = { complete: labels.partsAll, partial: labels.partsSome, none: labels.partsNone }[impact.archiveCoverage];
84
+ const prior = [impact.alreadyImported && labels.seenImport, impact.alreadyImported && firstImport,
85
+ (!impact.alreadyImported || impact.archiveCoverage !== "complete") && parts].filter(Boolean).join(" · ");
86
+ const total = preview.listeningEvents, stored = impact.sourceRecordsAlreadyStored;
87
+ const overlap = Number.isSafeInteger(stored) && Number.isSafeInteger(total) && total > 0
88
+ ? `${labels.storedRecords} ${numbers.format(stored)}/${numbers.format(total)}` : null;
89
+ const incoming = listeningDates({ earliest: preview.earliestListeningAt, latest: preview.latestListeningAt });
90
+ const extendsDates = before && incoming && (incoming.first < before.first || incoming.last > before.last);
91
+ return [prior, overlap, extendsDates && `${labels.outsideDates} ${before.text} (UTC)`, labels.partialImpact].filter(Boolean);
92
+ }
93
+ if (impact.state !== "exact") return [labels.previewUnavailable];
94
+
95
+ const { insertedEvents, duplicateEvents, supersededEvents, mirroredEvents, insertedProfileEvidence, effectiveEventDelta, upgradedRecordingEvents = 0 } = impact;
96
+ const changed = [insertedEvents, supersededEvents, mirroredEvents, insertedProfileEvidence, effectiveEventDelta, upgradedRecordingEvents].some(value => value !== 0);
97
+ const prior = impact.alreadyImported && (changed ? labels.repeatChanged : labels.repeatSame);
98
+ const hasPlays = preview.listeningEvents > 0 || insertedEvents > 0 || duplicateEvents > 0;
99
+ const delta = Number.isSafeInteger(effectiveEventDelta)
100
+ ? `${labels.playChange} ${effectiveEventDelta > 0 ? "+" : ""}${numbers.format(effectiveEventDelta)}` : null;
101
+ const summary = [delta, hasPlays && count(labels.inserted, insertedEvents), hasPlays && count(labels.duplicates, duplicateEvents)].filter(Boolean).join(" · ");
102
+ const details = [supersededEvents > 0 && count(labels.reconciled, supersededEvents),
103
+ mirroredEvents > 0 && count(labels.mirrored, mirroredEvents),
104
+ upgradedRecordingEvents > 0 && count(labels.recordingMatches, upgradedRecordingEvents),
105
+ (insertedProfileEvidence > 0 || preview.profileEvidence > 0 || preview.library) && count(labels.collectionAdded, insertedProfileEvidence)].filter(Boolean).join(" · ");
106
+ const after = listeningDates(impact.after);
107
+ let dates;
108
+ if (after && hasPlays) {
109
+ if (!before) dates = `${labels.afterDates} ${after.text} (UTC)`;
110
+ else if (before.text === after.text) dates = `${labels.sameDates} ${before.text} (UTC)`;
111
+ else dates = `${labels.beforeDates} ${before.text} → ${after.text} (UTC)`;
112
+ }
113
+ const newDays = impact.newListeningDays > 0 ? count(labels.newListeningDays, impact.newListeningDays) : null;
114
+ return [prior, impact.alreadyImported && firstImport, (!prior || changed) && labels.ifImported,
115
+ summary, details, dates, newDays && `${newDays} (UTC)`].filter(Boolean);
116
+ }
117
+
50
118
  /** Acquisition guidance and file review; all effects belong to the host. */
51
119
  export class HistoryImportView {
52
- constructor({ tui, getTheme, getRows, profileReady = false, onAction, getText = () => screenTranslator("en") }) {
120
+ constructor({ tui, getTheme, getRows, profileReady = false, onAction, getText = () => screenTranslator("en"), getLocale = () => getText().locale }) {
53
121
  this.getTheme = getTheme;
54
122
  this.getText = getText;
123
+ this.getLocale = getLocale;
55
124
  this.getRows = getRows;
56
125
  this.profileReady = profileReady;
57
126
  this.onAction = onAction;
@@ -83,6 +152,10 @@ export class HistoryImportView {
83
152
  async getSuggestions(lines, line, column, options) {
84
153
  const input = quotedInput(lines, line, column);
85
154
  const result = await completion.getSuggestions(input.lines, line, input.column, { ...options, force: true });
155
+ const typedPath = lines[line];
156
+ // Enter inspects a complete path even when another filename shares its prefix.
157
+ if (column === typedPath.length && result?.items.some((item) =>
158
+ !item.label.endsWith("/") && (item.value === typedPath || item.value === `"${typedPath}"`))) return null;
86
159
  return result && { ...result, prefix: input.quoted ? result.prefix.slice(1) : result.prefix };
87
160
  },
88
161
  applyCompletion(lines, line, column, item, prefix) {
@@ -163,13 +236,13 @@ export class HistoryImportView {
163
236
  case "spotify-quick-recent": return [tr("Spotify recent listening"),
164
237
  tr("Your latest plays, up to 50. Spotify doesn't say how long you listened here. A history ZIP can add the older ones later.")];
165
238
  case "apple-library": return [tr("Apple Music library"),
166
- tr("Your library with loves, ratings, play counts and when you last played each song. It doesn't list every play.")];
167
- case "listenbrainz": return [tr("ListenBrainz history"),
168
- tr("Your saved listens. Some don't say how long you listened, so they count as plays without minutes.")];
239
+ importHistoryStrings(this.getLocale()).appleLibraryScope];
240
+ case "listenbrainz": return [tr("ListenBrainz history"), preview.eventsWithPlayedMs < preview.listeningEvents
241
+ ? tr("Your saved listens. Some don't say how long you listened, so they count as plays without minutes.") : ""];
169
242
  case "spotify-extended": return [tr("Spotify Extended Streaming History"),
170
- tr("Every play in this file, with how long you listened and how each song started and ended.")];
243
+ importHistoryStrings(this.getLocale())[preview.listeningEvents === 0 ? "noExtendedMusic" : "extendedMusic"]];
171
244
  case "spotify-account": return [tr("Spotify Account Data"),
172
- tr("Your plays from the past year, plus your library and playlists. For older plays and listening time, use Extended streaming history.")];
245
+ tr("Account Data includes recent plays and can include saved music and playlists. Extended streaming history can cover earlier years and includes more playback details.")];
173
246
  case "youtube-music": return [clean(preview.sourceLabel),
174
247
  tr("Your library songs and YouTube Music plays, read in English or Chinese. Regular YouTube videos are left out. Google doesn't say how long you listened, and history you deleted or paused can't come back.")];
175
248
  case "lastfm": return [tr("Last.fm scrobbles"), preview.truncated
@@ -193,6 +266,7 @@ export class HistoryImportView {
193
266
  notice: tr("Nothing is added until you import it."),
194
267
  paragraphs: [
195
268
  label,
269
+ ...previewImpact(preview, this.getLocale()),
196
270
  ...(library ? [
197
271
  [tr.n(library.savedTracks, "{count} saved song", "{count} saved songs"), tr.n(library.savedAlbums, "{count} saved album", "{count} saved albums"),
198
272
  tr.n(library.followedArtists, "{count} followed artist", "{count} followed artists")].join(" · "),
@@ -221,6 +295,7 @@ export class HistoryImportView {
221
295
  const back = { type: "back", label: tr("Back") };
222
296
  const website = url => tr("Website: {url}", { url });
223
297
  switch (this.state.page) {
298
+ case "reviewChoice": return this.state.review;
224
299
  case "youtube_music": return {
225
300
  title: tr("Import from YouTube Music"),
226
301
  paragraphs: [tr("Start with the songs in your library, then add what you've played from Google Takeout."),
@@ -417,21 +492,54 @@ export class HistoryImportView {
417
492
  if (preview.kind === "spotify-quick") return this.spotifyQuickPreview(preview);
418
493
  const library = preview.kind === "library";
419
494
  const collection = preview.kind === "collection";
495
+ const evidenceOnly = !library && !collection && preview.listeningEvents === 0 && preview.profileEvidence > 0;
496
+ const collectionOnly = library || collection || evidenceOnly;
497
+ const compareSnapshots = preview.impact?.state === "apple-library" && preview.impact.status === "changed";
420
498
  const first = day(preview.earliestListeningAt);
421
499
  const last = day(preview.latestListeningAt);
500
+ const observed = day(preview.capturedAt);
501
+ let dates = first && last ? tr("{first} to {last}", { first, last }) : tr("No dates in this file.");
502
+ if (library) dates = tr("As of {date}", { date: observed ?? tr("an unknown date") });
503
+ else if (collection) {
504
+ // Takeout library CSVs have no source date. A live playlist read has a retrieval date.
505
+ dates = preview.source !== "youtube-music" && observed ? `${importHistoryStrings(this.getLocale()).readAt} ${observed} (UTC)` : null;
506
+ }
422
507
  const [label, note] = this.previewSource(preview);
423
508
  const known = value => Number.isFinite(value) && value >= 0;
509
+ let counts;
510
+ if (evidenceOnly) counts = `${importHistoryStrings(this.getLocale()).collectionRead} ${tr.number(preview.profileEvidence)}`;
511
+ else if (library || collection) counts = known(preview.tracks) ? tr.n(preview.tracks, "{count} song", "{count} songs") : tr("Unknown number of songs");
512
+ else {
513
+ const plays = known(preview.listeningEvents) ? tr.n(preview.listeningEvents, "{count} play", "{count} plays") : tr("Unknown number of plays");
514
+ const tracks = known(preview.tracks) ? tr.n(preview.tracks, "{count} track", "{count} tracks") : tr("Unknown number of tracks");
515
+ counts = `${plays} · ${tracks}`;
516
+ }
517
+ const source = [label || tr("Your history"), clean(preview.fileName)];
518
+ const labels = importHistoryStrings(this.getLocale());
519
+ const excluded = [preview.excludedNonMusic > 0 && `${library ? labels.appleNonMusic : labels.excludedNonMusic} ${tr.number(preview.excludedNonMusic)}`,
520
+ preview.unidentifiedEntries > 0 && `${labels.excludedUnidentified} ${tr.number(preview.unidentifiedEntries)}`].filter(Boolean).join(" · ");
521
+ const chooseFile = { type: "file", label: tr("Choose a different file") };
522
+ if (library && preview.impact?.status === "legacy-unclassified") {
523
+ return { title: tr("Review your Apple Music library"), paragraphs: [...source, ...previewImpact(preview, this.getLocale())].filter(Boolean), actions: [chooseFile, back] };
524
+ }
525
+ if (library && !preview.tracks && preview.excludedNonMusic > 0) {
526
+ return { title: tr("Review your Apple Music library"), paragraphs: [...source, labels.appleNoMusic, excluded,
527
+ compareSnapshots && labels.appleExistingKept].filter(Boolean), actions: [chooseFile, back] };
528
+ }
529
+ if (preview.source === "spotify-extended" && preview.listeningEvents === 0) {
530
+ return { title: tr("Review this import"), paragraphs: [...source, counts, note, excluded].filter(Boolean), actions: [chooseFile, back] };
531
+ }
424
532
  return {
425
533
  title: library ? tr("Review your Apple Music library") : recent ? tr("Review recent listening") : tr("Review this import"),
426
534
  notice: tr("Nothing is added until you import it."),
427
535
  paragraphs: [
428
- label || tr("Your history"),
429
- clean(preview.fileName),
430
- library || collection
431
- ? known(preview.tracks) ? tr.n(preview.tracks, "{count} song", "{count} songs") : tr("Unknown number of songs")
432
- : `${known(preview.listeningEvents) ? tr.n(preview.listeningEvents, "{count} play", "{count} plays") : tr("Unknown number of plays")} · ${known(preview.tracks) ? tr.n(preview.tracks, "{count} track", "{count} tracks") : tr("Unknown number of tracks")}`,
433
- library || collection ? tr("As of {date}", { date: day(preview.capturedAt) ?? tr("an unknown date") }) : first && last ? tr("{first} to {last}", { first, last }) : tr("No dates in this file."),
434
- library || collection ? tr("This shows what you keep, so no plays will be added.") : recent
536
+ ...source,
537
+ compareSnapshots ? null : counts,
538
+ compareSnapshots || evidenceOnly ? null : dates,
539
+ ...previewImpact(preview, this.getLocale()),
540
+ library && known(preview.tracksWithLastPlayedAt) && known(preview.tracks)
541
+ ? `${labels.lastPlayedCoverage} · ${tr.number(preview.tracksWithLastPlayedAt)}/${tr.number(preview.tracks)}` : null,
542
+ collectionOnly ? tr("This shows what you keep, so no plays will be added.") : recent
435
543
  ? tr("Spotify doesn't say how long you listened to recent plays.")
436
544
  : preview.source === "lastfm"
437
545
  ? tr("Last.fm counts a play after half a song or four minutes. It doesn't say how long you listened.")
@@ -440,16 +548,17 @@ export class HistoryImportView {
440
548
  : tr("Listening time is known for {known} of {total} plays.", { known: tr.number(preview.eventsWithPlayedMs), total: tr.number(preview.listeningEvents) }),
441
549
  ...(preview.source === "lastfm" && preview.lovedTracks > 0
442
550
  ? [tr.n(preview.lovedTracks, "Also {count} loved track", "Also {count} loved tracks")]
443
- : preview.profileEvidence > 0 ? [tr.n(preview.profileEvidence, "Also {count} saved song, follow, or playlist entry", "Also {count} saved songs, follows, or playlist entries")] : []),
551
+ : !evidenceOnly && preview.profileEvidence > 0 ? [tr.n(preview.profileEvidence, "Also {count} saved song, follow, or playlist entry", "Also {count} saved songs, follows, or playlist entries")] : []),
444
552
  ...(preview.skippedRecords > 0 ? [tr.n(preview.skippedRecords, "Left out {count} podcast, video, or incomplete entry", "Left out {count} podcasts, videos, or incomplete entries")] : []),
445
553
  note,
554
+ excluded,
446
555
  ...(preview.sampleTracks ?? []).map((track) => ` ${clean(track)}`),
447
556
  ].filter(Boolean),
448
557
  actions: [
449
558
  { type: "commit", label: tr("Add to my profile") },
450
559
  recent ? { type: "recent", label: tr("Refresh recent listening") }
451
560
  : preview.source === "lastfm" ? { type: "lastfmUser", label: tr("Use a different username") }
452
- : { type: "file", label: tr("Choose a different file") }, back,
561
+ : chooseFile, back,
453
562
  ],
454
563
  };
455
564
  }
@@ -53,13 +53,18 @@ function exactArguments(action, rest, count, usage) {
53
53
  }
54
54
 
55
55
  function formatImport(value) {
56
+ const overlaps = (value.superseded_events ?? 0) + (value.mirrored_events ?? 0);
57
+ const upgraded = value.upgraded_recording_events ?? 0;
56
58
  return [
57
59
  "# Your ListenBrainz history is in",
58
60
  `- ${value.input_records ?? 0} listens in the file, from ${value.earliest_occurred_at?.slice(0, 10) ?? "an unknown date"} to ${value.latest_occurred_at?.slice(0, 10) ?? "an unknown date"}`,
59
61
  value.already_imported
60
62
  ? "- You imported this file before, so nothing new was added"
61
- : `- ${value.inserted_events ?? 0} new${value.duplicate_events ? `, ${value.duplicate_events} I already had` : ""}`,
62
- `- ${value.inserted_track_refs ?? 0} songs new to your profile; ListenBrainz matched ${value.mapped_track_refs ?? 0} to MusicBrainz`,
63
+ : `- New source records ${value.inserted_events ?? 0} · Already recorded ${value.duplicate_events ?? 0}`,
64
+ ...(overlaps ? [`- Overlapping records ${overlaps}`] : []),
65
+ ...(upgraded ? [`- Listens linked to a MusicBrainz recording ${upgraded}`] : []),
66
+ `- Change in play count ${value.effective_event_delta > 0 ? "+" : ""}${value.effective_event_delta}`,
67
+ `- New recording references ${value.inserted_track_refs ?? 0} · Matched to MusicBrainz in this file ${value.mapped_track_refs ?? 0}`,
63
68
  `- Listening time is known for ${value.events_with_played_ms ?? 0} of them`,
64
69
  "- The file itself wasn't copied, and no account details were kept",
65
70
  `- File fingerprint: ${value.archive_sha256 ?? "unavailable"}`,
@@ -1,31 +1,82 @@
1
- import { sanitizeTerminalText } from "./format-output.mjs";
1
+ import { collectionCoverageLines, sanitizeTerminalText } from "./format-output.mjs";
2
2
  import { N_, screenTranslator } from "../../i18n/index.mjs";
3
+ import { avoidKey } from "../../core/listener-avoids.mjs";
3
4
 
4
5
  export const savedProfileActions = new Set(["build", "saved", "explain"]);
5
6
 
6
7
  const kindLabels = { observation: N_("measured"), hypothesis: N_("interpretation"), listener_assertion: N_("your choice") };
7
8
 
9
+ function versionedChoice(value, claim) {
10
+ return claim.kind === "listener_assertion" && value.state === "stale" && !value.newer_listening_only;
11
+ }
12
+
13
+ function sameChoiceTarget(choice, target) {
14
+ return (choice.subject ?? choice.entity_type) === target.entity_type
15
+ && avoidKey(choice.name ?? choice.label) === avoidKey(target.label)
16
+ && avoidKey(choice.artist ?? choice.artist_credit) === avoidKey(target.artist_credit);
17
+ }
18
+
19
+ function choiceLine(label, choice, tr) {
20
+ const inline = text => sanitizeTerminalText(text ?? "").replace(/\s+/gu, " ").trim();
21
+ const title = inline(choice.name ?? choice.label);
22
+ const artist = inline(choice.artist ?? choice.artist_credit);
23
+ const name = artist ? tr("{title} by {artist}", { title, artist }) : title;
24
+ return `${label} · ${choice.stance === "like" ? tr("Like") : tr("Keep out")} · ${name}`;
25
+ }
26
+
27
+ export function formatReadingChoiceChanges(value, tr = screenTranslator("en"), target) {
28
+ if (value?.state !== "stale" || value.newer_listening_only || !value.choices_since_reading) return [];
29
+ const lines = [];
30
+ for (const [key, label] of [["added", tr("Current choice")], ["retracted", tr("Choice removed since this reading")]]) {
31
+ for (const choice of value.choices_since_reading[key] ?? []) {
32
+ if (choice.from_import || !["like", "avoid"].includes(choice.stance)) continue;
33
+ if (!target || sameChoiceTarget(choice, target)) lines.push(choiceLine(label, choice, tr));
34
+ }
35
+ }
36
+ if (lines.length && value.listener_choices?.total === 0) lines.push(tr("No active Likes or Avoids."));
37
+ return lines;
38
+ }
39
+
40
+ function selectedChoiceLines(application, value, tr) {
41
+ const target = value.supporting_evidence[0]?.data;
42
+ if (!target) return [];
43
+ // The reading keeps a bounded change list. An older choice can still be checked by its exact target.
44
+ const choices = application.tasteReviewChoices?.();
45
+ if (!Array.isArray(choices)) return formatReadingChoiceChanges(value, tr, target);
46
+ const active = choices.find(choice => sameChoiceTarget(choice, target));
47
+ if (active) return [choiceLine(tr("Current choice"), active, tr)];
48
+ return [choiceLine(tr("Choice removed since this reading"), { ...target, stance: value.claim.stance }, tr),
49
+ ...(choices.length ? [] : [tr("No active Likes or Avoids.")])];
50
+ }
51
+
8
52
  function builtLine(value, tr) {
9
53
  const coverage = value.coverage?.coverage ?? {};
10
54
  const concerns = value.verification?.state === "flagged" ? value.verification.checks.at(-1).issues.length : 0;
11
55
  const check = value.verification?.state === "revised" ? tr("checked and revised once")
12
56
  : concerns ? tr.n(concerns, "checked; one concern remains", "checked; {count} concerns remain") : tr("checked");
13
- const built = [
14
- tr("Built {date}", { date: value.built_at.slice(0, 10) }),
15
- ...(Number.isInteger(coverage.effective_listening_events) ? [tr.n(coverage.effective_listening_events, "from {count} play", "from {count} plays")] : []),
16
- ].join(" ");
57
+ const built = tr("Built {date}", { date: value.built_at.slice(0, 10) });
58
+ const plays = coverage.effective_listening_events;
59
+ if (!Number.isSafeInteger(plays) || plays < 1) {
60
+ const collections = collectionCoverageLines({ ...coverage, tracks_observed: coverage.apple_library_tracks }, tr);
61
+ return [built, ...collections, check].join(" · ");
62
+ }
17
63
  const span = coverage.earliest_played_at && coverage.latest_played_at
18
64
  ? `, ${tr("{first} to {last}", { first: coverage.earliest_played_at.slice(0, 10), last: coverage.latest_played_at.slice(0, 10) })}` : "";
19
- return `${built}${span} · ${check}`;
65
+ return `${built} ${tr.n(plays, "from {count} play", "from {count} plays")}${span} · ${check}`;
20
66
  }
21
67
 
22
68
  function formatSaved(value, prefix, allFindings = false, tr) {
23
- if (value.state === "missing") return tr("No saved reading yet. Use {prefix} build with a connected model.", { prefix });
69
+ const failure = value.last_build_failure;
70
+ const failureLine = failure && tr("The last update, on {date}, did not finish: {reason}",
71
+ { date: failure.at.slice(0, 10), reason: sanitizeTerminalText(failure.message) });
72
+ if (value.state === "missing") return failureLine
73
+ ? `${failureLine}\n${tr("No reading was saved. Use {prefix} build to try again.", { prefix })}`
74
+ : tr("No saved reading yet. Use {prefix} build with a connected model.", { prefix });
24
75
  const lines = [
25
76
  `# ${tr("Your saved listening profile · v{version}", { version: value.sequence })}`,
26
77
  value.state === "stale" ? tr("Evidence, choices or analysis changed. Use {prefix} build to update this reading.", { prefix }) : builtLine(value, tr),
27
- ...(value.last_build_failure ? [tr("The last update, on {date}, did not finish: {reason}",
28
- { date: value.last_build_failure.at.slice(0, 10), reason: sanitizeTerminalText(value.last_build_failure.message) })] : []),
78
+ ...(failureLine ? [failureLine] : []),
79
+ ...formatReadingChoiceChanges(value, tr),
29
80
  "", value.summary, "",
30
81
  ];
31
82
  // The TUI renders this text as Markdown, which renumbers an ordered list from its
@@ -34,8 +85,10 @@ function formatSaved(value, prefix, allFindings = false, tr) {
34
85
  ...(value.highlights ?? []), ...(value.listener_assertions ?? []),
35
86
  ].map(claim => [claim.claim_id, claim])).values()].sort((a, b) => a.finding_number - b.finding_number);
36
87
  for (const [index, claim] of displayed.entries()) {
88
+ const kind = versionedChoice(value, claim) ? tr("Choice in v{version}", { version: value.sequence })
89
+ : kindLabels[claim.kind] ? tr.marked(kindLabels[claim.kind]) : claim.kind.replaceAll("_", " ");
37
90
  lines.push(`${claim.finding_number ?? value.offset + index + 1}. ${claim.statement}`,
38
- ` ${kindLabels[claim.kind] ? tr.marked(kindLabels[claim.kind]) : claim.kind.replaceAll("_", " ")} · ${claim.scope} · ${claim.uncertainty}`);
91
+ ` ${kind} · ${claim.scope} · ${claim.uncertainty}`);
39
92
  }
40
93
  if (value.state === "current" && value.verification?.state === "flagged") {
41
94
  lines.push("", tr("The final check still flagged:"), ...value.verification.checks.at(-1).issues.map(issue => `- ${issue.problem}`));
@@ -84,6 +137,10 @@ export async function runListenerProfileCommand({
84
137
  rendered = [
85
138
  `# ${result.state === "stale" ? tr("Finding {number} · profile v{version} · needs update", { number: values[0], version: result.sequence })
86
139
  : tr("Finding {number} · profile v{version}", { number: values[0], version: result.sequence })}`,
140
+ ...(versionedChoice(result, result.claim) ? [
141
+ ...selectedChoiceLines(application, result, tr),
142
+ tr("Choice in v{version}", { version: result.sequence }),
143
+ ] : []),
87
144
  result.claim.statement, "", tr("Scope: {scope}", { scope: result.claim.scope }), tr("Uncertainty: {uncertainty}", { uncertainty: result.claim.uncertainty }),
88
145
  "", tr("Supporting evidence:"), ...result.supporting_evidence.map(formatEvidence),
89
146
  ...(result.contradicting_evidence.length ? ["", tr("Conflicting evidence:"), ...result.contradicting_evidence.map(formatEvidence)] : []),
@@ -101,6 +101,9 @@ export class ListeningMenu {
101
101
  if (before !== this.input.getValue()) {
102
102
  this.query = this.input.getValue();
103
103
  this.rebuildList();
104
+ const query = this.query.trim().toLowerCase();
105
+ const exact = this.filteredItems.findIndex((item) => item.label.toLowerCase() === query);
106
+ if (exact >= 0) this.select.setSelectedIndex(exact);
104
107
  }
105
108
  }
106
109
 
@@ -253,6 +253,7 @@ export async function runProfileCommand({
253
253
  const corrections = store.listListenerCorrections({
254
254
  subjectId,
255
255
  includeInactive: options.includeInactive,
256
+ limit: null,
256
257
  });
257
258
  value = {
258
259
  subject_id: subjectId,
@@ -17,7 +17,7 @@ import {
17
17
  } from "../../integrations/spotify/recent-activity.mjs";
18
18
  import { readSpotifyHistoryArchive } from "../../integrations/spotify/history-archive.mjs";
19
19
  import { projectSpotifyLibrarySnapshot } from "../../integrations/spotify/library-snapshot.mjs";
20
- import { sanitizeTerminalText } from "./format-output.mjs";
20
+ import { formatImportReceipt, sanitizeTerminalText } from "./format-output.mjs";
21
21
 
22
22
  const readCommands = new Set(["account", "now", "devices", "queue", "recent", "library"]);
23
23
  const writeCommands = new Set([
@@ -248,7 +248,6 @@ function itemLabel(item) {
248
248
 
249
249
  function formatPlain(action, value) {
250
250
  const plays = (count) => `${count ?? 0} ${count === 1 ? "play" : "plays"}`;
251
- const day = (timestamp) => typeof timestamp === "string" ? timestamp.slice(0, 10) : "an unknown date";
252
251
  if (action === "configure") {
253
252
  return [
254
253
  "Spotify app saved.",
@@ -375,25 +374,14 @@ function formatPlain(action, value) {
375
374
  ].join("\n");
376
375
  }
377
376
  if (action === "import-history") {
378
- const extended =
379
- value.data_scope === "lifetime_extended_streaming_history";
380
- const lines = [
381
- extended ? "# Your Spotify history is in" : "# Your Spotify account data is in",
382
- `- ${plays(value.input_records)} in the file, from ${day(value.earliest_occurred_at)} to ${day(value.latest_occurred_at)}`,
383
- value.already_imported
384
- ? "- You imported this file before, so nothing new was added"
385
- : `- ${value.inserted_events ?? 0} new${value.duplicate_events ? `, ${value.duplicate_events} I already had` : ""}`,
386
- ];
387
- if (value.superseded_events > 0) {
388
- lines.push(`- ${plays(value.superseded_events)} you already had were replaced with more detailed versions`);
389
- }
390
- if (value.inserted_track_refs > 0) lines.push(`- ${value.inserted_track_refs} songs new to your profile`);
391
- if (!extended && value.inserted_profile_evidence > 0) {
392
- lines.push(`- ${value.inserted_profile_evidence} saved songs, follows, and playlist entries`);
377
+ const heading = value.data_scope === "lifetime_extended_streaming_history"
378
+ ? "# Your Spotify history is in" : "# Your Spotify account data is in";
379
+ const lines = [`- ${plays(value.input_records)} in the file`];
380
+ if (Number.isInteger(value.events_with_played_ms) && value.input_records > 0) {
381
+ lines.push(`- Listening time is known for ${value.events_with_played_ms} of ${plays(value.input_records)}`);
393
382
  }
394
- if (!extended) lines.push("- This format doesn't include listening time. Extended streaming history does.");
395
383
  lines.push(`- File fingerprint: ${value.archive_sha256 ?? "unavailable"}`);
396
- return lines.join("\n");
384
+ return [heading, formatImportReceipt({ kind: "history" }, value), lines.join("\n")].join("\n\n");
397
385
  }
398
386
  return JSON.stringify(value, null, 2);
399
387
  }
@@ -540,7 +528,7 @@ async function runReadCommand(action, service, input, { signal, onProgress } = {
540
528
  return service.queue();
541
529
  }
542
530
 
543
- async function runWriteCommand(action, rest, service) {
531
+ async function runWriteCommand(action, rest, service, playbackOptions) {
544
532
  if (["pause", "next", "previous"].includes(action)) {
545
533
  exactArguments(action, rest, 0);
546
534
  return actionResult(await service[action](), `playback.${action}`);
@@ -548,7 +536,7 @@ async function runWriteCommand(action, rest, service) {
548
536
  if (action === "play") {
549
537
  if (rest.length > 1) throw commandError("Usage: moondog spotify play [spotify-uri].");
550
538
  const input = rest[0] ? { uris: [rest[0]] } : undefined;
551
- return actionResult(await service.resume(input), "playback.resume");
539
+ return actionResult(await service.resume(input, playbackOptions), "playback.resume");
552
540
  }
553
541
  if (action === "volume") {
554
542
  exactArguments(action, rest, 1, "volume <0-100>");
@@ -591,7 +579,7 @@ async function runWriteCommand(action, rest, service) {
591
579
  throw commandError("Usage: moondog spotify transfer <device-id> [--play].");
592
580
  }
593
581
  return actionResult(
594
- await service.transfer({ deviceId: rest[0], play: rest[1] === "--play" }),
582
+ await service.transfer({ deviceId: rest[0], play: rest[1] === "--play" }, playbackOptions),
595
583
  "playback.transfer",
596
584
  );
597
585
  }
@@ -627,6 +615,7 @@ export async function runSpotifyCommand({
627
615
  signalTarget = process,
628
616
  signal,
629
617
  onProgress,
618
+ onPlaybackStarted,
630
619
  } = {}) {
631
620
  const options = parseArguments(args, json);
632
621
  const action = options.action;
@@ -685,8 +674,11 @@ export async function runSpotifyCommand({
685
674
  () => recentActivityStore.ingestImport(bundle),
686
675
  "Spotify account-data history could not be stored.",
687
676
  );
688
- emit(stdout, action, result, options.json);
689
- return result;
677
+ const receipt = Array.isArray(bundle.listening_events)
678
+ ? { ...result, events_with_played_ms: bundle.listening_events.filter(event => Number.isSafeInteger(event.played_ms)).length }
679
+ : result;
680
+ emit(stdout, action, receipt, options.json);
681
+ return receipt;
690
682
  }
691
683
 
692
684
  const runtime = createRuntimeResolver({
@@ -889,7 +881,7 @@ export async function runSpotifyCommand({
889
881
 
890
882
  const service = await runtime.service();
891
883
  const result = await externalCall(
892
- () => runWriteCommand(action, options.rest, service),
884
+ () => runWriteCommand(action, options.rest, service, { signal, onPlaybackStarted }),
893
885
  `Spotify ${action} failed.`,
894
886
  );
895
887
  emit(stdout, action, result, options.json);
@@ -0,0 +1,22 @@
1
+ import { screenTranslator } from "../../i18n/index.mjs";
2
+ import { utcDay } from "../import-source-history.mjs";
3
+
4
+ function lastRecordedPlay(profile) {
5
+ return utcDay(profile?.listening_behavior?.context?.reference_date)
6
+ ?? utcDay(profile?.listening_source?.listening_range?.latest) ?? utcDay(profile?.coverage?.latest_played_at);
7
+ }
8
+
9
+ export function recordedHistoryThrough(profile, tr = screenTranslator("en")) {
10
+ const date = lastRecordedPlay(profile);
11
+ return date ? tr("History through {date} (UTC)", { date }) : tr("Near the end of your recorded history");
12
+ }
13
+
14
+ export function recentListeningPeriod(profile, tr = screenTranslator("en")) {
15
+ const context = profile?.listening_behavior?.context;
16
+ const days = context?.recent_window_days;
17
+ if (!Number.isSafeInteger(days) || days < 1) return tr("Near the end of your recorded history");
18
+ const date = lastRecordedPlay(profile);
19
+ return date
20
+ ? tr.n(days, "{count} day ending {date} (UTC)", "{count} days ending {date} (UTC)", { date })
21
+ : tr.n(days, "Final {count} day of recorded history", "Final {count} days of recorded history");
22
+ }