cursedbelt-server 4.57.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.
@@ -1,20 +1,102 @@
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
+ * ── 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
+ *
38
+ * Pure and Worker-safe: the Bun store and the D1 recorder both write through
39
+ * {@link actionStatements}, so there is one write, not two that agree.
40
+ */
41
+ import { type ActionRef, type PlaceRef } from "./policy.js";
42
+ /** The most actions one POST records; the rest are cut and counted. The client sends no more. */
43
+ export declare const MAX_ACTION_BATCH = 100;
44
+ /** How far back a batched action's own clock may place it. The client holds one for 30 s at most. */
45
+ export declare const MAX_ACTION_AGE_MS: number;
1
46
  export declare const ENGAGEMENT_ACTION_DDL: readonly string[];
2
47
  /** One resolved action, ready to count. `place` and `action` have been through the allowlists. */
3
48
  export interface ActionUse {
4
49
  userKey: string;
5
50
  place: string;
6
51
  action: string;
52
+ /** When it happened; with `uses` > 1, the LAST of them. */
7
53
  ts: number;
54
+ /** How many uses this row counts. A batch folds repeats into one row ({@link tallyActions}); default 1. */
55
+ uses?: number;
56
+ /** The first of them, when `uses` > 1; default `ts`. */
57
+ firstTs?: number;
8
58
  }
9
- /** The two upserts one action is — run them together (a transaction, or one D1 batch). */
59
+ /** The two upserts one action (or one tally of them) is — run them together (a transaction, or one D1 batch). */
10
60
  export declare function actionStatements(use: ActionUse): Array<{
11
61
  sql: string;
12
62
  params: (string | number)[];
13
63
  }>;
