@vue-skuilder/db 0.2.27 → 0.2.28

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 (59) hide show
  1. package/dist/classroomDB-DLTtLZct.d.cts +86 -0
  2. package/dist/classroomDB-DLTtLZct.d.ts +86 -0
  3. package/dist/{contentSource-LPf044hY.d.ts → contentSource-BoFBwvYa.d.ts} +65 -98
  4. package/dist/{contentSource-D3c1fMAk.d.cts → contentSource-DpQqTG3m.d.cts} +65 -98
  5. package/dist/core/index.d.cts +6 -5
  6. package/dist/core/index.d.ts +6 -5
  7. package/dist/core/index.js +22 -2
  8. package/dist/core/index.js.map +1 -1
  9. package/dist/core/index.mjs +22 -2
  10. package/dist/core/index.mjs.map +1 -1
  11. package/dist/{dataLayerProvider-DaAootVV.d.ts → dataLayerProvider-D_LJT3F4.d.ts} +2 -8
  12. package/dist/{dataLayerProvider-CeLiFbHv.d.cts → dataLayerProvider-Dl3cAAvQ.d.cts} +2 -8
  13. package/dist/diagnostics/index.d.cts +370 -0
  14. package/dist/diagnostics/index.d.ts +370 -0
  15. package/dist/diagnostics/index.js +778 -0
  16. package/dist/diagnostics/index.js.map +1 -0
  17. package/dist/diagnostics/index.mjs +729 -0
  18. package/dist/diagnostics/index.mjs.map +1 -0
  19. package/dist/impl/couch/index.d.cts +4 -3
  20. package/dist/impl/couch/index.d.ts +4 -3
  21. package/dist/impl/couch/index.js +22 -2
  22. package/dist/impl/couch/index.js.map +1 -1
  23. package/dist/impl/couch/index.mjs +22 -2
  24. package/dist/impl/couch/index.mjs.map +1 -1
  25. package/dist/impl/static/index.d.cts +5 -5
  26. package/dist/impl/static/index.d.ts +5 -5
  27. package/dist/impl/static/index.js +22 -8
  28. package/dist/impl/static/index.js.map +1 -1
  29. package/dist/impl/static/index.mjs +22 -8
  30. package/dist/impl/static/index.mjs.map +1 -1
  31. package/dist/{index-BkBJlGDX.d.ts → index-CVGehe_t.d.ts} +1 -1
  32. package/dist/{index-D7WdMDAs.d.cts → index-Ktg72jKb.d.cts} +1 -1
  33. package/dist/index.d.cts +10 -9
  34. package/dist/index.d.ts +10 -9
  35. package/dist/index.js +64 -23
  36. package/dist/index.js.map +1 -1
  37. package/dist/index.mjs +64 -23
  38. package/dist/index.mjs.map +1 -1
  39. package/dist/{types-DjiFOZxJ.d.cts → types-D0oQeJAi.d.cts} +1 -1
  40. package/dist/{types-uJ2Xn3_X.d.ts → types-dXWfyz9B.d.ts} +1 -1
  41. package/dist/{types-legacy-CrwyZIvI.d.cts → types-legacy-BkOYOR6U.d.cts} +1 -1
  42. package/dist/{types-legacy-CrwyZIvI.d.ts → types-legacy-BkOYOR6U.d.ts} +1 -1
  43. package/dist/util/packer/index.d.cts +3 -3
  44. package/dist/util/packer/index.d.ts +3 -3
  45. package/package.json +15 -3
  46. package/src/core/interfaces/dataLayerProvider.ts +3 -8
  47. package/src/core/navigators/Pipeline.ts +5 -2
  48. package/src/core/navigators/PipelineDebugger.ts +64 -16
  49. package/src/core/navigators/index.ts +1 -0
  50. package/src/core/types/studySession.ts +37 -0
  51. package/src/diagnostics/dataset.ts +231 -0
  52. package/src/diagnostics/derive.ts +555 -0
  53. package/src/diagnostics/index.ts +24 -0
  54. package/src/diagnostics/loader.ts +191 -0
  55. package/src/diagnostics/text.ts +242 -0
  56. package/src/impl/couch/PouchDataLayerProvider.ts +0 -23
  57. package/src/impl/static/StaticDataLayerProvider.ts +0 -11
  58. package/src/study/SessionController.ts +56 -2
  59. package/tsup.config.ts +1 -0
