@vllnt/convex-progression 0.1.0-canary.0

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 (73) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/LICENSE +21 -0
  3. package/README.md +144 -0
  4. package/dist/client/index.d.ts +61 -0
  5. package/dist/client/index.d.ts.map +1 -0
  6. package/dist/client/index.js +64 -0
  7. package/dist/client/index.js.map +1 -0
  8. package/dist/client/types.d.ts +20 -0
  9. package/dist/client/types.d.ts.map +1 -0
  10. package/dist/client/types.js +3 -0
  11. package/dist/client/types.js.map +1 -0
  12. package/dist/component/_generated/api.d.ts +40 -0
  13. package/dist/component/_generated/api.d.ts.map +1 -0
  14. package/dist/component/_generated/api.js +31 -0
  15. package/dist/component/_generated/api.js.map +1 -0
  16. package/dist/component/_generated/component.d.ts +82 -0
  17. package/dist/component/_generated/component.d.ts.map +1 -0
  18. package/dist/component/_generated/component.js +11 -0
  19. package/dist/component/_generated/component.js.map +1 -0
  20. package/dist/component/_generated/dataModel.d.ts +46 -0
  21. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  22. package/dist/component/_generated/dataModel.js +11 -0
  23. package/dist/component/_generated/dataModel.js.map +1 -0
  24. package/dist/component/_generated/server.d.ts +133 -0
  25. package/dist/component/_generated/server.d.ts.map +1 -0
  26. package/dist/component/_generated/server.js +80 -0
  27. package/dist/component/_generated/server.js.map +1 -0
  28. package/dist/component/convex.config.d.ts +3 -0
  29. package/dist/component/convex.config.d.ts.map +1 -0
  30. package/dist/component/convex.config.js +4 -0
  31. package/dist/component/convex.config.js.map +1 -0
  32. package/dist/component/mutations.d.ts +43 -0
  33. package/dist/component/mutations.d.ts.map +1 -0
  34. package/dist/component/mutations.js +179 -0
  35. package/dist/component/mutations.js.map +1 -0
  36. package/dist/component/queries.d.ts +14 -0
  37. package/dist/component/queries.d.ts.map +1 -0
  38. package/dist/component/queries.js +45 -0
  39. package/dist/component/queries.js.map +1 -0
  40. package/dist/component/schema.d.ts +32 -0
  41. package/dist/component/schema.d.ts.map +1 -0
  42. package/dist/component/schema.js +21 -0
  43. package/dist/component/schema.js.map +1 -0
  44. package/dist/component/validation.d.ts +4 -0
  45. package/dist/component/validation.d.ts.map +1 -0
  46. package/dist/component/validation.js +22 -0
  47. package/dist/component/validation.js.map +1 -0
  48. package/dist/component/validators.d.ts +52 -0
  49. package/dist/component/validators.d.ts.map +1 -0
  50. package/dist/component/validators.js +20 -0
  51. package/dist/component/validators.js.map +1 -0
  52. package/dist/shared.d.ts +15 -0
  53. package/dist/shared.d.ts.map +1 -0
  54. package/dist/shared.js +36 -0
  55. package/dist/shared.js.map +1 -0
  56. package/docs/API.md +69 -0
  57. package/llms-full.txt +930 -0
  58. package/llms.txt +35 -0
  59. package/package.json +92 -0
  60. package/src/client/index.ts +191 -0
  61. package/src/client/types.ts +23 -0
  62. package/src/component/_generated/api.ts +56 -0
  63. package/src/component/_generated/component.ts +107 -0
  64. package/src/component/_generated/dataModel.ts +60 -0
  65. package/src/component/_generated/server.ts +169 -0
  66. package/src/component/convex.config.ts +5 -0
  67. package/src/component/mutations.ts +205 -0
  68. package/src/component/queries.ts +50 -0
  69. package/src/component/schema.ts +21 -0
  70. package/src/component/validation.ts +30 -0
  71. package/src/component/validators.ts +23 -0
  72. package/src/shared.ts +47 -0
  73. package/src/test.ts +15 -0