14
- /** Read the claimed `{ place, action }` out of a request body — a string each, or a reason why not. */
15
- export declare function claimedAction(body: unknown): {
64
+ /** One action as the browser claimed it: two NAMES, and its clock already clamped to the server's. */
65
+ export interface ClaimedAction {
16
66
  place: string;
17
67
  action: string;
68
+ at: number;
69
+ }
70
+ /**
71
+ * Read the claimed actions out of a request body: `{ place, action }` (one, at `now`) or
72
+ * `{ actions: [{ place, action, at? }…] }`. Every one must carry two strings, or the whole body is a
73
+ * 400, as a single one is. Past {@link MAX_ACTION_BATCH} they are cut, and `cut` says how many.
74
+ */
75
+ export declare function claimedActions(body: unknown, now: number): {
76
+ actions: ClaimedAction[];
77
+ cut: number;
78
+ batch: boolean;
79
+ } | {
80
+ error: string;
81
+ };
82
+ /**
83
+ * Fold resolved uses into one row per (place, action, day), so a batch is a handful of upserts
84
+ * however many clicks it carries. The order of first appearance is kept.
85
+ */
86
+ export declare function tallyActions(uses: readonly ActionUse[]): ActionUse[];
87
+ /**
88
+ * The action door's whole answer to one body — what to write and what to say back — so the Bun
89
+ * recorder and the D1 one cannot drift. One action replies as it always has; a batch replies with
90
+ * how many it recorded, how many of those were bucketed as `other`, and how many it cut.
91
+ */
92
+ export declare function actionDoor(body: unknown, door: {
93
+ userKey: string;
94
+ now: number;
95
+ places: readonly PlaceRef[];
96
+ actions: readonly ActionRef[];
97
+ }): {
98
+ uses: ActionUse[];
99
+ reply: Record<string, unknown>;
18
100
  } | {
19
101
  error: string;
20
102
  };
@@ -24,39 +24,121 @@
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 { dayKey, OTHER_PLACE, resolveAction, resolvePlace } from "./policy.js";
42
+ /** The most actions one POST records; the rest are cut and counted. The client sends no more. */
43
+ export const MAX_ACTION_BATCH = 100;
44
+ /** How far back a batched action's own clock may place it. The client holds one for 30 s at most. */
45
+ export const MAX_ACTION_AGE_MS = 10 * 60 * 1000;
31
46
  export const ENGAGEMENT_ACTION_DDL = [
32
47
  "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) )",
33
48
  "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) )",
34
49
  "CREATE INDEX IF NOT EXISTS idx_engagement_action_days_day ON engagement_action_days (day)",
35
50
  ];
36
- /** The two upserts one action is — run them together (a transaction, or one D1 batch). */
51
+ /** The two upserts one action (or one tally of them) is — run them together (a transaction, or one D1 batch). */
37
52
  export function actionStatements(use) {
38
53
  const { userKey, place, action, ts } = use;
54
+ const uses = use.uses ?? 1;
39
55
  return [
40
56
  {
57
+ // MIN/MAX, not "the newest wins": a batch's clock can sit behind a use the door recorded since.
41
58
  sql: `INSERT INTO engagement_actions (user_key, place, action, uses, first_ts, last_ts)
42
- VALUES (?, ?, ?, 1, ?, ?)
43
- ON CONFLICT(user_key, place, action) DO UPDATE SET uses = uses + 1, last_ts = excluded.last_ts`,
44
- params: [userKey, place, action, ts, ts],
59
+ VALUES (?, ?, ?, ?, ?, ?)
60
+ ON CONFLICT(user_key, place, action) DO UPDATE SET uses = uses + excluded.uses,
61
+ first_ts = MIN(first_ts, excluded.first_ts), last_ts = MAX(last_ts, excluded.last_ts)`,
62
+ params: [userKey, place, action, uses, use.firstTs ?? ts, ts],
45
63
  },
46
64
  {
47
65
  sql: `INSERT INTO engagement_action_days (user_key, place, action, day, uses)
48
- VALUES (?, ?, ?, ?, 1)
49
- ON CONFLICT(user_key, place, action, day) DO UPDATE SET uses = uses + 1`,
50
- params: [userKey, place, action, dayKey(ts)],
66
+ VALUES (?, ?, ?, ?, ?)
67
+ ON CONFLICT(user_key, place, action, day) DO UPDATE SET uses = uses + excluded.uses`,
68
+ params: [userKey, place, action, dayKey(ts), uses],
51
69
  },
52
70
  ];
53
71
  }
54
- /** Read the claimed `{ place, action }` out of a request body — a string each, or a reason why not. */
55
- export function claimedAction(body) {
72
+ /**
73
+ * Read the claimed actions out of a request body: `{ place, action }` (one, at `now`) or
74
+ * `{ actions: [{ place, action, at? }…] }`. Every one must carry two strings, or the whole body is a
75
+ * 400, as a single one is. Past {@link MAX_ACTION_BATCH} they are cut, and `cut` says how many.
76
+ */
77
+ export function claimedActions(body, now) {
78
+ const list = body?.actions;
79
+ if (list === undefined) {
80
+ const one = claimedOne(body, now);
81
+ return "error" in one ? one : { actions: [one], cut: 0, batch: false };
82
+ }
83
+ if (!Array.isArray(list))
84
+ return { error: "actions must be an array" };
85
+ const actions = [];
86
+ for (const item of list.slice(0, MAX_ACTION_BATCH)) {
87
+ const one = claimedOne(item, now);
88
+ if ("error" in one)
89
+ return { error: `actions[${actions.length}]: ${one.error}` };
90
+ actions.push(one);
91
+ }
92
+ return { actions, cut: Math.max(0, list.length - MAX_ACTION_BATCH), batch: true };
93
+ }
94
+ function claimedOne(body, now) {
56
95
  const b = body;
57
96
  if (typeof b?.action !== "string")
58
97
  return { error: "action must be a string" };
59
98
  if (typeof b.place !== "string")
60
99
  return { error: "place must be a string" };
61
- return { place: b.place, action: b.action };
100
+ const at = typeof b.at === "number" && Number.isFinite(b.at) ? Math.min(now, Math.max(now - MAX_ACTION_AGE_MS, b.at)) : now;
101
+ return { place: b.place, action: b.action, at };
102
+ }
103
+ /**
104
+ * Fold resolved uses into one row per (place, action, day), so a batch is a handful of upserts
105
+ * however many clicks it carries. The order of first appearance is kept.
106
+ */
107
+ export function tallyActions(uses) {
108
+ const rows = new Map();
109
+ for (const u of uses) {
110
+ const key = `${u.userKey}\u0000${u.place}\u0000${u.action}\u0000${dayKey(u.ts)}`;
111
+ const row = rows.get(key);
112
+ const n = u.uses ?? 1;
113
+ const first = u.firstTs ?? u.ts;
114
+ if (!row)
115
+ rows.set(key, { ...u, uses: n, firstTs: first });
116
+ else
117
+ rows.set(key, { ...row, uses: (row.uses ?? 1) + n, firstTs: Math.min(row.firstTs ?? row.ts, first), ts: Math.max(row.ts, u.ts) });
118
+ }
119
+ return [...rows.values()];
120
+ }
121
+ /**
122
+ * The action door's whole answer to one body — what to write and what to say back — so the Bun
123
+ * recorder and the D1 one cannot drift. One action replies as it always has; a batch replies with
124
+ * how many it recorded, how many of those were bucketed as `other`, and how many it cut.
125
+ */
126
+ export function actionDoor(body, door) {
127
+ const claimed = claimedActions(body, door.now);
128
+ if ("error" in claimed)
129
+ return claimed;
130
+ const resolved = claimed.actions.map((a) => ({
131
+ userKey: door.userKey,
132
+ place: resolvePlace(a.place, door.places),
133
+ action: resolveAction(a.action, door.actions),
134
+ ts: a.at,
135
+ }));
136
+ const bucketed = resolved.filter((u) => u.place === OTHER_PLACE || u.action === OTHER_PLACE).length;
137
+ if (claimed.cut > 0)
138
+ console.warn(`engagement: cut ${claimed.cut} action(s) past the batch cap of ${MAX_ACTION_BATCH}`);
139
+ const [one] = resolved;
140
+ const reply = !claimed.batch && one
141
+ ? { ok: true, place: one.place, action: one.action, bucketed: bucketed > 0 }
142
+ : { ok: true, recorded: resolved.length, bucketed, cut: claimed.cut };
143
+ return { uses: tallyActions(resolved), reply };
62
144
  }
@@ -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).
@@ -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).
@@ -33,8 +34,8 @@
33
34
  * rule and its reason: `docs/engagement.md` §2 in this package.
