cursedbelt-server 4.56.0 → 4.58.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.
@@ -26,6 +26,20 @@ view days). An app opts in by passing `actions` to the recorder (`engagementActi
26
26
  `actionsFromManifest(json)` on a Worker, whose D1 also needs `ENGAGEMENT_ACTION_DDL`); without it
27
27
  there is no action door.
28
28
 
29
+ **Batched actions (task 4034).** The browser queues actions and sends them as ONE
30
+ `POST <mount>/action {actions: [{place, action, at}…]}` after 5 s of quiet (30 s at most), and at
31
+ `pagehide` or a hidden tab through `navigator.sendBeacon`; a queue of one still posts `{place, action}`,
32
+ so an older server reads it. The door keeps `MAX_ACTION_BATCH` (100) and counts the cut in its reply
33
+ and the log, clamps `at` to the last 10 minutes, and folds repeats into one upsert per
34
+ (place, action, day).
35
+
36
+ **Visits (task 4032).** `engagement_sessions` holds one row per visit: start, end, views and attention,
37
+ cut where the sessions count is cut (`SESSION_GAP_MS`), and no place, so what it adds to the record
38
+ is WHEN and never WHERE. Station uses it to say which apps a person used at the same time. Trimmed
39
+ with the view days. The Bun store creates it; on a Worker `recordViewD1` writes it after the view's
40
+ batch, creates it the first time it is missing, and never fails a view over it, so an app needs no
41
+ migration (`src/server/engagement/visits.ts` says why).
42
+
29
43
  ## 2. Mount order — the decision four apps had to agree on
30
44
 
31
45
  | receiver | its credential | mounts |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursedbelt-server",
3
- "version": "4.56.0",
3
+ "version": "4.58.0",
4
4
  "license": "ISC",
5
5
  "type": "module",
6
6
  "description": "The app-facing Bun/Hono server tier of the cursedbelt split — storage, sharing, activity, guard, sync. React-free; cursedbelt-core below it.",
@@ -417,7 +417,7 @@
417
417
  "@node-rs/argon2": "^2.0.2",
418
418
  "@types/bun": "^1.3.14",
419
419
  "@types/node": "^24",
420
- "cursedbelt": "^5.99.6",
420
+ "cursedbelt": "^5.102.0",
421
421
  "hono": "4.12.28",
422
422
  "kysely": "^0.28.17",
423
423
  "kysely-bun-sqlite": "^0.4.0",
@@ -24,10 +24,27 @@
24
24
  * (music, family, desk, arch) would otherwise go red on the version bump alone. An app opts in by
25
25
  * declaring `actions` and applying {@link ENGAGEMENT_ACTION_DDL}; the Bun store always creates both.
26
26
  *
27
+ * ── One POST, many actions (task 4034) ──────────────────────────────────────
28
+ * The browser queues actions and sends them together after a few seconds of quiet, and at
29
+ * `pagehide` (`cursedbelt/react/engagement-beacon`), so a feature the owner adds to the record
30
+ * costs no extra request per click. The door reads either body: `{ place, action }`, one action
31
+ * as before, which is what the client still sends when its queue holds one, so an older server
32
+ * reads it; or `{ actions: [{ place, action, at }…] }`. A batch over {@link MAX_ACTION_BATCH} is
33
+ * cut, and the cut is counted in the reply and in the log. `at` is the browser's clock, so it
34
+ * is clamped to the last {@link MAX_ACTION_AGE_MS} and never ahead of the server's. It only
35
+ * picks the DAY a use counts on. Repeats fold before the write ({@link tallyActions}): ten plays
36
+ * on one page are one upsert of `uses + 10`.
37
+ *
27
38
  * Pure and Worker-safe: the Bun store and the D1 recorder both write through
28
39
  * {@link actionStatements}, so there is one write, not two that agree.
29
40
  */
30
- import { dayKey } from "./policy.js";
41
+ import { type ActionRef, dayKey, OTHER_PLACE, type PlaceRef, resolveAction, resolvePlace } from "./policy.js";
42
+
43
+ /** The most actions one POST records; the rest are cut and counted. The client sends no more. */
44
+ export const MAX_ACTION_BATCH = 100;
45
+
46
+ /** How far back a batched action's own clock may place it. The client holds one for 30 s at most. */
47
+ export const MAX_ACTION_AGE_MS = 10 * 60 * 1000;
31
48
 
32
49
  export const ENGAGEMENT_ACTION_DDL: readonly string[] = [
33
50
  "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) )",
@@ -40,32 +57,112 @@ export interface ActionUse {
40
57
  userKey: string;
41
58
  place: string;
42
59
  action: string;
60
+ /** When it happened; with `uses` > 1, the LAST of them. */
43
61
  ts: number;
62
+ /** How many uses this row counts. A batch folds repeats into one row ({@link tallyActions}); default 1. */
63
+ uses?: number;
64
+ /** The first of them, when `uses` > 1; default `ts`. */
65
+ firstTs?: number;
44
66
  }
45
67
 
46
- /** The two upserts one action is — run them together (a transaction, or one D1 batch). */
68
+ /** The two upserts one action (or one tally of them) is — run them together (a transaction, or one D1 batch). */
47
69
  export function actionStatements(use: ActionUse): Array<{ sql: string; params: (string | number)[] }> {
48
70
  const { userKey, place, action, ts } = use;
71
+ const uses = use.uses ?? 1;
49
72
  return [
50
73
  {
74
+ // MIN/MAX, not "the newest wins": a batch's clock can sit behind a use the door recorded since.
51
75
  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],
76
+ VALUES (?, ?, ?, ?, ?, ?)
77
+ ON CONFLICT(user_key, place, action) DO UPDATE SET uses = uses + excluded.uses,
78
+ first_ts = MIN(first_ts, excluded.first_ts), last_ts = MAX(last_ts, excluded.last_ts)`,
79
+ params: [userKey, place, action, uses, use.firstTs ?? ts, ts],
55
80
  },
