@audiofool/moondog 0.4.0-beta.2 → 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 (96) hide show
  1. package/README.md +19 -8
  2. package/package.json +1 -1
  3. package/scripts/moondog.mjs +130 -106
  4. package/src/core/apple-library-source-status.mjs +64 -18
  5. package/src/core/apple-projection-domain-services.mjs +67 -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 +32 -18
  16. package/src/core/listening-scope.mjs +119 -0
  17. package/src/core/moondog-application.mjs +1045 -270
  18. package/src/core/play-follower.mjs +104 -0
  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 +90 -26
  34. package/src/i18n/screen/ja.mjs +89 -25
  35. package/src/i18n/screen/pt.mjs +90 -26
  36. package/src/i18n/screen/zh.mjs +89 -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/music-app-listening.mjs +107 -0
  44. package/src/integrations/apple-music/music-app.mjs +6 -2
  45. package/src/integrations/apple-music/song-id.mjs +13 -0
  46. package/src/integrations/apple-music/terminal-preview-player.mjs +154 -44
  47. package/src/integrations/listenbrainz/history-file.mjs +63 -35
  48. package/src/integrations/netease/ncm-cli-player.mjs +355 -68
  49. package/src/integrations/netease/queue-occurrence.mjs +138 -0
  50. package/src/integrations/playlist-links.mjs +93 -30
  51. package/src/integrations/public-playlists.mjs +21 -15
  52. package/src/integrations/spotify/account-data-history.mjs +9 -10
  53. package/src/integrations/spotify/account-data-profile.mjs +1 -0
  54. package/src/integrations/spotify/extended-streaming-history.mjs +57 -52
  55. package/src/integrations/spotify/history-archive.mjs +8 -18
  56. package/src/integrations/spotify/library-snapshot.mjs +2 -1
  57. package/src/integrations/spotify/service.mjs +29 -11
  58. package/src/integrations/spotify/web-api-client.mjs +2 -2
  59. package/src/integrations/stable-audio/local-generator.mjs +13 -5
  60. package/src/integrations/youtube-music/takeout.mjs +12 -8
  61. package/src/memory/local-memory-store.mjs +479 -27
  62. package/src/memory/reflection-worker.mjs +19 -0
  63. package/src/profile/apple-library-import.mjs +56 -2
  64. package/src/profile/history-import.mjs +58 -27
  65. package/src/profile/listener-corrections.mjs +2 -4
  66. package/src/profile/listener-profile-build.mjs +133 -46
  67. package/src/profile/listener-profile-store.mjs +57 -4
  68. package/src/profile/listener-profile-verification.mjs +11 -5
  69. package/src/profile/listener-profile-worker.mjs +36 -10
  70. package/src/profile/listening-history-store.mjs +975 -354
  71. package/src/profile/listening-profile-projection.mjs +130 -160
  72. package/src/profile/local-file-import.mjs +172 -0
  73. package/src/profile/moondog-suggestions.mjs +40 -11
  74. package/src/profile/profile-exploration.mjs +36 -6
  75. package/src/profile/recorded-measures.mjs +5 -0
  76. package/src/profile/spotify-archive-taste.mjs +41 -65
  77. package/src/runtime/pi/agent-runtime.mjs +368 -221
  78. package/src/runtime/pi/custom-endpoints.mjs +30 -8
  79. package/src/runtime/pi/memory-agent-runtime.mjs +45 -3
  80. package/src/runtime/pi/moondog-model.mjs +6 -0
  81. package/src/runtime/pi/playback-rules.mjs +100 -0
  82. package/src/runtime/pi/profile-build-runtime.mjs +85 -24
  83. package/src/surfaces/cli/brand-components.mjs +9 -6
  84. package/src/surfaces/cli/command-completions.mjs +8 -1
  85. package/src/surfaces/cli/format-output.mjs +207 -34
  86. package/src/surfaces/cli/history-import-view.mjs +130 -21
  87. package/src/surfaces/cli/listenbrainz-command.mjs +7 -2
  88. package/src/surfaces/cli/listener-profile-command.mjs +67 -8
  89. package/src/surfaces/cli/listening-menu.mjs +3 -0
  90. package/src/surfaces/cli/profile-command.mjs +1 -0
  91. package/src/surfaces/cli/spotify-command.mjs +17 -25
  92. package/src/surfaces/cli/taste-period.mjs +22 -0
  93. package/src/surfaces/cli/taste-profile-model.mjs +52 -32
  94. package/src/surfaces/cli/tui.mjs +557 -170
  95. package/src/surfaces/html/tasteprint.mjs +181 -93
  96. 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,
@@ -220,6 +280,16 @@ const schema = `
220
280
  CREATE INDEX IF NOT EXISTS moondog_suggestions_time
221
281
  ON moondog_suggestions(requested_at);
222
282
 
283
+ -- How each song Moondog started went: played through, skipped within 30 seconds, or left
284
+ -- partway. An outcome of a suggestion, never a dislike. Older Moondogs leave this table alone.
285
+ CREATE TABLE IF NOT EXISTS moondog_suggestion_outcomes (
286
+ suggestion_id TEXT NOT NULL,
287
+ outcome TEXT NOT NULL CHECK (outcome IN ('completed', 'skipped', 'partial')),
288
+ heard_ms INTEGER NOT NULL,
289
+ observed_at TEXT NOT NULL,
290
+ PRIMARY KEY (suggestion_id, observed_at)
291
+ ) STRICT;
292
+
223
293
  ${listenerProfileSchema}
224
294
  `;
225
295
 
@@ -236,6 +306,21 @@ function isPlainObject(value) {
236
306
  return prototype === Object.prototype || prototype === null;
237
307
  }
