@schlessera/brain-ui-server 0.18.0 → 0.20.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.
Files changed (130) hide show
  1. package/README.md +5 -1
  2. package/data/model-prices.json +63 -0
  3. package/dist/activity/digest.d.ts +29 -0
  4. package/dist/activity/digest.d.ts.map +1 -0
  5. package/dist/activity/digest.js +89 -0
  6. package/dist/activity/digest.js.map +1 -0
  7. package/dist/activity/notify.d.ts +62 -0
  8. package/dist/activity/notify.d.ts.map +1 -0
  9. package/dist/activity/notify.js +193 -0
  10. package/dist/activity/notify.js.map +1 -0
  11. package/dist/activity/push-sender.d.ts +63 -0
  12. package/dist/activity/push-sender.d.ts.map +1 -0
  13. package/dist/activity/push-sender.js +131 -0
  14. package/dist/activity/push-sender.js.map +1 -0
  15. package/dist/activity/query.d.ts +16 -0
  16. package/dist/activity/query.d.ts.map +1 -0
  17. package/dist/activity/query.js +155 -0
  18. package/dist/activity/query.js.map +1 -0
  19. package/dist/activity/recorder.d.ts +53 -0
  20. package/dist/activity/recorder.d.ts.map +1 -0
  21. package/dist/activity/recorder.js +238 -0
  22. package/dist/activity/recorder.js.map +1 -0
  23. package/dist/activity/runtime.d.ts +37 -0
  24. package/dist/activity/runtime.d.ts.map +1 -0
  25. package/dist/activity/runtime.js +127 -0
  26. package/dist/activity/runtime.js.map +1 -0
  27. package/dist/activity/span-sink.d.ts +22 -0
  28. package/dist/activity/span-sink.d.ts.map +1 -0
  29. package/dist/activity/span-sink.js +138 -0
  30. package/dist/activity/span-sink.js.map +1 -0
  31. package/dist/activity/store.d.ts +256 -0
  32. package/dist/activity/store.d.ts.map +1 -0
  33. package/dist/activity/store.js +657 -0
  34. package/dist/activity/store.js.map +1 -0
  35. package/dist/activity/stream.d.ts +49 -0
  36. package/dist/activity/stream.d.ts.map +1 -0
  37. package/dist/activity/stream.js +353 -0
  38. package/dist/activity/stream.js.map +1 -0
  39. package/dist/agent/backend.d.ts +13 -4
  40. package/dist/agent/backend.d.ts.map +1 -1
  41. package/dist/agent/backend.js +68 -5
  42. package/dist/agent/backend.js.map +1 -1
  43. package/dist/app.d.ts.map +1 -1
  44. package/dist/app.js +33 -2
  45. package/dist/app.js.map +1 -1
  46. package/dist/config/env.d.ts +36 -0
  47. package/dist/config/env.d.ts.map +1 -1
  48. package/dist/config/env.js +66 -2
  49. package/dist/config/env.js.map +1 -1
  50. package/dist/cron/scheduler.d.ts.map +1 -1
  51. package/dist/cron/scheduler.js +20 -5
  52. package/dist/cron/scheduler.js.map +1 -1
  53. package/dist/db/client.d.ts.map +1 -1
  54. package/dist/db/client.js +32 -6
  55. package/dist/db/client.js.map +1 -1
  56. package/dist/db/settings.d.ts +15 -0
  57. package/dist/db/settings.d.ts.map +1 -1
  58. package/dist/db/settings.js +43 -0
  59. package/dist/db/settings.js.map +1 -1
  60. package/dist/index.d.ts +4 -0
  61. package/dist/index.d.ts.map +1 -1
  62. package/dist/index.js +7 -0
  63. package/dist/index.js.map +1 -1
  64. package/dist/pricing/model-pricing.d.ts +61 -0
  65. package/dist/pricing/model-pricing.d.ts.map +1 -0
  66. package/dist/pricing/model-pricing.js +379 -0
  67. package/dist/pricing/model-pricing.js.map +1 -0
  68. package/dist/routes/activity.d.ts +20 -0
  69. package/dist/routes/activity.d.ts.map +1 -0
  70. package/dist/routes/activity.js +308 -0
  71. package/dist/routes/activity.js.map +1 -0
  72. package/dist/routes/models.d.ts +6 -0
  73. package/dist/routes/models.d.ts.map +1 -1
  74. package/dist/routes/models.js +38 -3
  75. package/dist/routes/models.js.map +1 -1
  76. package/dist/routes/push.d.ts +6 -0
  77. package/dist/routes/push.d.ts.map +1 -0
  78. package/dist/routes/push.js +73 -0
  79. package/dist/routes/push.js.map +1 -0
  80. package/dist/routes/sessions.d.ts.map +1 -1
  81. package/dist/routes/sessions.js +20 -4
  82. package/dist/routes/sessions.js.map +1 -1
  83. package/dist/ws/bridge.d.ts +2 -1
  84. package/dist/ws/bridge.d.ts.map +1 -1
  85. package/dist/ws/bridge.js +27 -2
  86. package/dist/ws/bridge.js.map +1 -1
  87. package/dist/ws/connection.d.ts.map +1 -1
  88. package/dist/ws/connection.js +9 -1
  89. package/dist/ws/connection.js.map +1 -1
  90. package/dist/ws/dispatch.d.ts.map +1 -1
  91. package/dist/ws/dispatch.js +11 -0
  92. package/dist/ws/dispatch.js.map +1 -1
  93. package/dist/ws/host.d.ts +16 -0
  94. package/dist/ws/host.d.ts.map +1 -1
  95. package/dist/ws/host.js +2 -0
  96. package/dist/ws/host.js.map +1 -1
  97. package/dist/ws/run-session.d.ts.map +1 -1
  98. package/dist/ws/run-session.js +55 -1
  99. package/dist/ws/run-session.js.map +1 -1
  100. package/migrations/007_activity.sql +114 -0
  101. package/migrations/008_push_subscriptions.sql +24 -0
  102. package/migrations/009_activity_followups.sql +22 -0
  103. package/migrations/010_effective_cost.sql +21 -0
  104. package/package.json +6 -3
  105. package/src/activity/digest.ts +120 -0
  106. package/src/activity/notify.ts +307 -0
  107. package/src/activity/push-sender.ts +215 -0
  108. package/src/activity/query.ts +187 -0
  109. package/src/activity/recorder.ts +313 -0
  110. package/src/activity/runtime.ts +169 -0
  111. package/src/activity/span-sink.ts +152 -0
  112. package/src/activity/store.ts +1069 -0
  113. package/src/activity/stream.ts +396 -0
  114. package/src/agent/backend.ts +91 -10
  115. package/src/app.ts +35 -2
  116. package/src/config/env.ts +90 -2
  117. package/src/cron/scheduler.ts +28 -8
  118. package/src/db/client.ts +31 -6
  119. package/src/db/settings.ts +56 -0
  120. package/src/index.ts +23 -0
  121. package/src/pricing/model-pricing.ts +497 -0
  122. package/src/routes/activity.ts +371 -0
  123. package/src/routes/models.ts +57 -6
  124. package/src/routes/push.ts +90 -0
  125. package/src/routes/sessions.ts +24 -4
  126. package/src/ws/bridge.ts +29 -2
  127. package/src/ws/connection.ts +9 -1
  128. package/src/ws/dispatch.ts +13 -0
  129. package/src/ws/host.ts +18 -0
  130. package/src/ws/run-session.ts +71 -2
