cursedbelt-server 4.47.1 → 4.48.1

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 (203) hide show
  1. package/dist/server/activity/store.d.ts +1 -1
  2. package/dist/server/analytics/injectedScripts.d.ts +1 -1
  3. package/dist/server/analytics/injectedScripts.js +1 -1
  4. package/dist/server/analytics/webAnalytics.d.ts +1 -1
  5. package/dist/server/analytics/webAnalytics.js +1 -1
  6. package/dist/server/auth/loginThrottleDurable.d.ts +3 -3
  7. package/dist/server/auth/loginThrottleDurable.js +3 -3
  8. package/dist/server/auth/passwordCost.js +1 -1
  9. package/dist/server/ctgrChunkDurable.d.ts +1 -1
  10. package/dist/server/ctgrChunkDurable.js +1 -1
  11. package/dist/server/d1/backup.d.ts +1 -1
  12. package/dist/server/d1/backup.js +1 -1
  13. package/dist/server/d1/http.d.ts +2 -2
  14. package/dist/server/d1/http.js +2 -2
  15. package/dist/server/d1/invocation.js +1 -1
  16. package/dist/server/d1/limits.d.ts +1 -1
  17. package/dist/server/d1/limits.js +1 -1
  18. package/dist/server/d1/scheduling.d.ts +1 -1
  19. package/dist/server/d1/scheduling.js +1 -1
  20. package/dist/server/d1/types.d.ts +1 -1
  21. package/dist/server/d1/types.js +1 -1
  22. package/dist/server/d1/values.d.ts +1 -1
  23. package/dist/server/d1/values.js +1 -1
  24. package/dist/server/dropzone/scan.d.ts +1 -1
  25. package/dist/server/engagement/actions.d.ts +20 -0
  26. package/dist/server/engagement/actions.js +62 -0
  27. package/dist/server/engagement/api.d.ts +13 -2
  28. package/dist/server/engagement/api.js +30 -2
  29. package/dist/server/engagement/d1.d.ts +13 -2
  30. package/dist/server/engagement/d1.js +30 -2
  31. package/dist/server/engagement/index.d.ts +5 -4
  32. package/dist/server/engagement/index.js +3 -2
  33. package/dist/server/engagement/manifestPlaces.d.ts +7 -1
  34. package/dist/server/engagement/manifestPlaces.js +21 -0
  35. package/dist/server/engagement/places.d.ts +3 -0
  36. package/dist/server/engagement/places.js +9 -2
  37. package/dist/server/engagement/policy.d.ts +21 -0
  38. package/dist/server/engagement/policy.js +27 -0
  39. package/dist/server/engagement/store.d.ts +12 -3
  40. package/dist/server/engagement/store.js +30 -2
  41. package/dist/server/engagement/summary.d.ts +15 -1
  42. package/dist/server/engagement/summary.js +15 -0
  43. package/dist/server/engagement/types.d.ts +9 -0
  44. package/dist/server/guard/argon2Binding.js +1 -1
  45. package/dist/server/guard/kdfWorkerEntry.js +2 -2
  46. package/dist/server/incidents/index.d.ts +1 -1
  47. package/dist/server/incidents/index.js +1 -1
  48. package/dist/server/incidents/store.d.ts +1 -1
  49. package/dist/server/incidents/store.js +1 -1
  50. package/dist/server/jobs/timeout.d.ts +1 -1
  51. package/dist/server/jobs/timeout.js +1 -1
  52. package/dist/server/master-lock/accountsPage.d.ts +1 -1
  53. package/dist/server/master-lock/accountsPage.js +2 -2
  54. package/dist/server/master-lock/guard.js +1 -1
  55. package/dist/server/master-lock/lockPage.d.ts +1 -1
  56. package/dist/server/master-lock/lockPage.js +2 -2
  57. package/dist/server/master-lock/masterLock.d.ts +2 -2
  58. package/dist/server/master-lock/masterLock.js +2 -2
  59. package/dist/server/metrics/normalizeRoute.js +1 -1
  60. package/dist/server/metrics/telemetrySink.d.ts +2 -2
  61. package/dist/server/metrics/telemetrySink.js +1 -1
  62. package/dist/server/middleware/zValidator.js +2 -2
  63. package/dist/server/notifications/hub.js +1 -1
  64. package/dist/server/requestLog/requestMetrics.d.ts +2 -2
  65. package/dist/server/requestLog/requestMetrics.js +2 -2
  66. package/dist/server/retention/archive.d.ts +1 -1
  67. package/dist/server/retention/archive.js +2 -2
  68. package/dist/server/satellite/config.js +2 -2
  69. package/dist/server/satellite/door.d.ts +1 -1
  70. package/dist/server/sharing/contract.d.ts +1 -1
  71. package/dist/server/storage/binaryStore.d.ts +1 -1
  72. package/dist/server/storage/binaryStore.js +3 -3
  73. package/dist/server/storage/derivatives.d.ts +2 -2
  74. package/dist/server/storage/derivatives.js +2 -2
  75. package/dist/server/storage/files/adapter.d.ts +2 -2
  76. package/dist/server/storage/files/adapter.js +10 -10
  77. package/dist/server/storage/files/catalogue.d.ts +1 -1
  78. package/dist/server/storage/files/catalogue.js +4 -4
  79. package/dist/server/storage/files/chunkedUpload.d.ts +2 -2
  80. package/dist/server/storage/files/chunkedUpload.js +1 -1
  81. package/dist/server/storage/files/fileRoutes.d.ts +1 -1
  82. package/dist/server/storage/files/fileRoutes.js +4 -4
  83. package/dist/server/storage/files/mimeByExt.js +1 -1
  84. package/dist/server/storage/files/stack.d.ts +2 -2
  85. package/dist/server/storage/files/types.d.ts +4 -4
  86. package/dist/server/storage/files/types.js +1 -1
  87. package/dist/server/storage/index.js +1 -1
  88. package/dist/server/storage/objectStoreMediaStore.js +1 -1
  89. package/dist/server/storage/transcodeJobs.js +5 -5
  90. package/dist/server/storage/types.d.ts +1 -1
  91. package/dist/server/storage/types.js +1 -1
  92. package/dist/server/storage/videoDerivativeKeys.d.ts +1 -1
  93. package/dist/server/storage/videoDerivativeKeys.js +1 -1
  94. package/dist/server/storage/videoProcessor.js +1 -1
  95. package/dist/server/sync/status.d.ts +1 -1
  96. package/dist/server/zipStream.d.ts +1 -1
  97. package/dist/server/zipStream.js +1 -1
  98. package/docs/activity.md +2 -2
  99. package/docs/engagement.md +10 -1
  100. package/docs/retention.md +2 -2
  101. package/package.json +1 -1
  102. package/src/leafSubpathsImportNothing.spec.ts +1 -1
  103. package/src/namedSubpathsResolve.spec.ts +1 -1
  104. package/src/noTimerDialsAPeer.spec.ts +1 -1
  105. package/src/nodeBuiltinsAreProbedByCalling.spec.ts +1 -1
  106. package/src/publishShape.spec.ts +1 -1
  107. package/src/server/activity/store.ts +1 -1
  108. package/src/server/analytics/injectedScripts.spec.ts +1 -1
  109. package/src/server/analytics/injectedScripts.ts +1 -1
  110. package/src/server/analytics/webAnalytics.ts +1 -1
  111. package/src/server/auth/loginThrottleDurable.ts +3 -3
  112. package/src/server/auth/passwordCost.ts +1 -1
  113. package/src/server/bench/cpuBudget.spec.ts +1 -1
  114. package/src/server/bench/tail.spec.ts +1 -1
  115. package/src/server/ctgrChunkDurable.ts +1 -1
  116. package/src/server/d1/backup.spec.ts +1 -1
  117. package/src/server/d1/backup.ts +1 -1
  118. package/src/server/d1/http.ts +2 -2
  119. package/src/server/d1/invocation.spec.ts +1 -1
  120. package/src/server/d1/invocation.ts +1 -1
  121. package/src/server/d1/limits.ts +1 -1
  122. package/src/server/d1/pullD1.spec.ts +1 -1
  123. package/src/server/d1/scheduling.ts +1 -1
  124. package/src/server/d1/types.ts +1 -1
  125. package/src/server/d1/values.ts +1 -1
  126. package/src/server/dropzone/scan.spec.ts +2 -2
  127. package/src/server/dropzone/scan.ts +1 -1
  128. package/src/server/engagement/actions.ts +71 -0
  129. package/src/server/engagement/api.ts +36 -1
  130. package/src/server/engagement/d1.spec.ts +49 -3
  131. package/src/server/engagement/d1.ts +35 -2
  132. package/src/server/engagement/engagement.spec.ts +103 -1
  133. package/src/server/engagement/index.ts +5 -2
  134. package/src/server/engagement/manifestPlaces.ts +21 -1
  135. package/src/server/engagement/places.ts +12 -2
  136. package/src/server/engagement/policy.ts +34 -0
  137. package/src/server/engagement/store.ts +33 -4
  138. package/src/server/engagement/summary.ts +33 -0
  139. package/src/server/engagement/types.ts +10 -0
  140. package/src/server/google-oauth/googleOAuth.spec.ts +1 -1
  141. package/src/server/guard/argon2Binding.ts +1 -1
  142. package/src/server/guard/kdfWorkerEntry.ts +2 -2
  143. package/src/server/incidents/index.ts +1 -1
  144. package/src/server/incidents/store.ts +1 -1
  145. package/src/server/jobs/timeout.ts +1 -1
  146. package/src/server/master-lock/accountsPage.spec.ts +2 -2
  147. package/src/server/master-lock/accountsPage.ts +2 -2
  148. package/src/server/master-lock/beaconNeverReachesTheWall.spec.ts +2 -2
  149. package/src/server/master-lock/guard.spec.ts +2 -2
  150. package/src/server/master-lock/guard.ts +1 -1
  151. package/src/server/master-lock/lockPage.spec.ts +1 -1
  152. package/src/server/master-lock/lockPage.ts +2 -2
  153. package/src/server/master-lock/masterLock.spec.ts +1 -1
  154. package/src/server/master-lock/masterLock.ts +2 -2
  155. package/src/server/master-lock/sessions.spec.ts +1 -1
  156. package/src/server/metrics/normalizeRoute.ts +1 -1
  157. package/src/server/metrics/telemetrySink.ts +3 -3
  158. package/src/server/middleware/bodyLimit.spec.ts +1 -1
  159. package/src/server/middleware/zValidator.spec.ts +3 -3
  160. package/src/server/middleware/zValidator.ts +3 -3
  161. package/src/server/notifications/hub.ts +1 -1
  162. package/src/server/requestLog/requestMetrics.spec.ts +2 -2
  163. package/src/server/requestLog/requestMetrics.ts +3 -3
  164. package/src/server/retention/archive.spec.ts +2 -2
  165. package/src/server/retention/archive.ts +2 -2
  166. package/src/server/satellite/config.ts +2 -2
  167. package/src/server/satellite/door.ts +1 -1
  168. package/src/server/satellite/satellite.spec.ts +1 -1
  169. package/src/server/sharing/contract.ts +1 -1
  170. package/src/server/storage/binaryServerProcessing.spec.ts +1 -1
  171. package/src/server/storage/binaryServerProcessing.ts +4 -4
  172. package/src/server/storage/binaryStore.spec.ts +6 -6
  173. package/src/server/storage/binaryStore.ts +4 -4
  174. package/src/server/storage/chunked.integration.spec.ts +2 -2
  175. package/src/server/storage/derivatives.ts +2 -2
  176. package/src/server/storage/fileUploadClient.integration.spec.ts +1 -1
  177. package/src/server/storage/files/adapter.photo.spec.ts +2 -2
  178. package/src/server/storage/files/adapter.spec.ts +3 -3
  179. package/src/server/storage/files/adapter.ts +10 -10
  180. package/src/server/storage/files/catalogue.spec.ts +1 -1
  181. package/src/server/storage/files/catalogue.ts +4 -4
  182. package/src/server/storage/files/chunkedUpload.spec.ts +5 -5
  183. package/src/server/storage/files/chunkedUpload.ts +3 -3
  184. package/src/server/storage/files/fileRoutes.spec.ts +3 -3
  185. package/src/server/storage/files/fileRoutes.ts +5 -5
  186. package/src/server/storage/files/mimeByExt.ts +1 -1
  187. package/src/server/storage/files/stack.ts +3 -3
  188. package/src/server/storage/files/types.ts +6 -6
  189. package/src/server/storage/index.ts +1 -1
  190. package/src/server/storage/objectStoreMediaStore.ts +1 -1
  191. package/src/server/storage/sources.ts +1 -1
  192. package/src/server/storage/transcodeJobs.ts +5 -5
  193. package/src/server/storage/types.ts +2 -2
  194. package/src/server/storage/uploadSession.spec.ts +1 -1
  195. package/src/server/storage/videoDerivativeKeys.spec.ts +3 -3
  196. package/src/server/storage/videoDerivativeKeys.ts +1 -1
  197. package/src/server/storage/videoProcessor.ts +1 -1
  198. package/src/server/sync/status.ts +1 -1
  199. package/src/server/sync/timer.spec.ts +1 -1
  200. package/src/server/worker-argon2/index.spec.ts +1 -1
  201. package/src/server/zipStream.spec.ts +2 -2
  202. package/src/server/zipStream.ts +1 -1
  203. package/src/shippedFilesAreTracked.spec.ts +2 -2
