cursedbelt-server 4.47.0 → 4.48.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.
- package/dist/server/d1/pullD1.js +14 -1
- package/dist/server/engagement/actions.d.ts +20 -0
- package/dist/server/engagement/actions.js +62 -0
- package/dist/server/engagement/api.d.ts +13 -2
- package/dist/server/engagement/api.js +30 -2
- package/dist/server/engagement/d1.d.ts +13 -2
- package/dist/server/engagement/d1.js +30 -2
- package/dist/server/engagement/index.d.ts +4 -3
- package/dist/server/engagement/index.js +2 -1
- package/dist/server/engagement/manifestPlaces.d.ts +7 -1
- package/dist/server/engagement/manifestPlaces.js +21 -0
- package/dist/server/engagement/places.d.ts +3 -0
- package/dist/server/engagement/places.js +9 -2
- package/dist/server/engagement/policy.d.ts +21 -0
- package/dist/server/engagement/policy.js +27 -0
- package/dist/server/engagement/store.d.ts +12 -3
- package/dist/server/engagement/store.js +30 -2
- package/dist/server/engagement/summary.d.ts +15 -1
- package/dist/server/engagement/summary.js +15 -0
- package/dist/server/engagement/types.d.ts +9 -0
- package/docs/engagement.md +10 -1
- package/package.json +1 -1
- package/src/server/d1/pullD1.spec.ts +12 -0
- package/src/server/d1/pullD1.ts +16 -1
- package/src/server/engagement/actions.ts +71 -0
- package/src/server/engagement/api.ts +36 -1
- package/src/server/engagement/d1.spec.ts +49 -3
- package/src/server/engagement/d1.ts +35 -2
- package/src/server/engagement/engagement.spec.ts +102 -0
- package/src/server/engagement/index.ts +4 -1
- package/src/server/engagement/manifestPlaces.ts +21 -1
- package/src/server/engagement/places.ts +12 -2
- package/src/server/engagement/policy.ts +34 -0
- package/src/server/engagement/store.ts +33 -4
- package/src/server/engagement/summary.ts +33 -0
- package/src/server/engagement/types.ts +10 -0
|
@@ -82,6 +82,20 @@ export function summarize(input) {
|
|
|
82
82
|
lastTs: p.lastTs,
|
|
83
83
|
}))
|
|
84
84
|
.sort((a, b) => b.views - a.views);
|
|
85
|
+
const byAction = new Map();
|
|
86
|
+
for (const row of input.actions ?? []) {
|
|
87
|
+
const key = `${row.place}\u0000${row.action}`;
|
|
88
|
+
const existing = byAction.get(key);
|
|
89
|
+
if (existing) {
|
|
90
|
+
existing.count += row.uses;
|
|
91
|
+
existing.accounts += 1;
|
|
92
|
+
existing.lastTs = Math.max(existing.lastTs, row.lastTs);
|
|
93
|
+
}
|
|
94
|
+
else {
|
|
95
|
+
byAction.set(key, { place: row.place, name: row.action, count: row.uses, accounts: 1, lastTs: row.lastTs });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const actions = [...byAction.values()].sort((a, b) => b.count - a.count || a.place.localeCompare(b.place) || a.name.localeCompare(b.name));
|
|
85
99
|
return {
|
|
86
100
|
app,
|
|
87
101
|
generatedAt: now,
|
|
@@ -89,6 +103,7 @@ export function summarize(input) {
|
|
|
89
103
|
places,
|
|
90
104
|
userPlaces,
|
|
91
105
|
daily,
|
|
106
|
+
actions,
|
|
92
107
|
totals: {
|
|
93
108
|
users: users.length,
|
|
94
109
|
views: users.reduce((n, u) => n + u.views, 0),
|
|
@@ -29,6 +29,15 @@ export interface EngagementUserPlace {
|
|
|
29
29
|
firstTs: number;
|
|
30
30
|
lastTs: number;
|
|
31
31
|
}
|
|
32
|
+
/** One (user, place, action) lifetime roll-up — "who uses this feature, and when last" (task 3470). */
|
|
33
|
+
export interface EngagementActionUse {
|
|
34
|
+
userKey: string;
|
|
35
|
+
place: string;
|
|
36
|
+
action: string;
|
|
37
|
+
uses: number;
|
|
38
|
+
firstTs: number;
|
|
39
|
+
lastTs: number;
|
|
40
|
+
}
|
|
32
41
|
/** One account's relationship with the whole app. */
|
|
33
42
|
export interface EngagementUser {
|
|
34
43
|
userKey: string;
|
package/docs/engagement.md
CHANGED
|
@@ -17,11 +17,20 @@ a feedback-kit standard for its mount-order rule; neither existed here until 202
|
|
|
17
17
|
The user key comes ONLY from the app's `resolveUser(c)` — never from the request body — so the
|
|
18
18
|
beacon cannot be used to write somebody else's history.
|
|
19
19
|
|
|
20
|
+
**Feature actions (4.48.0, task 3470)** keep all three rules. `POST <mount>/action {place, action}`
|
|
21
|
+
counts a NAME from the manifest's top-level `actions` list (`{ id, label }[]`) on a resolved place —
|
|
22
|
+
`search`, never the query. Anything undeclared records as `other`. Two tables
|
|
23
|
+
(`src/server/engagement/actions.ts` says why): `engagement_actions` (lifetime per account, never
|
|
24
|
+
trimmed — it is who to ask before changing a feature) and `engagement_action_days` (trimmed with the
|
|
25
|
+
view days). An app opts in by passing `actions` to the recorder (`engagementActionsFor(dir)` on Bun,
|
|
26
|
+
`actionsFromManifest(json)` on a Worker, whose D1 also needs `ENGAGEMENT_ACTION_DDL`); without it
|
|
27
|
+
there is no action door.
|
|
28
|
+
|
|
20
29
|
## 2. Mount order — the decision four apps had to agree on
|
|
21
30
|
|
|
22
31
|
| receiver | its credential | mounts |
|
|
23
32
|
|---|---|---|
|
|
24
|
-
| the engagement recorder (`POST <mount>/view`) | none of its own — it needs the SESSION's user | **AFTER** the session gate |
|
|
33
|
+
| the engagement recorder (`POST <mount>/view`, `/action`) | none of its own — it needs the SESSION's user | **AFTER** the session gate |
|
|
25
34
|
| a sync receiver (a feed another machine pushes into) | its own bearer | **BEFORE** the session gate |
|
|
26
35
|
|
|
27
36
|
The two are mirror images for one reason: **a door mounts on the side of the gate that supplies
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cursedbelt-server",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.48.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.",
|
|
@@ -364,6 +364,18 @@ describe('pulling D1 down — paged SELECTs, table by table, never an export', (
|
|
|
364
364
|
expect(row?.art_key).toBe('art/1');
|
|
365
365
|
});
|
|
366
366
|
|
|
367
|
+
test('🔴 a column D1 holds that the schema has dropped is added to the snapshot, never refused (music, 2026-10-20)', async () => {
|
|
368
|
+
const dir = scratch();
|
|
369
|
+
// The schema stopped declaring `tracks.rating` before production D1 dropped it: every night
|
|
370
|
+
// between those two refused with `table tracks has no column named rating`.
|
|
371
|
+
const source = live("ALTER TABLE items ADD COLUMN rating INTEGER; INSERT INTO items VALUES ('i1', 'x', 4);");
|
|
372
|
+
await pull(dir, d1(source).run);
|
|
373
|
+
const db = opened(dir);
|
|
374
|
+
const row = db.query('select name, rating from items').get() as { name: string; rating: number } | null;
|
|
375
|
+
db.close();
|
|
376
|
+
expect(row).toEqual({ name: 'x', rating: 4 });
|
|
377
|
+
});
|
|
378
|
+
|
|
367
379
|
test('🔴 a schema TRIGGER does not fire on the restored rows, and is in the snapshot after (collections, 2026-09-29)', async () => {
|
|
368
380
|
const dir = scratch();
|
|
369
381
|
const schema = `${SCHEMA}
|
package/src/server/d1/pullD1.ts
CHANGED
|
@@ -408,7 +408,7 @@ export async function pullD1ToSqlite(options: PullD1Options): Promise<void> {
|
|
|
408
408
|
const dumps = tables.map((table, i) => {
|
|
409
409
|
const cols = (columnSets[i] ?? []) as Array<{ name: string; pk: number }>;
|
|
410
410
|
const plan = tablePlan(table, rows.find((r) => r.name === table)?.sql ?? null, cols);
|
|
411
|
-
return { table, ...dumpTable(caller, database, plan) };
|
|
411
|
+
return { table, columns: plan.columns, ...dumpTable(caller, database, plan) };
|
|
412
412
|
});
|
|
413
413
|
if (dumps.every((d) => d.rows === 0)) {
|
|
414
414
|
throw new Error('the D1 pull contains no rows — refusing to snapshot an empty database as if it were the library');
|
|
@@ -441,6 +441,21 @@ export async function pullD1ToSqlite(options: PullD1Options): Promise<void> {
|
|
|
441
441
|
if (!tables.includes(row.name) || have.has(row.name) || !row.sql) continue;
|
|
442
442
|
db.exec(row.sql.replace(/^\s*CREATE\s+TABLE\s+(?!IF\s+NOT\s+EXISTS)/i, 'CREATE TABLE IF NOT EXISTS '));
|
|
443
443
|
}
|
|
444
|
+
// 🔴 Likewise a COLUMN D1 holds that the schema does not declare is added, untyped, so its
|
|
445
|
+
// values land exactly as D1 quoted them: measured on music (2026-10-20), the schema dropped
|
|
446
|
+
// `tracks.rating` before production D1 did, and every night between the two refused with
|
|
447
|
+
// `table tracks has no column named rating`. A backup keeps what the live rows hold.
|
|
448
|
+
for (const { table, columns } of dumps) {
|
|
449
|
+
const local = new Set(
|
|
450
|
+
(db.query(`SELECT name FROM pragma_table_info(${sqlText(table)})`).all() as { name: string }[]).map((c) =>
|
|
451
|
+
c.name.toLowerCase(),
|
|
452
|
+
),
|
|
453
|
+
);
|
|
454
|
+
if (local.size === 0) continue;
|
|
455
|
+
for (const column of columns) {
|
|
456
|
+
if (!local.has(column.toLowerCase())) db.exec(`ALTER TABLE ${sqlIdent(table)} ADD COLUMN ${sqlIdent(column)}`);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
444
459
|
// One table at a time, so a fault is located rather than smeared over the whole load.
|
|
445
460
|
for (const { text } of dumps) if (text) db.exec(text);
|
|
446
461
|
for (const t of triggers) db.exec(t.sql);
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Feature ACTIONS — what somebody DID on a page, beside where they were (task 3470).
|
|
3
|
+
*
|
|
4
|
+
* A place-view answers "which pages do they open". The owner's question goes one step further:
|
|
5
|
+
* *"what features they use and ignore … and know which users to ask first when I am planning to
|
|
6
|
+
* add or delete a feature"*. A page is not a feature — music's library page holds play, search,
|
|
7
|
+
* rate and download — so this records a declared ACTION NAME per (account, place).
|
|
8
|
+
*
|
|
9
|
+
* ── The privacy contract is the places' contract, unchanged ─────────────────
|
|
10
|
+
* The action is a NAME from the app's own `routes.manifest.json` `actions` list
|
|
11
|
+
* (`policy.ts:resolveAction`); the place is resolved against the same manifest as a view. There is
|
|
12
|
+
* no field for a value — `search`, never the query; `play`, never the track — so nothing a person
|
|
13
|
+
* typed or chose can reach a row. The account is the session's subject, never the body's.
|
|
14
|
+
*
|
|
15
|
+
* ── Counts and clocks, two grains ───────────────────────────────────────────
|
|
16
|
+
* engagement_actions (user, place, action) → uses, first, last. LIFETIME, never trimmed:
|
|
17
|
+
* it is the row that answers "who uses this most, and when did they last",
|
|
18
|
+
* and trimming it would make a feature's old regulars vanish.
|
|
19
|
+
* engagement_action_days (user, place, action, day) → uses. Trimmed with the view days, for
|
|
20
|
+
* "used this month" against "used once, long ago".
|
|
21
|
+
* No event log, no sequence: an action does not touch the sessionization clock or dwell.
|
|
22
|
+
*
|
|
23
|
+
* 🔴 Its own DDL, not appended to `ENGAGEMENT_DDL`: an app whose schema is generated from that list
|
|
24
|
+
* (music, family, desk, arch) would otherwise go red on the version bump alone. An app opts in by
|
|
25
|
+
* declaring `actions` and applying {@link ENGAGEMENT_ACTION_DDL}; the Bun store always creates both.
|
|
26
|
+
*
|
|
27
|
+
* Pure and Worker-safe: the Bun store and the D1 recorder both write through
|
|
28
|
+
* {@link actionStatements}, so there is one write, not two that agree.
|
|
29
|
+
*/
|
|
30
|
+
import { dayKey } from "./policy.js";
|
|
31
|
+
|
|
32
|
+
export const ENGAGEMENT_ACTION_DDL: readonly string[] = [
|
|
33
|
+
"CREATE TABLE IF NOT EXISTS engagement_actions ( user_key TEXT NOT NULL, place TEXT NOT NULL, action TEXT NOT NULL, uses INTEGER NOT NULL DEFAULT 0, first_ts INTEGER NOT NULL, last_ts INTEGER NOT NULL, PRIMARY KEY (user_key, place, action) )",
|
|
34
|
+
"CREATE TABLE IF NOT EXISTS engagement_action_days ( user_key TEXT NOT NULL, place TEXT NOT NULL, action TEXT NOT NULL, day TEXT NOT NULL, uses INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (user_key, place, action, day) )",
|
|
35
|
+
"CREATE INDEX IF NOT EXISTS idx_engagement_action_days_day ON engagement_action_days (day)",
|
|
36
|
+
];
|
|
37
|
+
|
|
38
|
+
/** One resolved action, ready to count. `place` and `action` have been through the allowlists. */
|
|
39
|
+
export interface ActionUse {
|
|
40
|
+
userKey: string;
|
|
41
|
+
place: string;
|
|
42
|
+
action: string;
|
|
43
|
+
ts: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The two upserts one action is — run them together (a transaction, or one D1 batch). */
|
|
47
|
+
export function actionStatements(use: ActionUse): Array<{ sql: string; params: (string | number)[] }> {
|
|
48
|
+
const { userKey, place, action, ts } = use;
|
|
49
|
+
return [
|
|
50
|
+
{
|
|
51
|
+
sql: `INSERT INTO engagement_actions (user_key, place, action, uses, first_ts, last_ts)
|
|
52
|
+
VALUES (?, ?, ?, 1, ?, ?)
|
|
53
|
+
ON CONFLICT(user_key, place, action) DO UPDATE SET uses = uses + 1, last_ts = excluded.last_ts`,
|
|
54
|
+
params: [userKey, place, action, ts, ts],
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
sql: `INSERT INTO engagement_action_days (user_key, place, action, day, uses)
|
|
58
|
+
VALUES (?, ?, ?, ?, 1)
|
|
59
|
+
ON CONFLICT(user_key, place, action, day) DO UPDATE SET uses = uses + 1`,
|
|
60
|
+
params: [userKey, place, action, dayKey(ts)],
|
|
61
|
+
},
|
|
62
|
+
];
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Read the claimed `{ place, action }` out of a request body — a string each, or a reason why not. */
|
|
66
|
+
export function claimedAction(body: unknown): { place: string; action: string } | { error: string } {
|
|
67
|
+
const b = body as { place?: unknown; action?: unknown } | null;
|
|
68
|
+
if (typeof b?.action !== "string") return { error: "action must be a string" };
|
|
69
|
+
if (typeof b.place !== "string") return { error: "place must be a string" };
|
|
70
|
+
return { place: b.place, action: b.action };
|
|
71
|
+
}
|
|
@@ -3,6 +3,9 @@
|
|
|
3
3
|
*
|
|
4
4
|
* POST /api/engagement/view → the beacon. SESSION-gated; the user id comes
|
|
5
5
|
* from the session, never from the body.
|
|
6
|
+
* POST /api/engagement/action → a feature used on a page — `{ place, action }`, both
|
|
7
|
+
* NAMES resolved against the manifest (`actions.ts`).
|
|
8
|
+
* Mounted only for an app that passes `actions`.
|
|
6
9
|
*
|
|
7
10
|
* 🔴 **There is no HTTP read surface, on purpose** (task `113`/`268`, 2026-09-22).
|
|
8
11
|
* `GET /api/admin/engagement` used to sit here behind `SATELLITE_METRICS_TOKEN` —
|
|
@@ -31,7 +34,8 @@
|
|
|
31
34
|
*/
|
|
32
35
|
import { Hono } from "hono";
|
|
33
36
|
import type { Context } from "hono";
|
|
34
|
-
import {
|
|
37
|
+
import { claimedAction } from "./actions.js";
|
|
38
|
+
import { type ActionRef, OTHER_PLACE, type PlaceRef, resolveAction, resolvePlace } from "./policy.js";
|
|
35
39
|
import type { EngagementStore } from "./store.js";
|
|
36
40
|
import { type AppEngagement, returnCurve, summarize } from "./summary.js";
|
|
37
41
|
|
|
@@ -45,6 +49,12 @@ export interface EngagementApiOptions {
|
|
|
45
49
|
* rule 1 for why this is the whole privacy story.
|
|
46
50
|
*/
|
|
47
51
|
places: readonly PlaceRef[];
|
|
52
|
+
/**
|
|
53
|
+
* The allowlist of ACTION names — the manifest's `actions` (`engagementActionsFor`). Present,
|
|
54
|
+
* the recorder grows `POST /action`; an undeclared name records as `other`, as a place does.
|
|
55
|
+
* Absent, there is no action door at all (task 3470).
|
|
56
|
+
*/
|
|
57
|
+
actions?: readonly ActionRef[];
|
|
48
58
|
/** Resolve the CURRENT request's account. Null → 401, nothing recorded. */
|
|
49
59
|
resolveUser: (c: Context) => string | null;
|
|
50
60
|
/** Injectable clock, so the tests are not timing-dependent. */
|
|
@@ -81,6 +91,26 @@ export function createEngagementRecorder(options: EngagementApiOptions): Hono {
|
|
|
81
91
|
return c.json({ ok: true, place, bucketed: place === OTHER_PLACE, ...fold });
|
|
82
92
|
});
|
|
83
93
|
|
|
94
|
+
const actions = options.actions;
|
|
95
|
+
if (actions) {
|
|
96
|
+
app.post("/action", async (c) => {
|
|
97
|
+
const userKey = options.resolveUser(c);
|
|
98
|
+
if (!userKey) return c.json({ error: "unauthenticated" }, 401);
|
|
99
|
+
let body: unknown;
|
|
100
|
+
try {
|
|
101
|
+
body = await c.req.json();
|
|
102
|
+
} catch {
|
|
103
|
+
return c.json({ error: "expected a json body" }, 400);
|
|
104
|
+
}
|
|
105
|
+
const claimed = claimedAction(body);
|
|
106
|
+
if ("error" in claimed) return c.json({ error: claimed.error }, 400);
|
|
107
|
+
const place = resolvePlace(claimed.place, options.places);
|
|
108
|
+
const action = resolveAction(claimed.action, actions);
|
|
109
|
+
options.store.recordAction({ userKey, place, action, ts: now() });
|
|
110
|
+
return c.json({ ok: true, place, action, bucketed: place === OTHER_PLACE || action === OTHER_PLACE });
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
84
114
|
return app;
|
|
85
115
|
}
|
|
86
116
|
|
|
@@ -89,6 +119,8 @@ export interface AppEngagementSnapshot extends AppEngagement {
|
|
|
89
119
|
/** The manifest ids this app CAN report — so a reader can show a place
|
|
90
120
|
* with zero views, which is the half of the question that is easy to lose. */
|
|
91
121
|
knownPlaces: string[];
|
|
122
|
+
/** The action names this app declares — a declared action nobody used is the "ignored" half. */
|
|
123
|
+
knownActions: string[];
|
|
92
124
|
returnCurve: Array<{ day: string; joined: number; returned: number }>;
|
|
93
125
|
retention: { days: number; places: number; users: number; oldestDay: string | null };
|
|
94
126
|
}
|
|
@@ -98,6 +130,7 @@ export function readAppEngagement(
|
|
|
98
130
|
app: string,
|
|
99
131
|
now: number,
|
|
100
132
|
knownPlaces: readonly PlaceRef[] = [],
|
|
133
|
+
knownActions: readonly ActionRef[] = [],
|
|
101
134
|
): AppEngagementSnapshot {
|
|
102
135
|
const users = store.users();
|
|
103
136
|
const summary = summarize({
|
|
@@ -109,10 +142,12 @@ export function readAppEngagement(
|
|
|
109
142
|
// silently return less, which reads as a quiet period rather than as a
|
|
110
143
|
// window boundary.
|
|
111
144
|
days: store.days(now - 120 * 86_400_000),
|
|
145
|
+
actions: store.actions(),
|
|
112
146
|
});
|
|
113
147
|
return {
|
|
114
148
|
...summary,
|
|
115
149
|
knownPlaces: knownPlaces.map((p) => p.id),
|
|
150
|
+
knownActions: knownActions.map((a) => a.id),
|
|
116
151
|
returnCurve: returnCurve(users, now),
|
|
117
152
|
retention: store.stats(),
|
|
118
153
|
};
|
|
@@ -9,8 +9,16 @@ import { tmpdir } from 'node:os';
|
|
|
9
9
|
import { join } from 'node:path';
|
|
10
10
|
import { Hono } from 'hono';
|
|
11
11
|
import { createLocalD1 } from '../d1/local.js';
|
|
12
|
-
import {
|
|
13
|
-
|
|
12
|
+
import {
|
|
13
|
+
actionsFromManifest,
|
|
14
|
+
createD1EngagementRecorder,
|
|
15
|
+
ENGAGEMENT_ACTION_DDL,
|
|
16
|
+
ENGAGEMENT_DDL,
|
|
17
|
+
placesFromManifest,
|
|
18
|
+
recordActionD1,
|
|
19
|
+
recordViewD1,
|
|
20
|
+
} from './d1.js';
|
|
21
|
+
import { engagementActionsFor, engagementPlacesFor } from './places.js';
|
|
14
22
|
import { EngagementStore } from './store.js';
|
|
15
23
|
|
|
16
24
|
const dirs: string[] = [];
|
|
@@ -25,7 +33,7 @@ const tempDir = (): string => {
|
|
|
25
33
|
const kitStore = (): EngagementStore => new EngagementStore({ dbPath: join(tempDir(), 'engagement.sqlite') });
|
|
26
34
|
const d1 = () => {
|
|
27
35
|
const sqlite = new Database(':memory:');
|
|
28
|
-
for (const ddl of ENGAGEMENT_DDL) sqlite.run(ddl);
|
|
36
|
+
for (const ddl of [...ENGAGEMENT_DDL, ...ENGAGEMENT_ACTION_DDL]) sqlite.run(ddl);
|
|
29
37
|
return { sqlite, db: createLocalD1(sqlite) };
|
|
30
38
|
};
|
|
31
39
|
const shape = (db: Database) =>
|
|
@@ -38,6 +46,8 @@ const dump = (db: Database) => ({
|
|
|
38
46
|
days: db.query('SELECT * FROM engagement_days ORDER BY user_key, place, day').all(),
|
|
39
47
|
places: db.query('SELECT * FROM engagement_places ORDER BY user_key, place').all(),
|
|
40
48
|
users: db.query('SELECT * FROM engagement_users ORDER BY user_key').all(),
|
|
49
|
+
actions: db.query('SELECT * FROM engagement_actions ORDER BY user_key, place, action').all(),
|
|
50
|
+
actionDays: db.query('SELECT * FROM engagement_action_days ORDER BY user_key, place, action, day').all(),
|
|
41
51
|
});
|
|
42
52
|
|
|
43
53
|
describe('cursedbelt-server/engagement/d1', () => {
|
|
@@ -99,4 +109,40 @@ describe('cursedbelt-server/engagement/d1', () => {
|
|
|
99
109
|
expect(placesFromManifest('not a manifest')).toEqual([]);
|
|
100
110
|
expect(placesFromManifest(null)).toEqual([]);
|
|
101
111
|
});
|
|
112
|
+
|
|
113
|
+
test('🔴 the same actions produce the same rows as the kit store, and the door names only declared ones', async () => {
|
|
114
|
+
const kit = kitStore();
|
|
115
|
+
const { sqlite, db } = d1();
|
|
116
|
+
const t0 = Date.UTC(2026, 9, 22, 10, 0, 0);
|
|
117
|
+
const uses = [
|
|
118
|
+
{ userKey: 'u1', place: 'home', action: 'play', ts: t0 },
|
|
119
|
+
{ userKey: 'u1', place: 'home', action: 'play', ts: t0 + 60_000 },
|
|
120
|
+
{ userKey: 'u2', place: 'home', action: 'search', ts: t0 + 26 * 3_600_000 },
|
|
121
|
+
];
|
|
122
|
+
for (const u of uses) {
|
|
123
|
+
await recordActionD1(db, u);
|
|
124
|
+
kit.recordAction(u);
|
|
125
|
+
}
|
|
126
|
+
expect(dump(sqlite)).toEqual(dump(kit.handle));
|
|
127
|
+
|
|
128
|
+
const doc = { routes: [{ id: 'home', path: '/' }], actions: [{ id: 'play', label: 'play a track' }, 'search', { id: '' }, 'play'] };
|
|
129
|
+
const actions = actionsFromManifest(doc);
|
|
130
|
+
expect(actions).toEqual([{ id: 'play', label: 'play a track' }, { id: 'search' }]);
|
|
131
|
+
const dir = tempDir();
|
|
132
|
+
await Bun.write(join(dir, 'routes.manifest.json'), JSON.stringify(doc));
|
|
133
|
+
expect(engagementActionsFor(dir)).toEqual(actions);
|
|
134
|
+
expect(actionsFromManifest({ routes: [] })).toEqual([]);
|
|
135
|
+
|
|
136
|
+
const app = new Hono().route(
|
|
137
|
+
'/api/engagement',
|
|
138
|
+
createD1EngagementRecorder({ db, places: placesFromManifest(doc), actions, resolveUser: () => 'u3', now: () => t0 }),
|
|
139
|
+
);
|
|
140
|
+
const res = await app.request('http://x/api/engagement/action', {
|
|
141
|
+
method: 'POST',
|
|
142
|
+
headers: { 'content-type': 'application/json' },
|
|
143
|
+
body: JSON.stringify({ place: '/', action: 'rename playlist "private"' }),
|
|
144
|
+
});
|
|
145
|
+
expect(await res.json()).toMatchObject({ ok: true, place: 'home', action: 'other', bucketed: true });
|
|
146
|
+
expect(sqlite.query("SELECT action FROM engagement_actions WHERE user_key = 'u3'").all()).toEqual([{ action: 'other' }]);
|
|
147
|
+
});
|
|
102
148
|
});
|
|
@@ -31,13 +31,16 @@
|
|
|
31
31
|
*
|
|
32
32
|
* gated.route("/api/engagement", createD1EngagementRecorder({
|
|
33
33
|
* db, places: placesFromManifest(routesManifest), resolveUser: (c) => sso.userOf(c)?.id ?? null,
|
|
34
|
+
* // Optional — feature actions (task 3470); the D1 then needs ENGAGEMENT_ACTION_DDL too.
|
|
35
|
+
* actions: actionsFromManifest(routesManifest),
|
|
34
36
|
* }));
|
|
35
37
|
* ```
|
|
36
38
|
*/
|
|
37
39
|
import type { D1LikeDatabase } from "../d1/types.js";
|
|
38
40
|
import type { Context } from "hono";
|
|
39
41
|
import { Hono } from "hono";
|
|
40
|
-
import {
|
|
42
|
+
import { type ActionUse, actionStatements, claimedAction } from "./actions.js";
|
|
43
|
+
import { type ActionRef, dayKey, foldView, OTHER_PLACE, type PlaceRef, resolveAction, resolvePlace } from "./policy.js";
|
|
41
44
|
|
|
42
45
|
/** The kit store's own tables and indexes, as one-line DDL — see the header. */
|
|
43
46
|
export const ENGAGEMENT_DDL: readonly string[] = [
|
|
@@ -107,6 +110,11 @@ export async function recordViewD1(
|
|
|
107
110
|
return fold;
|
|
108
111
|
}
|
|
109
112
|
|
|
113
|
+
/** Count one resolved action — the Bun store's `recordAction`, as ONE D1 batch (`./actions.ts`). */
|
|
114
|
+
export async function recordActionD1(db: D1LikeDatabase, use: ActionUse): Promise<void> {
|
|
115
|
+
await db.batch(actionStatements(use).map(({ sql, params }) => db.prepare(sql).bind(...params)));
|
|
116
|
+
}
|
|
117
|
+
|
|
110
118
|
/**
|
|
111
119
|
* The recorder as the kit's `createEngagementRecorder` mounts it — `POST /view` under
|
|
112
120
|
* `ENGAGEMENT_BASE_PATH` — over D1. Recording only: there is no read surface here, as there is
|
|
@@ -115,6 +123,11 @@ export async function recordViewD1(
|
|
|
115
123
|
export function createD1EngagementRecorder(options: {
|
|
116
124
|
db: D1LikeDatabase;
|
|
117
125
|
places: readonly PlaceRef[];
|
|
126
|
+
/**
|
|
127
|
+
* The manifest's declared actions (`actionsFromManifest`). Present, `POST /action` is mounted
|
|
128
|
+
* and the D1 needs {@link ENGAGEMENT_ACTION_DDL} applied; absent, there is no action door.
|
|
129
|
+
*/
|
|
130
|
+
actions?: readonly ActionRef[];
|
|
118
131
|
resolveUser: (c: Context) => string | null;
|
|
119
132
|
now?: () => number;
|
|
120
133
|
}): Hono {
|
|
@@ -135,7 +148,27 @@ export function createD1EngagementRecorder(options: {
|
|
|
135
148
|
const fold = await recordViewD1(options.db, { userKey, place, ts: now() });
|
|
136
149
|
return c.json({ ok: true, place, bucketed: place === OTHER_PLACE, ...fold });
|
|
137
150
|
});
|
|
151
|
+
const actions = options.actions;
|
|
152
|
+
if (actions) {
|
|
153
|
+
app.post("/action", async (c) => {
|
|
154
|
+
const userKey = options.resolveUser(c);
|
|
155
|
+
if (!userKey) return c.json({ error: "unauthenticated" }, 401);
|
|
156
|
+
let body: unknown;
|
|
157
|
+
try {
|
|
158
|
+
body = await c.req.json();
|
|
159
|
+
} catch {
|
|
160
|
+
return c.json({ error: "expected a json body" }, 400);
|
|
161
|
+
}
|
|
162
|
+
const claimed = claimedAction(body);
|
|
163
|
+
if ("error" in claimed) return c.json({ error: claimed.error }, 400);
|
|
164
|
+
const place = resolvePlace(claimed.place, options.places);
|
|
165
|
+
const action = resolveAction(claimed.action, actions);
|
|
166
|
+
await recordActionD1(options.db, { userKey, place, action, ts: now() });
|
|
167
|
+
return c.json({ ok: true, place, action, bucketed: place === OTHER_PLACE || action === OTHER_PLACE });
|
|
168
|
+
});
|
|
169
|
+
}
|
|
138
170
|
return app;
|
|
139
171
|
}
|
|
140
172
|
|
|
141
|
-
export {
|
|
173
|
+
export { ENGAGEMENT_ACTION_DDL } from "./actions.js";
|
|
174
|
+
export { actionsFromManifest, placesFromManifest } from "./manifestPlaces.js";
|
|
@@ -23,6 +23,7 @@ import {
|
|
|
23
23
|
foldView,
|
|
24
24
|
MAX_DWELL_SLICE_MS,
|
|
25
25
|
OTHER_PLACE,
|
|
26
|
+
resolveAction,
|
|
26
27
|
resolvePlace,
|
|
27
28
|
SESSION_GAP_MS,
|
|
28
29
|
} from "./policy.js";
|
|
@@ -460,3 +461,104 @@ describe("the data directory is the APP's answer, and no answer means OFF", () =
|
|
|
460
461
|
expect(readEngagementEnv("vault", live, { dataDir: () => "/data/vault" }).enabled).toBe(false);
|
|
461
462
|
});
|
|
462
463
|
});
|
|
464
|
+
|
|
465
|
+
describe("feature actions — what they DID on a page, by name only (task 3470)", () => {
|
|
466
|
+
const ACTIONS = [{ id: "search", label: "run a search" }, { id: "play" }, { id: "download" }];
|
|
467
|
+
const mount = (resolveUser: (c: Context) => string | null, clock = { t: T0 }) => {
|
|
468
|
+
const s = store();
|
|
469
|
+
const app = new Hono();
|
|
470
|
+
app.route(
|
|
471
|
+
"/api/engagement",
|
|
472
|
+
createEngagementRecorder({ store: s, app: "music", places: PLACES, actions: ACTIONS, resolveUser, now: () => clock.t }),
|
|
473
|
+
);
|
|
474
|
+
const post = (body: unknown) =>
|
|
475
|
+
app.request("/api/engagement/action", {
|
|
476
|
+
method: "POST",
|
|
477
|
+
headers: { "content-type": "application/json" },
|
|
478
|
+
body: JSON.stringify(body),
|
|
479
|
+
});
|
|
480
|
+
return { s, post, clock };
|
|
481
|
+
};
|
|
482
|
+
|
|
483
|
+
test("a declared name resolves to itself, case-blind; anything else is `other`", () => {
|
|
484
|
+
expect(resolveAction("search", ACTIONS)).toBe("search");
|
|
485
|
+
expect(resolveAction(" Play ", ACTIONS)).toBe("play");
|
|
486
|
+
expect(resolveAction("search:my private query", ACTIONS)).toBe(OTHER_PLACE);
|
|
487
|
+
expect(resolveAction("", ACTIONS)).toBe(OTHER_PLACE);
|
|
488
|
+
expect(resolveAction("play", [])).toBe(OTHER_PLACE);
|
|
489
|
+
});
|
|
490
|
+
|
|
491
|
+
test("🔴 a value cannot become a row — the query, the track and the URL go nowhere", async () => {
|
|
492
|
+
const { s, post } = mount(() => "u1");
|
|
493
|
+
const res = await post({ place: "/#/note/my-divorce-reading-list", action: "search", query: "a secret", track: "x" });
|
|
494
|
+
expect(await res.json()).toMatchObject({ ok: true, place: "note", action: "search", bucketed: false });
|
|
495
|
+
expect(await (await post({ place: "files", action: "searched for a secret" })).json()).toMatchObject({
|
|
496
|
+
action: OTHER_PLACE,
|
|
497
|
+
bucketed: true,
|
|
498
|
+
});
|
|
499
|
+
const stored = JSON.stringify(s.handle.query("SELECT * FROM engagement_actions").all());
|
|
500
|
+
expect(stored).not.toContain("secret");
|
|
501
|
+
expect(stored).not.toContain("divorce");
|
|
502
|
+
const columns = (s.handle.query("PRAGMA table_info(engagement_actions)").all() as { name: string }[]).map((c) => c.name);
|
|
503
|
+
expect(columns).toEqual(["user_key", "place", "action", "uses", "first_ts", "last_ts"]);
|
|
504
|
+
});
|
|
505
|
+
|
|
506
|
+
test("no session → 401; a body userKey is ignored; a missing action is a 400", async () => {
|
|
507
|
+
const anon = mount(() => null);
|
|
508
|
+
expect((await anon.post({ place: "files", action: "play" })).status).toBe(401);
|
|
509
|
+
expect(anon.s.actions()).toEqual([]);
|
|
510
|
+
|
|
511
|
+
const signed = mount(() => "the-session-user");
|
|
512
|
+
await signed.post({ place: "files", action: "play", userKey: "somebody-else" });
|
|
513
|
+
expect(signed.s.actions().map((a) => a.userKey)).toEqual(["the-session-user"]);
|
|
514
|
+
expect((await signed.post({ place: "files" })).status).toBe(400);
|
|
515
|
+
expect((await signed.post({ place: 7, action: "play" })).status).toBe(400);
|
|
516
|
+
});
|
|
517
|
+
|
|
518
|
+
test("counts per account, keeps first and last, and never moves the view clock", async () => {
|
|
519
|
+
const { s, post, clock } = mount(() => "u1");
|
|
520
|
+
await post({ place: "files", action: "play" });
|
|
521
|
+
clock.t = T0 + 2 * DAY;
|
|
522
|
+
await post({ place: "files", action: "play" });
|
|
523
|
+
expect(s.actions()).toEqual([{ userKey: "u1", place: "files", action: "play", uses: 2, firstTs: T0, lastTs: T0 + 2 * DAY }]);
|
|
524
|
+
expect(s.handle.query("SELECT day, uses FROM engagement_action_days ORDER BY day").all()).toEqual([
|
|
525
|
+
{ day: "2026-08-10", uses: 1 },
|
|
526
|
+
{ day: "2026-08-12", uses: 1 },
|
|
527
|
+
]);
|
|
528
|
+
// An action is not a view: no session, no dwell, no user row.
|
|
529
|
+
expect(s.users()).toEqual([]);
|
|
530
|
+
});
|
|
531
|
+
|
|
532
|
+
test("the daily prune trims action DAYS and keeps the roll-up that says who used it", () => {
|
|
533
|
+
const s = store();
|
|
534
|
+
s.recordAction({ userKey: "u1", place: "files", action: "play", ts: T0 });
|
|
535
|
+
s.prune(T0 + 200 * DAY);
|
|
536
|
+
expect(s.handle.query("SELECT COUNT(*) AS n FROM engagement_action_days").get()).toEqual({ n: 0 });
|
|
537
|
+
expect(s.actions()).toHaveLength(1);
|
|
538
|
+
});
|
|
539
|
+
|
|
540
|
+
test("an app that declares no actions has no action door", async () => {
|
|
541
|
+
const app = new Hono();
|
|
542
|
+
app.route("/api/engagement", createEngagementRecorder({ store: store(), app: "family", places: PLACES, resolveUser: () => "u1" }));
|
|
543
|
+
const res = await app.request("/api/engagement/action", {
|
|
544
|
+
method: "POST",
|
|
545
|
+
headers: { "content-type": "application/json" },
|
|
546
|
+
body: JSON.stringify({ place: "files", action: "play" }),
|
|
547
|
+
});
|
|
548
|
+
expect(res.status).toBe(404);
|
|
549
|
+
});
|
|
550
|
+
|
|
551
|
+
test("the summary folds actions per place across accounts, most used first", () => {
|
|
552
|
+
const s = store();
|
|
553
|
+
s.recordAction({ userKey: "u1", place: "files", action: "play", ts: T0 });
|
|
554
|
+
s.recordAction({ userKey: "u1", place: "files", action: "play", ts: T0 + MINUTE });
|
|
555
|
+
s.recordAction({ userKey: "u2", place: "files", action: "play", ts: T0 + 2 * MINUTE });
|
|
556
|
+
s.recordAction({ userKey: "u2", place: "ask", action: "search", ts: T0 + 3 * MINUTE });
|
|
557
|
+
const snap = readAppEngagement(s, "music", T0 + DAY, PLACES, ACTIONS);
|
|
558
|
+
expect(snap.actions).toEqual([
|
|
559
|
+
{ place: "files", name: "play", count: 3, accounts: 2, lastTs: T0 + 2 * MINUTE },
|
|
560
|
+
{ place: "ask", name: "search", count: 1, accounts: 1, lastTs: T0 + 3 * MINUTE },
|
|
561
|
+
]);
|
|
562
|
+
expect(snap.knownActions).toEqual(["search", "play", "download"]);
|
|
563
|
+
});
|
|
564
|
+
});
|
|
@@ -54,8 +54,10 @@ export {
|
|
|
54
54
|
readAppEngagement,
|
|
55
55
|
} from "./api.js";
|
|
56
56
|
export { type EngagementEnv, type EngagementEnvOptions, readEngagementEnv } from "./env.js";
|
|
57
|
-
export {
|
|
57
|
+
export { actionsFromManifest } from "./manifestPlaces.js";
|
|
58
|
+
export { type EngagementPlace, engagementActionsFor, engagementPlacesFor } from "./places.js";
|
|
58
59
|
export {
|
|
60
|
+
type ActionRef,
|
|
59
61
|
classifyInterest,
|
|
60
62
|
dayKey,
|
|
61
63
|
daysSince,
|
|
@@ -82,6 +84,7 @@ export {
|
|
|
82
84
|
type EngagementUserPlace,
|
|
83
85
|
} from "./store.js";
|
|
84
86
|
export {
|
|
87
|
+
type ActionEngagement,
|
|
85
88
|
type AppEngagement,
|
|
86
89
|
type DailyEngagement,
|
|
87
90
|
type PlaceEngagement,
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
*
|
|
6
6
|
* Anything it cannot read is `[]`, never a throw: see `places.ts`, "Missing is EMPTY".
|
|
7
7
|
*/
|
|
8
|
-
import type { PlaceRef } from "./policy.js";
|
|
8
|
+
import type { ActionRef, PlaceRef } from "./policy.js";
|
|
9
9
|
|
|
10
10
|
export function placesFromManifest(doc: unknown): PlaceRef[] {
|
|
11
11
|
const routes = Array.isArray(doc) ? doc : ((doc as { routes?: unknown } | null)?.routes as unknown[] | undefined);
|
|
@@ -22,3 +22,23 @@ export function placesFromManifest(doc: unknown): PlaceRef[] {
|
|
|
22
22
|
places.sort((a, b) => a.id.localeCompare(b.id));
|
|
23
23
|
return places;
|
|
24
24
|
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* A parsed `routes.manifest.json` → the ACTION allowlist (task 3470): its top-level `actions`,
|
|
28
|
+
* each `{ id, label }` or a bare id. The same contract as the places — anything unreadable is
|
|
29
|
+
* `[]`, never a throw — and the same consequence: an app with no `actions` has no action door.
|
|
30
|
+
*/
|
|
31
|
+
export function actionsFromManifest(doc: unknown): ActionRef[] {
|
|
32
|
+
const raw = Array.isArray(doc) ? undefined : (doc as { actions?: unknown } | null)?.actions;
|
|
33
|
+
if (!Array.isArray(raw)) return [];
|
|
34
|
+
const seen = new Set<string>();
|
|
35
|
+
const actions: ActionRef[] = [];
|
|
36
|
+
for (const item of raw) {
|
|
37
|
+
const a = (typeof item === "string" ? { id: item } : item) as { id?: unknown; label?: unknown } | null;
|
|
38
|
+
if (!a || typeof a.id !== "string" || !a.id.trim() || seen.has(a.id)) continue;
|
|
39
|
+
seen.add(a.id);
|
|
40
|
+
actions.push(typeof a.label === "string" ? { id: a.id, label: a.label } : { id: a.id });
|
|
41
|
+
}
|
|
42
|
+
actions.sort((a, b) => a.id.localeCompare(b.id));
|
|
43
|
+
return actions;
|
|
44
|
+
}
|
|
@@ -24,7 +24,8 @@
|
|
|
24
24
|
*/
|
|
25
25
|
import { existsSync, readFileSync } from "node:fs";
|
|
26
26
|
import { join } from "node:path";
|
|
27
|
-
import { placesFromManifest } from "./manifestPlaces.js";
|
|
27
|
+
import { actionsFromManifest, placesFromManifest } from "./manifestPlaces.js";
|
|
28
|
+
import type { ActionRef } from "./policy.js";
|
|
28
29
|
|
|
29
30
|
/** Where the manifest sits, in a source tree and in a built artifact alike. */
|
|
30
31
|
const MANIFEST = "routes.manifest.json";
|
|
@@ -52,10 +53,19 @@ export interface EngagementPlace {
|
|
|
52
53
|
* manifest is copied into both.
|
|
53
54
|
*/
|
|
54
55
|
export function engagementPlacesFor(dir: string): EngagementPlace[] {
|
|
56
|
+
return readManifest(dir, placesFromManifest);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The declared ACTIONS in `<dir>/routes.manifest.json` — `[]` when it has none (task 3470). */
|
|
60
|
+
export function engagementActionsFor(dir: string): ActionRef[] {
|
|
61
|
+
return readManifest(dir, actionsFromManifest);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function readManifest<T>(dir: string, read: (doc: unknown) => T[]): T[] {
|
|
55
65
|
const path = join(dir, MANIFEST);
|
|
56
66
|
if (!existsSync(path)) return [];
|
|
57
67
|
try {
|
|
58
|
-
return
|
|
68
|
+
return read(JSON.parse(readFileSync(path, "utf8")) as unknown);
|
|
59
69
|
} catch {
|
|
60
70
|
return [];
|
|
61
71
|
}
|