@vellumai/assistant 0.9.0-dev.202606182256.609733d → 0.9.0-dev.202606190120.2d51b8d

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.9.0-dev.202606182256.609733d",
3
+ "version": "0.9.0-dev.202606190120.2d51b8d",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -25,12 +25,15 @@ import {
25
25
  type CanonicalGuardianRequest,
26
26
  createCanonicalGuardianDelivery,
27
27
  createCanonicalGuardianRequest,
28
+ getPendingCanonicalRequestByDestinationMessage,
28
29
  listCanonicalGuardianDeliveries,
29
30
  } from "../memory/canonical-guardian-store.js";
30
31
  import { getDb } from "../memory/db-connection.js";
31
32
  import { initializeDb } from "../memory/db-init.js";
32
- import { recordCanonicalChannelDelivery } from "../notifications/canonical-delivery-recorder.js";
33
- import type { NotificationDeliveryResult } from "../notifications/types.js";
33
+ import {
34
+ recordApprovalCardDelivery,
35
+ recordGuardianRequestDeliveries,
36
+ } from "../notifications/canonical-delivery-recorder.js";
34
37
 
35
38
  initializeDb();
36
39
 
@@ -232,28 +235,161 @@ describe("withdrawGuardianRequestCards", () => {
232
235
  });
233
236
  });
234
237
 