34
35
  */
35
36
  import { Hono } from "hono";
36
- import { claimedAction } from "./actions.js";
37
- import { OTHER_PLACE, resolveAction, resolvePlace } from "./policy.js";
37
+ import { actionDoor } from "./actions.js";
38
+ import { OTHER_PLACE, resolvePlace } from "./policy.js";
38
39
  import { returnCurve, summarize } from "./summary.js";
39
40
  /** The recorder half — session-gated, mounted at `/api/engagement`. */
40
41
  export function createEngagementRecorder(options) {
@@ -78,13 +79,11 @@ export function createEngagementRecorder(options) {
78
79
  catch {
79
80
  return c.json({ error: "expected a json body" }, 400);
80
81
  }
81
- const claimed = claimedAction(body);
82
- if ("error" in claimed)
83
- return c.json({ error: claimed.error }, 400);
84
- const place = resolvePlace(claimed.place, options.places);
85
- const action = resolveAction(claimed.action, actions);
86
- options.store.recordAction({ userKey, place, action, ts: now() });
87
- return c.json({ ok: true, place, action, bucketed: place === OTHER_PLACE || action === OTHER_PLACE });
82
+ const door = actionDoor(body, { userKey, now: now(), places: options.places, actions });
83
+ if ("error" in door)
84
+ return c.json({ error: door.error }, 400);
85
+ options.store.recordActions(door.uses);
86
+ return c.json(door.reply);
88
87
  });
89
88
  }
90
89
  return app;