@@ -0,0 +1,191 @@
1
+ import type { CourseSlice, LearnerDump } from './dataset';
2
+
3
+ type RawDoc = { _id: string; [key: string]: unknown };
4
+
5
+ export type CouchAuth =
6
+ | { kind: 'basic'; username: string; password: string }
7
+ /** Browser: the signed-in admin's couch session cookie. */
8
+ | { kind: 'cookie' };
9
+
10
+ export interface FetchLearnerDumpOptions {
11
+ /** Couch base URL, e.g. `https://example.com/couch`. */
12
+ couchUrl: string;
13
+ username: string;
14
+ courseId: string;
15
+ auth: CouchAuth;
16
+ /** Course-DB slice to include. Default `touched`. */
17
+ cards?: 'touched' | 'all' | 'none';
18
+ /** Inline user-DB attachments as base64. Default false. */
19
+ attachments?: boolean;
20
+ /** Defaults to the global `fetch`. */
21
+ fetchImpl?: typeof fetch;
22
+ }
23
+
24
+ /** couch_peruser convention: `userdb-` + lowercase hex of the username's UTF-8 bytes. */
25
+ export function userDbName(username: string): string {
26
+ let hex = '';
27
+ for (const b of new TextEncoder().encode(username)) hex += b.toString(16).padStart(2, '0');
28
+ return 'userdb-' + hex;
29
+ }
30
+
31
+ function base64(s: string): string {
32
+ let binary = '';
33
+ for (const b of new TextEncoder().encode(s)) binary += String.fromCharCode(b);
34
+ return btoa(binary);
35
+ }
36
+
37
+ /** Drop trailing slashes. A loop, not `/\/+$/`, which is quadratic on long runs of '/'. */
38
+ function trimTrailingSlashes(url: string): string {
39
+ let end = url.length;
40
+ while (end > 0 && url[end - 1] === '/') end--;
41
+ return url.slice(0, end);
42
+ }
43
+
44
+ /** A tiny read-only couch client. No Pouch, no user object, no sync. */
45
+ function couchReader(opts: FetchLearnerDumpOptions) {
46
+ const doFetch = opts.fetchImpl ?? fetch;
47
+ const base = trimTrailingSlashes(opts.couchUrl);
48
+ const headers: Record<string, string> = { Accept: 'application/json' };
49
+ if (opts.auth.kind === 'basic') {
50
+ headers.Authorization = 'Basic ' + base64(`${opts.auth.username}:${opts.auth.password}`);
51
+ }
52
+ const credentials: RequestCredentials | undefined =
53
+ opts.auth.kind === 'cookie' ? 'include' : undefined;
54
+
55
+ async function get<T>(path: string, init: { method?: string; body?: unknown } = {}): Promise<T> {
56
+ const res = await doFetch(`${base}/${path}`, {
57
+ method: init.method ?? 'GET',
58
+ headers: init.body ? { ...headers, 'Content-Type': 'application/json' } : headers,
59
+ ...(init.body ? { body: JSON.stringify(init.body) } : {}),
60
+ ...(credentials ? { credentials } : {}),
61
+ });
62
+ if (!res.ok) {
63
+ const detail = await res.text().catch(() => '');
64
+ throw new Error(`[diagnostics] ${init.method ?? 'GET'} ${path} -> ${res.status} ${detail}`);
65
+ }
66
+ return (await res.json()) as T;
67
+ }
68
+
69
+ async function byKeys(db: string, keys: string[]): Promise<RawDoc[]> {
70
+ const out: RawDoc[] = [];
71
+ const CHUNK = 500;
72
+ for (let i = 0; i < keys.length; i += CHUNK) {
73
+ const body = await get<{ rows: Array<{ doc?: RawDoc | null }> }>(
74
+ `${db}/_all_docs?include_docs=true`,
75
+ { method: 'POST', body: { keys: keys.slice(i, i + CHUNK) } }
76
+ );
77
+ for (const row of body.rows) if (row.doc) out.push(row.doc);
78
+ }
79
+ return out;
80
+ }
81
+
82
+ async function byPrefix(db: string, prefix: string): Promise<RawDoc[]> {
83
+ const q = new URLSearchParams({
84
+ include_docs: 'true',
85
+ startkey: JSON.stringify(prefix),
86
+ endkey: JSON.stringify(prefix + '￰'),
87
+ });
88
+ const body = await get<{ rows: Array<{ doc?: RawDoc }> }>(`${db}/_all_docs?${q}`);
89
+ return body.rows.map((r) => r.doc).filter((d): d is RawDoc => !!d);
90
+ }
91
+
92
+ return { base, get, byKeys, byPrefix };
93
+ }
94
+
95
+ /** Card ids the user has any trace of: history, pending schedule, or session ELO events. */
96
+ function touchedCardIds(docs: RawDoc[]): string[] {
97
+ const ids = new Set<string>();
98
+ for (const d of docs) {
99
+ if (d._id.startsWith('cardH') && typeof d.cardID === 'string') ids.add(d.cardID);
100
+ else if (d._id.startsWith('card_review_') && typeof d.cardId === 'string') ids.add(d.cardId);
101
+ else if (d._id.startsWith('SESSION::') && Array.isArray(d.eloEvents)) {
102
+ for (const e of d.eloEvents as Array<{ cardId?: string }>) if (e.cardId) ids.add(e.cardId);
103
+ }
104
+ }
105
+ return [...ids];
106
+ }
107
+
108
+ /**
109
+ * Read one learner's records for one course into a {@link LearnerDump}: the
110
+ * whole user DB, its tombstones, and (by default) the course cards the user
111
+ * has touched, with their displayable data and tags. Needs admin rights on
112
+ * the couch, via basic auth or the browser's session cookie.
113
+ */
114
+ export async function fetchLearnerDump(opts: FetchLearnerDumpOptions): Promise<LearnerDump> {
115
+ const couch = couchReader(opts);
116
+ const dbName = userDbName(opts.username);
117
+ const fetchedAt = new Date().toISOString();
118
+
119
+ const info = await couch.get<unknown>(dbName);
120
+
121
+ const q = new URLSearchParams({ include_docs: 'true' });
122
+ if (opts.attachments) q.set('attachments', 'true');
123
+ const all = await couch.get<{ rows: Array<{ doc?: RawDoc }> }>(`${dbName}/_all_docs?${q}`);
124
+ const docs = all.rows.map((r) => r.doc).filter((d): d is RawDoc => !!d);
125
+
126
+ const changes = await couch.get<{
127
+ results: Array<{
128
+ id: string;
129
+ seq: string | number;
130
+ deleted?: boolean;
131
+ changes: Array<{ rev: string }>;
132
+ }>;
133
+ }>(`${dbName}/_changes?style=main_only`);
134
+ const tombstones = changes.results
135
+ .filter((c) => c.deleted)
136
+ .map((c) => ({ id: c.id, rev: c.changes[0]?.rev, seq: Number(String(c.seq).split('-')[0]) }));
137
+
138
+ const scope = opts.cards ?? 'touched';
139
+ let course: CourseSlice | undefined;
140
+ if (scope !== 'none') {
141
+ const courseDb = `coursedb-${opts.courseId}`;
142
+ let cards: RawDoc[];
143
+ if (scope === 'all') {
144
+ const found = await couch.get<{ docs: RawDoc[] }>(`${courseDb}/_find`, {
145
+ method: 'POST',
146
+ body: { selector: { docType: 'CARD' }, limit: 1_000_000 },
147
+ });
148
+ cards = found.docs;
149
+ } else {
150
+ cards = await couch.byKeys(courseDb, touchedCardIds(docs));
151
+ }
152
+ const cardIds = new Set(cards.map((c) => c._id));
153
+ const ddIds = new Set<string>();
154
+ for (const c of cards) {
155
+ for (const id of (c.id_displayable_data as string[] | undefined) ?? []) ddIds.add(id);
156
+ }
157
+ const displayableData = await couch.byKeys(courseDb, [...ddIds]);
158
+ const tags = (await couch.byPrefix(courseDb, 'TAG'))
159
+ .map((t) => {
160
+ const tagged = Array.isArray(t.taggedCards) ? (t.taggedCards as string[]) : [];
161
+ return {
162
+ ...t,
163
+ taggedCount: tagged.length,
164
+ taggedCards: scope === 'all' ? tagged : tagged.filter((id) => cardIds.has(id)),
165
+ };
166
+ })
167
+ .filter((t) => scope === 'all' || t.taggedCards.length > 0);
168
+
169
+ course = {
170
+ courseId: opts.courseId,
171
+ source: `${couch.base}/${courseDb}`,
172
+ scope,
173
+ cards,
174
+ displayableData,
175
+ tags,
176
+ } as unknown as CourseSlice;
177
+ }
178
+
179
+ return {
180
+ formatVersion: 1,
181
+ username: opts.username,
182
+ dbName,
183
+ source: couch.base,
184
+ fetchedAt,
185
+ courseId: opts.courseId,
186
+ info,
187
+ docs,
188
+ tombstones,
189
+ ...(course ? { course } : {}),
190
+ };
191
+ }
@@ -0,0 +1,242 @@
1
+ /**
2
+ * Plain-text renderings of derivations, for pasting into an LLM or a note.
3
+ * Every admin view that shows something should be able to hand it out as
4
+ * text; these are those texts. Also the shared number formatting.
5
+ */
6
+ import type { StudySessionRunCardTrail, StudySessionRunSummary } from '../core/types/studySession';
7
+ import {
8
+ shortTag,
9
+ type DiagnosticsInterpreters,
10
+ type ResponseEloDelta,
11
+ type SessionDetail,
12
+ type ServedTagStat,
13
+ type EloLedger,
14
+ } from './derive';
15
+
16
+ /** Signed, at most one decimal; `—` for null. */
17
+ export function fmtDelta(d: number | null): string {
18
+ if (d === null) return '—';
19
+ if (d === 0) return '0';
20
+ const v = Number.isInteger(d) ? d : Number(d.toFixed(1));
21
+ return v > 0 ? `+${v}` : String(v);
22
+ }
23
+
24
+ /** 45s, 3m20s, 1.5h. */
25
+ export function fmtDuration(seconds: number): string {
26
+ const s = Math.max(0, Math.round(seconds));
27
+ if (s < 60) return `${s}s`;
28
+ const m = Math.floor(s / 60);
29
+ if (m < 60) return s % 60 ? `${m}m${s % 60}s` : `${m}m`;
30
+ return `${(m / 60).toFixed(1)}h`;
31
+ }
32
+
33
+ export function fmtAnswer(a: unknown, max = 40): string {
34
+ if (a == null) return '';
35
+ if (typeof a === 'string' || typeof a === 'number') return String(a);
36
+ try {
37
+ const s = JSON.stringify(a);
38
+ return s.length > max ? `${s.slice(0, max)}…` : s;
39
+ } catch {
40
+ return String(a);
41
+ }
42
+ }
43
+
44
+ function fmtScore(n: number): string {
45
+ return Math.abs(n) >= 0.01 || n === 0 ? n.toFixed(2) : n.toExponential(1);
46
+ }
47
+
48
+ function trailText(label: string, t: StudySessionRunCardTrail): string[] {
49
+ const lines = [
50
+ ` ${label}: ${t.cardId} (${t.origin}, ${t.generator ?? '?'}) final ${fmtScore(t.score)}`,
51
+ ];
52
+ for (const p of t.trail) {
53
+ lines.push(` ${p.action} ${p.strategyName} → ${fmtScore(p.score)}: ${p.reason}`);
54
+ }
55
+ return lines;
56
+ }
57
+
58
+ /** One run as a compact text block. */
59
+ export function runText(run: StudySessionRunSummary): string {
60
+ const L: string[] = [];
61
+ L.push(
62
+ `RUN ${run.label}${run.mode ? ` [${run.mode}]` : ''} @ ${run.at}` +
63
+ ` — generated ${run.generatedCount} → selected ${run.finalCount}` +
64
+ ` (${run.newSelected} new, ${run.reviewsSelected} review)` +
65
+ (run.generatedCount > 0 && run.finalCount === 0 ? ' ⚠ nothing survived' : '')
66
+ );
67
+ if (typeof run.userElo === 'number') L.push(` userElo: ${Math.round(run.userElo)}`);
68
+ if (run.generators?.length) {
69
+ L.push(' generators:');
70
+ for (const g of run.generators) {
71
+ L.push(
72
+ ` - ${g.name}: ${g.cardCount} cards (${g.newCount} new, ${g.reviewCount} review),` +
73
+ ` topScore ${g.topScore.toFixed(2)}`
74
+ );
75
+ }
76
+ }
77
+ if (run.filters?.length) {
78
+ L.push(' filters:');
79
+ for (const f of run.filters) {
80
+ L.push(
81
+ ` - ${f.name}: +${f.boosted} boosted, -${f.penalized} penalized,` +
82
+ ` ${f.passed} passed, ${f.removed} removed`
83
+ );
84
+ }
85
+ }
86
+ if (run.hints) L.push(` hints: ${JSON.stringify(run.hints)}`);
87
+ if (run.cards?.length) {
88
+ L.push(' selection (✓ selected, · runner-up):');
89
+ for (const c of run.cards) {
90
+ L.push(
91
+ ` ${c.selected ? '✓' : '·'} ${c.cardId} (${c.origin}, ${c.generator ?? '?'}) ${fmtScore(c.score)}`
92
+ );
93
+ }
94
+ }
95
+ if (run.unselectedNew?.nextInLine)
96
+ L.push(...trailText('next new in line', run.unselectedNew.nextInLine));
97
+ if (run.unselectedNew?.topGenerated) {
98
+ L.push(...trailText('top-generated new (sunk)', run.unselectedNew.topGenerated));
99
+ }
100
+ if (run.discardedTail) {
101
+ const t = run.discardedTail;
102
+ L.push(
103
+ ` discardedTail: ${t.count} cards` +
104
+ (t.scoreRange
105
+ ? ` · score [${t.scoreRange[0].toFixed(2)}, ${t.scoreRange[1].toFixed(2)}]`
106
+ : '') +
107
+ (t.eloRange ? ` · elo [${Math.round(t.eloRange[0])}, ${Math.round(t.eloRange[1])}]` : '')
108
+ );
109
+ if (t.note) L.push(` ${t.note}`);
110
+ }
111
+ return L.join('\n');
112
+ }
113
+
114
+ /** Per-tag ELO deltas worth showing inline: scored, non-zero, at most four. */
115
+ export function scoredTagDeltas(elo: ResponseEloDelta): ResponseEloDelta['tags'] {
116
+ return elo.tags.filter((t) => t.score !== null && t.delta !== 0).slice(0, 4);
117
+ }
118
+
119
+ function eloSuffix(elo: ResponseEloDelta | undefined, interp?: DiagnosticsInterpreters): string {
120
+ if (!elo) return '';
121
+ const g = `ELO g:${elo.global.before}→${elo.global.after} (${fmtDelta(elo.global.delta)})`;
122
+ const tags = scoredTagDeltas(elo).map((t) => `${shortTag(interp, t.tag)}:${fmtDelta(t.delta)}`);
123
+ return ` ${g}${tags.length ? ` | ${tags.join(' ')}` : ''}`;
124
+ }
125
+
126
+ function clock(iso: string): string {
127
+ const d = new Date(iso);
128
+ return Number.isNaN(d.getTime()) ? iso : d.toISOString().slice(11, 19);
129
+ }
130
+
131
+ /**
132
+ * A whole session as plain text, led by a legend so the numbers read without
133
+ * the UI.
134
+ */
135
+ export function sessionText(
136
+ username: string,
137
+ detail: SessionDetail,
138
+ extras: { servedTags?: ServedTagStat[]; eloLedger?: EloLedger | null } = {},
139
+ interp?: DiagnosticsInterpreters
140
+ ): string {
141
+ const s = detail.summary;
142
+ const doc = s.doc;
143
+ const responses = detail.timeline.filter((e) => e.kind === 'response').length;
144
+ const L: string[] = [];
145
+
146
+ L.push(`# Study session ${doc.sessionId} — user ${username}`);
147
+ L.push('');
148
+ L.push('## Legend');
149
+ L.push('- The TIMELINE is one time-ordered stream: RUN lines are pipeline (re)plans;');
150
+ L.push(' the lines between them are card responses in the order presented.');
151
+ L.push('- RUN "generated N → selected M (a new, b review)": the pipeline produced N');
152
+ L.push(' candidates and chose M. "nothing survived" = generated > 0 but 0 selected.');
153
+ L.push(' Bootstrap runs fire before card #1; replans are interleaved by time.');
154
+ L.push("- generators: each source's contribution. filters: how each reshaped scores.");
155
+ L.push(' hints: the ReplanHints the navigator was told (_label = replan reason).');
156
+ L.push(' selection: the chosen cards and top runners-up. "next new in line" / "top-generated');
157
+ L.push(' new (sunk)": the unselected new cards worth explaining, with each score change.');
158
+ L.push(' Prescribed and hint-required cards count as origin "unknown" (known miscount).');
159
+ L.push('- RESP "✓/✗ type <cardId> [tags] Ts (attempt k) \'answer\'": one presentation and');
160
+ L.push(' its outcome. A trailing "ELO g:before→after (Δ) | tag:Δ …" is the exchange it');
161
+ L.push(' produced. Only first attempts move ELO.');
162
+ L.push('');
163
+
164
+ L.push('## Headline');
165
+ L.push(`- status: ${doc.status}`);
166
+ L.push(`- start: ${doc.startTime}${doc.endTime ? ` · end: ${doc.endTime}` : ''}`);
167
+ L.push(
168
+ `- clock: ${s.durationSeconds ?? '—'}s of ${doc.plannedSeconds}s planned` +
169
+ (doc.tally ? ` · ${doc.tally.secondsRemaining}s remaining` : '')
170
+ );
171
+ if (doc.tally) {
172
+ L.push(
173
+ `- tally: ${doc.tally.cardsPresented} cards, ${doc.tally.responses} responses` +
174
+ ` (${doc.tally.correct} correct / ${doc.tally.incorrect} incorrect)` +
175
+ ` · failedQ remaining ${doc.tally.failedQRemaining}`
176
+ );
177
+ }
178
+ L.push(`- flags: ${s.flags.length ? s.flags.join(', ') : 'none'}`);
179
+ L.push(
180
+ `- config: batchLimit ${doc.config?.defaultBatchLimit ?? '?'}, ${doc.config?.sourceCount ?? '?'} source(s)` +
181
+ `, opening queues supply ${doc.initialQueues?.supplyQ ?? '?'} / failed ${doc.initialQueues?.failedQ ?? '?'}`
182
+ );
183
+ if (detail.responsesMissing) {
184
+ L.push(
185
+ `- ⚠ responsesMissing: tally claims ${doc.tally?.responses} responses but only` +
186
+ ` ${responses} stamped records were found.`
187
+ );
188
+ }
189
+ L.push('');
190
+
191
+ if (s.state.length) {
192
+ L.push('## Learner state (start → end, Δ)');
193
+ for (const r of s.state)
194
+ L.push(`- ${r.label}: ${r.from ?? '—'} → ${r.to ?? '—'} (${fmtDelta(r.delta)})`);
195
+ L.push('');
196
+ }
197
+
198
+ L.push('## Session hints');
199
+ L.push(`- at open: ${doc.config?.initHints ? JSON.stringify(doc.config.initHints) : 'none'}`);
200
+ L.push(`- at close: ${doc.finalHints ? JSON.stringify(doc.finalHints) : 'none'}`);
201
+ L.push('');
202
+
203
+ if (extras.servedTags?.length) {
204
+ L.push('## Served tags');
205
+ for (const t of extras.servedTags) {
206
+ L.push(
207
+ `- ${t.tag}: ${t.responses} resp / ${t.cards} card(s)` +
208
+ `, acc ${t.accuracy === null ? 'n/a' : `${Math.round(t.accuracy * 100)}%`}` +
209
+ ` (${t.correct}✓/${t.incorrect}✗), ${(t.totalTimeMs / 1000).toFixed(1)}s`
210
+ );
211
+ }
212
+ L.push('');
213
+ }
214
+
215
+ const led = extras.eloLedger;
216
+ if (led) {
217
+ L.push('## ELO ledger (learner global)');
218
+ L.push(
219
+ `- net ${fmtDelta(led.net)} across ${led.count} exchange(s)` +
220
+ ` · gained ${fmtDelta(led.gained)} over ${led.wins} win(s)` +
221
+ ` · lost ${fmtDelta(led.lost)} over ${led.losses} loss(es)`
222
+ );
223
+ L.push('');
224
+ }
225
+
226
+ L.push(`## Timeline (${detail.timeline.length} entries)`);
227
+ for (const e of detail.timeline) {
228
+ if (e.kind === 'run') {
229
+ L.push(runText(e.run));
230
+ continue;
231
+ }
232
+ const mark = e.isCorrect === true ? '✓' : e.isCorrect === false ? '✗' : '·';
233
+ const tags = e.tags.length ? ` [${e.tags.join(', ')}]` : '';
234
+ const attempt = e.priorAttempts ? ` (attempt ${e.priorAttempts + 1})` : '';
235
+ const ans = e.userAnswer != null ? ` '${fmtAnswer(e.userAnswer)}'` : '';
236
+ L.push(
237
+ `RESP ${clock(e.at)} ${mark} ${e.questionType ?? 'card'} ${e.cardId}${tags}` +
238
+ ` — ${(e.timeSpentMs / 1000).toFixed(1)}s${attempt}${ans}${eloSuffix(e.elo, interp)}`
239
+ );
240
+ }
241
+ return L.join('\n');
242
+ }
@@ -7,13 +7,10 @@ import {
7
7
  CourseDBInterface,
8
8
  DataLayerProvider,
9
9
  UserDBInterface,
10
- UserDBReader,
11
10
  } from '../../core/interfaces';
