cursedbelt-server 4.66.0 → 4.68.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.
@@ -0,0 +1,93 @@
1
+ /**
2
+ * `cursedbelt-server/client-issues/d1` — the server half of the page's issue record (forge task 4500).
3
+ *
4
+ * `cursedbelt/react/notifications`' `installIssueReporter` beacons every `raised` and `resolved`
5
+ * problem a page sees (a stuck video, a failing API, an uncaught error) to {@link CLIENT_ISSUES_PATH};
6
+ * this door writes one row per report into the app's own D1 `client_issues`, and autopilot's watch
7
+ * reads that table to file the work. Before it, a problem reached a fix only when the owner copied
8
+ * a report off his phone by hand.
9
+ *
10
+ * ```ts
11
+ * import { CLIENT_ISSUES_DDL, createD1ClientIssuesRecorder } from "cursedbelt-server/client-issues/d1";
12
+ * app.route("/api/client-issues", createD1ClientIssuesRecorder({ db: (c) => c.env.DB, resolveUser }));
13
+ * // and CLIENT_ISSUES_DDL in the app's schema
14
+ * ```
15
+ *
16
+ * 🔴 The door trusts nothing it is sent: every string is capped, the app's own query-key redaction
17
+ * ({@link REDACTED_QUERY_KEY}, byte-identical to `cursedbelt`'s — the spec compares them) runs again
18
+ * here, and the account is the session's, never the body's. It may be mounted outside the session
19
+ * gate (a page that cannot sign in is exactly the page with a problem), so two bounds hold whoever
20
+ * calls it: at most {@link ClientIssuesOptions.maxRowsPerHour} rows an hour per app, and rows older
21
+ * than {@link ClientIssuesOptions.retentionMs} are purged on every write.
22
+ *
23
+ * 🔴 Worker-safe: nothing reachable from here at runtime imports `bun:*`.
24
+ */
25
+ import type { Context } from "hono";
26
+ import { Hono } from "hono";
27
+ import type { D1LikeDatabase } from "../d1/types.js";
28
+ export declare const CLIENT_ISSUES_PATH = "/api/client-issues";
29
+ /** The table and its index, as one-line DDL for the app's schema. */
30
+ export declare const CLIENT_ISSUES_DDL: readonly string[];
31
+ /** 🔴 Must equal `cursedbelt/react/notifications`' `REDACTED_QUERY_KEY` — `d1.spec.ts` compares them. */
32
+ export declare const REDACTED_QUERY_KEY: RegExp;
33
+ /** Every `key=value` whose key is a {@link REDACTED_QUERY_KEY}, its value replaced by `…`. */
34
+ export declare function redactQueryValues(text: string): string;
35
+ /**
36
+ * The words of a title with what varies between occurrences taken out — numbers, ids, hosts,
37
+ * quoted names — so "Video 42 is stuck" and "Video 97 is stuck" are one group for autopilot.
38
+ */
39
+ export declare function issueStem(title: string): string;
40
+ export interface ClientIssueRow {
41
+ at: number;
42
+ change: "raised" | "resolved";
43
+ issue_id: string;
44
+ area: string;
45
+ stem: string;
46
+ tone: string;
47
+ outlook: string;
48
+ title: string;
49
+ occurrences: number;
50
+ started_at: number;
51
+ ended_at: number | null;
52
+ resolution: string;
53
+ page: string;
54
+ build: string;
55
+ user_agent: string;
56
+ user_key: string;
57
+ facts: string;
58
+ report: string;
59
+ }
60
+ /** One posted report as the row it becomes, or why it is refused. Pure, so the door is tested without a server. */
61
+ export declare function clientIssueDoor(body: unknown, context: {
62
+ now: number;
63
+ userAgent?: string;
64
+ userKey?: string | null;
65
+ }): {
66
+ row: ClientIssueRow;
67
+ } | {
68
+ error: string;
69
+ };
70
+ export interface ClientIssuesOptions {
71
+ /** The app's D1, or how to find it on the request. */
72
+ db: D1LikeDatabase | ((c: Context) => D1LikeDatabase);
73
+ /** The session's account, when there is one. Never read from the body. */
74
+ resolveUser?: (c: Context) => string | null;
75
+ /** Rows older than this are deleted on each write. Default 14 days. */
76
+ retentionMs?: number;
77
+ /** Reports past this many in the last hour are refused (429). Default 600. */
78
+ maxRowsPerHour?: number;
79
+ now?: () => number;
80
+ }
81
+ /** Write one row, purge the expired ones, refuse past the hourly bound. `"capped"` when refused. */
82
+ export declare function recordClientIssueD1(db: D1LikeDatabase, row: ClientIssueRow, bounds: {
83
+ retentionMs: number;
84
+ maxRowsPerHour: number;
85
+ }): Promise<"recorded" | "capped">;
86
+ /**
87
+ * The one handler: take one posted report, answer 204 (400 malformed, 429 past the hourly bound).
88
+ * For an app that declares its routes as literals (`app.post("/api/client-issues", handler)`, so a
89
+ * route census can read them); {@link createD1ClientIssuesRecorder} is the same handler as a sub-app.
90
+ */
91
+ export declare function clientIssuesHandler(options: ClientIssuesOptions): (c: Context) => Promise<Response>;
92
+ /** The Hono app to mount at {@link CLIENT_ISSUES_PATH}: `POST /` takes one report, answers 204. */
93
+ export declare function createD1ClientIssuesRecorder(options: ClientIssuesOptions): Hono;
@@ -0,0 +1,149 @@
1
+ import { Hono } from "hono";
2
+ export const CLIENT_ISSUES_PATH = "/api/client-issues";
3
+ /** The table and its index, as one-line DDL for the app's schema. */
4
+ export const CLIENT_ISSUES_DDL = [
5
+ "CREATE TABLE IF NOT EXISTS client_issues ( id INTEGER PRIMARY KEY AUTOINCREMENT, at INTEGER NOT NULL, change TEXT NOT NULL, issue_id TEXT NOT NULL, area TEXT NOT NULL, stem TEXT NOT NULL, tone TEXT NOT NULL, outlook TEXT NOT NULL, title TEXT NOT NULL, occurrences INTEGER NOT NULL DEFAULT 1, started_at INTEGER NOT NULL, ended_at INTEGER, resolution TEXT NOT NULL DEFAULT '', page TEXT NOT NULL DEFAULT '', build TEXT NOT NULL DEFAULT '', user_agent TEXT NOT NULL DEFAULT '', user_key TEXT NOT NULL DEFAULT '', facts TEXT NOT NULL DEFAULT '[]', report TEXT NOT NULL DEFAULT '' )",
6
+ "CREATE INDEX IF NOT EXISTS idx_client_issues_at ON client_issues (at)",
7
+ ];
8
+ /** 🔴 Must equal `cursedbelt/react/notifications`' `REDACTED_QUERY_KEY` — `d1.spec.ts` compares them. */
9
+ export const REDACTED_QUERY_KEY = /token|sig|signature|key|secret|password|code|exp/i;
10
+ /** Every `key=value` whose key is a {@link REDACTED_QUERY_KEY}, its value replaced by `…`. */
11
+ export function redactQueryValues(text) {
12
+ return text.replace(/([?&;]([^=&#\s]+)=)([^&#;\s]*)/g, (whole, head, key) => REDACTED_QUERY_KEY.test(key) ? `${head}…` : whole);
13
+ }
14
+ /**
15
+ * The words of a title with what varies between occurrences taken out — numbers, ids, hosts,
16
+ * quoted names — so "Video 42 is stuck" and "Video 97 is stuck" are one group for autopilot.
17
+ */
18
+ export function issueStem(title) {
19
+ return title
20
+ .toLowerCase()
21
+ .replace(/https?:\/\/\S+/g, "<url>")
22
+ .replace(/["“'‘][^"”'’]*["”'’]/g, "<name>")
23
+ .replace(/\b[0-9a-f]{8,}\b/g, "#")
24
+ .replace(/\d+(?:[.,:]\d+)*/g, "#")
25
+ .replace(/\s+/g, " ")
26
+ .trim()
27
+ .slice(0, 160);
28
+ }
29
+ const cap = (value, max) => (typeof value === "string" ? redactQueryValues(value).slice(0, max) : "");
30
+ const whole = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : null;
31
+ /** One posted report as the row it becomes, or why it is refused. Pure, so the door is tested without a server. */
32
+ export function clientIssueDoor(body, context) {
33
+ if (!body || typeof body !== "object")
34
+ return { error: "expected a json object" };
35
+ const b = body;
36
+ if (b.v !== 1)
37
+ return { error: "unknown report version" };
38
+ if (b.change !== "raised" && b.change !== "resolved")
39
+ return { error: "change must be raised or resolved" };
40
+ const issueId = cap(b.id, 160);
41
+ const title = cap(b.title, 240);
42
+ const area = cap(b.area, 40);
43
+ if (!issueId || !title || !area)
44
+ return { error: "id, area and title are required" };
45
+ const startedAt = whole(b.startedAt) ?? context.now;
46
+ const facts = Array.isArray(b.facts)
47
+ ? b.facts
48
+ .slice(0, 20)
49
+ .filter((f) => !!f && typeof f === "object")
50
+ .map((f) => ({ label: cap(f.label, 80), value: cap(f.value, 400) }))
51
+ : [];
52
+ return {
53
+ row: {
54
+ at: context.now,
55
+ change: b.change,
56
+ issue_id: issueId,
57
+ area,
58
+ stem: issueStem(title),
59
+ tone: cap(b.tone, 16) || "warning",
60
+ outlook: cap(b.outlook, 300),
61
+ title,
62
+ occurrences: Math.max(1, whole(b.occurrences) ?? 1),
63
+ started_at: startedAt,
64
+ ended_at: whole(b.endedAt),
65
+ resolution: cap(b.resolution, 300),
66
+ page: cap(b.page, 400),
67
+ build: cap(b.build, 80),
68
+ user_agent: cap(context.userAgent, 300),
69
+ user_key: context.userKey ?? "",
70
+ facts: JSON.stringify(facts),
71
+ report: cap(b.report, 12_000),
72
+ },
73
+ };
74
+ }
75
+ const COLUMNS = [
76
+ "at",
77
+ "change",
78
+ "issue_id",
79
+ "area",
80
+ "stem",
81
+ "tone",
82
+ "outlook",
83
+ "title",
84
+ "occurrences",
85
+ "started_at",
86
+ "ended_at",
87
+ "resolution",
88
+ "page",
89
+ "build",
90
+ "user_agent",
91
+ "user_key",
92
+ "facts",
93
+ "report",
94
+ ];
95
+ /** Write one row, purge the expired ones, refuse past the hourly bound. `"capped"` when refused. */
96
+ export async function recordClientIssueD1(db, row, bounds) {
97
+ const recent = await db
98
+ .prepare("SELECT COUNT(*) AS n FROM client_issues WHERE at > ?")
99
+ .bind(row.at - 3_600_000)
100
+ .first();
101
+ if ((recent?.n ?? 0) >= bounds.maxRowsPerHour)
102
+ return "capped";
103
+ await db.batch([
104
+ db
105
+ .prepare(`INSERT INTO client_issues (${COLUMNS.join(", ")}) VALUES (${COLUMNS.map(() => "?").join(", ")})`)
106
+ .bind(...COLUMNS.map((k) => row[k])),
107
+ db.prepare("DELETE FROM client_issues WHERE at < ?").bind(row.at - bounds.retentionMs),
108
+ ]);
109
+ return "recorded";
110
+ }
111
+ /**
112
+ * The one handler: take one posted report, answer 204 (400 malformed, 429 past the hourly bound).
113
+ * For an app that declares its routes as literals (`app.post("/api/client-issues", handler)`, so a
114
+ * route census can read them); {@link createD1ClientIssuesRecorder} is the same handler as a sub-app.
115
+ */
116
+ export function clientIssuesHandler(options) {
117
+ const now = options.now ?? (() => Date.now());
118
+ const bounds = {
119
+ retentionMs: options.retentionMs ?? 14 * 24 * 3_600_000,
120
+ maxRowsPerHour: options.maxRowsPerHour ?? 600,
121
+ };
122
+ return async (c) => {
123
+ let body;
124
+ try {
125
+ body = JSON.parse(await c.req.text());
126
+ }
127
+ catch {
128
+ return c.json({ error: "expected a json body" }, 400);
129
+ }
130
+ const door = clientIssueDoor(body, {
131
+ now: now(),
132
+ userAgent: c.req.header("user-agent") ?? "",
133
+ userKey: options.resolveUser?.(c) ?? null,
134
+ });
135
+ if ("error" in door)
136
+ return c.json({ error: door.error }, 400);
137
+ const db = typeof options.db === "function" ? options.db(c) : options.db;
138
+ const outcome = await recordClientIssueD1(db, door.row, bounds);
139
+ if (outcome === "capped")
140
+ return c.json({ error: "too many reports this hour" }, 429);
141
+ return c.body(null, 204);
142
+ };
143
+ }
144
+ /** The Hono app to mount at {@link CLIENT_ISSUES_PATH}: `POST /` takes one report, answers 204. */
145
+ export function createD1ClientIssuesRecorder(options) {
146
+ const app = new Hono();
147
+ app.post("/", clientIssuesHandler(options));
148
+ return app;
149
+ }
@@ -24,6 +24,11 @@
24
24
  * local driver, so `sameShape.spec.ts` was green on a bug BOTH sides shared — the one
25
25
  * failure mode a two-implementation test cannot see. A real port of
26
26
  * `apps/patterns/src/server/tokens.ts` found it on its first atomic write.
27
+ * 7. **`changes` includes the rows a TRIGGER wrote — on `.all()` of a writing statement too.**
28
+ * Measured 2026-11-10 on family-stage's D1: a 3-row INSERT whose AFTER INSERT trigger writes
29
+ * two log rows each reports `changes: 9`; an `INSERT … RETURNING` of 2, read with `.all()`,
30
+ * reports 6. bun's `.run().changes` is a `total_changes()` difference and agrees (SQLite's
31
+ * own `changes()` would say 3); this file's `.all()` said 0 until it went through `runSync`.
27
32
  *
28
33
  * SQL semantics are real: it runs against an actual in-memory SQLite. Only the edges are
29
34
  * emulated, which are exactly the edges under test.
@@ -24,6 +24,11 @@
24
24
  * local driver, so `sameShape.spec.ts` was green on a bug BOTH sides shared — the one
25
25
  * failure mode a two-implementation test cannot see. A real port of
26
26
  * `apps/patterns/src/server/tokens.ts` found it on its first atomic write.
27
+ * 7. **`changes` includes the rows a TRIGGER wrote — on `.all()` of a writing statement too.**
28
+ * Measured 2026-11-10 on family-stage's D1: a 3-row INSERT whose AFTER INSERT trigger writes
29
+ * two log rows each reports `changes: 9`; an `INSERT … RETURNING` of 2, read with `.all()`,
30
+ * reports 6. bun's `.run().changes` is a `total_changes()` difference and agrees (SQLite's
31
+ * own `changes()` would say 3); this file's `.all()` said 0 until it went through `runSync`.
27
32
  *
28
33
  * SQL semantics are real: it runs against an actual in-memory SQLite. Only the edges are
29
34
  * emulated, which are exactly the edges under test.
@@ -114,11 +119,9 @@ class FakeD1Statement {
114
119
  throw new Error(`D1_ERROR: no such column: ${column}`);
115
120
  return wire[column];
116
121
  }
122
+ /** `runSync`'s counters too: D1's `.all()` of an `INSERT … RETURNING` reports what it wrote (see 7. above). */
117
123
  async all() {
118
- assertRunnableOnD1(this.sql);
119
- const started = performance.now();
120
- const rows = this.db.query(this.sql).all(...this.params);
121
- return { results: rows.map(toWireRow), success: true, meta: this.meta(started) };
124
+ return this.runSync();
122
125
  }
123
126
  async run() {
124
127
  assertRunnableOnD1(this.sql);
@@ -151,8 +154,8 @@ class FakeD1Statement {
151
154
  const started = performance.now();
152
155
  const stmt = this.db.query(this.sql);
153
156
  const bound = this.params;
154
- // No result columns → cannot return rows, and `.run()` is the only call that reports
155
- // `changes`. This is the ordinary batch member: an INSERT, UPDATE or DELETE.
157
+ // No result columns → cannot return rows: the ordinary batch member, an INSERT, UPDATE or
158
+ // DELETE. bun's `.run().changes` is a `total_changes()` difference, trigger rows in (see 7.).
156
159
  if (stmt.columnNames.length === 0) {
157
160
  const res = stmt.run(...bound);
158
161
  return { results: [], success: true, meta: this.meta(started, res.changes, Number(res.lastInsertRowid)) };
@@ -18,6 +18,7 @@ export { createPendingWrites, type InvocationD1, type PendingWrites, perInvocati
18
18
  export { createHttpD1, D1HttpError, type HttpD1Options } from './http.js';
19
19
  export { assertBatchSize, assertWithinLimits, chunkForBind, inArray, LIMITS } from './limits.js';
20
20
  export { createLocalD1, refuseInteractiveTransaction } from './local.js';
21
+ export { LOW_CARDINALITY_COLUMNS, type PlanCheckOptions, type PlanRow, perRowReads, perRowSteps, planOf, planOffenders, preparedBy, wholeTablePages, } from './plans.js';
21
22
  export { createRemoteD1, type D1BindingLike, type D1BindingMeta, type D1BindingResult, type D1BindingStatement, } from './remote.js';
22
23
  export { classifySchedule, cronFieldCount, jobsForCron, type PortableJob, type PortableJobContext, type ScheduleVerdict, toCronTriggers, toFiveField, type TriggerShape, type WorkersPrimitive, } from './scheduling.js';
23
24
  export { D1BindError, type D1LikeBindable, type D1LikeDatabase, type D1LikeMeta, type D1LikeResult, type D1LikeRow, type D1LikeStatement, type D1LikeValue, D1LimitError, D1UnsupportedError, } from './types.js';
@@ -37,6 +37,7 @@ export { createPendingWrites, perInvocation } from './invocation.js';
37
37
  export { createHttpD1, D1HttpError } from './http.js';
38
38
  export { assertBatchSize, assertWithinLimits, chunkForBind, inArray, LIMITS } from './limits.js';
39
39
  export { createLocalD1, refuseInteractiveTransaction } from './local.js';
40
+ export { LOW_CARDINALITY_COLUMNS, perRowReads, perRowSteps, planOf, planOffenders, preparedBy, wholeTablePages, } from './plans.js';
40
41
  export { createRemoteD1, } from './remote.js';
41
42
  export { classifySchedule, cronFieldCount, jobsForCron, toCronTriggers, toFiveField, } from './scheduling.js';
42
43
  export { D1BindError, D1LimitError, D1UnsupportedError, } from './types.js';
@@ -0,0 +1,70 @@
1
+ /**
2
+ * `cursedbelt-server/d1` plan checks — an app's route tests hold its reads to the archive's size, not
3
+ * the fixture's.
4
+ *
5
+ * Every statement a route prepares is put through `EXPLAIN QUERY PLAN`. A subquery that runs once
6
+ * per outer row (`CORRELATED`, or an `EXISTS` semi-join) must find its rows by the row it is asked
7
+ * about: a `SCAN` there, or a search keyed by a low-cardinality column alone (a job's state, "not
8
+ * deleted", the owner), reads the whole table again for every row. That is what reset photos' D1 on
9
+ * 2026-11-05 (forge task 4467): a correlated search of `jobs_queue` by state, ~26,000 rows, for each of
10
+ * 963 photographs. A page is held too: one that reads its table whole and sorts it to hand back its
11
+ * LIMIT pays for the archive on every page (photos' `albums/assets`, 331,190 rows for one page).
12
+ *
13
+ * ```ts
14
+ * const statements = await preparedBy(db, () => app.request('/api/heavy'));
15
+ * expect(await planOffenders(db, statements)).toEqual([]);
16
+ * ```
17
+ *
18
+ * Lifted from photos (`src/server/knowledge/plans.test.ts`, forge task 4595), which holds the cases.
19
+ */
20
+ import type { D1LikeDatabase } from './types.js';
21
+ /** One row of `EXPLAIN QUERY PLAN`. */
22
+ export interface PlanRow {
23
+ id: number;
24
+ parent: number;
25
+ detail: string;
26
+ }
27
+ /**
28
+ * The columns a search keyed by alone still reads the table whole: one value matches most rows.
29
+ * An app widens it with its own (`[...LOW_CARDINALITY_COLUMNS, 'kind']`).
30
+ */
31
+ export declare const LOW_CARDINALITY_COLUMNS: readonly string[];
32
+ export interface PlanCheckOptions {
33
+ /** Replaces {@link LOW_CARDINALITY_COLUMNS}. */
34
+ lowCardinality?: readonly string[];
35
+ }
36
+ /** The steps of `plan` that run once per outer row: inside a correlated subquery, or an `EXISTS` semi-join. */
37
+ export declare function perRowSteps(plan: readonly PlanRow[]): PlanRow[];
38
+ /**
39
+ * The steps of `plan` that re-read a table for every outer row — or, with `perEvent`, every step
40
+ * that reads a table whole (a statement that itself runs once per event, so ANY step of it is per row).
41
+ */
42
+ export declare function perRowReads(plan: readonly PlanRow[], opts?: PlanCheckOptions & {
43
+ perEvent?: boolean;
44
+ }): string[];
45
+ /**
46
+ * The outer steps of a paged read that reads its table whole and then sorts every row it kept (`USE
47
+ * TEMP B-TREE FOR ORDER BY`) to hand back its LIMIT. A read keyed by its cursor (`(id>?)`), or walking
48
+ * an index in its own order (only `LAST TERM OF ORDER BY` sorted), stops at its page.
49
+ */
50
+ export declare function wholeTablePages(plan: readonly PlanRow[], opts?: PlanCheckOptions): string[];
51
+ /**
52
+ * Every distinct statement `run` prepares on `db`, in first-prepared order. `db.prepare` is restored
53
+ * after. Any handle with a `prepare(sql)` will do — an app's own async wrapper as well as this seam.
54
+ */
55
+ export declare function preparedBy(db: {
56
+ prepare(sql: string): unknown;
57
+ }, run: () => Promise<unknown>): Promise<string[]>;
58
+ /** `EXPLAIN QUERY PLAN` of `sql` on `db` — the app's own schema, so its indexes decide. */
59
+ export declare function planOf(db: D1LikeDatabase, sql: string): Promise<PlanRow[]>;
60
+ /**
61
+ * Every statement in `statements` that re-reads a table per row, or pages out of a sorted whole table
62
+ * — one line each, naming the step and the statement. `[]` is the pass.
63
+ *
64
+ * Reads are held to {@link perRowReads} and {@link wholeTablePages}. With `writes`, every INSERT,
65
+ * UPDATE, DELETE and REPLACE is held as `perEvent`: a write runs once per request or event, so ANY step
66
+ * of it that reads its table whole is the archive per call (desk's `UPDATE` that read 1.5 M rows).
67
+ */
68
+ export declare function planOffenders(db: D1LikeDatabase, statements: readonly string[], opts?: PlanCheckOptions & {
69
+ writes?: boolean;
70
+ }): Promise<string[]>;
@@ -0,0 +1,127 @@
1
+ /**
2
+ * `cursedbelt-server/d1` plan checks — an app's route tests hold its reads to the archive's size, not
3
+ * the fixture's.
4
+ *
5
+ * Every statement a route prepares is put through `EXPLAIN QUERY PLAN`. A subquery that runs once
6
+ * per outer row (`CORRELATED`, or an `EXISTS` semi-join) must find its rows by the row it is asked
7
+ * about: a `SCAN` there, or a search keyed by a low-cardinality column alone (a job's state, "not
8
+ * deleted", the owner), reads the whole table again for every row. That is what reset photos' D1 on
9
+ * 2026-11-05 (forge task 4467): a correlated search of `jobs_queue` by state, ~26,000 rows, for each of
10
+ * 963 photographs. A page is held too: one that reads its table whole and sorts it to hand back its
11
+ * LIMIT pays for the archive on every page (photos' `albums/assets`, 331,190 rows for one page).
12
+ *
13
+ * ```ts
14
+ * const statements = await preparedBy(db, () => app.request('/api/heavy'));
15
+ * expect(await planOffenders(db, statements)).toEqual([]);
16
+ * ```
17
+ *
18
+ * Lifted from photos (`src/server/knowledge/plans.test.ts`, forge task 4595), which holds the cases.
19
+ */
20
+ /**
21
+ * The columns a search keyed by alone still reads the table whole: one value matches most rows.
22
+ * An app widens it with its own (`[...LOW_CARDINALITY_COLUMNS, 'kind']`).
23
+ */
24
+ export const LOW_CARDINALITY_COLUMNS = ['state', 'status', 'deleted_at', 'owner_id'];
25
+ const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
26
+ const lowCardinalityRule = (columns) => columns.length === 0 ? null : new RegExp(` USING (?:COVERING )?INDEX \\S+ \\((?:${columns.map(escapeRegExp).join('|')})=\\?\\)`);
27
+ /** A step that reads its table whole: a scan with no index, or a search by a low-cardinality column alone. */
28
+ function readsWhole(detail, derived, low) {
29
+ const bareScan = /^SCAN (?!CONSTANT ROW)/.test(detail) &&
30
+ !detail.includes(' VIRTUAL TABLE ') &&
31
+ !derived.has(detail.split(' ')[1] ?? '') &&
32
+ !/ USING (?:COVERING )?INDEX /.test(detail);
33
+ return bareScan || (low?.test(detail) ?? false);
34
+ }
35
+ /** What a subquery made (`MATERIALIZE hit`, `CO-ROUTINE (subquery-1)`): its rows were counted where they were made. */
36
+ const derivedOf = (plan) => new Set(plan.flatMap((r) => /^(?:MATERIALIZE|CO-ROUTINE) (\S+)/.exec(r.detail)?.[1] ?? []));
37
+ /** The steps of `plan` that run once per outer row: inside a correlated subquery, or an `EXISTS` semi-join. */
38
+ export function perRowSteps(plan) {
39
+ const byId = new Map(plan.map((r) => [r.id, r]));
40
+ // The nearest subquery around a step decides: an uncorrelated one inside a correlated one is computed once.
41
+ const correlated = (row) => {
42
+ // Newer SQLite runs `EXISTS (…)` as a semi-join, a loop inside the outer one: `SEARCH s EXISTS USING …`.
43
+ if (/^SEARCH \S+ EXISTS /.test(row.detail))
44
+ return true;
45
+ for (let p = byId.get(row.parent); p; p = byId.get(p.parent)) {
46
+ if (/SUBQUERY|^CORRELATED/.test(p.detail))
47
+ return p.detail.startsWith('CORRELATED');
48
+ }
49
+ return false;
50
+ };
51
+ return plan.filter(correlated);
52
+ }
53
+ /**
54
+ * The steps of `plan` that re-read a table for every outer row — or, with `perEvent`, every step
55
+ * that reads a table whole (a statement that itself runs once per event, so ANY step of it is per row).
56
+ */
57
+ export function perRowReads(plan, opts = {}) {
58
+ const derived = derivedOf(plan);
59
+ const low = lowCardinalityRule(opts.lowCardinality ?? LOW_CARDINALITY_COLUMNS);
60
+ return (opts.perEvent ? plan : perRowSteps(plan)).filter((r) => readsWhole(r.detail, derived, low)).map((r) => r.detail);
61
+ }
62
+ /**
63
+ * The outer steps of a paged read that reads its table whole and then sorts every row it kept (`USE
64
+ * TEMP B-TREE FOR ORDER BY`) to hand back its LIMIT. A read keyed by its cursor (`(id>?)`), or walking
65
+ * an index in its own order (only `LAST TERM OF ORDER BY` sorted), stops at its page.
66
+ */
67
+ export function wholeTablePages(plan, opts = {}) {
68
+ const outer = plan.filter((r) => r.parent === 0);
69
+ if (!outer.some((r) => r.detail === 'USE TEMP B-TREE FOR ORDER BY'))
70
+ return [];
71
+ const derived = derivedOf(plan);
72
+ const low = lowCardinalityRule(opts.lowCardinality ?? LOW_CARDINALITY_COLUMNS);
73
+ return outer.filter((r) => readsWhole(r.detail, derived, low)).map((r) => r.detail);
74
+ }
75
+ /**
76
+ * Every distinct statement `run` prepares on `db`, in first-prepared order. `db.prepare` is restored
77
+ * after. Any handle with a `prepare(sql)` will do — an app's own async wrapper as well as this seam.
78
+ */
79
+ export async function preparedBy(db, run) {
80
+ const seen = new Set();
81
+ // Put back exactly what was there: an own property as it was, a prototype method by removing the shadow.
82
+ const own = Object.hasOwn(db, 'prepare');
83
+ const original = db.prepare;
84
+ const real = original.bind(db);
85
+ db.prepare = (sql) => {
86
+ seen.add(sql);
87
+ return real(sql);
88
+ };
89
+ try {
90
+ await run();
91
+ }
92
+ finally {
93
+ if (own)
94
+ db.prepare = original;
95
+ else
96
+ delete db.prepare;
97
+ }
98
+ return [...seen];
99
+ }
100
+ /** `EXPLAIN QUERY PLAN` of `sql` on `db` — the app's own schema, so its indexes decide. */
101
+ export async function planOf(db, sql) {
102
+ return (await db.prepare(`EXPLAIN QUERY PLAN ${sql}`).all()).results;
103
+ }
104
+ /**
105
+ * Every statement in `statements` that re-reads a table per row, or pages out of a sorted whole table
106
+ * — one line each, naming the step and the statement. `[]` is the pass.
107
+ *
108
+ * Reads are held to {@link perRowReads} and {@link wholeTablePages}. With `writes`, every INSERT,
109
+ * UPDATE, DELETE and REPLACE is held as `perEvent`: a write runs once per request or event, so ANY step
110
+ * of it that reads its table whole is the archive per call (desk's `UPDATE` that read 1.5 M rows).
111
+ */
112
+ export async function planOffenders(db, statements, opts = {}) {
113
+ const offenders = [];
114
+ for (const sql of statements) {
115
+ const write = /^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i.test(sql);
116
+ if (write ? !opts.writes : !/^\s*(?:SELECT|WITH)\b/i.test(sql))
117
+ continue;
118
+ const plan = await planOf(db, sql);
119
+ const where = sql.replace(/\s+/g, ' ').trim().slice(0, 160);
120
+ for (const step of perRowReads(plan, { ...opts, perEvent: write }))
121
+ offenders.push(`${step} ← ${where}`);
122
+ if (!write && /\bLIMIT\b/i.test(sql))
123
+ for (const step of wholeTablePages(plan, opts))
124
+ offenders.push(`page: ${step} ← ${where}`);
125
+ }
126
+ return offenders;
127
+ }
@@ -1,6 +1,13 @@
1
1
  /** The text embedder for both sides: a document and a query. Measured by photos, 2026-11-05. */
2
2
  export declare const EMBED_MODEL = "@cf/baai/bge-m3";
3
3
  export declare const EMBED_DIMS = 1024;
4
+ /**
5
+ * The image engines' widths — photos' Mac writes them, family's door refuses any other length, so
6
+ * they live once, here (forge task 4828). ArcFace: 512 float32, little-endian.
7
+ */
8
+ export declare const FACE_DIMS = 512;
9
+ /** The image region embedder: 1536 floats, sent as float16. */
10
+ export declare const REGION_DIMS = 1536;
4
11
  /** The cross-encoder that reads the query beside each candidate's document. */
5
12
  export declare const RERANK_MODEL = "@cf/baai/bge-reranker-base";
6
13
  /**
@@ -22,6 +22,13 @@
22
22
  /** The text embedder for both sides: a document and a query. Measured by photos, 2026-11-05. */
23
23
  export const EMBED_MODEL = '@cf/baai/bge-m3';
24
24
  export const EMBED_DIMS = 1024;
25
+ /**
26
+ * The image engines' widths — photos' Mac writes them, family's door refuses any other length, so
27
+ * they live once, here (forge task 4828). ArcFace: 512 float32, little-endian.
28
+ */
29
+ export const FACE_DIMS = 512;
30
+ /** The image region embedder: 1536 floats, sent as float16. */
31
+ export const REGION_DIMS = 1536;
25
32
  /** The cross-encoder that reads the query beside each candidate's document. */
26
33
  export const RERANK_MODEL = '@cf/baai/bge-reranker-base';
27
34
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursedbelt-server",
3
- "version": "4.66.0",
3
+ "version": "4.68.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.",
@@ -120,6 +120,12 @@
120
120
  "source": "./src/server/middleware/bodyLimit.ts",
121
121
  "import": "./dist/server/middleware/bodyLimit.js"
122
122
  },
123
+ "./client-issues/d1": {
124
+ "types": "./dist/server/clientIssues/d1.d.ts",
125
+ "bun": "./src/server/clientIssues/d1.ts",
126
+ "source": "./src/server/clientIssues/d1.ts",
127
+ "import": "./dist/server/clientIssues/d1.js"
128
+ },
123
129
  "./d1": {
124
130
  "types": "./dist/server/d1/index.d.ts",
125
131
  "bun": "./src/server/d1/index.ts",
@@ -435,7 +441,7 @@
435
441
  "@node-rs/argon2": "^2.0.2",
436
442
  "@types/bun": "^1.3.14",
437
443
  "@types/node": "^24",
438
- "cursedbelt": "^5.135.1",
444
+ "cursedbelt": "^5.138.0",
439
445
  "hono": "4.12.28",
440
446
  "kysely": "^0.28.17",
441
447
  "kysely-bun-sqlite": "^0.4.0",