@@ -58,6 +58,8 @@ export declare function recordViewD1(db: D1LikeDatabase, input: {
58
58
  }>;
59
59
  /** Count one resolved action — the Bun store's `recordAction`, as ONE D1 batch (`./actions.ts`). */
60
60
  export declare function recordActionD1(db: D1LikeDatabase, use: ActionUse): Promise<void>;
61
+ /** Count a tally of actions (`tallyActions`) as ONE D1 batch: two statements a row, 200 at the batch cap. */
62
+ export declare function recordActionsD1(db: D1LikeDatabase, uses: readonly ActionUse[]): Promise<void>;
61
63
  /**
62
64
  * The recorder as the kit's `createEngagementRecorder` mounts it — `POST /view` under
63
65
  * `ENGAGEMENT_BASE_PATH` — over D1. Recording only: there is no read surface here, as there is
@@ -75,4 +77,5 @@ export declare function createD1EngagementRecorder(options: {
75
77
  now?: () => number;
76
78
  }): Hono;
77
79
  export { ENGAGEMENT_ACTION_DDL } from "./actions.js";
80
+ export { ENGAGEMENT_SESSION_DDL } from "./visits.js";
78
81
  export { actionsFromManifest, placesFromManifest } from "./manifestPlaces.js";
@@ -1,6 +1,7 @@
1
1
  import { Hono } from "hono";
2
- import { actionStatements, claimedAction } from "./actions.js";
3
- import { dayKey, foldView, OTHER_PLACE, resolveAction, resolvePlace } from "./policy.js";
2
+ import { actionDoor, actionStatements } from "./actions.js";
3
+ import { dayKey, foldView, OTHER_PLACE, resolvePlace } from "./policy.js";
4
+ import { ENGAGEMENT_SESSION_DDL, visitStatements } from "./visits.js";
4
5
  /** The kit store's own tables and indexes, as one-line DDL — see the header. */
5
6
  export const ENGAGEMENT_DDL = [
6
7
  "CREATE TABLE IF NOT EXISTS engagement_days ( user_key TEXT NOT NULL, place TEXT NOT NULL, day TEXT NOT NULL, views INTEGER NOT NULL DEFAULT 0, active_ms INTEGER NOT NULL DEFAULT 0, sessions INTEGER NOT NULL DEFAULT 0, first_ts INTEGER NOT NULL, last_ts INTEGER NOT NULL, PRIMARY KEY (user_key, place, day) )",
@@ -49,11 +50,37 @@ export async function recordViewD1(db, input) {
49
50
  last_ts = excluded.last_ts, last_place = excluded.last_place`)
50
51
  .bind(userKey, sessionDelta, ts, ts, place, fold.activeMs));
51
52
  await db.batch(statements);
53
+ await recordVisitD1(db, { userKey, ts }, fold);
52
54
  return fold;
53
55
  }
56
+ /**
57
+ * The view's visit (`visits.ts`), after its batch and never in it, and it never throws: the view is
58
+ * already safe, and a beacon's answer must not depend on this. The first write on a D1 without the
59
+ * table creates it, so a version bump needs no migration in any app and no deploy order.
60
+ */
61
+ async function recordVisitD1(db, view, fold) {
62
+ const write = () => db.batch(visitStatements(view, fold).map(({ sql, params }) => db.prepare(sql).bind(...params)));
63
+ try {
64
+ await write().catch(async (error) => {
65
+ if (!/no such table/i.test(String(error)))
66
+ throw error;
67
+ await db.batch(ENGAGEMENT_SESSION_DDL.map((ddl) => db.prepare(ddl)));
68
+ await write();
69
+ });
70
+ }
71
+ catch (error) {
72
+ console.warn(`[engagement] a visit was not recorded: ${String(error)}`);
73
+ }
74
+ }
54
75
  /** Count one resolved action — the Bun store's `recordAction`, as ONE D1 batch (`./actions.ts`). */
55
76
  export async function recordActionD1(db, use) {
56
- await db.batch(actionStatements(use).map(({ sql, params }) => db.prepare(sql).bind(...params)));
77
+ await recordActionsD1(db, [use]);
78
+ }
79
+ /** Count a tally of actions (`tallyActions`) as ONE D1 batch: two statements a row, 200 at the batch cap. */
80
+ export async function recordActionsD1(db, uses) {
81
+ if (uses.length === 0)
82
+ return;
83
+ await db.batch(uses.flatMap(actionStatements).map(({ sql, params }) => db.prepare(sql).bind(...params)));
57
84
  }
58
85
  /**
59
86
  * The recorder as the kit's `createEngagementRecorder` mounts it — `POST /view` under
@@ -94,16 +121,15 @@ export function createD1EngagementRecorder(options) {
94
121
  catch {
95
122
  return c.json({ error: "expected a json body" }, 400);
96
123
  }
97
- const claimed = claimedAction(body);
98
- if ("error" in claimed)
99
- return c.json({ error: claimed.error }, 400);
100
- const place = resolvePlace(claimed.place, options.places);
101
- const action = resolveAction(claimed.action, actions);
102
- await recordActionD1(options.db, { userKey, place, action, ts: now() });
103
- return c.json({ ok: true, place, action, bucketed: place === OTHER_PLACE || action === OTHER_PLACE });
124
+ const door = actionDoor(body, { userKey, now: now(), places: options.places, actions });
125
+ if ("error" in door)
126
+ return c.json({ error: door.error }, 400);
127
+ await recordActionsD1(options.db, door.uses);
128
+ return c.json(door.reply);
104
129
  });
105
130
  }
106
131
  return app;
107
132
  }
108
133
  export { ENGAGEMENT_ACTION_DDL } from "./actions.js";
134
+ export { ENGAGEMENT_SESSION_DDL } from "./visits.js";
109
135
  export { actionsFromManifest, placesFromManifest } from "./manifestPlaces.js";
@@ -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
@@ -73,6 +75,8 @@ export declare class EngagementStore {
73
75
  * dwell: an action is something done on the page the view already counted.
74
76
  */
75
77
  recordAction(use: ActionUse): void;
78
+ /** Count a tally of actions (`tallyActions`) in ONE transaction — what a batched POST writes. */
79
+ recordActions(uses: readonly ActionUse[]): void;
76
80
  /** Every (user, place, action) lifetime roll-up, most used first. */
77
81
  actions(): EngagementActionUse[];
78
82
  /** Every account's roll-up for this app, most recently seen first. */
@@ -84,7 +88,7 @@ export declare class EngagementStore {
84
88
  /**
85
89
  * Drop daily rows older than the retention window.
86
90
  *
87
- * 🔴 Only the daily grains (`engagement_days`, `engagement_action_days`). The roll-ups are deliberately untouched —
91
+ * 🔴 Only the daily grains (`engagement_days`, `engagement_action_days`) and the visits. The roll-ups are deliberately untouched —
88
92
  * see the file header. An agent "completing" this by trimming them too would
89
93
  * delete the only record that somebody used to be here, which is the entire
90
94
  * drop-off signal.
@@ -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
@@ -36,6 +38,7 @@ import { mkdirSync } from "node:fs";
36
38
  import { dirname, resolve } from "node:path";
37
39
  import { actionStatements, ENGAGEMENT_ACTION_DDL } from "./actions.js";
38
40
  import { dayKey, foldView } from "./policy.js";
41
+ import { ENGAGEMENT_SESSION_DDL, visitStatements } from "./visits.js";
39
42
  /**
40
43
  * `bun:sqlite`'s `create: true` creates the FILE, never the directory above it, so a first boot
41
44
  * into an empty data dir would throw here. Swallowed on purpose: the open that follows names the
@@ -114,6 +117,9 @@ export class EngagementStore {
114
117
  // Feature actions (task 3470) — `actions.ts` says why they are their own two tables.
115
118
  for (const ddl of ENGAGEMENT_ACTION_DDL)
116
119
  this.handle.run(ddl);
120
+ // Visits (the owner's "at the same time", 2026-10-30) — `visits.ts` says why they are their own table.
121
+ for (const ddl of ENGAGEMENT_SESSION_DDL)
122
+ this.handle.run(ddl);
117
123
  }
118
124
  /**
119
125
  * Record one resolved place-view.
@@ -162,6 +168,8 @@ export class EngagementStore {
162
168
  active_ms = active_ms + ?,
163
169
  last_ts = excluded.last_ts,
164
170
  last_place = excluded.last_place`, [userKey, sessionDelta, ts, ts, place, fold.activeMs]);
171
+ for (const { sql, params } of visitStatements({ userKey, ts }, fold))
172
+ this.handle.run(sql, params);
165
173
  // Amortised, exactly as the metrics store trims: a DELETE per beacon would
166
174
  // cost more than the beacon, and never trimming lets a long-lived daemon
167
175
  // keep every day it has ever served.
@@ -175,13 +183,19 @@ export class EngagementStore {
175
183
  * dwell: an action is something done on the page the view already counted.
176
184
  */
177
185
  recordAction(use) {
178
- const statements = actionStatements(use);
186
+ this.recordActions([use]);
187
+ }
188
+ /** Count a tally of actions (`tallyActions`) in ONE transaction — what a batched POST writes. */
189
+ recordActions(uses) {
190
+ const last = uses.at(-1);
191
+ if (!last)
192
+ return;
179
193
  this.handle.transaction(() => {
180
- for (const { sql, params } of statements)
194
+ for (const { sql, params } of uses.flatMap(actionStatements))
181
195
  this.handle.run(sql, params);
182
196
  })();
183
197
  if (++this.writes % 256 === 0)
184
- this.prune(use.ts);
198
+ this.prune(last.ts);
185
199
  }
186
200
  /** Every (user, place, action) lifetime roll-up, most used first. */
187
201
  actions() {
@@ -221,7 +235,7 @@ export class EngagementStore {
221
235
  /**
222
236
  * Drop daily rows older than the retention window.
223
237
  *
224
- * 🔴 Only the daily grains (`engagement_days`, `engagement_action_days`). The roll-ups are deliberately untouched —
238
+ * 🔴 Only the daily grains (`engagement_days`, `engagement_action_days`) and the visits. The roll-ups are deliberately untouched —
225
239
  * see the file header. An agent "completing" this by trimming them too would
226
240
  * delete the only record that somebody used to be here, which is the entire
227
241
  * drop-off signal.
@@ -230,7 +244,8 @@ export class EngagementStore {
230
244
  const cutoff = dayKey(at - this.retentionDays * 86_400_000);
231
245
  // The action DAYS age out with the view days; `engagement_actions` is a roll-up and stays.
232
246
  const actionDays = this.handle.run("DELETE FROM engagement_action_days WHERE day < ?", [cutoff]).changes;
233
- return this.handle.run("DELETE FROM engagement_days WHERE day < ?", [cutoff]).changes + actionDays;
247
+ const visits = this.handle.run("DELETE FROM engagement_sessions WHERE start_ts < ?", [at - this.retentionDays * 86_400_000]).changes;
248
+ return this.handle.run("DELETE FROM engagement_days WHERE day < ?", [cutoff]).changes + actionDays + visits;
234
249
  }
235
250
  /** Row counts + age bounds, for the retention card. */
236
251
  stats() {
@@ -0,0 +1,37 @@
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
+ /** As long as the daily grain: a visit is the more sensitive row, so it is never kept longer. */
24
+ export declare const ENGAGEMENT_VISIT_RETENTION_DAYS = 120;
25
+ export declare const ENGAGEMENT_SESSION_DDL: readonly string[];
26
+ /**
27
+ * What one view does to the visits: opens one, trimming the ones past retention, or extends the open
28
+ * one. A view in a visit that began before this table existed updates nothing, and its visit is simply
29
+ * not recorded; the next one is.
30
+ */
31
+ export declare function visitStatements(view: {
32
+ userKey: string;
33
+ ts: number;
34
+ }, fold: ViewFold): Array<{
35
+ sql: string;
36
+ params: (string | number)[];
37
+ }>;
@@ -0,0 +1,28 @@
1
+ /** As long as the daily grain: a visit is the more sensitive row, so it is never kept longer. */
2
+ export const ENGAGEMENT_VISIT_RETENTION_DAYS = 120;
3
+ export const ENGAGEMENT_SESSION_DDL = [
4
+ "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) )",
5
+ "CREATE INDEX IF NOT EXISTS idx_engagement_sessions_start ON engagement_sessions (start_ts)",
6
+ ];
7
+ /**
8
+ * What one view does to the visits: opens one, trimming the ones past retention, or extends the open
9
+ * one. A view in a visit that began before this table existed updates nothing, and its visit is simply
10
+ * not recorded; the next one is.
11
+ */
12
+ export function visitStatements(view, fold) {
13
+ const { userKey, ts } = view;
14
+ if (fold.newSession)
15
+ return [
16
+ // IGNORE: two views in one millisecond are one visit opened twice.
17
+ { sql: "INSERT OR IGNORE INTO engagement_sessions (user_key, start_ts, end_ts, views, active_ms) VALUES (?, ?, ?, 1, 0)", params: [userKey, ts, ts] },
18
+ { sql: "DELETE FROM engagement_sessions WHERE start_ts < ?", params: [ts - ENGAGEMENT_VISIT_RETENTION_DAYS * 86_400_000] },
19
+ ];
20
+ return [
21
+ {
22
+ // MAX: a device with a wrong clock makes a number boring, never a visit that ends before it began.
23
+ sql: `UPDATE engagement_sessions SET end_ts = MAX(end_ts, ?), views = views + 1, active_ms = active_ms + ?
24
+ WHERE user_key = ? AND start_ts = (SELECT MAX(start_ts) FROM engagement_sessions WHERE user_key = ?)`,
25
+ params: [ts, fold.activeMs, userKey, userKey],
26
+ },
27
+ ];
28
+ }
@@ -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.57.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
+ }