12
11
  import { logger } from '../../util/logger';
13
12
  import { initializeDataDirectory } from '../../util/dataDirectory';
14
13
 
15
- import { getLoggedInUsername } from './auth';
16
-
17
14
  import { AdminDB } from './adminDB';
18
15
  import { StudentClassroomDB, TeacherClassroomDB } from './classroomDB';
19
16
  import { CourseDB, CoursesDB } from './courseDB';
@@ -115,26 +112,6 @@ export class CouchDataLayerProvider implements DataLayerProvider {
115
112
  return new AdminDB();
116
113
  }
117
114
 
118
- async createUserReaderForUser(targetUsername: string): Promise<UserDBReader> {
119
- // Security check: only admin can access other users' data
120
- const requestingUsername = await getLoggedInUsername();
121
- if (requestingUsername !== 'admin') {
122
- throw new Error('Unauthorized: Only admin users can access other users\' data');
123
- }
124
-
125
- logger.info(`Admin user '${requestingUsername}' requesting UserDBReader for '${targetUsername}'`);
126
-
127
- // Create a new sync strategy for the target user
128
- const syncStrategy = new CouchDBSyncStrategy();
129
-
130
- // Create a BaseUser instance for the target user
131
- // Note: This creates a read-capable user instance without affecting the current session
132
- const targetUserDB = await BaseUser.instance(syncStrategy, targetUsername);
133
-
134
- // Return as UserDBReader (which BaseUser implements since UserDBInterface extends UserDBReader)
135
- return targetUserDB as UserDBReader;
136
- }
137
-
138
115
  isReadOnly(): boolean {
139
116
  return false;
140
117
  }
