@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
@@ -69,6 +69,7 @@ export async function runMemoryReflection({
69
69
  const reflected = await runtime.reflect({
70
70
  episodes: run.episodes,
71
71
  activeMemories: run.active_memories,
72
+ activeSkills: run.active_skills ?? [],
72
73
  });
73
74
  return application.completeMemoryReflection({
74
75
  runId: run.run_id,
@@ -85,3 +86,21 @@ export async function runMemoryReflection({
85
86
  throw error;
86
87
  }
87
88
  }
89
+
90
+ // The room reflects without being asked, on its listening upkeep. A backlog drains one batch at
91
+ // a time, one each upkeep; after that, reflection waits a few hours between runs, and a failed run
92
+ // waits as long before the next try.
93
+ export const REFLECTION_CADENCE = Object.freeze({ backlogGapMs: 25 * 60_000, gapMs: 6 * 3_600_000 });
94
+
95
+ /** Reflect on completed conversations when enough time has passed since the last run. */
96
+ export async function runMemoryReflectionIfDue({ application, now = Date.now(), ...options } = {}) {
97
+ if (!application?.memoryStore) return { state: "unavailable" };
98
+ const status = application.memoryReflectionStatus();
99
+ if (status.state === "running") return { state: "busy" };
100
+ if (!status.pending_episodes) return { state: "no_work" };
101
+ const last = status.last_run;
102
+ const backlog = status.pending_episodes >= MAX_REFLECTION_EPISODES && last?.status !== "failed";
103
+ const since = now - Date.parse(last?.started_at ?? "");
104
+ if (since < (backlog ? REFLECTION_CADENCE.backlogGapMs : REFLECTION_CADENCE.gapMs)) return { state: "waiting" };
105
+ return runMemoryReflection({ ...options, application, trigger: "schedule" });
106
+ }
@@ -1,19 +1,73 @@
1
1
  import { mkdir } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
 
4
- import { resolveAppleMusicImportsRoot } from "../core/apple-library-source-status.mjs";
4
+ import { listAppleLibraryComparisonSources, resolveAppleMusicImportsRoot } from "../core/apple-library-source-status.mjs";
5
5
  import { resolveAppleMusicProjectionPath } from "../core/apple-projection-domain-services.mjs";
6
6
  import { writeAppleMusicImportBatch, rebuildAppleMusicSqliteProjection } from "../importers/apple-music-library/index.mjs";
7
+ import { verifySavedAppleMusicBatch } from "../importers/apple-music-library/import-batch.mjs";
8
+
9
+ function snapshotComparison(status, previous = null, firstImportedAt = null) {
10
+ return {
11
+ state: "apple-library", status, firstImportedAt,
12
+ previousObservedAt: previous?.captured_at ?? null,
13
+ previousTrackCount: previous?.trackCount ?? null,
14
+ };
15
+ }
16
+
17
+ export async function compareAppleLibraryImport(bundle, { environment = process.env } = {}) {
18
+ const manifest = bundle?.manifest;
19
+ if (manifest?.source?.format !== "apple_music_library_xml_plist") return snapshotComparison("unavailable");
20
+ let sources;
21
+ try {
22
+ sources = await listAppleLibraryComparisonSources(resolveAppleMusicImportsRoot(environment));
23
+ } catch {
24
+ return snapshotComparison("unavailable");
25
+ }
26
+ const { valid, invalidBatches, error } = sources;
27
+ if (error || invalidBatches || valid.some(item => item.subject_id !== manifest.subject_id)) {
28
+ return snapshotComparison("unavailable");
29
+ }
30
+ if (!valid.length) return snapshotComparison("first");
31
+ const same = valid.find(item => item.batchId === manifest.import_batch_id);
32
+ if (same) {
33
+ if (same.sourceHash !== manifest.source.sha256) return snapshotComparison("unavailable");
34
+ if (manifest.warning_counts.non_music_media_excluded) {
35
+ try {
36
+ const verified = await verifySavedAppleMusicBatch(bundle, path.join(resolveAppleMusicImportsRoot(environment), same.batchId));
37
+ if (verified.legacyUnclassified) return snapshotComparison("legacy-unclassified", same, verified.firstImportedAt);
38
+ } catch {
39
+ return snapshotComparison("unavailable");
40
+ }
41
+ }
42
+ return snapshotComparison("same", same, same.first_imported_at);
43
+ }
44
+
45
+ const sameLibrary = valid.filter(item => item.libraryFingerprint === manifest.source.library_fingerprint_sha256);
46
+ const latest = sameLibrary.at(-1);
47
+ if (!latest || sameLibrary.some(item => item.captured_at === latest.captured_at && item.trackCount !== latest.trackCount)) {
48
+ return snapshotComparison("unavailable");
49
+ }
50
+ return snapshotComparison("changed", latest);
51
+ }
7
52
 
8
53
  export async function persistAppleLibraryImport(bundle, { environment = process.env } = {}) {
9
54
  const outputRoot = resolveAppleMusicImportsRoot(environment);
10
55
  const boundaryRoot = path.dirname(outputRoot);
11
- await mkdir(boundaryRoot, { recursive: true, mode: 0o700 });
56
+ if (bundle.trackRefs.length || !bundle.manifest.warning_counts.non_music_media_excluded) {
57
+ await mkdir(boundaryRoot, { recursive: true, mode: 0o700 });
58
+ }
12
59
  const result = await writeAppleMusicImportBatch(bundle, { outputRoot, boundaryRoot });
60
+ const importedAt = result.status === "written" ? result.firstImportedAt : new Date().toISOString();
13
61
  return {
14
62
  provider: "apple-music-library",
15
63
  already_imported: result.status === "unchanged",
16
64
  library_tracks: result.manifest.counts.track_refs,
65
+ ...(result.legacyUnclassified ? { legacy_unclassified: true } : {}),
66
+ ...(result.manifest.warning_counts.non_music_media_excluded ? { excluded_non_music: result.manifest.warning_counts.non_music_media_excluded } : {}),
67
+ imported_at: importedAt,
68
+ ...(result.firstImportedAt ? { first_imported_at: result.firstImportedAt } : {}),
69
+ earliest_occurred_at: null,
70
+ latest_occurred_at: null,
17
71
  };
18
72
  }
19
73
 
@@ -3,12 +3,14 @@ import { homedir } from "node:os";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
 
6
- import { readSpotifyHistoryArchive } from "../integrations/spotify/history-archive.mjs";
7
- import { readListenBrainzHistoryFile } from "../integrations/listenbrainz/history-file.mjs";
6
+ import { importHistoryStrings } from "../i18n/import-history.mjs";
7
+ import { listZipMembers } from "../importers/zip-reader.mjs";
8
+ import { isSpotifyHistoryMember, readSpotifyHistoryArchive } from "../integrations/spotify/history-archive.mjs";
9
+ import { readHistoryJsonSource, readListenBrainzHistoryFile } from "../integrations/listenbrainz/history-file.mjs";
8
10
  import { projectSpotifyRecentActivity } from "../integrations/spotify/recent-activity.mjs";
9
11
  import { projectSpotifyLibrarySnapshot } from "../integrations/spotify/library-snapshot.mjs";
10
12
  import { buildAppleMusicLibraryImport } from "../importers/apple-music-library/index.mjs";
11
- import { readYouTubeMusicTakeout } from "../integrations/youtube-music/takeout.mjs";
13
+ import { isYouTubeMusicMember, readYouTubeMusicTakeout } from "../integrations/youtube-music/takeout.mjs";
12
14
  import { readPublicPlaylist } from "../integrations/public-playlists.mjs";
13
15
  import { readLastfmHistory } from "../integrations/lastfm/history.mjs";
14
16
 
@@ -23,6 +25,7 @@ export function prepareSpotifyQuickImport({ page, librarySnapshot = null, librar
23
25
  const dates = bundle.listening_events.map((event) => event.occurred_at).sort();
24
26
  return {
25
27
  provider: "spotify-quick",
28
+ subjectId: subjectId.toLowerCase(),
26
29
  bundle,
27
30
  libraryBundle: library?.bundle ?? null,
28
31
  preview: {
@@ -44,18 +47,9 @@ export function prepareSpotifyQuickImport({ page, librarySnapshot = null, librar
44
47
  };
45
48
  }
46
49
 
47
- /** Save both parts of an inspected quick import; returns one combined receipt. */
48
- // Both writes are idempotent, so retrying after a partial failure is safe.
49
- export function commitSpotifyQuickImport(store, prepared) {
50
- const library = prepared.libraryBundle ? store.ingestImport(prepared.libraryBundle) : null;
51
- const recent = store.ingest(prepared.bundle);
52
- if (!library) return { ...recent, provider: "spotify-quick" };
53
- return {
54
- ...recent, provider: "spotify-quick",
55
- inserted_track_refs: (recent.inserted_track_refs ?? 0) + (library.inserted_track_refs ?? 0),
56
- inserted_profile_evidence: library.inserted_profile_evidence ?? 0,
57
- library_already_imported: library.already_imported === true,
58
- };
50
+ /** Save the inspected recent plays and optional collection with one receipt for this confirmation. */
51
+ export function commitSpotifyQuickImport(store, { bundle, libraryBundle, subjectId }) {
52
+ return store.ingestSpotifyQuick({ recentBundle: bundle, libraryBundle, subjectId });
59
53
  }
60
54
 
61
55
  function fail(code, message) {
@@ -117,13 +111,19 @@ function literalPath(input) {
117
111
  return path.resolve(decoded);
118
112
  }
119
113
 
114
+ // QQ and NetEase share text can contain a link after the playlist's name.
115
+ export function isSharedPlaylistInput(input) {
116
+ return /https?:\/\//iu.test(input ?? "") && !String(input).startsWith("file:");
117
+ }
118
+
120
119
  export async function prepareHistoryImport({ filePath, subjectId, provider: selectedProvider, capturedAt = new Date().toISOString(), fetchImpl, onProgress, signal } = {}) {
120
+ signal?.throwIfAborted();
121
121
  // Last.fm is read by username (or profile link) rather than from a file.
122
122
  if (selectedProvider === "lastfm") {
123
123
  return readLastfmHistory({ username: filePath, subjectId, capturedAt, onProgress, signal, ...(fetchImpl ? { fetchImpl } : {}) });
124
124
  }
125
- if (/https?:\/\//iu.test(filePath ?? "") && !String(filePath).startsWith("file:")) {
126
- return readPublicPlaylist({ input: filePath, subjectId, capturedAt, provider: selectedProvider, fetchImpl });
125
+ if (isSharedPlaylistInput(filePath)) {
126
+ return readPublicPlaylist({ input: filePath, subjectId, capturedAt, provider: selectedProvider, fetchImpl, signal });
127
127
  }
128
128
  const resolvedPath = literalPath(filePath);
129
129
  let file;
@@ -140,9 +140,20 @@ export async function prepareHistoryImport({ filePath, subjectId, provider: sele
140
140
  }
141
141
  if (!file.isFile()) fail("history_import_file_invalid", "Choose a regular music export file.");
142
142
  const extension = path.extname(resolvedPath).toLowerCase();
143
- if (selectedProvider === "youtube_music" || extension === ".csv" || /^(?:watch-history|takeout)[-.]/iu.test(path.basename(resolvedPath))) {
144
- if (![".csv", ".json", ".zip"].includes(extension)) fail("history_import_format_unsupported", "Choose your Takeout ZIP, music-library-songs.csv or watch-history.json. For history, select JSON in Takeout instead of HTML.");
145
- return readYouTubeMusicTakeout({ filePath: resolvedPath, subjectId, capturedAt });
143
+ const options = { filePath: resolvedPath, subjectId, capturedAt, onProgress };
144
+ let zipMembers;
145
+ if (extension === ".zip") {
146
+ try { zipMembers = await listZipMembers(resolvedPath); }
147
+ catch { fail("history_import_zip_unreadable", "This ZIP could not be read safely. Choose the original downloaded ZIP."); }
148
+ const spotify = zipMembers.some(isSpotifyHistoryMember);
149
+ const youtube = zipMembers.some(isYouTubeMusicMember);
150
+ if (spotify && youtube) fail("history_import_zip_ambiguous", "This ZIP contains both Spotify and YouTube Music files. Choose each original export separately.");
151
+ if (!spotify && !youtube) fail("history_import_zip_unsupported", "This ZIP contains no supported Spotify history or YouTube Music Takeout files. Choose the original music export.");
152
+ if (youtube) return readYouTubeMusicTakeout(options);
153
+ } else if (selectedProvider === "youtube_music" || extension === ".csv" ||
154
+ (![".xml", ".json"].includes(extension) && /^(?:watch-history|takeout)[-.]/iu.test(path.basename(resolvedPath)))) {
155
+ if (![".csv", ".json"].includes(extension)) fail("history_import_format_unsupported", "Choose your Takeout ZIP, music-library-songs.csv or watch-history.json. For history, select JSON in Takeout instead of HTML.");
156
+ return readYouTubeMusicTakeout(options);
146
157
  }
147
158
  if (extension === ".xml") {
148
159
  const bundle = await buildAppleMusicLibraryImport(resolvedPath, { subjectId });
@@ -155,8 +166,10 @@ export async function prepareHistoryImport({ filePath, subjectId, provider: sele
155
166
  sourceLabel: "Apple Music library",
156
167
  fileName: path.basename(resolvedPath),
157
168
  tracks: bundle.trackRefs.length,
169
+ ...(bundle.manifest.warning_counts.non_music_media_excluded ? { excludedNonMusic: bundle.manifest.warning_counts.non_music_media_excluded } : {}),
158
170
  capturedAt: bundle.manifest.source.captured_at,
159
- scopeNote: "Your library with loves, ratings, play counts and when you last played each song. It doesn't list every play.",
171
+ tracksWithLastPlayedAt: bundle.trackSnapshots.filter(snapshot => snapshot.aggregate_state.last_played_at).length,
172
+ scopeNote: "Apple Music exports can include favorites, ratings and play counts. They do not list individual plays.",
160
173
  },
161
174
  };
162
175
  }
@@ -164,11 +177,26 @@ export async function prepareHistoryImport({ filePath, subjectId, provider: sele
164
177
  fail("history_import_format_unsupported", "This format is not supported. Choose a Spotify history ZIP, Apple Music library XML, YouTube Music Takeout ZIP/CSV/JSON or saved ListenBrainz JSON.");
165
178
  }
166
179
  const provider = extension === ".zip" ? "spotify" : "listenbrainz";
180
+ let jsonSource;
181
+ if (extension === ".json") {
182
+ if (selectedProvider === "spotify") fail("history_import_json_unsupported", "For Spotify, choose the original ZIP instead of an extracted JSON file.");
183
+ if (selectedProvider === "apple") fail("history_import_format_unsupported", "Choose your exported Apple Music library XML file.");
184
+ if (!selectedProvider) {
185
+ // Takeout uses an array and ListenBrainz uses an object. Each reader validates the contents.
186
+ jsonSource = await readHistoryJsonSource(resolvedPath);
187
+ if (jsonSource.text.trimStart().startsWith("[")) {
188
+ try { return await readYouTubeMusicTakeout(options, jsonSource); }
189
+ catch (error) {
190
+ fail("history_import_json_unsupported", `${error.message} If this is a Spotify export, choose the original ZIP instead of an extracted JSON file.`);
191
+ }
192
+ }
193
+ }
194
+ }
167
195
  let bundle;
168
196
  try {
169
197
  bundle = provider === "spotify"
170
- ? await readSpotifyHistoryArchive({ archivePath: resolvedPath, subjectId, capturedAt })
171
- : await readListenBrainzHistoryFile({ filePath: resolvedPath, subjectId, capturedAt });
198
+ ? await readSpotifyHistoryArchive({ archivePath: resolvedPath, subjectId, capturedAt, onProgress }, zipMembers)
199
+ : await readListenBrainzHistoryFile(options, jsonSource);
172
200
  } catch (error) {
173
201
  if (provider === "listenbrainz" && error.code === "listenbrainz_history_invalid") {
174
202
  error.message += " If this is a Spotify export, choose the original ZIP instead of an extracted JSON file.";
@@ -176,6 +204,7 @@ export async function prepareHistoryImport({ filePath, subjectId, provider: sele
176
204
  throw error;
177
205
  }
178
206
  const extended = bundle.import_batch.data_scope === "lifetime_extended_streaming_history";
207
+ const eventsWithPlayedMs = bundle.listening_events.filter(event => Number.isSafeInteger(event.played_ms)).length;
179
208
  return {
180
209
  provider,
181
210
  bundle,
@@ -189,13 +218,15 @@ export async function prepareHistoryImport({ filePath, subjectId, provider: sele
189
218
  tracks: bundle.track_refs.length,
190
219
  earliestListeningAt: bundle.import_batch.earliest_occurred_at,
191
220
  latestListeningAt: bundle.import_batch.latest_occurred_at,
192
- eventsWithPlayedMs: bundle.listening_events.filter((event) => Number.isSafeInteger(event.played_ms)).length,
221
+ eventsWithPlayedMs,
222
+ ...(extended ? { excludedNonMusic: bundle.excluded_records.non_music, unidentifiedEntries: bundle.excluded_records.unidentified } : {}),
193
223
  profileEvidence: bundle.profile_evidence?.length ?? 0,
194
224
  scopeNote: provider === "listenbrainz"
195
- ? "Your saved listens. Some don't say how long you listened, so they count as plays without minutes."
225
+ ? (eventsWithPlayedMs < bundle.listening_events.length
226
+ ? "Your saved listens. Some don't say how long you listened, so they count as plays without minutes." : "")
196
227
  : extended
197
- ? "Every play in this file, with how long you listened and how each song started and ended."
198
- : "Your plays from the past year, plus your library and playlists. For older plays and listening time, use Extended streaming history.",
228
+ ? importHistoryStrings("en")[bundle.listening_events.length ? "extendedMusic" : "noExtendedMusic"]
229
+ : "Account Data includes recent plays and can include saved music and playlists. Extended streaming history can cover earlier years and includes more playback details.",
199
230
  },
200
231
  };
201
232
  }
@@ -204,10 +204,8 @@ export function recordListenerChoice(store, {
204
204
  if (stance !== "retract") {
205
205
  return store.recordListenerCorrection({ subjectId, entityType, label, artistCredit, stance, occurredAt, recordedAt: occurredAt });
206
206
  }
207
- const key = (value) => typeof value === "string" ? normalizedIdentity(value.replace(/\s+/gu, " ").trim()) : "";
208
- const active = store.listListenerCorrections({ subjectId, limit: 100 }).find((choice) =>
209
- choice.entity_type === entityType && key(choice.label) === key(label) &&
210
- (entityType !== "track" || key(choice.artist_credit) === key(artistCredit)));
207
+ const { targetKey } = correctionTarget({ entityType, label, artistCredit });
208
+ const [active] = store.listListenerCorrections({ subjectId, targetKey, limit: 1 });
211
209
  if (!active) return { state: "not_found", entity_type: entityType, label };
212
210
  return {
213
211
  ...store.retractListenerCorrection({ subjectId, correctionId: active.correction_id, occurredAt, recordedAt: occurredAt }),