56
81
  {
57
82
  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)],
83
+ VALUES (?, ?, ?, ?, ?)
84
+ ON CONFLICT(user_key, place, action, day) DO UPDATE SET uses = uses + excluded.uses`,
85
+ params: [userKey, place, action, dayKey(ts), uses],
61
86
  },
62
87
  ];
63
88
  }
64
89
 
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;
90
+ /** One action as the browser claimed it: two NAMES, and its clock already clamped to the server's. */
91
+ export interface ClaimedAction {
92
+ place: string;
93
+ action: string;
94
+ at: number;
95
+ }
96
+
97
+ /**
98
+ * Read the claimed actions out of a request body: `{ place, action }` (one, at `now`) or
99
+ * `{ actions: [{ place, action, at? }…] }`. Every one must carry two strings, or the whole body is a
100
+ * 400, as a single one is. Past {@link MAX_ACTION_BATCH} they are cut, and `cut` says how many.
101
+ */
102
+ export function claimedActions(body: unknown, now: number): { actions: ClaimedAction[]; cut: number; batch: boolean } | { error: string } {
103
+ const list = (body as { actions?: unknown } | null)?.actions;
104
+ if (list === undefined) {
105
+ const one = claimedOne(body, now);
106
+ return "error" in one ? one : { actions: [one], cut: 0, batch: false };
107
+ }
108
+ if (!Array.isArray(list)) return { error: "actions must be an array" };
109
+ const actions: ClaimedAction[] = [];
110
+ for (const item of list.slice(0, MAX_ACTION_BATCH)) {
111
+ const one = claimedOne(item, now);
112
+ if ("error" in one) return { error: `actions[${actions.length}]: ${one.error}` };
113
+ actions.push(one);
114
+ }
115
+ return { actions, cut: Math.max(0, list.length - MAX_ACTION_BATCH), batch: true };
116
+ }
117
+
118
+ function claimedOne(body: unknown, now: number): ClaimedAction | { error: string } {
119
+ const b = body as { place?: unknown; action?: unknown; at?: unknown } | null;
68
120
  if (typeof b?.action !== "string") return { error: "action must be a string" };
69
121
  if (typeof b.place !== "string") return { error: "place must be a string" };
70
- return { place: b.place, action: b.action };
122
+ const at = typeof b.at === "number" && Number.isFinite(b.at) ? Math.min(now, Math.max(now - MAX_ACTION_AGE_MS, b.at)) : now;
123
+ return { place: b.place, action: b.action, at };
124
+ }
125
+
126
+ /**
127
+ * Fold resolved uses into one row per (place, action, day), so a batch is a handful of upserts
128
+ * however many clicks it carries. The order of first appearance is kept.
129
+ */
130
+ export function tallyActions(uses: readonly ActionUse[]): ActionUse[] {
131
+ const rows = new Map<string, ActionUse>();
132
+ for (const u of uses) {
133
+ const key = `${u.userKey}\u0000${u.place}\u0000${u.action}\u0000${dayKey(u.ts)}`;
134
+ const row = rows.get(key);
135
+ const n = u.uses ?? 1;
136
+ const first = u.firstTs ?? u.ts;
137
+ if (!row) rows.set(key, { ...u, uses: n, firstTs: first });
138
+ else rows.set(key, { ...row, uses: (row.uses ?? 1) + n, firstTs: Math.min(row.firstTs ?? row.ts, first), ts: Math.max(row.ts, u.ts) });
139
+ }
140
+ return [...rows.values()];
141
+ }
142
+
143
+ /**
144
+ * The action door's whole answer to one body — what to write and what to say back — so the Bun
145
+ * recorder and the D1 one cannot drift. One action replies as it always has; a batch replies with
146
+ * how many it recorded, how many of those were bucketed as `other`, and how many it cut.
147
+ */
148
+ export function actionDoor(
149
+ body: unknown,
150
+ door: { userKey: string; now: number; places: readonly PlaceRef[]; actions: readonly ActionRef[] },
151
+ ): { uses: ActionUse[]; reply: Record<string, unknown> } | { error: string } {
152
+ const claimed = claimedActions(body, door.now);
153
+ if ("error" in claimed) return claimed;
154
+ const resolved = claimed.actions.map((a) => ({
155
+ userKey: door.userKey,
156
+ place: resolvePlace(a.place, door.places),
157
+ action: resolveAction(a.action, door.actions),
158
+ ts: a.at,
159
+ }));
160
+ const bucketed = resolved.filter((u) => u.place === OTHER_PLACE || u.action === OTHER_PLACE).length;
161
+ if (claimed.cut > 0) console.warn(`engagement: cut ${claimed.cut} action(s) past the batch cap of ${MAX_ACTION_BATCH}`);
162
+ const [one] = resolved;
163
+ const reply =
164
+ !claimed.batch && one
165
+ ? { ok: true, place: one.place, action: one.action, bucketed: bucketed > 0 }
166
+ : { ok: true, recorded: resolved.length, bucketed, cut: claimed.cut };
167
+ return { uses: tallyActions(resolved), reply };
71
168
  }
@@ -4,7 +4,8 @@
4
4
  * POST /api/engagement/view → the beacon. SESSION-gated; the user id comes
5
5
  * from the session, never from the body.
6
6
  * POST /api/engagement/action → a feature used on a page — `{ place, action }`, both
7
- * NAMES resolved against the manifest (`actions.ts`).
7
+ * NAMES resolved against the manifest (`actions.ts`), or a
8
+ * batch of them, `{ actions: [{ place, action, at }…] }`.
8
9
  * Mounted only for an app that passes `actions`.
9
10
  *
10
11
  * 🔴 **There is no HTTP read surface, on purpose** (task `113`/`268`, 2026-09-22).
@@ -34,8 +35,8 @@
34
35
  */
35
36
  import { Hono } from "hono";
36
37
  import type { Context } from "hono";
37
- import { claimedAction } from "./actions.js";
38
- import { type ActionRef, OTHER_PLACE, type PlaceRef, resolveAction, resolvePlace } from "./policy.js";
38
+ import { actionDoor } from "./actions.js";
39
+ import { type ActionRef, OTHER_PLACE, type PlaceRef, resolvePlace } from "./policy.js";
39
40
  import type { EngagementStore } from "./store.js";
40
41
  import { type AppEngagement, returnCurve, summarize } from "./summary.js";
41
42
 
@@ -102,12 +103,10 @@ export function createEngagementRecorder(options: EngagementApiOptions): Hono {
102
103
  } catch {
103
104
  return c.json({ error: "expected a json body" }, 400);
104
105
  }
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 });
106
+ const door = actionDoor(body, { userKey, now: now(), places: options.places, actions });
107
+ if ("error" in door) return c.json({ error: door.error }, 400);
108
+ options.store.recordActions(door.uses);
109
+ return c.json(door.reply);
111
110
  });
112
111
  }
113
112
 
@@ -16,10 +16,13 @@ import {
16
16
  ENGAGEMENT_DDL,
17
17
  placesFromManifest,
18
18
  recordActionD1,
19
+ recordActionsD1,
19
20
  recordViewD1,
20
21
  } from './d1.js';
22
+ import { tallyActions } from './actions.js';
21
23
  import { engagementActionsFor, engagementPlacesFor } from './places.js';
22
24
  import { EngagementStore } from './store.js';
25
+ import { ENGAGEMENT_SESSION_DDL } from './visits.js';
23
26
 
24
27
  const dirs: string[] = [];
25
28
  afterEach(() => {
@@ -33,7 +36,7 @@ const tempDir = (): string => {
33
36
  const kitStore = (): EngagementStore => new EngagementStore({ dbPath: join(tempDir(), 'engagement.sqlite') });
34
37
  const d1 = () => {
35
38
  const sqlite = new Database(':memory:');
36
- for (const ddl of [...ENGAGEMENT_DDL, ...ENGAGEMENT_ACTION_DDL]) sqlite.run(ddl);
39
+ for (const ddl of [...ENGAGEMENT_DDL, ...ENGAGEMENT_ACTION_DDL, ...ENGAGEMENT_SESSION_DDL]) sqlite.run(ddl);
37
40
  return { sqlite, db: createLocalD1(sqlite) };
38
41
  };
39
42
  const shape = (db: Database) =>
@@ -48,6 +51,7 @@ const dump = (db: Database) => ({
48
51
  users: db.query('SELECT * FROM engagement_users ORDER BY user_key').all(),
49
52
  actions: db.query('SELECT * FROM engagement_actions ORDER BY user_key, place, action').all(),
50
53
  actionDays: db.query('SELECT * FROM engagement_action_days ORDER BY user_key, place, action, day').all(),
54
+ visits: db.query('SELECT * FROM engagement_sessions ORDER BY user_key, start_ts').all(),
51
55
  });
52
56
 
53
57
  describe('cursedbelt-server/engagement/d1', () => {
@@ -73,6 +77,53 @@ describe('cursedbelt-server/engagement/d1', () => {
73
77
  expect(dump(sqlite)).toEqual(dump(kit.handle));
74
78
  });
75
79
 
80
+ test('🔴 two views 29 minutes apart are one visit, 31 minutes apart are two — on both hosts', async () => {
81
+ const t0 = Date.UTC(2026, 9, 30, 15, 0, 0);
82
+ const views = [0, 29, 60].map((m) => ({ userKey: 'u1', place: 'library', ts: t0 + m * 60_000 }));
83
+ const kit = kitStore();
84
+ const { sqlite, db } = d1();
85
+ for (const v of views) {
86
+ kit.recordView(v);
87
+ await recordViewD1(db, v);
88
+ }
89
+ const expected = [
90
+ { user_key: 'u1', start_ts: t0, end_ts: views[1]?.ts, views: 2, active_ms: 5 * 60_000 },
91
+ { user_key: 'u1', start_ts: views[2]?.ts, end_ts: views[2]?.ts, views: 1, active_ms: 0 },
92
+ ];
93
+ expect(dump(sqlite).visits).toEqual(expected);
94
+ expect(dump(kit.handle).visits).toEqual(expected);
95
+ });
96
+
97
+ test('🔴 a D1 without the visits table keeps the view, creates the table, and records the visit', async () => {
98
+ const sqlite = new Database(':memory:');
99
+ for (const ddl of ENGAGEMENT_DDL) sqlite.run(ddl);
100
+ const db = createLocalD1(sqlite);
101
+ const ts = Date.UTC(2026, 9, 30, 15, 0, 0);
102
+ expect((await recordViewD1(db, { userKey: 'u1', place: 'library', ts })).newSession).toBe(true);
103
+ expect(sqlite.query('SELECT views FROM engagement_days').all()).toEqual([{ views: 1 }]);
104
+ expect(sqlite.query('SELECT start_ts, views FROM engagement_sessions').all()).toEqual([{ start_ts: ts, views: 1 }]);
105
+ });
106
+
107
+ test('🔴 a visit that cannot be written costs the view nothing, and the beacon still answers', async () => {
108
+ const sqlite = new Database(':memory:');
109
+ for (const ddl of ENGAGEMENT_DDL) sqlite.run(ddl);
110
+ sqlite.run('CREATE VIEW engagement_sessions AS SELECT 1 AS not_a_table');
111
+ const db = createLocalD1(sqlite);
112
+ const fold = await recordViewD1(db, { userKey: 'u1', place: 'library', ts: Date.UTC(2026, 9, 30, 15, 0, 0) });
113
+ expect(fold.newSession).toBe(true);
114
+ expect(sqlite.query('SELECT views FROM engagement_days').all()).toEqual([{ views: 1 }]);
115
+ });
116
+
117
+ test('visits past retention are trimmed when the next one opens, and a visit from before the table is skipped', async () => {
118
+ const { sqlite, db } = d1();
119
+ const t0 = Date.UTC(2026, 9, 30, 15, 0, 0);
120
+ sqlite.run('INSERT INTO engagement_sessions VALUES (?, ?, ?, 1, 0)', ['old', t0 - 121 * 86_400_000, t0 - 121 * 86_400_000]);
121
+ sqlite.run('INSERT INTO engagement_users (user_key, first_ts, last_ts, last_place) VALUES (?, ?, ?, ?)', ['u2', t0, t0, 'library']);
122
+ await recordViewD1(db, { userKey: 'u1', place: 'library', ts: t0 });
123
+ await recordViewD1(db, { userKey: 'u2', place: 'library', ts: t0 + 60_000 });
124
+ expect(sqlite.query('SELECT user_key FROM engagement_sessions').all()).toEqual([{ user_key: 'u1' }]);
125
+ });
126
+
76
127
  test('records only a signed-in account, and buckets an off-manifest place as `other`', async () => {
77
128
  const { sqlite, db } = d1();
78
129
  const places = placesFromManifest({ routes: [{ id: 'library', path: '/library' }, { id: 'library' }, { path: '/x' }] });
@@ -144,5 +195,13 @@ describe('cursedbelt-server/engagement/d1', () => {
144
195
  });
145
196
  expect(await res.json()).toMatchObject({ ok: true, place: 'home', action: 'other', bucketed: true });
146
197
  expect(sqlite.query("SELECT action FROM engagement_actions WHERE user_key = 'u3'").all()).toEqual([{ action: 'other' }]);
198
+
199
+ // A batch (task 4034): the same rows as the kit store writes for it, in one D1 batch.
200
+ const batch = tallyActions([...uses, ...uses].map((u) => ({ ...u, userKey: 'u4' })));
201
+ await recordActionsD1(db, batch);
202
+ kit.recordActions(batch);
203
+ const u4 = (h: { query: (sql: string) => { all: () => unknown[] } }) => h.query("SELECT * FROM engagement_actions WHERE user_key = 'u4' ORDER BY action").all();
204
+ expect(u4(sqlite)).toEqual(u4(kit.handle));
205
+ expect(u4(sqlite)).toMatchObject([{ action: 'play', uses: 4 }, { action: 'search', uses: 2 }]);
147
206
  });
148
207
  });
@@ -39,8 +39,9 @@
39
39
  import type { D1LikeDatabase } from "../d1/types.js";
40
40
  import type { Context } from "hono";
41
41
  import { Hono } from "hono";
42
- import { type ActionUse, actionStatements, claimedAction } from "./actions.js";
43
- import { type ActionRef, dayKey, foldView, OTHER_PLACE, type PlaceRef, resolveAction, resolvePlace } from "./policy.js";
42
+ import { type ActionUse, actionDoor, actionStatements } from "./actions.js";
43
+ import { type ActionRef, dayKey, foldView, OTHER_PLACE, type PlaceRef, resolvePlace, type ViewFold } from "./policy.js";
44
+ import { ENGAGEMENT_SESSION_DDL, visitStatements } from "./visits.js";
44
45
 
45
46
  /** The kit store's own tables and indexes, as one-line DDL — see the header. */
46
47
  export const ENGAGEMENT_DDL: readonly string[] = [
@@ -107,12 +108,37 @@ export async function recordViewD1(
107
108
  .bind(userKey, sessionDelta, ts, ts, place, fold.activeMs),
108
109
  );
109
110
  await db.batch(statements);
111
+ await recordVisitD1(db, { userKey, ts }, fold);
110
112
  return fold;
111
113
  }
112
114
 
115
+ /**
116
+ * The view's visit (`visits.ts`), after its batch and never in it, and it never throws: the view is
117
+ * already safe, and a beacon's answer must not depend on this. The first write on a D1 without the
118
+ * table creates it, so a version bump needs no migration in any app and no deploy order.
119
+ */
120
+ async function recordVisitD1(db: D1LikeDatabase, view: { userKey: string; ts: number }, fold: ViewFold): Promise<void> {
121
+ const write = () => db.batch(visitStatements(view, fold).map(({ sql, params }) => db.prepare(sql).bind(...params)));
122
+ try {
123
+ await write().catch(async (error: unknown) => {
124
+ if (!/no such table/i.test(String(error))) throw error;
125
+ await db.batch(ENGAGEMENT_SESSION_DDL.map((ddl) => db.prepare(ddl)));
126
+ await write();
127
+ });
128
+ } catch (error) {
129
+ console.warn(`[engagement] a visit was not recorded: ${String(error)}`);
130
+ }
131
+ }
132
+
113
133
  /** Count one resolved action — the Bun store's `recordAction`, as ONE D1 batch (`./actions.ts`). */
114
134
  export async function recordActionD1(db: D1LikeDatabase, use: ActionUse): Promise<void> {
115
- await db.batch(actionStatements(use).map(({ sql, params }) => db.prepare(sql).bind(...params)));
135
+ await recordActionsD1(db, [use]);
136
+ }
137
+
138
+ /** Count a tally of actions (`tallyActions`) as ONE D1 batch: two statements a row, 200 at the batch cap. */
139
+ export async function recordActionsD1(db: D1LikeDatabase, uses: readonly ActionUse[]): Promise<void> {
140
+ if (uses.length === 0) return;
141
+ await db.batch(uses.flatMap(actionStatements).map(({ sql, params }) => db.prepare(sql).bind(...params)));
116
142
  }
117
143
 
118
144
  /**
@@ -159,16 +185,15 @@ export function createD1EngagementRecorder(options: {
159
185
  } catch {
160
186
  return c.json({ error: "expected a json body" }, 400);
161
187
  }
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 });
188
+ const door = actionDoor(body, { userKey, now: now(), places: options.places, actions });
189
+ if ("error" in door) return c.json({ error: door.error }, 400);
190
+ await recordActionsD1(options.db, door.uses);
191
+ return c.json(door.reply);
168
192
  });
169
193
  }
170
194
  return app;
171
195
  }
172
196
 
173
197
  export { ENGAGEMENT_ACTION_DDL } from "./actions.js";
198
+ export { ENGAGEMENT_SESSION_DDL } from "./visits.js";
174
199
  export { actionsFromManifest, placesFromManifest } from "./manifestPlaces.js";
@@ -15,6 +15,7 @@
15
15
  import { describe, expect, test } from "bun:test";
16
16
  import { Hono } from "hono";
17
17
  import type { Context } from "hono";
18
+ import { MAX_ACTION_AGE_MS, MAX_ACTION_BATCH, tallyActions } from "./actions.js";
18
19
  import { createEngagementRecorder, readAppEngagement } from "./api.js";
19
20
  import { readEngagementEnv } from "./env.js";
20
21
  import {
@@ -545,6 +546,46 @@ describe("feature actions — what they DID on a page, by name only (task 3470)"
545
546
  expect(s.users()).toEqual([]);
546
547
  });
547
548
 
549
+ test("🔴 a batch is one POST: repeats fold into one row, `at` is clamped, a newer use keeps last_ts (task 4034)", async () => {
550
+ const { s, post, clock } = mount(() => "u1");
551
+ clock.t = T0 + DAY;
552
+ await post({ place: "files", action: "play" });
553
+ const res = await post({
554
+ actions: [
555
+ { place: "files", action: "play", at: T0 + DAY - 2 * MINUTE },
556
+ { place: "files", action: "play", at: T0 + DAY - MINUTE },
557
+ { place: "files", action: "search", at: T0 + DAY - 60 * MINUTE },
558
+ { place: "files", action: "download", at: T0 + 9 * DAY },
559
+ { place: "files", action: "download", at: "yesterday" },
560
+ { place: "/#/note/private", action: "rename to a secret" },
561
+ ],
562
+ });
563
+ expect(await res.json()).toEqual({ ok: true, recorded: 6, bucketed: 1, cut: 0 });
564
+ const rows = Object.fromEntries(s.actions().map((a) => [`${a.place}/${a.action}`, a]));
565
+ expect(rows["files/play"]).toMatchObject({ uses: 3, firstTs: T0 + DAY - 2 * MINUTE, lastTs: T0 + DAY });
566
+ expect(rows["files/search"]).toMatchObject({ uses: 1, firstTs: T0 + DAY - MAX_ACTION_AGE_MS });
567
+ expect(rows["files/download"]).toMatchObject({ uses: 2, firstTs: T0 + DAY, lastTs: T0 + DAY });
568
+ expect(rows["note/other"]).toMatchObject({ uses: 1 });
569
+ });
570
+
571
+ test("🔴 past the cap a batch is cut and the cut is counted; one malformed item writes nothing", async () => {
572
+ const { s, post } = mount(() => "u1");
573
+ const plays = Array.from({ length: MAX_ACTION_BATCH + 50 }, () => ({ place: "files", action: "play", at: T0 }));
574
+ expect(await (await post({ actions: plays })).json()).toEqual({ ok: true, recorded: MAX_ACTION_BATCH, bucketed: 0, cut: 50 });
575
+ expect(s.actions()).toMatchObject([{ action: "play", uses: MAX_ACTION_BATCH }]);
576
+ const bad = await post({ actions: [{ place: "files", action: "search" }, { place: "files" }] });
577
+ expect(bad.status).toBe(400);
578
+ expect(await bad.json()).toEqual({ error: "actions[1]: action must be a string" });
579
+ expect((await post({ actions: "play" })).status).toBe(400);
580
+ expect(s.actions().map((a) => a.action)).toEqual(["play"]);
581
+ });
582
+
583
+ test("ten clicks are one upsert pair, not ten", () => {
584
+ const uses = Array.from({ length: 10 }, (_, i) => ({ userKey: "u1", place: "files", action: "play", ts: T0 + i }));
585
+ expect(tallyActions(uses)).toEqual([{ userKey: "u1", place: "files", action: "play", ts: T0 + 9, uses: 10, firstTs: T0 }]);
586
+ expect(tallyActions([...uses, { userKey: "u1", place: "files", action: "play", ts: T0 + DAY }])).toHaveLength(2);
587
+ });
588
+
548
589
  test("the daily prune trims action DAYS and keeps the roll-up that says who used it", () => {
549
590
  const s = store();
550
591
  s.recordAction({ userKey: "u1", place: "files", action: "play", ts: T0 });
@@ -14,8 +14,10 @@
14
14
  * One row per (user, place, UTC day). The alternative — a row per view — buys
15
15
  * nothing at this fleet's size and costs the one thing worth protecting: an
16
16
  * event log is a timeline, and a timeline of a household's private apps is a
17
- * far more sensitive object than a count. Sequence is exactly the information
18
- * we do not want to be holding, so the schema cannot express it.
17
+ * far more sensitive object than a count. Sequence of PLACES is exactly the
18
+ * information we do not want to be holding, so the schema cannot express it.
19
+ * `engagement_sessions` (`visits.ts`, the owner's ask of 2026-10-30) holds when a
20
+ * visit began and ended and has no place in it.
19
21
  *
20
22
  * The one place ordering DOES matter is sessionization, and it is resolved at
21
23
  * WRITE time against `engagement_users.last_ts` — a single stored clock per
@@ -37,6 +39,7 @@ import { dirname, resolve } from "node:path";
37
39
  import { type ActionUse, actionStatements, ENGAGEMENT_ACTION_DDL } from "./actions.js";
38
40
  import { dayKey, foldView } from "./policy.js";
39
41
  import type { EngagementActionUse, EngagementDay, EngagementUser, EngagementUserPlace } from "./types.js";
42
+ import { ENGAGEMENT_SESSION_DDL, visitStatements } from "./visits.js";
40
43
 
41
44
  export type { EngagementActionUse, EngagementDay, EngagementUser, EngagementUserPlace } from "./types.js";
42
45
 
@@ -126,6 +129,8 @@ export class EngagementStore {
126
129
  )`);