@@ -8,7 +8,6 @@ import {
8
8
  CourseDBInterface,
9
9
  DataLayerProvider,
10
10
  UserDBInterface,
11
- UserDBReader,
12
11
  } from '../../core/interfaces';
13
12
  import { logger } from '../../util/logger';
14
13
  import { StaticCourseManifest } from '../../util/packer/types';
@@ -152,16 +151,6 @@ export class StaticDataLayerProvider implements DataLayerProvider {
152
151
  throw new Error('Admin functions not supported in static mode');
153
152
  }
154
153
 
155
- async createUserReaderForUser(targetUsername: string): Promise<UserDBReader> {
156
- logger.warn(`StaticDataLayerProvider: Multi-user access not supported in static mode`);
157
- logger.warn(`Request: trying to access data for ${targetUsername}`);
158
- logger.warn(`Returning current user's data instead`);
159
-
160
- // In static mode, just return the current user's DB as a reader
161
- // This is safe since static mode is typically for development/testing
162
- return this.getUserDB() as UserDBReader;
163
- }
164
-
165
154
  isReadOnly(): boolean {
166
155
  return true;
167
156
  }
@@ -21,6 +21,8 @@ import {
21
21
  type SessionStateSnapshot,
22
22
  type SessionStateSnapshotProvider,
23
23
  type StudySessionDoc,
24
+ type StudySessionRunCard,
25
+ type StudySessionRunCardTrail,
24
26
  type StudySessionRunSummary,
25
27
  } from '@db/core/types/studySession';
