@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
@@ -1,32 +1,63 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { chmod, mkdir } from "node:fs/promises";
2
+ import { chmod, mkdir, stat } from "node:fs/promises";
3
3
  import path from "node:path";
4
+ import { pathToFileURL } from "node:url";
4
5
 
5
6
  import { resolveMoondogStateDirectory } from "../core/state-directory.mjs";
6
7
  import { isUuid } from "../core/uuid-v5.mjs";
8
+ import { historyAvoidArtists } from "../core/listener-avoids.mjs";
9
+ import { LISTENBRAINZ_HISTORY_SOURCE, listenBrainzMsidTrackRefId } from "../integrations/listenbrainz/history-file.mjs";
10
+ import { isPreviouslySkippedSpotifyHistoryMember } from "../integrations/spotify/extended-streaming-history.mjs";
7
11
  import {
8
12
  createListenerCorrection,
9
13
  createListenerCorrectionRetraction,
10
14
  } from "./listener-corrections.mjs";
11
15
  import { projectListeningProfile } from "./listening-profile-projection.mjs";
12
16
  import {
13
- listeningFamiliarity, markMoondogStartedPlays, mixSlot, suggestionEntry, suggestionIdentities, SUGGESTION_WINDOW,
17
+ listeningFamiliarity, markMoondogStartedPlays, mixSlot, PLAYLIST_SAVE_ACTION, sameCompletedRecording, suggestionEntry, suggestionIdentities, SUGGESTION_WINDOW,
14
18
  } from "./moondog-suggestions.mjs";
15
19
  import { ListenerProfileStore, listenerProfileSchema } from "./listener-profile-store.mjs";
16
20
 
17
21
  export const LISTENING_HISTORY_SCHEMA_VERSION = 7;
22
+ const SPOTIFY_QUICK_FORMAT = "spotify_quick_import_v1";
23
+
24
+ // The profile excludes Spotify's explicit private-session flag. Both attention views use the same rule.
25
+ const attentionEvents = `e.subject_id = ?
26
+ AND NOT EXISTS (SELECT 1 FROM listening_event_supersessions s WHERE s.superseded_event_id = e.listening_event_id)
27
+ AND NOT EXISTS (SELECT 1 FROM listening_event_mirrors m WHERE m.mirror_event_id = e.listening_event_id)
28
+ AND json_type(e.record_json, '$.extensions."spotify.incognito_mode"') IS NOT 'true'`;
18
29
 
19
30
  // The tables a cached projection, build input, Avoid gate or status reads, apart from the
20
- // suggestions ledger (listeningDataVersion). Rows are only added to the first ones: the one
21
- // update to a stored play, which records the play that supersedes it, is made with its row in
22
- // listening_event_supersessions. Imports update their batch rows, so those are read in full.
31
+ // suggestions ledger (listeningDataVersion). Changes to a stored play also append a
32
+ // supersession, an import batch or a repair marker. Import batch rows are read in full.
23
33
  // A new table those caches read, or a new update or delete, belongs here.
24
34
  const APPENDED_EVIDENCE_TABLES = Object.freeze([
25
- "track_refs", "listening_events", "listening_event_supersessions", "listening_event_mirrors",
35
+ "track_refs", "listening_events", "listening_event_supersessions", "listening_event_mirrors", "listening_history_repairs",
26
36
  "spotify_profile_evidence", "taste_events",
27
37
  ]);
28
38
  const UPDATED_EVIDENCE_TABLES = Object.freeze(["import_batches", "profile_import_batches"]);
29
39
 
40
+ // Hash the actual collection, choices, and projected play rows held by each dated reading.
41
+ // The query orders plays by timestamp and ID, so all saved cutoffs share one pass through the history.
42
+ function historyDigestsThrough(cutoffs, rows, profileEvidence, tasteEvents) {
43
+ const dates = [...new Set(cutoffs.filter(Boolean))].sort();
44
+ const digests = {};
45
+ if (!dates.length) return digests;
46
+ const digest = createHash("sha256");
47
+ for (const group of [profileEvidence, tasteEvents]) {
48
+ for (const row of group) digest.update(JSON.stringify(row)).update("\n");
49
+ digest.update("\0");
50
+ }
51
+ let index = 0;
52
+ for (const through of dates) {
53
+ while (index < rows.length && rows[index].event.occurred_at <= through) {
54
+ digest.update(JSON.stringify(rows[index++])).update("\n");
55
+ }
56
+ digests[through] = digest.copy().digest("hex");
57
+ }
58
+ return digests;
59
+ }
60
+
30
61
  export function resolveListeningHistoryPath(environment = process.env) {
31
62
  return path.join(resolveMoondogStateDirectory(environment), "listening-history.sqlite");
32
63
  }
@@ -103,6 +134,31 @@ const schema = `
103
134
  UNIQUE (source_key, subject_id, archive_sha256)
104
135
  ) STRICT;
105
136
 
137
+ -- A repeat is another confirmed import even when it adds no listening evidence.
138
+ CREATE TABLE IF NOT EXISTS listening_import_receipts (
139
+ receipt_id INTEGER PRIMARY KEY,
140
+ import_batch_id TEXT REFERENCES import_batches(import_batch_id) ON DELETE CASCADE,
141
+ subject_id TEXT NOT NULL,
142
+ source_key TEXT NOT NULL,
143
+ source_format TEXT NOT NULL,
144
+ data_scope TEXT NOT NULL,
145
+ imported_at TEXT NOT NULL,
146
+ earliest_occurred_at TEXT,
147
+ latest_occurred_at TEXT,
148
+ input_records INTEGER NOT NULL,
149
+ inserted_events INTEGER NOT NULL,
150
+ duplicate_events INTEGER NOT NULL,
151
+ captured_at TEXT,
152
+ input_profile_evidence INTEGER,
153
+ superseded_events INTEGER,
154
+ mirrored_events INTEGER,
155
+ inserted_profile_evidence INTEGER,
156
+ events_with_played_ms INTEGER,
157
+ already_imported INTEGER CHECK (already_imported IN (0, 1))
158
+ ) STRICT;
159
+ CREATE INDEX IF NOT EXISTS listening_import_receipts_batch ON listening_import_receipts(import_batch_id);
160
+ CREATE INDEX IF NOT EXISTS listening_import_receipts_time ON listening_import_receipts(subject_id, imported_at DESC, receipt_id DESC);
161
+
106
162
  CREATE TABLE IF NOT EXISTS listening_event_supersessions (
107
163
  superseded_event_id TEXT PRIMARY KEY NOT NULL,
108
164
  superseding_event_id TEXT NOT NULL UNIQUE,
@@ -139,6 +195,10 @@ const schema = `
139
195
  REFERENCES listening_events(listening_event_id)
140
196
  ) STRICT;
141
197
 
