cursedbelt-server 4.78.0 → 4.79.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/server/analytics/injectedScripts.d.ts +1 -1
  2. package/dist/server/analytics/injectedScripts.js +1 -1
  3. package/dist/server/analytics/webAnalytics.d.ts +2 -2
  4. package/dist/server/analytics/webAnalytics.js +2 -2
  5. package/dist/server/clientIssues/d1.d.ts +1 -1
  6. package/dist/server/engagement/visits.d.ts +1 -1
  7. package/dist/server/incidents/channels.d.ts +2 -2
  8. package/dist/server/incidents/channels.js +2 -2
  9. package/dist/server/incidents/index.d.ts +2 -2
  10. package/dist/server/incidents/index.js +2 -2
  11. package/dist/server/incidents/notifier.d.ts +6 -6
  12. package/dist/server/incidents/notifier.js +6 -6
  13. package/dist/server/incidents/reporter.d.ts +1 -1
  14. package/dist/server/incidents/types.d.ts +5 -5
  15. package/dist/server/incidents/types.js +2 -2
  16. package/dist/server/maps-budget/mapsBudget.d.ts +37 -0
  17. package/dist/server/maps-budget/mapsBudget.js +52 -0
  18. package/dist/server/maps-static/staticMap.d.ts +30 -3
  19. package/dist/server/maps-static/staticMap.js +35 -3
  20. package/dist/server/master-lock/accountsPage.js +2 -2
  21. package/dist/server/master-lock/attempts.js +1 -1
  22. package/dist/server/master-lock/masterLock.d.ts +2 -2
  23. package/dist/server/master-lock/masterLock.js +3 -3
  24. package/dist/server/master-lock/principals.js +1 -1
  25. package/dist/server/presence/index.d.ts +3 -2
  26. package/dist/server/presence/index.js +35 -2
  27. package/dist/server/requestScope.d.ts +8 -0
  28. package/dist/server/requestScope.js +33 -0
  29. package/dist/server/resume/store.d.ts +1 -1
  30. package/dist/server/storage/binaryStoreFake.d.ts +1 -1
  31. package/dist/server/sync/status.d.ts +1 -1
  32. package/dist/server/youtube/ytdlp.d.ts +1 -1
  33. package/package.json +3 -3
  34. package/src/cursedopsRange.spec.ts +5 -3
  35. package/src/noTimerDialsAPeer.spec.ts +3 -3
  36. package/src/server/analytics/injectedScripts.spec.ts +1 -1
  37. package/src/server/analytics/injectedScripts.ts +1 -1
  38. package/src/server/analytics/webAnalytics.ts +2 -2
  39. package/src/server/clientIssues/d1.ts +1 -1
  40. package/src/server/engagement/engagement.spec.ts +1 -1
  41. package/src/server/engagement/visits.ts +1 -1
  42. package/src/server/incidents/channels.ts +2 -2
  43. package/src/server/incidents/index.ts +2 -2
  44. package/src/server/incidents/notifier.ts +9 -9
  45. package/src/server/incidents/reporter.ts +1 -1
  46. package/src/server/incidents/types.ts +5 -5
  47. package/src/server/maps-budget/mapsBudget.ts +73 -0
  48. package/src/server/maps-static/renderStaticMap.spec.ts +79 -0
  49. package/src/server/maps-static/staticMap.ts +47 -3
  50. package/src/server/master-lock/accounts.spec.ts +4 -4
  51. package/src/server/master-lock/accountsPage.spec.ts +1 -1
  52. package/src/server/master-lock/accountsPage.ts +2 -2
  53. package/src/server/master-lock/attempts.ts +1 -1
  54. package/src/server/master-lock/beaconNeverReachesTheWall.spec.ts +3 -3
  55. package/src/server/master-lock/guard.spec.ts +1 -1
  56. package/src/server/master-lock/masterLock.ts +3 -3
  57. package/src/server/master-lock/principals.spec.ts +2 -2
  58. package/src/server/master-lock/principals.ts +1 -1
  59. package/src/server/presence/index.ts +3 -2
  60. package/src/server/requestScope.spec.ts +15 -1
  61. package/src/server/requestScope.ts +35 -0
  62. package/src/server/resume/store.ts +1 -1
  63. package/src/server/storage/binaryStoreFake.ts +1 -1
  64. package/src/server/sync/status.ts +1 -1
  65. package/src/server/youtube/ytdlp.ts +1 -1