@@ -0,0 +1,21 @@
1
+ -- Frozen effective-cost accounting on run rollups (computed in rollupRunInTx).
2
+ --
3
+ -- effective_cost_usd: what the run actually cost — 0 for subscription-billed
4
+ -- work regardless of tokens, priced per-model usage for api-billed. NULL =
5
+ -- unknown, 0 = genuinely free (never conflated). billing_mode is the
6
+ -- 'subscription' | 'api' classification behind that number; pricing_estimate
7
+ -- is 1 when the price came from estimated rates (snapshot data, or an
8
+ -- OpenRouter routing variant priced at its base rate).
9
+ --
10
+ -- Deliberately NO backfill: pre-feature rows carry no billing attrs and their
11
+ -- span detail may already be pruned, so any classification would be a guess.
12
+ -- They stay NULL (= unknown) by decision — every surface renders unknown,
13
+ -- never $0.
14
+ -- The CHECKs admit NULL (unknown) by SQL semantics; they reject only a wrong
15
+ -- non-NULL value at the door. rowToRunRollup still validates on read, so a
16
+ -- row written around them degrades to NULL rather than surfacing garbage.
17
+ ALTER TABLE activity_run_rollups ADD COLUMN effective_cost_usd REAL;
18
+ ALTER TABLE activity_run_rollups ADD COLUMN billing_mode TEXT
19
+ CHECK (billing_mode IN ('subscription', 'api'));
20
+ ALTER TABLE activity_run_rollups ADD COLUMN pricing_estimate INTEGER
21
+ CHECK (pricing_estimate IN (0, 1));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@schlessera/brain-ui-server",
3
- "version": "0.18.0",
3
+ "version": "0.20.0",
4
4
  "description": "brain-kit chat-UI server: Hono app factory, WebSocket turn coordinator, auth (password/passkeys/tailscale/proxy), session catalog, and brain/files/voice routes",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -39,6 +39,7 @@
