@schlessera/brain-ui-server 0.17.0 → 0.19.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 (112) hide show
  1. package/README.md +1 -0
  2. package/dist/activity/digest.d.ts +29 -0
  3. package/dist/activity/digest.d.ts.map +1 -0
  4. package/dist/activity/digest.js +61 -0
  5. package/dist/activity/digest.js.map +1 -0
  6. package/dist/activity/notify.d.ts +62 -0
  7. package/dist/activity/notify.d.ts.map +1 -0
  8. package/dist/activity/notify.js +171 -0
  9. package/dist/activity/notify.js.map +1 -0
  10. package/dist/activity/push-sender.d.ts +63 -0
  11. package/dist/activity/push-sender.d.ts.map +1 -0
  12. package/dist/activity/push-sender.js +131 -0
  13. package/dist/activity/push-sender.js.map +1 -0
  14. package/dist/activity/query.d.ts +16 -0
  15. package/dist/activity/query.d.ts.map +1 -0
  16. package/dist/activity/query.js +128 -0
  17. package/dist/activity/query.js.map +1 -0
  18. package/dist/activity/recorder.d.ts +48 -0
  19. package/dist/activity/recorder.d.ts.map +1 -0
  20. package/dist/activity/recorder.js +205 -0
  21. package/dist/activity/recorder.js.map +1 -0
  22. package/dist/activity/runtime.d.ts +31 -0
  23. package/dist/activity/runtime.d.ts.map +1 -0
  24. package/dist/activity/runtime.js +109 -0
  25. package/dist/activity/runtime.js.map +1 -0
  26. package/dist/activity/span-sink.d.ts +22 -0
  27. package/dist/activity/span-sink.d.ts.map +1 -0
  28. package/dist/activity/span-sink.js +138 -0
  29. package/dist/activity/span-sink.js.map +1 -0
  30. package/dist/activity/store.d.ts +207 -0
  31. package/dist/activity/store.d.ts.map +1 -0
  32. package/dist/activity/store.js +440 -0
  33. package/dist/activity/store.js.map +1 -0
  34. package/dist/activity/stream.d.ts +45 -0
  35. package/dist/activity/stream.d.ts.map +1 -0
  36. package/dist/activity/stream.js +312 -0
  37. package/dist/activity/stream.js.map +1 -0
  38. package/dist/app.d.ts.map +1 -1
  39. package/dist/app.js +20 -1
  40. package/dist/app.js.map +1 -1
  41. package/dist/config/env.d.ts +5 -0
  42. package/dist/config/env.d.ts.map +1 -1
  43. package/dist/config/env.js +12 -0
  44. package/dist/config/env.js.map +1 -1
  45. package/dist/cron/scheduler.d.ts.map +1 -1
  46. package/dist/cron/scheduler.js +20 -5
  47. package/dist/cron/scheduler.js.map +1 -1
  48. package/dist/db/client.d.ts.map +1 -1
  49. package/dist/db/client.js +32 -6
  50. package/dist/db/client.js.map +1 -1
  51. package/dist/index.d.ts +4 -0
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +7 -0
  54. package/dist/index.js.map +1 -1
  55. package/dist/routes/activity.d.ts +20 -0
  56. package/dist/routes/activity.d.ts.map +1 -0
  57. package/dist/routes/activity.js +300 -0
  58. package/dist/routes/activity.js.map +1 -0
  59. package/dist/routes/push.d.ts +6 -0
  60. package/dist/routes/push.d.ts.map +1 -0
  61. package/dist/routes/push.js +73 -0
  62. package/dist/routes/push.js.map +1 -0
  63. package/dist/routes/sessions.d.ts.map +1 -1
  64. package/dist/routes/sessions.js +20 -4
  65. package/dist/routes/sessions.js.map +1 -1
  66. package/dist/ws/bridge.d.ts +2 -1
  67. package/dist/ws/bridge.d.ts.map +1 -1
  68. package/dist/ws/bridge.js +45 -3
  69. package/dist/ws/bridge.js.map +1 -1
  70. package/dist/ws/connection.d.ts.map +1 -1
  71. package/dist/ws/connection.js +41 -5
  72. package/dist/ws/connection.js.map +1 -1
  73. package/dist/ws/dispatch.d.ts.map +1 -1
  74. package/dist/ws/dispatch.js +11 -0
  75. package/dist/ws/dispatch.js.map +1 -1
  76. package/dist/ws/host.d.ts +16 -0
  77. package/dist/ws/host.d.ts.map +1 -1
  78. package/dist/ws/host.js +2 -0
  79. package/dist/ws/host.js.map +1 -1
  80. package/dist/ws/run-session.d.ts.map +1 -1
  81. package/dist/ws/run-session.js +25 -1
  82. package/dist/ws/run-session.js.map +1 -1
  83. package/dist/ws/turns.d.ts +22 -2
  84. package/dist/ws/turns.d.ts.map +1 -1
  85. package/dist/ws/turns.js +13 -0
  86. package/dist/ws/turns.js.map +1 -1
  87. package/migrations/007_activity.sql +114 -0
  88. package/migrations/008_push_subscriptions.sql +24 -0
  89. package/package.json +5 -3
  90. package/src/activity/digest.ts +92 -0
  91. package/src/activity/notify.ts +285 -0
  92. package/src/activity/push-sender.ts +215 -0
  93. package/src/activity/query.ts +160 -0
  94. package/src/activity/recorder.ts +261 -0
  95. package/src/activity/runtime.ts +141 -0
  96. package/src/activity/span-sink.ts +152 -0
  97. package/src/activity/store.ts +774 -0
  98. package/src/activity/stream.ts +366 -0
  99. package/src/app.ts +21 -1
  100. package/src/config/env.ts +19 -0
  101. package/src/cron/scheduler.ts +28 -8
  102. package/src/db/client.ts +31 -6
  103. package/src/index.ts +22 -0
  104. package/src/routes/activity.ts +363 -0
  105. package/src/routes/push.ts +90 -0
  106. package/src/routes/sessions.ts +24 -4
  107. package/src/ws/bridge.ts +47 -3
  108. package/src/ws/connection.ts +57 -5
  109. package/src/ws/dispatch.ts +13 -0
  110. package/src/ws/host.ts +18 -0
  111. package/src/ws/run-session.ts +32 -1
  112. package/src/ws/turns.ts +29 -1
