@vue-skuilder/db 0.2.27 → 0.2.29

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 (82) 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-B6FrSihy.d.cts} +282 -99
  4. package/dist/{contentSource-D3c1fMAk.d.cts → contentSource-CqJmbOZN.d.ts} +282 -99
  5. package/dist/core/index.d.cts +16 -92
  6. package/dist/core/index.d.ts +16 -92
  7. package/dist/core/index.js +607 -179
  8. package/dist/core/index.js.map +1 -1
  9. package/dist/core/index.mjs +606 -179
  10. package/dist/core/index.mjs.map +1 -1
  11. package/dist/{dataLayerProvider-DaAootVV.d.ts → dataLayerProvider-B9_UCvkR.d.ts} +2 -8
  12. package/dist/{dataLayerProvider-CeLiFbHv.d.cts → dataLayerProvider-DUxDqMtZ.d.cts} +2 -8
  13. package/dist/diagnostics/index.d.cts +443 -0
  14. package/dist/diagnostics/index.d.ts +443 -0
  15. package/dist/diagnostics/index.js +932 -0
  16. package/dist/diagnostics/index.js.map +1 -0
  17. package/dist/diagnostics/index.mjs +881 -0
  18. package/dist/diagnostics/index.mjs.map +1 -0
  19. package/dist/impl/couch/index.d.cts +13 -3
  20. package/dist/impl/couch/index.d.ts +13 -3
  21. package/dist/impl/couch/index.js +605 -179
  22. package/dist/impl/couch/index.js.map +1 -1
  23. package/dist/impl/couch/index.mjs +605 -179
  24. package/dist/impl/couch/index.mjs.map +1 -1
  25. package/dist/impl/static/index.d.cts +11 -5
  26. package/dist/impl/static/index.d.ts +11 -5
  27. package/dist/impl/static/index.js +602 -185
  28. package/dist/impl/static/index.js.map +1 -1
  29. package/dist/impl/static/index.mjs +602 -185
  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 +73 -11
  34. package/dist/index.d.ts +73 -11
  35. package/dist/index.js +696 -200
  36. package/dist/index.js.map +1 -1
  37. package/dist/index.mjs +683 -200
  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/contentSource.ts +7 -0
  47. package/src/core/interfaces/dataLayerProvider.ts +3 -8
  48. package/src/core/navigators/Pipeline.ts +149 -14
  49. package/src/core/navigators/PipelineAssembler.ts +19 -40
  50. package/src/core/navigators/PipelineDebugger.ts +74 -17
  51. package/src/core/navigators/SrsDebugger.ts +37 -12
  52. package/src/core/navigators/defaults.ts +29 -5
  53. package/src/core/navigators/filters/WeightedFilter.ts +5 -1
  54. package/src/core/navigators/filters/eloDistance.ts +261 -76
  55. package/src/core/navigators/filters/hierarchyDefinition.ts +5 -1
  56. package/src/core/navigators/filters/index.ts +2 -2
  57. package/src/core/navigators/filters/interferenceMitigator.ts +5 -1
  58. package/src/core/navigators/filters/relativePriority.ts +5 -1
  59. package/src/core/navigators/filters/types.ts +24 -1
  60. package/src/core/navigators/filters/userTagPreference.ts +5 -1
  61. package/src/core/navigators/generators/elo.ts +23 -53
  62. package/src/core/navigators/generators/srs.ts +27 -124
  63. package/src/core/navigators/index.ts +32 -5
  64. package/src/core/navigators/pipelinePlan.ts +245 -0
  65. package/src/core/navigators/regulators.ts +230 -0
  66. package/src/core/types/studySession.ts +40 -0
  67. package/src/diagnostics/dataset.ts +242 -0
  68. package/src/diagnostics/derive.ts +555 -0
  69. package/src/diagnostics/index.ts +27 -0
  70. package/src/diagnostics/loader.ts +194 -0
  71. package/src/diagnostics/pipeline.ts +236 -0
  72. package/src/diagnostics/text.ts +265 -0
  73. package/src/impl/couch/PouchDataLayerProvider.ts +0 -23
  74. package/src/impl/couch/courseDB.ts +13 -0
  75. package/src/impl/static/StaticDataLayerProvider.ts +0 -11
  76. package/src/impl/static/courseDB.ts +9 -0
  77. package/src/index.ts +4 -0
  78. package/src/study/SessionController.ts +76 -2
  79. package/src/study/SessionOverlay.ts +7 -4
  80. package/tests/core/navigators/PipelineAssembler.test.ts +20 -5
  81. package/tests/core/navigators/eloDistanceFilter.test.ts +9 -9
  82. package/tsup.config.ts +1 -0
