@vue-skuilder/db 0.3.0 → 0.3.2

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 (46) hide show
  1. package/dist/{contentSource-2zVmcjKA.d.ts → contentSource-CSI0pJ2D.d.ts} +10 -0
  2. package/dist/core/index.cjs +105 -36
  3. package/dist/core/index.cjs.map +1 -1
  4. package/dist/core/index.d.ts +3 -3
  5. package/dist/core/interfaces/contentSource.mjs.map +1 -1
  6. package/dist/core/navigators/Pipeline.mjs +7 -1
  7. package/dist/core/navigators/Pipeline.mjs.map +1 -1
  8. package/dist/core/navigators/filters/eloDistance.mjs +17 -2
  9. package/dist/core/navigators/filters/eloDistance.mjs.map +1 -1
  10. package/dist/core/navigators/generators/prescribed.mjs +20 -10
  11. package/dist/core/navigators/generators/prescribed.mjs.map +1 -1
  12. package/dist/core/navigators/index.mjs +2 -0
  13. package/dist/core/navigators/index.mjs.map +1 -1
  14. package/dist/core/versionStamps.mjs +1 -1
  15. package/dist/{dataLayerProvider-rGyLQ93v.d.ts → dataLayerProvider-D5n1gGc_.d.ts} +1 -1
  16. package/dist/diagnostics/index.d.ts +2 -2
  17. package/dist/impl/common/BaseUserDB.mjs +43 -21
  18. package/dist/impl/common/BaseUserDB.mjs.map +1 -1
  19. package/dist/impl/couch/courseDB.mjs +5 -0
  20. package/dist/impl/couch/courseDB.mjs.map +1 -1
  21. package/dist/impl/couch/index.cjs +80 -24
  22. package/dist/impl/couch/index.cjs.map +1 -1
  23. package/dist/impl/couch/index.d.ts +4 -2
  24. package/dist/impl/static/courseDB.mjs +5 -0
  25. package/dist/impl/static/courseDB.mjs.map +1 -1
  26. package/dist/impl/static/index.cjs +80 -24
  27. package/dist/impl/static/index.cjs.map +1 -1
  28. package/dist/impl/static/index.d.ts +4 -2
  29. package/dist/index.cjs +116 -37
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.ts +3 -3
  32. package/dist/study/SessionController.mjs +1 -0
  33. package/dist/study/SessionController.mjs.map +1 -1
  34. package/docs/session-lifecycle-and-replan.md +71 -58
  35. package/package.json +3 -3
  36. package/src/core/interfaces/contentSource.ts +7 -0
  37. package/src/core/navigators/Pipeline.ts +7 -0
  38. package/src/core/navigators/filters/eloDistance.ts +31 -2
  39. package/src/core/navigators/generators/prescribed.ts +56 -11
  40. package/src/core/navigators/generators/types.ts +3 -0
  41. package/src/core/navigators/index.ts +5 -0
  42. package/src/impl/common/BaseUserDB.ts +47 -25
  43. package/src/impl/couch/courseDB.ts +13 -0
  44. package/src/impl/static/courseDB.ts +13 -0
  45. package/src/study/SessionController.ts +3 -0
  46. package/tests/core/navigators/eloDistanceFilter.test.ts +15 -0
@@ -1807,6 +1807,8 @@ declare abstract class ContentNavigator implements StudyContentSource {
1807
1807
  * No-op for non-Pipeline navigators. Pipeline overrides this.
1808
1808
  */
1809
1809
  setEphemeralHints(_hints: ReplanHints): void;
1810
+ /** See StudyContentSource.setSessionId. No-op for non-Pipeline navigators. */
1811
+ setSessionId(_sessionId: string): void;
1810
1812
  }
1811
1813
 
1812
1814
  /**
@@ -1846,6 +1848,8 @@ interface GeneratorContext {
1846
1848
  userElo: number;
1847
1849
  /** Orchestration context for evolutionary weighting */
1848
1850
  orchestration?: OrchestrationContext;
1851
+ /** The study session this run belongs to, when the caller set one. */
1852
+ sessionId?: string;
1849
1853
  }