@@ -1,9 +1,42 @@
1
+ /**
2
+ * `cursedbelt-server/presence` — 🔴 an app nobody is using costs (close to) nothing (forge task 5325).
3
+ *
4
+ * The owner, 2026-11-16: *"if no one uses apps like photos, roms, flix, vault, desk, etc all day I don't
5
+ * want thousands of requests […] back and forth with no benefit."* Measured that day: the
6
+ * fleet's Worker crons fired ~6,500 times and spent ~172k CPU-ms — about a sixth of the account's Workers
7
+ * CPU, which the month was already past — and nearly all of it ran with nobody there. A five-minute cron
8
+ * is a promise to someone looking at the page; at 4 a.m. it is a promise to no one.
9
+ *
10
+ * So scheduled work keys on PRESENCE, not the clock (night is just the common case of idle):
11
+ *
12
+ * - **{@link createUseTick}** — work that used to run every few minutes runs on USE instead: a signed-in
13
+ * request kicks it under `waitUntil` when it is due, at most once per `everyMs` across every isolate
14
+ * ({@link claimTick} in D1). The Worker's own cron drops to the lowest cadence that is still correct
15
+ * with nobody there (an hourly backstop for queued work, the day's purge), and a stage tier keeps no
16
+ * cron at all: its tests in flight are the use that ticks it.
17
+ * - **{@link notePresence} / {@link lastPresence}** — for a Worker with no sign-in of its own (the media
18
+ * edge): it notes "a reader of <name> was here", throttled per isolate, and its cron asks before it
19
+ * spends anything.
20
+ * - **{@link lastHumanUse}** — for an app behind cursedauth's door: `sessions.last_seen_at` is ALREADY
21
+ * the signal. The door moves it on every signed-in request (`userIdOf`, throttled to a minute), so
22
+ * `MAX(last_seen_at)` is the tier's last human use, with no write of ours at all.
23
+ *
24
+ * Everything is created on first use (`presence_marks`, like `events_days` and the engagement tables),
25
+ * so no app's schema has to learn it. A failed claim runs nothing and warns: a lost tick is the next
26
+ * request's or the backstop cron's, never a double.
27
+ *
28
+ * `tools/check-idle-cost.ts` in the generation holds the other half: a sub-hourly cron or a stage cron
29
+ * that does not go through here is red.
30
+ *
31
+ * 🔴 Worker-safe: nothing here imports `bun:*`.
32
+ */
33
+ import { IDLE_AFTER_MS } from "cursedops/idle-window";
1
34
  /** One row per name: a presence mark (`reader:<tenant>`) or a tick's last run (`tick:<name>`). */
2
35
  export const PRESENCE_DDL = ["CREATE TABLE IF NOT EXISTS presence_marks (name TEXT PRIMARY KEY, at INTEGER NOT NULL)"];
3
36
  /** How often one isolate writes the same presence mark. Presence is an hours-scale question. */
4
37
  export const PRESENCE_THROTTLE_MS = 5 * 60_000;
5
- /** The default "nobody is here" line: no use for this long and scheduled work stands down. */
6
- export const IDLE_AFTER_MS = 3 * 60 * 60_000;
38
+ /** The default "nobody is here" line: no use for this long and scheduled work stands down. cursedops' one home (forge task 5853). */
39
+ export { IDLE_AFTER_MS };
7
40
  const TICK_PREFIX = "tick:";
8
41
  /** An upsert that only moves `at` when the row is older than `?3` — the claim and the throttled mark both. */
9
42
  const UPSERT_IF_OLDER = "INSERT INTO presence_marks (name, at) VALUES (?1, ?2) ON CONFLICT(name) DO UPDATE SET at = excluded.at WHERE presence_marks.at <= ?3";
@@ -9,3 +9,11 @@ export interface RequestScope<S extends object> {
9
9
  lateOf<T extends object>(read: (scope: S) => T | null | undefined, what: string): T;
10
10
  }
11
11
  export declare function createRequestScope<S extends object>(name: string): RequestScope<S>;
12
+ /**
13
+ * What an isolate-built graph is keyed by: every binding by name — a string by value, an object (a D1, a
14
+ * service binding) by identity. A changed secret or a swapped binding builds afresh; the same env never does.
15
+ * photos and collections each held a copy of this until forge task 5830.
16
+ */
17
+ export declare function isolateKey(env: object): string;
18
+ /** `build(env)` once per {@link isolateKey}: the same env answers the same value, a changed one builds afresh. */
19
+ export declare function cacheByBindings<E extends object, T>(build: (env: E) => T): (env: E) => T;
@@ -59,3 +59,36 @@ export function createRequestScope(name) {
59
59
  const late = (key) => lateOf((scope) => scope[key], String(key));
60
60
  return { run: (scope, work) => storage.run(scope, work), current, late, lateOf };
61
61
  }