@@ -141,7 +141,7 @@ const LEAVES = [
141
141
  * in 4.1.0 from five app-side copies, and it is the module that decides whether a ROM
142
142
  * byte, a photograph, a song and a scanned document are readable — so every app takes
143
143
  * it, and none of them may pay `sharp`/`otplib`/`kysely` for the privilege. It sits
144
- * in `src/server/storage/` beside the file-catalogue and transcode graph, which is
144
+ * in `src/server/storage/` beside the file-catalog and transcode graph, which is
145
145
  * exactly the barrel this must never be reached through: `./storage`'s index is heavy
146
146
  * and this module's whole point is that it costs `node:crypto` and nothing else.
147
147
  * Its batched `/internal/ops/meta` client (4.47.0) is a sibling that imports nothing.
@@ -103,7 +103,7 @@ describe('subpaths named in this repo resolve', () => {
103
103
  });
104
104
 
105
105
  it('knows what the manifest exports', () => {
106
- // If `exports` is ever read wrong, every offence below silently becomes one.
106
+ // If `exports` is ever read wrong, every offense below silently becomes one.
107
107
  expect(exported.has('')).toBe(true); // the "." root entry
108
108
  expect(exported.has('/master-lock')).toBe(true);
109
109
  expect(exported.has('/react')).toBe(false); // the react tier stayed in `cursedbelt` at the 2026-09-15 split
@@ -46,7 +46,7 @@ import { fileURLToPath } from 'node:url';
46
46
  * dependency: `sync/timer.ts`'s callback calls `deps.sync(peer)`, which dials, and
47
47
  * that is legitimate (it is the push). A reintroduced `deps.checkRequest(peer)`
48
48
  * would be structurally identical and this check would miss it. Nothing static can
49
- * separate those two — so the strict measurement is **behavioural** and lives in
49
+ * separate those two — so the strict measurement is **behavioral** and lives in
50
50
  * `sync/timer.spec.ts` ("a healthy peer with no local news is dialed ONCE at boot,
51
51
  * then never", 24 simulated hours) and `sync/signal.spec.ts` ("a connected client
52
52
  * issues exactly ONE outbound request, forever"). Those two bound the sync engine
@@ -46,7 +46,7 @@ import { fileURLToPath } from 'node:url';
46
46
  * ## The excuse, and why there is one
47
47
  *
48
48
  * A line carrying `probe-by-calling:ignore` (on it, or on the line above) is allowed — for
49
- * the one honest use left: labelling. `cpuClock.ts` decides by calling and then uses a
49
+ * the one honest use left: labeling. `cpuClock.ts` decides by calling and then uses a
50
50
  * presence check only to say `(absent)` or `(throws)` in the clock's source string. Excuse
51
51
  * the LINE, never delete the rule.
52
52
  *
@@ -65,7 +65,7 @@ describe('publish shape', () => {
65
65
  // npm rejects a "./"-prefixed bin value, calls the NAME invalid, and drops
66
66
  // the entry — with a warning, not an error. The package publishes fine and
67
67
  // installs with no CLI at all. Invisible under a file: link, where the bin
68
- // is linked from the source manifest before npm ever normalises it.
68
+ // is linked from the source manifest before npm ever normalizes it.
69
69
  const bin = (pkg as { bin?: Record<string, string> }).bin ?? {};
70
70
  const prefixed = Object.entries(bin).filter(([, v]) => v.startsWith('./'));
71
71
  expect(
@@ -19,7 +19,7 @@
19
19
  * ```
20
20
  *
21
21
  * ── 🔴 Four properties this file exists to guarantee ────────────────────────
22
- * 1. **Append only.** No update verb, no delete verb, no `TRUNCATE`. Ageing
22
+ * 1. **Append only.** No update verb, no delete verb, no `TRUNCATE`. Aging
23
23
  * rows out is the fleet retention standard's job, through a declaration the
24
24
  * owner can see (`satellite-kit/retention`) — never a silent cutoff here.
25
25
  * 2. **A source is READ, never copied.** `share_events` stays the canonical
@@ -9,7 +9,7 @@ const PAGE = "https://collections.cursedalchemy.com/";
9
9
  * The tag Cloudflare's Automatic Setup appended, byte-for-byte as the zone emitted it on
10
10
  * 2026-09-18 — pinned path, integrity hash, `crossorigin` and all. It is kept in its
11
11
  * AUTOMATIC spelling on purpose: this is the shape that was arriving unasked-for, and a
12
- * checker that only recognised the manual snippet would go quiet the moment somebody turned
12
+ * checker that only recognized the manual snippet would go quiet the moment somebody turned
13
13
  * auto-install back on.
14
14
  */
15
15
  const BEACON =
@@ -41,7 +41,7 @@ export interface InjectedScript {
41
41
  * Every `<script src=…>` in `html` whose origin is NOT `pageUrl`'s.
42
42
  *
43
43
  * Inline scripts are ignored: they are the page's own (most shells here ship one, a pre-paint
44
- * colour-scheme script) and a CSP that refuses them is a different finding from this one.
44
+ * color-scheme script) and a CSP that refuses them is a different finding from this one.
45
45
  * `data:` and `blob:` are ignored for the same reason — neither is a host anything could have
46
46
  * injected.
47
47
  */
@@ -139,7 +139,7 @@ export const WEB_ANALYTICS_PUBLIC_HOST = "cursedalchemy.com";
139
139
  *
140
140
  * A device in GET-only mode (`cursedbelt-core/ctgr-client`) sits behind something that drops
141
141
  * every non-GET, and the beacon reports with a POST to the page's `/cdn-cgi/rum`. It cannot be
142
- * tunnelled the way our own API is — the script is Cloudflare's — so there it only ever failed,
142
+ * tunneled the way our own API is — the script is Cloudflare's — so there it only ever failed,
143
143
  * a red line per page view, and recorded nothing. Not loading it loses no data (2026-10-08).
144
144
  *
145
145
  * The guard reads the URL as well as `localStorage.ctgr`: this script runs before the app's
@@ -11,7 +11,7 @@
11
11
  * spread across N isolates gets N × the global allowance the header calls "the actual defense".
12
12
  *
13
13
  * A Durable Object is the exact shape of the fix: one instance addressed by name, requests to it
14
- * serialised, so every isolate in every colo meets the same counts. It runs the SAME
14
+ * serialized, so every isolate in every colo meets the same counts. It runs the SAME
15
15
  * `createLoginThrottle` algorithm — nothing here re-decides a threshold or a delay — and persists
16
16
  * the ledger to the object's storage after every change, so the object's own eviction (minutes
17
17
  * idle, measured on patterns' live object) forgets nothing either.
@@ -20,10 +20,10 @@
20
20
  * The throttle is checked BEFORE argon2, on every attempt, and the point of checking first is
21
21
  * that a refused attempt is cheap. A D1 read-modify-write per attempt is a query against the
22
22
  * invocation's 1,000-query budget and, worse, not atomic across concurrent invocations: two
23
- * guesses that snapshot the same count both write count+1. The object serialises for free.
23
+ * guesses that snapshot the same count both write count+1. The object serializes for free.
24
24
  *
25
25
  * ── `attempt` is one operation, not two ─────────────────────────────────────
26
- * `/throttle/attempt` checks and charges in one serialised step, so a burst of concurrent guesses
26
+ * `/throttle/attempt` checks and charges in one serialized step, so a burst of concurrent guesses
27
27
  * is admitted only up to the threshold rather than all at once against one stale count. See
28
28
  * `loginThrottle.ts`'s `attempt` section.
29
29
  *
@@ -14,7 +14,7 @@
14
14
  * production cost 52.85 s
15
15
  * test cost 7.32 s
16
16
  *
17
- * Eighty-six per cent of what was, that morning, the largest single workspace in
17
+ * Eighty-six percent of what was, that morning, the largest single workspace in
18
18
  * `verify:scoped` — paid by every agent on every branch touching auth or any shared
19
19
  * package, and again on every union gate.
20
20
  *
@@ -328,7 +328,7 @@ describe('the bench runner', () => {
328
328
  *
329
329
  * Filed 2026-09-19 by the `collections` port — the first app to mount this harness — which
330
330
  * had to leave `POST /api/duplicates/rescan` and `POST /api/recycle/purge`, the only two
331
- * routes in it whose cost is O(catalogue), declared but unbenched for exactly this reason.
331
+ * routes in it whose cost is O(catalog), declared but unbenched for exactly this reason.
332
332
  */
333
333
  describe('a destructive case — the fixture rebuild between iterations', () => {
334
334
  /** ~4 CPU-ms per item held, ~0 CPU-ms when the library is empty. */
@@ -55,7 +55,7 @@ describe('recordTailTraces', () => {
55
55
  expect(report.routes.map((r) => r.key)).toEqual(['GET /api/items/:id']);
56
56
  });
57
57
 
58
- it('🔴 refuses a PROXY recorder — real numbers may not be labelled a proxy, nor the reverse', () => {
58
+ it('🔴 refuses a PROXY recorder — real numbers may not be labeled a proxy, nor the reverse', () => {
59
59
  const recorder = createCpuRecorder({ clock: processCpuClock(), config: BUDGETS });
60
60
  expect(() => recordTailTraces(recorder, [])).toThrow(/is a PROXY/);
61
61
  });
@@ -18,7 +18,7 @@
18
18
  *
19
19
  * ── One object per payload ───────────────────────────────────────────────────
20
20
  * Addressed by `ctgr:<_cid>` (a `crypto.randomUUID()` the client mints per request), so the
21
- * chunks of one request are serialised through one object and different requests never
21
+ * chunks of one request are serialized through one object and different requests never
22
22
  * contend. The partial lives in the object's memory: chunks arrive milliseconds apart, the idle
23
23
  * TTL is 30 s, and an object is only evicted after minutes idle — a partial it loses is one a
24
24
  * deploy would have lost too. An object holding nothing costs nothing.
@@ -98,7 +98,7 @@ describe('the D1 half records a coordinate instead of copying bytes', () => {
98
98
 
99
99
  test('🔴 it reports needsPeriodicCapture: false — Time Travel is automatic', () => {
100
100
  // A nightly no-op job logging "backup complete" is worse than no job, because it
101
- // reads as evidence. A scheduler must honour this flag.
101
+ // reads as evidence. A scheduler must honor this flag.
102
102
  expect(createTimeTravelBackup({ databaseName: 'patterns' }).needsPeriodicCapture).toBe(false);
103
103
  });
104
104
 
@@ -67,7 +67,7 @@ export interface TimeTravelOpts {
67
67
  /**
68
68
  * The D1 implementation: record the coordinate, because retention is automatic.
69
69
  *
70
- * 🔴 It reports `needsPeriodicCapture: false`, and a scheduler must honour that rather
70
+ * 🔴 It reports `needsPeriodicCapture: false`, and a scheduler must honor that rather
71
71
  * than calling `capture()` on a timer — a nightly no-op job that logs "backup complete"
72
72
  * is worse than no job, because it reads as evidence.
73
73
  */
@@ -10,12 +10,12 @@
10
10
  * the only other door into D1 was a per-app bearer route on the Worker for each one.
11
11
  *
12
12
  * So the Mac gets the same {@link D1LikeDatabase} a Worker holds, pointed at the same
13
- * database, and the app's own catalogue code runs unchanged against production — ONE writer
13
+ * database, and the app's own catalog code runs unchanged against production — ONE writer
14
14
  * of the rows, one schema, one set of statements.
15
15
  *
16
16
  * ── How ──────────────────────────────────────────────────────────────────────────────────
17
17
  * It is a {@link D1BindingLike} over `POST /accounts/:account/d1/database/:db/query` (and
18
- * `/raw`), handed to {@link createRemoteD1} — so every value normalisation, limit check and
18
+ * `/raw`), handed to {@link createRemoteD1} — so every value normalization, limit check and
19
19
  * `success: false` guard is the binding driver's own, not a second copy that could drift.
20
20
  * `batch()` sends `{ batch: [...] }`, which D1 runs as one unit exactly as a binding's batch
21
21
  * does: measured 2026-09-23 on a throwaway database, a batch whose second statement violated
@@ -129,7 +129,7 @@ describe('the per-invocation query budget', () => {
129
129
  expect(db.used).toBe(0);
130
130
  });
131
131
 
132
- test('a budget above D1\'s real cap is refused rather than honoured', () => {
132
+ test('a budget above D1\'s real cap is refused rather than honored', () => {
133
133
  expect(() => perInvocation(base, { max: LIMITS.queriesPerInvocation + 1 })).toThrow(D1LimitError);
134
134
  expect(() => perInvocation(base, { max: 0 })).toThrow(RangeError);
135
135
  expect(() => perInvocation(base, { max: 1.5 })).toThrow(RangeError);
@@ -170,7 +170,7 @@ export function perInvocation(db: D1LikeDatabase, opts: { max?: number } = {}):
170
170
  'queries per Worker invocation',
171
171
  max,
172
172
  LIMITS.queriesPerInvocation,
173
- 'A budget above D1\'s own cap cannot be honoured — the service refuses first. Lower it, or split the work across invocations.',
173
+ 'A budget above D1\'s own cap cannot be honored — the service refuses first. Lower it, or split the work across invocations.',
174
174
  );
175
175
  }
176
176
  const budget = new Budget(max);
@@ -226,7 +226,7 @@ export function chunkForBind<T>(items: readonly T[], paramsPerItem: number): T[]
226
226
  * `WHERE … ORDER BY … LIMIT ? OFFSET ?` page and the `COUNT(*)` beside it), and on a write
227
227
  * it trades one atomic statement for a batch that is atomic only per chunk. `json_each`
228
228
  * over a JSON array is one parameter however long the list is, keeps the statement whole,
229
- * and SQLite still drives the column's index through the materialised set.
229
+ * and SQLite still drives the column's index through the materialized set.
230
230
  *
231
231
  * The array travels as one TEXT value, so the ceiling moves from 100 ids to
232
232
  * `LIMITS.valueBytes` (2 MB) of JSON — about 70,000 of this fleet's 25-character ids — and
@@ -324,7 +324,7 @@ describe('pulling D1 down — paged SELECTs, table by table, never an export', (
324
324
 
325
325
  test('a page that blips is asked again at the SAME size — a wire failure is not a page too large', async () => {
326
326
  const source = live("INSERT INTO items VALUES ('i1', 'a');");
327
- // wrangler's coloured form, as patterns' log has it.
327
+ // wrangler's colored form, as patterns' log has it.
328
328
  const { run, seen } = blipping(source, (sql) => sql.includes('FROM "items"'), 1, '✘ \u001b[1mfetch failed\u001b[0m');
329
329
  const slept: number[] = [];
330
330
  await pullWaiting(scratch(), run, slept);
@@ -31,7 +31,7 @@
31
31
  * a 6-field expression with a leading seconds column, and this repo already contains three
32
32
  * jobs declared `'* * * * * *'` — once per second. Those cannot become Cron Triggers at
33
33
  * all, and {@link classifySchedule} says so by name instead of silently rounding them up to
34
- * a minute, which would change behaviour in production and nowhere else.
34
+ * a minute, which would change behavior in production and nowhere else.
35
35
  */
36
36
 
37
37
  import type { D1LikeDatabase } from './types.js';
@@ -40,7 +40,7 @@
40
40
  *
41
41
  * D1 has no interactive transaction — there is no `BEGIN`/`COMMIT` over HTTP, only
42
42
  * {@link D1LikeDatabase.batch}, which is atomic and runs as one round trip. A local
43
- * driver that happily honoured `BEGIN` would be the sync-vs-async trap a third time, so
43
+ * driver that happily honored `BEGIN` would be the sync-vs-async trap a third time, so
44
44
  * {@link D1UnsupportedError} is thrown by both. Wrap the statements in `batch()` instead;
45
45
  * it is atomic on D1 and wrapped in a real `bun:sqlite` transaction locally, so the
46
46
  * guarantee is the same.
@@ -97,7 +97,7 @@ const LEADING_NOISE = /^(?:\s|--[^\n]*\n?|\/\*[\s\S]*?\*\/)+/;
97
97
  * Only a leading `SELECT` is claimed, because that is the one keyword that is
98
98
  * unambiguous: `WITH … INSERT … RETURNING` and `INSERT … RETURNING` both return rows AND
99
99
  * write. Anything this returns `false` for is measured exactly instead (see
100
- * `local.ts`), so a statement shape this does not recognise costs two extra queries —
100
+ * `local.ts`), so a statement shape this does not recognize costs two extra queries —
101
101
  * never a wrong number.
102
102
  */
103
103
  export const isPureReadSql = (sql: string): boolean => /^select\b/i.test(sql.replace(LEADING_NOISE, ''));
@@ -61,7 +61,7 @@ describe("scanDropzone", () => {
61
61
 
62
62
  test("captureSiblings records each directory's file list on the ONE walk", async () => {
63
63
  // A folder's cover.jpg is only reachable while the directory still exists, and filing
64
- // the audio out of it removes the neighbours. Re-reading later finds nothing.
64
+ // the audio out of it removes the neighbors. Re-reading later finds nothing.
65
65
  write("Album/track.mp3");
66
66
  write("Album/cover.jpg");
67
67
  const found = await scanDropzone(root, { captureSiblings: true });
@@ -113,7 +113,7 @@ describe("sweepDropzone — what gets deleted", () => {
113
113
  expect(report.failed).toHaveLength(1);
114
114
  });
115
115
 
116
- test("🔴 a DUPLICATE is deleted — that is the point of recognising one", async () => {
116
+ test("🔴 a DUPLICATE is deleted — that is the point of recognizing one", async () => {
117
117
  // "if it's a dup skip it then delete it". The bytes are already safe at the destination,
118
118
  // so keeping the local copy is exactly the two-copies problem the owner is solving.
119
119
  write("already-have.mp3");
@@ -89,7 +89,7 @@ export interface ScanOptions {
89
89
  *
90
90
  * 🔴 Load-bearing for sidecar art, and it cannot be done later. A folder's `cover.jpg` is
91
91
  * only reachable while the directory still exists, and filing the audio out of it removes
92
- * the neighbours — by the time anything else could look, they are gone. Capturing on the
92
+ * the neighbors — by the time anything else could look, they are gone. Capturing on the
93
93
  * walk also costs one `readdir` per directory instead of one per file, which on a 6,000
94
94
  * track library is the difference between seconds and minutes.
95
95
  */
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Feature ACTIONS — what somebody DID on a page, beside where they were (task 3470).
3
+ *
4
+ * A place-view answers "which pages do they open". The owner's question goes one step further:
5
+ * *"what features they use and ignore … and know which users to ask first when I am planning to
6
+ * add or delete a feature"*. A page is not a feature — music's library page holds play, search,
7
+ * rate and download — so this records a declared ACTION NAME per (account, place).
8
+ *
9
+ * ── The privacy contract is the places' contract, unchanged ─────────────────
10
+ * The action is a NAME from the app's own `routes.manifest.json` `actions` list
11
+ * (`policy.ts:resolveAction`); the place is resolved against the same manifest as a view. There is
12
+ * no field for a value — `search`, never the query; `play`, never the track — so nothing a person
13
+ * typed or chose can reach a row. The account is the session's subject, never the body's.
14
+ *
15
+ * ── Counts and clocks, two grains ───────────────────────────────────────────
16
+ * engagement_actions (user, place, action) → uses, first, last. LIFETIME, never trimmed:
17
+ * it is the row that answers "who uses this most, and when did they last",
18
+ * and trimming it would make a feature's old regulars vanish.
19
+ * engagement_action_days (user, place, action, day) → uses. Trimmed with the view days, for
20
+ * "used this month" against "used once, long ago".
21
+ * No event log, no sequence: an action does not touch the sessionization clock or dwell.
22
+ *
23
+ * 🔴 Its own DDL, not appended to `ENGAGEMENT_DDL`: an app whose schema is generated from that list
24
+ * (music, family, desk, arch) would otherwise go red on the version bump alone. An app opts in by
25
+ * declaring `actions` and applying {@link ENGAGEMENT_ACTION_DDL}; the Bun store always creates both.
26
+ *
27
+ * Pure and Worker-safe: the Bun store and the D1 recorder both write through
28
+ * {@link actionStatements}, so there is one write, not two that agree.
29
+ */
30
+ import { dayKey } from "./policy.js";
31
+
32
+ export const ENGAGEMENT_ACTION_DDL: readonly string[] = [
33
+ "CREATE TABLE IF NOT EXISTS engagement_actions ( user_key TEXT NOT NULL, place TEXT NOT NULL, action TEXT NOT NULL, uses INTEGER NOT NULL DEFAULT 0, first_ts INTEGER NOT NULL, last_ts INTEGER NOT NULL, PRIMARY KEY (user_key, place, action) )",
34
+ "CREATE TABLE IF NOT EXISTS engagement_action_days ( user_key TEXT NOT NULL, place TEXT NOT NULL, action TEXT NOT NULL, day TEXT NOT NULL, uses INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (user_key, place, action, day) )",
35
+ "CREATE INDEX IF NOT EXISTS idx_engagement_action_days_day ON engagement_action_days (day)",
36
+ ];
37
+
38
+ /** One resolved action, ready to count. `place` and `action` have been through the allowlists. */
39
+ export interface ActionUse {
40
+ userKey: string;
41
+ place: string;
42
+ action: string;
43
+ ts: number;
44
+ }
45
+
46
+ /** The two upserts one action is — run them together (a transaction, or one D1 batch). */
47
+ export function actionStatements(use: ActionUse): Array<{ sql: string; params: (string | number)[] }> {
48
+ const { userKey, place, action, ts } = use;
49
+ return [
50
+ {
51
+ sql: `INSERT INTO engagement_actions (user_key, place, action, uses, first_ts, last_ts)
52
+ VALUES (?, ?, ?, 1, ?, ?)
53
+ ON CONFLICT(user_key, place, action) DO UPDATE SET uses = uses + 1, last_ts = excluded.last_ts`,
54
+ params: [userKey, place, action, ts, ts],
55
+ },
56
+ {
57
+ sql: `INSERT INTO engagement_action_days (user_key, place, action, day, uses)
58
+ VALUES (?, ?, ?, ?, 1)
59
+ ON CONFLICT(user_key, place, action, day) DO UPDATE SET uses = uses + 1`,
60
+ params: [userKey, place, action, dayKey(ts)],
61
+ },
62
+ ];
63
+ }
64
+
65
+ /** Read the claimed `{ place, action }` out of a request body — a string each, or a reason why not. */
66
+ export function claimedAction(body: unknown): { place: string; action: string } | { error: string } {
67
+ const b = body as { place?: unknown; action?: unknown } | null;
68
+ if (typeof b?.action !== "string") return { error: "action must be a string" };
69
+ if (typeof b.place !== "string") return { error: "place must be a string" };
70
+ return { place: b.place, action: b.action };
71
+ }
@@ -3,6 +3,9 @@
3
3
  *
4
4
  * POST /api/engagement/view → the beacon. SESSION-gated; the user id comes
5
5
  * from the session, never from the body.
6
+ * POST /api/engagement/action → a feature used on a page — `{ place, action }`, both
7
+ * NAMES resolved against the manifest (`actions.ts`).
8
+ * Mounted only for an app that passes `actions`.
6
9
  *
7
10
  * 🔴 **There is no HTTP read surface, on purpose** (task `113`/`268`, 2026-09-22).
8
11
  * `GET /api/admin/engagement` used to sit here behind `SATELLITE_METRICS_TOKEN` —
@@ -31,7 +34,8 @@
31
34
  */
32
35
  import { Hono } from "hono";
33
36
  import type { Context } from "hono";
34
- import { OTHER_PLACE, type PlaceRef, resolvePlace } from "./policy.js";
37
+ import { claimedAction } from "./actions.js";
38
+ import { type ActionRef, OTHER_PLACE, type PlaceRef, resolveAction, resolvePlace } from "./policy.js";
35
39
  import type { EngagementStore } from "./store.js";
36
40
  import { type AppEngagement, returnCurve, summarize } from "./summary.js";
37
41
 
@@ -45,6 +49,12 @@ export interface EngagementApiOptions {
45
49
  * rule 1 for why this is the whole privacy story.
46
50
  */
47
51
  places: readonly PlaceRef[];
52
+ /**
53
+ * The allowlist of ACTION names — the manifest's `actions` (`engagementActionsFor`). Present,
54
+ * the recorder grows `POST /action`; an undeclared name records as `other`, as a place does.
55
+ * Absent, there is no action door at all (task 3470).
56
+ */
57
+ actions?: readonly ActionRef[];
48
58
  /** Resolve the CURRENT request's account. Null → 401, nothing recorded. */
49
59
  resolveUser: (c: Context) => string | null;
50
60
  /** Injectable clock, so the tests are not timing-dependent. */
@@ -81,6 +91,26 @@ export function createEngagementRecorder(options: EngagementApiOptions): Hono {
81
91
  return c.json({ ok: true, place, bucketed: place === OTHER_PLACE, ...fold });
82
92
  });
83
93
 
94
+ const actions = options.actions;
95
+ if (actions) {
96
+ app.post("/action", async (c) => {
97
+ const userKey = options.resolveUser(c);
98
+ if (!userKey) return c.json({ error: "unauthenticated" }, 401);
99
+ let body: unknown;
100
+ try {
101
+ body = await c.req.json();
102
+ } catch {
103
+ return c.json({ error: "expected a json body" }, 400);
104
+ }
105
+ const claimed = claimedAction(body);
106
+ if ("error" in claimed) return c.json({ error: claimed.error }, 400);
107
+ const place = resolvePlace(claimed.place, options.places);
108
+ const action = resolveAction(claimed.action, actions);
109
+ options.store.recordAction({ userKey, place, action, ts: now() });
110
+ return c.json({ ok: true, place, action, bucketed: place === OTHER_PLACE || action === OTHER_PLACE });
111
+ });
112
+ }
113
+
84
114
  return app;
85
115
  }
86
116
 
@@ -89,6 +119,8 @@ export interface AppEngagementSnapshot extends AppEngagement {
89
119
  /** The manifest ids this app CAN report — so a reader can show a place
90
120
  * with zero views, which is the half of the question that is easy to lose. */
91
121
  knownPlaces: string[];
122
+ /** The action names this app declares — a declared action nobody used is the "ignored" half. */
123
+ knownActions: string[];
92
124
  returnCurve: Array<{ day: string; joined: number; returned: number }>;
93
125
  retention: { days: number; places: number; users: number; oldestDay: string | null };
94
126
  }
@@ -98,6 +130,7 @@ export function readAppEngagement(
98
130
  app: string,
99
131
  now: number,
100
132
  knownPlaces: readonly PlaceRef[] = [],
133
+ knownActions: readonly ActionRef[] = [],
101
134
  ): AppEngagementSnapshot {
102
135
  const users = store.users();
103
136
  const summary = summarize({
@@ -109,10 +142,12 @@ export function readAppEngagement(
109
142
  // silently return less, which reads as a quiet period rather than as a
110
143
  // window boundary.
111
144
  days: store.days(now - 120 * 86_400_000),
145
+ actions: store.actions(),
112
146
  });
113
147
  return {
114
148
  ...summary,
115
149
  knownPlaces: knownPlaces.map((p) => p.id),
150
+ knownActions: knownActions.map((a) => a.id),
116
151
  returnCurve: returnCurve(users, now),
117
152
  retention: store.stats(),
118
153
  };
@@ -9,8 +9,16 @@ import { tmpdir } from 'node:os';
9
9
  import { join } from 'node:path';
10
10
  import { Hono } from 'hono';
11
11
  import { createLocalD1 } from '../d1/local.js';
12
- import { createD1EngagementRecorder, ENGAGEMENT_DDL, placesFromManifest, recordViewD1 } from './d1.js';
13
- import { engagementPlacesFor } from './places.js';
12
+ import {
13
+ actionsFromManifest,
14
+ createD1EngagementRecorder,
15
+ ENGAGEMENT_ACTION_DDL,
16
+ ENGAGEMENT_DDL,
17
+ placesFromManifest,
18
+ recordActionD1,
19
+ recordViewD1,
20
+ } from './d1.js';
21
+ import { engagementActionsFor, engagementPlacesFor } from './places.js';
14
22
  import { EngagementStore } from './store.js';
15
23
 
16
24
  const dirs: string[] = [];
@@ -25,7 +33,7 @@ const tempDir = (): string => {
25
33
  const kitStore = (): EngagementStore => new EngagementStore({ dbPath: join(tempDir(), 'engagement.sqlite') });
26
34
  const d1 = () => {
27
35
  const sqlite = new Database(':memory:');
28
- for (const ddl of ENGAGEMENT_DDL) sqlite.run(ddl);
36
+ for (const ddl of [...ENGAGEMENT_DDL, ...ENGAGEMENT_ACTION_DDL]) sqlite.run(ddl);
29
37
  return { sqlite, db: createLocalD1(sqlite) };
30
38
  };
31
39
  const shape = (db: Database) =>
@@ -38,6 +46,8 @@ const dump = (db: Database) => ({
38
46
  days: db.query('SELECT * FROM engagement_days ORDER BY user_key, place, day').all(),
39
47
  places: db.query('SELECT * FROM engagement_places ORDER BY user_key, place').all(),
40
48
  users: db.query('SELECT * FROM engagement_users ORDER BY user_key').all(),
49
+ actions: db.query('SELECT * FROM engagement_actions ORDER BY user_key, place, action').all(),
50
+ actionDays: db.query('SELECT * FROM engagement_action_days ORDER BY user_key, place, action, day').all(),
41
51
  });
42
52
 
43
53
  describe('cursedbelt-server/engagement/d1', () => {
@@ -99,4 +109,40 @@ describe('cursedbelt-server/engagement/d1', () => {
99
109
  expect(placesFromManifest('not a manifest')).toEqual([]);
100
110
  expect(placesFromManifest(null)).toEqual([]);
101
111
  });
112
+
113
+ test('🔴 the same actions produce the same rows as the kit store, and the door names only declared ones', async () => {
114
+ const kit = kitStore();
115
+ const { sqlite, db } = d1();
116
+ const t0 = Date.UTC(2026, 9, 22, 10, 0, 0);
117
+ const uses = [
118
+ { userKey: 'u1', place: 'home', action: 'play', ts: t0 },
119
+ { userKey: 'u1', place: 'home', action: 'play', ts: t0 + 60_000 },
120
+ { userKey: 'u2', place: 'home', action: 'search', ts: t0 + 26 * 3_600_000 },
121
+ ];
122
+ for (const u of uses) {
123
+ await recordActionD1(db, u);
124
+ kit.recordAction(u);
125
+ }
126
+ expect(dump(sqlite)).toEqual(dump(kit.handle));
127
+
128
+ const doc = { routes: [{ id: 'home', path: '/' }], actions: [{ id: 'play', label: 'play a track' }, 'search', { id: '' }, 'play'] };
129
+ const actions = actionsFromManifest(doc);
130
+ expect(actions).toEqual([{ id: 'play', label: 'play a track' }, { id: 'search' }]);
131
+ const dir = tempDir();
132
+ await Bun.write(join(dir, 'routes.manifest.json'), JSON.stringify(doc));
133
+ expect(engagementActionsFor(dir)).toEqual(actions);
134
+ expect(actionsFromManifest({ routes: [] })).toEqual([]);
135
+
136
+ const app = new Hono().route(
137
+ '/api/engagement',
138
+ createD1EngagementRecorder({ db, places: placesFromManifest(doc), actions, resolveUser: () => 'u3', now: () => t0 }),
139
+ );
140
+ const res = await app.request('http://x/api/engagement/action', {
141
+ method: 'POST',
142
+ headers: { 'content-type': 'application/json' },
143
+ body: JSON.stringify({ place: '/', action: 'rename playlist "private"' }),
144
+ });
145
+ expect(await res.json()).toMatchObject({ ok: true, place: 'home', action: 'other', bucketed: true });
146
+ expect(sqlite.query("SELECT action FROM engagement_actions WHERE user_key = 'u3'").all()).toEqual([{ action: 'other' }]);
147
+ });
102
148
  });
@@ -31,13 +31,16 @@
31
31
  *
32
32
  * gated.route("/api/engagement", createD1EngagementRecorder({
33
33
  * db, places: placesFromManifest(routesManifest), resolveUser: (c) => sso.userOf(c)?.id ?? null,
34
+ * // Optional — feature actions (task 3470); the D1 then needs ENGAGEMENT_ACTION_DDL too.
35
+ * actions: actionsFromManifest(routesManifest),
34
36
  * }));
35
37
  * ```
36
38
  */
37
39
  import type { D1LikeDatabase } from "../d1/types.js";
38
40
  import type { Context } from "hono";
39
41
  import { Hono } from "hono";
40
- import { dayKey, foldView, OTHER_PLACE, type PlaceRef, resolvePlace } from "./policy.js";
42
+ import { type ActionUse, actionStatements, claimedAction } from "./actions.js";
43
+ import { type ActionRef, dayKey, foldView, OTHER_PLACE, type PlaceRef, resolveAction, resolvePlace } from "./policy.js";
41
44
 
42
45
  /** The kit store's own tables and indexes, as one-line DDL — see the header. */
43
46
  export const ENGAGEMENT_DDL: readonly string[] = [
@@ -107,6 +110,11 @@ export async function recordViewD1(
107
110
  return fold;
108
111
  }
109
112
 
113
+ /** Count one resolved action — the Bun store's `recordAction`, as ONE D1 batch (`./actions.ts`). */
114
+ export async function recordActionD1(db: D1LikeDatabase, use: ActionUse): Promise<void> {
115
+ await db.batch(actionStatements(use).map(({ sql, params }) => db.prepare(sql).bind(...params)));
116
+ }
117
+
110
118
  /**
111
119
  * The recorder as the kit's `createEngagementRecorder` mounts it — `POST /view` under
112
120
  * `ENGAGEMENT_BASE_PATH` — over D1. Recording only: there is no read surface here, as there is
@@ -115,6 +123,11 @@ export async function recordViewD1(
115
123
  export function createD1EngagementRecorder(options: {
116
124
  db: D1LikeDatabase;
117
125
  places: readonly PlaceRef[];
126
+ /**
127
+ * The manifest's declared actions (`actionsFromManifest`). Present, `POST /action` is mounted
128
+ * and the D1 needs {@link ENGAGEMENT_ACTION_DDL} applied; absent, there is no action door.
129
+ */
130
+ actions?: readonly ActionRef[];
118
131
  resolveUser: (c: Context) => string | null;
119
132
  now?: () => number;
120
133
  }): Hono {
@@ -135,7 +148,27 @@ export function createD1EngagementRecorder(options: {
135
148
  const fold = await recordViewD1(options.db, { userKey, place, ts: now() });
136
149
  return c.json({ ok: true, place, bucketed: place === OTHER_PLACE, ...fold });
137
150
  });
151
+ const actions = options.actions;
152
+ if (actions) {
153
+ app.post("/action", async (c) => {
154
+ const userKey = options.resolveUser(c);
155
+ if (!userKey) return c.json({ error: "unauthenticated" }, 401);
156
+ let body: unknown;
157
+ try {
158
+ body = await c.req.json();
159
+ } catch {
160
+ return c.json({ error: "expected a json body" }, 400);
161
+ }
162
+ const claimed = claimedAction(body);
163
+ if ("error" in claimed) return c.json({ error: claimed.error }, 400);
164
+ const place = resolvePlace(claimed.place, options.places);
165
+ const action = resolveAction(claimed.action, actions);
166
+ await recordActionD1(options.db, { userKey, place, action, ts: now() });
167
+ return c.json({ ok: true, place, action, bucketed: place === OTHER_PLACE || action === OTHER_PLACE });
168
+ });
169
+ }
138
170
  return app;
139
171
  }
140
172
 
141
- export { placesFromManifest } from "./manifestPlaces.js";
173
+ export { ENGAGEMENT_ACTION_DDL } from "./actions.js";
174
+ export { actionsFromManifest, placesFromManifest } from "./manifestPlaces.js";