@@ -0,0 +1,194 @@
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, plus the course's strategy
112
+ * docs. Needs admin rights on the couch, via basic auth or the browser's
113
+ * session cookie.
114
+ */
115
+ export async function fetchLearnerDump(opts: FetchLearnerDumpOptions): Promise<LearnerDump> {
116
+ const couch = couchReader(opts);
117
+ const dbName = userDbName(opts.username);
118
+ const fetchedAt = new Date().toISOString();
119
+
120
+ const info = await couch.get<unknown>(dbName);
121
+
122
+ const q = new URLSearchParams({ include_docs: 'true' });
123
+ if (opts.attachments) q.set('attachments', 'true');
124
+ const all = await couch.get<{ rows: Array<{ doc?: RawDoc }> }>(`${dbName}/_all_docs?${q}`);
125
+ const docs = all.rows.map((r) => r.doc).filter((d): d is RawDoc => !!d);
126
+
127
+ const changes = await couch.get<{
128
+ results: Array<{
129
+ id: string;
130
+ seq: string | number;
131
+ deleted?: boolean;
132
+ changes: Array<{ rev: string }>;
133
+ }>;
134
+ }>(`${dbName}/_changes?style=main_only`);
135
+ const tombstones = changes.results
136
+ .filter((c) => c.deleted)
137
+ .map((c) => ({ id: c.id, rev: c.changes[0]?.rev, seq: Number(String(c.seq).split('-')[0]) }));
138
+
139
+ const scope = opts.cards ?? 'touched';
140
+ let course: CourseSlice | undefined;
141
+ if (scope !== 'none') {
142
+ const courseDb = `coursedb-${opts.courseId}`;
143
+ let cards: RawDoc[];
144
+ if (scope === 'all') {
145
+ const found = await couch.get<{ docs: RawDoc[] }>(`${courseDb}/_find`, {
146
+ method: 'POST',
147
+ body: { selector: { docType: 'CARD' }, limit: 1_000_000 },
148
+ });
149
+ cards = found.docs;
150
+ } else {
151
+ cards = await couch.byKeys(courseDb, touchedCardIds(docs));
152
+ }
153
+ const cardIds = new Set(cards.map((c) => c._id));
154
+ const ddIds = new Set<string>();
155
+ for (const c of cards) {
156
+ for (const id of (c.id_displayable_data as string[] | undefined) ?? []) ddIds.add(id);
157
+ }
158
+ const displayableData = await couch.byKeys(courseDb, [...ddIds]);
159
+ const tags = (await couch.byPrefix(courseDb, 'TAG'))
160
+ .map((t) => {
161
+ const tagged = Array.isArray(t.taggedCards) ? (t.taggedCards as string[]) : [];
162
+ return {
163
+ ...t,
164
+ taggedCount: tagged.length,
165
+ taggedCards: scope === 'all' ? tagged : tagged.filter((id) => cardIds.has(id)),
166
+ };
167
+ })
168
+ .filter((t) => scope === 'all' || t.taggedCards.length > 0);
169
+ const strategies = await couch.byPrefix(courseDb, 'NAVIGATION_STRATEGY');
170
+
171
+ course = {
172
+ courseId: opts.courseId,
173
+ source: `${couch.base}/${courseDb}`,
174
+ scope,
175
+ cards,
176
+ displayableData,
177
+ tags,
178
+ strategies,
179
+ } as unknown as CourseSlice;
180
+ }
181
+
182
+ return {
183
+ formatVersion: 1,
184
+ username: opts.username,
185
+ dbName,
186
+ source: couch.base,
187
+ fetchedAt,
188
+ courseId: opts.courseId,
189
+ info,
190
+ docs,
191
+ tombstones,
192
+ ...(course ? { course } : {}),
193
+ };
194
+ }
@@ -0,0 +1,236 @@
1
+ import type { DatasetRecord, LearnerDataset } from './dataset';
2
+ import type { FilterKind } from '../core/navigators/filters/types';
3
+ import type { RegulatorName, RegulatorReading } from '../core/navigators/regulators';
4
+
5
+ // ============================================================================
6
+ // Pipeline run stats
7
+ // ============================================================================
8
+ //
9
+ // What each pipeline piece did across a learner's persisted runs, keyed by the
10
+ // names runs report generators and filters under. Those are the strategy docs'
11
+ // names, so these join to a `PipelinePlan` (`@vue-skuilder/db`) by name.
12
+ //
13
+ // Selection and outcome counts need runs that persist their selected cards
14
+ // (`StudySessionRunSummary.cards`, 0.2.28+). Older runs contribute only their
15
+ // generator and filter summaries.
16
+ //
17
+ // Generator new/review counts: before 0.2.29 the ELO generator's cards were
18
+ // counted as neither (the counts went by reason text), so means over older
19
+ // runs undercount `new`.
20
+ //
21
+ // ============================================================================
22
+
23
+ /** One generator across persisted runs. */
24
+ export interface GeneratorRunStat {
25
+ /** The name runs report it under (its strategy doc's name). */
26
+ name: string;
27
+ /** Runs it emitted at least one candidate in. */
28
+ runs: number;
29
+ /** Mean candidates per run, over the runs it appeared in. */
30
+ meanCards: number;
31
+ meanNew: number;
32
+ meanReview: number;
33
+ topScoreMax: number;
34
+ /** Top score in the most recent run it appeared in. */
35
+ topScoreLast: number;
36
+ /** Selected cards it originated (first provenance entry), over runs that persist selection. */
37
+ selected: number;
38
+ /** First attempts at those cards in the same session. */
39
+ firstAttempts: number;
40
+ firstAttemptsCorrect: number;
41
+ }
42
+
43
+ /** One filter across persisted runs: candidate counts summed over runs. */
44
+ export interface FilterRunStat {
45
+ name: string;
46
+ /** As recorded by the most recent run that recorded it (0.2.29+). */
47
+ kind?: FilterKind;
48
+ runs: number;
49
+ boosted: number;
50
+ penalized: number;
51
+ passed: number;
52
+ removed: number;
53
+ }
54
+
55
+ /** One regulator across persisted runs (0.2.29+). */
56
+ export interface RegulatorRunStat {
57
+ name: RegulatorName;
58
+ class: RegulatorReading['class'];
59
+ runs: number;
60
+ meanMultiplier: number;
61
+ maxMultiplier: number;
62
+ /** Runs where the multiplier was above 1. */
63
+ runsActive: number;
64
+ /** The most recent reading. */
65
+ last: RegulatorReading;
66
+ }
67
+
68
+ export interface PipelineRunStats {
69
+ sessions: number;
70
+ runs: number;
71
+ /** Runs that persist their selected cards. Selection and outcome counts cover only these. */
72
+ runsWithSelection: number;
73
+ firstRunAt?: string;
74
+ lastRunAt?: string;
75
+ /** Busiest first. */
76
+ generators: GeneratorRunStat[];
77
+ /** By name. */
78
+ filters: FilterRunStat[];
79
+ /** Empty before 0.2.29. */
80
+ regulators: RegulatorRunStat[];
81
+ /** Selected cards with no originating generator: cards forced in by `requireCards`. */
82
+ selectedUnattributed: number;
83
+ }
84
+
85
+ /** Aggregate a learner's persisted pipeline runs, optionally only sessions started at or after `since` (ISO). */
86
+ export function pipelineRunStats(
87
+ ds: LearnerDataset,
88
+ opts: { since?: string } = {}
89
+ ): PipelineRunStats {
90
+ const sessions = ds.sessions.filter((s) => !opts.since || s.startTime >= opts.since);
91
+
92
+ const recordsBySession = new Map<string, Array<{ cardId: string; record: DatasetRecord }>>();
93
+ for (const h of ds.cardHistories) {
94
+ for (const record of h.records) {
95
+ if (!record.sessionId) continue;
96
+ const list = recordsBySession.get(record.sessionId) ?? [];
97
+ list.push({ cardId: h.cardID, record });
98
+ recordsBySession.set(record.sessionId, list);
99
+ }
100
+ }
101
+
102
+ type GenAcc = Omit<GeneratorRunStat, 'meanCards' | 'meanNew' | 'meanReview'> & {
103
+ cards: number;
104
+ newCards: number;
105
+ reviewCards: number;
106
+ };
107
+ const gens = new Map<string, GenAcc>();
108
+ const gen = (name: string): GenAcc => {
109
+ let g = gens.get(name);
110
+ if (!g) {
111
+ g = {
112
+ name,
113
+ runs: 0,
114
+ cards: 0,
115
+ newCards: 0,
116
+ reviewCards: 0,
117
+ topScoreMax: 0,
118
+ topScoreLast: 0,
119
+ selected: 0,
120
+ firstAttempts: 0,
121
+ firstAttemptsCorrect: 0,
122
+ };
123
+ gens.set(name, g);
124
+ }
125
+ return g;
126
+ };
127
+ const filters = new Map<string, FilterRunStat>();
128
+ const regulators = new Map<RegulatorName, RegulatorRunStat & { sumMultiplier: number }>();
129
+
130
+ let runs = 0;
131
+ let runsWithSelection = 0;
132
+ let selectedUnattributed = 0;
133
+ let firstRunAt: string | undefined;
134
+ let lastRunAt: string | undefined;
135
+
136
+ for (const session of sessions) {
137
+ // A card selected by several runs is credited to the first run that chose it.
138
+ const originBySelectedCard = new Map<string, string>();
139
+
140
+ for (const run of session.runs ?? []) {
141
+ runs++;
142
+ if (!firstRunAt || run.at < firstRunAt) firstRunAt = run.at;
143
+ if (!lastRunAt || run.at > lastRunAt) lastRunAt = run.at;
144
+
145
+ for (const s of run.generators ?? []) {
146
+ const g = gen(s.name);
147
+ g.runs++;
148
+ g.cards += s.cardCount;
149
+ g.newCards += s.newCount;
150
+ g.reviewCards += s.reviewCount;
151
+ g.topScoreMax = Math.max(g.topScoreMax, s.topScore);
152
+ g.topScoreLast = s.topScore;
153
+ }
154
+
155
+ for (const f of run.filters ?? []) {
156
+ const acc = filters.get(f.name) ?? {
157
+ name: f.name,
158
+ runs: 0,
159
+ boosted: 0,
160
+ penalized: 0,
161
+ passed: 0,
162
+ removed: 0,
163
+ };
164
+ acc.runs++;
165
+ if (f.kind) acc.kind = f.kind;
166
+ acc.boosted += f.boosted;
167
+ acc.penalized += f.penalized;
168
+ acc.passed += f.passed;
169
+ acc.removed += f.removed;
170
+ filters.set(f.name, acc);
171
+ }
172
+
173
+ for (const r of run.regulators ?? []) {
174
+ const acc = regulators.get(r.name) ?? {
175
+ name: r.name,
176
+ class: r.class,
177
+ runs: 0,
178
+ meanMultiplier: 0,
179
+ maxMultiplier: 0,
180
+ runsActive: 0,
181
+ last: r,
182
+ sumMultiplier: 0,
183
+ };
184
+ acc.runs++;
185
+ acc.sumMultiplier += r.multiplier;
186
+ acc.maxMultiplier = Math.max(acc.maxMultiplier, r.multiplier);
187
+ if (r.multiplier > 1) acc.runsActive++;
188
+ acc.last = r;
189
+ regulators.set(r.name, acc);
190
+ }
191
+
192
+ if (run.cards) {
193
+ runsWithSelection++;
194
+ for (const c of run.cards) {
195
+ if (!c.selected) continue;
196
+ if (!c.generator) {
197
+ selectedUnattributed++;
198
+ continue;
199
+ }
200
+ gen(c.generator).selected++;
201
+ if (!originBySelectedCard.has(c.cardId)) originBySelectedCard.set(c.cardId, c.generator);
202
+ }
203
+ }
204
+ }
205
+
206
+ for (const { cardId, record } of recordsBySession.get(session.sessionId) ?? []) {
207
+ const origin = originBySelectedCard.get(cardId);
208
+ if (!origin || record.priorAttemps !== 0) continue;
209
+ const g = gen(origin);
210
+ g.firstAttempts++;
211
+ if (record.isCorrect === true) g.firstAttemptsCorrect++;
212
+ }
213
+ }
214
+
215
+ return {
216
+ sessions: sessions.length,
217
+ runs,
218
+ runsWithSelection,
219
+ firstRunAt,
220
+ lastRunAt,
221
+ generators: [...gens.values()]
222
+ .map(({ cards, newCards, reviewCards, ...g }) => ({
223
+ ...g,
224
+ meanCards: g.runs ? cards / g.runs : 0,
225
+ meanNew: g.runs ? newCards / g.runs : 0,
226
+ meanReview: g.runs ? reviewCards / g.runs : 0,
227
+ }))
228
+ .sort((a, b) => b.runs - a.runs || a.name.localeCompare(b.name)),
229
+ filters: [...filters.values()].sort((a, b) => a.name.localeCompare(b.name)),
230
+ regulators: [...regulators.values()].map(({ sumMultiplier, ...r }) => ({
231
+ ...r,
232
+ meanMultiplier: r.runs ? sumMultiplier / r.runs : 0,
233
+ })),
234
+ selectedUnattributed,
235
+ };
236
+ }
@@ -0,0 +1,265 @@
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 type { RegulatorReading } from '../core/navigators/regulators';
8
+ import {
9
+ shortTag,
10
+ type DiagnosticsInterpreters,
11
+ type ResponseEloDelta,
12
+ type SessionDetail,
13
+ type ServedTagStat,
14
+ type EloLedger,
15
+ } from './derive';
16
+
17
+ /** Signed, at most one decimal; `—` for null. */
18
+ export function fmtDelta(d: number | null): string {
19
+ if (d === null) return '—';
20
+ if (d === 0) return '0';
21
+ const v = Number.isInteger(d) ? d : Number(d.toFixed(1));
22
+ return v > 0 ? `+${v}` : String(v);
23
+ }
24
+
25
+ /** 45s, 3m20s, 1.5h. */
26
+ export function fmtDuration(seconds: number): string {
27
+ const s = Math.max(0, Math.round(seconds));
28
+ if (s < 60) return `${s}s`;
29
+ const m = Math.floor(s / 60);
30
+ if (m < 60) return s % 60 ? `${m}m${s % 60}s` : `${m}m`;
31
+ return `${(m / 60).toFixed(1)}h`;
32
+ }
33
+
34
+ export function fmtAnswer(a: unknown, max = 40): string {
35
+ if (a == null) return '';
36
+ if (typeof a === 'string' || typeof a === 'number') return String(a);
37
+ try {
38
+ const s = JSON.stringify(a);
39
+ return s.length > max ? `${s.slice(0, max)}…` : s;
40
+ } catch {
41
+ return String(a);
42
+ }
43
+ }
44
+
45
+ function fmtScore(n: number): string {
46
+ return Math.abs(n) >= 0.01 || n === 0 ? n.toFixed(2) : n.toExponential(1);
47
+ }
48
+
49
+ function trailText(label: string, t: StudySessionRunCardTrail): string[] {
50
+ const lines = [
51
+ ` ${label}: ${t.cardId} (${t.origin}, ${t.generator ?? '?'}) final ${fmtScore(t.score)}`,
52
+ ];
53
+ for (const p of t.trail) {
54
+ lines.push(` ${p.action} ${p.strategyName} → ${fmtScore(p.score)}: ${p.reason}`);
55
+ }
56
+ return lines;
57
+ }
58
+
59
+ /** One regulator reading as a line: its urgency, inputs, and multiplier. */
60
+ export function regulatorText(r: RegulatorReading): string {
61
+ const i = r.inputs;
62
+ if (r.name === 'review-mass') {
63
+ return (
64
+ `review mass ${r.urgency.toFixed(1)} over ${i.due ?? r.applied} due` +
65
+ ` (healthy ${i.healthyMass}) → ×${r.multiplier.toFixed(2)}`
66
+ );
67
+ }
68
+ const frozen = i.frozenHours ? `, ${i.frozenHours.toFixed(1)}h frozen` : '';
69
+ return (
70
+ `intake ${r.urgency.toFixed(1)}h since a new card${frozen};` +
71
+ ` ${i.eligibleNew ?? r.applied}/${i.newCandidates ?? '?'} new eligible → ×${r.multiplier.toFixed(2)}`
72
+ );
73
+ }
74
+
75
+ /** One run as a compact text block. */
76
+ export function runText(run: StudySessionRunSummary): string {
77
+ const L: string[] = [];
78
+ L.push(
79
+ `RUN ${run.label}${run.mode ? ` [${run.mode}]` : ''} @ ${run.at}` +
80
+ ` — generated ${run.generatedCount} → selected ${run.finalCount}` +
81
+ ` (${run.newSelected} new, ${run.reviewsSelected} review)` +
82
+ (run.generatedCount > 0 && run.finalCount === 0 ? ' ⚠ nothing survived' : '')
83
+ );
84
+ if (typeof run.userElo === 'number') L.push(` userElo: ${Math.round(run.userElo)}`);
85
+ if (run.generators?.length) {
86
+ L.push(' generators:');
87
+ for (const g of run.generators) {
88
+ L.push(
89
+ ` - ${g.name}: ${g.cardCount} cards (${g.newCount} new, ${g.reviewCount} review),` +
90
+ ` topScore ${g.topScore.toFixed(2)}`
91
+ );
92
+ }
93
+ }
94
+ if (run.filters?.length) {
95
+ L.push(' filters:');
96
+ for (const f of run.filters) {
97
+ L.push(
98
+ ` - ${f.name}${f.kind ? ` (${f.kind})` : ''}: +${f.boosted} boosted,` +
99
+ ` -${f.penalized} penalized, ${f.passed} passed, ${f.removed} removed`
100
+ );
101
+ }
102
+ }
103
+ if (run.regulators?.length) {
104
+ L.push(' regulators:');
105
+ for (const r of run.regulators) L.push(` - ${regulatorText(r)}`);
106
+ }
107
+ if (run.hints) L.push(` hints: ${JSON.stringify(run.hints)}`);
108
+ if (run.cards?.length) {
109
+ L.push(' selection (✓ selected, · runner-up):');
110
+ for (const c of run.cards) {
111
+ L.push(
112
+ ` ${c.selected ? '✓' : '·'} ${c.cardId} (${c.origin}, ${c.generator ?? '?'}) ${fmtScore(c.score)}`
113
+ );
114
+ }
115
+ }
116
+ if (run.unselectedNew?.nextInLine)
117
+ L.push(...trailText('next new in line', run.unselectedNew.nextInLine));
118
+ if (run.unselectedNew?.topGenerated) {
119
+ L.push(...trailText('top-generated new (sunk)', run.unselectedNew.topGenerated));
120
+ }
121
+ if (run.discardedTail) {
122
+ const t = run.discardedTail;
123
+ L.push(
124
+ ` discardedTail: ${t.count} cards` +
125
+ (t.scoreRange
126
+ ? ` · score [${t.scoreRange[0].toFixed(2)}, ${t.scoreRange[1].toFixed(2)}]`
127
+ : '') +
128
+ (t.eloRange ? ` · elo [${Math.round(t.eloRange[0])}, ${Math.round(t.eloRange[1])}]` : '')
129
+ );
130
+ if (t.note) L.push(` ${t.note}`);
131
+ }
132
+ return L.join('\n');
133
+ }
134
+
135
+ /** Per-tag ELO deltas worth showing inline: scored, non-zero, at most four. */
136
+ export function scoredTagDeltas(elo: ResponseEloDelta): ResponseEloDelta['tags'] {
137
+ return elo.tags.filter((t) => t.score !== null && t.delta !== 0).slice(0, 4);
138
+ }
139
+
140
+ function eloSuffix(elo: ResponseEloDelta | undefined, interp?: DiagnosticsInterpreters): string {
141
+ if (!elo) return '';
142
+ const g = `ELO g:${elo.global.before}→${elo.global.after} (${fmtDelta(elo.global.delta)})`;
143
+ const tags = scoredTagDeltas(elo).map((t) => `${shortTag(interp, t.tag)}:${fmtDelta(t.delta)}`);
144
+ return ` ${g}${tags.length ? ` | ${tags.join(' ')}` : ''}`;
145
+ }
146
+
147
+ function clock(iso: string): string {
148
+ const d = new Date(iso);
149
+ return Number.isNaN(d.getTime()) ? iso : d.toISOString().slice(11, 19);
150
+ }
151
+
152
+ /**
153
+ * A whole session as plain text, led by a legend so the numbers read without
154
+ * the UI.
155
+ */
156
+ export function sessionText(
157
+ username: string,
158
+ detail: SessionDetail,
159
+ extras: { servedTags?: ServedTagStat[]; eloLedger?: EloLedger | null } = {},
160
+ interp?: DiagnosticsInterpreters
161
+ ): string {
162
+ const s = detail.summary;
163
+ const doc = s.doc;
164
+ const responses = detail.timeline.filter((e) => e.kind === 'response').length;
165
+ const L: string[] = [];
166
+
167
+ L.push(`# Study session ${doc.sessionId} — user ${username}`);
168
+ L.push('');
169
+ L.push('## Legend');
170
+ L.push('- The TIMELINE is one time-ordered stream: RUN lines are pipeline (re)plans;');
171
+ L.push(' the lines between them are card responses in the order presented.');
172
+ L.push('- RUN "generated N → selected M (a new, b review)": the pipeline produced N');
173
+ L.push(' candidates and chose M. "nothing survived" = generated > 0 but 0 selected.');
174
+ L.push(' Bootstrap runs fire before card #1; replans are interleaved by time.');
175
+ L.push("- generators: each source's contribution. filters: how each reshaped scores");
176
+ L.push(' (gate: not ready yet; signal: preference). regulators: the pressure on each class,');
177
+ L.push(' review mass (due reviews by value) and intake (hours since a new card).');
178
+ L.push(' hints: the ReplanHints the navigator was told (_label = replan reason).');
179
+ L.push(' selection: the chosen cards and top runners-up. "next new in line" / "top-generated');
180
+ L.push(' new (sunk)": the unselected new cards worth explaining, with each score change.');
181
+ L.push(' Prescribed and hint-required cards count as origin "unknown" (known miscount).');
182
+ L.push('- RESP "✓/✗ type <cardId> [tags] Ts (attempt k) \'answer\'": one presentation and');
183
+ L.push(' its outcome. A trailing "ELO g:before→after (Δ) | tag:Δ …" is the exchange it');
184
+ L.push(' produced. Only first attempts move ELO.');
185
+ L.push('');
186
+
187
+ L.push('## Headline');
188
+ L.push(`- status: ${doc.status}`);
189
+ L.push(`- start: ${doc.startTime}${doc.endTime ? ` · end: ${doc.endTime}` : ''}`);
190
+ L.push(
191
+ `- clock: ${s.durationSeconds ?? '—'}s of ${doc.plannedSeconds}s planned` +
192
+ (doc.tally ? ` · ${doc.tally.secondsRemaining}s remaining` : '')
193
+ );
194
+ if (doc.tally) {
195
+ L.push(
196
+ `- tally: ${doc.tally.cardsPresented} cards, ${doc.tally.responses} responses` +
197
+ ` (${doc.tally.correct} correct / ${doc.tally.incorrect} incorrect)` +
198
+ ` · failedQ remaining ${doc.tally.failedQRemaining}`
199
+ );
200
+ }
201
+ L.push(`- flags: ${s.flags.length ? s.flags.join(', ') : 'none'}`);
202
+ L.push(
203
+ `- config: batchLimit ${doc.config?.defaultBatchLimit ?? '?'}, ${doc.config?.sourceCount ?? '?'} source(s)` +
204
+ `, opening queues supply ${doc.initialQueues?.supplyQ ?? '?'} / failed ${doc.initialQueues?.failedQ ?? '?'}`
205
+ );
206
+ if (detail.responsesMissing) {
207
+ L.push(
208
+ `- ⚠ responsesMissing: tally claims ${doc.tally?.responses} responses but only` +
209
+ ` ${responses} stamped records were found.`
210
+ );
211
+ }
212
+ L.push('');
213
+
214
+ if (s.state.length) {
215
+ L.push('## Learner state (start → end, Δ)');
216
+ for (const r of s.state)
217
+ L.push(`- ${r.label}: ${r.from ?? '—'} → ${r.to ?? '—'} (${fmtDelta(r.delta)})`);
218
+ L.push('');
219
+ }
220
+
221
+ L.push('## Session hints');
222
+ L.push(`- at open: ${doc.config?.initHints ? JSON.stringify(doc.config.initHints) : 'none'}`);
223
+ L.push(`- at close: ${doc.finalHints ? JSON.stringify(doc.finalHints) : 'none'}`);
224
+ L.push('');
225
+
226
+ if (extras.servedTags?.length) {
227
+ L.push('## Served tags');
228
+ for (const t of extras.servedTags) {
229
+ L.push(
230
+ `- ${t.tag}: ${t.responses} resp / ${t.cards} card(s)` +
231
+ `, acc ${t.accuracy === null ? 'n/a' : `${Math.round(t.accuracy * 100)}%`}` +
232
+ ` (${t.correct}✓/${t.incorrect}✗), ${(t.totalTimeMs / 1000).toFixed(1)}s`
233
+ );
234
+ }
235
+ L.push('');
236
+ }
237
+
238
+ const led = extras.eloLedger;
239
+ if (led) {
240
+ L.push('## ELO ledger (learner global)');
241
+ L.push(
242
+ `- net ${fmtDelta(led.net)} across ${led.count} exchange(s)` +
243
+ ` · gained ${fmtDelta(led.gained)} over ${led.wins} win(s)` +
244
+ ` · lost ${fmtDelta(led.lost)} over ${led.losses} loss(es)`
245
+ );
246
+ L.push('');
247
+ }
248
+
249
+ L.push(`## Timeline (${detail.timeline.length} entries)`);
250
+ for (const e of detail.timeline) {
251
+ if (e.kind === 'run') {
252
+ L.push(runText(e.run));
253
+ continue;
254
+ }
255
+ const mark = e.isCorrect === true ? '✓' : e.isCorrect === false ? '✗' : '·';
256
+ const tags = e.tags.length ? ` [${e.tags.join(', ')}]` : '';
257
+ const attempt = e.priorAttempts ? ` (attempt ${e.priorAttempts + 1})` : '';
258
+ const ans = e.userAnswer != null ? ` '${fmtAnswer(e.userAnswer)}'` : '';
259
+ L.push(
260
+ `RESP ${clock(e.at)} ${mark} ${e.questionType ?? 'card'} ${e.cardId}${tags}` +
261
+ ` — ${(e.timeSpentMs / 1000).toFixed(1)}s${attempt}${ans}${eloSuffix(e.elo, interp)}`
262
+ );
263
+ }
264
+ return L.join('\n');
265
+ }