198
+ CREATE TABLE IF NOT EXISTS listening_history_repairs (
199
+ repair_key TEXT PRIMARY KEY NOT NULL
200
+ ) STRICT;
201
+
142
202
  CREATE TABLE IF NOT EXISTS profile_import_batches (
143
203
  profile_import_id TEXT PRIMARY KEY NOT NULL,
144
204
  subject_id TEXT NOT NULL,
@@ -246,6 +306,21 @@ function isPlainObject(value) {
246
306
  return prototype === Object.prototype || prototype === null;
247
307
  }
248
308
 
309
+ function suggestionsByIdentity(suggestions) {
310
+ const byIdentity = new Map();
311
+ for (const suggestion of suggestions) {
312
+ for (const identity of suggestionIdentities(suggestion)) {
313
+ if (!byIdentity.has(identity)) byIdentity.set(identity, []);
314
+ byIdentity.get(identity).push(suggestion);
315
+ }
316
+ }
317
+ return byIdentity;
318
+ }
319
+
320
+ function lookupSuggestion(track) {
321
+ return suggestionEntry({ service: "spotify", action: "lookup", ...track, artistCredit: track?.artistCredit ?? track?.artist_credit });
322
+ }
323
+
249
324
  function cleanSourceKey(value) {
250
325
  if (
251
326
  typeof value !== "string" ||
@@ -450,7 +525,6 @@ function normalizedProfileInput(value, batch) {
450
525
  archiveSizeBytes: profileImport.archive_size_bytes,
451
526
  memberNames: [...profileImport.member_names],
452
527
  inputRecords: profileImport.input_records,
453
- importedAt,
454
528
  },
455
529
  profileEvidence: records,
456
530
  };
@@ -680,18 +754,19 @@ function insertBundleRecords(bundle, statements) {
680
754
  return { insertedTracks, insertedEvents };
681
755
  }
682
756
 
757
+ const MUSIC_APP_PLAY = "apple_music.music_app_play";
758
+
683
759
  // Where stored plays came from, in words the agent can repeat. Others keep their kind.
684
760
  const COVERAGE_SOURCE_LABELS = {
685
761
  "spotify.play_history": "Spotify recent plays, read while Moondog runs",
686
762
  "spotify.extended_history.play": "Spotify Extended Streaming History file",
687
763
  "spotify.account_data.play_history": "Spotify Account Data file",
688
764
  "listenbrainz.listen": "ListenBrainz export file",
689
- "apple_music.music_app_play": "Music app plays on this Mac, kept while Moondog runs",
765
+ [MUSIC_APP_PLAY]: "Music app plays on this Mac, kept while Moondog runs",
690
766
  };
691
767
 
692
768
  const SCROBBLE_SOURCE_KEY = "lastfm.music_import";
693
- // Scrobbles record when a song started. Spotify records when a play ended, so its start is
694
- // the end minus the listening time; Account Data times are rounded to the minute.
769
+ // Scrobbles record when a song started. Spotify Account Data times are rounded to the minute.
695
770
  const MIRROR_TOLERANCE_MS = 150_000;
696
771
  const DAY_MS = 86_400_000;
697
772
 
@@ -706,11 +781,11 @@ const foldLabel = (value) => String(value ?? "").normalize("NFKC").toLocaleLower
706
781
  const lexicalCompare = (left, right) => (left < right ? -1 : left > right ? 1 : 0);
707
782
 
708
783
  /**
709
- * Many Last.fm scrobbles repeat plays that Spotify or ListenBrainz recorded too. Each scrobble
784
+ * Many Last.fm scrobbles repeat plays that another service recorded too. Each scrobble
710
785
  * that matches another service's play (same artist and title, starting within a few minutes)
711
786
  * is linked to it once, whichever was imported first, so the play counts once.
712
787
  */
713
- function reconcileScrobbleMirrors(database, subjectId, earliest, latest, createdAt) {
788
+ function reconcileScrobbleMirrors(database, subjectId, earliest, latest, createdAt, { musicAppOnly = false, maxPairs = Infinity } = {}) {
714
789
  if (!subjectId || !earliest || !latest) return 0;
715
790
  const scrobbled = database.prepare(
716
791
  "SELECT 1 FROM import_batches WHERE subject_id = ? AND source_key = ? LIMIT 1",
@@ -747,17 +822,25 @@ function reconcileScrobbleMirrors(database, subjectId, earliest, latest, created
747
822
  if (!artist || !title) continue;
748
823
  const key = `${artist}\u0000${title}`;
749
824
  const at = Date.parse(row.at);
750
- const system = String(event.provenance?.external_ref?.system ?? "");
825
+ const source = event.provenance?.external_ref;
826
+ const system = String(source?.system ?? "");
751
827
  if (system === "lastfm") {
752
828
  if (!scrobbles.has(key)) scrobbles.set(key, []);
753
829
  scrobbles.get(key).push({ id: row.id, start: at });
754
830
  continue;
755
831
  }
756
- const length = Number.isSafeInteger(event.played_ms) ? event.played_ms
757
- : Number.isSafeInteger(track.duration_ms) ? track.duration_ms : null;
758
- // A Spotify play of unknown length can't be placed precisely enough to match.
759
- if (system.startsWith("spotify") && length === null) continue;
760
- plays.push({ id: row.id, key, start: system.startsWith("spotify") ? at - length : at });
832
+ const musicApp = event.provenance?.source_kind === "tool" && system === "apple_music" && source.entity_type === MUSIC_APP_PLAY;
833
+ if (musicAppOnly && !musicApp) continue;
834
+ let start = at;
835
+ if (musicApp || system.startsWith("spotify")) {
836
+ // The Music app watcher records the end and how long it actually heard the song.
837
+ // A catalog duration cannot recover the beginning of a partial or skipped play.
838
+ let duration = event.played_ms;
839
+ if (!musicApp && !Number.isSafeInteger(duration)) duration = track.duration_ms;
840
+ if (!Number.isSafeInteger(duration) || duration < 0) continue;
841
+ start -= duration;
842
+ }
843
+ plays.push({ id: row.id, key, start });
761
844
  }
762
845
  const pairs = [];
763
846
  for (const list of scrobbles.values()) list.sort((left, right) => left.start - right.start);
@@ -772,6 +855,7 @@ function reconcileScrobbleMirrors(database, subjectId, earliest, latest, created
772
855
  else high = middle;
773
856
  }
774
857
  for (let index = low; index < list.length && list[index].start <= play.start + MIRROR_TOLERANCE_MS; index += 1) {
858
+ if (pairs.length === maxPairs) throw comparisonLimit();
775
859
  pairs.push({ gap: Math.abs(list[index].start - play.start), play: play.id, scrobble: list[index].id });
776
860
  }
777
861
  }
@@ -794,6 +878,108 @@ function reconcileScrobbleMirrors(database, subjectId, earliest, latest, created
794
878
  return linked;
795
879
  }
796
880
 
881
+ function repairEarlierMusicAppMirrors(database, maxPairs = Infinity) {
882
+ const key = "music_app_scrobble_starts";
883
+ if (database.prepare("SELECT 1 FROM listening_history_repairs WHERE repair_key = ?").get(key)) return;
884
+ database.exec("BEGIN IMMEDIATE");
885
+ try {
886
+ if (database.prepare("INSERT OR IGNORE INTO listening_history_repairs (repair_key) VALUES (?)").run(key).changes) {
887
+ const watched = `json_extract(record_json, '$.provenance.source_kind') = 'tool'
888
+ AND json_extract(record_json, '$.provenance.external_ref.system') = 'apple_music'
889
+ AND json_extract(record_json, '$.provenance.external_ref.entity_type') = '${MUSIC_APP_PLAY}'`;
890
+ const windows = database.prepare(`SELECT MIN(occurred_at) AS earliest, MAX(occurred_at) AS latest
891
+ FROM listening_events WHERE subject_id = ? AND ${watched} GROUP BY substr(occurred_at, 1, 7) ORDER BY earliest`);
892
+ const unlink = database.prepare(`DELETE FROM listening_event_mirrors WHERE original_event_id IN
893
+ (SELECT listening_event_id FROM listening_events WHERE subject_id = ? AND ${watched})`);
894
+ const now = new Date().toISOString();
895
+ for (const { subject_id } of database.prepare("SELECT DISTINCT subject_id FROM import_batches WHERE source_key = ?").all(SCROBBLE_SOURCE_KEY)) {
896
+ const months = windows.all(subject_id);
897
+ if (!months.length) continue;
898
+ // The old comparison could link the next scrobble to the previous play of the same song.
899
+ unlink.run(subject_id);
900
+ for (const { earliest, latest } of months) {
901
+ reconcileScrobbleMirrors(database, subject_id, earliest, latest, now, { musicAppOnly: true, maxPairs });
902
+ }
903
+ }
904
+ }
905
+ database.exec("COMMIT");
906
+ } catch (error) {
907
+ database.exec("ROLLBACK");
908
+ throw error;
909
+ }
910
+ }
911
+
912
+ const isListenBrainzEvent = `json_extract(e.record_json, '$.provenance.external_ref.system') = 'listenbrainz'
913
+ AND json_extract(e.record_json, '$.provenance.external_ref.entity_type') = 'listenbrainz.listen'`;
914
+
915
+ // 0.4.0-beta.3 and earlier keyed a mapped listen on its MusicBrainz recording, so a
916
+ // listen saved once unmapped and again mapped became two rows. A mapped listen now
917
+ // finds the first by its deduplication key and the second by its event ID: count one.
918
+ function supersedeEarlierListenBrainzCopies(database, bundle, createdAt) {
919
+ const pair = database.prepare(`SELECT p.listening_event_id AS provisional FROM listening_events p, listening_events r
920
+ WHERE p.deduplication_key = ? AND r.listening_event_id = ? AND p.listening_event_id <> r.listening_event_id
921
+ AND p.subject_id = r.subject_id
922
+ AND json_type(r.record_json, '$.extensions."listenbrainz.recording_msid"') IS NULL
923
+ AND NOT EXISTS (SELECT 1 FROM listening_event_supersessions s
924
+ WHERE s.superseded_event_id IN (p.listening_event_id, r.listening_event_id)
925
+ OR s.superseding_event_id IN (p.listening_event_id, r.listening_event_id))
926
+ AND NOT (EXISTS (SELECT 1 FROM listening_event_mirrors WHERE original_event_id = p.listening_event_id)
927
+ AND EXISTS (SELECT 1 FROM listening_event_mirrors WHERE original_event_id = r.listening_event_id))`);
928
+ const link = database.prepare(`INSERT INTO listening_event_supersessions
929
+ (superseded_event_id, superseding_event_id, import_batch_id, created_at) VALUES (?, ?, ?, ?)`);
930
+ const record = database.prepare(`UPDATE listening_events SET record_json =
931
+ json_set(record_json, '$.supersedes_listening_event_id', ?) WHERE listening_event_id = ?`);
932
+ let linked = 0;
933
+ for (const event of bundle.listeningEvents) {
934
+ if (!event.extensions || !Object.hasOwn(event.extensions, "listenbrainz.recording_msid")) continue;
935
+ const match = pair.get(event.deduplication_key, event.listening_event_id);
936
+ if (!match) continue;
937
+ link.run(match.provisional, event.listening_event_id, bundle.importBatch.importBatchId, createdAt);
938
+ record.run(match.provisional, event.listening_event_id);
939
+ linked += 1;
940
+ }
941
+ return linked;
942
+ }
943
+
944
+ function upgradeListenBrainzRecordings(database, subjectId, bundle) {
945
+ const provisional = database.prepare("SELECT 1 FROM listening_events WHERE subject_id = ? AND track_ref_id = ? LIMIT 1");
946
+ const involved = new Map();
947
+ const resolvedTracks = new Set();
948
+ for (const track of bundle.trackRefs) {
949
+ if (track.identity_status === "resolved") resolvedTracks.add(track.track_ref_id);
950
+ const msid = track.external_refs?.find(ref => ref.system === "listenbrainz" && ref.entity_type === "listenbrainz.recording_msid")?.external_id;
951
+ if (msid) involved.set(msid, listenBrainzMsidTrackRefId(msid));
952
+ }
953
+ for (const event of bundle.listeningEvents) {
954
+ const msid = event.extensions?.["listenbrainz.recording_msid"];
955
+ if (msid && !involved.has(msid)) involved.set(msid, listenBrainzMsidTrackRefId(msid));
956
+ }
957
+ for (const [msid, trackId] of involved) {
958
+ if (!provisional.get(subjectId, trackId)) involved.delete(msid);
959
+ }
960
+ if (!involved.size) return 0;
961
+ const mappings = new Map();
962
+ const observe = (msid, trackId) => {
963
+ if (involved.has(msid)) mappings.set(msid, !mappings.has(msid) || mappings.get(msid) === trackId ? trackId : null);
964
+ };
965
+ for (const event of bundle.listeningEvents) {
966
+ if (resolvedTracks.has(event.track_ref_id)) observe(event.extensions?.["listenbrainz.recording_msid"], event.track_ref_id);
967
+ }
968
+ const known = database.prepare(`SELECT DISTINCT json_extract(e.record_json, '$.extensions."listenbrainz.recording_msid"') AS msid, e.track_ref_id
969
+ FROM listening_events e JOIN track_refs t ON t.track_ref_id = e.track_ref_id AND t.revision = e.track_ref_revision
970
+ WHERE e.subject_id = ? AND json_extract(t.record_json, '$.identity_status') = 'resolved' AND ${isListenBrainzEvent}`);
971
+ for (const row of known.iterate(subjectId)) observe(row.msid, row.track_ref_id);
972
+ const upgrade = database.prepare(`UPDATE listening_events AS e SET track_ref_id = ?,
973
+ record_json = json_set(record_json, '$.track_ref_id', ?, '$.extensions."listenbrainz.recording_msid"', ?)
974
+ WHERE e.subject_id = ? AND e.track_ref_id = ? AND e.track_ref_revision = 1 AND ${isListenBrainzEvent}
975
+ AND NOT EXISTS (SELECT 1 FROM listening_event_supersessions WHERE superseded_event_id = e.listening_event_id)`);
976
+ let upgraded = 0;
977
+ for (const [msid, trackId] of mappings) {
978
+ if (trackId) upgraded += upgrade.run(trackId, trackId, msid, subjectId, involved.get(msid)).changes;
979
+ }
980
+ return upgraded;
981
+ }
982
+
797
983
  function preserveExtendedHistoryMatches(bundle, retainedMatch) {
798
984
  const candidates = bundle.reconciliationCandidates;
799
985
  if (bundle.importBatch.sourceFormat !== "spotify_extended_streaming_history_music_v1") return candidates;
@@ -804,7 +990,7 @@ function preserveExtendedHistoryMatches(bundle, retainedMatch) {
804
990
  retained.get(candidate.supersedingEventId) !== candidate.supersededEventId)) return candidates;
805
991
 
806
992
  // Account Data cannot distinguish equal-duration plays of the same title and
807
- // artist within one minute. Added video plays can reorder those ordinals.
993
+ // artist within one minute. Newly recovered plays can reorder those ordinals.
808
994
  // A narrower export may omit an established counterpart's ordinal entirely.
809
995
  // Keep those pairs too; only new plays use this archive's remaining candidates.
810
996
  // The store's conflict checks still reject a new play claiming an absent play's
@@ -847,8 +1033,45 @@ function preserveExtendedHistoryMatches(bundle, retainedMatch) {
847
1033
  }));
848
1034
  }
849
1035
 
1036
+ const localSubjectSources = ["listening_events", "import_batches", "profile_import_batches", "spotify_profile_evidence", "taste_events"];
1037
+
1038
+ function resolveLocalMusicSubject(database, { preferredSubjectId, create = false, register = false, availableTables, schemaName = "main" } = {}) {
1039
+ if (preferredSubjectId !== undefined && !isUuid(preferredSubjectId)) {
1040
+ throw new TypeError("A valid preferred local music subject is required");
1041
+ }
1042
+ if (typeof create !== "boolean") throw new TypeError("Local music subject creation flag is invalid");
1043
+ const preferred = preferredSubjectId?.toLowerCase() ?? null;
1044
+ if (!database) return preferred;
1045
+
1046
+ const hasTable = name => !availableTables || availableTables.has(name);
1047
+ const registered = hasTable("local_music_subject")
1048
+ ? database.prepare(`SELECT subject_id FROM ${schemaName}.local_music_subject WHERE singleton = 1`).get()?.subject_id
1049
+ : undefined;
1050
+ let stored;
1051
+ if (registered !== undefined) {
1052
+ if (!isUuid(registered)) throw new Error("The local music subject registry is invalid");
1053
+ stored = registered.toLowerCase();
1054
+ } else {
1055
+ const sources = localSubjectSources.filter(hasTable);
1056
+ const select = sources.map(name => `SELECT DISTINCT subject_id FROM ${schemaName}.${name}`).join(" UNION ");
1057
+ const observed = select ? database.prepare(select).all().map(row => row.subject_id?.toLowerCase()) : [];
1058
+ if (observed.some(id => !isUuid(id))) throw new Error("Stored listening history contains an invalid subject");
1059
+ if (observed.length > 1) throw new Error("Stored listening history contains multiple local music subjects");
1060
+ stored = observed[0];
1061
+ }
1062
+ if (preferred && stored && preferred !== stored) {
1063
+ throw new Error("The trusted Apple and local listening-history subjects do not match");
1064
+ }
1065
+ const resolved = stored ?? preferred ?? (create ? randomUUID() : null);
1066
+ if (register && registered === undefined && resolved) {
1067
+ database.prepare("INSERT INTO local_music_subject (singleton, subject_id) VALUES (1, ?)").run(resolved);
1068
+ }
1069
+ return resolved;
1070
+ }
1071
+
850
1072
  export class ListeningHistoryStore {
851
1073
  #database;
1074
+ #maxMirrorPairs;
852
1075
  #closed = false;
853
1076
  #snapshot = null;
854
1077
  #projection = null;
@@ -857,8 +1080,9 @@ export class ListeningHistoryStore {
857
1080
  #ledgerChanges = 0;
858
1081
  #listeningDays = null;
859
1082
 
860
- constructor(database) {
1083
+ constructor(database, { maxMirrorPairs = Infinity } = {}) {
861
1084
  this.#database = database;
1085
+ this.#maxMirrorPairs = maxMirrorPairs;
862
1086
  }
863
1087
 
864
1088
  sourceCursor(sourceKey) {
@@ -875,70 +1099,7 @@ export class ListeningHistoryStore {
875
1099
 
876
1100
  localSubjectId({ preferredSubjectId, create = false } = {}) {
877
1101
  if (this.#closed) throw new Error("Listening history store is closed");
878
- if (preferredSubjectId !== undefined && !isUuid(preferredSubjectId)) {
879
- throw new TypeError("A valid preferred local music subject is required");
880
- }
881
- if (typeof create !== "boolean") {
882
- throw new TypeError("Local music subject creation flag is invalid");
883
- }
884
- const preferred = preferredSubjectId?.toLowerCase() ?? null;
885
- const registered = this.#database
886
- .prepare(
887
- "SELECT subject_id FROM local_music_subject WHERE singleton = 1",
888
- )
889
- .get()?.subject_id;
890
- if (registered !== undefined) {
891
- if (!isUuid(registered)) {
892
- throw new Error("The local music subject registry is invalid");
893
- }
894
- const normalized = registered.toLowerCase();
895
- if (preferred && preferred !== normalized) {
896
- throw new Error(
897
- "The trusted Apple and local listening-history subjects do not match",
898
- );
899
- }
900
- return normalized;
901
- }
902
-
903
- const observed = this.#database
904
- .prepare(
905
- `SELECT subject_id FROM (
906
- SELECT subject_id FROM listening_events
907
- UNION
908
- SELECT subject_id FROM import_batches
909
- UNION
910
- SELECT subject_id FROM profile_import_batches
911
- UNION
912
- SELECT subject_id FROM spotify_profile_evidence
913
- UNION
914
- SELECT subject_id FROM taste_events
915
- )
916
- ORDER BY subject_id`,
917
- )
918
- .all()
919
- .map((row) => row.subject_id?.toLowerCase());
920
- if (observed.some((subjectId) => !isUuid(subjectId))) {
921
- throw new Error("Stored listening history contains an invalid subject");
922
- }
923
- if (observed.length > 1) {
924
- throw new Error(
925
- "Stored listening history contains multiple local music subjects",
926
- );
927
- }
928
- const inherited = observed[0] ?? null;
929
- if (preferred && inherited && preferred !== inherited) {
930
- throw new Error(
931
- "The trusted Apple and local listening-history subjects do not match",
932
- );
933
- }
934
- const resolved = inherited ?? preferred ?? (create ? randomUUID() : null);
935
- if (!resolved) return null;
936
- this.#database
937
- .prepare(
938
- "INSERT INTO local_music_subject (singleton, subject_id) VALUES (1, ?)",
939
- )
940
- .run(resolved);
941
- return resolved;
1102
+ return resolveLocalMusicSubject(this.#database, { preferredSubjectId, create, register: true });
942
1103
  }
943
1104
 
944
1105
  subjectDataStatus({ subjectId } = {}) {
@@ -1209,6 +1370,7 @@ export class ListeningHistoryStore {
1209
1370
 
1210
1371
  listListenerCorrections({
1211
1372
  subjectId,
1373
+ targetKey = null,
1212
1374
  includeInactive = false,
1213
1375
  limit = 50,
1214
1376
  } = {}) {
@@ -1219,7 +1381,7 @@ export class ListeningHistoryStore {
1219
1381
  if (typeof includeInactive !== "boolean") {
1220
1382
  throw new TypeError("Listener correction history flag is invalid");
1221
1383
  }
1222
- if (!Number.isInteger(limit) || limit < 1 || limit > 100) {
1384
+ if (limit !== null && (!Number.isInteger(limit) || limit < 1 || limit > 100)) {
1223
1385
  throw new TypeError("Listener correction limit is invalid");
1224
1386
  }
1225
1387
  const rows = this.#database
@@ -1247,6 +1409,7 @@ export class ListeningHistoryStore {
1247
1409
  FROM taste_events a
1248
1410
  WHERE a.subject_id = ?
1249
1411
  AND a.operation = 'assert'
1412
+ AND (? IS NULL OR a.target_key = ?)
1250
1413
  AND (
1251
1414
  ? = 1 OR (
1252
1415
  NOT EXISTS (
@@ -1262,7 +1425,7 @@ export class ListeningHistoryStore {
1262
1425
  ORDER BY a.recorded_at DESC, a.taste_event_id DESC
1263
1426
  LIMIT ?`,
1264
1427
  )
1265
- .all(subjectId.toLowerCase(), includeInactive ? 1 : 0, limit);
1428
+ .all(subjectId.toLowerCase(), targetKey, targetKey, includeInactive ? 1 : 0, limit ?? -1);
1266
1429
  return rows
1267
1430
  .map((row) => {
1268
1431
  const record = JSON.parse(row.record_json);
@@ -1313,9 +1476,25 @@ export class ListeningHistoryStore {
1313
1476
  .get(subjectId.toLowerCase()).count;
1314
1477
  }
1315
1478
 
1479
+ #ingestTransaction(work) {
1480
+ this.#database.exec("BEGIN IMMEDIATE");
1481
+ try {
1482
+ const result = work();
1483
+ this.#database.exec("COMMIT");
1484
+ return result;
1485
+ } catch (error) {
1486
+ this.#database.exec("ROLLBACK");
1487
+ throw error;
1488
+ }
1489
+ }
1490
+
1316
1491
  ingest(value) {
1317
1492
  if (this.#closed) throw new Error("Listening history store is closed");
1318
1493
  const bundle = normalizedBundle(value);
1494
+ return this.#ingestTransaction(() => this.#saveRecent(bundle));
1495
+ }
1496
+
1497
+ #saveRecent(bundle) {
1319
1498
  const subjects = new Set(
1320
1499
  bundle.listeningEvents.map((record) => record.subject_id?.toLowerCase()),
1321
1500
  );
@@ -1325,32 +1504,17 @@ export class ListeningHistoryStore {
1325
1504
  const subjectId = [...subjects][0];
1326
1505
  const statements = ingestionStatements(this.#database);
1327
1506
 
1328
- this.#database.exec("BEGIN IMMEDIATE");
1329
- let insertedTracks;
1330
- let insertedEvents;
1331
- let mirroredEvents = 0;
1332
- try {
1333
- if (subjectId !== undefined) {
1334
- this.localSubjectId({ preferredSubjectId: subjectId });
1335
- }
1336
- const times = bundle.listeningEvents.map((record) => record.occurred_at).sort();
1337
- // A read that overlaps a stored play joins up with it.
1338
- const overlaps = bundle.listeningEvents.some((record) => statements.hasEvent.get(record.deduplication_key));
1339
- if (bundle.windowFull && subjectId !== undefined && !overlaps) {
1340
- recordCoverageGap(this.#database, { subjectId, sourceKey: bundle.sourceKey, before: times[0], detectedAt: bundle.capturedAt });
1341
- }
1342
- ({ insertedTracks, insertedEvents } = insertBundleRecords(
1343
- bundle,
1344
- statements,
1345
- ));
1346
- // A read that finds nothing new still moves the source's checked time.
1347
- statements.touchCursor.run(bundle.capturedAt, bundle.sourceKey);
1348
- mirroredEvents = reconcileScrobbleMirrors(this.#database, subjectId, times[0], times.at(-1), bundle.capturedAt);
1349
- this.#database.exec("COMMIT");
1350
- } catch (error) {
1351
- this.#database.exec("ROLLBACK");
1352
- throw error;
1507
+ if (subjectId !== undefined) this.localSubjectId({ preferredSubjectId: subjectId });
1508
+ const times = bundle.listeningEvents.map((record) => record.occurred_at).sort();
1509
+ // A read that overlaps a stored play joins up with it.
1510
+ const overlaps = bundle.listeningEvents.some((record) => statements.hasEvent.get(record.deduplication_key));
1511
+ if (bundle.windowFull && subjectId !== undefined && !overlaps) {
1512
+ recordCoverageGap(this.#database, { subjectId, sourceKey: bundle.sourceKey, before: times[0], detectedAt: bundle.capturedAt });
1353
1513
  }
1514
+ const { insertedTracks, insertedEvents } = insertBundleRecords(bundle, statements);
1515
+ // A read that finds nothing new still moves the source's checked time.
1516
+ statements.touchCursor.run(bundle.capturedAt, bundle.sourceKey);
1517
+ const mirroredEvents = reconcileScrobbleMirrors(this.#database, subjectId, times[0], times.at(-1), bundle.capturedAt, { maxPairs: this.#maxMirrorPairs });
1354
1518
 
1355
1519
  return {
1356
1520
  state: "ready",
@@ -1368,7 +1532,18 @@ export class ListeningHistoryStore {
1368
1532
  ingestImport(value) {
1369
1533
  if (this.#closed) throw new Error("Listening history store is closed");
1370
1534
  const bundle = normalizedImportBundle(value);
1535
+ return this.#ingestTransaction(() => {
1536
+ const receipt = this.#saveArchive(bundle, new Date().toISOString());
1537
+ this.#recordImportReceipt(bundle.importBatch.subjectId, bundle.capturedAt, receipt);
1538
+ return receipt;
1539
+ });
1540
+ }
1541
+
1542
+ #saveArchive(bundle, importedAt) {
1371
1543
  const batch = bundle.importBatch;
1544
+ const eventsWithPlayedMs = bundle.listeningEvents.reduce(
1545
+ (count, event) => Number.isSafeInteger(event.played_ms) ? count + 1 : count, 0,
1546
+ );
1372
1547
  const existingBatch = this.#database.prepare(
1373
1548
  `SELECT * FROM import_batches
1374
1549
  WHERE import_batch_id = ?`,
@@ -1452,201 +1627,199 @@ export class ListeningHistoryStore {
1452
1627
  );
1453
1628
  const statements = ingestionStatements(this.#database);
1454
1629
 
1455
- this.#database.exec("BEGIN IMMEDIATE");
1456
1630
  let insertedTracks = 0;
1457
1631
  let insertedEvents = 0;
1458
1632
  let supersededEvents = 0;
1459
- let mirroredEvents = 0;
1633
+ let upgradedListens = 0;
1460
1634
  let insertedProfileEvidence = 0;
1461
- let alreadyImported = false;
1462
1635
  let profileAlreadyImported = bundle.profileImport === undefined;
1463
- try {
1464
- this.localSubjectId({ preferredSubjectId: batch.subjectId });
1465
- const previousBatch = existingBatch.get(batch.importBatchId);
1466
- alreadyImported = Boolean(previousBatch);
1467
- if (!alreadyImported) {
1468
- ({ insertedTracks, insertedEvents } = insertBundleRecords(
1469
- bundle,
1470
- statements,
1471
- ));
1472
- insertBatch.run(
1473
- batch.importBatchId,
1474
- batch.subjectId,
1475
- bundle.sourceKey,
1476
- batch.sourceFormat,
1477
- batch.dataScope,
1478
- batch.archiveSha256,
1479
- batch.archiveSizeBytes,
1480
- JSON.stringify(batch.memberNames),
1481
- batch.inputRecords,
1482
- batch.earliestOccurredAt,
1483
- batch.latestOccurredAt,
1484
- batch.importedAt,
1485
- insertedEvents,
1486
- batch.inputRecords - insertedEvents,
1487
- insertedTracks,
1488
- );
1489
- } else {
1490
- // Earlier readers skipped video members, even when they contained music.
1491
- // Extend that same archive's receipt without replacing its existing rows.
1492
- const previousMembers = JSON.parse(previousBatch.member_names_json);
1493
- const addedMembers = batch.memberNames.filter((name) => !previousMembers.includes(name));
1494
- const expandsExtendedArchive = batch.sourceFormat === "spotify_extended_streaming_history_music_v1" &&
1495
- previousBatch.subject_id === batch.subjectId && previousBatch.source_key === bundle.sourceKey &&
1496
- previousBatch.source_format === batch.sourceFormat && previousBatch.data_scope === batch.dataScope &&
1497
- previousBatch.archive_sha256 === batch.archiveSha256 && previousBatch.archive_size_bytes === batch.archiveSizeBytes &&
1498
- previousMembers.every((name) => batch.memberNames.includes(name)) && addedMembers.length > 0 &&
1499
- addedMembers.every((name) => /^Streaming_History_Video_\d{4}(?:_\d+)?\.json$/u.test(name));
1500
- if (expandsExtendedArchive) {
1501
- const incomingIds = new Set(bundle.listeningEvents.map((event) => event.listening_event_id));
1502
- const previousEvents = this.#database.prepare(`SELECT listening_event_id FROM listening_events
1503
- WHERE subject_id = ? AND json_extract(record_json, '$.provenance.import_batch_id') = ?`)
1504
- .all(batch.subjectId, batch.importBatchId);
1505
- if (batch.inputRecords < previousBatch.input_records || previousEvents.some((event) => !incomingIds.has(event.listening_event_id))) {
1506
- throw new Error("Extended archive expansion must preserve every previously imported event");
1507
- }
1508
- ({ insertedTracks, insertedEvents } = insertBundleRecords(bundle, statements));
1509
- this.#database.prepare(`UPDATE import_batches SET member_names_json = ?, input_records = ?,
1510
- earliest_occurred_at = ?, latest_occurred_at = ?,
1511
- inserted_events = inserted_events + ?, duplicate_events = ? - inserted_events - ?,
1512
- inserted_track_refs = inserted_track_refs + ? WHERE import_batch_id = ?`)
1513
- .run(JSON.stringify(batch.memberNames), batch.inputRecords, batch.earliestOccurredAt, batch.latestOccurredAt,
1514
- insertedEvents, batch.inputRecords, insertedEvents, insertedTracks, batch.importBatchId);
1636
+ this.localSubjectId({ preferredSubjectId: batch.subjectId });
1637
+ const previousBatch = existingBatch.get(batch.importBatchId);
1638
+ // An older open client can add a batch since this store last checked for missing receipts.
1639
+ if (previousBatch) recordEarlierImportReceipts(this.#database, batch.importBatchId);
1640
+ if (!previousBatch) {
1641
+ ({ insertedTracks, insertedEvents } = insertBundleRecords(
1642
+ bundle,
1643
+ statements,
1644
+ ));
1645
+ insertBatch.run(
1646
+ batch.importBatchId,
1647
+ batch.subjectId,
1648
+ bundle.sourceKey,
1649
+ batch.sourceFormat,
1650
+ batch.dataScope,
1651
+ batch.archiveSha256,
1652
+ batch.archiveSizeBytes,
1653
+ JSON.stringify(batch.memberNames),
1654
+ batch.inputRecords,
1655
+ batch.earliestOccurredAt,
1656
+ batch.latestOccurredAt,
1657
+ importedAt,
1658
+ insertedEvents,
1659
+ batch.inputRecords - insertedEvents,
1660
+ insertedTracks,
1661
+ );
1662
+ } else {
1663
+ // Earlier readers skipped year ranges, and some skipped video members.
1664
+ // Extend that same archive's receipt without replacing its existing rows.
1665
+ const previousMembers = JSON.parse(previousBatch.member_names_json);
1666
+ const addedMembers = batch.memberNames.filter((name) => !previousMembers.includes(name));
1667
+ const expandsExtendedArchive = batch.sourceFormat === "spotify_extended_streaming_history_music_v1" &&
1668
+ previousBatch.subject_id === batch.subjectId && previousBatch.source_key === bundle.sourceKey &&
1669
+ previousBatch.source_format === batch.sourceFormat && previousBatch.data_scope === batch.dataScope &&
1670
+ previousBatch.archive_sha256 === batch.archiveSha256 && previousBatch.archive_size_bytes === batch.archiveSizeBytes &&
1671
+ previousMembers.every((name) => batch.memberNames.includes(name)) && addedMembers.length > 0 &&
1672
+ addedMembers.every(isPreviouslySkippedSpotifyHistoryMember);
1673
+ if (expandsExtendedArchive) {
1674
+ const incomingIds = new Set(bundle.listeningEvents.map((event) => event.listening_event_id));
1675
+ const previousEvents = this.#database.prepare(`SELECT listening_event_id FROM listening_events
1676
+ WHERE subject_id = ? AND json_extract(record_json, '$.provenance.import_batch_id') = ?`)
1677
+ .all(batch.subjectId, batch.importBatchId);
1678
+ if (batch.inputRecords < previousBatch.input_records || previousEvents.some((event) => !incomingIds.has(event.listening_event_id))) {
1679
+ throw new Error("Extended archive expansion must preserve every previously imported event");
1515
1680
  }
1681
+ ({ insertedTracks, insertedEvents } = insertBundleRecords(bundle, statements));
1682
+ this.#database.prepare(`UPDATE import_batches SET member_names_json = ?, input_records = ?,
1683
+ earliest_occurred_at = ?, latest_occurred_at = ?,
1684
+ inserted_events = inserted_events + ?, duplicate_events = ? - inserted_events - ?,
1685
+ inserted_track_refs = inserted_track_refs + ? WHERE import_batch_id = ?`)
1686
+ .run(JSON.stringify(batch.memberNames), batch.inputRecords, batch.earliestOccurredAt, batch.latestOccurredAt,
1687
+ insertedEvents, batch.inputRecords, insertedEvents, insertedTracks, batch.importBatchId);
1516
1688
  }
1517
- const reconciliationCandidates = preserveExtendedHistoryMatches(bundle, (eventId) =>
1518
- selectCandidateBySuperseding.get(eventId)?.superseded_event_id ??
1519
- selectBySuperseding.get(eventId)?.superseded_event_id);
1520
- for (const candidate of reconciliationCandidates) {
1521
- const existingBySuperseded = selectCandidateBySuperseded.get(
1522
- candidate.supersededEventId,
1523
- )?.superseding_event_id;
1524
- const existingBySuperseding = selectCandidateBySuperseding.get(
1525
- candidate.supersedingEventId,
1526
- )?.superseded_event_id;
1527
- const resolvedSuperseding = selectBySuperseded.get(
1689
+ }
1690
+ const reconciliationCandidates = preserveExtendedHistoryMatches(bundle, (eventId) =>
1691
+ selectCandidateBySuperseding.get(eventId)?.superseded_event_id ??
1692
+ selectBySuperseding.get(eventId)?.superseded_event_id);
1693
+ for (const candidate of reconciliationCandidates) {
1694
+ const existingBySuperseded = selectCandidateBySuperseded.get(
1695
+ candidate.supersededEventId,
1696
+ )?.superseding_event_id;
1697
+ const existingBySuperseding = selectCandidateBySuperseding.get(
1698
+ candidate.supersedingEventId,
1699
+ )?.superseded_event_id;
1700
+ const resolvedSuperseding = selectBySuperseded.get(
1701
+ candidate.supersededEventId,
1702
+ )?.superseding_event_id;
1703
+ const resolvedSuperseded = selectBySuperseding.get(
1704
+ candidate.supersedingEventId,
1705
+ )?.superseded_event_id;
1706
+ if (
1707
+ (existingBySuperseded &&
1708
+ existingBySuperseded !== candidate.supersedingEventId) ||
1709
+ (existingBySuperseding &&
1710
+ existingBySuperseding !== candidate.supersededEventId) ||
1711
+ (resolvedSuperseding &&
1712
+ resolvedSuperseding !== candidate.supersedingEventId) ||
1713
+ (resolvedSuperseded &&
1714
+ resolvedSuperseded !== candidate.supersededEventId)
1715
+ ) {
1716
+ throw new Error("Listening history reconciliation conflict");
1717
+ }
1718
+ if (!existingBySuperseded && !existingBySuperseding) {
1719
+ insertCandidate.run(
1528
1720
  candidate.supersededEventId,
1529
- )?.superseding_event_id;
1530
- const resolvedSuperseded = selectBySuperseding.get(
1531
1721
  candidate.supersedingEventId,
1532
- )?.superseded_event_id;
1533
- if (
1534
- (existingBySuperseded &&
1535
- existingBySuperseded !== candidate.supersedingEventId) ||
1536
- (existingBySuperseding &&
1537
- existingBySuperseding !== candidate.supersededEventId) ||
1538
- (resolvedSuperseding &&
1539
- resolvedSuperseding !== candidate.supersedingEventId) ||
1540
- (resolvedSuperseded &&
1541
- resolvedSuperseded !== candidate.supersededEventId)
1542
- ) {
1543
- throw new Error("Listening history reconciliation conflict");
1544
- }
1545
- if (!existingBySuperseded && !existingBySuperseding) {
1546
- insertCandidate.run(
1547
- candidate.supersededEventId,
1548
- candidate.supersedingEventId,
1549
- batch.importBatchId,
1550
- batch.importedAt,
1551
- );
1552
- }
1722
+ batch.importBatchId,
1723
+ batch.importedAt,
1724
+ );
1725
+ }
1726
+ }
1727
+ for (const candidate of selectResolvableCandidates.all()) {
1728
+ const supersededEventId = candidate.superseded_event_id;
1729
+ const supersedingEventId = candidate.superseding_event_id;
1730
+ const existingSuperseding = selectBySuperseded.get(
1731
+ supersededEventId,
1732
+ )?.superseding_event_id;
1733
+ const existingSuperseded = selectBySuperseding.get(
1734
+ supersedingEventId,
1735
+ )?.superseded_event_id;
1736
+ if (
1737
+ (existingSuperseding && existingSuperseding !== supersedingEventId) ||
1738
+ (existingSuperseded && existingSuperseded !== supersededEventId)
1739
+ ) {
1740
+ throw new Error("Listening history reconciliation conflict");
1553
1741
  }
1554
- for (const candidate of selectResolvableCandidates.all()) {
1555
- const supersededEventId = candidate.superseded_event_id;
1556
- const supersedingEventId = candidate.superseding_event_id;
1557
- const existingSuperseding = selectBySuperseded.get(
1742
+ const eventRow = selectEventRecord.get(supersedingEventId);
1743
+ const event = JSON.parse(eventRow.record_json);
1744
+ if (
1745
+ event.supersedes_listening_event_id !== undefined &&
1746
+ event.supersedes_listening_event_id.toLowerCase() !== supersededEventId
1747
+ ) {
1748
+ throw new Error("Listening history reconciliation conflict");
1749
+ }
1750
+ if (event.supersedes_listening_event_id === undefined) {
1751
+ updateEventRecord.run(
1752
+ JSON.stringify({
1753
+ ...event,
1754
+ supersedes_listening_event_id: supersededEventId,
1755
+ }),
1756
+ supersedingEventId,
1757
+ );
1758
+ }
1759
+ if (!existingSuperseding && !existingSuperseded) {
1760
+ supersededEvents += insertSupersession.run(
1558
1761
  supersededEventId,
1559
- )?.superseding_event_id;
1560
- const existingSuperseded = selectBySuperseding.get(
1561
1762
  supersedingEventId,
1562
- )?.superseded_event_id;
1563
- if (
1564
- (existingSuperseding && existingSuperseding !== supersedingEventId) ||
1565
- (existingSuperseded && existingSuperseded !== supersededEventId)
1566
- ) {
1567
- throw new Error("Listening history reconciliation conflict");
1568
- }
1569
- const eventRow = selectEventRecord.get(supersedingEventId);
1570
- const event = JSON.parse(eventRow.record_json);
1571
- if (
1572
- event.supersedes_listening_event_id !== undefined &&
1573
- event.supersedes_listening_event_id.toLowerCase() !== supersededEventId
1574
- ) {
1575
- throw new Error("Listening history reconciliation conflict");
1576
- }
1577
- if (event.supersedes_listening_event_id === undefined) {
1578
- updateEventRecord.run(
1579
- JSON.stringify({
1580
- ...event,
1581
- supersedes_listening_event_id: supersededEventId,
1582
- }),
1583
- supersedingEventId,
1584
- );
1585
- }
1586
- if (!existingSuperseding && !existingSuperseded) {
1587
- supersededEvents += insertSupersession.run(
1588
- supersededEventId,
1589
- supersedingEventId,
1590
- candidate.import_batch_id,
1591
- batch.importedAt,
1592
- ).changes;
1593
- }
1763
+ candidate.import_batch_id,
1764
+ batch.importedAt,
1765
+ ).changes;
1594
1766
  }
1595
- if (bundle.profileImport) {
1596
- const profile = bundle.profileImport;
1597
- profileAlreadyImported = Boolean(
1598
- existingProfileBatch.get(profile.profileImportId),
1599
- );
1600
- if (!profileAlreadyImported) {
1601
- if (alreadyImported) {
1602
- for (const record of bundle.trackRefs) {
1603
- insertedTracks += statements.insertTrack.run(
1604
- record.track_ref_id,
1605
- record.revision,
1606
- JSON.stringify(record),
1607
- ).changes;
1608
- }
1609
- }
1610
- insertProfileBatch.run(
1611
- profile.profileImportId,
1612
- profile.subjectId,
1613
- profile.sourceKey,
1614
- profile.sourceFormat,
1615
- profile.archiveSha256,
1616
- profile.archiveSizeBytes,
1617
- JSON.stringify(profile.memberNames),
1618
- profile.inputRecords,
1619
- profile.importedAt,
1620
- );
1621
- for (const record of bundle.profileEvidence) {
1622
- insertedProfileEvidence += insertProfileEvidence.run(
1623
- record.profile_evidence_id,
1624
- record.evidence_key,
1625
- record.subject_id,
1626
- record.evidence_kind,
1627
- profile.profileImportId,
1628
- record.observed_at,
1629
- record.provenance.captured_at,
1767
+ }
1768
+ if (bundle.profileImport) {
1769
+ const profile = bundle.profileImport;
1770
+ profileAlreadyImported = Boolean(
1771
+ existingProfileBatch.get(profile.profileImportId),
1772
+ );
1773
+ if (!profileAlreadyImported) {
1774
+ if (previousBatch) {
1775
+ for (const record of bundle.trackRefs) {
1776
+ insertedTracks += statements.insertTrack.run(
1777
+ record.track_ref_id,
1778
+ record.revision,
1630
1779
  JSON.stringify(record),
1631
1780
  ).changes;
1632
1781
  }
1633
- if (insertedProfileEvidence !== profile.inputRecords) {
1634
- throw new Error("Spotify profile evidence import was incomplete");
1635
- }
1636
- updateProfileBatch.run(
1637
- insertedProfileEvidence,
1782
+ }
1783
+ insertProfileBatch.run(
1784
+ profile.profileImportId,
1785
+ profile.subjectId,
1786
+ profile.sourceKey,
1787
+ profile.sourceFormat,
1788
+ profile.archiveSha256,
1789
+ profile.archiveSizeBytes,
1790
+ JSON.stringify(profile.memberNames),
1791
+ profile.inputRecords,
1792
+ importedAt,
1793
+ );
1794
+ for (const record of bundle.profileEvidence) {
1795
+ insertedProfileEvidence += insertProfileEvidence.run(
1796
+ record.profile_evidence_id,
1797
+ record.evidence_key,
1798
+ record.subject_id,
1799
+ record.evidence_kind,
1638
1800
  profile.profileImportId,
1639
- );
1801
+ record.observed_at,
1802
+ record.provenance.captured_at,
1803
+ JSON.stringify(record),
1804
+ ).changes;
1640
1805
  }
1806
+ if (insertedProfileEvidence !== profile.inputRecords) {
1807
+ throw new Error("Spotify profile evidence import was incomplete");
1808
+ }
1809
+ updateProfileBatch.run(
1810
+ insertedProfileEvidence,
1811
+ profile.profileImportId,
1812
+ );
1641
1813
  }
1642
- mirroredEvents = reconcileScrobbleMirrors(
1643
- this.#database, batch.subjectId, batch.earliestOccurredAt, batch.latestOccurredAt, batch.importedAt,
1644
- );
1645
- this.#database.exec("COMMIT");
1646
- } catch (error) {
1647
- this.#database.exec("ROLLBACK");
1648
- throw error;
1649
1814
  }
1815
+ if (bundle.sourceKey === LISTENBRAINZ_HISTORY_SOURCE) {
1816
+ supersededEvents += supersedeEarlierListenBrainzCopies(this.#database, bundle, importedAt);
1817
+ upgradedListens = upgradeListenBrainzRecordings(this.#database, batch.subjectId, bundle);
1818
+ }
1819
+ const mirroredEvents = reconcileScrobbleMirrors(
1820
+ this.#database, batch.subjectId, batch.earliestOccurredAt, batch.latestOccurredAt, batch.importedAt,
1821
+ { maxPairs: this.#maxMirrorPairs },
1822
+ );
1650
1823
 
1651
1824
  return {
1652
1825
  state: "ready",
@@ -1656,16 +1829,20 @@ export class ListeningHistoryStore {
1656
1829
  import_batch_id: batch.importBatchId,
1657
1830
  archive_sha256: batch.archiveSha256,
1658
1831
  input_records: batch.inputRecords,
1832
+ events_with_played_ms: eventsWithPlayedMs,
1659
1833
  inserted_events: insertedEvents,
1660
1834
  duplicate_events: batch.inputRecords - insertedEvents,
1661
1835
  inserted_track_refs: insertedTracks,
1662
1836
  superseded_events: supersededEvents,
1837
+ ...(upgradedListens ? { upgraded_recording_events: upgradedListens } : {}),
1663
1838
  ...(mirroredEvents ? { mirrored_events: mirroredEvents } : {}),
1664
1839
  effective_event_delta: insertedEvents - supersededEvents - mirroredEvents,
1665
1840
  cursor_after_ms: this.sourceCursor(bundle.sourceKey),
1666
1841
  earliest_occurred_at: batch.earliestOccurredAt,
1667
1842
  latest_occurred_at: batch.latestOccurredAt,
1668
- already_imported: alreadyImported,
1843
+ imported_at: importedAt,
1844
+ first_imported_at: previousBatch?.imported_at ?? importedAt,
1845
+ already_imported: Boolean(previousBatch),
1669
1846
  ...(bundle.profileImport
1670
1847
  ? {
1671
1848
  profile_input_records: bundle.profileImport.inputRecords,
@@ -1684,12 +1861,114 @@ export class ListeningHistoryStore {
1684
1861
  }
1685
1862
  : {}),
1686
1863
  profile_effects:
1687
- insertedEvents > 0 || supersededEvents > 0 || insertedProfileEvidence > 0
1864
+ insertedEvents > 0 || supersededEvents > 0 || insertedProfileEvidence > 0 || upgradedListens > 0
1688
1865
  ? "updated"
1689
1866
  : "unchanged",
1690
1867
  };
1691
1868
  }
1692
1869
 
1870
+ #recordImportReceipt(subjectId, capturedAt, receipt) {
1871
+ this.#database.prepare(`INSERT INTO listening_import_receipts (
1872
+ subject_id, source_key, source_format, data_scope, import_batch_id, imported_at,
1873
+ earliest_occurred_at, latest_occurred_at, input_records, inserted_events, duplicate_events,
1874
+ superseded_events, mirrored_events, inserted_profile_evidence, events_with_played_ms,
1875
+ already_imported, captured_at, input_profile_evidence
1876
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(
1877
+ subjectId, receipt.source_key, receipt.source_format, receipt.data_scope, receipt.import_batch_id ?? null,
1878
+ receipt.imported_at, receipt.earliest_occurred_at, receipt.latest_occurred_at, receipt.input_records,
1879
+ receipt.inserted_events, receipt.duplicate_events, receipt.superseded_events ?? 0, receipt.mirrored_events ?? 0,
1880
+ receipt.inserted_profile_evidence ?? 0, receipt.events_with_played_ms,
1881
+ receipt.already_imported == null ? null : Number(receipt.already_imported), capturedAt, receipt.profile_input_records ?? 0,
1882
+ );
1883
+ }
1884
+
1885
+ ingestSpotifyQuick({ recentBundle, libraryBundle, subjectId } = {}) {
1886
+ if (this.#closed) throw new Error("Listening history store is closed");
1887
+ if (!isUuid(subjectId)) throw new TypeError("A valid Spotify Quick import subject is required");
1888
+ const subject = subjectId.toLowerCase();
1889
+ const recent = normalizedBundle(recentBundle);
1890
+ const library = libraryBundle ? normalizedImportBundle(libraryBundle) : null;
1891
+ if (recent.sourceKey !== "spotify.recently_played" ||
1892
+ recent.listeningEvents.some(event => event?.subject_id?.toLowerCase() !== subject) ||
1893
+ (library && (library.sourceKey !== "spotify.web_api_library" || library.importBatch.subjectId !== subject ||
1894
+ library.importBatch.dataScope !== "account_library_snapshot" || library.listeningEvents.length))) {
1895
+ throw new TypeError("Spotify Quick import sources do not match the selected listener");
1896
+ }
1897
+ return this.#ingestTransaction(() => {
1898
+ this.localSubjectId({ preferredSubjectId: subject });
1899
+ const importedAt = new Date().toISOString();
1900
+ const savedLibrary = library ? this.#saveArchive(library, importedAt) : null;
1901
+ const savedRecent = this.#saveRecent(recent);
1902
+ const times = recent.listeningEvents.map(event => event.occurred_at).sort();
1903
+ const superseded = savedLibrary?.superseded_events ?? 0;
1904
+ const mirrored = (savedRecent.mirrored_events ?? 0) + (savedLibrary?.mirrored_events ?? 0);
1905
+ const receipt = {
1906
+ ...savedRecent, provider: "spotify-quick", imported_at: importedAt,
1907
+ earliest_occurred_at: times[0] ?? null, latest_occurred_at: times.at(-1) ?? null,
1908
+ events_with_played_ms: 0, effective_event_delta: savedRecent.inserted_events - superseded - mirrored,
1909
+ ...(superseded ? { superseded_events: superseded } : {}),
1910
+ ...(mirrored ? { mirrored_events: mirrored } : {}),
1911
+ ...(savedLibrary ? {
1912
+ inserted_track_refs: savedRecent.inserted_track_refs + savedLibrary.inserted_track_refs,
1913
+ profile_input_records: savedLibrary.profile_input_records ?? 0,
1914
+ inserted_profile_evidence: savedLibrary.inserted_profile_evidence ?? 0,
1915
+ library_already_imported: savedLibrary.already_imported,
1916
+ } : {}),
1917
+ profile_effects: savedRecent.profile_effects === "updated" || savedLibrary?.profile_effects === "updated" || mirrored
1918
+ ? "updated" : "unchanged",
1919
+ };
1920
+ // This rolling read has no archive identity. The optional batch link accounts for the collection part on later opens.
1921
+ this.#recordImportReceipt(subject, library?.capturedAt ?? recent.capturedAt, {
1922
+ ...receipt, source_key: "spotify.quick_import", source_format: SPOTIFY_QUICK_FORMAT,
1923
+ data_scope: library ? "recent_listening_and_library" : "recent_listening",
1924
+ import_batch_id: savedLibrary?.import_batch_id, input_records: savedRecent.fetched_events,
1925
+ });
1926
+ return receipt;
1927
+ });
1928
+ }
1929
+
1930
+ importSourceHistory({ subjectId, limit = 20, offset = 0 } = {}) {
1931
+ if (this.#closed) throw new Error("Listening history store is closed");
1932
+ if (!isUuid(subjectId)) throw new TypeError("A valid import history subject is required");
1933
+ if (!Number.isSafeInteger(limit) || limit < 1 || !Number.isSafeInteger(offset) || offset < 0) {
1934
+ throw new TypeError("Import history pagination is invalid");
1935
+ }
1936
+ const subject = subjectId.toLowerCase();
1937
+ const source = `FROM listening_import_receipts r LEFT JOIN import_batches b USING (import_batch_id)
1938
+ WHERE r.subject_id = ?`;
1939
+ this.#database.exec("BEGIN");
1940
+ try {
1941
+ const { total } = this.#database.prepare(`SELECT COUNT(*) AS total ${source}`).get(subject);
1942
+ // These live reads timestamp the collection itself. File reads and saved playlist copies do not.
1943
+ const rows = this.#database.prepare(`SELECT r.source_key AS sourceKey, r.source_format AS sourceFormat,
1944
+ r.data_scope AS dataScope, r.imported_at AS importedAt,
1945
+ CASE WHEN r.source_format <> '${SPOTIFY_QUICK_FORMAT}' THEN b.imported_at END AS firstImportedAt,
1946
+ r.earliest_occurred_at AS earliestOccurredAt, r.latest_occurred_at AS latestOccurredAt,
1947
+ r.input_records AS inputRecords, r.inserted_events AS insertedEvents, r.duplicate_events AS duplicateEvents,
1948
+ r.superseded_events AS supersededEvents, r.mirrored_events AS mirroredEvents,
1949
+ r.inserted_events - r.superseded_events - r.mirrored_events AS effectiveEventDelta,
1950
+ r.input_profile_evidence AS inputProfileEvidence, r.inserted_profile_evidence AS insertedProfileEvidence,
1951
+ r.events_with_played_ms AS eventsWithPlayedMs,
1952
+ CASE WHEN r.source_format = '${SPOTIFY_QUICK_FORMAT}' THEN r.captured_at
1953
+ WHEN r.input_profile_evidence > 0 AND (b.source_key = 'spotify.web_api_library' OR
1954
+ (b.source_key IN ('qq_music.music_import', 'netease.music_import') AND
1955
+ EXISTS (SELECT 1 FROM json_each(b.member_names_json) WHERE value = 'public-playlist.json')))
1956
+ THEN r.captured_at END AS observedAt,
1957
+ r.already_imported AS alreadyImported ${source} ORDER BY r.imported_at DESC, r.receipt_id DESC LIMIT ? OFFSET ?`)
1958
+ .all(subject, limit, offset);
1959
+ const items = rows.map(row => ({
1960
+ ...row, kind: row.inputRecords === 0 && row.inputProfileEvidence > 0 ? "collection" : "listening",
1961
+ legacy: row.sourceFormat !== SPOTIFY_QUICK_FORMAT && row.alreadyImported === null,
1962
+ alreadyImported: row.alreadyImported === null ? null : Boolean(row.alreadyImported),
1963
+ }));
1964
+ this.#database.exec("COMMIT");
1965
+ return { total, items };
1966
+ } catch (error) {
1967
+ this.#database.exec("ROLLBACK");
1968
+ throw error;
1969
+ }
1970
+ }
1971
+
1693
1972
  recentEvents({ subjectId, limit = 20 } = {}) {
1694
1973
  if (this.#closed) throw new Error("Listening history store is closed");
1695
1974
  if (typeof subjectId !== "string" || !subjectId.trim()) {
@@ -1717,7 +1996,7 @@ export class ListeningHistoryStore {
1717
1996
  .map((row) => JSON.parse(row.record_json));
1718
1997
  }
1719
1998
 
1720
- #profileProjection({ subjectId, maxItems }) {
1999
+ #profileProjection({ subjectId, maxItems, readingThrough }) {
1721
2000
  if (this.#closed) throw new Error("Listening history store is closed");
1722
2001
  if (!isUuid(subjectId)) {
1723
2002
  throw new TypeError("A valid listening profile subject ID is required");
@@ -1847,39 +2126,45 @@ export class ListeningHistoryStore {
1847
2126
  .all(normalizedSubjectId)
1848
2127
  .map((row) => JSON.parse(row.record_json));
1849
2128
  const { rows, adopted } = markMoondogStartedPlays(eventRows, this.#suggestionsForMatching());
1850
- return {
1851
- ...projectListeningProfile({
1852
- subjectId: normalizedSubjectId,
1853
- eventRows: rows,
1854
- profileEvidence,
1855
- tasteEvents,
1856
- maxItems,
1857
- adoptedSuggestionIds: adopted,
1858
- }),
2129
+ const projected = projectListeningProfile({
2130
+ subjectId: normalizedSubjectId,
2131
+ eventRows: rows,
2132
+ profileEvidence,
2133
+ tasteEvents,
2134
+ maxItems,
1859
2135
  adoptedSuggestionIds: adopted,
2136
+ });
2137
+ return {
2138
+ ...projected, adoptedSuggestionIds: adopted,
2139
+ ...(readingThrough !== undefined ? { historyDigests: historyDigestsThrough(
2140
+ [readingThrough, projected.summary.coverage.latest_played_at], rows, profileEvidence, tasteEvents,
2141
+ ) } : {}),
1860
2142
  };
1861
2143
  }
1862
2144
 
1863
2145
  #suggestionsForMatching() {
1864
- return this.#database.prepare(`SELECT suggestion_id, provider_track_id, isrc, track_key, release_key, title, artist_credit,
2146
+ return this.#database.prepare(`SELECT suggestion_id, action, provider_track_id, isrc, track_key, release_key, title, artist_credit,
1865
2147
  requested_at FROM moondog_suggestions ORDER BY requested_at, suggestion_id`).all();
1866
2148
  }
1867
2149
 
1868
- /** Records what Moondog itself queued or played. Only accepted host writes belong here. */
1869
- recordMoondogSuggestions({ entries } = {}) {
2150
+ /** Records songs Moondog saved in a playlist, queued or played, from accepted host writes. */
2151
+ recordMoondogSuggestions({ entries, includeIds = false } = {}) {
1870
2152
  if (this.#closed) throw new Error("Listening history store is closed");
1871
2153
  if (!Array.isArray(entries) || entries.length > 50) throw new TypeError("Moondog suggestions are invalid");
1872
2154
  const insert = this.#database.prepare(`INSERT INTO moondog_suggestions
1873
2155
  (suggestion_id, service, action, provider_track_id, isrc, track_key, release_key, title, artist_credit, requested_at, mix_slot)
1874
2156
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
1875
2157
  let recorded = 0;
2158
+ const suggestionIds = includeIds === true ? Array(entries.length).fill(null) : null;
1876
2159
  this.#database.exec("BEGIN IMMEDIATE");
1877
2160
  try {
1878
- for (const value of entries) {
1879
- const entry = suggestionEntry(value);
2161
+ for (const [index, value] of entries.entries()) {
2162
+ const entry = suggestionEntry(value ?? {});
1880
2163
  if (!entry || !/^[a-z][a-z0-9_.]{1,63}$/u.test(entry.action ?? "") || !Number.isFinite(Date.parse(entry.requested_at))) continue;
1881
- insert.run(randomUUID(), entry.service, entry.action, entry.provider_track_id, entry.isrc, entry.track_key, entry.release_key,
2164
+ const id = randomUUID();
2165
+ insert.run(id, entry.service, entry.action, entry.provider_track_id, entry.isrc, entry.track_key, entry.release_key,
1882
2166
  entry.title, entry.artist_credit, new Date(entry.requested_at).toISOString(), entry.mix_slot);
2167
+ if (suggestionIds) suggestionIds[index] = id;
1883
2168
  recorded += 1;
1884
2169
  }
1885
2170
  this.#database.exec("COMMIT");
@@ -1888,31 +2173,58 @@ export class ListeningHistoryStore {
1888
2173
  throw error;
1889
2174
  }
1890
2175
  this.#ledgerChanges += recorded;
1891
- return { recorded };
2176
+ return suggestionIds ? { recorded, suggestionIds } : { recorded };
1892
2177
  }
1893
2178
 
1894
2179
  /**
1895
- * How a song Moondog started went. It belongs to the latest suggestion of that song requested
1896
- * up to six hours before the play ended; a song Moondog did not start keeps no outcome.
2180
+ * Moondog owns each Apple and NetEase queue entry. Spotify reports only the playing song,
2181
+ * so an observed play needs an unambiguous matching suggestion accepted before that play.
1897
2182
  */
1898
- recordSuggestionOutcome({ service, providerTrackId = null, title, artists, artistCredit, outcome, heardMs, at } = {}) {
2183
+ recordSuggestionOutcome({ service, suggestionId, providerTrackId = null, title, artists, artistCredit, outcome, heardMs, startedBy, at } = {}) {
1899
2184
  if (this.#closed) throw new Error("Listening history store is closed");
1900
2185
  if (!["completed", "skipped", "partial"].includes(outcome) || !Number.isSafeInteger(heardMs) || heardMs < 0) {
1901
2186
  throw new TypeError("Suggestion outcome is invalid");
1902
2187
  }
1903
2188
  const observedMs = Date.parse(at);
1904
2189
  if (!Number.isFinite(observedMs)) throw new TypeError("Suggestion outcome time is invalid");
2190
+ if (service === "apple_music" || service === "netease") {
2191
+ const providerId = service === "apple_music" ? /^apple_music:\d{1,20}$/u : /^netease:\S+$/u;
2192
+ if (!isUuid(suggestionId) || typeof providerTrackId !== "string" || !providerId.test(providerTrackId)) return { recorded: false };
2193
+ const observedAt = new Date(observedMs).toISOString();
2194
+ // Two windows can report different stop times for one occurrence. The first observation
2195
+ // wins in one SQLite write, including after reopening the history or waiting in a queue.
2196
+ const inserted = this.#database.prepare(`INSERT INTO moondog_suggestion_outcomes (suggestion_id, outcome, heard_ms, observed_at)
2197
+ SELECT s.suggestion_id, ?, ?, ? FROM moondog_suggestions s
2198
+ WHERE s.suggestion_id = ? AND s.service = ? AND s.provider_track_id = ?
2199
+ AND (s.action IN (s.service || '.play', s.service || '.queue') OR (s.service = 'apple_music' AND s.action = 'apple_music.queue.up_next'))
2200
+ AND s.track_key IS NOT NULL AND s.requested_at <= ?
2201
+ AND NOT EXISTS (SELECT 1 FROM moondog_suggestion_outcomes WHERE suggestion_id = s.suggestion_id)`)
2202
+ .run(outcome, heardMs, observedAt, suggestionId.toLowerCase(), service, providerTrackId, observedAt);
2203
+ return { recorded: inserted.changes === 1 };
2204
+ }
2205
+ if (service !== "spotify" || suggestionId != null) return { recorded: false };
1905
2206
  const entry = suggestionEntry({ service, action: "lookup", providerTrackId, title, artists, artistCredit, requestedAt: at });
1906
2207
  if (!entry) return { recorded: false };
1907
2208
  const identities = new Set(suggestionIdentities(entry).filter((identity) => !identity.startsWith("release:")));
1908
- const from = new Date(observedMs - SUGGESTION_WINDOW.afterMs).toISOString();
1909
- const to = new Date(observedMs + SUGGESTION_WINDOW.beforeMs).toISOString();
2209
+ const startBound = startedBy == null ? observedMs : Date.parse(startedBy);
2210
+ if (!Number.isFinite(startBound) || startBound > observedMs) return { recorded: false };
2211
+ // Both clocks are local. A pick accepted while this copy was already playing belongs to a later play.
2212
+ const latestStart = Math.min(startBound, observedMs - heardMs);
2213
+ const from = new Date(latestStart - SUGGESTION_WINDOW.afterMs).toISOString();
2214
+ const to = new Date(latestStart).toISOString();
1910
2215
  const candidates = this.#database.prepare(`SELECT suggestion_id, provider_track_id, isrc, track_key, release_key, title, artist_credit,
1911
- requested_at FROM moondog_suggestions WHERE requested_at BETWEEN ? AND ? ORDER BY requested_at DESC, suggestion_id`).all(from, to);
1912
- const match = candidates.find((suggestion) => suggestionIdentities(suggestion).some((identity) => identities.has(identity)));
1913
- if (!match) return { recorded: false };
1914
- const inserted = this.#database.prepare(`INSERT OR IGNORE INTO moondog_suggestion_outcomes (suggestion_id, outcome, heard_ms, observed_at)
1915
- VALUES (?, ?, ?, ?)`).run(match.suggestion_id, outcome, heardMs, new Date(observedMs).toISOString());
2216
+ EXISTS (SELECT 1 FROM moondog_suggestion_outcomes o WHERE o.suggestion_id = s.suggestion_id) AS observed
2217
+ FROM moondog_suggestions s WHERE requested_at BETWEEN ? AND ? AND service = ? AND action <> ? AND track_key IS NOT NULL
2218
+ ORDER BY requested_at DESC, rowid DESC`).all(from, to, service, PLAYLIST_SAVE_ACTION);
2219
+ const matches = candidates.filter(suggestion => entry.provider_track_id && suggestion.provider_track_id
2220
+ ? entry.provider_track_id === suggestion.provider_track_id
2221
+ : suggestionIdentities(suggestion).some(identity => identities.has(identity)));
2222
+ const match = matches[0];
2223
+ // Spotify supplies no queue-entry ID. Two outstanding copies cannot identify which one was heard.
2224
+ if (!match || match.observed || matches.slice(1).some(other => !other.observed)) return { recorded: false };
2225
+ const inserted = this.#database.prepare(`INSERT INTO moondog_suggestion_outcomes (suggestion_id, outcome, heard_ms, observed_at)
2226
+ SELECT ?, ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM moondog_suggestion_outcomes WHERE suggestion_id = ?)`)
2227
+ .run(match.suggestion_id, outcome, heardMs, new Date(observedMs).toISOString(), match.suggestion_id);
1916
2228
  return { recorded: inserted.changes === 1, suggestion_id: match.suggestion_id };
1917
2229
  }
1918
2230
 
@@ -1926,23 +2238,23 @@ export class ListeningHistoryStore {
1926
2238
  const suggestions = this.#suggestionsForMatching();
1927
2239
  if (!suggestions.length) return tracks.map(() => null);
1928
2240
  const { adopted } = this.#listeningSnapshot(subjectId);
1929
- const byIdentity = new Map();
1930
- for (const suggestion of suggestions) {
1931
- for (const identity of suggestionIdentities(suggestion)) {
1932
- byIdentity.set(identity, [...(byIdentity.get(identity) ?? []), suggestion]);
1933
- }
1934
- }
2241
+ const byIdentity = suggestionsByIdentity(suggestions);
1935
2242
  const outcomes = new Map();
1936
- for (const row of this.#database.prepare("SELECT suggestion_id, outcome FROM moondog_suggestion_outcomes").all()) {
1937
- outcomes.set(row.suggestion_id, [...(outcomes.get(row.suggestion_id) ?? []), row.outcome]);
2243
+ // Older readers could count later replays again or attach an outcome to a playlist save.
2244
+ for (const row of this.#database.prepare(`SELECT suggestion_id, outcome FROM moondog_suggestion_outcomes
2245
+ JOIN moondog_suggestions USING (suggestion_id) WHERE action <> ? ORDER BY observed_at`).all(PLAYLIST_SAVE_ACTION)) {
2246
+ if (!outcomes.has(row.suggestion_id)) outcomes.set(row.suggestion_id, row.outcome);
1938
2247
  }
1939
2248
  return tracks.map((track) => {
1940
- const entry = suggestionEntry({ service: "spotify", action: "lookup", ...track });
2249
+ const entry = lookupSuggestion(track);
1941
2250
  const matches = new Set(entry ? suggestionIdentities(entry).flatMap((identity) => byIdentity.get(identity) ?? []) : []);
1942
2251
  if (!matches.size) return null;
1943
2252
  const last = [...matches].reduce((latest, item) => item.requested_at > latest ? item.requested_at : latest, "");
1944
2253
  const heard = { completed: 0, skipped: 0, partial: 0 };
1945
- for (const item of matches) for (const row of outcomes.get(item.suggestion_id) ?? []) heard[row] += 1;
2254
+ for (const item of matches) {
2255
+ const outcome = outcomes.get(item.suggestion_id);
2256
+ if (outcome && (outcome !== "completed" || sameCompletedRecording(entry, item))) heard[outcome] += 1;
2257
+ }
1946
2258
  return { times: matches.size, last_suggested_at: last.slice(0, 10),
1947
2259
  adopted: [...matches].some((item) => adopted.has(item.suggestion_id)),
1948
2260
  ...(heard.completed + heard.skipped + heard.partial ? { outcomes: heard } : {}) };
@@ -1953,15 +2265,31 @@ export class ListeningHistoryStore {
1953
2265
  listeningMix({ subjectId, tracks } = {}) {
1954
2266
  if (!Array.isArray(tracks)) throw new TypeError("Listening mix tracks are invalid");
1955
2267
  const { familiarity } = this.#listeningSnapshot(subjectId);
1956
- return tracks.map((track) => mixSlot(track, familiarity));
2268
+ // Outcomes change independently of the taste projection. The underlying SQLite change counters
2269
+ // invalidate this small index even when the projection's evidence fingerprint stays the same.
2270
+ this.#evidence.completedRecordings ??= suggestionsByIdentity(this.#database.prepare(`SELECT s.provider_track_id, s.isrc,
2271
+ s.track_key, s.title, s.artist_credit FROM moondog_suggestion_outcomes o JOIN moondog_suggestions s USING (suggestion_id)
2272
+ WHERE o.outcome = 'completed' AND s.track_key IS NOT NULL AND s.action NOT IN (?, 'apple_music.preview')
2273
+ AND NOT EXISTS (SELECT 1 FROM moondog_suggestion_outcomes first WHERE first.suggestion_id = o.suggestion_id
2274
+ AND first.observed_at < o.observed_at)`).all(PLAYLIST_SAVE_ACTION));
2275
+ return tracks.map(track => {
2276
+ const entry = this.#evidence.completedRecordings.size ? lookupSuggestion(track) : null;
2277
+ const completed = entry && suggestionIdentities(entry).some(identity =>
2278
+ this.#evidence.completedRecordings.get(identity)?.some(heard => sameCompletedRecording(entry, heard)));
2279
+ return mixSlot(track, familiarity, completed);
2280
+ });
1957
2281
  }
1958
2282
 
1959
2283
  // One projection with a single item per list serves the status, the Avoids, the catalog, the
1960
2284
  // mix and the suggestion history until the listening data changes. Callers copy what they return.
1961
- #sharedProjection(subjectId) {
2285
+ #sharedProjection(subjectId, readingThrough) {
1962
2286
  const version = `${subjectId}:${this.listeningDataVersion()}`;
1963
- if (this.#projection?.version !== version) {
1964
- this.#projection = { version, value: this.#profileProjection({ subjectId, maxItems: 1 }) };
2287
+ const digests = this.#projection?.value.historyDigests;
2288
+ if (this.#projection?.version !== version || (readingThrough && !digests?.[readingThrough])) {
2289
+ // Status and the mix may open the current reading's source data before the host asks for it.
2290
+ const cutoff = readingThrough ?? this.#database.prepare(`SELECT json_extract(record_json, '$.coverage.coverage.latest_played_at') AS through
2291
+ FROM listener_profile_revisions WHERE subject_id = ? ORDER BY sequence DESC LIMIT 1`).get(subjectId.toLowerCase())?.through ?? null;
2292
+ this.#projection = { version, value: this.#profileProjection({ subjectId, maxItems: 1, readingThrough: cutoff }) };
1965
2293
  }
1966
2294
  return this.#projection.value;
1967
2295
  }
@@ -2039,8 +2367,8 @@ export class ListeningHistoryStore {
2039
2367
  : this.#profileProjection({ subjectId, maxItems })).summary);
2040
2368
  }
2041
2369
 
2042
- profileCatalog({ subjectId } = {}) {
2043
- const projected = this.#sharedProjection(subjectId);
2370
+ profileCatalog({ subjectId, readingThrough } = {}) {
2371
+ const projected = this.#sharedProjection(subjectId, readingThrough);
2044
2372
  const normalizedSubjectId = subjectId.toLowerCase();
2045
2373
  const imports = this.#database.prepare(`SELECT source_format AS format, data_scope AS scope,
2046
2374
  SUM(input_records) AS input_records, MIN(earliest_occurred_at) AS earliest,
@@ -2054,6 +2382,8 @@ export class ListeningHistoryStore {
2054
2382
  stored_listening_events: stored,
2055
2383
  superseded_listening_events: stored - projected.summary.coverage.effective_listening_events },
2056
2384
  sources: imports,
2385
+ ...(readingThrough !== undefined ? { historyDigests: projected.historyDigests } : {}),
2386
+ rankingWindows: projected.rankingWindows,
2057
2387
  context: {
2058
2388
  reference_date: projected.summary.listening_behavior.context.reference_date,
2059
2389
  recent_window_days: projected.summary.listening_behavior.context.recent_window_days,
@@ -2074,31 +2404,30 @@ export class ListeningHistoryStore {
2074
2404
  if (!isUuid(subjectId)) throw new TypeError("A valid profile subject is required");
2075
2405
  const today = new Date(now);
2076
2406
  const start = new Date(today);
2077
- start.setHours(0, 0, 0, 0);
2078
2407
  start.setDate(start.getDate() - (days - 1));
2079
- const from = start.toISOString();
2080
- const effective = `e.subject_id = ? AND e.occurred_at >= ?
2081
- AND NOT EXISTS (SELECT 1 FROM listening_event_supersessions s WHERE s.superseded_event_id = e.listening_event_id)
2082
- AND NOT EXISTS (SELECT 1 FROM listening_event_mirrors m WHERE m.mirror_event_id = e.listening_event_id)`;
2083
- const subject = subjectId.toLowerCase();
2408
+ start.setHours(0, 0, 0, 0);
2409
+ const tomorrow = new Date(today);
2410
+ tomorrow.setHours(24, 0, 0, 0);
2411
+ const range = [subjectId.toLowerCase(), start.toISOString(), tomorrow.toISOString()];
2412
+ const effective = `${attentionEvents} AND e.occurred_at >= ? AND e.occurred_at < ?`;
2084
2413
  // Plays Moondog started are not the listener's own attention.
2085
2414
  const suggestions = this.#suggestionsForMatching()
2086
- .filter((suggestion) => Date.parse(suggestion.requested_at) + SUGGESTION_WINDOW.afterMs >= Date.parse(from));
2415
+ .filter((suggestion) => Date.parse(suggestion.requested_at) + SUGGESTION_WINDOW.afterMs >= start.getTime());
2087
2416
  const started = suggestions.length === 0 ? [] : markMoondogStartedPlays(this.#database.prepare(`SELECT
2088
2417
  e.listening_event_id, e.record_json AS event_json, t.record_json AS track_json FROM listening_events e
2089
2418
  JOIN track_refs t ON t.track_ref_id = e.track_ref_id AND t.revision = e.track_ref_revision WHERE ${effective}`)
2090
- .all(subject, from).map((row) => ({ id: row.listening_event_id, event: JSON.parse(row.event_json), track: JSON.parse(row.track_json) })),
2419
+ .all(...range).map((row) => ({ id: row.listening_event_id, event: JSON.parse(row.event_json), track: JSON.parse(row.track_json) })),
2091
2420
  suggestions).rows.filter((row) => row.moondog_suggestion_id).map((row) => row.id);
2092
2421
  const own = `${effective} AND e.listening_event_id NOT IN (SELECT value FROM json_each(?))`;
2093
2422
  const plays = this.#database.prepare(`SELECT COUNT(*) AS plays FROM listening_events e WHERE ${own}`)
2094
- .get(subject, from, JSON.stringify(started)).plays;
2423
+ .get(...range, JSON.stringify(started)).plays;
2095
2424
  const artists = this.#database.prepare(`SELECT json_extract(a.value, '$.name') AS name, COUNT(*) AS plays,
2096
2425
  MAX(e.occurred_at) AS last_played_at
2097
2426
  FROM listening_events e
2098
2427
  JOIN track_refs t ON t.track_ref_id = e.track_ref_id AND t.revision = e.track_ref_revision
2099
2428
  JOIN json_each(t.record_json, '$.artist_credits') a
2100
2429
  WHERE ${own} AND name IS NOT NULL
2101
- GROUP BY name ORDER BY plays DESC, last_played_at DESC LIMIT ?`).all(subject, from, JSON.stringify(started), limit);
2430
+ GROUP BY name ORDER BY plays DESC, last_played_at DESC LIMIT ?`).all(...range, JSON.stringify(started), limit);
2102
2431
  return structuredClone({ from_date: localDate(start), through_date: localDate(today), plays,
2103
2432
  ...(started.length ? { moondog_started_plays: started.length } : {}), top_artists: artists });
2104
2433
  }
@@ -2113,18 +2442,15 @@ export class ListeningHistoryStore {
2113
2442
  const subject = subjectId.toLowerCase();
2114
2443
  const version = `${this.listeningDataVersion()}:${subject}:${artists}`;
2115
2444
  if (this.#listeningDays?.version === version) return structuredClone(this.#listeningDays.value);
2116
- const effective = `e.subject_id = ?
2117
- AND NOT EXISTS (SELECT 1 FROM listening_event_supersessions s WHERE s.superseded_event_id = e.listening_event_id)
2118
- AND NOT EXISTS (SELECT 1 FROM listening_event_mirrors m WHERE m.mirror_event_id = e.listening_event_id)`;
2119
2445
  const suggestions = this.#suggestionsForMatching();
2120
2446
  const since = suggestions.length ? new Date(Date.parse(suggestions[0].requested_at) - SUGGESTION_WINDOW.beforeMs).toISOString() : null;
2121
2447
  const started = !since ? [] : markMoondogStartedPlays(this.#database.prepare(`SELECT
2122
2448
  e.listening_event_id, e.record_json AS event_json, t.record_json AS track_json FROM listening_events e
2123
2449
  JOIN track_refs t ON t.track_ref_id = e.track_ref_id AND t.revision = e.track_ref_revision
2124
- WHERE ${effective} AND e.occurred_at >= ?`)
2450
+ WHERE ${attentionEvents} AND e.occurred_at >= ?`)
2125
2451
  .all(subject, since).map((row) => ({ id: row.listening_event_id, event: JSON.parse(row.event_json), track: JSON.parse(row.track_json) })),
2126
2452
  suggestions).rows.filter((row) => row.moondog_suggestion_id).map((row) => row.id);
2127
- const own = `${effective} AND e.listening_event_id NOT IN (SELECT value FROM json_each(?))`;
2453
+ const own = `${attentionEvents} AND e.listening_event_id NOT IN (SELECT value FROM json_each(?))`;
2128
2454
  const left = JSON.stringify(started);
2129
2455
  const pairs = (rows) => rows.map((row) => [row.day, row.plays]);
2130
2456
  const days = this.#database.prepare(`SELECT date(e.occurred_at, 'localtime') AS day, COUNT(*) AS plays
@@ -2258,12 +2584,23 @@ export class ListeningHistoryStore {
2258
2584
  .get(subjectId.toLowerCase()).latest;
2259
2585
  const latestMs = Date.parse(latest ?? "");
2260
2586
  const suggestions = Number.isFinite(latestMs) ? this.#database.prepare(`SELECT suggestion_id, provider_track_id, isrc, track_key,
2261
- release_key, title, artist_credit, requested_at FROM moondog_suggestions WHERE requested_at <= ? ORDER BY suggestion_id`)
2262
- .all(new Date(latestMs + SUGGESTION_WINDOW.beforeMs).toISOString()) : [];
2587
+ release_key, title, artist_credit, requested_at FROM moondog_suggestions WHERE requested_at <= ? AND action <> ? ORDER BY suggestion_id`)
2588
+ .all(new Date(latestMs + SUGGESTION_WINDOW.beforeMs).toISOString(), PLAYLIST_SAVE_ACTION) : [];
2263
2589
  if (suggestions.length) digest.update("moondog_suggestions\0").update(JSON.stringify(suggestions));
2264
2590
  return digest.digest("hex");
2265
2591
  }
2266
2592
 
2593
+ // Resolve a history selection in its original listener scope. Older plans retained its
2594
+ // track reference and primary artist, which by itself cannot identify a featured artist.
2595
+ historyTrackArtists({ subjectId, trackRefId } = {}) {
2596
+ if (!isUuid(subjectId) || !isUuid(trackRefId)) return null;
2597
+ const row = this.#database.prepare(`SELECT t.record_json AS track, json_extract(e.record_json, '$.provenance.external_ref.system') AS source
2598
+ FROM listening_events e JOIN track_refs t ON t.track_ref_id = e.track_ref_id AND t.revision = e.track_ref_revision
2599
+ WHERE e.subject_id = ? AND e.track_ref_id = ? ORDER BY e.track_ref_revision DESC, e.rowid LIMIT 1`)
2600
+ .get(subjectId.toLowerCase(), trackRefId.toLowerCase());
2601
+ return row ? historyAvoidArtists(JSON.parse(row.track), row.source) : null;
2602
+ }
2603
+
2267
2604
  rediscoveryCandidates({ subjectId, limit = 6 } = {}) {
2268
2605
  if (!Number.isInteger(limit) || limit < 1 || limit > 12) {
2269
2606
  throw new TypeError("Listening rediscovery limit is invalid");
@@ -2703,14 +3040,30 @@ function databaseConstructor() {
2703
3040
  return databaseConstructorPromise;
2704
3041
  }
2705
3042
 
2706
- async function initializeListeningHistoryDatabase(
2707
- database,
2708
- { journalMode, filePath = null },
2709
- ) {
2710
- database.exec("PRAGMA busy_timeout = 5000");
2711
- database.exec(`PRAGMA journal_mode = ${journalMode}`);
2712
- database.exec("PRAGMA foreign_keys = ON");
2713
- database.exec("PRAGMA trusted_schema = OFF");
3043
+ // Older versions kept one cumulative row per archive. They did not record which
3044
+ // confirmation caused a reconciliation, or when unchanged repeats happened.
3045
+ function recordEarlierImportReceipts(database, batchId) {
3046
+ const parameters = batchId ? [batchId] : [];
3047
+ const missing = `${batchId ? "b.import_batch_id = ? AND " : ""}NOT EXISTS (
3048
+ SELECT 1 FROM listening_import_receipts r WHERE r.import_batch_id = b.import_batch_id)`;
3049
+ if (!database.prepare(`SELECT 1 FROM import_batches b WHERE ${missing} LIMIT 1`).get(...parameters)) return;
3050
+ database.prepare(`INSERT INTO listening_import_receipts (
3051
+ subject_id, source_key, source_format, data_scope, import_batch_id, imported_at, earliest_occurred_at, latest_occurred_at,
3052
+ input_records, inserted_events, duplicate_events, input_profile_evidence, inserted_profile_evidence, captured_at,
3053
+ events_with_played_ms
3054
+ ) SELECT b.subject_id, b.source_key, b.source_format, b.data_scope, b.import_batch_id, b.imported_at,
3055
+ b.earliest_occurred_at, b.latest_occurred_at,
3056
+ b.input_records, b.inserted_events, b.duplicate_events, p.input_records, p.inserted_evidence,
3057
+ (SELECT e.captured_at FROM spotify_profile_evidence e WHERE e.profile_import_id = p.profile_import_id LIMIT 1),
3058
+ CASE WHEN b.input_records = 0 THEN 0 END
3059
+ FROM import_batches b LEFT JOIN profile_import_batches p
3060
+ ON p.subject_id = b.subject_id AND p.archive_sha256 = b.archive_sha256 AND p.archive_size_bytes = b.archive_size_bytes
3061
+ AND p.source_key = CASE b.source_key WHEN 'spotify.account_data.streaming_history'
3062
+ THEN 'spotify.account_data.music_profile' ELSE b.source_key END
3063
+ WHERE ${missing} ORDER BY b.imported_at, b.rowid`).run(...parameters);
3064
+ }
3065
+
3066
+ function listeningSchemaVersion(database) {
2714
3067
  const currentVersion = database.prepare("PRAGMA user_version").get()
2715
3068
  .user_version;
2716
3069
  if (
@@ -2720,11 +3073,25 @@ async function initializeListeningHistoryDatabase(
2720
3073
  ) {
2721
3074
  throw new Error("Listening history database schema is incompatible");
2722
3075
  }
3076
+ return currentVersion;
3077
+ }
3078
+
3079
+ async function initializeListeningHistoryDatabase(
3080
+ database,
3081
+ { journalMode, filePath = null },
3082
+ ) {
3083
+ database.exec("PRAGMA busy_timeout = 5000");
3084
+ database.exec(`PRAGMA journal_mode = ${journalMode}`);
3085
+ database.exec("PRAGMA foreign_keys = ON");
3086
+ database.exec("PRAGMA trusted_schema = OFF");
3087
+ const currentVersion = listeningSchemaVersion(database);
2723
3088
  const recordsGaps = database.prepare(
2724
3089
  "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'listening_coverage_gaps'",
2725
3090
  ).get();
2726
3091
  database.exec(schema);
2727
3092
  if (!recordsGaps) recordEarlierRecentSyncGaps(database);
3093
+ repairEarlierMusicAppMirrors(database);
3094
+ recordEarlierImportReceipts(database);
2728
3095
  if (currentVersion < LISTENING_HISTORY_SCHEMA_VERSION) {
2729
3096
  database.exec(
2730
3097
  `PRAGMA user_version = ${LISTENING_HISTORY_SCHEMA_VERSION}`,
@@ -2749,24 +3116,234 @@ export async function openEphemeralListeningHistoryStore() {
2749
3116
  }
2750
3117
  }
2751
3118
 
2752
- export async function openListeningHistoryStore({
2753
- databasePath = defaultListeningHistoryPath,
2754
- environment = process.env,
2755
- } = {}) {
2756
- const resolvedPath =
2757
- databasePath === defaultListeningHistoryPath
2758
- ? resolveListeningHistoryPath(environment)
2759
- : databasePath;
2760
- const parent = path.dirname(path.resolve(resolvedPath));
3119
+ function listeningDatabasePath({ databasePath = defaultListeningHistoryPath, environment = process.env } = {}) {
3120
+ return path.resolve(databasePath === defaultListeningHistoryPath ? resolveListeningHistoryPath(environment) : databasePath);
3121
+ }
3122
+
3123
+
3124
+ // Compare in a disposable SQLite database using the same writes as a confirmed import.
3125
+ // The limits apply only to previews. An oversized archive can still be saved normally.
3126
+ const comparisonRowLimit = 100_000;
3127
+ const comparisonLookupLimit = 100_000;
3128
+ const comparisonPageLimit = 32_768; // 128 MiB with the private database's 4 KiB pages
3129
+ const comparisonPairLimit = 150_000;
3130
+ const comparisonTables = [
3131
+ "import_batches", "profile_import_batches", "source_cursors", "listening_history_repairs",
3132
+ "listening_events", "listening_event_reconciliation_candidates", "listening_event_supersessions", "listening_event_mirrors",
3133
+ ];
3134
+
3135
+ function comparisonLimit() {
3136
+ return Object.assign(new Error("Listening comparison exceeds the preview limit"), { code: "comparison_limit" });
3137
+ }
3138
+
3139
+ function effectiveComparisonEvents(schemaName, tables) {
3140
+ const conditions = ["e.subject_id = ?"];
3141
+ if (tables.has("listening_event_supersessions")) {
3142
+ conditions.push(`NOT EXISTS (SELECT 1 FROM ${schemaName}.listening_event_supersessions s WHERE s.superseded_event_id = e.listening_event_id)`);
3143
+ }
3144
+ if (tables.has("listening_event_mirrors")) {
3145
+ conditions.push(`NOT EXISTS (SELECT 1 FROM ${schemaName}.listening_event_mirrors m WHERE m.mirror_event_id = e.listening_event_id)`);
3146
+ }
3147
+ return `FROM ${schemaName}.listening_events e WHERE ${conditions.join(" AND ")}`;
3148
+ }
3149
+
3150
+ function effectiveBounds(database, schemaName, tables, subjectId) {
3151
+ if (!tables.has("listening_events")) return { earliest: null, latest: null };
3152
+ const select = `SELECT e.occurred_at ${effectiveComparisonEvents(schemaName, tables)} ORDER BY e.occurred_at`;
3153
+ return {
3154
+ earliest: database.prepare(`${select} ASC LIMIT 1`).get(subjectId)?.occurred_at ?? null,
3155
+ latest: database.prepare(`${select} DESC LIMIT 1`).get(subjectId)?.occurred_at ?? null,
3156
+ };
3157
+ }
3158
+
3159
+ function savedArchiveCoverage(database, schemaName, tables, bundle) {
3160
+ if (!bundle) return { alreadyImported: null, firstImportedAt: null, archiveCoverage: null };
3161
+ const batch = bundle.import_batch;
3162
+ const previous = tables.has("import_batches") && database.prepare(
3163
+ `SELECT * FROM ${schemaName}.import_batches WHERE import_batch_id = ? AND subject_id = ? AND source_key = ? AND archive_sha256 = ?`,
3164
+ ).get(batch.import_batch_id, batch.subject_id, bundle.source_key, batch.archive_sha256);
3165
+ if (!previous) return { alreadyImported: false, firstImportedAt: null, archiveCoverage: "none" };
3166
+ const covers = (old, incoming) => {
3167
+ if (old?.source_format !== incoming.source_format || old.archive_size_bytes !== incoming.archive_size_bytes ||
3168
+ old.input_records < incoming.input_records) return false;
3169
+ const savedMembers = new Set(JSON.parse(old.member_names_json));
3170
+ return incoming.member_names.every(name => savedMembers.has(name));
3171
+ };
3172
+ const profile = bundle.profile_import;
3173
+ const previousProfile = profile && tables.has("profile_import_batches") && database.prepare(
3174
+ `SELECT * FROM ${schemaName}.profile_import_batches WHERE profile_import_id = ? AND subject_id = ? AND source_key = ? AND archive_sha256 = ?`,
3175
+ ).get(profile.profile_import_id, profile.subject_id, profile.source_key, profile.archive_sha256);
3176
+ return {
3177
+ alreadyImported: true,
3178
+ firstImportedAt: previous.imported_at,
3179
+ archiveCoverage: covers(previous, batch) && (!profile || covers(previousProfile, profile)) ? "complete" : "partial",
3180
+ };
3181
+ }
3182
+
3183
+ function existingSourceRecords(database, schemaName, tables, events, subjectId) {
3184
+ if (!events.length || !tables.has("listening_events")) return 0;
3185
+ const from = `FROM ${schemaName}.listening_events WHERE subject_id = ?`;
3186
+ if (!database.prepare(`SELECT 1 ${from} LIMIT 1`).get(subjectId)) return 0;
3187
+ if (events.length > comparisonLookupLimit) return null;
3188
+ // Both identities are unique. Keep these as direct indexed lookups even
3189
+ // when SQLite's statistics favor an index over the listener's entire span.
3190
+ const byId = database.prepare(`SELECT subject_id FROM ${schemaName}.listening_events WHERE listening_event_id = ?`);
3191
+ const byKey = database.prepare(`SELECT subject_id FROM ${schemaName}.listening_events WHERE deduplication_key = ?`);
3192
+ let count = 0;
3193
+ for (const event of events) {
3194
+ if (byId.get(event.listening_event_id)?.subject_id === subjectId || byKey.get(event.deduplication_key)?.subject_id === subjectId) count += 1;
3195
+ }
3196
+ return count;
3197
+ }
3198
+
3199
+ function copyImportState(database, tables, bundles, rowsLeft) {
3200
+ // These tables contain the prior candidates and one-to-one links the writer can
3201
+ // resolve even when its input arrived through a different client or archive.
3202
+ const copy = comparisonTables.filter(table => tables.has(table));
3203
+ for (const table of copy) {
3204
+ const { count } = database.prepare(`SELECT count(*) AS count FROM (SELECT 1 FROM saved.${table} LIMIT ?)`).get(rowsLeft + 1);
3205
+ rowsLeft -= count;
3206
+ if (rowsLeft < 0) throw comparisonLimit();
3207
+ }
3208
+ // A saved collection can contain many tracks without a play. Only records
3209
+ // referenced by saved events or the incoming bundles can affect this import.
3210
+ if (tables.has("track_refs")) {
3211
+ if (tables.has("listening_events")) database.exec(`INSERT INTO main.track_refs
3212
+ SELECT t.* FROM (SELECT DISTINCT track_ref_id, track_ref_revision FROM saved.listening_events) e
3213
+ JOIN saved.track_refs t ON t.track_ref_id = e.track_ref_id AND t.revision = e.track_ref_revision`);
3214
+ const copyTrack = database.prepare("INSERT OR IGNORE INTO main.track_refs SELECT * FROM saved.track_refs WHERE track_ref_id = ? AND revision = ?");
3215
+ for (const bundle of bundles) {
3216
+ for (const track of bundle.track_refs) copyTrack.run(track.track_ref_id, track.revision);
3217
+ }
3218
+ }
3219
+ for (const table of copy) database.exec(`INSERT INTO main.${table} SELECT * FROM saved.${table}`);
3220
+ // Other stored profile observations cannot collide with the two unique keys
3221
+ // used by an incoming observation. The comparison does not need their content.
3222
+ if (tables.has("spotify_profile_evidence")) {
3223
+ const copyEvidence = database.prepare(`INSERT OR IGNORE INTO main.spotify_profile_evidence SELECT * FROM saved.spotify_profile_evidence
3224
+ WHERE profile_evidence_id = ? OR (profile_import_id = ? AND evidence_key = ?)`);
3225
+ for (const bundle of bundles) {
3226
+ for (const record of bundle.profile_evidence ?? []) {
3227
+ copyEvidence.run(record.profile_evidence_id, bundle.profile_import.profile_import_id, record.evidence_key);
3228
+ }
3229
+ }
3230
+ }
3231
+ }
3232
+
3233
+ async function comparePreparedListening({ bundle, libraryBundle, subjectId, quick = false }, options) {
3234
+ let database;
3235
+ let facts;
3236
+ try {
3237
+ if (!isUuid(subjectId)) throw new Error("Invalid local music subject");
3238
+ subjectId = subjectId.toLowerCase();
3239
+ const filePath = listeningDatabasePath(options);
3240
+ const exists = await stat(filePath).then(() => true, error => {
3241
+ if (error.code === "ENOENT") return false;
3242
+ throw error;
3243
+ });
3244
+ const DatabaseSync = await databaseConstructor();
3245
+ database = new DatabaseSync(":memory:");
3246
+ database.exec(`PRAGMA temp_store = MEMORY; PRAGMA page_size = 4096; PRAGMA max_page_count = ${comparisonPageLimit}`);
3247
+ database.exec(schema);
3248
+ const source = exists ? "saved" : "main";
3249
+ if (exists) {
3250
+ const url = pathToFileURL(filePath);
3251
+ url.searchParams.set("mode", "ro");
3252
+ database.prepare("ATTACH DATABASE ? AS saved").run(url.href);
3253
+ }
3254
+ database.exec("BEGIN");
3255
+ const version = database.prepare(`PRAGMA ${source}.user_version`).get().user_version;
3256
+ if (version > LISTENING_HISTORY_SCHEMA_VERSION) throw new Error("Incompatible listening schema");
3257
+ const tables = new Set(database.prepare(`SELECT name FROM ${source}.sqlite_schema WHERE type = 'table'`).all().map(row => row.name));
3258
+ resolveLocalMusicSubject(database, { preferredSubjectId: subjectId, availableTables: tables, schemaName: source });
3259
+ facts = {
3260
+ before: effectiveBounds(database, source, tables, subjectId),
3261
+ ...savedArchiveCoverage(database, source, tables, quick ? null : bundle),
3262
+ sourceRecordsAlreadyStored: existingSourceRecords(database, source, tables, bundle.listening_events, subjectId),
3263
+ };
3264
+ const bundles = libraryBundle ? [bundle, libraryBundle] : [bundle];
3265
+ let rowsLeft = comparisonRowLimit;
3266
+ for (const part of bundles) {
3267
+ rowsLeft -= part.listening_events.length + part.track_refs.length +
3268
+ (part.profile_evidence?.length ?? 0) + (part.reconciliation_candidates?.length ?? 0);
3269
+ }
3270
+ if (rowsLeft < 0) throw comparisonLimit();
3271
+ if (exists) copyImportState(database, tables, bundles, rowsLeft);
3272
+ database.exec("COMMIT");
3273
+ if (exists) database.exec("DETACH DATABASE saved");
3274
+ const privateTables = new Set(comparisonTables);
3275
+ const listeningDays = database.prepare(`SELECT DISTINCT substr(e.occurred_at, 1, 10) AS day ${effectiveComparisonEvents("main", privateTables)}`);
3276
+ const priorDays = new Set(listeningDays.all(subjectId).map(row => row.day));
3277
+ // A legacy database can still need the same one-shot repair as the normal
3278
+ // writer. Apply it only to the snapshot before predicting its receipt.
3279
+ repairEarlierMusicAppMirrors(database, comparisonPairLimit);
3280
+ const store = new ListeningHistoryStore(database, { maxMirrorPairs: comparisonPairLimit });
3281
+ const receipt = quick
3282
+ ? store.ingestSpotifyQuick({ recentBundle: bundle, libraryBundle, subjectId })
3283
+ : store.ingestImport(bundle);
3284
+ return {
3285
+ state: "exact", ...facts,
3286
+ after: effectiveBounds(database, "main", privateTables, subjectId),
3287
+ newListeningDays: listeningDays.all(subjectId).filter(row => !priorDays.has(row.day)).length,
3288
+ insertedEvents: receipt.inserted_events,
3289
+ duplicateEvents: receipt.duplicate_events,
3290
+ ...(receipt.upgraded_recording_events ? { upgradedRecordingEvents: receipt.upgraded_recording_events } : {}),
3291
+ supersededEvents: receipt.superseded_events ?? 0,
3292
+ mirroredEvents: receipt.mirrored_events ?? 0,
3293
+ effectiveEventDelta: receipt.effective_event_delta,
3294
+ insertedProfileEvidence: receipt.inserted_profile_evidence ?? 0,
3295
+ };
3296
+ } catch (error) {
3297
+ const reason = error.code === "comparison_limit" || error.errcode === 13 ? "comparison_limit" : "comparison_unavailable";
3298
+ return facts ? { state: "partial", reason, ...facts } : { state: "unavailable", reason };
3299
+ } finally {
3300
+ database?.close();
3301
+ }
3302
+ }
3303
+
3304
+ /** Compare the prepared archive with one snapshot of the saved listener, before confirmation. */
3305
+ export function compareListeningImport(bundle, options = {}) {
3306
+ return comparePreparedListening({ bundle, subjectId: bundle?.import_batch?.subject_id }, options);
3307
+ }
3308
+
3309
+ /** A rolling Spotify read has no prior archive date or immutable file identity. */
3310
+ export function compareSpotifyQuickImport({ bundle, libraryBundle, subjectId } = {}, options = {}) {
3311
+ return comparePreparedListening({ bundle, libraryBundle, subjectId, quick: true }, options);
3312
+ }
3313
+
3314
+ export async function readListeningImportSubject({ preferredSubjectId, ...options } = {}) {
3315
+ const filePath = listeningDatabasePath(options);
3316
+ try {
3317
+ await stat(filePath);
3318
+ } catch (error) {
3319
+ if (error.code === "ENOENT") return resolveLocalMusicSubject(null, { preferredSubjectId });
3320
+ throw error;
3321
+ }
3322
+ const DatabaseSync = await databaseConstructor();
3323
+ const database = new DatabaseSync(filePath, { readOnly: true });
3324
+ try {
3325
+ // Use normal SQLite locking so a commit in a live WAL is visible.
3326
+ database.exec("PRAGMA trusted_schema = OFF; BEGIN");
3327
+ listeningSchemaVersion(database);
3328
+ const availableTables = new Set(database.prepare("SELECT name FROM sqlite_schema WHERE type = 'table'").all().map(row => row.name));
3329
+ return resolveLocalMusicSubject(database, { preferredSubjectId, availableTables });
3330
+ } finally {
3331
+ database.close();
3332
+ }
3333
+ }
3334
+
3335
+ export async function openListeningHistoryStore(options = {}) {
3336
+ const resolvedPath = listeningDatabasePath(options);
3337
+ const parent = path.dirname(resolvedPath);
2761
3338
  await mkdir(parent, { recursive: true, mode: 0o700 });
2762
3339
  if (process.platform !== "win32") await chmod(parent, 0o700);
2763
3340
 
2764
3341
  const DatabaseSync = await databaseConstructor();
2765
- const database = new DatabaseSync(path.resolve(resolvedPath));
3342
+ const database = new DatabaseSync(resolvedPath);
2766
3343
  try {
2767
3344
  await initializeListeningHistoryDatabase(database, {
2768
3345
  journalMode: "WAL",
2769
- filePath: path.resolve(resolvedPath),
3346
+ filePath: resolvedPath,
2770
3347
  });
2771
3348
  return new ListeningHistoryStore(database);
2772
3349
  } catch (error) {