26
28
  import { recordUserOutcome } from '@db/core/orchestration/recording';
@@ -33,6 +35,7 @@ import {
33
35
  setDebugSessionId,
34
36
  drainCapturedRuns,
35
37
  } from '@db/core/navigators';
38
+ import type { PipelineRunReport, RunReportCard } from '@db/core/navigators';
36
39
  import { ReplanHints } from '@db/core/navigators/generators/types';
37
40
  import { mergeHints } from '@db/core/navigators/Pipeline';
38
41
  import { SourceMixer, QuotaRoundRobinMixer, SourceBatch } from './SourceMixer';
@@ -222,6 +225,54 @@ export type OutcomeObserver = (
222
225
  controls: SessionControls
223
226
  ) => void | Promise<void>;
224
227
 
228
+ /** Unselected cards persisted per run, after the selected ones. */
229
+ const PERSISTED_RUNNERS_UP = 5;
230
+
231
+ /** 4 significant figures: keeps 6.4e-7 distinguishable from 0 without 17-digit floats. */
232
+ function sig4(x: number): number {
233
+ return Number(x.toPrecision(4));
234
+ }
235
+
236
+ function toRunCard(c: RunReportCard): StudySessionRunCard {
237
+ return {
238
+ cardId: c.cardId,
239
+ origin: c.origin,
240
+ ...(c.generator ? { generator: c.generator } : {}),
241
+ score: sig4(c.finalScore),
242
+ selected: c.selected,
243
+ };
244
+ }
245
+
246
+ function toRunCardTrail(c: RunReportCard): StudySessionRunCardTrail {
247
+ return {
248
+ ...toRunCard(c),
249
+ trail: c.provenance
250
+ .filter((p) => p.action !== 'passed')
251
+ .map((p) => ({
252
+ strategyName: p.strategyName,
253
+ action: p.action,
254
+ score: sig4(p.score),
255
+ reason: p.reason,
256
+ })),
257
+ };
258
+ }
259
+
260
+ /** `run.cards` is selected-then-near-misses, each in score order. */
261
+ function persistedRunCards(run: PipelineRunReport): StudySessionRunCard[] {
262
+ const selected = run.cards.filter((c) => c.selected);
263
+ const runnersUp = run.cards.filter((c) => !c.selected).slice(0, PERSISTED_RUNNERS_UP);
264
+ return [...selected, ...runnersUp].map(toRunCard);
265
+ }
266
+
267
+ function persistedUnselectedNew(
268
+ u: NonNullable<PipelineRunReport['unselectedNew']>
269
+ ): StudySessionRunSummary['unselectedNew'] {
270
+ return {
271
+ ...(u.nextInLine ? { nextInLine: toRunCardTrail(u.nextInLine) } : {}),
272
+ ...(u.topGenerated ? { topGenerated: toRunCardTrail(u.topGenerated) } : {}),
273
+ };
274
+ }
275
+
225
276
  interface SessionServices {
226
277
  response: ResponseProcessor;
227
278
  }