package/llms-full.txt ADDED
@@ -0,0 +1,930 @@
1
+ # @vllnt/convex-progression — Full Source
2
+
3
+ Auto-generated by `pnpm generate:llms`. Do not edit manually.
4
+
5
+ ---
6
+
7
+ ## README.md
8
+
9
+ <!-- Badges -->
10
+ [![convex-component](https://img.shields.io/badge/convex-component-EE342F.svg)](https://www.convex.dev/components)
11
+ [![npm](https://img.shields.io/npm/v/@vllnt/convex-progression.svg)](https://www.npmjs.com/package/@vllnt/convex-progression)
12
+ [![CI](https://github.com/vllnt/convex-progression/actions/workflows/ci.yml/badge.svg)](https://github.com/vllnt/convex-progression/actions/workflows/ci.yml)
13
+ [![license](https://img.shields.io/npm/l/@vllnt/convex-progression.svg)](./LICENSE)
14
+
15
+ # @vllnt/convex-progression
16
+
17
+ XP → level and streak windows as a Convex component.
18
+
19
+ Not money (`@vllnt/convex-wallet`), not a resetting cap (`@vllnt/convex-quota`).
20
+ The host passes opaque `subjectRef` + `key` and the level `thresholds` on each write.
21
+
22
+ ```ts
23
+ const xp = new Progression(components.progression);
24
+ await xp.accrue(ctx, subjectRef, "solo", 10, [50, 150, 400]);
25
+ await xp.recordActivity(ctx, subjectRef, "solo", today, [], {
26
+ expectedPrevious: yesterday,
27
+ });
28
+ ```
29
+
30
+ ## Features
31
+
32
+ - **XP / level** — `accrue` adds XP; `level` is how many host `thresholds` that XP has reached.
33
+ - **Streaks** — `recordActivity` with a host `periodKey`; pass `expectedPrevious` to continue a streak or reset on a gap.
34
+ - **Opaque refs** — `subjectRef` and `key` are host strings (max 256 chars).
35
+ - **Recompute on read** — `get(..., thresholds)` can recompute `level` if the host changed the ladder.
36
+ - **Bounded erase** — `eraseSubject` deletes in batches and reschedules until clean.
37
+ - **Scopes** — default `"global"`.
38
+
39
+ ## Installation
40
+
41
+ Unreleased candidate (`0.1.0`); registry availability is not asserted. The command
42
+ below applies after publication. For pre-release evaluation, install a locally
43
+ built package tarball.
44
+
45
+ ```bash
46
+ pnpm add @vllnt/convex-progression
47
+ ```
48
+
49
+ Peer dependency: `convex@^1.45.0`; Node.js ≥20 (development toolchain:
50
+ Node 20.19+ or 22.12+).
51
+
52
+ ## Usage
53
+
54
+ ```ts
55
+ // convex/convex.config.ts
56
+ import { defineApp } from "convex/server";
57
+ import progression from "@vllnt/convex-progression/convex.config";
58
+
59
+ const app = defineApp();
60
+ app.use(progression);
61
+ export default app;
62
+ ```
63
+
64
+ ```ts
65
+ import { components } from "./_generated/api";
66
+ import { mutation } from "./_generated/server";
67
+ import { Progression } from "@vllnt/convex-progression";
68
+
69
+ const xp = new Progression(components.progression);
70
+ const THRESHOLDS = [50, 150, 400];
71
+
72
+ export const onWin = mutation({
73
+ args: {},
74
+ handler: async (ctx) => {
75
+ const subjectRef = /* host-resolved identity */ "user_1";
76
+ await xp.accrue(ctx, subjectRef, "solo", 10, THRESHOLDS);
77
+ await xp.recordActivity(ctx, subjectRef, "solo", "2026-09-11", THRESHOLDS, {
78
+ expectedPrevious: "2026-09-10",
79
+ });
80
+ },
81
+ });
82
+ ```
83
+
84
+ **Host rules:** never take `delta` or `thresholds` from the end-user.
85
+
86
+ ## API Reference
87
+
88
+ | Method | Kind | Result |
89
+ |--------|------|--------|
90
+ | `accrue(ctx, subjectRef, key, delta, thresholds, scope?)` | mutation | `{ xp, level, streak, maxStreak, leveledUp, previousLevel, ... }` |
91
+ | `recordActivity(ctx, subjectRef, key, periodKey, thresholds, opts?)` | mutation | `{ streak, streakDelta, maxStreak, ... }` |
92
+ | `get(ctx, subjectRef, key, scope?, thresholds?)` | query | progress or `null` |
93
+ | `reset(ctx, subjectRef, key, scope?)` | mutation | `null` |
94
+ | `eraseSubject(ctx, subjectRef, scope?, batch?)` | mutation | `number` deleted this pass |
95
+
96
+ Full reference: [docs/API.md](docs/API.md).
97
+
98
+ ## React
99
+
100
+ Backend-only — no `./react` entry.
101
+
102
+ ## Security
103
+
104
+ - Auth-agnostic — the host resolves identity and passes an opaque `subjectRef`.
105
+ - Tables sandboxed — reached only through the exported functions.
106
+ - The host authorizes every read/write, derives scope and period keys, deduplicates
107
+ award events, and rejects late activity. See [lifecycle limits](docs/API.md#lifecycle-and-retries).
108
+
109
+ ## Multiple mounts
110
+
111
+ Mount with `app.use(progression, { name: "gameProgress" })` and separately with
112
+ `{ name: "learningProgress" }`; construct a client for each generated component
113
+ reference. Each mount has isolated tables and scheduled work.
114
+
115
+ ## Testing
116
+
117
+ ```bash
118
+ pnpm test
119
+ pnpm test:coverage
120
+ ```
121
+
122
+ Tests use the `convex-test` in-memory simulation (`@edge-runtime/vm`), not a real
123
+ Convex backend. They do not prove production OCC retries or scheduler behavior.
124
+
125
+ `node scripts/check-pack.mjs` checks tarball imports and NodeNext consumer types.
126
+ For a separate **local backend** concurrency/scheduler smoke test, provision an
127
+ anonymous deployment in an isolated HOME (never a cloud/production deployment):
128
+
129
+ ```bash
130
+ HOME=/tmp/progression-audit-home CONVEX_AGENT_MODE=anonymous pnpm convex dev --once --local-cloud-port 3320 --local-site-port 3321 --typecheck disable
131
+ HOME=/tmp/progression-audit-home CONVEX_AGENT_MODE=anonymous node scripts/check-local.mjs
132
+ ```
133
+
134
+ The probe starts/stops its own CLI and backend. This is bounded smoke evidence,
135
+ not proof of every conflict schedule or production workload. Example wrappers
136
+ accept raw refs and awards for testing only; they are not production auth gates.
137
+
138
+ ## Contributing
139
+
140
+ See [CONTRIBUTING.md](CONTRIBUTING.md).
141
+
142
+ ## Author
143
+
144
+ Built by [bntvllnt](https://github.com/bntvllnt) · [bntvllnt.com](https://bntvllnt.com) · [X @bntvllnt](https://x.com/bntvllnt)
145
+
146
+ Part of the [@vllnt](https://github.com/vllnt) Convex component fleet — [vllnt.com](https://vllnt.com)
147
+
148
+ If this is useful, [sponsor the work](https://github.com/sponsors/bntvllnt).
149
+
150
+ ## License
151
+
152
+ MIT — see [LICENSE](LICENSE).
153
+
154
+
155
+ ---
156
+
157
+ ## CHANGELOG.md
158
+
159
+ # Changelog
160
+
161
+ All notable changes to this project are documented here. The format is based on
162
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to
163
+ [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
164
+
165
+ ## [Unreleased]
166
+
167
+ ### Fixed
168
+
169
+ - Bound XP/streak arithmetic and reject silently lost awards.
170
+ - Validate query thresholds and all namespace/period refs.
171
+ - Clarify replay, erasure, simulation-test, and unreleased-candidate limitations.
172
+
173
+ ### Added
174
+
175
+ - Initial unpublished candidate of `@vllnt/convex-progression`.
176
+ - `accrue`, `recordActivity`, `get` (optional threshold recompute), `reset`,
177
+ `eraseSubject` (batched).
178
+
179
+
180
+ ---
181
+
182
+ ## docs/API.md
183
+
184
+ # API Reference — @vllnt/convex-progression
185
+
186
+ **Compatibility:** `convex@^1.45.0`
187
+
188
+ ```ts
189
+ import { Progression } from "@vllnt/convex-progression";
190
+
191
+ const xp = new Progression(components.progression, { defaultScope: "global" });
192
+ ```
193
+
194
+ `subjectRef`, `key`, `scope`, `periodKey`, and provided `expectedPrevious` are
195
+ opaque host strings (1..256 UTF-16 code units). Never trust these, `delta`, or
196
+ `thresholds` from an end-user without host authorization. `thresholds` must be
197
+ strictly increasing, finite, and in `0..Number.MAX_SAFE_INTEGER` (empty is valid).
198
+ These rules apply to reads as well as writes, including missing-row queries.
199
+
200
+ ### `accrue(ctx, subjectRef, key, delta, thresholds, scope?)`
201
+
202
+ Adds `delta` XP (positive finite, at most `Number.MAX_SAFE_INTEGER`). Fractions
203
+ are supported with JavaScript floating-point rounding. Rejects totals above that
204
+ bound or an addition that makes no progress (`XP_OVERFLOW`). `level` counts
205
+ reached thresholds. `previousLevel` is the stored level from the previous write;
206
+ `leveledUp` compares against it, so a changed ladder can itself produce a level-up.
207
+
208
+ ### `recordActivity(ctx, subjectRef, key, periodKey, thresholds, opts?)`
209
+
210
+ `opts`: `{ scope?, expectedPrevious? }`.
211
+
212
+ - Same `periodKey` as stored → streak unchanged (`streakDelta: 0`), but level
213
+ is recomputed and `updatedAt` is refreshed.
214
+ - `lastPeriodKey === expectedPrevious` → streak + 1.
215
+ - Otherwise → streak resets to 1.
216
+
217
+ ### `get(ctx, subjectRef, key, scope?, thresholds?)`
218
+
219
+ Returns the progress row or `null`. When `thresholds` is passed, `level` is
220
+ recomputed from stored XP.
221
+
222
+ ### `reset(ctx, subjectRef, key, scope?)`
223
+
224
+ Deletes that `(scope, subjectRef, key)` row.
225
+
226
+ ### `eraseSubject(ctx, subjectRef, scope?, batch?)`
227
+
228
+ Deletes up to `batch` rows (default 200, positive integer clamped to 500),
229
+ returning only this pass's count. A full batch atomically schedules another pass;
230
+ there is no completion token or aggregate count.
231
+
232
+ ### Lifecycle and retries
233
+
234
+ - `accrue` is additive, **not event-idempotent**. Host mutations should deduplicate
235
+ event IDs atomically with awards. Convex transaction retries are distinct from
236
+ submitting a new logical award request.
237
+ - Periods are opaque, not ordered. Only the latest period is remembered. Replaying
238
+ an older period can reset/rewind a streak; the host must reject stale events and
239
+ serialize its period policy. `expectedPrevious` declares adjacency, not a CAS
240
+ precondition. Streaks exceeding `MAX_SAFE_INTEGER` reject with `STREAK_OVERFLOW`.
241
+ - Erase has no tombstone or write fence. Gate writes before starting erasure and
242
+ keep them gated until a host-controlled completion check. Concurrent/new writes
243
+ may be deleted by scheduled passes or survive after the final pass. Reset does
244
+ not cancel pending subject erasure. Schedule execution failures require host
245
+ monitoring and retry; this component has no durable completion status.
246
+ - `get` with thresholds only recomputes the returned level; it does not persist
247
+ the ladder or level. Threshold policy consistency belongs to the host.
248
+
249
+ Validation failures use `ConvexError` data `{ code, message }`: `INVALID_REF`,
250
+ `INVALID_THRESHOLDS`, `INVALID_DELTA`, `INVALID_BATCH`, `XP_OVERFLOW`, or
251
+ `STREAK_OVERFLOW`. There are no component logs; hosts should monitor rejected
252
+ calls and scheduled-function failures without logging sensitive refs.
253
+
254
+
255
+ ---
256
+
257
+ ## src/shared.ts
258
+
259
+ ```ts
260
+ /** Shared constants used by both `client/` and `component/`. */
261
+
262
+ export const COMPONENT_NAME = "progression";
263
+
264
+ /** Default namespace when the host does not scope progress. */
265
+ export const DEFAULT_SCOPE = "global";
266
+
267
+ export const MAX_REF_LENGTH = 256;
268
+ export const DEFAULT_ERASE_BATCH = 200;
269
+ export const MAX_ERASE_BATCH = 500;
270
+
271
+ /**
272
+ * Level is the count of thresholds the current XP has reached.
273
+ * `thresholds` must be strictly increasing non-negative numbers.
274
+ */
275
+ export function levelForXp(xp: number, thresholds: readonly number[]): number {
276
+ return thresholds.reduce((level, threshold) => {
277
+ return xp >= threshold ? level + 1 : level;
278
+ }, 0);
279
+ }
280
+
281
+ export function assertThresholds(thresholds: readonly number[]): void {
282
+ thresholds.reduce<number>((previous, threshold) => {
283
+ if (
284
+ !Number.isFinite(threshold) ||
285
+ threshold < 0 ||
286
+ threshold > Number.MAX_SAFE_INTEGER
287
+ ) {
288
+ throw new Error(
289
+ "INVALID_THRESHOLDS: thresholds must be finite and in 0..MAX_SAFE_INTEGER",
290
+ );
291
+ }
292
+ if (threshold <= previous) {
293
+ throw new Error(
294
+ "INVALID_THRESHOLDS: thresholds must be strictly increasing",
295
+ );
296
+ }
297
+ return threshold;
298
+ }, -1);
299
+ }
300
+
301
+ export function clampEraseBatch(batch: number): number {
302
+ if (!Number.isInteger(batch) || batch < 1) {
303
+ throw new Error("INVALID_BATCH: batch must be a positive integer");
304
+ }
305
+ return Math.min(batch, MAX_ERASE_BATCH);
306
+ }
307
+
308
+ ```
309
+
310
+ ---
311
+
312
+ ## src/client/types.ts
313
+
314
+ ```ts
315
+ /** Public TypeScript surface for the progression client. */
316
+
317
+ export type ProgressState = {
318
+ lastPeriodKey?: string;
319
+ level: number;
320
+ maxStreak: number;
321
+ streak: number;
322
+ updatedAt: number;
323
+ xp: number;
324
+ };
325
+
326
+ export type AccrueResult = {
327
+ leveledUp: boolean;
328
+ previousLevel: number;
329
+ } & ProgressState;
330
+
331
+ export type ActivityResult = {
332
+ streakDelta: number;
333
+ } & ProgressState;
334
+
335
+ export type ProgressionOptions = {
336
+ defaultScope?: string;
337
+ };
338
+
339
+ ```
340
+
341
+ ---
342
+
343
+ ## src/client/index.ts
344
+
345
+ ```ts
346
+ import type {
347
+ FunctionArgs,
348
+ FunctionReference,
349
+ FunctionReturnType,
350
+ } from "convex/server";
351
+
352
+ import { DEFAULT_SCOPE } from "../shared.js";
353
+
354
+ import type {
355
+ AccrueResult,
356
+ ActivityResult,
357
+ ProgressionOptions,
358
+ ProgressState,
359
+ } from "./types.js";
360
+
361
+ export type ProgressionComponent = {
362
+ mutations: {
363
+ accrue: FunctionReference<
364
+ "mutation",
365
+ "internal",
366
+ {
367
+ delta: number;
368
+ key: string;
369
+ scope: string;
370
+ subjectRef: string;
371
+ thresholds: number[];
372
+ },
373
+ AccrueResult
374
+ >;
375
+ eraseSubject: FunctionReference<
376
+ "mutation",
377
+ "internal",
378
+ { batch?: number; scope: string; subjectRef: string },
379
+ number
380
+ >;
381
+ recordActivity: FunctionReference<
382
+ "mutation",
383
+ "internal",
384
+ {
385
+ expectedPrevious?: string;
386
+ key: string;
387
+ periodKey: string;
388
+ scope: string;
389
+ subjectRef: string;
390
+ thresholds: number[];
391
+ },
392
+ ActivityResult
393
+ >;
394
+ reset: FunctionReference<
395
+ "mutation",
396
+ "internal",
397
+ { key: string; scope: string; subjectRef: string },
398
+ null
399
+ >;
400
+ };
401
+ queries: {
402
+ get: FunctionReference<
403
+ "query",
404
+ "internal",
405
+ {
406
+ key: string;
407
+ scope: string;
408
+ subjectRef: string;
409
+ thresholds?: number[];
410
+ },
411
+ null | ProgressState
412
+ >;
413
+ };
414
+ };
415
+
416
+ type RunQueryCtx = {
417
+ runQuery<TQuery extends FunctionReference<"query", "internal">>(
418
+ reference: TQuery,
419
+ arguments_: FunctionArgs<TQuery>,
420
+ ): Promise<FunctionReturnType<TQuery>>;
421
+ };
422
+
423
+ type RunMutationCtx = {
424
+ runMutation<TMutation extends FunctionReference<"mutation", "internal">>(
425
+ reference: TMutation,
426
+ arguments_: FunctionArgs<TMutation>,
427
+ ): Promise<FunctionReturnType<TMutation>>;
428
+ };
429
+
430
+ export class Progression {
431
+ private readonly defaultScope: string;
432
+
433
+ constructor(
434
+ private readonly component: ProgressionComponent,
435
+ options: ProgressionOptions = {},
436
+ ) {
437
+ this.defaultScope = options.defaultScope ?? DEFAULT_SCOPE;
438
+ }
439
+
440
+ private scopeOf(scope?: string): string {
441
+ return scope ?? this.defaultScope;
442
+ }
443
+
444
+ // Public positional API retained for compatibility.
445
+ // eslint-disable-next-line max-params
446
+ accrue(
447
+ ctx: RunMutationCtx,
448
+ subjectRef: string,
449
+ key: string,
450
+ delta: number,
451
+ thresholds: number[],
452
+ scope?: string,
453
+ ): Promise<AccrueResult> {
454
+ return ctx.runMutation(this.component.mutations.accrue, {
455
+ delta,
456
+ key,
457
+ scope: this.scopeOf(scope),
458
+ subjectRef,
459
+ thresholds,
460
+ });
461
+ }
462
+
463
+ // Public positional API retained for compatibility.
464
+ // eslint-disable-next-line max-params
465
+ recordActivity(
466
+ ctx: RunMutationCtx,
467
+ subjectRef: string,
468
+ key: string,
469
+ periodKey: string,
470
+ thresholds: number[],
471
+ options: { expectedPrevious?: string; scope?: string } = {},
472
+ ): Promise<ActivityResult> {
473
+ return ctx.runMutation(this.component.mutations.recordActivity, {
474
+ expectedPrevious: options.expectedPrevious,
475
+ key,
476
+ periodKey,
477
+ scope: this.scopeOf(options.scope),
478
+ subjectRef,
479
+ thresholds,
480
+ });
481
+ }
482
+
483
+ // Public positional API retained for compatibility.
484
+ // eslint-disable-next-line max-params
485
+ get(
486
+ ctx: RunQueryCtx,
487
+ subjectRef: string,
488
+ key: string,
489
+ scope?: string,
490
+ thresholds?: number[],
491
+ ): Promise<null | ProgressState> {
492
+ return ctx.runQuery(this.component.queries.get, {
493
+ key,
494
+ scope: this.scopeOf(scope),
495
+ subjectRef,
496
+ thresholds,
497
+ });
498
+ }
499
+
500
+ // Public positional API retained for compatibility.
501
+ // eslint-disable-next-line max-params
502
+ reset(
503
+ ctx: RunMutationCtx,
504
+ subjectRef: string,
505
+ key: string,
506
+ scope?: string,
507
+ ): Promise<null> {
508
+ return ctx.runMutation(this.component.mutations.reset, {
509
+ key,
510
+ scope: this.scopeOf(scope),
511
+ subjectRef,
512
+ });
513
+ }
514
+
515
+ // Public positional API retained for compatibility.
516
+ // eslint-disable-next-line max-params
517
+ eraseSubject(
518
+ ctx: RunMutationCtx,
519
+ subjectRef: string,
520
+ scope?: string,
521
+ batch?: number,
522
+ ): Promise<number> {
523
+ return ctx.runMutation(this.component.mutations.eraseSubject, {
524
+ batch,
525
+ scope: this.scopeOf(scope),
526
+ subjectRef,
527
+ });
528
+ }
529
+ }
530
+
531
+ export {
532
+ type AccrueResult,
533
+ type ActivityResult,
534
+ type ProgressionOptions,
535
+ type ProgressState,
536
+ } from "./types.js";
537
+
538
+ ```
539
+
540
+ ---
541
+
542
+ ## src/component/schema.ts
543
+
544
+ ```ts
545
+ import { defineSchema, defineTable } from "convex/server";
546
+ import { v } from "convex/values";
547
+
548
+ /**
549
+ * Sandboxed tables — XP / level / streak per opaque `(scope, subjectRef, key)`.
550
+ * Thresholds are host-supplied on each write so the component never stores a
551
+ * domain-shaped definition table.
552
+ */
553
+ export default defineSchema({
554
+ progress: defineTable({
555
+ key: v.string(),
556
+ lastPeriodKey: v.optional(v.string()),
557
+ level: v.number(),
558
+ maxStreak: v.number(),
559
+ scope: v.string(),
560
+ streak: v.number(),
561
+ subjectRef: v.string(),
562
+ updatedAt: v.number(),
563
+ xp: v.number(),
564
+ }).index("by_scope_subject_key", ["scope", "subjectRef", "key"]),
565
+ });
566
+
567
+ ```
568
+
569
+ ---
570
+
571
+ ## src/component/validators.ts
572
+
573
+ ```ts
574
+ import { v } from "convex/values";
575
+
576
+ const progressFields = {
577
+ lastPeriodKey: v.optional(v.string()),
578
+ level: v.number(),
579
+ maxStreak: v.number(),
580
+ streak: v.number(),
581
+ updatedAt: v.number(),
582
+ xp: v.number(),
583
+ };
584
+
585
+ export const progressState = v.object(progressFields);
586
+
587
+ export const accrueResult = v.object({
588
+ ...progressFields,
589
+ leveledUp: v.boolean(),
590
+ previousLevel: v.number(),
591
+ });
592
+
593
+ export const activityResult = v.object({
594
+ ...progressFields,
595
+ streakDelta: v.number(),
596
+ });
597
+
598
+ ```
599
+
600
+ ---
601
+
602
+ ## src/component/validation.ts
603
+
604
+ ```ts
605
+ import { ConvexError } from "convex/values";
606
+
607
+ import { assertThresholds, MAX_REF_LENGTH } from "../shared";
608
+
609
+ export function fail(code: string, message: string): never {
610
+ throw new ConvexError({ code, message });
611
+ }
612
+
613
+ export function requireRef(value: string, name: string): void {
614
+ if (value.length === 0 || value.length > MAX_REF_LENGTH) {
615
+ fail(
616
+ "INVALID_REF",
617
+ `${name} must be 1..${String(MAX_REF_LENGTH)} characters`,
618
+ );
619
+ }
620
+ }
621
+
622
+ export function parseThresholds(thresholds: number[]): number[] {
623
+ try {
624
+ assertThresholds(thresholds);
625
+ } catch (error) {
626
+ fail(
627
+ "INVALID_THRESHOLDS",
628
+ String(error)
629
+ .replace(/^Error:\s*/, "")
630
+ .replace(/^INVALID_THRESHOLDS:\s*/, ""),
631
+ );
632
+ }
633
+ return thresholds;
634
+ }
635
+
636
+ ```
637
+
638
+ ---
639
+
640
+ ## src/component/mutations.ts
641
+
642
+ ```ts
643
+ import { v } from "convex/values";
644
+
645
+ import { DEFAULT_ERASE_BATCH, levelForXp, MAX_ERASE_BATCH } from "../shared";
646
+
647
+ import { api } from "./_generated/api";
648
+ import { mutation } from "./_generated/server";
649
+ import { fail, parseThresholds, requireRef } from "./validation";
650
+ import { accrueResult, activityResult } from "./validators";
651
+
652
+ export const accrue = mutation({
653
+ args: {
654
+ delta: v.number(),
655
+ key: v.string(),
656
+ scope: v.string(),
657
+ subjectRef: v.string(),
658
+ thresholds: v.array(v.number()),
659
+ },
660
+ // Keep each atomic transaction readable as one handler.
661
+ // eslint-disable-next-line max-lines-per-function
662
+ handler: async (ctx, arguments_) => {
663
+ requireRef(arguments_.subjectRef, "subjectRef");
664
+ requireRef(arguments_.key, "key");
665
+ requireRef(arguments_.scope, "scope");
666
+ if (
667
+ !Number.isFinite(arguments_.delta) ||
668
+ arguments_.delta <= 0 ||
669
+ arguments_.delta > Number.MAX_SAFE_INTEGER
670
+ ) {
671
+ fail(
672
+ "INVALID_DELTA",
673
+ "delta must be positive and at most MAX_SAFE_INTEGER",
674
+ );
675
+ }
676
+ const thresholds = parseThresholds(arguments_.thresholds);
677
+ const existing = await ctx.db
678
+ .query("progress")
679
+ .withIndex("by_scope_subject_key", (q) =>
680
+ q
681
+ .eq("scope", arguments_.scope)
682
+ .eq("subjectRef", arguments_.subjectRef)
683
+ .eq("key", arguments_.key),
684
+ )
685
+ .unique();
686
+ const now = Date.now();
687
+ const previousLevel = existing?.level ?? 0;
688
+ const xp = (existing?.xp ?? 0) + arguments_.delta;
689
+ if (
690
+ !Number.isFinite(xp) ||
691
+ xp > Number.MAX_SAFE_INTEGER ||
692
+ xp <= (existing?.xp ?? 0)
693
+ ) {
694
+ fail(
695
+ "XP_OVERFLOW",
696
+ "XP exceeds the safe bound or delta is lost to floating-point precision",
697
+ );
698
+ }
699
+ const level = levelForXp(xp, thresholds);
700
+ const row = {
701
+ lastPeriodKey: existing?.lastPeriodKey,
702
+ level,
703
+ maxStreak: existing?.maxStreak ?? 0,
704
+ streak: existing?.streak ?? 0,
705
+ updatedAt: now,
706
+ xp,
707
+ };
708
+ await (existing === null
709
+ ? ctx.db.insert("progress", {
710
+ key: arguments_.key,
711
+ scope: arguments_.scope,
712
+ subjectRef: arguments_.subjectRef,
713
+ ...row,
714
+ })
715
+ : ctx.db.patch("progress", existing._id, row));
716
+ return { ...row, leveledUp: level > previousLevel, previousLevel };
717
+ },
718
+ returns: accrueResult,
719
+ });
720
+
721
+ export const recordActivity = mutation({
722
+ args: {
723
+ expectedPrevious: v.optional(v.string()),
724
+ key: v.string(),
725
+ periodKey: v.string(),
726
+ scope: v.string(),
727
+ subjectRef: v.string(),
728
+ thresholds: v.array(v.number()),
729
+ },
730
+ // Keep each atomic transaction readable as one handler.
731
+ // eslint-disable-next-line max-lines-per-function
732
+ handler: async (ctx, arguments_) => {
733
+ requireRef(arguments_.subjectRef, "subjectRef");
734
+ requireRef(arguments_.key, "key");
735
+ requireRef(arguments_.scope, "scope");
736
+ requireRef(arguments_.periodKey, "periodKey");
737
+ if (arguments_.expectedPrevious !== undefined) {
738
+ requireRef(arguments_.expectedPrevious, "expectedPrevious");
739
+ }
740
+ const thresholds = parseThresholds(arguments_.thresholds);
741
+ const existing = await ctx.db
742
+ .query("progress")
743
+ .withIndex("by_scope_subject_key", (q) =>
744
+ q
745
+ .eq("scope", arguments_.scope)
746
+ .eq("subjectRef", arguments_.subjectRef)
747
+ .eq("key", arguments_.key),
748
+ )
749
+ .unique();
750
+ const now = Date.now();
751
+ const xp = existing?.xp ?? 0;
752
+ const lastPeriodKey = existing?.lastPeriodKey;
753
+ const samePeriod = lastPeriodKey === arguments_.periodKey;
754
+ const consecutive =
755
+ lastPeriodKey !== undefined &&
756
+ lastPeriodKey === arguments_.expectedPrevious;
757
+ const continuedStreak =
758
+ consecutive && existing !== null ? existing.streak + 1 : 1;
759
+ const streak =
760
+ samePeriod && existing !== null ? existing.streak : continuedStreak;
761
+ if (!Number.isSafeInteger(streak)) {
762
+ fail("STREAK_OVERFLOW", "streak exceeds MAX_SAFE_INTEGER");
763
+ }
764
+ const streakDelta = samePeriod ? 0 : 1;
765
+ const row = {
766
+ lastPeriodKey: arguments_.periodKey,
767
+ level: levelForXp(xp, thresholds),
768
+ maxStreak: Math.max(existing?.maxStreak ?? 0, streak),
769
+ streak,
770
+ updatedAt: now,
771
+ xp,
772
+ };
773
+ await (existing === null
774
+ ? ctx.db.insert("progress", {
775
+ key: arguments_.key,
776
+ scope: arguments_.scope,
777
+ subjectRef: arguments_.subjectRef,
778
+ ...row,
779
+ })
780
+ : ctx.db.patch("progress", existing._id, row));
781
+ return { ...row, streakDelta };
782
+ },
783
+ returns: activityResult,
784
+ });
785
+
786
+ export const reset = mutation({
787
+ args: {
788
+ key: v.string(),
789
+ scope: v.string(),
790
+ subjectRef: v.string(),
791
+ },
792
+ handler: async (ctx, arguments_) => {
793
+ requireRef(arguments_.subjectRef, "subjectRef");
794
+ requireRef(arguments_.key, "key");
795
+ requireRef(arguments_.scope, "scope");
796
+ const existing = await ctx.db
797
+ .query("progress")
798
+ .withIndex("by_scope_subject_key", (q) =>
799
+ q
800
+ .eq("scope", arguments_.scope)
801
+ .eq("subjectRef", arguments_.subjectRef)
802
+ .eq("key", arguments_.key),
803
+ )
804
+ .unique();
805
+ if (existing !== null) {
806
+ await ctx.db.delete("progress", existing._id);
807
+ }
808
+ return null;
809
+ },
810
+ returns: v.null(),
811
+ });
812
+
813
+ export const eraseSubject = mutation({
814
+ args: {
815
+ batch: v.optional(v.number()),
816
+ scope: v.string(),
817
+ subjectRef: v.string(),
818
+ },
819
+ handler: async (ctx, arguments_) => {
820
+ requireRef(arguments_.subjectRef, "subjectRef");
821
+ requireRef(arguments_.scope, "scope");
822
+ const raw = arguments_.batch ?? DEFAULT_ERASE_BATCH;
823
+ if (!Number.isInteger(raw)) {
824
+ fail("INVALID_BATCH", "batch must be a positive integer");
825
+ }
826
+ if (raw < 1) {
827
+ fail("INVALID_BATCH", "batch must be a positive integer");
828
+ }
829
+ const batch = Math.min(raw, MAX_ERASE_BATCH);
830
+ const rows = await ctx.db
831
+ .query("progress")
832
+ .withIndex("by_scope_subject_key", (q) =>
833
+ q.eq("scope", arguments_.scope).eq("subjectRef", arguments_.subjectRef),
834
+ )
835
+ .take(batch);
836
+ await Promise.all(rows.map((row) => ctx.db.delete("progress", row._id)));
837
+ if (rows.length === batch) {
838
+ await ctx.scheduler.runAfter(0, api.mutations.eraseSubject, {
839
+ batch,
840
+ scope: arguments_.scope,
841
+ subjectRef: arguments_.subjectRef,
842
+ });
843
+ }
844
+ return rows.length;
845
+ },
846
+ returns: v.number(),
847
+ });
848
+
849
+ ```
850
+
851
+ ---
852
+
853
+ ## src/component/queries.ts
854
+
855
+ ```ts
856
+ import { v } from "convex/values";
857
+
858
+ import { levelForXp } from "../shared";
859
+
860
+ import { query } from "./_generated/server";
861
+ import { parseThresholds, requireRef } from "./validation";
862
+ import { progressState } from "./validators";
863
+
864
+ export const get = query({
865
+ args: {
866
+ key: v.string(),
867
+ scope: v.string(),
868
+ subjectRef: v.string(),
869
+ thresholds: v.optional(v.array(v.number())),
870
+ },
871
+ // Keep boundary validation and indexed read together.
872
+ // eslint-disable-next-line max-lines-per-function
873
+ handler: async (ctx, arguments_) => {
874
+ requireRef(arguments_.subjectRef, "subjectRef");
875
+ requireRef(arguments_.key, "key");
876
+ requireRef(arguments_.scope, "scope");
877
+ if (arguments_.thresholds !== undefined) {
878
+ parseThresholds(arguments_.thresholds);
879
+ }
880
+ const row = await ctx.db
881
+ .query("progress")
882
+ .withIndex("by_scope_subject_key", (q) =>
883
+ q
884
+ .eq("scope", arguments_.scope)
885
+ .eq("subjectRef", arguments_.subjectRef)
886
+ .eq("key", arguments_.key),
887
+ )
888
+ .unique();
889
+ if (row === null) {
890
+ return null;
891
+ }
892
+ return {
893
+ lastPeriodKey: row.lastPeriodKey,
894
+ level:
895
+ arguments_.thresholds === undefined
896
+ ? row.level
897
+ : levelForXp(row.xp, arguments_.thresholds),
898
+ maxStreak: row.maxStreak,
899
+ streak: row.streak,
900
+ updatedAt: row.updatedAt,
901
+ xp: row.xp,
902
+ };
903
+ },
904
+ returns: v.union(v.null(), progressState),
905
+ });
906
+
907
+ ```
908
+
909
+ ---
910
+
911
+ ## src/test.ts
912
+
913
+ ```ts
914
+ import type { TestConvex } from "convex-test";
915
+
916
+ import schema from "./component/schema.js";
917
+
918
+ const modules = import.meta.glob([
919
+ "./component/**/*.ts",
920
+ "!./component/**/*.test.ts",
921
+ ]);
922
+
923
+ export function register(
924
+ t: Pick<TestConvex<typeof schema>, "registerComponent">,
925
+ name = "progression",
926
+ ): void {
927
+ t.registerComponent(name, schema, modules);
928
+ }
929
+
930
+ ```