127
130
  // Feature actions (task 3470) — `actions.ts` says why they are their own two tables.
128
131
  for (const ddl of ENGAGEMENT_ACTION_DDL) this.handle.run(ddl);
132
+ // Visits (the owner's "at the same time", 2026-10-30) — `visits.ts` says why they are their own table.
133
+ for (const ddl of ENGAGEMENT_SESSION_DDL) this.handle.run(ddl);
129
134
  }
130
135
 
131
136
  /**
@@ -197,6 +202,7 @@ export class EngagementStore {
197
202
  last_place = excluded.last_place`,
198
203
  [userKey, sessionDelta, ts, ts, place, fold.activeMs],
199
204
  );
205
+ for (const { sql, params } of visitStatements({ userKey, ts }, fold)) this.handle.run(sql, params);
200
206
 
201
207
  // Amortised, exactly as the metrics store trims: a DELETE per beacon would
202
208
  // cost more than the beacon, and never trimming lets a long-lived daemon
@@ -211,11 +217,17 @@ export class EngagementStore {
211
217
  * dwell: an action is something done on the page the view already counted.
212
218
  */
213
219
  recordAction(use: ActionUse): void {
214
- const statements = actionStatements(use);
220
+ this.recordActions([use]);
221
+ }
222
+
223
+ /** Count a tally of actions (`tallyActions`) in ONE transaction — what a batched POST writes. */
224
+ recordActions(uses: readonly ActionUse[]): void {
225
+ const last = uses.at(-1);
226
+ if (!last) return;
215
227
  this.handle.transaction(() => {
216
- for (const { sql, params } of statements) this.handle.run(sql, params);
228
+ for (const { sql, params } of uses.flatMap(actionStatements)) this.handle.run(sql, params);
217
229
  })();
218
- if (++this.writes % 256 === 0) this.prune(use.ts);
230
+ if (++this.writes % 256 === 0) this.prune(last.ts);
219
231
  }