@@ -575,13 +626,16 @@ export class SessionController<TView = unknown> extends Loggable {
575
626
  newSelected: run.newSelected,
576
627
  // Compact detail projected off the full report so a persisted run is
577
628
  // self-explanatory once the in-memory ring buffer has rolled over.
578
- // Per-card provenance (`run.cards`) is intentionally left out — it's
579
- // the dominant memory cost and not worth persisting per run.
629
+ // Per-card provenance is the dominant cost, so it's kept only for the
630
+ // (at most two) `unselectedNew` cards, and only its score-changing
631
+ // entries. Everything else is ids and scores.
580
632
  ...(typeof run.userElo === 'number' ? { userElo: run.userElo } : {}),
581
633
  ...(run.generators ? { generators: run.generators } : {}),
582
634
  ...(run.filters ? { filters: run.filters } : {}),
583
635
  ...(run.hints ? { hints: run.hints } : {}),
584
636
  ...(run.discardedTail ? { discardedTail: run.discardedTail } : {}),
637
+ cards: persistedRunCards(run),
638
+ ...(run.unselectedNew ? { unselectedNew: persistedUnselectedNew(run.unselectedNew) } : {}),
585
639
  });
586
640
  }
587
641
  }
package/tsup.config.ts CHANGED
@@ -8,6 +8,7 @@ export default defineConfig({
8
8
  'src/impl/couch/index.ts',
9
9
  'src/impl/static/index.ts',
10
10
  'src/util/packer/index.ts',
11
+ 'src/diagnostics/index.ts',
11
12
  ],
12
13
  format: ['cjs', 'esm'],
13
14
  dts: true,