235
- describe("recordCanonicalChannelDelivery", () => {
238
+ describe("recordApprovalCardDelivery", () => {
236
239
  beforeEach(() => {
237
240
  resetTables();
238
- withdrawSlackApprovalCard.mockClear();
239
241
  });
240
242
 
241
- test("captures the channel-native message id so the card can be withdrawn", async () => {
243
+ test("records a channel card with its addressing and status", () => {
242
244
  const req = makeRequest();
243
- const result: NotificationDeliveryResult = {
245
+ const delivery = recordApprovalCardDelivery({
246
+ requestId: req.id,
247
+ channel: "slack",
248
+ chatId: "C1",
249
+ messageId: "1700000000.0001",
250
+ status: "sent",
251
+ });
252
+ expect(delivery?.destinationChannel).toBe("slack");
253
+ expect(delivery?.destinationChatId).toBe("C1");
254
+ expect(delivery?.destinationMessageId).toBe("1700000000.0001");
255
+ expect(delivery?.status).toBe("sent");
256
+ });
257
+
258
+ test("records a vellum card addressed by conversation id, defaulting to pending", () => {
259
+ const req = makeRequest();
260
+ const delivery = recordApprovalCardDelivery({
261
+ requestId: req.id,
262
+ channel: "vellum",
263
+ conversationId: "conv-x",
264
+ });
265
+ expect(delivery?.destinationConversationId).toBe("conv-x");
266
+ expect(delivery?.destinationChatId).toBeNull();
267
+ expect(delivery?.status).toBe("pending");
268
+ });
269
+
270
+ test("lets a Slack reaction resolve back to its request (LUM-2502)", () => {
271
+ // A delivered Slack approval card must be addressable by (channel, chat, ts)
272
+ // so an emoji reaction on it resolves to the right request rather than
273
+ // silently falling through to transcript persistence.
274
+ const req = makeRequest();
275
+ recordApprovalCardDelivery({
276
+ requestId: req.id,
244
277
  channel: "slack",
245
- destination: "C999",
278
+ chatId: "C-guardian",
279
+ messageId: "1700000000.5678",
246
280
  status: "sent",
247
- messageId: "1700000000.1234",
248
- };
281
+ });
282
+
283
+ const resolved = getPendingCanonicalRequestByDestinationMessage(
284
+ "slack",
285
+ "C-guardian",
286
+ "1700000000.5678",
287
+ );
288
+ expect(resolved?.id).toBe(req.id);
289
+ });
290
+ });
291
+
292
+ describe("recordGuardianRequestDeliveries", () => {
293
+ beforeEach(() => {
294
+ resetTables();
295
+ withdrawSlackApprovalCard.mockClear();
296
+ });
297
+
298
+ test("records each delivery with addressing + status and returns the vellum id", () => {
299
+ const req = makeRequest();
300
+ const vellumId = recordGuardianRequestDeliveries({
301
+ requestId: req.id,
302
+ deliveryResults: [
303
+ {
304
+ channel: "vellum",
305
+ destination: "",
306
+ status: "sent",
307
+ conversationId: "conv-1",
308
+ },
309
+ {
310
+ channel: "slack",
311
+ destination: "C999",
312
+ status: "sent",
313
+ messageId: "1700000000.1234",
314
+ },
315
+ ],
316
+ });
317
+
318
+ const deliveries = listCanonicalGuardianDeliveries(req.id);
319
+ expect(deliveries).toHaveLength(2);
320
+ const vellum = deliveries.find((d) => d.destinationChannel === "vellum");
321
+ const slack = deliveries.find((d) => d.destinationChannel === "slack");
322
+ expect(vellumId).toBe(vellum?.id);
323
+ expect(vellum?.destinationConversationId).toBe("conv-1");
324
+ expect(vellum?.status).toBe("sent");
325
+ expect(slack?.destinationChatId).toBe("C999");
326
+ expect(slack?.destinationMessageId).toBe("1700000000.1234");
327
+ expect(slack?.status).toBe("sent");
328
+ });
329
+
330
+ test("reuses a pre-created vellum row instead of creating a second", () => {
331
+ const req = makeRequest();
332
+ const pre = recordApprovalCardDelivery({
333
+ requestId: req.id,
334
+ channel: "vellum",
335
+ conversationId: "conv-1",
336
+ });
337
+
338
+ const vellumId = recordGuardianRequestDeliveries({
339
+ requestId: req.id,
340
+ deliveryResults: [
341
+ {
342
+ channel: "vellum",
343
+ destination: "",
344
+ status: "sent",
345
+ conversationId: "conv-1",
346
+ },
347
+ ],
348
+ vellumDeliveryId: pre?.id,
349
+ });
350
+
351
+ expect(vellumId).toBe(pre?.id);
352
+ const deliveries = listCanonicalGuardianDeliveries(req.id);
353
+ expect(deliveries).toHaveLength(1);
354
+ expect(deliveries[0].status).toBe("sent");
355
+ });
356
+
357
+ test("marks a non-sent delivery result as failed (status now tracked for all producers)", () => {
358
+ const req = makeRequest();
359
+ recordGuardianRequestDeliveries({
360
+ requestId: req.id,
361
+ deliveryResults: [
362
+ { channel: "slack", destination: "C1", status: "failed" },
363
+ ],
364
+ });
365
+ const [delivery] = listCanonicalGuardianDeliveries(req.id);
366
+ expect(delivery.status).toBe("failed");
367
+ });
249
368
 
250
- const delivery = recordCanonicalChannelDelivery(req.id, result);
369
+ test("omits chat id when the channel destination is empty", () => {
370
+ const req = makeRequest();
371
+ recordGuardianRequestDeliveries({
372
+ requestId: req.id,
373
+ deliveryResults: [{ channel: "slack", destination: "", status: "sent" }],
374
+ });
375
+ const [delivery] = listCanonicalGuardianDeliveries(req.id);
376
+ expect(delivery.destinationChatId).toBeNull();
377
+ });
251
378
 
252
- expect(delivery.destinationChannel).toBe("slack");
253
- expect(delivery.destinationChatId).toBe("C999");
254
- expect(delivery.destinationMessageId).toBe("1700000000.1234");
379
+ test("records a Slack delivery the withdrawal path can then edit in place", async () => {
380
+ const req = makeRequest();
381
+ recordGuardianRequestDeliveries({
382
+ requestId: req.id,
383
+ deliveryResults: [
384
+ {
385
+ channel: "slack",
386
+ destination: "C999",
387
+ status: "sent",
388
+ messageId: "1700000000.1234",
389
+ },
390
+ ],
391
+ });
255
392
 
256
- // End-to-end: the recorded delivery is now editable by the withdrawal path.
257
393
  await withdrawGuardianRequestCards({
258
394
  request: req,
259
395
  status: "approved",
@@ -264,15 +400,4 @@ describe("recordCanonicalChannelDelivery", () => {
264
400
  "1700000000.1234",
265
401
  );
266
402
  });
267
-
268
- test("omits chat id when the destination is empty", () => {
269
- const req = makeRequest();
270
- const delivery = recordCanonicalChannelDelivery(req.id, {
271
- channel: "slack",
272
- destination: "",
273
- status: "sent",
274
- });
275
- expect(delivery.destinationChatId).toBeNull();
276
- expect(listCanonicalGuardianDeliveries(req.id)).toHaveLength(1);
277
- });
278
403
  });
@@ -0,0 +1,118 @@
1
+ import { beforeEach, describe, expect, mock, test } from "bun:test";
2
+
3
+ // ---------------------------------------------------------------------------
4
+ // Mock state
5
+ // ---------------------------------------------------------------------------
6
+
7
+ const existsSyncFn = mock((_path: string): boolean => false);
8
+ const readFileSyncFn = mock((_path: string, _encoding: string): string => "");
9
+ const writeFileSyncFn = mock((_path: string, _data: string): void => undefined);
10
+
11
+ // ---------------------------------------------------------------------------
12
+ // Mock modules — before importing module under test
13
+ // ---------------------------------------------------------------------------
14
+
15
+ mock.module("node:fs", () => ({
16
+ existsSync: existsSyncFn,
17
+ readFileSync: readFileSyncFn,
18
+ writeFileSync: writeFileSyncFn,
19
+ }));
20
+
21
+ // Import after mocking
22
+ import { dropSendDiagnosticsMigration } from "../workspace/migrations/107-drop-send-diagnostics.js";
23
+
24
+ // ---------------------------------------------------------------------------
25
+ // Helpers
26
+ // ---------------------------------------------------------------------------
27
+
28
+ const WORKSPACE_DIR = "/tmp/test-workspace";
29
+ const CONFIG_PATH = `${WORKSPACE_DIR}/config.json`;
30
+
31
+ function setupConfigExists(config: unknown) {
32
+ existsSyncFn.mockImplementation((path: string) => path === CONFIG_PATH);
33
+ readFileSyncFn.mockImplementation(() => JSON.stringify(config));
34
+ }
35
+
36
+ function getWrittenConfig(): Record<string, unknown> {
37
+ expect(writeFileSyncFn).toHaveBeenCalledTimes(1);
38
+ const [path, data] = writeFileSyncFn.mock.calls[0] as [string, string];
39
+ expect(path).toBe(CONFIG_PATH);
40
+ return JSON.parse(data) as Record<string, unknown>;
41
+ }
42
+
43
+ // ---------------------------------------------------------------------------
44
+ // Tests
45
+ // ---------------------------------------------------------------------------
46
+
47
+ describe("107-drop-send-diagnostics migration", () => {
48
+ beforeEach(() => {
49
+ existsSyncFn.mockClear();
50
+ readFileSyncFn.mockClear();
51
+ writeFileSyncFn.mockClear();
52
+ });
53
+
54
+ test("no-op when config.json is absent", () => {
55
+ existsSyncFn.mockImplementation(() => false);
56
+
57
+ dropSendDiagnosticsMigration.run(WORKSPACE_DIR);
58
+
59
+ expect(readFileSyncFn).not.toHaveBeenCalled();
60
+ expect(writeFileSyncFn).not.toHaveBeenCalled();
61
+ });
62
+
63
+ test("explicit opt-out is preserved as legacyDiagnosticsOptOut", () => {
64
+ setupConfigExists({ sendDiagnostics: false, someSetting: "value" });
65
+
66
+ dropSendDiagnosticsMigration.run(WORKSPACE_DIR);
67
+
68
+ const written = getWrittenConfig();
69
+ expect(written.sendDiagnostics).toBeUndefined();
70
+ expect(written.legacyDiagnosticsOptOut).toBe(true);
71
+ expect(written.someSetting).toBe("value");
72
+ });
73
+
74
+ test("sendDiagnostics: true is removed without setting the marker", () => {
75
+ setupConfigExists({ sendDiagnostics: true });
76
+
77
+ dropSendDiagnosticsMigration.run(WORKSPACE_DIR);
78
+
79
+ const written = getWrittenConfig();
80
+ expect(written.sendDiagnostics).toBeUndefined();
81
+ expect(written.legacyDiagnosticsOptOut).toBeUndefined();
82
+ });
83
+
84
+ test("non-false value is removed without setting the marker", () => {
85
+ setupConfigExists({ sendDiagnostics: "yes" });
86
+
87
+ dropSendDiagnosticsMigration.run(WORKSPACE_DIR);
88
+
89
+ const written = getWrittenConfig();
90
+ expect(written.sendDiagnostics).toBeUndefined();
91
+ expect(written.legacyDiagnosticsOptOut).toBeUndefined();
92
+ });
93
+
94
+ test("no-op when sendDiagnostics is absent (no marker)", () => {
95
+ setupConfigExists({ someSetting: "value" });
96
+
97
+ dropSendDiagnosticsMigration.run(WORKSPACE_DIR);
98
+
99
+ expect(writeFileSyncFn).not.toHaveBeenCalled();
100
+ });
101
+
102
+ test("malformed config is handled gracefully", () => {
103
+ existsSyncFn.mockImplementation((path: string) => path === CONFIG_PATH);
104
+ readFileSyncFn.mockImplementation(() => "not valid json {{{");
105
+
106
+ dropSendDiagnosticsMigration.run(WORKSPACE_DIR);
107
+
108
+ expect(writeFileSyncFn).not.toHaveBeenCalled();
109
+ });
110
+
111
+ test("no-op when config is an array", () => {
112
+ setupConfigExists([1, 2, 3]);
113
+
114
+ dropSendDiagnosticsMigration.run(WORKSPACE_DIR);
115
+
116
+ expect(writeFileSyncFn).not.toHaveBeenCalled();
117
+ });
118
+ });
@@ -9,15 +9,15 @@
9
9
 
10
10
  import { findGuardianForChannel } from "../contacts/contact-store.js";
11
11
  import {
12
- createCanonicalGuardianDelivery,
13
12
  createCanonicalGuardianRequest,
14
13
  listCanonicalGuardianDeliveries,
15
14
  listCanonicalGuardianRequests,
16
- updateCanonicalGuardianDelivery,
17
15
  } from "../memory/canonical-guardian-store.js";
18
- import { recordCanonicalChannelDelivery } from "../notifications/canonical-delivery-recorder.js";
16
+ import {
17
+ recordApprovalCardDelivery,
18
+ recordGuardianRequestDeliveries,
19
+ } from "../notifications/canonical-delivery-recorder.js";
19
20
  import { emitNotificationSignal } from "../notifications/emit-signal.js";
20
- import type { NotificationDeliveryResult } from "../notifications/types.js";
21
21
  import { getLogger } from "../util/logger.js";
22
22
  import { getUserConsultationTimeoutMs } from "./call-constants.js";
23
23
  import type { CallPendingQuestion } from "./types.js";
@@ -40,17 +40,6 @@ export interface GuardianDispatchParams {
40
40
  inputDigest?: string;
41
41
  }
42
42
 
43
- function applyDeliveryStatus(
44
- deliveryId: string,
45
- result: NotificationDeliveryResult,
46
- ): void {
47
- if (result.status === "sent") {
48
- updateCanonicalGuardianDelivery(deliveryId, { status: "sent" });
49
- return;
50
- }
51
- updateCanonicalGuardianDelivery(deliveryId, { status: "failed" });
52
- }
53
-
54
43
  /**
55
44
  * Dispatch a guardian action request to all configured channels.
56
45
  * Fire-and-forget: errors are logged but do not propagate.
@@ -180,7 +169,7 @@ async function dispatchGuardianQuestionInner(
180
169
 
181
170
  // Route through the canonical notification pipeline. The paired vellum
182
171
  // conversation from this pipeline is the canonical guardian conversation.
183
- let vellumDeliveryId: string | null = null;
172
+ let vellumDeliveryId: string | undefined;
184
173
  const requestCode =
185
174
  request.requestCode ?? request.id.slice(0, 6).toUpperCase();
186
175
  const signalResult = await emitNotificationSignal({
@@ -209,39 +198,26 @@ async function dispatchGuardianQuestionInner(
209
198
  onConversationCreated: (info) => {
210
199
  if (info.sourceEventName !== "guardian.question" || vellumDeliveryId)
211
200
  return;
212
- const delivery = createCanonicalGuardianDelivery({
201
+ vellumDeliveryId = recordApprovalCardDelivery({
213
202
  requestId: request.id,
214
- destinationChannel: "vellum",
215
- destinationConversationId: info.conversationId,
216
- });
217
- vellumDeliveryId = delivery.id;
203
+ channel: "vellum",
204
+ conversationId: info.conversationId,
205
+ })?.id;
218
206
  },
219
207
  });
220
208
 
221
- for (const result of signalResult.deliveryResults) {
222
- if (result.channel === "vellum") {
223
- if (!vellumDeliveryId) {
224
- const delivery = createCanonicalGuardianDelivery({
225
- requestId: request.id,
226
- destinationChannel: "vellum",
227
- destinationConversationId: result.conversationId,
228
- });
229
- vellumDeliveryId = delivery.id;
230
- }
231
- applyDeliveryStatus(vellumDeliveryId, result);
232
- continue;
233
- }
234
-
235
- const delivery = recordCanonicalChannelDelivery(request.id, result);
236
- applyDeliveryStatus(delivery.id, result);
237
- }
209
+ vellumDeliveryId = recordGuardianRequestDeliveries({
210
+ requestId: request.id,
211
+ deliveryResults: signalResult.deliveryResults,
212
+ vellumDeliveryId,
213
+ });
238
214
 
239
215
  if (!vellumDeliveryId) {
240
- const fallback = createCanonicalGuardianDelivery({
216
+ recordApprovalCardDelivery({
241
217
  requestId: request.id,
242
- destinationChannel: "vellum",
218
+ channel: "vellum",
219
+ status: "failed",
243
220
  });
244
- updateCanonicalGuardianDelivery(fallback.id, { status: "failed" });
245
221
  log.warn(
246
222
  { requestId: request.id, reason: signalResult.reason },
247
223
  "Notification pipeline did not produce a vellum delivery result",
@@ -136,16 +136,18 @@ export const AssistantConfigSchema = z
136
136
  .describe(
137
137
  "Per-plugin configuration keyed by plugin name. Validated downstream by each plugin's manifest.config validator at bootstrap.",
138
138
  ),
139
- sendDiagnostics: z
140
- .boolean()
141
- .default(true)
142
- .describe("Whether to send diagnostic/crash reports"),
143
139
  legacyTelemetryOptOut: z
144
140
  .boolean()
145
141
  .optional()
146
142
  .describe(
147
143
  "Fail-closed telemetry marker: set for a workspace that had an explicit local usage-data opt-out before telemetry moved to platform share_analytics consent. While set, usage telemetry stays disabled regardless of platform consent.",
148
144
  ),
145
+ legacyDiagnosticsOptOut: z
146
+ .boolean()
147
+ .optional()
148
+ .describe(
149
+ "Fail-closed diagnostics marker: set for a workspace that had an explicit local sendDiagnostics opt-out before crash reporting moved to platform share_diagnostics consent. While set, Sentry stays disabled regardless of platform consent.",
150
+ ),
149
151
  maxStepsPerSession: z
150
152
  .number({ error: "maxStepsPerSession must be a number" })
151
153
  .int("maxStepsPerSession must be an integer")
@@ -133,13 +133,9 @@ export const MemoryCleanupConfigSchema = z
133
133
  .nonnegative(
134
134
  "memory.cleanup.llmRequestLogRetentionMs must be non-negative",
135
135
  )
136
- // Upper bound must match gateway MAX_LLM_REQUEST_LOG_RETENTION_MS in
137
- // gateway/src/http/routes/privacy-config.ts. If a manually edited
138
- // config.json sets a value larger than this, the gateway GET would
139
- // return it and the macOS picker would snap it to its largest known
140
- // option, and the next PATCH would silently truncate the value —
141
- // causing quiet data loss. Enforcing the same cap here prevents the
142
- // daemon from accepting out-of-range values in the first place.
136
+ // Cap retention at 365 days. Enforced daemon-side only: the cleanup jobs
137
+ // honor this bound, so a manually edited config.json with a larger value
138
+ // is rejected here rather than silently retained.
143
139
  .max(
144
140
  365 * 24 * 60 * 60 * 1000,
145
141
  "memory.cleanup.llmRequestLogRetentionMs must be <= 365 days in ms",
@@ -289,9 +289,10 @@ export async function runDaemon(): Promise<void> {
289
289
  log.info({ version: APP_VERSION }, "Daemon starting");
290
290
 
291
291
  try {
292
- // Initialize crash reporting eagerly so early startup failures are
293
- // captured. After config loads we check the opt-out flag and call
294
- // closeSentry() if the user has disabled it.
292
+ // Initialize crash reporting eagerly so the Sentry client is ready before
293
+ // early startup failures occur. Events are dropped (beforeSend) until the
294
+ // consent gate below confirms share_diagnostics opt-in; dev mode and the
295
+ // legacy local opt-out hard-disable via closeSentry().
295
296
  initSentry();
296
297
 
297
298
  ensureDataDir();
@@ -641,13 +642,17 @@ export async function runDaemon(): Promise<void> {
641
642
  });
642
643
  }
643
644
 
644
- // Privacy gating: Sentry crash/error reporting is gated by sendDiagnostics,
645
- // while the usage telemetry reporter re-checks the platform share_analytics
646
- // consent on every flush. Both are disabled in dev mode. Early-startup
647
- // crashes before this point are still captured.
645
+ // Privacy gating: Sentry crash/error reporting follows the platform owner's
646
+ // share_diagnostics consent; the usage telemetry reporter re-checks
647
+ // share_analytics on every flush. Both are disabled in dev mode. Sentry was
648
+ // initialized early, but beforeSend re-reads getCachedShareDiagnostics() on
649
+ // every event, so it drops events until consent confirms opt-in and honors a
650
+ // later revocation within one refresh cycle (the cache is refreshed by
651
+ // startConsentRefresh() below, mirroring the share_analytics posture).
648
652
  const isDevMode = process.env.VELLUM_DEV === "1";
649
- const sendDiagnostics = !isDevMode && config.sendDiagnostics;
650
- if (!sendDiagnostics) {
653
+ if (isDevMode || config.legacyDiagnosticsOptOut === true) {
654
+ // Dev mode and a preserved legacy local opt-out both disable Sentry
655
+ // unconditionally, without waiting on platform consent.
651
656
  await closeSentry();
652
657
  }
653
658
 
package/src/instrument.ts CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  getPlatformUserId,
8
8
  getSentryDsn,
9
9
  } from "./config/env.js";
10
+ import { getCachedShareDiagnostics } from "./platform/consent-cache.js";
10
11
  import { APP_VERSION, COMMIT_SHA } from "./version.js";
11
12
 
12
13
  /** Patterns that match sensitive data in Sentry event values. */
@@ -41,9 +42,11 @@ function redactObject(obj: unknown): unknown {
41
42
  /**
42
43
  * Call after dotenv has loaded so SENTRY_DSN_ASSISTANT is available.
43
44
  * Initializes Sentry when the DSN is set; no-ops when empty/unset so
44
- * local dev builds don't send crash reports. If the user later opts out
45
- * via the sendDiagnostics config key (or VELLUM_DEV=1), call closeSentry()
46
- * after config is loaded to stop future event capturing.
45
+ * local dev builds don't send crash reports. Events are dropped by
46
+ * beforeSend until the platform share_diagnostics consent confirms opt-in
47
+ * (re-read from the consent cache per event, so a revocation takes effect
48
+ * within one refresh cycle); VELLUM_DEV=1 and legacyDiagnosticsOptOut
49
+ * hard-disable via closeSentry() after config loads.
47
50
  */
48
51
  export function initSentry(): void {
49
52
  const dsn = getSentryDsn();
@@ -54,6 +57,14 @@ export function initSentry(): void {
54
57
  dist: COMMIT_SHA,
55
58
  environment: process.env.VELLUM_ENVIRONMENT ?? "production",
56
59
  sendDefaultPii: false,
60
+ // Fail-closed: suppress client-report pings (discarded-event counts) so an
61
+ // assistant with unconfirmed share_diagnostics consent stays network-silent.
62
+ sendClientReports: false,
63
+ // Drop the default ProcessSession integration: it starts a release-health
64
+ // session on init and flushes a session envelope on process exit (a network
65
+ // request not covered by the beforeSend event gate), violating fail-closed.
66
+ integrations: (defaults) =>
67
+ defaults.filter((i) => i.name !== "ProcessSession"),
57
68
  serverName: hostname(),
58
69
  initialScope: {
59
70
  tags: {
@@ -77,6 +88,7 @@ export function initSentry(): void {
77
88
  },
78
89
  },
79
90
  beforeSend(event) {
91
+ if (!getCachedShareDiagnostics()) return null;
80
92
  if (event.exception?.values) {
81
93
  event.exception.values = event.exception.values.map((ex) => ({
82
94
  ...ex,
@@ -101,9 +113,9 @@ export function initSentry(): void {
101
113
  }
102
114
 
103
115
  /**
104
- * Stop capturing future Sentry events. Called after config loads when the
105
- * user has disabled sendDiagnostics so that early-startup crashes are
106
- * still captured but subsequent events are suppressed.
116
+ * Stop capturing future Sentry events. Called after config loads for the
117
+ * legacyDiagnosticsOptOut local opt-out (or VELLUM_DEV=1) to hard-disable
118
+ * crash reporting independent of the share_diagnostics consent gate.
107
119
  */
108
120
  export async function closeSentry(): Promise<void> {
109
121
  await Sentry.close();
@@ -3,3 +3,5 @@
3
3
  All notification producers **MUST** go through `emitNotificationSignal()` in `notifications/emit-signal.ts`. Do not bypass the pipeline by broadcasting events directly -- the pipeline handles event persistence, deduplication, decision routing, and delivery audit.
4
4
 
5
5
  When a notification flow creates a server-side conversation (e.g. guardian question conversations, task run conversations), the conversation and initial message **MUST** be persisted before the conversation-created event is emitted. This ensures the macOS/iOS client can immediately fetch the conversation contents when it receives the event.
6
+
7
+ Guardian-request producers (access requests, tool approvals, tool-grant escalations, voice questions, trusted-contact confirmations) **MUST** record approval-card deliveries through `recordApprovalCardDelivery` / `recordGuardianRequestDeliveries` in `canonical-delivery-recorder.ts` -- never by calling `createCanonicalGuardianDelivery` directly. That sink is the single place the card-to-request addressing convention lives (conversation id for the in-app card; chat + channel-native `ts` for channel cards), so the path that writes a delivery row cannot drift from the paths that read it back to withdraw a card or resolve an emoji reaction -- the drift that previously fanned this logic into four divergent copies. (Tests may call the store helper directly for fixtures.)
@@ -1,39 +1,139 @@
1
1
  /**
2
- * Bridge from notification-pipeline delivery results to the per-request
3
- * `canonical_guardian_deliveries` registry.
2
+ * The single sink for the per-(request, surface) `canonical_guardian_deliveries`
3
+ * registry.
4
4
  *
5
5
  * Guardian-request producers (access requests, tool approvals, tool-grant
6
- * escalations, voice questions) emit a notification signal and then record one
7
- * canonical delivery row per surface the card reached. Capturing the
8
- * channel-native message id (e.g. Slack `ts`) here is what lets a delivered
9
- * card be addressed back to its request later: to withdraw it in place when the
10
- * request resolves (`approvals/guardian-card-withdrawal.ts`), and to resolve an
11
- * emoji reaction on the card to the right request when several are pending in
12
- * the same chat.
6
+ * escalations, voice questions, trusted-contact confirmations) emit a
7
+ * notification signal and then record one canonical delivery row per surface the
8
+ * card reached. Capturing the surface address here — the conversation id for the
9
+ * in-app vellum card, or the channel-native message id (e.g. Slack `ts`) for a
10
+ * channel card — is what lets a delivered card be addressed back to its request
11
+ * later:
12
+ *
13
+ * - to withdraw it in place when the request resolves
14
+ * (`approvals/guardian-card-withdrawal.ts`), and
15
+ * - to resolve an emoji reaction on the card to the right request when several
16
+ * are pending in the same chat
17
+ * (`getPendingCanonicalRequestByDestinationMessage`).
18
+ *
19
+ * Every producer records through here so the addressing convention lives in one
20
+ * place and cannot drift between the path that writes the row and the paths that
21
+ * read it back.
13
22
  */
14
23
 
15
24
  import {
16
25
  type CanonicalGuardianDelivery,
17
26
  createCanonicalGuardianDelivery,
27
+ updateCanonicalGuardianDelivery,
18
28
  } from "../memory/canonical-guardian-store.js";
29
+ import { getLogger } from "../util/logger.js";
19
30
  import type { NotificationDeliveryResult } from "./types.js";
20
31
 
32
+ const log = getLogger("canonical-delivery-recorder");
33
+
34
+ /**
35
+ * Where an approval card was delivered. Exactly one addressing modality is
36
+ * meaningful per channel:
37
+ *
38
+ * - vellum (in-app): addressed by `conversationId` + the card's surface id.
39
+ * - channels (slack/telegram/...): addressed by `chatId` + the channel-native
40
+ * `messageId` (Slack `ts`).
41
+ */
42
+ export interface ApprovalCardDeliveryAddress {
43
+ requestId: string;
44
+ channel: string;
45
+ /** In-app vellum addressing: the conversation the card was posted to. */
46
+ conversationId?: string;
47
+ /** Channel addressing: the chat the card was delivered to. */
48
+ chatId?: string;
49
+ /** Channel-native message id (e.g. Slack `ts`) — the reaction/withdrawal key. */
50
+ messageId?: string;
51
+ /** Initial delivery status (defaults to "pending"). */
52
+ status?: string;
53
+ }
54
+
55
+ /**
56
+ * Record where an approval card was delivered so it can be located later.
57
+ *
58
+ * Best-effort: a recording failure must never be mistaken for a delivery
59
+ * failure (which, in the prompt path, would trigger a fallback re-post), so
60
+ * errors are swallowed and logged and `null` is returned. Callers that need the
61
+ * row id (to apply a status afterwards) must null-check the result.
62
+ */
63
+ export function recordApprovalCardDelivery(
64
+ address: ApprovalCardDeliveryAddress,
65
+ ): CanonicalGuardianDelivery | null {
66
+ try {
67
+ return createCanonicalGuardianDelivery({
68
+ requestId: address.requestId,
69
+ destinationChannel: address.channel,
70
+ destinationConversationId: address.conversationId,
71
+ destinationChatId: address.chatId,
72
+ destinationMessageId: address.messageId,
73
+ ...(address.status ? { status: address.status } : {}),
74
+ });
75
+ } catch (err) {
76
+ log.error(
77
+ { err, requestId: address.requestId, channel: address.channel },
78
+ "Failed to record approval card delivery; reaction/withdrawal on this card will not resolve",
79
+ );
80
+ return null;
81
+ }
82
+ }
83
+
21
84
  /**
22
- * Record a canonical guardian delivery for a non-vellum channel result.
85
+ * Record every delivery for a guardian request from a notification signal's
86
+ * results, persisting each delivery's terminal status.
87
+ *
88
+ * This is the shared post-broadcast recording loop for the signal-based
89
+ * producers. The vellum row is normally created up front in the signal's
90
+ * `onConversationCreated` callback so the in-app client sees it immediately; pass
91
+ * that row's id as `vellumDeliveryId` and it is reused (only its status applied)
92
+ * — otherwise the vellum row is created here from the result.
23
93
  *
24
- * Vellum deliveries are recorded separately by their producers (via the
25
- * notification pipeline's `onConversationCreated` callback) because they are
26
- * addressed by conversation + surface id rather than a channel message id.
94
+ * The pipeline result carries the delivered address directly: a `vellum` result
95
+ * carries a `conversationId`; channel results carry the chat (`destination`) and
96
+ * channel-native id (`messageId`). A blank `destination` is recorded as unknown
97
+ * rather than persisting the literal channel name as a chat id. Status is
98
+ * diagnostic — the read paths key off addressing, not status.
99
+ *
100
+ * Returns the vellum delivery id (passed in, or created here) so a caller can
101
+ * record its own "pipeline produced no vellum delivery" fallback.
27
102
  */
28
- export function recordCanonicalChannelDelivery(
29
- requestId: string,
30
- result: NotificationDeliveryResult,
31
- ): CanonicalGuardianDelivery {
32
- return createCanonicalGuardianDelivery({
33
- requestId,
34
- destinationChannel: result.channel,
35
- destinationChatId:
36
- result.destination.length > 0 ? result.destination : undefined,
37
- destinationMessageId: result.messageId,
38
- });
103
+ export function recordGuardianRequestDeliveries(params: {
104
+ requestId: string;
105
+ deliveryResults: NotificationDeliveryResult[];
106
+ vellumDeliveryId?: string;
107
+ }): string | undefined {
108
+ const { requestId, deliveryResults } = params;
109
+ let vellumDeliveryId = params.vellumDeliveryId;
110
+
111
+ for (const result of deliveryResults) {
112
+ let deliveryId: string | undefined;
113
+ if (result.channel === "vellum") {
114
+ if (!vellumDeliveryId) {
115
+ vellumDeliveryId = recordApprovalCardDelivery({
116
+ requestId,
117
+ channel: "vellum",
118
+ conversationId: result.conversationId,
119
+ })?.id;
120
+ }
121
+ deliveryId = vellumDeliveryId;
122
+ } else {
123
+ deliveryId = recordApprovalCardDelivery({
124
+ requestId,
125
+ channel: result.channel,
126
+ chatId: result.destination.length > 0 ? result.destination : undefined,
127
+ messageId: result.messageId,
128
+ })?.id;
129
+ }
130
+
131
+ if (deliveryId) {
132
+ updateCanonicalGuardianDelivery(deliveryId, {
133
+ status: result.status === "sent" ? "sent" : "failed",
134
+ });
135
+ }
136
+ }
137
+
138
+ return vellumDeliveryId;
39
139
  }
@@ -47,7 +47,9 @@ mock.module("../util/logger.js", () => ({
47
47
 
48
48
  import {
49
49
  __setCachedShareAnalyticsForTest,
50
+ __setCachedShareDiagnosticsForTest,
50
51
  getCachedShareAnalytics,
52
+ getCachedShareDiagnostics,
51
53
  refreshConsentCache,
52
54
  startConsentRefresh,
53
55
  stopConsentRefresh,
@@ -66,6 +68,7 @@ describe("consent-cache", () => {
66
68
  createCallCount = 0;
67
69
  mockLegacyTelemetryOptOut = false;
68
70
  __setCachedShareAnalyticsForTest(false);
71
+ __setCachedShareDiagnosticsForTest(false);
69
72
  });
70
73
 
71
74
  afterEach(async () => {
@@ -156,4 +159,53 @@ describe("consent-cache", () => {
156
159
  await new Promise((resolve) => setTimeout(resolve, 0));
157
160
  expect(getCachedShareAnalytics()).toBe(true);
158
161
  });
162
+
163
+ // share_diagnostics tracks the same refresh as share_analytics; Sentry's
164
+ // beforeSend re-reads it per event so a revocation is honored within a cycle.
165
+ test("diagnostics defaults to false before any refresh", () => {
166
+ expect(getCachedShareDiagnostics()).toBe(false);
167
+ });
168
+
169
+ test("diagnostics becomes true after a fetch reporting shareDiagnostics: true", async () => {
170
+ mockClient = makeClient({ shareAnalytics: false, shareDiagnostics: true });
171
+ await refreshConsentCache();
172
+ expect(getCachedShareDiagnostics()).toBe(true);
173
+ });
174
+
175
+ test("a later fetch reporting shareDiagnostics: false honors the revocation", async () => {
176
+ mockClient = makeClient({ shareAnalytics: false, shareDiagnostics: true });
177
+ await refreshConsentCache();
178
+ expect(getCachedShareDiagnostics()).toBe(true);
179
+
180
+ mockClient = makeClient({ shareAnalytics: false, shareDiagnostics: false });
181
+ await refreshConsentCache();
182
+ expect(getCachedShareDiagnostics()).toBe(false);
183
+ });
184
+
185
+ test("a null diagnostics fetch keeps the last known value", async () => {
186
+ mockClient = makeClient({ shareAnalytics: false, shareDiagnostics: true });
187
+ await refreshConsentCache();
188
+ expect(getCachedShareDiagnostics()).toBe(true);
189
+
190
+ mockClient = makeClient(null);
191
+ await refreshConsentCache();
192
+ expect(getCachedShareDiagnostics()).toBe(true);
193
+ });
194
+
195
+ test("a missing client flips a prior diagnostics opt-in back to false", async () => {
196
+ __setCachedShareDiagnosticsForTest(true);
197
+ mockClient = null;
198
+ await refreshConsentCache();
199
+ expect(getCachedShareDiagnostics()).toBe(false);
200
+ });
201
+
202
+ test("a client without a resolvable assistant identity fails diagnostics closed", async () => {
203
+ __setCachedShareDiagnosticsForTest(true);
204
+ mockClient = makeClient(
205
+ { shareAnalytics: false, shareDiagnostics: true },
206
+ "",
207
+ );
208
+ await refreshConsentCache();
209
+ expect(getCachedShareDiagnostics()).toBe(false);
210
+ });
159
211
  });
@@ -1,11 +1,13 @@
1
1
  /**
2
- * In-memory cache of the platform owner's `share_analytics` consent.
2
+ * In-memory cache of the platform owner's `share_analytics` and
3
+ * `share_diagnostics` consent.
3
4
  *
4
- * Record-time telemetry gates need a synchronous, I/O-free read, so this module
5
- * owns the consent value and refreshes it periodically in the background.
6
- * Default-off until the first successful fetch: an absent session, a disabled
7
- * platform, or a transient fetch failure all leave the value untouched (initial
8
- * `false`), so we never report analytics without a confirmed opt-in.
5
+ * Hot-path gates (record-time telemetry writes, Sentry `beforeSend`) need a
6
+ * synchronous, I/O-free read, so this module owns both consent values and
7
+ * refreshes them periodically in the background. Default-off until the first
8
+ * successful fetch: an absent session, a disabled platform, or a transient
9
+ * fetch failure all leave the values untouched (initial `false`), so we never
10
+ * report analytics or send crash diagnostics without a confirmed opt-in.
9
11
  */
10
12
 
11
13
  import { getConfigReadOnly } from "../config/loader.js";
@@ -17,6 +19,7 @@ const log = getLogger("consent-cache");
17
19
  const REFRESH_INTERVAL_MS = 5 * 60_000; // refresh consent every 5 min
18
20
 
19
21
  let cachedShareAnalytics = false; // default-off until first success
22
+ let cachedShareDiagnostics = false; // default-off until first success
20
23
  // Fail-closed marker for a workspace that locally opted out of usage data
21
24
  // before telemetry moved to platform `share_analytics` consent (migration 106).
22
25
  // While set, telemetry stays off regardless of platform consent. Cleared by a
@@ -34,14 +37,24 @@ export function getCachedShareAnalytics(): boolean {
34
37
  return cachedShareAnalytics && !legacyOptOut;
35
38
  }
36
39
 
40
+ /**
41
+ * Synchronous hot-path accessor for the `share_diagnostics` consent (read by
42
+ * Sentry `beforeSend`). Never does I/O; returns `false` until a successful
43
+ * refresh proves otherwise. Because every Sentry event re-reads this, a
44
+ * mid-session opt-out is honored within one refresh cycle.
45
+ */
46
+ export function getCachedShareDiagnostics(): boolean {
47
+ return cachedShareDiagnostics;
48
+ }
49
+
37
50
  /**
38
51
  * Refresh the cached consent from the platform.
39
52
  *
40
53
  * No platform session / features disabled (`create()` is null) → default-off.
41
54
  * No resolvable assistant identity (no owner whose consent we can attest to) →
42
- * fail closed. A successful fetch adopts the reported value. A `null` fetch
43
- * (transient failure / undeployed endpoint) leaves the previous value unchanged
44
- * so a known opt-in is not flipped off mid-session.
55
+ * fail closed. A successful fetch adopts the reported values. A `null` fetch
56
+ * (transient failure / undeployed endpoint) leaves the previous values
57
+ * unchanged so a known opt-in is not flipped off mid-session.
45
58
  */
46
59
  export async function refreshConsentCache(): Promise<void> {
47
60
  legacyOptOut = getConfigReadOnly().legacyTelemetryOptOut === true;
@@ -49,18 +62,21 @@ export async function refreshConsentCache(): Promise<void> {
49
62
  const client = await VellumPlatformClient.create();
50
63
  if (!client) {
51
64
  setCachedShareAnalytics(false);
65
+ setCachedShareDiagnostics(false);
52
66
  return;
53
67
  }
54
68
 
55
69
  // No resolvable owner identity → fail closed (don't ride a stale opt-in).
56
70
  if (!client.platformAssistantId) {
57
71
  setCachedShareAnalytics(false);
72
+ setCachedShareDiagnostics(false);
58
73
  return;
59
74
  }
60
75
 
61
76
  const consent = await client.getOwnerConsent();
62
77
  if (consent) {
63
78
  setCachedShareAnalytics(consent.shareAnalytics);
79
+ setCachedShareDiagnostics(consent.shareDiagnostics);
64
80
  }
65
81
  }
66
82
 
@@ -74,6 +90,16 @@ function setCachedShareAnalytics(value: boolean): void {
74
90
  }
75
91
  }
76
92
 
93
+ function setCachedShareDiagnostics(value: boolean): void {
94
+ if (value !== cachedShareDiagnostics) {
95
+ log.debug(
96
+ { from: cachedShareDiagnostics, to: value },
97
+ "share_diagnostics consent changed",
98
+ );
99
+ cachedShareDiagnostics = value;
100
+ }
101
+ }
102
+
77
103
  /**
78
104
  * Begin periodic consent refresh. Idempotent — a second call is a no-op while a
79
105
  * timer is already running. Runs one immediate refresh, then every 5 minutes.
@@ -101,7 +127,12 @@ export async function stopConsentRefresh(): Promise<void> {
101
127
  }
102
128
  }
103
129
 
104
- /** Test-only: override the cached value without going through a refresh. */
130
+ /** Test-only: override the cached analytics value without going through a refresh. */
105
131
  export function __setCachedShareAnalyticsForTest(value: boolean): void {
106
132
  cachedShareAnalytics = value;
107
133
  }
134
+
135
+ /** Test-only: override the cached diagnostics value without going through a refresh. */
136
+ export function __setCachedShareDiagnosticsForTest(value: boolean): void {
137
+ cachedShareDiagnostics = value;
138
+ }
@@ -15,31 +15,20 @@ import type { ChannelId } from "../channels/types.js";
15
15
  import { findGuardianForChannel } from "../contacts/contact-store.js";
16
16
  import type { ChannelStatus } from "../contacts/types.js";
17
17
  import {
18
- createCanonicalGuardianDelivery,
19
18
  createCanonicalGuardianRequest,
20
19
  listCanonicalGuardianRequests,
21
- updateCanonicalGuardianDelivery,
22
20
  } from "../memory/canonical-guardian-store.js";
23
- import { recordCanonicalChannelDelivery } from "../notifications/canonical-delivery-recorder.js";
21
+ import {
22
+ recordApprovalCardDelivery,
23
+ recordGuardianRequestDeliveries,
24
+ } from "../notifications/canonical-delivery-recorder.js";
24
25
  import { emitNotificationSignal } from "../notifications/emit-signal.js";
25
26
  import type { GuardianResolutionSource } from "../notifications/signal.js";
26
- import type { NotificationDeliveryResult } from "../notifications/types.js";
27
27
  import { getLogger } from "../util/logger.js";
28
28
  import { GUARDIAN_APPROVAL_TTL_MS } from "./routes/channel-route-shared.js";
29
29
 
30
30
  const log = getLogger("access-request-helper");
31
31
 
32
- function applyDeliveryStatus(
33
- deliveryId: string,
34
- result: NotificationDeliveryResult,
35
- ): void {
36
- if (result.status === "sent") {
37
- updateCanonicalGuardianDelivery(deliveryId, { status: "sent" });
38
- return;
39
- }
40
- updateCanonicalGuardianDelivery(deliveryId, { status: "failed" });
41
- }
42
-
43
32
  // ---------------------------------------------------------------------------
44
33
  // Types
45
34
  // ---------------------------------------------------------------------------
@@ -197,7 +186,7 @@ export function notifyGuardianOfAccessRequest(
197
186
  expiresAt: Date.now() + GUARDIAN_APPROVAL_TTL_MS,
198
187
  });
199
188
 
200
- let vellumDeliveryId: string | null = null;
189
+ let vellumDeliveryId: string | undefined;
201
190
  // When the access request originates from a text channel with
202
191
  // notification delivery support (Slack, Telegram) and the guardian was
203
192
  // resolved via a verified same-channel contact, route the notification
@@ -247,42 +236,26 @@ export function notifyGuardianOfAccessRequest(
247
236
  onConversationCreated: (info) => {
248
237
  if (info.sourceEventName !== "ingress.access_request" || vellumDeliveryId)
249
238
  return;
250
- const delivery = createCanonicalGuardianDelivery({
239
+ vellumDeliveryId = recordApprovalCardDelivery({
251
240
  requestId: canonicalRequest.id,
252
- destinationChannel: "vellum",
253
- destinationConversationId: info.conversationId,
254
- });
255
- vellumDeliveryId = delivery.id;
241
+ channel: "vellum",
242
+ conversationId: info.conversationId,
243
+ })?.id;
256
244
  },
257
245
  })
258
246
  .then((signalResult) => {
259
- for (const result of signalResult.deliveryResults) {
260
- if (result.channel === "vellum") {
261
- if (!vellumDeliveryId) {
262
- const delivery = createCanonicalGuardianDelivery({
263
- requestId: canonicalRequest.id,
264
- destinationChannel: "vellum",
265
- destinationConversationId: result.conversationId,
266
- });
267
- vellumDeliveryId = delivery.id;
268
- }
269
- applyDeliveryStatus(vellumDeliveryId, result);
270
- continue;
271
- }
272
-
273
- const delivery = recordCanonicalChannelDelivery(
274
- canonicalRequest.id,
275
- result,
276
- );
277
- applyDeliveryStatus(delivery.id, result);
278
- }
247
+ vellumDeliveryId = recordGuardianRequestDeliveries({
248
+ requestId: canonicalRequest.id,
249
+ deliveryResults: signalResult.deliveryResults,
250
+ vellumDeliveryId,
251
+ });
279
252
 
280
253
  if (!vellumDeliveryId && !sameChannelOnly) {
281
- const fallback = createCanonicalGuardianDelivery({
254
+ recordApprovalCardDelivery({
282
255
  requestId: canonicalRequest.id,
283
- destinationChannel: "vellum",
256
+ channel: "vellum",
257
+ status: "failed",
284
258
  });
285
- updateCanonicalGuardianDelivery(fallback.id, { status: "failed" });
286
259
  log.warn(
287
260
  { requestId: canonicalRequest.id, reason: signalResult.reason },
288
261
  "Notification pipeline did not produce a vellum delivery result for access request",
@@ -13,11 +13,11 @@
13
13
  */
14
14
 
15
15
  import type { TrustContext } from "../daemon/trust-context.js";
16
+ import type { CanonicalGuardianRequest } from "../memory/canonical-guardian-store.js";
16
17
  import {
17
- type CanonicalGuardianRequest,
18
- createCanonicalGuardianDelivery,
19
- } from "../memory/canonical-guardian-store.js";
20
- import { recordCanonicalChannelDelivery } from "../notifications/canonical-delivery-recorder.js";
18
+ recordApprovalCardDelivery,
19
+ recordGuardianRequestDeliveries,
20
+ } from "../notifications/canonical-delivery-recorder.js";
21
21
  import { emitNotificationSignal } from "../notifications/emit-signal.js";
22
22
  import { canonicalizeInboundIdentity } from "../util/canonicalize-identity.js";
23
23
  import { getLogger } from "../util/logger.js";
@@ -151,6 +151,10 @@ export function bridgeConfirmationRequestToGuardian(
151
151
  ? `Approve tool: ${toolName} — ${canonicalRequest.activityText}`
152
152
  : `Approve tool: ${toolName}`;
153
153
 
154
+ // The vellum delivery row is created up front in onConversationCreated so the
155
+ // in-app client sees it immediately; the post-resolve recorder reuses it.
156
+ let vellumDeliveryId: string | undefined;
157
+
154
158
  // Emit guardian.question notification so the guardian is alerted.
155
159
  const signalPromise = emitNotificationSignal({
156
160
  sourceEventName: "guardian.question",
@@ -180,21 +184,22 @@ export function bridgeConfirmationRequestToGuardian(
180
184
  },
181
185
  dedupeKey: `tc-confirmation-request:${canonicalRequest.id}`,
182
186
  onConversationCreated: (info) => {
183
- createCanonicalGuardianDelivery({
187
+ vellumDeliveryId = recordApprovalCardDelivery({
184
188
  requestId: canonicalRequest.id,
185
- destinationChannel: "vellum",
186
- destinationConversationId: info.conversationId,
187
- });
189
+ channel: "vellum",
190
+ conversationId: info.conversationId,
191
+ })?.id;
188
192
  },
189
193
  });
190
194
 
191
- // Record channel deliveries from the notification pipeline (fire-and-forget).
195
+ // Record deliveries from the notification pipeline (fire-and-forget).
192
196
  void signalPromise
193
197
  .then((signalResult) => {
194
- for (const result of signalResult.deliveryResults) {
195
- if (result.channel === "vellum") continue; // handled in onConversationCreated
196
- recordCanonicalChannelDelivery(canonicalRequest.id, result);
197
- }
198
+ recordGuardianRequestDeliveries({
199
+ requestId: canonicalRequest.id,
200
+ deliveryResults: signalResult.deliveryResults,
201
+ vellumDeliveryId,
202
+ });
198
203
  })
199
204
  .catch((err) => {
200
205
  log.warn(
@@ -2,7 +2,7 @@
2
2
  * Approval prompt delivery: rich UI (buttons) with plain-text fallback.
3
3
  */
4
4
  import type { ChannelId } from "../../channels/types.js";
5
- import { createCanonicalGuardianDelivery } from "../../memory/canonical-guardian-store.js";
5
+ import { recordApprovalCardDelivery } from "../../notifications/canonical-delivery-recorder.js";
6
6
  import { redactSecrets } from "../../security/secret-scanner.js";
7
7
  import { getLogger } from "../../util/logger.js";
8
8
  import type { ApprovalMessageContext } from "../approval-message-composer.js";
@@ -22,37 +22,6 @@ import { requiredDecisionKeywords } from "./channel-route-shared.js";
22
22
 
23
23
  const log = getLogger("runtime-http");
24
24
 
25
- /**
26
- * Record the delivered approval card so an emoji reaction on it can be routed
27
- * back to its canonical request. The card's channel-native message id (e.g.
28
- * Slack `ts`) is the addressing key the reaction decision path uses to recover
29
- * which request the guardian acted on.
30
- *
31
- * Best-effort: a failure here must not be mistaken for a delivery failure by
32
- * the surrounding try/catch (which would trigger a fallback re-post), so errors
33
- * are swallowed and logged.
34
- */
35
- function recordApprovalCardDelivery(
36
- requestId: string,
37
- channel: ChannelId,
38
- chatId: string,
39
- messageId: string,
40
- ): void {
41
- try {
42
- createCanonicalGuardianDelivery({
43
- requestId,
44
- destinationChannel: channel,
45
- destinationChatId: chatId,
46
- destinationMessageId: messageId,
47
- });
48
- } catch (err) {
49
- log.error(
50
- { err, requestId, channel, chatId },
51
- "Failed to record approval card delivery; reaction-based approval on this card will not resolve",
52
- );
53
- }
54
- }
55
-
56
25
  // ---------------------------------------------------------------------------
57
26
  // Tool input summary for rich-UI approval prompts
58
27
  // ---------------------------------------------------------------------------
@@ -179,12 +148,13 @@ export async function deliverGeneratedApprovalPrompt(
179
148
  assistantId,
180
149
  );
181
150
  if (deliveryResult.ts) {
182
- recordApprovalCardDelivery(
183
- uiMetadata.requestId,
184
- sourceChannel,
151
+ recordApprovalCardDelivery({
152
+ requestId: uiMetadata.requestId,
153
+ channel: sourceChannel,
185
154
  chatId,
186
- deliveryResult.ts,
187
- );
155
+ messageId: deliveryResult.ts,
156
+ status: "sent",
157
+ });
188
158
  }
189
159
  return true;
190
160
  } catch (err) {
@@ -211,12 +181,13 @@ export async function deliverGeneratedApprovalPrompt(
211
181
  assistantId,
212
182
  });
213
183
  if (fallbackResult.ts) {
214
- recordApprovalCardDelivery(
215
- uiMetadata.requestId,
216
- sourceChannel,
184
+ recordApprovalCardDelivery({
185
+ requestId: uiMetadata.requestId,
186
+ channel: sourceChannel,
217
187
  chatId,
218
- fallbackResult.ts,
219
- );
188
+ messageId: fallbackResult.ts,
189
+ status: "sent",
190
+ });
220
191
  }
221
192
  return true;
222
193
  } catch (err) {
@@ -244,12 +215,13 @@ export async function deliverGeneratedApprovalPrompt(
244
215
  assistantId,
245
216
  });
246
217
  if (plainResult.ts) {
247
- recordApprovalCardDelivery(
248
- uiMetadata.requestId,
249
- sourceChannel,
218
+ recordApprovalCardDelivery({
219
+ requestId: uiMetadata.requestId,
220
+ channel: sourceChannel,
250
221
  chatId,
251
- plainResult.ts,
252
- );
222
+ messageId: plainResult.ts,
223
+ status: "sent",
224
+ });
253
225
  }
254
226
  return true;
255
227
  } catch (err) {
@@ -13,11 +13,13 @@
13
13
 
14
14
  import type { ChannelId } from "../channels/types.js";
15
15
  import {
16
- createCanonicalGuardianDelivery,
17
16
  createCanonicalGuardianRequest,
18
17
  listCanonicalGuardianRequests,
19
18
  } from "../memory/canonical-guardian-store.js";
20
- import { recordCanonicalChannelDelivery } from "../notifications/canonical-delivery-recorder.js";
19
+ import {
20
+ recordApprovalCardDelivery,
21
+ recordGuardianRequestDeliveries,
22
+ } from "../notifications/canonical-delivery-recorder.js";
21
23
  import { emitNotificationSignal } from "../notifications/emit-signal.js";
22
24
  import { getLogger } from "../util/logger.js";
23
25
  import { getGuardianBinding } from "./channel-verification-service.js";
@@ -140,6 +142,10 @@ export function createOrReuseToolGrantRequest(
140
142
  canonicalRequest.requestCode ??
141
143
  canonicalRequest.id.slice(0, 6).toUpperCase();
142
144
 
145
+ // The vellum delivery row is created up front in onConversationCreated so the
146
+ // in-app client sees it immediately; the post-resolve recorder reuses it.
147
+ let vellumDeliveryId: string | undefined;
148
+
143
149
  // Emit notification so guardian is alerted. Uses 'guardian.question' as
144
150
  // sourceEventName so that existing request-code guidance in the notification
145
151
  // pipeline is preserved.
@@ -167,20 +173,21 @@ export function createOrReuseToolGrantRequest(
167
173
  },
168
174
  dedupeKey: `tool-grant-request:${canonicalRequest.id}`,
169
175
  onConversationCreated: (info) => {
170
- createCanonicalGuardianDelivery({
176
+ vellumDeliveryId = recordApprovalCardDelivery({
171
177
  requestId: canonicalRequest.id,
172
- destinationChannel: "vellum",
173
- destinationConversationId: info.conversationId,
174
- });
178
+ channel: "vellum",
179
+ conversationId: info.conversationId,
180
+ })?.id;
175
181
  },
176
182
  });
177
183
 
178
184
  // Record deliveries from the notification pipeline results (fire-and-forget).
179
185
  void signalPromise.then((signalResult) => {
180
- for (const result of signalResult.deliveryResults) {
181
- if (result.channel === "vellum") continue; // handled in onConversationCreated
182
- recordCanonicalChannelDelivery(canonicalRequest.id, result);
183
- }
186
+ recordGuardianRequestDeliveries({
187
+ requestId: canonicalRequest.id,
188
+ deliveryResults: signalResult.deliveryResults,
189
+ vellumDeliveryId,
190
+ });
184
191
  });
185
192
 
186
193
  log.info(
@@ -0,0 +1,47 @@
1
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ import type { WorkspaceMigration } from "./types.js";
5
+
6
+ /**
7
+ * Drops the `sendDiagnostics` config key (crash reporting is governed by the
8
+ * platform `share_diagnostics` consent). An explicit local opt-out
9
+ * (`sendDiagnostics: false`) is preserved as `legacyDiagnosticsOptOut: true` so
10
+ * Sentry stays off regardless of platform consent, which defaults to opt-in and
11
+ * cannot be written by the daemon. A `true`/non-false value carries no opt-out
12
+ * intent, so the key is removed without setting the marker. The schema strips
13
+ * unknown keys on the next save, so a stale value is otherwise harmless.
14
+ */
15
+ export const dropSendDiagnosticsMigration: WorkspaceMigration = {
16
+ id: "107-drop-send-diagnostics",
17
+ description:
18
+ "Drop sendDiagnostics; preserve an explicit opt-out as legacyDiagnosticsOptOut (crash reporting is gated by platform share_diagnostics consent)",
19
+ run(workspaceDir: string): void {
20
+ const configPath = join(workspaceDir, "config.json");
21
+ if (!existsSync(configPath)) return;
22
+
23
+ let config: Record<string, unknown>;
24
+ try {
25
+ const raw = JSON.parse(readFileSync(configPath, "utf-8"));
26
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return;
27
+ config = raw as Record<string, unknown>;
28
+ } catch {
29
+ return; // Malformed config — skip
30
+ }
31
+
32
+ if (!("sendDiagnostics" in config)) return;
33
+
34
+ // An explicit opt-out is preserved as a fail-closed marker; any non-false
35
+ // value carries no opt-out intent.
36
+ if (config.sendDiagnostics === false) {
37
+ config.legacyDiagnosticsOptOut = true;
38
+ }
39
+
40
+ delete config.sendDiagnostics;
41
+ writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
42
+ },
43
+ down(_workspaceDir: string): void {
44
+ // No-op: the forward migration only removes a key and sets a fail-closed
45
+ // marker, so there is nothing to restore.
46
+ },
47
+ };
@@ -104,6 +104,7 @@ import { upgradeQualityProfileToOpus48Migration } from "./103-upgrade-quality-pr
104
104
  import { recheckAdaptiveThinkingModelImpliedAnthropicMigration } from "./104-recheck-adaptive-thinking-model-implied-anthropic.js";
105
105
  import { enableMemoryV3LiveForNewWorkspacesMigration } from "./105-enable-memory-v3-live-for-new-workspaces.js";
106
106
  import { dropCollectUsageDataMigration } from "./106-drop-collect-usage-data.js";
107
+ import { dropSendDiagnosticsMigration } from "./107-drop-send-diagnostics.js";
107
108
  import { migrateToWorkspaceVolumeMigration } from "./migrate-to-workspace-volume.js";
108
109
  import type { WorkspaceMigration } from "./types.js";
109
110
 
@@ -219,4 +220,5 @@ export const WORKSPACE_MIGRATIONS: WorkspaceMigration[] = [
219
220
  recheckAdaptiveThinkingModelImpliedAnthropicMigration,
220
221
  enableMemoryV3LiveForNewWorkspacesMigration,
221
222
  dropCollectUsageDataMigration,
223
+ dropSendDiagnosticsMigration,
222
224
  ];