220
232
 
221
233
  /** Every (user, place, action) lifetime roll-up, most used first. */
@@ -268,7 +280,7 @@ export class EngagementStore {
268
280
  /**
269
281
  * Drop daily rows older than the retention window.
270
282
  *
271
- * 🔴 Only the daily grains (`engagement_days`, `engagement_action_days`). The roll-ups are deliberately untouched —
283
+ * 🔴 Only the daily grains (`engagement_days`, `engagement_action_days`) and the visits. The roll-ups are deliberately untouched —
272
284
  * see the file header. An agent "completing" this by trimming them too would
273
285
  * delete the only record that somebody used to be here, which is the entire
274
286
  * drop-off signal.
@@ -277,7 +289,8 @@ export class EngagementStore {
277
289
  const cutoff = dayKey(at - this.retentionDays * 86_400_000);
278
290
  // The action DAYS age out with the view days; `engagement_actions` is a roll-up and stays.
279
291
  const actionDays = this.handle.run("DELETE FROM engagement_action_days WHERE day < ?", [cutoff]).changes;
280
- return this.handle.run("DELETE FROM engagement_days WHERE day < ?", [cutoff]).changes + actionDays;
292
+ const visits = this.handle.run("DELETE FROM engagement_sessions WHERE start_ts < ?", [at - this.retentionDays * 86_400_000]).changes;
293
+ return this.handle.run("DELETE FROM engagement_days WHERE day < ?", [cutoff]).changes + actionDays + visits;
281
294
  }
282
295
 
283
296
  /** Row counts + age bounds, for the retention card. */
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Visits — WHEN a person was in this app, so station can say which apps they used at the same time.
3
+ *
4
+ * The owner, 2026-10-30: *"see a timeline of what apps they went to, for how long, which ones at the
5
+ * same time"*. `engagement_days` answers the first two per DAY; its `first_ts`/`last_ts` span every
6
+ * visit that day, so "more than one app on the same day" can be two visits hours apart.
7
+ *
8
+ * ── What it may hold, and why this much ─────────────────────────────────────
9
+ * `store.ts`'s header refuses a timeline of a household's private apps, and that still holds for
10
+ * everything with a PLACE in it. A row here has no place: a visit's start, end, view count and
11
+ * attention, the least that answers his question, and only for {@link ENGAGEMENT_VISIT_RETENTION_DAYS}.
12
+ * One row per VISIT (the same cut as the sessions count, `policy.ts:foldView`), not per beacon: 264
13
+ * visits across the fleet in the 30 days to 2026-10-30, against "a few thousand a month" as the line.
14
+ *
15
+ * 🔴 Its own DDL, not appended to `ENGAGEMENT_DDL`, for the reason `actions.ts` gives: an app whose
16
+ * schema is generated from that list goes red on the version bump alone. And on a Worker the write is
17
+ * NOT in the view's batch: a D1 missing this table would fail that whole atomic batch and lose the view.
18
+ * `d1.ts` `recordVisitD1` runs it after, creates the table the first time it is missing, and never throws.
19
+ *
20
+ * Pure and Worker-safe: the Bun store and the D1 recorder both write through {@link visitStatements}.
21
+ */
22
+ import type { ViewFold } from "./policy.js";
23
+
24
+ /** As long as the daily grain: a visit is the more sensitive row, so it is never kept longer. */
25
+ export const ENGAGEMENT_VISIT_RETENTION_DAYS = 120;
26
+
27
+ export const ENGAGEMENT_SESSION_DDL: readonly string[] = [
28
+ "CREATE TABLE IF NOT EXISTS engagement_sessions ( user_key TEXT NOT NULL, start_ts INTEGER NOT NULL, end_ts INTEGER NOT NULL, views INTEGER NOT NULL DEFAULT 0, active_ms INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (user_key, start_ts) )",
29
+ "CREATE INDEX IF NOT EXISTS idx_engagement_sessions_start ON engagement_sessions (start_ts)",
30
+ ];
31
+
32
+ /**
33
+ * What one view does to the visits: opens one, trimming the ones past retention, or extends the open
34
+ * one. A view in a visit that began before this table existed updates nothing, and its visit is simply
35
+ * not recorded; the next one is.
36
+ */
37
+ export function visitStatements(view: { userKey: string; ts: number }, fold: ViewFold): Array<{ sql: string; params: (string | number)[] }> {
38
+ const { userKey, ts } = view;
39
+ if (fold.newSession)
40
+ return [
41
+ // IGNORE: two views in one millisecond are one visit opened twice.
42
+ { sql: "INSERT OR IGNORE INTO engagement_sessions (user_key, start_ts, end_ts, views, active_ms) VALUES (?, ?, ?, 1, 0)", params: [userKey, ts, ts] },
43
+ { sql: "DELETE FROM engagement_sessions WHERE start_ts < ?", params: [ts - ENGAGEMENT_VISIT_RETENTION_DAYS * 86_400_000] },
44
+ ];
45
+ return [
46
+ {
47
+ // MAX: a device with a wrong clock makes a number boring, never a visit that ends before it began.
48
+ sql: `UPDATE engagement_sessions SET end_ts = MAX(end_ts, ?), views = views + 1, active_ms = active_ms + ?
49
+ WHERE user_key = ? AND start_ts = (SELECT MAX(start_ts) FROM engagement_sessions WHERE user_key = ?)`,
50
+ params: [ts, fold.activeMs, userKey, userKey],
51
+ },
52
+ ];
53
+ }
@@ -187,6 +187,19 @@ describe("the fetcher", () => {
187
187
  expect((await readdir(dir)).filter((name) => name.startsWith("ytdlp-"))).toEqual([]);
188
188
  });
189
189
 
190
+ test("🔴 a resumable download keeps its directory and its partial bytes through a failure, and continues there", async () => {
191
+ const work = join(dir, "job-1");
192
+ await make(scripted("Connection reset by peer"))("abc", undefined, { workDir: work }).catch(() => undefined);
193
+ // The partial is where the next call looks — never deleted on a failure.
194
+ expect((await stat(work)).isDirectory()).toBe(true);
195
+ const args = runs.at(-1) as string[];
196
+ expect(args).toContain("--continue");
197
+ expect(args).not.toContain("--no-part");
198
+ expect(args[args.indexOf("-o") + 1]).toBe(join(work, "download.%(ext)s"));
199
+ // A non-resumable call is unchanged: no partial, a fresh directory, gone on failure.
200
+ expect(ytDlpArgs("abc", "/out", VIDEO)).toContain("--no-part");
201
+ });
202
+
190
203
  test("the ceiling sentence uses the profile's own noun and size", async () => {
191
204
  const failure = await make(scripted("File is larger than max-filesize (9 > 8). Aborting."), VIDEO)("abc").then(
192
205
  () => {