@@ -0,0 +1,114 @@
1
+ -- Agent activity record: one span per unit of agent activity (turn, tool
2
+ -- call, subagent run, cron run), forming a tree per run. Current state lives
3
+ -- in activity_spans; append-only transcript/progress increments live in
4
+ -- activity_events; every committed write also lands one row in
5
+ -- activity_changes, which is BOTH the global change cursor (change_id, for
6
+ -- the server's foreign-write poller) and the per-run sequence authority
7
+ -- (seq, for the client's snapshot-then-delta discard rule).
8
+ --
9
+ -- Outcome is write-once: 'interrupted' is assigned only by a sweeper, never
10
+ -- by a live writer. last_heartbeat_at is touched by external writers (the
11
+ -- cron wrapper) so staleness is judged on heartbeat age, not span age.
12
+ CREATE TABLE IF NOT EXISTS activity_spans (
13
+ span_id TEXT PRIMARY KEY,
14
+ run_id TEXT NOT NULL,
15
+ parent_span_id TEXT,
16
+ name TEXT NOT NULL,
17
+ kind TEXT NOT NULL CHECK (kind IN ('turn', 'tool', 'subagent', 'cron')),
18
+ origin TEXT NOT NULL CHECK (origin IN ('session', 'cron')),
19
+ session_id TEXT,
20
+ job_name TEXT,
21
+ attrs TEXT,
22
+ started_at INTEGER NOT NULL,
23
+ wait_until INTEGER,
24
+ ended_at INTEGER,
25
+ outcome TEXT CHECK (outcome IN ('success', 'error', 'timeout', 'cancelled', 'denied', 'interrupted')),
26
+ outcome_reason TEXT,
27
+ input_tokens INTEGER,
28
+ output_tokens INTEGER,
29
+ cache_read_tokens INTEGER,
30
+ cache_creation_tokens INTEGER,
31
+ cost_usd REAL,
32
+ model TEXT,
33
+ writer TEXT NOT NULL,
34
+ last_heartbeat_at INTEGER
35
+ );
36
+
37
+ CREATE INDEX IF NOT EXISTS idx_activity_spans_run ON activity_spans(run_id, started_at);
38
+ CREATE INDEX IF NOT EXISTS idx_activity_spans_open ON activity_spans(started_at DESC) WHERE outcome IS NULL AND parent_span_id IS NULL;
39
+ CREATE INDEX IF NOT EXISTS idx_activity_spans_session ON activity_spans(session_id, started_at DESC) WHERE session_id IS NOT NULL;
40
+ CREATE INDEX IF NOT EXISTS idx_activity_spans_job ON activity_spans(job_name, started_at DESC) WHERE job_name IS NOT NULL;
41
+
42
+ -- Append-only span events (subagent transcript excerpts, progress notes).
43
+ -- Payloads are capped at persist time (stored truncation marker) so a single
44
+ -- WS delta can never approach the frame size cap.
45
+ CREATE TABLE IF NOT EXISTS activity_events (
46
+ span_id TEXT NOT NULL,
47
+ event_index INTEGER NOT NULL,
48
+ ts INTEGER NOT NULL,
49
+ event_type TEXT NOT NULL,
50
+ payload TEXT,
51
+ PRIMARY KEY (span_id, event_index)
52
+ );
53
+
54
+ -- Change log: one row per committed write. change_id is the global monotonic
55
+ -- cursor (a brand-new foreign run is discoverable only through this); seq is
56
+ -- per-run monotonic and totally orders every delta-visible write within a
57
+ -- run. event_index is NULL for span-state changes.
58
+ CREATE TABLE IF NOT EXISTS activity_changes (
59
+ change_id INTEGER PRIMARY KEY AUTOINCREMENT,
60
+ run_id TEXT NOT NULL,
61
+ seq INTEGER NOT NULL,
62
+ span_id TEXT NOT NULL,
63
+ event_index INTEGER
64
+ );
65
+
66
+ CREATE INDEX IF NOT EXISTS idx_activity_changes_run ON activity_changes(run_id, seq);
67
+
68
+ -- Per-run rollups survive span pruning forever: any run id that ever existed
69
+ -- resolves to at least this row ("detail pruned"), and cost/token aggregation
70
+ -- reads ROOT rollups only (subagent usage is display-only enrichment —
71
+ -- result-level accounting already includes subagent consumption).
72
+ CREATE TABLE IF NOT EXISTS activity_run_rollups (
73
+ run_id TEXT PRIMARY KEY,
74
+ origin TEXT NOT NULL,
75
+ name TEXT NOT NULL,
76
+ session_id TEXT,
77
+ job_name TEXT,
78
+ started_at INTEGER NOT NULL,
79
+ ended_at INTEGER,
80
+ outcome TEXT,
81
+ duration_ms INTEGER,
82
+ span_count INTEGER NOT NULL DEFAULT 0,
83
+ input_tokens INTEGER,
84
+ output_tokens INTEGER,
85
+ cache_read_tokens INTEGER,
86
+ cache_creation_tokens INTEGER,
87
+ cost_usd REAL,
88
+ failure_reason TEXT,
89
+ detail_pruned INTEGER NOT NULL DEFAULT 0
90
+ );
91
+
92
+ CREATE INDEX IF NOT EXISTS idx_activity_rollups_started ON activity_run_rollups(started_at DESC);
93
+ CREATE INDEX IF NOT EXISTS idx_activity_rollups_job ON activity_run_rollups(job_name, started_at DESC) WHERE job_name IS NOT NULL;
94
+
95
+ -- Notification intents: persisted with the triggering event so delivery is
96
+ -- at-least-once (pending rows are swept on boot). status transitions:
97
+ -- pending -> sent | send_failed | suppressed. tag deduplicates per run so
98
+ -- repeats coalesce instead of stacking.
99
+ CREATE TABLE IF NOT EXISTS notification_intents (
100
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
101
+ run_id TEXT NOT NULL,
102
+ span_id TEXT,
103
+ kind TEXT NOT NULL CHECK (kind IN ('failure', 'completion', 'stuck')),
104
+ tag TEXT NOT NULL,
105
+ title TEXT NOT NULL,
106
+ body TEXT NOT NULL,
107
+ status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'sent', 'send_failed', 'suppressed')),
108
+ acknowledged INTEGER NOT NULL DEFAULT 0,
109
+ created_at INTEGER NOT NULL,
110
+ updated_at INTEGER NOT NULL
111
+ );
112
+
113
+ CREATE INDEX IF NOT EXISTS idx_notification_intents_status ON notification_intents(status, created_at);
114
+ CREATE INDEX IF NOT EXISTS idx_notification_intents_tag ON notification_intents(tag, created_at DESC);
@@ -0,0 +1,24 @@
1
+ -- Web push: per-device subscriptions, modeled on passkey_credentials (the
2
+ -- app is single-user — no user_id column; a row IS a device+browser).
3
+ -- Endpoints are unique; a 404/410 on send prunes the row.
4
+ CREATE TABLE IF NOT EXISTS push_subscriptions (
5
+ endpoint TEXT PRIMARY KEY,
6
+ p256dh TEXT NOT NULL,
7
+ auth TEXT NOT NULL,
8
+ label TEXT,
9
+ created_at INTEGER NOT NULL,
10
+ last_used_at INTEGER
11
+ );
12
+
13
+ -- The VAPID keypair, generated at first boot. DELIBERATELY its own table,
14
+ -- not a settings-KV row: settings are non-secret preferences that a future
15
+ -- list/export route may expose wholesale, while this private key must never
16
+ -- ride along (a leak lets an attacker send authentic push to the user's
17
+ -- device). Nothing may ever add a route that reads this table's private_key
18
+ -- out of the process.
19
+ CREATE TABLE IF NOT EXISTS vapid_keys (
20
+ id INTEGER PRIMARY KEY CHECK (id = 1),
21
+ public_key TEXT NOT NULL,
22
+ private_key TEXT NOT NULL,
23
+ created_at INTEGER NOT NULL
24
+ );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@schlessera/brain-ui-server",
3
- "version": "0.17.0",
3
+ "version": "0.19.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": [
@@ -48,11 +48,12 @@
48
48
  "dependencies": {
49
49
  "@opentelemetry/api": "^1.9.1",
50
50
  "@opentelemetry/api-logs": "0.221.0",
51
- "@schlessera/brain-render-template": "0.17.0",
52
- "@schlessera/brain-ui-sdk": "0.17.0",
51
+ "@schlessera/brain-render-template": "0.19.0",
52
+ "@schlessera/brain-ui-sdk": "0.19.0",
53
53
  "@simplewebauthn/server": "^13.3.2",
54
54
  "hono": "^4",
55
55
  "ignore": "^7.0.5",
56
+ "web-push": "^3.6.7",
56
57
  "zod": "^4.4.3"
57
58
  },
58
59
  "peerDependencies": {
@@ -73,6 +74,7 @@
73
74
  },
74
75
  "devDependencies": {
75
76
  "@types/bun": "^1.3.14",
77
+ "@types/web-push": "^3.6.4",
76
78
  "typescript": "^6.0.3"
77
79
  }
78
80
  }