1850
1854
  /**
1851
1855
  * Structured generator result.
@@ -1996,6 +2000,12 @@ interface StudyContentSource {
1996
2000
  * No-op for sources that don't support hints.
1997
2001
  */
1998
2002
  setEphemeralHints?(hints: ReplanHints): void;
2003
+ /**
2004
+ * The study session the following runs belong to. Persists until replaced
2005
+ * (unlike hints). Generators read it from their context, e.g. to count
2006
+ * sessions rather than runs.
2007
+ */
2008
+ setSessionId?(sessionId: string): void;
1999
2009
  /**
2000
2010
  * A card was just presented. `status` is the session item's (`'new'`,
2001
2011
  * `'review'`, `'failed-new'`, ...). Pipelines use a new card's first
@@ -1617,9 +1617,12 @@ var init_prescribed = __esm({
1617
1617
  const allRelevantIds = dedupe([...allTargetIds, ...allSupportIds]);
1618
1618
  const tagsByCard = allRelevantIds.length > 0 ? await this.course.getAppliedTagsBatch(allRelevantIds) : /* @__PURE__ */ new Map();
1619
1619
  const cardsByTag = await this.loadCardsByTag();
1620
+ const sessionId = context?.sessionId;
1621
+ const newSession = sessionId === void 0 || sessionId !== progress.lastSessionId;
1620
1622
  const nextState = {
1621
1623
  updatedAt: isoNow(),
1622
- groups: {}
1624
+ groups: {},
1625
+ ...sessionId || progress.lastSessionId ? { lastSessionId: sessionId ?? progress.lastSessionId } : {}
1623
1626
  };
1624
1627
  const emitted = [];
1625
1628
  const emittedIds = /* @__PURE__ */ new Set();
@@ -1659,7 +1662,11 @@ var init_prescribed = __esm({
1659
1662
  );
1660
1663
  }
1661
1664
  }