238
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
+
239
324
  function cleanSourceKey(value) {
240
325
  if (
241
326
  typeof value !== "string" ||
@@ -440,7 +525,6 @@ function normalizedProfileInput(value, batch) {
440
525
  archiveSizeBytes: profileImport.archive_size_bytes,
441
526
  memberNames: [...profileImport.member_names],
442
527
  inputRecords: profileImport.input_records,
443
- importedAt,
444
528
  },
445
529
  profileEvidence: records,
446
530
  };
@@ -670,17 +754,19 @@ function insertBundleRecords(bundle, statements) {
670
754
  return { insertedTracks, insertedEvents };
671
755
  }
672
756
 
757
+ const MUSIC_APP_PLAY = "apple_music.music_app_play";
758
+
673
759
  // Where stored plays came from, in words the agent can repeat. Others keep their kind.
674
760
  const COVERAGE_SOURCE_LABELS = {
675
761
  "spotify.play_history": "Spotify recent plays, read while Moondog runs",
676
762
  "spotify.extended_history.play": "Spotify Extended Streaming History file",
677
763
  "spotify.account_data.play_history": "Spotify Account Data file",
678
764
  "listenbrainz.listen": "ListenBrainz export file",
765
+ [MUSIC_APP_PLAY]: "Music app plays on this Mac, kept while Moondog runs",
679
766
  };
680
767
 
681
768
  const SCROBBLE_SOURCE_KEY = "lastfm.music_import";
682
- // Scrobbles record when a song started. Spotify records when a play ended, so its start is
683
- // 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.
684
770
  const MIRROR_TOLERANCE_MS = 150_000;
685
771
  const DAY_MS = 86_400_000;
686
772
 
@@ -695,11 +781,11 @@ const foldLabel = (value) => String(value ?? "").normalize("NFKC").toLocaleLower
695
781
  const lexicalCompare = (left, right) => (left < right ? -1 : left > right ? 1 : 0);
696
782
 
697
783
  /**
698
- * 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
699
785
  * that matches another service's play (same artist and title, starting within a few minutes)
700
786
  * is linked to it once, whichever was imported first, so the play counts once.
701
787
  */
702
- function reconcileScrobbleMirrors(database, subjectId, earliest, latest, createdAt) {
788
+ function reconcileScrobbleMirrors(database, subjectId, earliest, latest, createdAt, { musicAppOnly = false, maxPairs = Infinity } = {}) {
703
789
  if (!subjectId || !earliest || !latest) return 0;
704
790
  const scrobbled = database.prepare(
705
791
  "SELECT 1 FROM import_batches WHERE subject_id = ? AND source_key = ? LIMIT 1",
@@ -736,17 +822,25 @@ function reconcileScrobbleMirrors(database, subjectId, earliest, latest, created
736
822
  if (!artist || !title) continue;
737
823
  const key = `${artist}\u0000${title}`;
738
824
  const at = Date.parse(row.at);
739
- const system = String(event.provenance?.external_ref?.system ?? "");
825
+ const source = event.provenance?.external_ref;
826
+ const system = String(source?.system ?? "");
740
827
  if (system === "lastfm") {
741
828
  if (!scrobbles.has(key)) scrobbles.set(key, []);
742
829
  scrobbles.get(key).push({ id: row.id, start: at });
743
830
  continue;
744
831
  }
745
- const length = Number.isSafeInteger(event.played_ms) ? event.played_ms
746
- : Number.isSafeInteger(track.duration_ms) ? track.duration_ms : null;
747
- // A Spotify play of unknown length can't be placed precisely enough to match.
748
- if (system.startsWith("spotify") && length === null) continue;
749
- 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 });
750
844
  }
751
845
  const pairs = [];
752
846
  for (const list of scrobbles.values()) list.sort((left, right) => left.start - right.start);
@@ -761,6 +855,7 @@ function reconcileScrobbleMirrors(database, subjectId, earliest, latest, created
761
855
  else high = middle;
762
856
  }
763
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();
764
859
  pairs.push({ gap: Math.abs(list[index].start - play.start), play: play.id, scrobble: list[index].id });
765
860
  }
766
861
  }
@@ -783,6 +878,108 @@ function reconcileScrobbleMirrors(database, subjectId, earliest, latest, created
783
878
  return linked;
784
879
  }
785
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
+
786
983
  function preserveExtendedHistoryMatches(bundle, retainedMatch) {
787
984
  const candidates = bundle.reconciliationCandidates;
788
985
  if (bundle.importBatch.sourceFormat !== "spotify_extended_streaming_history_music_v1") return candidates;
@@ -793,7 +990,7 @@ function preserveExtendedHistoryMatches(bundle, retainedMatch) {
793
990
  retained.get(candidate.supersedingEventId) !== candidate.supersededEventId)) return candidates;
794
991
 
795
992
  // Account Data cannot distinguish equal-duration plays of the same title and
796
- // artist within one minute. Added video plays can reorder those ordinals.
993
+ // artist within one minute. Newly recovered plays can reorder those ordinals.
797
994
  // A narrower export may omit an established counterpart's ordinal entirely.
798
995
  // Keep those pairs too; only new plays use this archive's remaining candidates.
799
996
  // The store's conflict checks still reject a new play claiming an absent play's
@@ -836,8 +1033,45 @@ function preserveExtendedHistoryMatches(bundle, retainedMatch) {
836
1033
  }));
837
1034
  }