39
39
  "src",
40
40
  "dist",
41
41
  "migrations",
42
+ "data",
42
43
  "README.md"
43
44
  ],
44
45
  "scripts": {
@@ -48,11 +49,12 @@
48
49
  "dependencies": {
49
50
  "@opentelemetry/api": "^1.9.1",
50
51
  "@opentelemetry/api-logs": "0.221.0",
51
- "@schlessera/brain-render-template": "0.18.0",
52
- "@schlessera/brain-ui-sdk": "0.18.0",
52
+ "@schlessera/brain-render-template": "0.20.0",
53
+ "@schlessera/brain-ui-sdk": "0.20.0",
53
54
  "@simplewebauthn/server": "^13.3.2",
54
55
  "hono": "^4",
55
56
  "ignore": "^7.0.5",
57
+ "web-push": "^3.6.7",
56
58
  "zod": "^4.4.3"
57
59
  },
58
60
  "peerDependencies": {
@@ -73,6 +75,7 @@
73
75
  },
74
76
  "devDependencies": {
75
77
  "@types/bun": "^1.3.14",
78
+ "@types/web-push": "^3.6.4",
76
79
  "typescript": "^6.0.3"
77
80
  }
78
81
  }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * The while-you-were-away digest: a deterministic summary rendered from
3
+ * per-run rollups, produced by its OWN scheduled job (through the standard
4
+ * cron wrapper, so its runs land in the record like any other) — never a
5
+ * side effect of instrumentation.
6
+ *
7
+ * The digest's covered-until time is the retention floor: full-detail spans
8
+ * older than the last covered window are prunable, newer ones are not (the
9
+ * hard ceiling in the store bounds a broken digest job regardless). Windows
10
+ * are labeled — the card says WHAT period it covers rather than implying
11
+ * "now". The digest job's own runs are recorded but excluded from the
12
+ * notable list, or every digest would feature itself.
13
+ */
14
+ import type { Database } from "bun:sqlite";
15
+ import { isFailureOutcome, type ActivityDigest } from "@schlessera/brain-ui-sdk/protocol";
16
+
17
+ import { getSetting, setSetting } from "../db/settings.js";
18
+ import { rowToRunRollup, sumEffectiveCost } from "./store.js";
19
+
20
+ export type { ActivityDigest } from "@schlessera/brain-ui-sdk/protocol";
21
+
22
+ export const DIGEST_LATEST_KEY = "activity.digest.latest";
23
+ export const DIGEST_COVERED_KEY = "activity.digest.coveredUntil";
24
+ export const DIGEST_DISMISSED_KEY = "activity.digest.dismissedAt";
25
+ export const DIGEST_JOB_NAME = "digest";
26
+
27
+ /** First run ever: no covered-until marker — cap the window at 24h. */
28
+ const FIRST_WINDOW_MS = 24 * 60 * 60 * 1000;
29
+
30
+ /** Generate and persist the digest for [coveredUntil, now]. */
31
+ export function generateActivityDigest(db: Database, now = Date.now()): ActivityDigest {
32
+ // The read-compute-write of coveredUntil runs as ONE immediate transaction:
33
+ // the cron digest job and a manual generation are separate processes on the
34
+ // same DB, and unserialized they both window from the same coveredUntil —
35
+ // double-counting the overlap and letting the retention floor regress when
36
+ // the earlier `now` lands last. BEGIN IMMEDIATE + busy_timeout serializes
37
+ // them; the loser re-reads the winner's coveredUntil and windows after it.
38
+ return db.transaction(() => generateInTx(db, now)).immediate();
39
+ }
40
+
41
+ function generateInTx(db: Database, now: number): ActivityDigest {
42
+ const covered = getSetting<number | null>(db, DIGEST_COVERED_KEY, null);
43
+ if (covered !== null && now <= covered) {
44
+ // A newer generation already committed — we serialized behind the race's
45
+ // winner, or our clock trails coveredUntil. The window would be inverted
46
+ // and empty; return the winner's digest instead of overwriting it.
47
+ const latest = latestActivityDigest(db);
48
+ if (latest) return latest;
49
+ // Covered set but no stored digest (partial state): degrade to an empty
50
+ // window at the floor rather than inverting it.
51
+ now = covered;
52
+ }
53
+ const windowStart = covered ?? now - FIRST_WINDOW_MS;
54
+
55
+ // Windowed on ended_at, not started_at: every FINISHED run gets
56
+ // exactly-once coverage — a run still open at generation is picked up by
57
+ // the NEXT digest once it ends, instead of falling between windows.
58
+ const rows = (
59
+ db
60
+ .query(
61
+ `SELECT * FROM activity_run_rollups
62
+ WHERE ended_at IS NOT NULL AND ended_at >= ? AND ended_at < ?
63
+ ORDER BY started_at DESC`
64
+ )
65
+ .all(windowStart, now) as any[]
66
+ ).map(rowToRunRollup);
67
+
68
+ const relevant = rows.filter((r) => r.jobName !== DIGEST_JOB_NAME);
69
+ const failures = relevant.filter((r) => isFailureOutcome(r.outcome));
70
+ // Both cost sums are sum-of-knowns; sumEffectiveCost counts the excluded
71
+ // unknown-cost runs so the digest never passes an unknown off as $0 (AE3).
72
+ const effective = sumEffectiveCost(relevant);
73
+
74
+ const digest: ActivityDigest = {
75
+ generatedAt: now,
76
+ windowStart,
77
+ windowEnd: now,
78
+ runs: relevant.length,
79
+ failures: failures.length,
80
+ costUsd: relevant.reduce((a, r) => a + (r.costUsd ?? 0), 0),
81
+ effectiveCostUsd: effective.effectiveCostUsd,
82
+ unpricedRuns: effective.unpricedRuns,
83
+ inputTokens: relevant.reduce((a, r) => a + (r.inputTokens ?? 0), 0),
84
+ outputTokens: relevant.reduce((a, r) => a + (r.outputTokens ?? 0), 0),
85
+ notable: failures.slice(0, 10).map((r) => ({
86
+ runId: r.runId,
87
+ name: r.name,
88
+ jobName: r.jobName,
89
+ sessionId: r.sessionId,
90
+ outcome: r.outcome,
91
+ failureReason: r.failureReason,
92
+ startedAt: r.startedAt,
93
+ })),
94
+ };
95
+
96
+ setSetting(db, DIGEST_LATEST_KEY, digest);
97
+ // Monotonic: a generator whose clock trails the previous coveredUntil
98
+ // (skew, or a back-to-back manual run) must not walk the retention floor
99
+ // backwards and re-expose already-covered spans to double coverage.
100
+ setSetting(db, DIGEST_COVERED_KEY, Math.max(now, covered ?? 0));
101
+ return digest;
102
+ }
103
+
104
+ /** The latest digest, or null before the first run. */
105
+ export function latestActivityDigest(db: Database): ActivityDigest | null {
106
+ return getSetting<ActivityDigest | null>(db, DIGEST_LATEST_KEY, null);
107
+ }
108
+
109
+ /** The retention floor: never prune spans the digest has not covered. */
110
+ export function digestRetentionFloor(db: Database): number {
111
+ return getSetting<number>(db, DIGEST_COVERED_KEY, 0);
112
+ }
113
+
114
+ export function dismissActivityDigest(db: Database, at = Date.now()): void {
115
+ setSetting(db, DIGEST_DISMISSED_KEY, at);
116
+ }
117
+
118
+ export function digestDismissedAt(db: Database): number {
119
+ return getSetting<number>(db, DIGEST_DISMISSED_KEY, 0);
120
+ }
@@ -0,0 +1,307 @@
1
+ /**
2
+ * Notification intents: the at-least-once layer between the activity record
3
+ * and every delivery channel.
4
+ *
5
+ * An intent is persisted when the triggering condition is DETECTED (a
6
+ * terminal failure span, a stuck run) and carries its own lifecycle:
7
+ * pending -> sent | send_failed | suppressed. The in-app inbox is the
8
+ * guaranteed tier — it lists unacknowledged intents regardless of delivery
9
+ * status — and web push (the accelerator) marks sent/send_failed on top.
10
+ * Undelivered intents survive restarts by construction; the boot/tick sweep
11
+ * simply finds them still pending.
12
+ *
13
+ * Detection runs on the server's always-on tick with its OWN change-log
14
+ * cursor (the live stream's cursor only advances for subscribers), so a
15
+ * foreign writer's failure — the cron wrapper recording an error while
16
+ * nobody watches — is noticed within one tick, not at the next app open.
17
+ *
18
+ * Storm safety: a run-scoped tag deduplicates (one active intent per tag),
19
+ * per-job debounce collapses repeats, and a global creation rate cap stops
20
+ * one bad API key from paging for every job at once.
21
+ */
22
+ import type { Database } from "bun:sqlite";
23
+ import type { Logger } from "@opentelemetry/api-logs";
24
+ import { isFailureOutcome } from "@schlessera/brain-ui-sdk/protocol";
25
+
26
+ import { getSetting } from "../db/settings.js";
27
+ import type { ActivityStore, SpanRow } from "./store.js";
28
+
29
+ export type IntentKind = "failure" | "completion" | "stuck";
30
+
31
+ export interface NotificationIntent {
32
+ id: number;
33
+ runId: string;
34
+ spanId: string | null;
35
+ kind: IntentKind;
36
+ tag: string;
37
+ title: string;
38
+ body: string;
39
+ status: "pending" | "sent" | "send_failed" | "suppressed";
40
+ acknowledged: boolean;
41
+ createdAt: number;
42
+ }
43
+
44
+ export interface ActivityNotifierDeps {
45
+ db: Database;
46
+ store: ActivityStore;
47
+ /** Was anyone watching this run/session when the event was recorded? */
48
+ isWatched: (scope: { runId?: string; sessionId?: string }) => boolean;
49
+ log?: Logger;
50
+ }
51
+
52
+ export interface ActivityNotifier {
53
+ /** Detect new terminal failures + stuck runs; create intents. */
54
+ tick(now?: number): void;
55
+ /** Unacknowledged intents, newest first (the inbox). */
56
+ inbox(limit?: number): NotificationIntent[];
57
+ /** Intents awaiting delivery (the push sender's queue). */
58
+ pending(limit?: number): NotificationIntent[];
59
+ markDelivered(id: number, status: "sent" | "send_failed"): void;
60
+ acknowledge(id: number): boolean;
61
+ acknowledgeAll(): number;
62
+ /** Retention: delete acknowledged intents untouched for longer than this. */
63
+ pruneAcknowledged(olderThanMs: number): number;
64
+ }
65
+
66
+ /** Global cap on intents CREATED per hour — failure-storm circuit. */
67
+ const MAX_INTENTS_PER_HOUR = 20;
68
+ /** A send_failed intent is retried this many times before push is forfeited
69
+ * (the inbox — the guaranteed tier — has it regardless). */
70
+ const MAX_SEND_ATTEMPTS = 3;
71
+ /** Backoff between retry attempts, so a transient push-service outage longer
72
+ * than one tick still gets fresh attempts spread over ~15 minutes. */
73
+ const SEND_RETRY_BACKOFF_MS = 5 * 60 * 1000;
74
+ /** Watchdog default: a live root run older than this is flagged as stuck. */
75
+ const DEFAULT_STUCK_THRESHOLD_MS = 45 * 60 * 1000;
76
+
77
+ export function createActivityNotifier(deps: ActivityNotifierDeps): ActivityNotifier {
78
+ const { db, store, isWatched, log } = deps;
79
+ let cursor = latestCursor(db);
80
+ /** Runs already flagged as stuck this process lifetime (tag also guards). */
81
+ const stuckFlagged = new Set<string>();
82
+
83
+ function latestCursor(database: Database): number {
84
+ const row = database
85
+ .query("SELECT COALESCE(MAX(change_id), 0) AS hi FROM activity_changes")
86
+ .get() as { hi: number };
87
+ return row.hi;
88
+ }
89
+
90
+ function createIntent(input: {
91
+ runId: string;
92
+ spanId?: string;
93
+ kind: IntentKind;
94
+ tag: string;
95
+ title: string;
96
+ body: string;
97
+ suppressed?: boolean;
98
+ }): void {
99
+ const now = Date.now();
100
+ // Tag dedupe: one live (unacknowledged) intent per tag — repeats coalesce.
101
+ const existing = db
102
+ .query(
103
+ "SELECT id FROM notification_intents WHERE tag = ? AND acknowledged = 0 LIMIT 1"
104
+ )
105
+ .get(input.tag);
106
+ if (existing) return;
107
+ // Global creation rate cap.
108
+ const recent = db
109
+ .query("SELECT COUNT(*) AS n FROM notification_intents WHERE created_at > ?")
110
+ .get(now - 60 * 60 * 1000) as { n: number };
111
+ const status =
112
+ input.suppressed || recent.n >= MAX_INTENTS_PER_HOUR ? "suppressed" : "pending";
113
+ db.query(
114
+ `INSERT INTO notification_intents
115
+ (run_id, span_id, kind, tag, title, body, status, acknowledged, created_at, updated_at)
116
+ VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?)`
117
+ ).run(
118
+ input.runId,
119
+ input.spanId ?? null,
120
+ input.kind,
121
+ input.tag,
122
+ input.title,
123
+ input.body,
124
+ status,
125
+ now,
126
+ now
127
+ );
128
+ log?.emit({
129
+ severityText: "INFO",
130
+ body: "notification intent created",
131
+ attributes: { kind: input.kind, tag: input.tag, status },
132
+ });
133
+ }
134
+
135
+ function intentForSpan(span: SpanRow): void {
136
+ if (span.parentSpanId) return;
137
+ if (isFailureOutcome(span.outcome)) {
138
+ const label = span.jobName ?? span.name;
139
+ // "Unwatched" is evaluated when the failure is NOTICED — a live
140
+ // subscription to the run or its session means the user saw it happen,
141
+ // so the intent lands acknowledged-free but suppressed for delivery.
142
+ const watched = isWatched({
143
+ runId: span.runId,
144
+ ...(span.sessionId ? { sessionId: span.sessionId } : {}),
145
+ });
146
+ // Payload minimization: name + outcome word only. Lock screens render
147
+ // this outside the app's auth; detail is behind the tap-through.
148
+ createIntent({
149
+ runId: span.runId,
150
+ spanId: span.spanId,
151
+ kind: "failure",
152
+ tag: `failure:${span.jobName ?? span.sessionId ?? span.runId}`,
153
+ title: `${label} ${span.outcome === "interrupted" ? "was interrupted" : "failed"}`,
154
+ body: "Open to see the run.",
155
+ suppressed: watched,
156
+ });
157
+ return;
158
+ }
159
+ if (span.outcome === "success" && span.jobName) {
160
+ // Completion notifications are opt-in per job.
161
+ const optIn = getSetting<string[]>(db, "activity.notify.completions", [], log);
162
+ if (optIn.includes(span.jobName)) {
163
+ createIntent({
164
+ runId: span.runId,
165
+ spanId: span.spanId,
166
+ kind: "completion",
167
+ tag: `completion:${span.jobName}:${span.runId}`,
168
+ title: `${span.jobName} completed`,
169
+ body: "Open to see the run.",
170
+ });
171
+ }
172
+ }
173
+ }
174
+
175
+ return {
176
+ tick(now) {
177
+ try {
178
+ // New committed changes since our own cursor: terminal root spans
179
+ // among them become intents (SQL-side filter + join in the store).
180
+ // The head is read BEFORE the detection query so advancing past
181
+ // non-terminal changes can never skip a terminal write committed
182
+ // in between; a change seen twice is absorbed by the tag dedupe.
183
+ const head = latestCursor(db);
184
+ const rows = store.terminalRootChangesSince(cursor, 500);
185
+ for (const { span } of rows) intentForSpan(span);
186
+ const lastSeen = rows.length > 0 ? rows[rows.length - 1]!.changeId : cursor;
187
+ cursor = rows.length === 500 ? lastSeen : Math.max(head, lastSeen);
188
+
189
+ // Watchdog: an over-threshold LIVE root run is stuck — a signal, not
190
+ // an outcome. Threshold from settings, per-job override supported.
191
+ const defaultThreshold = getSetting<number>(
192
+ db,
193
+ "activity.watchdog.thresholdMs",
194
+ DEFAULT_STUCK_THRESHOLD_MS,
195
+ log
196
+ );
197
+ const overrides = getSetting<Record<string, number>>(
198
+ db,
199
+ "activity.watchdog.perJobMs",
200
+ {},
201
+ log
202
+ );
203
+ // Scan with the SMALLEST effective threshold: findStuck pre-filters
204
+ // by age, so a per-job override below the default would otherwise
205
+ // never see its candidates. The per-span check below still applies
206
+ // each job's own threshold.
207
+ const overrideValues = Object.values(overrides).filter(
208
+ (v): v is number => typeof v === "number" && v > 0
209
+ );
210
+ const scanThreshold = Math.min(defaultThreshold, ...overrideValues);
211
+ for (const span of store.findStuck(scanThreshold, now)) {
212
+ if (stuckFlagged.has(span.runId)) continue;
213
+ const threshold = span.jobName ? (overrides[span.jobName] ?? defaultThreshold) : defaultThreshold;
214
+ if ((now ?? Date.now()) - span.startedAt < threshold) continue;
215
+ stuckFlagged.add(span.runId);
216
+ createIntent({
217
+ runId: span.runId,
218
+ spanId: span.spanId,
219
+ kind: "stuck",
220
+ tag: `stuck:${span.runId}`,
221
+ title: `${span.jobName ?? span.name} is taking unusually long`,
222
+ body: "Still running. Open to check on it.",
223
+ });
224
+ }
225
+ } catch (err) {
226
+ log?.emit({
227
+ severityText: "WARN",
228
+ body: "notifier tick failed",
229
+ attributes: { error: err instanceof Error ? err.message : String(err) },
230
+ });
231
+ }
232
+ },
233
+
234
+ inbox(limit = 50) {
235
+ return (
236
+ db
237
+ .query(
238
+ "SELECT * FROM notification_intents WHERE acknowledged = 0 ORDER BY created_at DESC LIMIT ?"
239
+ )
240
+ .all(limit) as any[]
241
+ ).map(rowToIntent);
242
+ },
243
+
244
+ pending(limit = 20) {
245
+ // Acknowledged means dismissed in the inbox — never push it later.
246
+ // send_failed is retried with backoff until the attempt budget is
247
+ // spent: one transient push-service failure must not forfeit push.
248
+ return (
249
+ db
250
+ .query(
251
+ `SELECT * FROM notification_intents
252
+ WHERE acknowledged = 0
253
+ AND (status = 'pending'
254
+ OR (status = 'send_failed' AND send_attempts < ? AND updated_at < ?))
255
+ ORDER BY created_at LIMIT ?`
256
+ )
257
+ .all(MAX_SEND_ATTEMPTS, Date.now() - SEND_RETRY_BACKOFF_MS, limit) as any[]
258
+ ).map(rowToIntent);
259
+ },
260
+
261
+ markDelivered(id, status) {
262
+ // A failed pass spends one attempt from the retry budget.
263
+ db.query(
264
+ `UPDATE notification_intents
265
+ SET status = ?, updated_at = ?,
266
+ send_attempts = send_attempts + (CASE WHEN ? = 'send_failed' THEN 1 ELSE 0 END)
267
+ WHERE id = ?`
268
+ ).run(status, Date.now(), status, id);
269
+ },
270
+
271
+ acknowledge(id) {
272
+ const res = db
273
+ .query("UPDATE notification_intents SET acknowledged = 1, updated_at = ? WHERE id = ?")
274
+ .run(Date.now(), id);
275
+ return res.changes > 0;
276
+ },
277
+
278
+ acknowledgeAll() {
279
+ const res = db
280
+ .query("UPDATE notification_intents SET acknowledged = 1, updated_at = ? WHERE acknowledged = 0")
281
+ .run(Date.now());
282
+ return res.changes;
283
+ },
284
+
285
+ pruneAcknowledged(olderThanMs) {
286
+ const res = db
287
+ .query("DELETE FROM notification_intents WHERE acknowledged = 1 AND updated_at < ?")
288
+ .run(Date.now() - olderThanMs);
289
+ return res.changes;
290
+ },
291
+ };
292
+ }
293
+
294
+ function rowToIntent(r: any): NotificationIntent {
295
+ return {
296
+ id: r.id,
297
+ runId: r.run_id,
298
+ spanId: r.span_id,
299
+ kind: r.kind,
300
+ tag: r.tag,
301
+ title: r.title,
302
+ body: r.body,
303
+ status: r.status,
304
+ acknowledged: r.acknowledged === 1,
305
+ createdAt: r.created_at,
306
+ };
307
+ }