1662
- nextState.groups[group.id] = this.buildNextGroupState(runtime, progress.groups[group.id]);
1665
+ nextState.groups[group.id] = this.buildNextGroupState(
1666
+ runtime,
1667
+ progress.groups[group.id],
1668
+ newSession
1669
+ );
1663
1670
  const directCards = this.buildDirectTargetCards(
1664
1671
  runtime,
1665
1672
  courseId,
@@ -1731,12 +1738,8 @@ var init_prescribed = __esm({
1731
1738
  for (const group of this.config.groups) {
1732
1739
  const groupState = nextState.groups[group.id];
1733
1740
  const surfaced = surfacedByGroup.get(group.id);
1734
- if (surfaced && (surfaced.targetIds.length > 0 || surfaced.supportIds.length > 0)) {
1735
- groupState.lastSurfacedAt = isoNow();
1736
- groupState.sessionsSinceSurfaced = 0;
1737
- if (surfaced.supportIds.length > 0) {
1738
- groupState.lastSupportAt = isoNow();
1739
- }
1741
+ if (surfaced && surfaced.supportIds.length > 0) {
1742
+ groupState.lastSupportAt = isoNow();
1740
1743
  }
1741
1744
  }
1742
1745
  await this.putStrategyState(nextState).catch((e) => {
@@ -2002,14 +2005,24 @@ var init_prescribed = __esm({
2002
2005
  debugVersion: PRESCRIBED_DEBUG_VERSION
2003
2006
  };
2004
2007
  }
2005
- buildNextGroupState(runtime, prior) {
2008
+ /**
2009
+ * The group's state after this run. The staleness clock resets only when a
2010
+ * target has reached the learner since the last run: it is newly in
2011
+ * `encounteredTargets`, which reads card history and scheduled reviews, so
2012
+ * the card was shown and answered. Emitting a target does not count; it may
2013
+ * lose to the rest of the heap. (Before 2026-11, emission reset the clock,
2014
+ * and a group that emitted every run never escalated.) The clock advances
2015
+ * once per study session, not per run.
2016
+ */
2017
+ buildNextGroupState(runtime, prior, newSession) {
2006
2018
  const carriedSessions = prior?.sessionsSinceSurfaced ?? 0;
2007
- const surfacedThisRun = false;
2019
+ const previouslyEncountered = new Set(prior?.encounteredCardIds ?? []);
2020
+ const surfacedThisRun = prior !== void 0 && [...runtime.encounteredTargets].some((id) => !previouslyEncountered.has(id));
2008
2021
  return {
2009
2022
  encounteredCardIds: [...runtime.encounteredTargets].sort(),
2010
2023
  pendingTargetIds: [...runtime.pendingTargets].sort(),
2011
- lastSurfacedAt: prior?.lastSurfacedAt ?? null,
2012
- sessionsSinceSurfaced: surfacedThisRun ? 0 : carriedSessions + 1,
2024
+ lastSurfacedAt: surfacedThisRun ? isoNow() : prior?.lastSurfacedAt ?? null,
2025
+ sessionsSinceSurfaced: surfacedThisRun ? 0 : carriedSessions + (newSession ? 1 : 0),
2013
2026
  lastSupportAt: prior?.lastSupportAt ?? null,
2014
2027
  blockedTargetIds: [...runtime.blockedTargets].sort(),
2015
2028
  lastResolvedSupportTags: [...runtime.supportTags].sort()
@@ -3136,6 +3149,9 @@ __export(eloDistance_exports, {
3136
3149
  mountMultiDimEloToggle: () => mountMultiDimEloToggle,
3137
3150
  tagAwareGap: () => tagAwareGap
3138
3151
  });
3152
+ function isIntroCard(card) {
3153
+ return (card.tags ?? []).some((t) => (0, import_common5.tagRole)(t) === "intro");
3154
+ }
3139
3155
  function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
3140
3156
  const normalizedDistance = distance / halfLife;
3141
3157
  const decay = Math.exp(-(normalizedDistance * normalizedDistance));
@@ -3203,7 +3219,7 @@ async function applyEloDistance(cards, context, config, source) {
3203
3219
  const { course, userElo, userCourseElo } = context;
3204
3220
  const { halfLife, minMultiplier, maxMultiplier } = config;
3205
3221
  const tagAware = (config.tagAware || multiDimElo) && userCourseElo !== void 0;
3206
- const missing = cards.filter((c) => tagAware || c.cardElo === void 0).map((c) => c.cardId);
3222
+ const missing = cards.filter((c) => !isIntroCard(c) && (tagAware || c.cardElo === void 0)).map((c) => c.cardId);
3207
3223
  const fetched = /* @__PURE__ */ new Map();
3208
3224
  if (missing.length > 0) {
3209
3225
  const elos = await course.getCardEloData(missing);
@@ -3212,6 +3228,22 @@ async function applyEloDistance(cards, context, config, source) {
3212
3228
  });
3213
3229
  }
3214
3230
  return cards.map((card) => {
3231
+ if (isIntroCard(card)) {
3232
+ return {
3233
+ ...card,
3234
+ provenance: [
3235
+ ...card.provenance,
3236
+ {
3237
+ strategy: "eloDistance",
3238
+ strategyName: source.name,
3239
+ strategyId: source.strategyId,
3240
+ action: "passed",
3241
+ score: card.score,
3242
+ reason: "intro card: ELO is a placeholder, distance not applied \u2192 1.00x"
3243
+ }
3244
+ ]
3245
+ };
3246
+ }
3215
3247
  const full = fetched.get(card.cardId);
3216
3248
  const cardElo = full?.global?.score ?? card.cardElo ?? DEFAULT_CARD_ELO;
3217
3249
  let distance = Math.abs(cardElo - userElo);
@@ -3584,6 +3616,9 @@ var init_navigators = __esm({
3584
3616
  */
3585
3617
  setEphemeralHints(_hints) {
3586
3618
  }
3619
+ /** See StudyContentSource.setSessionId. No-op for non-Pipeline navigators. */
3620
+ setSessionId(_sessionId) {
3621
+ }
3587
3622
  };
3588
3623
  }
3589
3624
  });
@@ -4532,6 +4567,7 @@ var init_Pipeline = __esm({
4532
4567
  * getWeightedCards() call, then cleared.
4533
4568
  */
4534
4569
  _ephemeralHints = null;
4570
+ _sessionId;
4535
4571
  /**
4536
4572
  * The intake valve's clock (see regulators.ts), loaded from strategy state on
4537
4573
  * first use and kept in memory. Writes are chained so a presentation and a
@@ -4567,6 +4603,10 @@ var init_Pipeline = __esm({
4567
4603
  *
4568
4604
  * Overrides ContentNavigator.setEphemeralHints() no-op.
4569
4605
  */
4606
+ /** See StudyContentSource.setSessionId. Carried into every run's context. */
4607
+ setSessionId(sessionId) {
4608
+ this._sessionId = sessionId;
4609
+ }
4570
4610
  setEphemeralHints(hints) {
4571
4611
  this._ephemeralHints = hints;
4572
4612
  logger.info(`[Pipeline] Ephemeral hints set: ${JSON.stringify(hints)}`);
@@ -5014,7 +5054,8 @@ var init_Pipeline = __esm({
5014
5054
  course: this.course,
5015
5055
  userElo,
5016
5056
  ...userCourseElo ? { userCourseElo } : {},
5017
- orchestration
5057
+ orchestration,
5058
+ ...this._sessionId ? { sessionId: this._sessionId } : {}
5018
5059
  };
5019
5060
  }
5020
5061
  /**
@@ -6261,6 +6302,10 @@ ${e.stack}` : JSON.stringify(e);
6261
6302
  setEphemeralHints(hints) {
6262
6303
  this._pendingHints = hints;
6263
6304
  }
6305
+ _sessionId = null;
6306
+ setSessionId(sessionId) {
6307
+ this._sessionId = sessionId;
6308
+ }
6264
6309
  /**
6265
6310
  * Forward a presentation to the navigator (a new card restarts its intake
6266
6311
  * clock). Builds the navigator if the cached one has expired.
@@ -6277,6 +6322,9 @@ ${e.stack}` : JSON.stringify(e);
6277
6322
  navigator2.setEphemeralHints(this._pendingHints);
6278
6323
  this._pendingHints = null;
6279
6324
  }
6325
+ if (this._sessionId) {
6326
+ navigator2.setSessionId(this._sessionId);
6327
+ }
6280
6328
  const result = await navigator2.getWeightedCards(limit);
6281
6329
  return result;
6282
6330
  } catch (e) {
@@ -7877,6 +7925,9 @@ var init_BaseUserDB = __esm({
7877
7925
  // Database to use for write operations (local-first approach)
7878
7926
  updateQueue;
7879
7927
  _hydration = { state: "not-required" };
7928
+ /** See scanScheduledCards. Bumped by every write to scheduled reviews. */
7929
+ _scheduledScan = null;
7930
+ _scheduledGeneration = 0;
7880
7931
  /** In-flight hydration, so concurrent callers can wait for a real answer. */
7881
7932
  _hydrationPromise = null;
7882
7933
  /**
@@ -8121,18 +8172,38 @@ Currently logged-in as ${this._username}.`
8121
8172
  *
8122
8173
  */
8123
8174
  async getActiveCards() {
8175
+ return (await this.scanScheduledCards()).map((doc) => ({
8176
+ courseID: doc.courseId,
8177
+ cardID: doc.cardId
8178
+ }));
8179
+ }
8180
+ /**
8181
+ * The user's scheduled reviews (`card_review_*`), all of them: one `allDocs`
8182
+ * scan shared by concurrent readers. A pipeline run's generators start
8183
+ * together (`CompositeGenerator`), and each used to scan the range itself
8184
+ * (`getActiveCards` from ELO and Prescribed, `getReviewstoDate` from SRS).
8185
+ * Sharing only an in-flight scan keeps reads as fresh as before; a schedule
8186
+ * or removal of a review starts a new scan for anyone reading after it.
8187
+ * Docs are shared between callers: copy before mutating.
8188
+ */
8189
+ scanScheduledCards() {
8190
+ const inFlight = this._scheduledScan;
8191
+ if (inFlight && inFlight.generation === this._scheduledGeneration) return inFlight.scan;
8124
8192
  const keys = getStartAndEndKeys(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */]);
8125
- const reviews = await this.remoteDB.allDocs({
8126
- startkey: keys.startkey,
8127
- endkey: keys.endkey,
8128
- include_docs: true
8129
- });
8130
- return reviews.rows.map((r) => {
8131
- return {
8132
- courseID: r.doc.courseId,
8133
- cardID: r.doc.cardId
8134
- };
8135
- });
8193
+ const entry = {
8194
+ generation: this._scheduledGeneration,
8195
+ scan: this.remoteDB.allDocs({
8196
+ startkey: keys.startkey,
8197
+ endkey: keys.endkey,
8198
+ include_docs: true
8199
+ }).then((res) => res.rows.map((row) => row.doc))
8200
+ };
8201
+ this._scheduledScan = entry;
8202
+ const done = () => {
8203
+ if (this._scheduledScan === entry) this._scheduledScan = null;
8204
+ };
8205
+ entry.scan.then(done, done);
8206
+ return entry.scan;
8136
8207
  }
8137
8208
  async getActivityRecords() {
8138
8209
  try {
@@ -8198,28 +8269,23 @@ Currently logged-in as ${this._username}.`
8198
8269
  }
8199
8270
  }
8200
8271
  async getReviewstoDate(targetDate, course_id) {
8201
- const keys = getStartAndEndKeys(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */]);
8202
- const reviews = await this.remoteDB.allDocs({
8203
- startkey: keys.startkey,
8204
- endkey: keys.endkey,
8205
- include_docs: true
8206
- });
8272
+ const reviews = await this.scanScheduledCards();
8207
8273
  log3(
8208
8274
  `Fetching ${this._username}'s scheduled reviews${course_id ? ` for course ${course_id}` : ""}.`
8209
8275
  );
8210
- return reviews.rows.filter((r) => {
8211
- if (r.id.startsWith(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */])) {
8276
+ return reviews.filter((doc) => {
8277
+ if (doc._id.startsWith(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */])) {
8212
8278
  const date = import_moment6.default.utc(
8213
- r.id.substr(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */].length),
8279
+ doc._id.substr(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */].length),
8214
8280
  REVIEW_TIME_FORMAT
8215
8281
  );
8216
8282
  if (targetDate.isAfter(date)) {
8217
- if (course_id === void 0 || r.doc.courseId === course_id) {
8283
+ if (course_id === void 0 || doc.courseId === course_id) {
8218
8284
  return true;
8219
8285
  }
8220
8286
  }
8221
8287
  }
8222
- }).map((r) => r.doc);
8288
+ }).map((doc) => ({ ...doc }));
8223
8289
  }
8224
8290
  async getReviewsForcast(daysCount, course_id) {
8225
8291
  const time = import_moment6.default.utc().add(daysCount, "days");
@@ -8690,6 +8756,7 @@ Currently logged-in as ${this._username}.`
8690
8756
  const deletePromises = duplicateDocIds.map(async (docId) => {
8691
8757
  try {
8692
8758
  const doc = await this.remoteDB.get(docId);
8759
+ this._scheduledGeneration++;
8693
8760
  await this.writeDB.remove(doc);
8694
8761
  log3(`Successfully removed duplicate review: ${docId}`);
8695
8762
  } catch (error) {
@@ -8835,9 +8902,11 @@ Currently logged-in as ${this._username}.`
8835
8902
  }
8836
8903
  }
8837
8904
  async scheduleCardReview(review) {
8905
+ this._scheduledGeneration++;
8838
8906
  return scheduleCardReviewLocal(this.writeDB, review);
8839
8907
  }
8840
8908
  async removeScheduledCardReview(reviewId) {
8909
+ this._scheduledGeneration++;
8841
8910
  return removeScheduledCardReviewLocal(this.writeDB, reviewId);
8842
8911
  }
8843
8912
  async registerForClassroom(_classId, _registerAs) {