@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,10 +1,12 @@
1
1
  import { createHash } from "node:crypto";
2
2
 
3
3
  import { avoidKey } from "../core/listener-avoids.mjs";
4
- import { recordedShare } from "./recorded-measures.mjs";
4
+ import { rankingTimeCoverage, recordedShare } from "./recorded-measures.mjs";
5
5
 
6
6
  export const LISTENER_PROFILE_ANALYSIS_VERSION = "listener-profile/2";
7
- export const LISTENER_PROFILE_SYNTHESIS_VERSION = "listener-synthesis/5";
7
+ // Bump this whenever the same stored data can give a different input digest or dossier. An older
8
+ // Moondog leaves a reading with a higher synthesis number to the version that wrote it.
9
+ export const LISTENER_PROFILE_SYNTHESIS_VERSION = "listener-synthesis/6";
8
10
  // A saved reading is current only after its whole-profile check has run.
9
11
  export const CHECKED_PROFILE_STATES = new Set(["passed", "revised", "flagged"]);
10
12
 
@@ -17,20 +19,19 @@ const DUPLICATED_PROVIDER_KINDS = new Set([
17
19
 
18
20
  const RANKED_LISTENING_SECTIONS = new Set(["history_artists", "history_tracks", "recent_artists", "recent_tracks"]);
19
21
  const PLAY_COUNT_SECTIONS = new Set([...RANKED_LISTENING_SECTIONS, "history_releases"]);
20
- // Below this share of plays with a recorded duration, minutes can't compare artists, years or
21
- // sources (Last.fm and many ListenBrainz files record none), so the build compares by plays.
22
- const TIMED_PLAY_SHARE = 0.95;
23
22
 
24
23
  function measurement(listening) {
25
- const plays = listening?.coverage?.effective_listening_events ?? 0;
26
- const timed = listening?.coverage?.events_with_played_duration;
27
- const time = timed === undefined ? "all" : recordedShare(plays, timed, TIMED_PLAY_SHARE);
24
+ const { lifetime, recent } = listening?.rankingWindows ?? {};
25
+ const plays = lifetime?.plays ?? listening?.coverage?.effective_listening_events ?? 0;
26
+ const timed = lifetime?.timed ?? listening?.coverage?.events_with_played_duration;
27
+ const time = timed === undefined ? "all" : rankingTimeCoverage(plays, timed);
28
+ const recentTime = recent ? rankingTimeCoverage(recent.plays, recent.timed) : time;
28
29
  // Listening rows state skips only where some play recorded them, so no row with skips means
29
30
  // no play in the history recorded one.
30
31
  const rows = Object.entries(listening?.sections ?? {})
31
32
  .filter(([section]) => RANKED_LISTENING_SECTIONS.has(section)).flatMap(([, rows]) => rows);
32
- const unskipped = rows.length > 0 && !rows.some(row => row.explicit_skips !== undefined);
33
- return { plays, timed, time, unskipped };
33
+ const unskipped = rows.length > 0 && !rows.some(row => row.explicit_skips !== undefined || row.plays_with_skip_data !== undefined);
34
+ return { plays, timed, time, recentTime, unskipped };
34
35
  }
35
36
 
36
37
  const without = (row, keys) => Object.fromEntries(Object.entries(row).filter(([key]) => !keys.includes(key)));
@@ -38,7 +39,7 @@ const without = (row, keys) => Object.fromEntries(Object.entries(row).filter(([k
38
39
  // Listening rows already leave out what their plays never recorded. Here a row also drops minutes
39
40
  // that can't compare it with others, and an Apple facet drops a play count none of its tracks
40
41
  // carry. Rows that lose a measure are marked, because the host's prose explanations still state it.
41
- function measuredRows(section, rows, { time }, withheld) {
42
+ function measuredRows(section, rows, time, withheld) {
42
43
  const unrecordedKeys = row => section.startsWith("apple_")
43
44
  ? (recordedShare(row.library_tracks, row.tracks_with_play_count) === "none" ? ["play_count"] : [])
44
45
  : time !== "all" ? ["listening_minutes"] : [];
@@ -51,12 +52,10 @@ function measuredRows(section, rows, { time }, withheld) {
51
52
  return measured;
52
53
  });
53
54
  if (time === "all" || !PLAY_COUNT_SECTIONS.has(section)) return next;
54
- // A row without skip data counts every play as engaged.
55
- const engaged = row => row.engaged_play_count ?? row.play_count ?? 0;
56
- return next.sort((left, right) => engaged(right) - engaged(left) || (right.play_count ?? 0) - (left.play_count ?? 0));
55
+ return next.sort((left, right) => (right.play_count ?? 0) - (left.play_count ?? 0));
57
56
  }
58
57
 
59
- function sectionSemantics(section, { time = "all" } = {}) {
58
+ function sectionSemantics(section, time, rows) {
60
59
  const common = {
61
60
  ordering: "Catalog order, not chronology or preference strength unless explicitly stated.",
62
61
  limitations: "Row position and repeated rows are not independent evidence of importance. Use the row's dated fields for time claims.",
@@ -64,23 +63,27 @@ function sectionSemantics(section, { time = "all" } = {}) {
64
63
  if (RANKED_LISTENING_SECTIONS.has(section)) {
65
64
  return { ordering: time === "all" ? "Ranked by measured listening duration, descending."
66
65
  : "Ranked by plays, descending, because listening time is not known for every play.",
67
- limitations: "Attention in the imported history is not a direct statement of liking. Recent and lifetime views overlap; do not add their totals." };
66
+ limitations: "Attention in the imported history is not a direct statement of liking. Recent and lifetime views overlap; do not add their totals."
67
+ + (rows.some(row => row.plays_with_skip_data !== undefined) ? " Where reported, recorded_skips covers only plays_with_skip_data." : "") };
68
68
  }
69
69
  if (section === "history_years") return { ...common,
70
- ordering: time === "all" ? "top_artist is selected by measured listening duration, not play count. Row position is not a preference ranking."
71
- : "top_artist is selected by measured listening duration where the year records it, otherwise by plays. Row position is not a preference ranking.",
70
+ ordering: time === "all" && !rows.some(row => row.top_artist_ranked_by === "plays")
71
+ ? "top_artist is selected by measured listening duration, not play count. Row position is not a preference ranking."
72
+ : "Each year ranks artists by measured listening duration when at least 95% of its plays record it. Other years rank by play count.",
72
73
  limitations: "Years have unequal coverage. Sparse or missing imported records do not establish a gap in the listener's actual listening." };
73
74
  if (section === "saved_tracks") return {
74
75
  ordering: time === "all" ? "Measured listening duration descending, then playlist membership count descending, then title."
75
76
  : "Not a preference ranking; listening time is not known for every play.",
76
- limitations: "Row order is not save or addition chronology. Missing listening minutes mean no matched duration in this import, not proof the listener never played a saved track.",
77
+ limitations: "Row order is not save or addition chronology. Missing listening minutes mean no matched duration in this import, not proof the listener never played a saved track."
78
+ + (rows.length ? " The dossier groups the full set of saved tracks by credited artist as collection evidence." : ""),
77
79
  };
78
80
  if (section === "moondog_suggestions") return {
79
81
  ordering: "Plays descending, then most recent.",
80
82
  limitations: "Moondog queued or played these, so they are left out of every listening ranking and are not the listener's taste. adopted means the listener later played the song again on their own, which is a reaction to a suggestion, not a preference by itself.",
81
83
  };
82
84
  if (section === "playlist_tracks") return { ...common,
83
- ordering: "Playlist membership count descending, then measured listening duration descending, then title." };
85
+ ordering: "Playlist membership count descending, then measured listening duration descending, then title.",
86
+ ...(rows.length ? { limitations: `${common.limitations} The dossier groups the full set of playlist tracks by credited artist.` } : {}) };
84
87
  if (section.startsWith("apple_")) return {
85
88
  ordering: section === "apple_tracks" ? "Imported preference strength descending, then snapshot play count descending, then internal stable identity."
86
89
  : "Imported preference strength descending, then library track count descending, then name.",
@@ -108,11 +111,17 @@ function text(value, maximum, field) {
108
111
  return value.trim();
109
112
  }
110
113
 
111
- export function createListenerProfileInput({ subjectId, evidenceRevision, listening, apple }) {
114
+ export function createListenerProfileInput({ subjectId, evidenceRevision, listening, apple, appleRevision }) {
112
115
  const measured = measurement(listening);
113
116
  const withheld = new Set();
117
+ const sectionTime = section => section.startsWith("recent_") ? measured.recentTime : measured.time;
114
118
  const sections = Object.fromEntries(Object.entries({ ...listening?.sections, ...apple?.sections })
115
- .map(([section, rows]) => [section, measuredRows(section, rows, measured, withheld)]));
119
+ .map(([section, rows]) => {
120
+ // The window-aware projection already checks each year's total and its leading artist
121
+ // separately. Older inputs only have a lifetime duration count.
122
+ if (section === "history_years" && listening?.rankingWindows?.lifetime) return [section, rows];
123
+ return [section, measuredRows(section, rows, sectionTime(section), withheld)];
124
+ }));
116
125
  const context = listening?.context ?? {};
117
126
  const coverage = { ...listening?.coverage, ...apple?.coverage };
118
127
  const evidence = new Map();
@@ -128,21 +137,24 @@ export function createListenerProfileInput({ subjectId, evidenceRevision, listen
128
137
  analysis_version: LISTENER_PROFILE_ANALYSIS_VERSION,
129
138
  coverage,
130
139
  sources: listening?.sources ?? [], context,
131
- sections: Object.entries(sections).map(([section, rows]) => ({ section, rows: rows.length, ...sectionSemantics(section, measured) })),
140
+ sections: Object.entries(sections).map(([section, rows]) => ({ section, rows: rows.length, ...sectionSemantics(section, sectionTime(section), rows) })),
132
141
  evidence_rows: evidence.size,
133
142
  limitations: [
134
143
  "Every supported record contributes to local analysis before the dossier selects rows. Rows are aggregates or observations, not a count of distinct plays.",
135
144
  "History measures attention. Apple snapshot counts are separate from dated plays; private-session plays and superseded overlaps do not become behavioral evidence.",
136
145
  "Provider labels are not listener assertions or measured audio features.",
137
146
  ...(measured.time === "none" ? ["No play in this history records how long it lasted, so listening time is unknown, not zero; rows rank by plays."] : []),
138
- ...(measured.time === "some" ? [`Listening time is known for only ${measured.timed} of ${measured.plays} plays, so minutes and hours cannot compare artists, years or sources; rows rank by plays, and coverage.listening_hours covers only the timed plays.`] : []),
147
+ ...(measured.timed > 0 && measured.timed < measured.plays ? [`Listening time is known for only ${measured.timed} of ${measured.plays} plays used for the profile. Lifetime listening ranks by ${measured.time === "all" ? "measured duration" : "play count"}. The recent window and each year use their own duration coverage. Listening hours cover only timed plays.`] : []),
139
148
  ...(measured.unskipped ? ["No play in this history is marked as skipped. These sources may not record skips, so skips and engaged plays are unknown, and having no skips says nothing about approval."] : []),
140
149
  ],
141
150
  };
142
151
  // Rows are content-addressed, so the ordered references cover every evidence value.
143
152
  const input_digest = profileDigest({ subjectId, evidenceRevision, manifest, evidence: [...evidence.keys()] });
144
153
  // Unrecorded measures change the evidence rows, so the digest already covers this set.
145
- return { subjectId, input_digest, manifest, evidence, unrecorded };
154
+ // The Apple snapshot is undated collection evidence across every listening cutoff.
155
+ const historyDigests = Object.fromEntries(Object.entries(listening?.historyDigests ?? {}).map(([through, digest]) =>
156
+ [through, profileDigest([digest, appleRevision ?? null])]));
157
+ return { subjectId, input_digest, manifest, evidence, unrecorded, historyDigests };
146
158
  }
147
159
 
148
160
  export function modelEvidence(entry, offset = 0, limit = 12) {
@@ -152,13 +164,18 @@ export function modelEvidence(entry, offset = 0, limit = 12) {
152
164
  "name", "label", "title", "artist_credit", "release", "genre", "entity_type", "stance", "asserted_at",
153
165
  "first_played_at", "last_played_at", "source_label", "identity_status", "evidence_kind", "period",
154
166
  "text", "playlist_name", "unit", "observed_at", "last_added_at", "play_count", "engaged_play_count",
155
- "explicit_skips", "listening_minutes", "distinct_tracks", "year", "event_count", "first_observed_tracks",
167
+ "explicit_skips", "plays_with_skip_data", "recorded_skips", "listening_minutes", "distinct_tracks", "year", "event_count",
168
+ "first_observed_tracks", "top_artist_ranked_by",
156
169
  "playlist_count", "library_tracks", "preferred_tracks", "tracks_with_play_count", "preference_strength",
157
170
  "loved", "favorited", "rating_value", "rating_computed", "rank", "playlist_position", "value",
158
171
  "stream_count", "played_seconds", "playlist_names", "top_artist", "first_year", "last_year", "active_years", "adopted",
159
172
  "yearly_plays", "activation", "trajectory",
160
173
  ]);
161
174
  const data = Object.fromEntries(Object.entries(entry.data).filter(([key]) => fields.has(key)));
175
+ if (LISTENER_SECTIONS.has(entry.section)) {
176
+ data.stance = entry.section === "listener_avoids" ? "avoid" : "like";
177
+ if (!entry.data.correction_id) data.from_import = true;
178
+ }
162
179
  if (data.top_artist) data.top_artist = Object.fromEntries(Object.entries(data.top_artist)
163
180
  .filter(([key]) => ["name", "play_count", "listening_minutes"].includes(key)));
164
181
  const continuations = {};
@@ -174,6 +191,12 @@ export function modelEvidence(entry, offset = 0, limit = 12) {
174
191
 
175
192
  const artistKey = value => typeof value === "string" ? value.normalize("NFKC").trim().toLocaleLowerCase() : null;
176
193
 
194
+ // Keep both stances in a bounded sample. Either one can use space the other does not need.
195
+ function sampleChoices(likes, avoids, limit) {
196
+ const shownLikes = likes.slice(0, Math.max(Math.floor(limit / 2), limit - avoids.length));
197
+ return [...shownLikes, ...avoids.slice(0, limit - shownLikes.length)];
198
+ }
199
+
177
200
  /**
178
201
  * A compact, deterministic view of the complete evidence for one synthesis
179
202
  * session. Every row keeps its reference so the model can cite it; the full
@@ -187,12 +210,16 @@ export function listenerProfileDossier(input) {
187
210
  const lifetimeRank = new Map(lifetime.map((entry, index) => [artistKey(entry.data.name), index + 1]));
188
211
  const listened = new Set(lifetime.slice(0, 80).map(entry => artistKey(entry.data.name)));
189
212
  const curated = new Map();
190
- const curate = (name, entry, signal) => {
213
+ const curate = (name, entry, signal, trackCount) => {
191
214
  const key = artistKey(name);
192
215
  if (!key || listened.has(key)) return;
193
- const item = curated.get(key) ?? { artist: name, signals: [], refs: [] };
194
- if (item.refs.length < 4) item.refs.push(entry.reference_id);
195
- item.signals.push(signal);
216
+ const item = curated.get(key) ?? { artist: name, signals: [], refs: [], observations: 0 };
217
+ item.observations += 1;
218
+ if (trackCount) item[trackCount] = (item[trackCount] ?? 0) + 1;
219
+ if (item.refs.length < 4) {
220
+ item.refs.push(entry.reference_id);
221
+ item.signals.push(signal);
222
+ }
196
223
  curated.set(key, item);
197
224
  };
198
225
  for (const entry of rows("followed_artists")) curate(entry.data.name, entry, "followed");
@@ -202,12 +229,17 @@ export function listenerProfileDossier(input) {
202
229
  curate(entry.data.name, entry, `Apple library: ${entry.data.library_tracks} tracks, ${entry.data.preferred_tracks ?? 0} preferred`);
203
230
  }
204
231
  }
205
- for (const entry of rows("playlist_tracks").slice(0, 300)) curate(entry.data.artist_credit, entry, `playlist track ${entry.data.label}`);
206
- const provider = rows("provider_evidence").filter(entry => !DUPLICATED_PROVIDER_KINDS.has(entry.data.evidence_kind) && !SPOTIFY_TOP_KINDS.has(entry.data.evidence_kind));
232
+ for (const entry of rows("playlist_tracks")) curate(entry.data.artist_credit, entry, `playlist track ${entry.data.label}`, "playlist_tracks");
233
+ for (const entry of rows("saved_tracks")) curate(entry.data.artist_credit, entry, `saved track ${entry.data.label}`, "saved_tracks");
234
+ const providerRows = rows("provider_evidence");
235
+ const provider = providerRows.filter(entry => !DUPLICATED_PROVIDER_KINDS.has(entry.data.evidence_kind) && !SPOTIFY_TOP_KINDS.has(entry.data.evidence_kind));
236
+ const ranked = providerRows.filter(entry => SPOTIFY_TOP_KINDS.has(entry.data.evidence_kind));
237
+ // The listening projection retains the most recent Spotify library snapshot.
238
+ const rankDates = new Set(ranked.map(entry => entry.data.observed_at ?? null));
207
239
  // Spotify ranks the same names across three periods; one row per name keeps them comparable.
208
240
  const spotifyTop = (kind, limit) => {
209
241
  const grouped = new Map();
210
- for (const entry of rows("provider_evidence").filter(entry => entry.data.evidence_kind === kind)) {
242
+ for (const entry of ranked.filter(entry => entry.data.evidence_kind === kind)) {
211
243
  const key = artistKey(`${entry.data.label}\0${entry.data.artist_credit ?? ""}`);
212
244
  const item = grouped.get(key) ?? { ref: entry.reference_id, label: entry.data.label,
213
245
  ...(entry.data.artist_credit ? { artist_credit: entry.data.artist_credit } : {}), ranks: {}, best: Infinity };
@@ -220,8 +252,10 @@ export function listenerProfileDossier(input) {
220
252
  };
221
253
  const sections = Object.fromEntries(input.manifest.sections.map(({ section, rows: total, ordering, limitations }) =>
222
254
  [section, { total, ordering, limitations }]));
255
+ const { reference_date, ...context } = input.manifest.context;
223
256
  return {
224
- coverage: input.manifest.coverage, sources: input.manifest.sources, context: input.manifest.context,
257
+ coverage: input.manifest.coverage, sources: input.manifest.sources,
258
+ context: { ...context, recent_window_ends_at: reference_date ?? null },
225
259
  sections,
226
260
  lifetime_artists: lifetime.slice(0, 40).map(row),
227
261
  next_lifetime_artists: lifetime.slice(40, 80).map(entry => ({ ref: entry.reference_id, name: entry.data.name,
@@ -241,8 +275,8 @@ export function listenerProfileDossier(input) {
241
275
  lifetime_tracks: take("history_tracks", 25),
242
276
  recent_tracks: take("recent_tracks", 15),
243
277
  releases_in_depth: take("history_releases", 15),
244
- curated_beyond_listening: [...curated.values()].sort((a, b) => b.signals.length - a.signals.length).slice(0, 20)
245
- .map(item => ({ ...item, signals: item.signals.slice(0, 4) })),
278
+ curated_beyond_listening: [...curated.values()].sort((a, b) => b.observations - a.observations).slice(0, 20)
279
+ .map(({ observations, ...item }) => item),
246
280
  saved_albums: take("saved_albums", 20),
247
281
  saved_tracks: take("saved_tracks", 15),
248
282
  playlist_tracks: take("playlist_tracks", 15),
@@ -253,12 +287,13 @@ export function listenerProfileDossier(input) {
253
287
  apple_tracks: take("apple_tracks", 15),
254
288
  provider_genres: take("provider_genres", 15),
255
289
  spotify_top: {
256
- note: "Spotify's own affinity ranks (1 is highest) for the last four weeks, six months and about a year, read from the live account. Short-term ranks reflect recent attention; ranks held across all periods suggest something more enduring. Not play counts.",
290
+ observed_at: rankDates.size === 1 ? [...rankDates][0] : null,
291
+ note: "Spotify's saved affinity ranks (1 is highest) cover four weeks, six months or about a year ending at observed_at. Agreement across periods describes interest at that time. Without a capture date, timing is unknown.",
257
292
  artists: spotifyTop("top_artist_ranked", 40),
258
293
  tracks: spotifyTop("top_track_ranked", 25),
259
294
  },
260
295
  provider_signals: provider.slice(0, 50).map(row),
261
- explicit_choices: [...rows("listener_preferences"), ...rows("listener_avoids")].slice(0, 100).map(row),
296
+ explicit_choices: sampleChoices(rows("listener_preferences"), rows("listener_avoids"), 100).map(row),
262
297
  ...(rows("moondog_suggestions").length ? { played_from_moondog: {
263
298
  note: "Plays Moondog itself queued or played. They are not in any ranking above and are not taste. adopted means the listener played the song again later on their own.",
264
299
  plays: input.manifest.context.moondog_started_events_excluded ?? null,
@@ -269,6 +304,42 @@ export function listenerProfileDossier(input) {
269
304
  };
270
305
  }
271
306
 
307
+ // Keep a few citable examples of each available kind for a small model. The section totals
308
+ // describe the full catalog, including rows the model can still search and read by ref.
309
+ export function smallContextProfileDossier(dossier) {
310
+ const ranked = ({ ref, name, label, artist_credit, play_count, listening_minutes, distinct_tracks, trajectory, lifetime_rank,
311
+ explicit_skips, plays_with_skip_data, recorded_skips }) =>
312
+ ({ ref, name, label, artist_credit, play_count, listening_minutes, distinct_tracks, trajectory, lifetime_rank,
313
+ explicit_skips, plays_with_skip_data, recorded_skips });
314
+ const select = (rows, limit) => rows.slice(0, limit).map(ranked);
315
+ const sections = Object.fromEntries(Object.entries(dossier.sections).filter(([, item]) => item.total)
316
+ .map(([key, item]) => [key, item.total]));
317
+ const ordering = Object.fromEntries(["history_artists", "recent_artists", "history_years", "apple_artists", "apple_tracks"]
318
+ .filter(key => sections[key]).map(key => [key, dossier.sections[key].ordering]));
319
+ const movement = Object.fromEntries(Object.entries(dossier.movement)
320
+ .filter(([, rows]) => Array.isArray(rows) && rows.length).map(([kind, rows]) => [kind, rows.slice(0, 1)]));
321
+ if (Object.keys(movement).length) movement.note = dossier.movement.note;
322
+ const lifetime = select(dossier.lifetime_artists, 5);
323
+ if (lifetime.length) lifetime[0].yearly_plays = dossier.lifetime_artists[0].yearly_plays;
324
+ const years = dossier.years.length > 4 ? [dossier.years[0], ...dossier.years.slice(-3)] : dossier.years;
325
+ return {
326
+ coverage: dossier.coverage, sources: dossier.sources, context: dossier.context, sections, ordering,
327
+ lifetime_artists: lifetime, recent_artists: select(dossier.recent_artists, 3),
328
+ movement, years: years.map(({ ref, year, event_count, listening_minutes, top_artist, top_artist_ranked_by }) =>
329
+ ({ ref, year, event_count, listening_minutes, top_artist, top_artist_ranked_by })),
330
+ lifetime_tracks: select(dossier.lifetime_tracks, 2), recent_tracks: select(dossier.recent_tracks, 1),
331
+ ...Object.fromEntries(["releases_in_depth", "curated_beyond_listening", "saved_albums", "saved_tracks", "playlist_tracks",
332
+ "followed_artists", "apple_artists", "apple_genres", "apple_tracks", "provider_genres", "provider_signals"]
333
+ .filter(key => dossier[key].length).map(key => [key, dossier[key].slice(0, 1)])),
334
+ ...(dossier.spotify_top.artists.length || dossier.spotify_top.tracks.length ? { spotify_top: { ...dossier.spotify_top,
335
+ artists: dossier.spotify_top.artists.slice(0, 3), tracks: dossier.spotify_top.tracks.slice(0, 1) } } : {}),
336
+ explicit_choices: sampleChoices(dossier.explicit_choices.filter(row => row.stance === "like"),
337
+ dossier.explicit_choices.filter(row => row.stance === "avoid"), 6),
338
+ ...(dossier.played_from_moondog ? { played_from_moondog: { ...dossier.played_from_moondog,
339
+ examples: dossier.played_from_moondog.examples.slice(0, 1) } } : {}),
340
+ };
341
+ }
342
+
272
343
  function validateClaim(input, raw) {
273
344
  if (!["observation", "hypothesis"].includes(raw?.kind)) {
274
345
  throw new TypeError("Only the listener can establish a direct preference");
@@ -317,10 +388,12 @@ export function compileListenerProfile(input, submission) {
317
388
  const insights = submission.insights.map(raw => validateClaim(input, raw));
318
389
  const claims = [...new Map([...insights, ...listenerAssertionClaims(input)].map(claim => [claim.claim_id, claim])).values()];
319
390
  const referenced = new Set(claims.flatMap(claim => [...claim.supporting_refs, ...claim.contradicting_refs]));
391
+ const historyDigest = input.historyDigests?.[input.manifest.coverage.latest_played_at];
320
392
  return {
321
393
  analysis_version: LISTENER_PROFILE_ANALYSIS_VERSION,
322
394
  synthesis_version: LISTENER_PROFILE_SYNTHESIS_VERSION,
323
395
  input_digest: input.input_digest,
396
+ ...(historyDigest ? { history_through_digest: historyDigest } : {}),
324
397
  summary: text(submission.summary, 1_600, "summary"),
325
398
  coverage: input.manifest,
326
399
  claims, highlight_claim_ids: [...new Set(insights.map(claim => claim.claim_id))],
@@ -379,33 +452,43 @@ export function savedListenerChoices(corrections, total) {
379
452
  };
380
453
  }
381
454
 
382
- export function readListenerProfile({ input, getInput, store, getChoices }, { offset = 0, limit = 12, claimId, revisionId } = {}) {
455
+ function onlyLaterListening(revision, input) {
456
+ const previous = revision.coverage?.coverage;
457
+ const current = input.manifest?.coverage;
458
+ return Boolean(revision.history_through_digest && previous?.latest_played_at &&
459
+ current?.latest_played_at > previous.latest_played_at &&
460
+ current.effective_listening_events > previous.effective_listening_events &&
461
+ input.historyDigests?.[previous.latest_played_at] === revision.history_through_digest);
462
+ }
463
+
464
+ export function readListenerProfile({ input, getInput, store, getChoices }, { offset = 0, limit = 12, claimId, revisionId, includeBuildStatus = false } = {}) {
383
465
  if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isInteger(limit) || limit < 1 || limit > 20) {
384
466
  throw new TypeError("Saved profile page is invalid");
385
467
  }
386
468
  const current = store.current();
387
469
  const revision = revisionId ? store.revision(revisionId) : current;
388
470
  if (revisionId && !revision) throw new Error("That saved profile version is unavailable");
471
+ // A background update that failed since this reading was saved, so a surface can say so.
472
+ const failure = revisionId ? null : store.lastFailure?.() ?? null;
389
473
  if (!revision) {
390
474
  const choices = getChoices?.();
391
- return { state: "missing", total_claims: 0, claims: [], next_offset: null, ...(choices ? { listener_choices: choices } : {}) };
475
+ return { state: "missing", total_claims: 0, claims: [], next_offset: null, ...(choices ? { listener_choices: choices } : {}),
476
+ ...(failure ? { last_build_failure: failure } : {}) };
392
477
  }
393
478
  // Most new listeners have no saved reading. Do not scan their source archive
394
479
  // merely to tell an ordinary conversation that the reading is missing.
395
- input ??= getInput();
480
+ input ??= getInput(revision.history_through_digest ? revision.coverage?.coverage?.latest_played_at : null);
396
481
  const analysisHolds = revision.synthesis_version === LISTENER_PROFILE_SYNTHESIS_VERSION &&
397
482
  CHECKED_PROFILE_STATES.has(revision.verification?.state);
398
483
  const state = analysisHolds && revision.input_digest === input.input_digest ? "current" : "stale";
399
484
  const result = {
400
485
  state,
401
- // New plays alone change the input. A reading whose analysis and listener choices
402
- // still hold stays usable as taste up to the listening it was built from.
403
- ...(state === "stale" && analysisHolds && sameListenerChoices(new Map(Object.entries(revision.evidence ?? {})), input.evidence)
404
- ? { newer_listening_only: true } : {}),
486
+ ...(state === "stale" && analysisHolds && onlyLaterListening(revision, input) ? { newer_listening_only: true } : {}),
405
487
  revision_id: revision.revision_id, sequence: revision.sequence,
406
488
  parent_revision_id: revision.parent_revision_id, built_at: revision.built_at, model: revision.model,
407
489
  synthesis_version: revision.synthesis_version,
408
490
  verification: revision.verification,
491
+ ...(failure && state !== "current" ? { last_build_failure: failure } : {}),
409
492
  summary: revision.summary, coverage: revision.coverage,
410
493
  total_claims: revision.claims.length,
411
494
  claims: revision.claims.slice(offset, offset + limit), offset,
@@ -418,6 +501,10 @@ export function readListenerProfile({ input, getInput, store, getChoices }, { of
418
501
  ? [{ ...claim, finding_number: index + 1 }] : []),
419
502
  ...listenerChoices(input.evidence ?? new Map(), new Map(Object.entries(revision.evidence ?? {}))),
420
503
  };
504
+ if (includeBuildStatus === true && !revisionId && state === "current") {
505
+ const pending = store.interruptedRebuild(input.input_digest, revision.revision_id);
506
+ if (pending) result.resumable_build = pending;
507
+ }
421
508
  if (claimId !== undefined) {
422
509
  const claim = revision.claims.find(item => item.claim_id === claimId);
423
510
  if (!claim) throw new Error("That finding is not part of this saved profile");
@@ -445,7 +532,7 @@ export function compactListenerProfile(value) {
445
532
  ...(value.state === "current" || behind || previous ? {
446
533
  ...(behind ? { note: "Built from listening up to coverage.last_played_at. Plays stored since then are not in this reading; listening coverage shows them. Listener choices and analysis are unchanged." } : {}),
447
534
  ...(previous ? { previous_reading: true,
448
- note: "The previous reading. It predates listener_choices and choices_since_reading, or the analysis has changed since. Use it only as background: where they differ, the listener's choices win. Update the reading before treating it as current taste." } : {}),
535
+ note: "This is a previous reading. Its listening history, collection evidence, listener choices or analysis has changed. Use current evidence for recommendations. Where it differs from listener_choices, the listener's choices win. The saved summary and findings are historical." } : {}),
449
536
  summary: value.summary,
450
537
  claims: value.highlights,
451
538
  // A previous reading's own choices may be out of date; listener_choices holds the current ones.
@@ -1,6 +1,9 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { profileDigest } from "./listener-profile-build.mjs";
3
3
 
4
+ const isAbort = (error) => error?.name === "AbortError" || error?.code === "ABORT_ERR";
5
+ const abandonedBefore = () => new Date(Date.now() - 24 * 3_600_000).toISOString();
6
+
4
7
  // listener_profile_partitions holds page findings from builds before
5
8
  // listener-synthesis/4. New builds no longer write it; it stays so existing
6
9
  // databases open unchanged.
@@ -51,11 +54,27 @@ export class ListenerProfileStore {
51
54
  FROM listener_profile_builds WHERE subject_id = ?`).get(this.subjectId)?.attempted_at ?? null;
52
55
  }
53
56
 
57
+ /** A stopped rebuild of the current reading. A newer attempt supersedes an older draft. */
58
+ interruptedRebuild(inputDigest, parentRevisionId) {
59
+ const row = this.database.prepare(`SELECT state, record_json FROM listener_profile_builds
60
+ WHERE subject_id = ? AND input_digest = ? AND json_extract(record_json, '$.parent_revision_id') = ?
61
+ ORDER BY rowid DESC LIMIT 1`).get(this.subjectId, inputDigest, parentRevisionId);
62
+ if (!row) return null;
63
+ const build = JSON.parse(row.record_json);
64
+ const attemptedAt = build.attempted_at ?? build.started_at;
65
+ if (row.state !== "interrupted" && !(row.state === "building" && attemptedAt < abandonedBefore())) return null;
66
+ // Older builds kept the time of the error. New ones identify its attempt even on the same clock tick.
67
+ const failed = row.state === "interrupted" && build.failure && (build.failed_lease
68
+ ? build.failed_lease === build.lease_token : build.failure.at >= attemptedAt);
69
+ return { build_id: build.build_id, model: build.model, ...(failed ? { failure: build.failure } : {}) };
70
+ }
71
+
54
72
  /** Resume an unfinished build for the same input and model, or start a new one. */
55
- begin(input, model, { force = false } = {}) {
73
+ begin(input, model, { force = false, resumeBuildId } = {}) {
56
74
  const modelKey = profileDigest(model);
57
75
  this.database.exec("BEGIN IMMEDIATE");
58
76
  try {
77
+ this.#releaseAbandoned();
59
78
  const parent = this.current()?.revision_id ?? null;
60
79
  const existing = force ? null : this.database.prepare(`SELECT record_json FROM listener_profile_builds
61
80
  WHERE subject_id = ? AND input_digest = ? AND model_key = ? AND state <> 'complete'
@@ -63,6 +82,12 @@ export class ListenerProfileStore {
63
82
  const saved = existing ? JSON.parse(existing.record_json) : null;
64
83
  // A checkpoint written against an older current reading cannot replace the newer one.
65
84
  const resumable = saved?.parent_revision_id === parent ? saved : null;
85
+ // A second client may have resumed, replaced or published the draft while the model connected.
86
+ if (resumeBuildId && (resumable?.build_id !== resumeBuildId ||
87
+ this.interruptedRebuild(input.input_digest, parent)?.build_id !== resumeBuildId)) {
88
+ this.database.exec("COMMIT");
89
+ return null;
90
+ }
66
91
  const build = resumable ?? {
67
92
  build_id: randomUUID(), input_digest: input.input_digest, model,
68
93
  parent_revision_id: parent, started_at: new Date().toISOString(),
@@ -100,10 +125,38 @@ export class ListenerProfileStore {
100
125
  } catch (error) { this.database.exec("ROLLBACK"); throw error; }
101
126
  }
102
127
 
103
- interrupt(build) {
104
- this.database.prepare(`UPDATE listener_profile_builds SET state = 'interrupted'
128
+ // The reason stays with the build, so the taste page and /taste can say why a reading stopped updating.
129
+ interrupt(build, error = null) {
130
+ const failure = error && !isAbort(error) ? {
131
+ at: new Date().toISOString(),
132
+ code: typeof error.code === "string" ? error.code.slice(0, 64) : null,
133
+ // The first paragraph names the cause; the rest is the terminal's advice to retry.
134
+ message: String(error.message ?? error).split("\n\n")[0].slice(0, 300),
135
+ } : null;
136
+ this.database.prepare(`UPDATE listener_profile_builds SET state = 'interrupted',
137
+ record_json = CASE WHEN ? IS NULL THEN record_json ELSE json_set(record_json, '$.failure', json(?), '$.failed_lease', lease_token) END
105
138
  WHERE subject_id = ? AND build_id = ? AND lease_token = ? AND state = 'building'`)
106
- .run(this.subjectId, build.build_id, build.lease_token);
139
+ .run(failure && JSON.stringify(failure), failure && JSON.stringify(failure), this.subjectId, build.build_id, build.lease_token);
140
+ }
141
+
142
+ /** The latest build that failed after the current reading was saved, or null. */
143
+ lastFailure() {
144
+ const builtAt = this.current()?.built_at ?? "";
145
+ const row = this.database.prepare(`SELECT json_extract(record_json, '$.failure') AS failure,
146
+ json_extract(record_json, '$.model') AS model
147
+ FROM listener_profile_builds WHERE subject_id = ? AND state = 'interrupted'
148
+ AND json_extract(record_json, '$.failure.at') > ?
149
+ ORDER BY json_extract(record_json, '$.failure.at') DESC LIMIT 1`).get(this.subjectId, builtAt);
150
+ return row?.failure ? { ...JSON.parse(row.failure), model: row.model ? JSON.parse(row.model) : null } : null;
151
+ }
152
+
153
+ // A build whose process ended without a word (a quit, a crash) keeps its lease forever; a day later
154
+ // nothing holds it, so it reads as interrupted.
155
+ #releaseAbandoned() {
156
+ this.database.prepare(`UPDATE listener_profile_builds SET state = 'interrupted'
157
+ WHERE subject_id = ? AND state = 'building'
158
+ AND COALESCE(json_extract(record_json, '$.attempted_at'), json_extract(record_json, '$.started_at')) < ?`)
159
+ .run(this.subjectId, abandonedBefore());
107
160
  }
108
161
 
109
162
  complete(build, profile, assertCurrentInput = () => {}) {
@@ -1,4 +1,5 @@
1
1
  import { modelEvidence, profileDigest } from "./listener-profile-build.mjs";
2
+ import { isListenerChoiceSection, listenerChoiceMatcher } from "./profile-exploration.mjs";
2
3
 
3
4
  export const LISTENER_PROFILE_CHECK_VERSION = "listener-check/1";
4
5
  const MAX_CHECK_ISSUES = 6;
@@ -53,16 +54,21 @@ export function validateListenerProfileCheck(candidate, value) {
53
54
  };
54
55
  }
55
56
 
56
- export function searchListenerProfileEvidence(input, { section, query, offset = 0 } = {}) {
57
+ export function searchListenerProfileEvidence(input, { section, query, offset = 0 } = {}, pageSize = 12) {
57
58
  if (section !== undefined && !input.manifest.sections.some(item => item.section === section)) {
58
59
  throw new TypeError("Unknown evidence section");
59
60
  }
60
61
  if ((query !== undefined && (typeof query !== "string" || query.length > 200)) ||
61
62
  !Number.isSafeInteger(offset) || offset < 0) throw new TypeError("Invalid evidence search");
62
63
  const needle = query?.normalize("NFKC").toLocaleLowerCase();
64
+ const choiceMatch = listenerChoiceMatcher(query);
63
65
  const matches = [...input.evidence.values()].filter(entry => !section || entry.section === section)
64
- .filter(entry => !needle || JSON.stringify(modelEvidence(entry, 0, Number.MAX_SAFE_INTEGER).data)
65
- .normalize("NFKC").toLocaleLowerCase().includes(needle));
66
- return { total: matches.length, offset, items: matches.slice(offset, offset + 12).map(entry => modelEvidence(entry)),
67
- next_offset: offset + 12 < matches.length ? offset + 12 : null };
66
+ .filter(entry => {
67
+ if (!needle) return true;
68
+ const { data } = modelEvidence(entry, 0, Number.MAX_SAFE_INTEGER);
69
+ return (isListenerChoiceSection(entry.section) && choiceMatch(data)) ||
70
+ JSON.stringify(data).normalize("NFKC").toLocaleLowerCase().includes(needle);
71
+ });
72
+ return { total: matches.length, offset, items: matches.slice(offset, offset + pageSize).map(entry => modelEvidence(entry)),
73
+ next_offset: offset + pageSize < matches.length ? offset + pageSize : null };
68
74
  }
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  CHECKED_PROFILE_STATES, compileListenerProfile, listenerProfileDossier, LISTENER_PROFILE_SYNTHESIS_VERSION, modelEvidence,
3
- sameListenerChoices,
3
+ profileDigest, sameListenerChoices,
4
4
  } from "./listener-profile-build.mjs";
5
5
  import {
6
6
  LISTENER_PROFILE_CHECK_VERSION, listenerProfileCandidate, searchListenerProfileEvidence, validateListenerProfileCheck,
@@ -11,6 +11,10 @@ import { createConfiguredProfileBuildRuntime } from "../runtime/pi/profile-build
11
11
  // a model that hits its turn limit continue the same stage.
12
12
  const MAX_REVISIONS = 1;
13
13
  const MAX_SESSIONS = 8;
14
+ const MAX_CUT_REPLIES = 2;
15
+ const RETRIED_FAILURES = new Set(["profile_model_reply_cut", "model_connection_failed"]);
16
+ const resumeUnavailable = () => Object.assign(new Error("That build is no longer available to resume. Open Taste to see the current reading."),
17
+ { code: "profile_resume_unavailable" });
14
18
 
15
19
  const HOUR_MS = 3_600_000;
16
20
  // A reading that only new plays have overtaken is rebuilt after a week or 300 plays.
@@ -45,22 +49,36 @@ export async function refreshListenerProfileIfDue({ application, now = Date.now(
45
49
  }
46
50
 
47
51
  export async function runListenerProfileBuild({
48
- application, environment = process.env, signal, onProgress = () => {}, force = false,
52
+ application, environment = process.env, signal, onProgress = () => {}, force = false, resumeBuildId,
49
53
  runtimeFactory = createConfiguredProfileBuildRuntime,
50
54
  } = {}) {
51
55
  signal?.throwIfAborted();
52
56
  const { input, store } = application.getProfileBuildContext();
53
57
  if (!input.evidence.size) return { state: "no_evidence" };
54
58
  const previous = store.current();
55
- if (!force && previous?.input_digest === input.input_digest && previous.synthesis_version === LISTENER_PROFILE_SYNTHESIS_VERSION &&
56
- CHECKED_PROFILE_STATES.has(previous.verification?.state)) {
59
+ const current = !force && previous?.input_digest === input.input_digest &&
60
+ previous.synthesis_version === LISTENER_PROFILE_SYNTHESIS_VERSION && CHECKED_PROFILE_STATES.has(previous.verification?.state);
61
+ const pending = current ? store.interruptedRebuild(input.input_digest, previous.revision_id) : null;
62
+ if (resumeBuildId !== undefined && resumeBuildId !== pending?.build_id) throw resumeUnavailable();
63
+ if (current && !pending) {
57
64
  return { state: "unchanged", revision: await application.getListenerProfile() };
58
65
  }
59
66
  const runtime = await runtimeFactory(environment);
67
+ // A foreground build may have taken over while the previous build was connecting.
68
+ signal?.throwIfAborted();
60
69
  const status = runtime.publicStatus();
61
- if (status.state !== "configured") throw new Error("Connect a model with /model, then use /profile build. Your imported profile is still available.");
70
+ if (status.state !== "configured") {
71
+ const error = new Error("Connect a model with /model, then use /profile build. Your imported profile is still available.");
72
+ error.code = "profile_model_required";
73
+ throw error;
74
+ }
62
75
  const model = { provider: status.provider, model: status.model, worker_version: status.worker_version };
63
- const build = store.begin(input, model, { force });
76
+ if (pending && profileDigest(pending.model) !== profileDigest(model)) {
77
+ throw Object.assign(new Error("That draft used a different model or version. Use the original model to continue it, or start a fresh build. Your saved reading is available."),
78
+ { code: "profile_resume_model_changed" });
79
+ }
80
+ const build = store.begin(input, model, { force, resumeBuildId: pending?.build_id });
81
+ if (!build) throw resumeUnavailable();
64
82
  // Drafts and checks are checkpoints, never current profile revisions.
65
83
  let finalization = build.finalization?.synthesis_version === LISTENER_PROFILE_SYNTHESIS_VERSION
66
84
  ? structuredClone(build.finalization)
@@ -96,9 +114,9 @@ export async function runListenerProfileBuild({
96
114
  language: application.locale ?? "en",
97
115
  get candidate() { return candidate; },
98
116
  get check() { return latestCheck(); },
99
- search: args => {
117
+ search: (args, pageSize) => {
100
118
  signal?.throwIfAborted();
101
- const result = searchListenerProfileEvidence(input, args);
119
+ const result = searchListenerProfileEvidence(input, args, pageSize);
102
120
  for (const item of result.items) inspected.add(item.reference_id);
103
121
  return result;
104
122
  },
@@ -147,6 +165,7 @@ export async function runListenerProfileBuild({
147
165
  signal?.throwIfAborted();
148
166
  onProgress(progress());
149
167
  let sessions = 0;
168
+ let cutReplies = 0;
150
169
  while (phase() !== "complete") {
151
170
  signal?.throwIfAborted();
152
171
  session.phase = phase();
@@ -155,7 +174,14 @@ export async function runListenerProfileBuild({
155
174
  throw new Error("The profile build reached its session limit. Your previous reading and the saved draft are kept. Use /profile build to continue.");
156
175
  }
157
176
  const inspectedBefore = inspected.size;
158
- await runtime.investigate(session);
177
+ try {
178
+ await runtime.investigate(session);
179
+ } catch (error) {
180
+ // A reply cut off on its way, or a dropped connection, loses only that session; the saved
181
+ // draft and checks stay, and the same stage runs again.
182
+ if (!RETRIED_FAILURES.has(error?.code) || ++cutReplies > MAX_CUT_REPLIES || signal?.aborted) throw error;
183
+ continue;
184
+ }
159
185
  signal?.throwIfAborted();
160
186
  assertCurrentInput();
161
187
  if (!stageFinished && inspected.size === inspectedBefore) {
@@ -170,7 +196,7 @@ export async function runListenerProfileBuild({
170
196
  } }, assertCurrentInput);
171
197
  return { state: "ready", revision: await application.getListenerProfile(), ...progress() };
172
198
  } catch (error) {
173
- store.interrupt(build);
199
+ store.interrupt(build, error);
174
200
  throw error;
175
201
  } finally {
176
202
  signal?.removeEventListener("abort", abort);