838
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
+
839
1072
  export class ListeningHistoryStore {
840
1073
  #database;
1074
+ #maxMirrorPairs;
841
1075
  #closed = false;
842
1076
  #snapshot = null;
843
1077
  #projection = null;
@@ -846,8 +1080,9 @@ export class ListeningHistoryStore {
846
1080
  #ledgerChanges = 0;
847
1081
  #listeningDays = null;
848
1082
 
849
- constructor(database) {
1083
+ constructor(database, { maxMirrorPairs = Infinity } = {}) {
850
1084
  this.#database = database;
1085
+ this.#maxMirrorPairs = maxMirrorPairs;
851
1086
  }
852
1087
 
853
1088
  sourceCursor(sourceKey) {
@@ -864,70 +1099,7 @@ export class ListeningHistoryStore {
864
1099
 
865
1100
  localSubjectId({ preferredSubjectId, create = false } = {}) {
866
1101
  if (this.#closed) throw new Error("Listening history store is closed");
867
- if (preferredSubjectId !== undefined && !isUuid(preferredSubjectId)) {
868
- throw new TypeError("A valid preferred local music subject is required");
869
- }
870
- if (typeof create !== "boolean") {
871
- throw new TypeError("Local music subject creation flag is invalid");
872
- }
873
- const preferred = preferredSubjectId?.toLowerCase() ?? null;
874
- const registered = this.#database
875
- .prepare(
876
- "SELECT subject_id FROM local_music_subject WHERE singleton = 1",
877
- )
878
- .get()?.subject_id;
879
- if (registered !== undefined) {
880
- if (!isUuid(registered)) {
881
- throw new Error("The local music subject registry is invalid");
882
- }
883
- const normalized = registered.toLowerCase();
884
- if (preferred && preferred !== normalized) {
885
- throw new Error(
886
- "The trusted Apple and local listening-history subjects do not match",
887
- );
888
- }
889
- return normalized;
890
- }
891
-
892
- const observed = this.#database
893
- .prepare(
894
- `SELECT subject_id FROM (
895
- SELECT subject_id FROM listening_events
896
- UNION
897
- SELECT subject_id FROM import_batches
898
- UNION
899
- SELECT subject_id FROM profile_import_batches
900
- UNION
901
- SELECT subject_id FROM spotify_profile_evidence
902
- UNION
903
- SELECT subject_id FROM taste_events
904
- )
905
- ORDER BY subject_id`,
906
- )
907
- .all()
908
- .map((row) => row.subject_id?.toLowerCase());
909
- if (observed.some((subjectId) => !isUuid(subjectId))) {
910
- throw new Error("Stored listening history contains an invalid subject");
911
- }
912
- if (observed.length > 1) {
913
- throw new Error(
914
- "Stored listening history contains multiple local music subjects",
915
- );
916
- }
917
- const inherited = observed[0] ?? null;
918
- if (preferred && inherited && preferred !== inherited) {
919
- throw new Error(
920
- "The trusted Apple and local listening-history subjects do not match",
921
- );
922
- }
923
- const resolved = inherited ?? preferred ?? (create ? randomUUID() : null);
924
- if (!resolved) return null;
925
- this.#database
926
- .prepare(
927
- "INSERT INTO local_music_subject (singleton, subject_id) VALUES (1, ?)",
928
- )
929
- .run(resolved);
930
- return resolved;
1102
+ return resolveLocalMusicSubject(this.#database, { preferredSubjectId, create, register: true });
931
1103
  }
932
1104
 
933
1105
  subjectDataStatus({ subjectId } = {}) {
@@ -1198,6 +1370,7 @@ export class ListeningHistoryStore {
1198
1370
 
1199
1371
  listListenerCorrections({
1200
1372
  subjectId,
1373
+ targetKey = null,
1201
1374
  includeInactive = false,
1202
1375
  limit = 50,
1203
1376
  } = {}) {
@@ -1208,7 +1381,7 @@ export class ListeningHistoryStore {
1208
1381
  if (typeof includeInactive !== "boolean") {
1209
1382
  throw new TypeError("Listener correction history flag is invalid");
1210
1383
  }
1211
- if (!Number.isInteger(limit) || limit < 1 || limit > 100) {
1384
+ if (limit !== null && (!Number.isInteger(limit) || limit < 1 || limit > 100)) {
1212
1385
  throw new TypeError("Listener correction limit is invalid");
1213
1386
  }
1214
1387
  const rows = this.#database
@@ -1236,6 +1409,7 @@ export class ListeningHistoryStore {
1236
1409
  FROM taste_events a
1237
1410
  WHERE a.subject_id = ?
1238
1411
  AND a.operation = 'assert'
1412
+ AND (? IS NULL OR a.target_key = ?)
1239
1413
  AND (
1240
1414
  ? = 1 OR (
1241
1415
  NOT EXISTS (
@@ -1251,7 +1425,7 @@ export class ListeningHistoryStore {
1251
1425
  ORDER BY a.recorded_at DESC, a.taste_event_id DESC
1252
1426
  LIMIT ?`,
1253
1427
  )
1254
- .all(subjectId.toLowerCase(), includeInactive ? 1 : 0, limit);
1428
+ .all(subjectId.toLowerCase(), targetKey, targetKey, includeInactive ? 1 : 0, limit ?? -1);
1255
1429
  return rows
1256
1430
  .map((row) => {
1257
1431
  const record = JSON.parse(row.record_json);
@@ -1302,9 +1476,25 @@ export class ListeningHistoryStore {
1302
1476
  .get(subjectId.toLowerCase()).count;
1303
1477
  }
1304
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
+
1305
1491
  ingest(value) {
1306
1492
  if (this.#closed) throw new Error("Listening history store is closed");
1307
1493
  const bundle = normalizedBundle(value);
1494
+ return this.#ingestTransaction(() => this.#saveRecent(bundle));
1495
+ }
1496
+
1497
+ #saveRecent(bundle) {
1308
1498
  const subjects = new Set(
1309
1499
  bundle.listeningEvents.map((record) => record.subject_id?.toLowerCase()),
1310
1500
  );
@@ -1314,32 +1504,17 @@ export class ListeningHistoryStore {
1314
1504
  const subjectId = [...subjects][0];
1315
1505
  const statements = ingestionStatements(this.#database);
1316
1506
 
1317
- this.#database.exec("BEGIN IMMEDIATE");
1318
- let insertedTracks;
1319
- let insertedEvents;
1320
- let mirroredEvents = 0;
1321
- try {
1322
- if (subjectId !== undefined) {
1323
- this.localSubjectId({ preferredSubjectId: subjectId });
1324
- }
1325
- const times = bundle.listeningEvents.map((record) => record.occurred_at).sort();
1326
- // A read that overlaps a stored play joins up with it.
1327
- const overlaps = bundle.listeningEvents.some((record) => statements.hasEvent.get(record.deduplication_key));
1328
- if (bundle.windowFull && subjectId !== undefined && !overlaps) {
1329
- recordCoverageGap(this.#database, { subjectId, sourceKey: bundle.sourceKey, before: times[0], detectedAt: bundle.capturedAt });
1330
- }
1331
- ({ insertedTracks, insertedEvents } = insertBundleRecords(
1332
- bundle,
1333
- statements,
1334
- ));
1335
- // A read that finds nothing new still moves the source's checked time.
1336
- statements.touchCursor.run(bundle.capturedAt, bundle.sourceKey);
1337
- mirroredEvents = reconcileScrobbleMirrors(this.#database, subjectId, times[0], times.at(-1), bundle.capturedAt);
1338
- this.#database.exec("COMMIT");
1339
- } catch (error) {
1340
- this.#database.exec("ROLLBACK");
1341
- 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 });
1342
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 });
1343
1518
 
1344
1519
  return {
1345
1520
  state: "ready",
@@ -1357,7 +1532,18 @@ export class ListeningHistoryStore {
1357
1532
  ingestImport(value) {
1358
1533
  if (this.#closed) throw new Error("Listening history store is closed");
1359
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) {
1360
1543
  const batch = bundle.importBatch;
1544
+ const eventsWithPlayedMs = bundle.listeningEvents.reduce(
1545
+ (count, event) => Number.isSafeInteger(event.played_ms) ? count + 1 : count, 0,
1546
+ );
1361
1547
  const existingBatch = this.#database.prepare(
1362
1548
  `SELECT * FROM import_batches
1363
1549
  WHERE import_batch_id = ?`,
@@ -1441,201 +1627,199 @@ export class ListeningHistoryStore {
1441
1627
  );
1442
1628
  const statements = ingestionStatements(this.#database);
1443
1629
 
1444
- this.#database.exec("BEGIN IMMEDIATE");
1445
1630
  let insertedTracks = 0;
1446
1631
  let insertedEvents = 0;
1447
1632
  let supersededEvents = 0;
1448
- let mirroredEvents = 0;
1633
+ let upgradedListens = 0;
1449
1634
  let insertedProfileEvidence = 0;
1450
- let alreadyImported = false;
1451
1635
  let profileAlreadyImported = bundle.profileImport === undefined;
1452
- try {
1453
- this.localSubjectId({ preferredSubjectId: batch.subjectId });
1454
- const previousBatch = existingBatch.get(batch.importBatchId);
1455
- alreadyImported = Boolean(previousBatch);
1456
- if (!alreadyImported) {
1457
- ({ insertedTracks, insertedEvents } = insertBundleRecords(
1458
- bundle,
1459
- statements,
1460
- ));
1461
- insertBatch.run(
1462
- batch.importBatchId,
1463
- batch.subjectId,
1464
- bundle.sourceKey,
1465
- batch.sourceFormat,
1466
- batch.dataScope,
1467
- batch.archiveSha256,
1468
- batch.archiveSizeBytes,
1469
- JSON.stringify(batch.memberNames),
1470
- batch.inputRecords,
1471
- batch.earliestOccurredAt,
1472
- batch.latestOccurredAt,
1473
- batch.importedAt,
1474
- insertedEvents,
1475
- batch.inputRecords - insertedEvents,
1476
- insertedTracks,
1477
- );
1478
- } else {
1479
- // Earlier readers skipped video members, even when they contained music.
1480
- // Extend that same archive's receipt without replacing its existing rows.
1481
- const previousMembers = JSON.parse(previousBatch.member_names_json);
1482
- const addedMembers = batch.memberNames.filter((name) => !previousMembers.includes(name));
1483
- const expandsExtendedArchive = batch.sourceFormat === "spotify_extended_streaming_history_music_v1" &&
1484
- previousBatch.subject_id === batch.subjectId && previousBatch.source_key === bundle.sourceKey &&
1485
- previousBatch.source_format === batch.sourceFormat && previousBatch.data_scope === batch.dataScope &&
1486
- previousBatch.archive_sha256 === batch.archiveSha256 && previousBatch.archive_size_bytes === batch.archiveSizeBytes &&
1487
- previousMembers.every((name) => batch.memberNames.includes(name)) && addedMembers.length > 0 &&
1488
- addedMembers.every((name) => /^Streaming_History_Video_\d{4}(?:_\d+)?\.json$/u.test(name));
1489
- if (expandsExtendedArchive) {
1490
- const incomingIds = new Set(bundle.listeningEvents.map((event) => event.listening_event_id));
1491
- const previousEvents = this.#database.prepare(`SELECT listening_event_id FROM listening_events
1492
- WHERE subject_id = ? AND json_extract(record_json, '$.provenance.import_batch_id') = ?`)
1493
- .all(batch.subjectId, batch.importBatchId);
1494
- if (batch.inputRecords < previousBatch.input_records || previousEvents.some((event) => !incomingIds.has(event.listening_event_id))) {
1495
- throw new Error("Extended archive expansion must preserve every previously imported event");
1496
- }
1497
- ({ insertedTracks, insertedEvents } = insertBundleRecords(bundle, statements));
1498
- this.#database.prepare(`UPDATE import_batches SET member_names_json = ?, input_records = ?,
1499
- earliest_occurred_at = ?, latest_occurred_at = ?,
1500
- inserted_events = inserted_events + ?, duplicate_events = ? - inserted_events - ?,
1501
- inserted_track_refs = inserted_track_refs + ? WHERE import_batch_id = ?`)
1502
- .run(JSON.stringify(batch.memberNames), batch.inputRecords, batch.earliestOccurredAt, batch.latestOccurredAt,
1503
- 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");
1504
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);
1505
1688
  }
1506
- const reconciliationCandidates = preserveExtendedHistoryMatches(bundle, (eventId) =>
1507
- selectCandidateBySuperseding.get(eventId)?.superseded_event_id ??
1508
- selectBySuperseding.get(eventId)?.superseded_event_id);
1509
- for (const candidate of reconciliationCandidates) {
1510
- const existingBySuperseded = selectCandidateBySuperseded.get(
1511
- candidate.supersededEventId,
1512
- )?.superseding_event_id;
1513
- const existingBySuperseding = selectCandidateBySuperseding.get(
1514
- candidate.supersedingEventId,
1515
- )?.superseded_event_id;
1516
- 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(
1517
1720
  candidate.supersededEventId,
1518
- )?.superseding_event_id;
1519
- const resolvedSuperseded = selectBySuperseding.get(
1520
1721
  candidate.supersedingEventId,
1521
- )?.superseded_event_id;
1522
- if (
1523
- (existingBySuperseded &&
1524
- existingBySuperseded !== candidate.supersedingEventId) ||
1525
- (existingBySuperseding &&
1526
- existingBySuperseding !== candidate.supersededEventId) ||
1527
- (resolvedSuperseding &&
1528
- resolvedSuperseding !== candidate.supersedingEventId) ||
1529
- (resolvedSuperseded &&
1530
- resolvedSuperseded !== candidate.supersededEventId)
1531
- ) {
1532
- throw new Error("Listening history reconciliation conflict");
1533
- }
1534
- if (!existingBySuperseded && !existingBySuperseding) {
1535
- insertCandidate.run(
1536
- candidate.supersededEventId,
1537
- candidate.supersedingEventId,
1538
- batch.importBatchId,
1539
- batch.importedAt,
1540
- );
1541
- }
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");
1542
1741
  }
1543
- for (const candidate of selectResolvableCandidates.all()) {
1544
- const supersededEventId = candidate.superseded_event_id;
1545
- const supersedingEventId = candidate.superseding_event_id;
1546
- 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(
1547
1761
  supersededEventId,
1548
- )?.superseding_event_id;
1549
- const existingSuperseded = selectBySuperseding.get(
1550
1762
  supersedingEventId,
1551
- )?.superseded_event_id;
1552
- if (
1553
- (existingSuperseding && existingSuperseding !== supersedingEventId) ||
1554
- (existingSuperseded && existingSuperseded !== supersededEventId)
1555
- ) {
1556
- throw new Error("Listening history reconciliation conflict");
1557
- }
1558
- const eventRow = selectEventRecord.get(supersedingEventId);
1559
- const event = JSON.parse(eventRow.record_json);
1560
- if (
1561
- event.supersedes_listening_event_id !== undefined &&
1562
- event.supersedes_listening_event_id.toLowerCase() !== supersededEventId
1563
- ) {
1564
- throw new Error("Listening history reconciliation conflict");
1565
- }
1566
- if (event.supersedes_listening_event_id === undefined) {
1567
- updateEventRecord.run(
1568
- JSON.stringify({
1569
- ...event,
1570
- supersedes_listening_event_id: supersededEventId,
1571
- }),
1572
- supersedingEventId,
1573
- );
1574
- }
1575
- if (!existingSuperseding && !existingSuperseded) {
1576
- supersededEvents += insertSupersession.run(
1577
- supersededEventId,
1578
- supersedingEventId,
1579
- candidate.import_batch_id,
1580
- batch.importedAt,
1581
- ).changes;
1582
- }
1763
+ candidate.import_batch_id,
1764
+ batch.importedAt,
1765
+ ).changes;
1583
1766
  }
1584
- if (bundle.profileImport) {
1585
- const profile = bundle.profileImport;
1586
- profileAlreadyImported = Boolean(
1587
- existingProfileBatch.get(profile.profileImportId),
1588
- );
1589
- if (!profileAlreadyImported) {
1590
- if (alreadyImported) {
1591
- for (const record of bundle.trackRefs) {
1592
- insertedTracks += statements.insertTrack.run(
1593
- record.track_ref_id,
1594
- record.revision,
1595
- JSON.stringify(record),
1596
- ).changes;
1597
- }
1598
- }
1599
- insertProfileBatch.run(
1600
- profile.profileImportId,
1601
- profile.subjectId,
1602
- profile.sourceKey,
1603
- profile.sourceFormat,
1604
- profile.archiveSha256,
1605
- profile.archiveSizeBytes,
1606
- JSON.stringify(profile.memberNames),
1607
- profile.inputRecords,
1608
- profile.importedAt,
1609
- );
1610
- for (const record of bundle.profileEvidence) {
1611
- insertedProfileEvidence += insertProfileEvidence.run(
1612
- record.profile_evidence_id,
1613
- record.evidence_key,
1614
- record.subject_id,
1615
- record.evidence_kind,
1616
- profile.profileImportId,
1617
- record.observed_at,
1618
- 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,
1619
1779
  JSON.stringify(record),
1620
1780
  ).changes;
1621
1781
  }
1622
- if (insertedProfileEvidence !== profile.inputRecords) {
1623
- throw new Error("Spotify profile evidence import was incomplete");
1624
- }
1625
- updateProfileBatch.run(
1626
- 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,
1627
1800
  profile.profileImportId,
1628
- );
1801
+ record.observed_at,
1802
+ record.provenance.captured_at,
1803
+ JSON.stringify(record),
1804
+ ).changes;
1805
+ }
1806
+ if (insertedProfileEvidence !== profile.inputRecords) {
1807
+ throw new Error("Spotify profile evidence import was incomplete");
1629
1808
  }
1809
+ updateProfileBatch.run(
1810
+ insertedProfileEvidence,
1811
+ profile.profileImportId,
1812
+ );
1630
1813
  }
1631
- mirroredEvents = reconcileScrobbleMirrors(
1632
- this.#database, batch.subjectId, batch.earliestOccurredAt, batch.latestOccurredAt, batch.importedAt,
1633
- );
1634
- this.#database.exec("COMMIT");
1635
- } catch (error) {
1636
- this.#database.exec("ROLLBACK");
1637
- throw error;
1638
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
+ );
1639
1823
 
1640
1824
  return {
1641
1825
  state: "ready",
@@ -1645,16 +1829,20 @@ export class ListeningHistoryStore {
1645
1829
  import_batch_id: batch.importBatchId,
1646
1830
  archive_sha256: batch.archiveSha256,
1647
1831
  input_records: batch.inputRecords,
1832
+ events_with_played_ms: eventsWithPlayedMs,
1648
1833
  inserted_events: insertedEvents,
1649
1834
  duplicate_events: batch.inputRecords - insertedEvents,
1650
1835
  inserted_track_refs: insertedTracks,
1651
1836
  superseded_events: supersededEvents,
1837
+ ...(upgradedListens ? { upgraded_recording_events: upgradedListens } : {}),
1652
1838
  ...(mirroredEvents ? { mirrored_events: mirroredEvents } : {}),
1653
1839
  effective_event_delta: insertedEvents - supersededEvents - mirroredEvents,
1654
1840
  cursor_after_ms: this.sourceCursor(bundle.sourceKey),
1655
1841
  earliest_occurred_at: batch.earliestOccurredAt,
1656
1842
  latest_occurred_at: batch.latestOccurredAt,
1657
- already_imported: alreadyImported,
1843
+ imported_at: importedAt,
1844
+ first_imported_at: previousBatch?.imported_at ?? importedAt,
1845
+ already_imported: Boolean(previousBatch),
1658
1846
  ...(bundle.profileImport
1659
1847
  ? {
1660
1848
  profile_input_records: bundle.profileImport.inputRecords,
@@ -1673,12 +1861,114 @@ export class ListeningHistoryStore {
1673
1861
  }
1674
1862
  : {}),
1675
1863
  profile_effects:
1676
- insertedEvents > 0 || supersededEvents > 0 || insertedProfileEvidence > 0
1864
+ insertedEvents > 0 || supersededEvents > 0 || insertedProfileEvidence > 0 || upgradedListens > 0
1677
1865
  ? "updated"
1678
1866
  : "unchanged",
1679
1867
  };
1680
1868
  }
1681
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
+
1682
1972
  recentEvents({ subjectId, limit = 20 } = {}) {
1683
1973
  if (this.#closed) throw new Error("Listening history store is closed");
1684
1974
  if (typeof subjectId !== "string" || !subjectId.trim()) {
@@ -1706,7 +1996,7 @@ export class ListeningHistoryStore {
1706
1996
  .map((row) => JSON.parse(row.record_json));
1707
1997
  }
1708
1998
 
1709
- #profileProjection({ subjectId, maxItems }) {
1999
+ #profileProjection({ subjectId, maxItems, readingThrough }) {
1710
2000
  if (this.#closed) throw new Error("Listening history store is closed");
1711
2001
  if (!isUuid(subjectId)) {
1712
2002
  throw new TypeError("A valid listening profile subject ID is required");
@@ -1836,39 +2126,45 @@ export class ListeningHistoryStore {
1836
2126
  .all(normalizedSubjectId)
1837
2127
  .map((row) => JSON.parse(row.record_json));
1838
2128
  const { rows, adopted } = markMoondogStartedPlays(eventRows, this.#suggestionsForMatching());
1839
- return {
1840
- ...projectListeningProfile({
1841
- subjectId: normalizedSubjectId,
1842
- eventRows: rows,
1843
- profileEvidence,
1844
- tasteEvents,
1845
- maxItems,
1846
- adoptedSuggestionIds: adopted,
1847
- }),
2129
+ const projected = projectListeningProfile({
2130
+ subjectId: normalizedSubjectId,
2131
+ eventRows: rows,
2132
+ profileEvidence,
2133
+ tasteEvents,
2134
+ maxItems,
1848
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
+ ) } : {}),
1849
2142
  };
1850
2143
  }
1851
2144
 
1852
2145
  #suggestionsForMatching() {
1853
- 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,
1854
2147
  requested_at FROM moondog_suggestions ORDER BY requested_at, suggestion_id`).all();
1855
2148
  }
1856
2149
 
1857
- /** Records what Moondog itself queued or played. Only accepted host writes belong here. */
1858
- recordMoondogSuggestions({ entries } = {}) {
2150
+ /** Records songs Moondog saved in a playlist, queued or played, from accepted host writes. */
2151
+ recordMoondogSuggestions({ entries, includeIds = false } = {}) {
1859
2152
  if (this.#closed) throw new Error("Listening history store is closed");
1860
2153
  if (!Array.isArray(entries) || entries.length > 50) throw new TypeError("Moondog suggestions are invalid");
1861
2154
  const insert = this.#database.prepare(`INSERT INTO moondog_suggestions
1862
2155
  (suggestion_id, service, action, provider_track_id, isrc, track_key, release_key, title, artist_credit, requested_at, mix_slot)
1863
2156
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
1864
2157
  let recorded = 0;
2158
+ const suggestionIds = includeIds === true ? Array(entries.length).fill(null) : null;
1865
2159
  this.#database.exec("BEGIN IMMEDIATE");
1866
2160
  try {
1867
- for (const value of entries) {
1868
- const entry = suggestionEntry(value);
2161
+ for (const [index, value] of entries.entries()) {
2162
+ const entry = suggestionEntry(value ?? {});
1869
2163
  if (!entry || !/^[a-z][a-z0-9_.]{1,63}$/u.test(entry.action ?? "") || !Number.isFinite(Date.parse(entry.requested_at))) continue;
1870
- 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,
1871
2166
  entry.title, entry.artist_credit, new Date(entry.requested_at).toISOString(), entry.mix_slot);
2167
+ if (suggestionIds) suggestionIds[index] = id;
1872
2168
  recorded += 1;
1873
2169
  }
1874
2170
  this.#database.exec("COMMIT");
@@ -1877,31 +2173,91 @@ export class ListeningHistoryStore {
1877
2173
  throw error;
1878
2174
  }
1879
2175
  this.#ledgerChanges += recorded;
1880
- return { recorded };
2176
+ return suggestionIds ? { recorded, suggestionIds } : { recorded };
2177
+ }
2178
+
2179
+ /**
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.
2182
+ */
2183
+ recordSuggestionOutcome({ service, suggestionId, providerTrackId = null, title, artists, artistCredit, outcome, heardMs, startedBy, at } = {}) {
2184
+ if (this.#closed) throw new Error("Listening history store is closed");
2185
+ if (!["completed", "skipped", "partial"].includes(outcome) || !Number.isSafeInteger(heardMs) || heardMs < 0) {
2186
+ throw new TypeError("Suggestion outcome is invalid");
2187
+ }
2188
+ const observedMs = Date.parse(at);
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 };
2206
+ const entry = suggestionEntry({ service, action: "lookup", providerTrackId, title, artists, artistCredit, requestedAt: at });
2207
+ if (!entry) return { recorded: false };
2208
+ const identities = new Set(suggestionIdentities(entry).filter((identity) => !identity.startsWith("release:")));
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();
2215
+ const candidates = this.#database.prepare(`SELECT suggestion_id, provider_track_id, isrc, track_key, release_key, title, artist_credit,
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);
2228
+ return { recorded: inserted.changes === 1, suggestion_id: match.suggestion_id };
1881
2229
  }
1882
2230
 
1883
2231
  /**
1884
2232
  * Moondog's earlier suggestions of each track, matched as stored plays are: the same provider
1885
- * track, ISRC or song. Adopted means the listener later played it again on their own.
2233
+ * track, ISRC or song. Adopted means the listener later played it again on their own; outcomes
2234
+ * count how the plays Moondog started went.
1886
2235
  */
1887
2236
  moondogSuggestionHistory({ subjectId, tracks } = {}) {
1888
2237
  if (!Array.isArray(tracks)) throw new TypeError("Suggestion history tracks are invalid");
1889
2238
  const suggestions = this.#suggestionsForMatching();
1890
2239
  if (!suggestions.length) return tracks.map(() => null);
1891
2240
  const { adopted } = this.#listeningSnapshot(subjectId);
1892
- const byIdentity = new Map();
1893
- for (const suggestion of suggestions) {
1894
- for (const identity of suggestionIdentities(suggestion)) {
1895
- byIdentity.set(identity, [...(byIdentity.get(identity) ?? []), suggestion]);
1896
- }
2241
+ const byIdentity = suggestionsByIdentity(suggestions);
2242
+ const outcomes = new Map();
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);
1897
2247
  }
1898
2248
  return tracks.map((track) => {
1899
- const entry = suggestionEntry({ service: "spotify", action: "lookup", ...track });
2249
+ const entry = lookupSuggestion(track);
1900
2250
  const matches = new Set(entry ? suggestionIdentities(entry).flatMap((identity) => byIdentity.get(identity) ?? []) : []);
1901
2251
  if (!matches.size) return null;
1902
2252
  const last = [...matches].reduce((latest, item) => item.requested_at > latest ? item.requested_at : latest, "");
2253
+ const heard = { completed: 0, skipped: 0, partial: 0 };
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
+ }
1903
2258
  return { times: matches.size, last_suggested_at: last.slice(0, 10),
1904
- adopted: [...matches].some((item) => adopted.has(item.suggestion_id)) };
2259
+ adopted: [...matches].some((item) => adopted.has(item.suggestion_id)),
2260
+ ...(heard.completed + heard.skipped + heard.partial ? { outcomes: heard } : {}) };
1905
2261
  });
1906
2262
  }
1907
2263
 
@@ -1909,15 +2265,31 @@ export class ListeningHistoryStore {
1909
2265
  listeningMix({ subjectId, tracks } = {}) {
1910
2266
  if (!Array.isArray(tracks)) throw new TypeError("Listening mix tracks are invalid");
1911
2267
  const { familiarity } = this.#listeningSnapshot(subjectId);
1912
- 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
+ });
1913
2281
  }
1914
2282
 
1915
2283
  // One projection with a single item per list serves the status, the Avoids, the catalog, the
1916
2284
  // mix and the suggestion history until the listening data changes. Callers copy what they return.
1917
- #sharedProjection(subjectId) {
2285
+ #sharedProjection(subjectId, readingThrough) {
1918
2286
  const version = `${subjectId}:${this.listeningDataVersion()}`;
1919
- if (this.#projection?.version !== version) {
1920
- 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 }) };
1921
2293
  }
1922
2294
  return this.#projection.value;
1923
2295
  }
@@ -1995,8 +2367,8 @@ export class ListeningHistoryStore {
1995
2367
  : this.#profileProjection({ subjectId, maxItems })).summary);
1996
2368
  }
1997
2369
 
1998
- profileCatalog({ subjectId } = {}) {
1999
- const projected = this.#sharedProjection(subjectId);
2370
+ profileCatalog({ subjectId, readingThrough } = {}) {
2371
+ const projected = this.#sharedProjection(subjectId, readingThrough);
2000
2372
  const normalizedSubjectId = subjectId.toLowerCase();
2001
2373
  const imports = this.#database.prepare(`SELECT source_format AS format, data_scope AS scope,
2002
2374
  SUM(input_records) AS input_records, MIN(earliest_occurred_at) AS earliest,
@@ -2010,6 +2382,8 @@ export class ListeningHistoryStore {
2010
2382
  stored_listening_events: stored,
2011
2383
  superseded_listening_events: stored - projected.summary.coverage.effective_listening_events },
2012
2384
  sources: imports,
2385
+ ...(readingThrough !== undefined ? { historyDigests: projected.historyDigests } : {}),
2386
+ rankingWindows: projected.rankingWindows,
2013
2387
  context: {
2014
2388
  reference_date: projected.summary.listening_behavior.context.reference_date,
2015
2389
  recent_window_days: projected.summary.listening_behavior.context.recent_window_days,
@@ -2030,31 +2404,30 @@ export class ListeningHistoryStore {
2030
2404
  if (!isUuid(subjectId)) throw new TypeError("A valid profile subject is required");
2031
2405
  const today = new Date(now);
2032
2406
  const start = new Date(today);
2033
- start.setHours(0, 0, 0, 0);
2034
2407
  start.setDate(start.getDate() - (days - 1));
2035
- const from = start.toISOString();
2036
- const effective = `e.subject_id = ? AND e.occurred_at >= ?
2037
- AND NOT EXISTS (SELECT 1 FROM listening_event_supersessions s WHERE s.superseded_event_id = e.listening_event_id)
2038
- AND NOT EXISTS (SELECT 1 FROM listening_event_mirrors m WHERE m.mirror_event_id = e.listening_event_id)`;
2039
- 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 < ?`;
2040
2413
  // Plays Moondog started are not the listener's own attention.
2041
2414
  const suggestions = this.#suggestionsForMatching()
2042
- .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());
2043
2416
  const started = suggestions.length === 0 ? [] : markMoondogStartedPlays(this.#database.prepare(`SELECT
2044
2417
  e.listening_event_id, e.record_json AS event_json, t.record_json AS track_json FROM listening_events e
2045
2418
  JOIN track_refs t ON t.track_ref_id = e.track_ref_id AND t.revision = e.track_ref_revision WHERE ${effective}`)
2046
- .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) })),
2047
2420
  suggestions).rows.filter((row) => row.moondog_suggestion_id).map((row) => row.id);
2048
2421
  const own = `${effective} AND e.listening_event_id NOT IN (SELECT value FROM json_each(?))`;
2049
2422
  const plays = this.#database.prepare(`SELECT COUNT(*) AS plays FROM listening_events e WHERE ${own}`)
2050
- .get(subject, from, JSON.stringify(started)).plays;
2423
+ .get(...range, JSON.stringify(started)).plays;
2051
2424
  const artists = this.#database.prepare(`SELECT json_extract(a.value, '$.name') AS name, COUNT(*) AS plays,
2052
2425
  MAX(e.occurred_at) AS last_played_at
2053
2426
  FROM listening_events e
2054
2427
  JOIN track_refs t ON t.track_ref_id = e.track_ref_id AND t.revision = e.track_ref_revision
2055
2428
  JOIN json_each(t.record_json, '$.artist_credits') a
2056
2429
  WHERE ${own} AND name IS NOT NULL
2057
- 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);
2058
2431
  return structuredClone({ from_date: localDate(start), through_date: localDate(today), plays,
2059
2432
  ...(started.length ? { moondog_started_plays: started.length } : {}), top_artists: artists });
2060
2433
  }
@@ -2069,18 +2442,15 @@ export class ListeningHistoryStore {
2069
2442
  const subject = subjectId.toLowerCase();
2070
2443
  const version = `${this.listeningDataVersion()}:${subject}:${artists}`;
2071
2444
  if (this.#listeningDays?.version === version) return structuredClone(this.#listeningDays.value);
2072
- const effective = `e.subject_id = ?
2073
- AND NOT EXISTS (SELECT 1 FROM listening_event_supersessions s WHERE s.superseded_event_id = e.listening_event_id)
2074
- AND NOT EXISTS (SELECT 1 FROM listening_event_mirrors m WHERE m.mirror_event_id = e.listening_event_id)`;
2075
2445
  const suggestions = this.#suggestionsForMatching();
2076
2446
  const since = suggestions.length ? new Date(Date.parse(suggestions[0].requested_at) - SUGGESTION_WINDOW.beforeMs).toISOString() : null;
2077
2447
  const started = !since ? [] : markMoondogStartedPlays(this.#database.prepare(`SELECT
2078
2448
  e.listening_event_id, e.record_json AS event_json, t.record_json AS track_json FROM listening_events e
2079
2449
  JOIN track_refs t ON t.track_ref_id = e.track_ref_id AND t.revision = e.track_ref_revision
2080
- WHERE ${effective} AND e.occurred_at >= ?`)
2450
+ WHERE ${attentionEvents} AND e.occurred_at >= ?`)
2081
2451
  .all(subject, since).map((row) => ({ id: row.listening_event_id, event: JSON.parse(row.event_json), track: JSON.parse(row.track_json) })),
2082
2452
  suggestions).rows.filter((row) => row.moondog_suggestion_id).map((row) => row.id);
2083
- 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(?))`;
2084
2454
  const left = JSON.stringify(started);
2085
2455
  const pairs = (rows) => rows.map((row) => [row.day, row.plays]);
2086
2456
  const days = this.#database.prepare(`SELECT date(e.occurred_at, 'localtime') AS day, COUNT(*) AS plays
@@ -2214,12 +2584,23 @@ export class ListeningHistoryStore {
2214
2584
  .get(subjectId.toLowerCase()).latest;
2215
2585
  const latestMs = Date.parse(latest ?? "");
2216
2586
  const suggestions = Number.isFinite(latestMs) ? this.#database.prepare(`SELECT suggestion_id, provider_track_id, isrc, track_key,
2217
- release_key, title, artist_credit, requested_at FROM moondog_suggestions WHERE requested_at <= ? ORDER BY suggestion_id`)
2218
- .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) : [];
2219
2589
  if (suggestions.length) digest.update("moondog_suggestions\0").update(JSON.stringify(suggestions));
2220
2590
  return digest.digest("hex");
2221
2591
  }
2222
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
+
2223
2604
  rediscoveryCandidates({ subjectId, limit = 6 } = {}) {
2224
2605
  if (!Number.isInteger(limit) || limit < 1 || limit > 12) {
2225
2606
  throw new TypeError("Listening rediscovery limit is invalid");
@@ -2659,14 +3040,30 @@ function databaseConstructor() {
2659
3040
  return databaseConstructorPromise;
2660
3041
  }
2661
3042
 
2662
- async function initializeListeningHistoryDatabase(
2663
- database,
2664
- { journalMode, filePath = null },
2665
- ) {
2666
- database.exec("PRAGMA busy_timeout = 5000");
2667
- database.exec(`PRAGMA journal_mode = ${journalMode}`);
2668
- database.exec("PRAGMA foreign_keys = ON");
2669
- 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) {
2670
3067
  const currentVersion = database.prepare("PRAGMA user_version").get()
2671
3068
  .user_version;
2672
3069
  if (
@@ -2676,11 +3073,25 @@ async function initializeListeningHistoryDatabase(
2676
3073
  ) {
2677
3074
  throw new Error("Listening history database schema is incompatible");
2678
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);
2679
3088
  const recordsGaps = database.prepare(
2680
3089
  "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'listening_coverage_gaps'",
2681
3090
  ).get();
2682
3091
  database.exec(schema);
2683
3092
  if (!recordsGaps) recordEarlierRecentSyncGaps(database);
3093
+ repairEarlierMusicAppMirrors(database);
3094
+ recordEarlierImportReceipts(database);
2684
3095
  if (currentVersion < LISTENING_HISTORY_SCHEMA_VERSION) {
2685
3096
  database.exec(
2686
3097
  `PRAGMA user_version = ${LISTENING_HISTORY_SCHEMA_VERSION}`,
@@ -2705,24 +3116,234 @@ export async function openEphemeralListeningHistoryStore() {
2705
3116
  }
2706
3117
  }
2707
3118
 
2708
- export async function openListeningHistoryStore({
2709
- databasePath = defaultListeningHistoryPath,
2710
- environment = process.env,
2711
- } = {}) {
2712
- const resolvedPath =
2713
- databasePath === defaultListeningHistoryPath
2714
- ? resolveListeningHistoryPath(environment)
2715
- : databasePath;
2716
- 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);
2717
3338
  await mkdir(parent, { recursive: true, mode: 0o700 });
2718
3339
  if (process.platform !== "win32") await chmod(parent, 0o700);
2719
3340
 
2720
3341
  const DatabaseSync = await databaseConstructor();
2721
- const database = new DatabaseSync(path.resolve(resolvedPath));
3342
+ const database = new DatabaseSync(resolvedPath);
2722
3343
  try {
2723
3344
  await initializeListeningHistoryDatabase(database, {
2724
3345
  journalMode: "WAL",
2725
- filePath: path.resolve(resolvedPath),
3346
+ filePath: resolvedPath,
2726
3347
  });
2727
3348
  return new ListeningHistoryStore(database);
2728
3349
  } catch (error) {