62
+ /** A stable id per binding object, so a key changes when a binding is swapped, not only when a string is. */
63
+ const bindingIds = new WeakMap();
64
+ let lastBindingId = 0;
65
+ function bindingId(value) {
66
+ let id = bindingIds.get(value);
67
+ if (id === undefined) {
68
+ lastBindingId += 1;
69
+ id = lastBindingId;
70
+ bindingIds.set(value, id);
71
+ }
72
+ return id;
73
+ }
74
+ /**
75
+ * What an isolate-built graph is keyed by: every binding by name — a string by value, an object (a D1, a
76
+ * service binding) by identity. A changed secret or a swapped binding builds afresh; the same env never does.
77
+ * photos and collections each held a copy of this until forge task 5830.
78
+ */
79
+ export function isolateKey(env) {
80
+ const entries = Object.entries(env).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
81
+ return JSON.stringify(entries.map(([name, value]) => [name, value !== null && (typeof value === "object" || typeof value === "function") ? bindingId(value) : value]));
82
+ }
83
+ /** `build(env)` once per {@link isolateKey}: the same env answers the same value, a changed one builds afresh. */
84
+ export function cacheByBindings(build) {
85
+ let built = null;
86
+ return (env) => {
87
+ const key = isolateKey(env);
88
+ if (built?.key === key)
89
+ return built.value;
90
+ const value = build(env);
91
+ built = { key, value };
92
+ return value;
93
+ };
94
+ }
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * ── Why server-side at all ──────────────────────────────────────────────────
6
6
  * `localStorage` would be one line and would answer the wrong question. The
7
- * owner's report is about coming BACK to an app, and he does that from another
7
+ * owner's report is about coming BACK to an app, and the owner does that from another
8
8
  * device — the 2026-08-13 music sign-in from a second laptop is the same shape.
9
9
  * A place remembered only in the browser that saw it is not remembered.
10
10
  *
@@ -12,7 +12,7 @@
12
12
  * `verify:scoped` only typechecks the workspaces its own diff touches, which is
13
13
  * exactly the property that makes it fast.
14
14
  *
15
- * The owner's rule, in his words: *"a change to roms for example cannot block
15
+ * The owner's rule, in their words: *"a change to roms for example cannot block
16
16
  * family tree app from passing its tests."* This is that rule for the one
17
17
  * interface twenty-two suites all fake by hand.
18
18
  *