@@ -0,0 +1,92 @@
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 } 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
+ const covered = getSetting<number | null>(db, DIGEST_COVERED_KEY, null);
33
+ const windowStart = covered ?? now - FIRST_WINDOW_MS;
34
+
35
+ // Windowed on ended_at, not started_at: every FINISHED run gets
36
+ // exactly-once coverage — a run still open at generation is picked up by
37
+ // the NEXT digest once it ends, instead of falling between windows.
38
+ const rows = (
39
+ db
40
+ .query(
41
+ `SELECT * FROM activity_run_rollups
42
+ WHERE ended_at IS NOT NULL AND ended_at >= ? AND ended_at < ?
43
+ ORDER BY started_at DESC`
44
+ )
45
+ .all(windowStart, now) as any[]
46
+ ).map(rowToRunRollup);
47
+
48
+ const relevant = rows.filter((r) => r.jobName !== DIGEST_JOB_NAME);
49
+ const failures = relevant.filter((r) => isFailureOutcome(r.outcome));
50
+
51
+ const digest: ActivityDigest = {
52
+ generatedAt: now,
53
+ windowStart,
54
+ windowEnd: now,
55
+ runs: relevant.length,
56
+ failures: failures.length,
57
+ costUsd: relevant.reduce((a, r) => a + (r.costUsd ?? 0), 0),
58
+ inputTokens: relevant.reduce((a, r) => a + (r.inputTokens ?? 0), 0),
59
+ outputTokens: relevant.reduce((a, r) => a + (r.outputTokens ?? 0), 0),
60
+ notable: failures.slice(0, 10).map((r) => ({
61
+ runId: r.runId,
62
+ name: r.name,
63
+ jobName: r.jobName,
64
+ sessionId: r.sessionId,
65
+ outcome: r.outcome,
66
+ failureReason: r.failureReason,
67
+ startedAt: r.startedAt,
68
+ })),
69
+ };
70
+
71
+ setSetting(db, DIGEST_LATEST_KEY, digest);
72
+ setSetting(db, DIGEST_COVERED_KEY, now);
73
+ return digest;
74
+ }
75
+
76
+ /** The latest digest, or null before the first run. */
77
+ export function latestActivityDigest(db: Database): ActivityDigest | null {
78
+ return getSetting<ActivityDigest | null>(db, DIGEST_LATEST_KEY, null);
79
+ }
80
+
81
+ /** The retention floor: never prune spans the digest has not covered. */
82
+ export function digestRetentionFloor(db: Database): number {
83
+ return getSetting<number>(db, DIGEST_COVERED_KEY, 0);
84
+ }
85
+
86
+ export function dismissActivityDigest(db: Database, at = Date.now()): void {
87
+ setSetting(db, DIGEST_DISMISSED_KEY, at);
88
+ }
89
+
90
+ export function digestDismissedAt(db: Database): number {
91
+ return getSetting<number>(db, DIGEST_DISMISSED_KEY, 0);
92
+ }
@@ -0,0 +1,285 @@
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
+ /** Watchdog default: a live root run older than this is flagged as stuck. */
69
+ const DEFAULT_STUCK_THRESHOLD_MS = 45 * 60 * 1000;
70
+
71
+ export function createActivityNotifier(deps: ActivityNotifierDeps): ActivityNotifier {
72
+ const { db, store, isWatched, log } = deps;
73
+ let cursor = latestCursor(db);
74
+ /** Runs already flagged as stuck this process lifetime (tag also guards). */
75
+ const stuckFlagged = new Set<string>();
76
+
77
+ function latestCursor(database: Database): number {
78
+ const row = database
79
+ .query("SELECT COALESCE(MAX(change_id), 0) AS hi FROM activity_changes")
80
+ .get() as { hi: number };
81
+ return row.hi;
82
+ }
83
+
84
+ function createIntent(input: {
85
+ runId: string;
86
+ spanId?: string;
87
+ kind: IntentKind;
88
+ tag: string;
89
+ title: string;
90
+ body: string;
91
+ suppressed?: boolean;
92
+ }): void {
93
+ const now = Date.now();
94
+ // Tag dedupe: one live (unacknowledged) intent per tag — repeats coalesce.
95
+ const existing = db
96
+ .query(
97
+ "SELECT id FROM notification_intents WHERE tag = ? AND acknowledged = 0 LIMIT 1"
98
+ )
99
+ .get(input.tag);
100
+ if (existing) return;
101
+ // Global creation rate cap.
102
+ const recent = db
103
+ .query("SELECT COUNT(*) AS n FROM notification_intents WHERE created_at > ?")
104
+ .get(now - 60 * 60 * 1000) as { n: number };
105
+ const status =
106
+ input.suppressed || recent.n >= MAX_INTENTS_PER_HOUR ? "suppressed" : "pending";
107
+ db.query(
108
+ `INSERT INTO notification_intents
109
+ (run_id, span_id, kind, tag, title, body, status, acknowledged, created_at, updated_at)
110
+ VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?)`
111
+ ).run(
112
+ input.runId,
113
+ input.spanId ?? null,
114
+ input.kind,
115
+ input.tag,
116
+ input.title,
117
+ input.body,
118
+ status,
119
+ now,
120
+ now
121
+ );
122
+ log?.emit({
123
+ severityText: "INFO",
124
+ body: "notification intent created",
125
+ attributes: { kind: input.kind, tag: input.tag, status },
126
+ });
127
+ }
128
+
129
+ function intentForSpan(span: SpanRow): void {
130
+ if (span.parentSpanId) return;
131
+ if (isFailureOutcome(span.outcome)) {
132
+ const label = span.jobName ?? span.name;
133
+ // "Unwatched" is evaluated when the failure is NOTICED — a live
134
+ // subscription to the run or its session means the user saw it happen,
135
+ // so the intent lands acknowledged-free but suppressed for delivery.
136
+ const watched = isWatched({
137
+ runId: span.runId,
138
+ ...(span.sessionId ? { sessionId: span.sessionId } : {}),
139
+ });
140
+ // Payload minimization: name + outcome word only. Lock screens render
141
+ // this outside the app's auth; detail is behind the tap-through.
142
+ createIntent({
143
+ runId: span.runId,
144
+ spanId: span.spanId,
145
+ kind: "failure",
146
+ tag: `failure:${span.jobName ?? span.sessionId ?? span.runId}`,
147
+ title: `${label} ${span.outcome === "interrupted" ? "was interrupted" : "failed"}`,
148
+ body: "Open to see the run.",
149
+ suppressed: watched,
150
+ });
151
+ return;
152
+ }
153
+ if (span.outcome === "success" && span.jobName) {
154
+ // Completion notifications are opt-in per job.
155
+ const optIn = getSetting<string[]>(db, "activity.notify.completions", [], log);
156
+ if (optIn.includes(span.jobName)) {
157
+ createIntent({
158
+ runId: span.runId,
159
+ spanId: span.spanId,
160
+ kind: "completion",
161
+ tag: `completion:${span.jobName}:${span.runId}`,
162
+ title: `${span.jobName} completed`,
163
+ body: "Open to see the run.",
164
+ });
165
+ }
166
+ }
167
+ }
168
+
169
+ return {
170
+ tick(now) {
171
+ try {
172
+ // New committed changes since our own cursor: terminal root spans
173
+ // among them become intents (SQL-side filter + join in the store).
174
+ // The head is read BEFORE the detection query so advancing past
175
+ // non-terminal changes can never skip a terminal write committed
176
+ // in between; a change seen twice is absorbed by the tag dedupe.
177
+ const head = latestCursor(db);
178
+ const rows = store.terminalRootChangesSince(cursor, 500);
179
+ for (const { span } of rows) intentForSpan(span);
180
+ const lastSeen = rows.length > 0 ? rows[rows.length - 1]!.changeId : cursor;
181
+ cursor = rows.length === 500 ? lastSeen : Math.max(head, lastSeen);
182
+
183
+ // Watchdog: an over-threshold LIVE root run is stuck — a signal, not
184
+ // an outcome. Threshold from settings, per-job override supported.
185
+ const defaultThreshold = getSetting<number>(
186
+ db,
187
+ "activity.watchdog.thresholdMs",
188
+ DEFAULT_STUCK_THRESHOLD_MS,
189
+ log
190
+ );
191
+ const overrides = getSetting<Record<string, number>>(
192
+ db,
193
+ "activity.watchdog.perJobMs",
194
+ {},
195
+ log
196
+ );
197
+ for (const span of store.findStuck(defaultThreshold, now)) {
198
+ if (stuckFlagged.has(span.runId)) continue;
199
+ const threshold = span.jobName ? (overrides[span.jobName] ?? defaultThreshold) : defaultThreshold;
200
+ if ((now ?? Date.now()) - span.startedAt < threshold) continue;
201
+ stuckFlagged.add(span.runId);
202
+ createIntent({
203
+ runId: span.runId,
204
+ spanId: span.spanId,
205
+ kind: "stuck",
206
+ tag: `stuck:${span.runId}`,
207
+ title: `${span.jobName ?? span.name} is taking unusually long`,
208
+ body: "Still running. Open to check on it.",
209
+ });
210
+ }
211
+ } catch (err) {
212
+ log?.emit({
213
+ severityText: "WARN",
214
+ body: "notifier tick failed",
215
+ attributes: { error: err instanceof Error ? err.message : String(err) },
216
+ });
217
+ }
218
+ },
219
+
220
+ inbox(limit = 50) {
221
+ return (
222
+ db
223
+ .query(
224
+ "SELECT * FROM notification_intents WHERE acknowledged = 0 ORDER BY created_at DESC LIMIT ?"
225
+ )
226
+ .all(limit) as any[]
227
+ ).map(rowToIntent);
228
+ },
229
+
230
+ pending(limit = 20) {
231
+ // Acknowledged means dismissed in the inbox — never push it later.
232
+ return (
233
+ db
234
+ .query(
235
+ "SELECT * FROM notification_intents WHERE status = 'pending' AND acknowledged = 0 ORDER BY created_at LIMIT ?"
236
+ )
237
+ .all(limit) as any[]
238
+ ).map(rowToIntent);
239
+ },
240
+
241
+ markDelivered(id, status) {
242
+ db.query("UPDATE notification_intents SET status = ?, updated_at = ? WHERE id = ?").run(
243
+ status,
244
+ Date.now(),
245
+ id
246
+ );
247
+ },
248
+
249
+ acknowledge(id) {
250
+ const res = db
251
+ .query("UPDATE notification_intents SET acknowledged = 1, updated_at = ? WHERE id = ?")
252
+ .run(Date.now(), id);
253
+ return res.changes > 0;
254
+ },
255
+
256
+ acknowledgeAll() {
257
+ const res = db
258
+ .query("UPDATE notification_intents SET acknowledged = 1, updated_at = ? WHERE acknowledged = 0")
259
+ .run(Date.now());
260
+ return res.changes;
261
+ },
262
+
263
+ pruneAcknowledged(olderThanMs) {
264
+ const res = db
265
+ .query("DELETE FROM notification_intents WHERE acknowledged = 1 AND updated_at < ?")
266
+ .run(Date.now() - olderThanMs);
267
+ return res.changes;
268
+ },
269
+ };
270
+ }
271
+
272
+ function rowToIntent(r: any): NotificationIntent {
273
+ return {
274
+ id: r.id,
275
+ runId: r.run_id,
276
+ spanId: r.span_id,
277
+ kind: r.kind,
278
+ tag: r.tag,
279
+ title: r.title,
280
+ body: r.body,
281
+ status: r.status,
282
+ acknowledged: r.acknowledged === 1,
283
+ createdAt: r.created_at,
284
+ };
285
+ }