@@ -42,7 +42,7 @@ export interface SyncStatusReporter {
42
42
  * genuinely not attempted anything, and a restored `consecutiveFailures: 3` would be
43
43
  * a claim about failures that did not happen. But "a peer authenticated here" is
44
44
  * something that happened to the database, and forgetting it produced the owner's
45
- * 2026-08-16 report — prod saying *"Awaiting first sync"* over a vault he had used
45
+ * 2026-08-16 report — prod saying *"Awaiting first sync"* over a vault the owner had used
46
46
  * for weeks. The badge's own words are "your Mac has not dialed since this server
47
47
  * last restarted", which is true and which nobody reads as anything but "this has
48
48
  * never synced". A receiver restarts on every deploy, and the dialer runs every 5
@@ -50,7 +50,7 @@ export interface YtDownload {
50
50
  dir: string;
51
51
  dispose(): Promise<void>;
52
52
  }
53
- /** What one call may add to the profile: a site that needs the owner's sign-in gets his cookies. */
53
+ /** What one call may add to the profile: a site that needs the owner's sign-in gets their cookies. */
54
54
  interface YtDlpCallOptions {
55
55
  /** A Netscape-format cookie jar yt-dlp reads (`--cookies`). The caller owns and removes it. */
56
56
  cookiesFile?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursedbelt-server",
3
- "version": "4.78.0",
3
+ "version": "4.79.2",
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.",
@@ -419,7 +419,7 @@
419
419
  "dependencies": {
420
420
  "argon2id": "1.0.1",
421
421
  "cursedbelt-core": "^2.20.0",
422
- "cursedops": ">=0.8.1 <1.0.0",
422
+ "cursedops": ">=0.39.0 <1.0.0",
423
423
  "cwip": "^4.6.0",
424
424
  "jose": "^6.2.3"
425
425
  },
@@ -459,7 +459,7 @@
459
459
  "@node-rs/argon2": "^2.0.2",
460
460
  "@types/bun": "^1.3.14",
461
461
  "@types/node": "^24",
462
- "cursedbelt": "^6.28.0",
462
+ "cursedbelt": "^6.31.1",
463
463
  "hono": "4.12.28",
464
464
  "kysely": "^0.28.17",
465
465
  "kysely-bun-sqlite": "^0.4.0",
@@ -7,7 +7,8 @@ import pkg from '../package.json';
7
7
  * range used to stop at the next 0.x minor (`<0.10.0`, `<0.12.0`, `<0.13.0`, `<0.14.0`), and every
8
8
  * cursedops minor needed a hand-widening here before the ship could bump apps onto it with one
9
9
  * copy (4.30.1, 4.40.3, 4.40.4, and again for cursedops 0.14.0 — forge task 2832). All this
10
- * package takes from it is `forgeState` from `cursedops/roots`, and `tools/publish-libs.sh`'s
10
+ * package takes from it is `forgeState` from `cursedops/roots` and `IDLE_AFTER_MS` from
11
+ * `cursedops/idle-window` (0.39.0 — the FLOOR, forge task 5853), and `tools/publish-libs.sh`'s
11
12
  * consumer preflight runs every app on a new cursedops before it ships, so the cap bought nothing
12
13
  * but the chore. It is gone; this keeps it gone for the whole 0.x line.
13
14
  */
@@ -15,12 +16,13 @@ describe('cursedops range', () => {
15
16
  const range = pkg.dependencies.cursedops;
16
17
 
17
18
  it('admits every later cursedops 0.x minor, so an app bumping cursedops keeps one copy', () => {
18
- for (const version of ['0.14.0', '0.15.0', '0.20.3', '0.99.0']) {
19
+ for (const version of ['0.39.0', '0.40.0', '0.52.3', '0.99.0']) {
19
20
  expect({ version, admitted: Bun.semver.satisfies(version, range) }).toEqual({ version, admitted: true });
20
21
  }
21
22
  });
22
23
 
23
- it('still refuses what predates forgeState', () => {
24
+ it('still refuses what predates cursedops/idle-window', () => {
24
25
  expect(Bun.semver.satisfies('0.8.0', range)).toBe(false);
26
+ expect(Bun.semver.satisfies('0.38.9', range)).toBe(false);
25
27
  });
26
28
  });
@@ -8,7 +8,7 @@ import { fileURLToPath } from 'node:url';
8
8
  * The owner's ruling, 2026-09-15: *"station shouldn't need it either. This mac can
9
9
  * use a station api to send updates to prod if needed, such as for openclaw. There
10
10
  * should be no polling in cb unless you can make some good case for it that beats
11
- * the api option."* He asked for the case against; there isn't one, and this file is
11
+ * the api option."* The owner asked for the case against; there isn't one, and this file is
12
12
  * the ruling expressed as a check rather than as a paragraph.
13
13
  *
14
14
  * ## Why a paragraph was not enough
@@ -30,8 +30,8 @@ import { fileURLToPath } from 'node:url';
30
30
  *
31
31
  * 🔴 The third row is why this is not "no `setInterval`". `metricsBuffer`'s flush
32
32
  * timer is literally the *"turn many requests into 1"* the owner asked for in the
33
- * same conversation, and a rule that deleted it would contradict him while claiming
34
- * to enforce him. The forbidden act is **dialing a peer**, not scheduling work. The
33
+ * same conversation, and a rule that deleted it would contradict the owner while claiming
34
+ * to enforce their word. The forbidden act is **dialing a peer**, not scheduling work. The
35
35
  * same carve-out covers `signal.ts`'s heartbeat (a comment frame on an already-open
36
36
  * socket) and its reconnect backoff, which runs *only while disconnected*.
37
37
  *
@@ -61,7 +61,7 @@ describe("scriptsRefusedByCsp", () => {
61
61
 
62
62
  /**
63
63
  * 🔴 The failure path this whole file exists for — the owner's console line, turned into a
64
- * refusal. `script-src 'self'` with something injecting is exactly what he pasted.
64
+ * refusal. `script-src 'self'` with something injecting is exactly what the owner pasted.
65
65
  *
66
66
  * 🔴 **`MASTER_LOCK_CSP` itself, never a hand-typed copy of it.** `guard.ts:91` exports the
67
67
  * policy for exactly this reason and says so — *"EXPORTED so that nothing has to copy it"* —
@@ -10,7 +10,7 @@
10
10
  * the foreign scripts disappear — green. Decide a third-party script is wanted and allow its
11
11
  * host — green. Harden a page with `script-src 'self'` while something is still injecting into
12
12
  * it — RED, and it names the origin, which is the console line the owner would otherwise find
13
- * himself during an incident.
13
+ * themselves during an incident.
14
14
  *
15
15
  * ## 🔴 Why it lives in this package
16
16
  *
@@ -11,7 +11,7 @@
11
11
  * line was that tag being refused; it broke nothing and cost an agent the first minutes of
12
12
  * the incident.
13
13
  *
14
- * His decision, 2026-09-18, in his words: *"do your recommendation with option c but not on
14
+ * The owner's decision, 2026-09-18, in their words: *"do your recommendation with option c but not on
15
15
  * the wall. If we can stop the console error that would be good since we are purposely
16
16
  * blocking on that page and it makes it look like there is a mistake when it shows."* — and,
17
17
  * on why the wall's CSP may not simply be loosened: *"I don't want to trust cloudflare with
@@ -124,7 +124,7 @@ export const WEB_ANALYTICS_PUBLIC_HOST = "cursedalchemy.com";
124
124
  * `apps/desk` lost 24, both asserting the console is empty, and the owner's own local console
125
125
  * would have gained a red line on every page.
126
126
  *
127
- * That is the exact cost he asked to be rid of, one environment over. So the guard: the beacon
127
+ * That is the exact cost the owner asked to be rid of, one environment over. So the guard: the beacon
128
128
  * is appended only when the page is being served from {@link WEB_ANALYTICS_PUBLIC_HOST}, which
129
129
  * is the only place it can report anyway.
130
130
  *
@@ -5,7 +5,7 @@
5
5
  * problem a page sees (a stuck video, a failing API, an uncaught error) to {@link CLIENT_ISSUES_PATH};
6
6
  * this door writes one row per report into the app's own D1 `client_issues`, and autopilot's watch
7
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.
8
+ * a report off the owner's phone by hand.
9
9
  *
10
10
  * ```ts
11
11
  * import { CLIENT_ISSUES_DDL, createD1ClientIssuesRecorder } from "cursedbelt-server/client-issues/d1";
@@ -8,7 +8,7 @@
8
8
  * failure that would be invisible in normal use and expensive to discover.
9
9
  *
10
10
  * The arithmetic gets the second most, because the owner's fleet is three
11
- * people: every number the console draws has to be one he could check by hand
11
+ * people: every number the console draws has to be one the owner could check by hand
12
12
  * with a stopwatch and a calendar, so the tests assert exact whole values
13
13
  * rather than "greater than zero".
14
14
  */
@@ -8,7 +8,7 @@
8
8
  * ── What it may hold, and why this much ─────────────────────────────────────
9
9
  * `store.ts`'s header refuses a timeline of a household's private apps, and that still holds for
10
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}.
11
+ * attention, the least that answers the owner's question, and only for {@link ENGAGEMENT_VISIT_RETENTION_DAYS}.
12
12
  * One row per VISIT (the same cut as the sessions count, `policy.ts:foldView`), not per beacon: 264
13
13
  * visits across the fleet in the 30 days to 2026-10-30, against "a few thousand a month" as the line.
14
14
  *
@@ -4,8 +4,8 @@
4
4
  *
5
5
  * ── The severity split is the feature ───────────────────────────────────────
6
6
  * The owner asked for "an email and a text message about blocking issues like
7
- * these (can't deploy, can't ingest files)". A warning that texts him is a
8
- * warning that gets the channel muted, and a muted channel puts him back where
7
+ * these (can't deploy, can't ingest files)". A warning that texts the owner is a
8
+ * warning that gets the channel muted, and a muted channel puts the owner back where
9
9
  * this whole unit started — finding out days later, by accident. So: in-app for
10
10
  * everything, email + text for `blocking` only, and `notifier.ts` is the only
11
11
  * place that decision is made.
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * `cursedbelt-server/incidents` — the fleet's ONE owner-alert primitive: a
3
3
  * condition that is true for a while, told to the owner exactly once, and told
4
- * to him again when it clears.
4
+ * to the owner again when it clears.
5
5
  *
6
6
  * ── Why it exists (the owner, 2026-08-13) ───────────────────────────────────
7
7
  * *"I found out from an agent my collection uploads were stuck … there are
@@ -10,7 +10,7 @@
10
10
  * The incident behind it: 42 videos / 35 GB sat in the collections dropzone and
11
11
  * every scheduled ingest failed all 42 with EPIPE against binary-server, while
12
12
  * binary-server logged that it was under its 12 GB disk reserve — and the
13
- * dropzone deletes originals once they reach the catalog. Nothing told him. Two
13
+ * dropzone deletes originals once they reach the catalog. Nothing told the owner. Two
14
14
  * separate deterministic checks would each have caught it on the first run.
15
15
  *
16
16
  * ── Why it is HERE and not in `satellite-kit` ───────────────────────────────
@@ -13,12 +13,12 @@
13
13
  * symptom, a command and a credential without saying what any of them are. So
14
14
  * an incident message is three sentences with fixed jobs, in this order:
15
15
  *
16
- * WHAT BROKE — in words, naming the app. Assume he does not know what
16
+ * WHAT BROKE — in words, naming the app. Assume the owner does not know what
17
17
  * your daemon, flag, tab or port is.
18
- * WHAT IT BLOCKS — what he cannot do until it is fixed. This is the sentence
18
+ * WHAT IT BLOCKS — what the owner cannot do until it is fixed. This is the sentence
19
19
  * that earns a text message at 2am; if you cannot write it,
20
20
  * the incident is a `warning`.
21
- * WHAT TO DO — a next step. A command carries its own `cd`, because he
21
+ * WHAT TO DO — a next step. A command carries its own `cd`, because the owner
22
22
  * opens terminals anywhere (`fleet/rules/
23
23
  * commands-must-run-from-anywhere.md`).
24
24
  *
@@ -53,9 +53,9 @@ export interface AnnounceResult {
53
53
  * overdue backup opened as blocking while the email channel was still
54
54
  * misconfigured, both channels failed, and — because `notifiedAt` was stamped —
55
55
  * nothing would ever have tried again. The owner would have had a blocking
56
- * incident on a board he had no reason to open. The dedupe promise is "you are
56
+ * incident on a board the owner had no reason to open. The dedupe promise is "you are
57
57
  * told ONCE", not "we attempt once": an attempt that reached nobody has not told
58
- * him anything.
58
+ * the owner anything.
59
59
  *
60
60
  * It retries at most hourly, and it STOPS the moment any channel reports
61
61
  * `delivered` — so a permanently broken channel costs one send an hour, and a
@@ -90,7 +90,7 @@ export function composeOpened(incident: Incident): ChannelMessage {
90
90
 
91
91
  /**
92
92
  * The message for a resolve. It exists so "is it fixed?" is answered without
93
- * him having to go and look — the same reason the open message exists.
93
+ * the owner having to go and look — the same reason the open message exists.
94
94
  */
95
95
  export function composeResolved(incident: Incident): ChannelMessage {
96
96
  const minutes = Math.max(1, Math.round(((incident.resolvedAt ?? 0) - incident.firstSeen) / 60000));
@@ -175,8 +175,8 @@ export function createIncidentNotifier(options: CreateNotifierOptions): Incident
175
175
  const result = await dispatch(incident, composeOpened(incident), transition);
176
176
  // 🔴 Only stamp `notifiedAt` when there was actually a channel to try.
177
177
  // A host with none (a prod deployment that only stores what the Mac
178
- // pushes it) has not told him anything, and stamping it there is what
179
- // made the resolve message below fire for an open he never saw.
178
+ // pushes it) has not told the owner anything, and stamping it there is what
179
+ // made the resolve message below fire for an open the owner never saw.
180
180
  if (result.results.length > 0) {
181
181
  store.markNotified([incident.fingerprint], summarise(result.results));
182
182
  }
@@ -199,7 +199,7 @@ export function createIncidentNotifier(options: CreateNotifierOptions): Incident
199
199
 
200
200
  for (const incident of t.resolved) {
201
201
  // Never announce a resolve for something whose OPEN was never
202
- // announced — the owner would get "cleared: X" for an X he has never
202
+ // announced — the owner would get "cleared: X" for an X they have never
203
203
  // heard of, which reads as a bug in the alerting rather than as good
204
204
  // news. This happens for real: an incident opened, acknowledged and
205
205
  // resolved between two sweeps of a host that had no channels.
@@ -19,7 +19,7 @@
19
19
  * which is the same uselessness as a permanently green one.
20
20
  *
21
21
  * The dedupe is entirely the console's: post the same thing every five minutes
22
- * for a week and he is told once. So a reporter needs no state, no "have I said
22
+ * for a week and the owner is told once. So a reporter needs no state, no "have I said
23
23
  * this?" flag, and no backoff — which is why this file is forty lines and not
24
24
  * four hundred.
25
25
  *
@@ -5,7 +5,7 @@
5
5
  * "auto notifying me once per incident (it needs to avoid sending me the same
6
6
  * problem over and over in duplicated notifications if it's polling for
7
7
  * problems)". A poller that re-sends every five minutes is the failure mode
8
- * that gets the whole feature muted, which puts him back where he started but
8
+ * that gets the whole feature muted, which puts the owner back where they started but
9
9
  * with more noise. So the unit of this module is a *condition that is true for
10
10
  * a while*, identified by a stable {@link fingerprint}, with a lifecycle —
11
11
  * and a notification is attached to a TRANSITION of that lifecycle, never to
@@ -27,7 +27,7 @@
27
27
  export type IncidentSeverity =
28
28
  /** The owner's own examples: "can't deploy, can't ingest files". Email AND text. */
29
29
  | "blocking"
30
- /** Worth knowing, in-app only. A warning that texts him is a warning that mutes the channel. */
30
+ /** Worth knowing, in-app only. A warning that texts the owner is a warning that mutes the channel. */
31
31
  | "warning";
32
32
 
33
33
  /** Where an incident is in its life. */
@@ -60,9 +60,9 @@ export interface IncidentReport {
60
60
  severity: IncidentSeverity;
61
61
  /** One line, for a notification subject and a table row. Names the app. */
62
62
  title: string;
63
- /** ELI5: what actually broke. Assume he does not know what your daemon is. */
63
+ /** ELI5: what actually broke. Assume the owner does not know what your daemon is. */
64
64
  whatBroke: string;
65
- /** ELI5: what it stops him doing. This is the sentence that earns the text message. */
65
+ /** ELI5: what it stops the owner doing. This is the sentence that earns the text message. */
66
66
  whatItBlocks: string;
67
67
  /** ELI5: what to do about it. A runnable command carries its own `cd` (fleet rule). */
68
68
  whatToDo: string;
@@ -109,7 +109,7 @@ export interface IncidentTransitions {
109
109
  /**
110
110
  * A stable identity for a condition. Deliberately NOT a hash of the message:
111
111
  * an author who improves the wording of `whatToDo` must not thereby re-alert
112
- * the owner about a problem he already knows about.
112
+ * the owner about a problem they already know about.
113
113
  */
114
114
  export function fingerprint(report: Pick<IncidentReport, "source" | "kind" | "subject">): string {
115
115
  return `${report.source}:${report.kind}:${report.subject}`;
@@ -378,3 +378,76 @@ export function createMetaTableBudget<Api extends string>(
378
378
  },
379
379
  };
380
380
  }
381
+
382
+ // ───────────────────────────── a refused key ─────────────────────────────
383
+
384
+ /**
385
+ * A Maps key Google REFUSED, remembered in the app's `meta (key, value)` table so the app stops asking
386
+ * (forge tasks 5592, 5764).
387
+ *
388
+ * 🔴 On 2026-11-18 every Places viewport in photos spent a count of the ceiling on a key Google called
389
+ * "invalid", and the 404's reason said only "answered 403". A new key is the owner's hands, never minutes
390
+ * away, so a 401/403 is written down for an hour: until then the door answers with the refusal's own words
391
+ * and touches neither the ceiling nor the network. photos, trivia and family each held a copy of this; a
392
+ * fix to it (a new status Google uses to refuse) now reaches all three.
393
+ *
394
+ * One row per API (`maps-refused.<api>`), because a key restricted away from ONE API is still good for
395
+ * the rest.
396
+ */
397
+
398
+ /** How long an app stops asking after Google refused its key. */
399
+ export const KEY_REFUSED_HOLD_MS = 60 * 60 * 1000;
400
+
401
+ /** The `meta` row a refusal of `api` is remembered under: `{ at: ISO, reason }`. */
402
+ export const keyRefusedRow = (api: string): string => `maps-refused.${api}`;
403
+
404
+ /** The HTTP statuses that mean Google refuses the KEY, not the request. */
405
+ export const isKeyRefusal = (status: number): boolean => status === 401 || status === 403;
406
+
407
+ export interface KeyRefusalOptions {
408
+ /** The app's own name, as a reader sees it in the reason ("photos", "trivia", "family"). */
409
+ app: string;
410
+ /** Defaults to the wall clock; a spec passes its own. */
411
+ now?: () => number;
412
+ /** Defaults to {@link KEY_REFUSED_HOLD_MS}. */
413
+ holdMs?: number;
414
+ }
415
+
416
+ export interface KeyRefusalMemory {
417
+ /** The refusal of `api` still holding now, in words a reader sees — or null. A malformed row is null. */
418
+ held(api: string): Promise<string | null>;
419
+ /**
420
+ * When `response` is Google refusing the key, remember it and return the reason; otherwise null.
421
+ * Reads the body (Google's one line of plain text, "The provided API key is invalid.") only then.
422
+ */
423
+ record(api: string, response: Response): Promise<string | null>;
424
+ }
425
+
426
+ export function createKeyRefusalMemory(db: Pick<D1LikeDatabase, 'prepare'>, options: KeyRefusalOptions): KeyRefusalMemory {
427
+ const now = options.now ?? Date.now;
428
+ const holdMs = options.holdMs ?? KEY_REFUSED_HOLD_MS;
429
+ return {
430
+ async held(api) {
431
+ const row = await db.prepare('SELECT value FROM meta WHERE key = ?').bind(keyRefusedRow(api)).first<{ value: string }>();
432
+ if (!row) return null;
433
+ try {
434
+ const mark = JSON.parse(row.value) as { at?: unknown; reason?: unknown };
435
+ const at = typeof mark.at === 'string' ? Date.parse(mark.at) : Number.NaN;
436
+ if (!Number.isFinite(at) || now() - at >= holdMs || typeof mark.reason !== 'string') return null;
437
+ return `${mark.reason} ${options.app} stopped asking at ${mark.at as string} and asks again an hour after.`;
438
+ } catch {
439
+ return null;
440
+ }
441
+ },
442
+ async record(api, response) {
443
+ if (!isKeyRefusal(response.status)) return null;
444
+ const said = (await response.text().catch(() => '')).trim().slice(0, 200);
445
+ const reason = `Google refuses the Maps key ${options.app} holds, for ${api} (${response.status}${said ? `: ${said}` : ''}) — a new GOOGLE_MAPS_API_KEY is needed; the map draws every pin meanwhile.`;
446
+ await db
447
+ .prepare('INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value')
448
+ .bind(keyRefusedRow(api), JSON.stringify({ at: new Date(now()).toISOString(), reason }))
449
+ .run();
450
+ return reason;
451
+ },
452
+ };
453
+ }
@@ -0,0 +1,79 @@
1
+ import { Database } from 'bun:sqlite';
2
+ import { describe, expect, it } from 'bun:test';
3
+ import { createLocalD1 } from '../d1/local.js';
4
+ import { createKeyRefusalMemory, createMetaTableBudget, KEY_REFUSED_HOLD_MS, keyRefusedRow } from '../maps-budget/mapsBudget.js';
5
+ import { renderStaticMap, type StaticMapRequest } from './staticMap.js';
6
+
7
+ const AT = Date.UTC(2026, 10, 18, 12);
8
+ const request: StaticMapRequest = { center: { lat: 30, lng: -97 }, zoom: 6, width: 320, height: 180, theme: 'light' };
9
+
10
+ function harness(answer: (signal?: AbortSignal) => Response | Promise<Response>) {
11
+ const sqlite = new Database(':memory:');
12
+ sqlite.run('CREATE TABLE meta ( key TEXT PRIMARY KEY, value TEXT NOT NULL )');
13
+ const db = createLocalD1(sqlite);
14
+ let clock = AT;
15
+ const calls: string[] = [];
16
+ const budget = createMetaTableBudget<'staticmap'>(db, { ceilings: { staticmap: 300 }, refusal: () => ({ reason: 'over the ceiling' }), now: () => clock });
17
+ const render = () =>
18
+ renderStaticMap({
19
+ request,
20
+ maps: {
21
+ apiKey: 'key',
22
+ fetch: async (url, init) => {
23
+ calls.push(url);
24
+ return answer(init?.signal ?? undefined);
25
+ },
26
+ },
27
+ budget,
28
+ refusals: createKeyRefusalMemory(db, { app: 'photos', now: () => clock }),
29
+ timeoutMs: 20,
30
+ });
31
+ return { sqlite, render, calls, advance: (ms: number) => (clock += ms), spent: async () => (await budget.usage())[0]?.used };
32
+ }
33
+
34
+ describe('renderStaticMap — THE door to Google Static Maps', () => {
35
+ it('answers the bytes and counts one against the ceiling', async () => {
36
+ const h = harness(() => new Response(new Uint8Array([1, 2, 3])));
37
+ expect(await h.render()).toEqual({ ok: true, bytes: new Uint8Array([1, 2, 3]) });
38
+ expect(await h.spent()).toBe(1);
39
+ });
40
+
41
+ it('🔴 a key Google refuses is remembered: the next render touches neither the ceiling nor the network', async () => {
42
+ const h = harness(() => new Response('The provided API key is invalid.', { status: 403 }));
43
+ const first = await h.render();
44
+ expect(first).toEqual({ ok: false, reason: expect.stringContaining("Google refuses the Maps key photos holds, for staticmap (403: The provided API key is invalid.)") });
45
+ expect(h.sqlite.query('SELECT key FROM meta WHERE key = ?').get(keyRefusedRow('staticmap'))).not.toBeNull();
46
+ const second = await h.render();
47
+ expect(second.ok).toBe(false);
48
+ expect(second.ok ? '' : second.reason).toContain('photos stopped asking at 2026-11-18T12:00:00.000Z');
49
+ expect(h.calls).toHaveLength(1);
50
+ expect(await h.spent()).toBe(1);
51
+ // An hour on, it asks again.
52
+ h.advance(KEY_REFUSED_HOLD_MS);
53
+ await h.render();
54
+ expect(h.calls).toHaveLength(2);
55
+ });
56
+
57
+ it('a 401 is a refusal too; a 500 is not remembered', async () => {
58
+ const unauthorized = harness(() => new Response('', { status: 401 }));
59
+ await unauthorized.render();
60
+ await unauthorized.render();
61
+ expect(unauthorized.calls).toHaveLength(1);
62
+ const down = harness(() => new Response('', { status: 500 }));
63
+ expect(await down.render()).toEqual({ ok: false, reason: 'Google staticmap answered 500' });
64
+ await down.render();
65
+ expect(down.calls).toHaveLength(2);
66
+ });
67
+
68
+ it('gives up at the timeout, with the reason', async () => {
69
+ // Google never answers; only the door's own abort ends the wait.
70
+ const silent = harness((signal) => new Promise<Response>((_, reject) => signal?.addEventListener('abort', () => reject(new Error('The operation was aborted.')))));
71
+ expect(await silent.render()).toEqual({ ok: false, reason: 'Google staticmap did not answer (The operation was aborted.)' });
72
+ });
73
+
74
+ it('a malformed refusal row holds nothing', async () => {
75
+ const h = harness(() => new Response(new Uint8Array([9])));
76
+ h.sqlite.run('INSERT INTO meta (key, value) VALUES (?, ?)', [keyRefusedRow('staticmap'), '{not json']);
77
+ expect((await h.render()).ok).toBe(true);
78
+ });
79
+ });