@vellumai/assistant 0.11.7-dev.202608282003.8ce5421 → 0.11.7-dev.202608282208.54fd2e3

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 (46) hide show
  1. package/ARCHITECTURE.md +9 -9
  2. package/docs/trusted-contact-access.md +13 -12
  3. package/node_modules/@vellumai/gateway-client/src/__tests__/guardian-request-contract.test.ts +8 -18
  4. package/node_modules/@vellumai/gateway-client/src/guardian-request-contract.ts +40 -18
  5. package/node_modules/@vellumai/gateway-client/src/index.ts +4 -4
  6. package/package.json +1 -1
  7. package/src/__tests__/guardian-card-withdrawal.test.ts +128 -5
  8. package/src/__tests__/guardian-expiry-notifier.test.ts +117 -13
  9. package/src/__tests__/guardian-gateway-sim.test.ts +72 -0
  10. package/src/__tests__/guardian-gateway-sim.ts +28 -15
  11. package/src/approvals/guardian-card-withdrawal.ts +61 -18
  12. package/src/approvals/guardian-expiry-notifier.ts +22 -16
  13. package/src/calls/guardian-action-sweep.ts +6 -1
  14. package/src/channels/__tests__/gateway-guardian-requests.test.ts +12 -12
  15. package/src/channels/gateway-guardian-requests.ts +14 -13
  16. package/src/daemon/conversation-surfaces.ts +12 -2
  17. package/src/daemon/daemon-control.ts +6 -18
  18. package/src/messaging/providers/slack/__tests__/adapter-mention-rendering.test.ts +7 -0
  19. package/src/messaging/providers/slack/__tests__/auth.test.ts +35 -0
  20. package/src/messaging/providers/slack/api.test.ts +10 -0
  21. package/src/messaging/providers/slack/auth.ts +32 -6
  22. package/src/messaging/providers/telegram-bot/withdraw.ts +13 -5
  23. package/src/monitoring/control.ts +2 -2
  24. package/src/notifications/guardian-delivery-recorder.ts +10 -3
  25. package/src/permissions/question-guardian-request.test.ts +1 -1
  26. package/src/plugins/defaults/memory/jobs-worker.ts +1 -2
  27. package/src/plugins/defaults/memory/src/__tests__/memory-worker-routes.test.ts +4 -7
  28. package/src/plugins/defaults/memory/src/memory-worker-routes.ts +1 -1
  29. package/src/plugins/defaults/memory/worker-control.ts +1 -2
  30. package/src/routes/__tests__/control.test.ts +4 -3
  31. package/src/routes/control.ts +1 -1
  32. package/src/routes/route-host-client.ts +1 -1
  33. package/src/runtime/AGENTS.md +23 -11
  34. package/src/runtime/routes/__tests__/monitoring-routes.test.ts +3 -4
  35. package/src/runtime/routes/__tests__/route-host-worker-routes.test.ts +3 -4
  36. package/src/runtime/routes/__tests__/schedule-worker-routes.test.ts +5 -6
  37. package/src/runtime/routes/guardian-expiry-sweep.ts +80 -31
  38. package/src/runtime/routes/monitoring-routes.ts +0 -3
  39. package/src/runtime/routes/route-host-worker-routes.ts +1 -1
  40. package/src/runtime/routes/schedule-worker-routes.ts +1 -1
  41. package/src/schedule/scheduler.ts +1 -1
  42. package/src/schedule/worker-control.ts +2 -2
  43. package/src/util/__tests__/worker-ownership.test.ts +77 -0
  44. package/src/util/worker-ownership.ts +76 -9
  45. package/src/util/worker-process.ts +7 -18
  46. package/src/workspace/git-service.ts +1 -0
package/ARCHITECTURE.md CHANGED
@@ -203,7 +203,7 @@ The guardian request system provides a channel-agnostic, unified domain for all
203
203
 
204
204
  **Resolver registry:** Kind-specific resolvers (`src/approvals/guardian-request-resolvers.ts`) handle side effects after CAS resolution. Built-in resolvers: `tool_approval` (channel/desktop approval path), `pending_question` (voice call question path), and `access_request` (trusted-contact verification session creation). New request kinds register resolvers without touching the core primitive.
205
205
 
206
- **Expiry:** the daemon's 60-second sweep (`src/runtime/routes/guardian-expiry-sweep.ts`) asks the gateway to CAS-expire pending requests past `expiresAt` (`guardian_requests_sweep_expired`) and fans out card withdrawal + requester notices from the returned rows; interaction-bound kinds (`tool_approval`, `pending_question`) are expired at daemon boot via `guardian_requests_expire_interaction_bound` since they die with the in-memory pending-interactions map. `src/calls/guardian-action-sweep.ts` sends the guardian-facing expiry notices for voice questions.
206
+ **Expiry:** the daemon's 60-second sweep (`src/runtime/routes/guardian-expiry-sweep.ts`) lists a bounded batch of past-deadline pending requests (`guardian_requests_list_expired_pending`, read-only), fans out card withdrawal + requester notices per row, and only then confirms each with the per-request `guardian_requests_expire` CAS, so a lost response or crash leaves the row listed for the next round; interaction-bound kinds (`tool_approval`, `pending_question`) are expired at daemon boot via `guardian_requests_expire_interaction_bound` since they die with the in-memory pending-interactions map, and the boot call never touches persistent kinds. `src/calls/guardian-action-sweep.ts` sends the guardian-facing expiry notices for voice questions.
207
207
 
208
208
  **Key source files:**
209
209
 
@@ -267,19 +267,19 @@ Guardian requests (tool approvals, access requests, voice ASK_GUARDIAN questions
267
267
 
268
268
  **Voice consultation timeout:** When a voice call's ASK_GUARDIAN consultation times out before the guardian responds, the call controller expires the request via the gateway (`guardian_requests_expire` — deliveries expire with it), sends expiry notices to every surface the approval card reached (vellum conversations get an assistant message; external channels get a direct channel reply), and injects a `[GUARDIAN_TIMEOUT]` instruction so the model apologizes to the caller and offers a message or callback on the next voice turn.
269
269
 
270
- **Background expiry sweep:** Independent of any active call, a 60-second sweep asks the gateway to CAS-expire pending guardian requests past their `expiresAt` (`guardian_requests_sweep_expired` — a concurrent decision that wins the race is never overwritten), then fans out the side effects per expired row: withdrawing the approval cards on every surface, notifying the requester, and releasing any in-memory pending interaction.
270
+ **Background expiry sweep:** Independent of any active call, a 60-second sweep lists pending guardian requests past their `expiresAt` (`guardian_requests_list_expired_pending`), runs the side effects per row (withdrawing the approval cards on every surface, notifying the requester, releasing any in-memory pending interaction), and then confirms each with the per-request `guardian_requests_expire` CAS; a decision arriving past the deadline loses to expiry atomically, since the decide CAS guards on `expires_at`.
271
271
 
272
272
  **Generated messaging requirement:** All user-facing copy in the guardian timeout/expiry path is generated through the `guardian-action-message-composer.ts` composition system, which uses a 2-tier priority chain: (1) daemon-injected LLM generator for natural, varied text; (2) deterministic fallback templates for reliability. No hardcoded user-facing strings exist in the flow files outside of internal log messages and LLM-instruction prompts. A guard test (`guardian-action-no-hardcoded-copy.test.ts`) enforces this invariant.
273
273
 
274
274
  **Key source files:**
275
275
 
276
- | File | Purpose |
277
- | ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
278
- | `src/channels/gateway-guardian-requests.ts` | Gateway-backed guardian-request client: typed wrappers over the `guardian_requests_*` IPC routes that own request/delivery state and expiry |
279
- | `src/runtime/routes/guardian-expiry-sweep.ts` | Periodic 60s sweep: gateway CAS-expiry (`guardian_requests_sweep_expired`) plus card-withdrawal, requester-notice, and pending-interaction fan-out |
280
- | `src/calls/call-controller.ts` | Voice timeout handling: expires the request, sends expiry notices, injects `[GUARDIAN_TIMEOUT]` instruction for the generated voice response |
281
- | `src/calls/guardian-action-sweep.ts` | Expiry notice delivery to guardian destinations (vellum conversation message or direct channel reply) |
282
- | `src/runtime/guardian-action-message-composer.ts` | 2-tier text generation: daemon-injected LLM generator with deterministic fallback templates |
276
+ | File | Purpose |
277
+ | ------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
278
+ | `src/channels/gateway-guardian-requests.ts` | Gateway-backed guardian-request client: typed wrappers over the `guardian_requests_*` IPC routes that own request/delivery state and expiry |
279
+ | `src/runtime/routes/guardian-expiry-sweep.ts` | Periodic 60s sweep: bounded expired-pending list, per-row card-withdrawal, requester-notice, and pending-interaction fan-out, then per-request expire CAS |
280
+ | `src/calls/call-controller.ts` | Voice timeout handling: expires the request, sends expiry notices, injects `[GUARDIAN_TIMEOUT]` instruction for the generated voice response |
281
+ | `src/calls/guardian-action-sweep.ts` | Expiry notice delivery to guardian destinations (vellum conversation message or direct channel reply) |
282
+ | `src/runtime/guardian-action-message-composer.ts` | 2-tier text generation: daemon-injected LLM generator with deterministic fallback templates |
283
283
 
284
284
  ### WhatsApp Channel (Meta Cloud API)
285
285
 
@@ -68,12 +68,12 @@ requested -> pending_guardian -> verification_pending -> active | denied | expir
68
68
 
69
69
  Identity binding ensures the verification code can only be consumed by the intended recipient on the intended channel. The binding fields are set on the gateway `channel_verification_sessions` record when the session is created; the check itself is `checkIdentityMatch` (`gateway/src/verification/identity-match.ts`).
70
70
 
71
- | Channel | Identity fields | Binding behavior |
72
- | --------- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
73
- | Telegram | `expectedExternalUserId` = Telegram user ID, `expectedChatId` = Telegram chat ID | Both are taken from the original denied message's metadata. The `identityBindingStatus` is `'bound'`. Verification requires the actor's user ID or chat ID to match (user ID required when both are set on a shared chat). |
74
- | Voice | `expectedPhoneE164` = phone number in E.164 format | Phone-based identity binding. Verification requires the caller's number to match the expected phone. |
71
+ | Channel | Identity fields | Binding behavior |
72
+ | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
73
+ | Telegram | `expectedExternalUserId` = Telegram user ID, `expectedChatId` = Telegram chat ID | Both are taken from the original denied message's metadata. The `identityBindingStatus` is `'bound'`. Verification requires the actor's user ID or chat ID to match (user ID required when both are set on a shared chat). |
74
+ | Voice | `expectedPhoneE164` = phone number in E.164 format | Phone-based identity binding. Verification requires the caller's number to match the expected phone. |
75
75
  | Discord | `expectedExternalUserId` = Discord user snowflake. `expectedChatId` is unset on the guardian-initiated and trusted-contact paths, and is the originating guild channel on the access-request approval path (`mint_outbound_session`), which sets it for every channel alike. | The code is delivered to a DM and answered there, but the DM channel does not exist until it is opened, so those two paths have no chat id to record at mint time. Where the approval path does set one, it is a room rather than an identity and never becomes a sufficient credential on its own: `checkIdentityMatch` requires the `expectedExternalUserId` match whenever both fields are set. That path also writes the room into `destinationAddress`, where it describes nothing the code is ever sent to (see LUM-3110). |
76
- | Bootstrap | none yet (`identityBindingStatus: 'pending_bootstrap'`) | Unbound deep-link sessions use a 32-byte hex token instead of a numeric code; the identity is bound when the token is redeemed (`verification_sessions_bind_identity`). |
76
+ | Bootstrap | none yet (`identityBindingStatus: 'pending_bootstrap'`) | Unbound deep-link sessions use a 32-byte hex token instead of a numeric code; the identity is bound when the token is redeemed (`verification_sessions_bind_identity`). |
77
77
 
78
78
  **Anti-oracle invariant:** When identity verification fails, the error message is identical to the "invalid or expired code" message. This prevents attackers from distinguishing between a wrong code and a wrong identity, which would leak information about which identities have pending sessions.
79
79
 
@@ -129,10 +129,10 @@ Separately, the admitted-mode introduction **nudge** (for a contact who cleared
129
129
 
130
130
  ### Stage: `expired`
131
131
 
132
- | Store | Table | Record |
133
- | ------------------------------------------------ | ------------------------------- | --------------------------------------------------------------------------------------------------------- |
134
- | gateway `guardian-request-store.ts` (gateway DB) | `guardian_requests` | Updated to `status: 'expired'` via `guardian_requests_sweep_expired` (the daemon's sweep runs every 60s). |
135
- | `session-store.ts` (gateway DB) | `channel_verification_sessions` | Expires naturally: `expiresAt < Date.now()` makes it invisible to `findPendingSessionByHash()`. |
132
+ | Store | Table | Record |
133
+ | ------------------------------------------------ | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
134
+ | gateway `guardian-request-store.ts` (gateway DB) | `guardian_requests` | Updated to `status: 'expired'` via the per-request `guardian_requests_expire` CAS, after the daemon's 60s sweep has run that row's side effects. |
135
+ | `session-store.ts` (gateway DB) | `channel_verification_sessions` | Expires naturally: `expiresAt < Date.now()` makes it invisible to `findPendingSessionByHash()`. |
136
136
 
137
137
  ### Invites (alternative path)
138
138
 
@@ -216,10 +216,11 @@ sequenceDiagram
216
216
 
217
217
  else Guardian never responds
218
218
  Note over A: runGuardianExpirySweep()<br/>runs every 60 seconds
219
- A->>GW: guardian_requests_sweep_expired (IPC)
220
- GW->>GW: Approval TTL elapsed → status: 'expired' (CAS)
219
+ A->>GW: guardian_requests_list_expired_pending (IPC)
221
220
  A->>A: Withdraw approval cards on all surfaces
222
221
  A-->>U: "Your access request has expired."
222
+ A->>GW: guardian_requests_expire (IPC)
223
+ GW->>GW: status: 'expired' (CAS, the fan-out's receipt)
223
224
 
224
225
  else Code expires (requester never enters it)
225
226
  Note over GW: Verification session TTL: 10 min
@@ -232,7 +233,7 @@ sequenceDiagram
232
233
 
233
234
  ### Guardian never responds
234
235
 
235
- - The `runGuardianExpirySweep()` timer (`runtime/routes/guardian-expiry-sweep.ts`) runs every 60 seconds; the gateway CAS-transitions pending requests past their `expiresAt` to `status: 'expired'` (`guardian_requests_sweep_expired`) and returns the expired rows.
236
+ - The `runGuardianExpirySweep()` timer (`runtime/routes/guardian-expiry-sweep.ts`) runs every 60 seconds; the gateway returns a bounded, read-only batch of pending requests past their `expiresAt` (`guardian_requests_list_expired_pending`), and the daemon confirms each row with the per-request `guardian_requests_expire` CAS only after running its side effects, so the fan-out is recoverable from state.
236
237
  - The daemon then withdraws the now-stale approval cards on every surface and notifies the requester that the request expired.
237
238
 
238
239
  ### Verification code expires
@@ -31,8 +31,7 @@ import {
31
31
  ListGuardianRequestsIpcParamsSchema,
32
32
  ListPendingGuardianRequestsByDestinationIpcParamsSchema,
33
33
  ListPendingGuardianRequestsByScopeIpcParamsSchema,
34
- SweepExpiredGuardianRequestsIpcParamsSchema,
35
- SweepExpiredGuardianRequestsIpcResponseSchema,
34
+ ListExpiredPendingGuardianRequestsIpcParamsSchema,
36
35
  UpdateGuardianRequestIpcParamsSchema,
37
36
  type GuardianRequestWire,
38
37
  } from "../guardian-request-contract.js";
@@ -439,29 +438,20 @@ describe("decide IPC schemas", () => {
439
438
  });
440
439
 
441
440
  describe("expiry IPC schemas", () => {
442
- test("expire and sweep round-trip", () => {
441
+ test("expire and expired-pending list round-trip", () => {
443
442
  expect(ExpireGuardianRequestIpcParamsSchema.parse({ id: "req-1" })).toEqual(
444
443
  { id: "req-1" },
445
444
  );
446
445
 
447
446
  expect(
448
- SweepExpiredGuardianRequestsIpcParamsSchema.parse({
447
+ ListExpiredPendingGuardianRequestsIpcParamsSchema.parse({
449
448
  now: 1_700_000_000_000,
449
+ limit: 50,
450
450
  }),
451
- ).toEqual({ now: 1_700_000_000_000 });
452
- expect(SweepExpiredGuardianRequestsIpcParamsSchema.parse({})).toEqual({});
453
- // The sweep returns full rows so the daemon fan-out never re-reads.
454
- const expiredRow = { ...accessRequest, status: "expired" as const };
455
- expect(
456
- SweepExpiredGuardianRequestsIpcResponseSchema.parse({
457
- expired: [expiredRow],
458
- }),
459
- ).toEqual({ expired: [expiredRow] });
460
- expect(() =>
461
- SweepExpiredGuardianRequestsIpcResponseSchema.parse({
462
- expired: ["req-1"],
463
- }),
464
- ).toThrow();
451
+ ).toEqual({ now: 1_700_000_000_000, limit: 50 });
452
+ expect(ListExpiredPendingGuardianRequestsIpcParamsSchema.parse({})).toEqual(
453
+ {},
454
+ );
465
455
 
466
456
  expect(
467
457
  ExpireInteractionBoundIpcResponseSchema.parse({ expired: 3 }),
@@ -189,7 +189,7 @@ export const GUARDIAN_REQUESTS_IPC_METHODS = {
189
189
  decide: "guardian_requests_decide",
190
190
  expire: "guardian_requests_expire",
191
191
  expireInteractionBound: "guardian_requests_expire_interaction_bound",
192
- sweepExpired: "guardian_requests_sweep_expired",
192
+ listExpiredPending: "guardian_requests_list_expired_pending",
193
193
  createDelivery: "guardian_requests_create_delivery",
194
194
  updateDelivery: "guardian_requests_update_delivery",
195
195
  listDeliveries: "guardian_requests_list_deliveries",
@@ -201,6 +201,32 @@ export const GUARDIAN_REQUESTS_IPC_METHODS = {
201
201
  getByPendingQuestion: "guardian_requests_get_by_pending_question",
202
202
  } as const;
203
203
 
204
+ /**
205
+ * The delivery-row statuses this codebase writes and matches on.
206
+ *
207
+ * `GuardianRequestDeliverySchema.status` stays a plain `z.string()` rather
208
+ * than an enum built from these: the column is persisted, so a row written
209
+ * by a different build must still read rather than throw on parse. These
210
+ * constants exist so a call site names a value instead of spelling it, not
211
+ * to close the set.
212
+ *
213
+ * `pending` is the creation default; `sent` and `failed` carry the
214
+ * notification delivery result the recorder maps in; `expired` is stamped
215
+ * when the request itself expires; `withdrawn` is the daemon's per-surface
216
+ * receipt that a card was durably withdrawn, which the gateway's
217
+ * per-request expire preserves and a retrying withdrawal skips.
218
+ */
219
+ export const DELIVERY_STATUS = {
220
+ pending: "pending",
221
+ sent: "sent",
222
+ failed: "failed",
223
+ expired: "expired",
224
+ withdrawn: "withdrawn",
225
+ } as const;
226
+
227
+ export type DeliveryStatus =
228
+ (typeof DELIVERY_STATUS)[keyof typeof DELIVERY_STATUS];
229
+
204
230
  export type GuardianRequestsIpcMethod =
205
231
  (typeof GUARDIAN_REQUESTS_IPC_METHODS)[keyof typeof GUARDIAN_REQUESTS_IPC_METHODS];
206
232
 
@@ -418,7 +444,7 @@ const OUTCOME_TYPES_BY_DECISION_STATUS: Record<
418
444
  /**
419
445
  * Request for `guardian_requests_decide` (status CAS + optional ACL outcome).
420
446
  * Decisions only resolve a pending request to approved/denied — expiry has
421
- * `guardian_requests_expire`/`_sweep_expired` — so a malformed call can never
447
+ * `guardian_requests_expire`/`_list_expired_pending`, so a malformed call can never
422
448
  * apply an `aclOutcome` while leaving the request decidable again. The
423
449
  * outcome type must agree with the status: activation/minting only on
424
450
  * approval, seeding/blocking only on denial.
@@ -508,26 +534,22 @@ export type ExpireInteractionBoundIpcResponse = z.infer<
508
534
  typeof ExpireInteractionBoundIpcResponseSchema
509
535
  >;
510
536
 
511
- /** Request for `guardian_requests_sweep_expired` (`now` defaults gateway-side). */
512
- export const SweepExpiredGuardianRequestsIpcParamsSchema = z.object({
513
- now: z.number().optional(),
514
- });
515
-
516
- export type SweepExpiredGuardianRequestsIpcParams = z.infer<
517
- typeof SweepExpiredGuardianRequestsIpcParamsSchema
518
- >;
519
-
520
537
  /**
521
- * Response for `guardian_requests_sweep_expired`: the full expired rows, so
522
- * the daemon's card-withdrawal/notification fan-out never needs a follow-up
523
- * read that could fail after the status flip and strand the side effects.
538
+ * Request for `guardian_requests_list_expired_pending` (`now` defaults
539
+ * gateway-side; `limit` bounds the batch and is capped gateway-side).
540
+ * Read-only: the rows stay `pending` until the daemon has run each one's
541
+ * expiry side effects and confirms with `guardian_requests_expire`, so a
542
+ * lost response leaves the work discoverable by the next sweep round
543
+ * instead of silently done. Past-deadline pending rows are undecidable
544
+ * either way: every decision path checks `expiresAt` before any write.
524
545
  */
525
- export const SweepExpiredGuardianRequestsIpcResponseSchema = z.object({
526
- expired: z.array(GuardianRequestSchema),
546
+ export const ListExpiredPendingGuardianRequestsIpcParamsSchema = z.object({
547
+ now: z.number().optional(),
548
+ limit: z.number().optional(),
527
549
  });
528
550
 
529
- export type SweepExpiredGuardianRequestsIpcResponse = z.infer<
530
- typeof SweepExpiredGuardianRequestsIpcResponseSchema
551
+ export type ListExpiredPendingGuardianRequestsIpcParams = z.infer<
552
+ typeof ListExpiredPendingGuardianRequestsIpcParamsSchema
531
553
  >;
532
554
 
533
555
  // ---------------------------------------------------------------------------
@@ -268,8 +268,8 @@ export {
268
268
  ListGuardianRequestsIpcParamsSchema,
269
269
  ListPendingGuardianRequestsByDestinationIpcParamsSchema,
270
270
  ListPendingGuardianRequestsByScopeIpcParamsSchema,
271
- SweepExpiredGuardianRequestsIpcParamsSchema,
272
- SweepExpiredGuardianRequestsIpcResponseSchema,
271
+ DELIVERY_STATUS,
272
+ ListExpiredPendingGuardianRequestsIpcParamsSchema,
273
273
  UpdateGuardianRequestDeliveryIpcParamsSchema,
274
274
  UpdateGuardianRequestIpcParamsSchema,
275
275
  } from "./guardian-request-contract.js";
@@ -279,6 +279,7 @@ export type {
279
279
  CreateGuardianRequestIpcParams,
280
280
  DecideGuardianRequestIpcParams,
281
281
  DecideGuardianRequestIpcResponse,
282
+ DeliveryStatus,
282
283
  ExpireGuardianRequestIpcParams,
283
284
  ExpireInteractionBoundIpcParams,
284
285
  ExpireInteractionBoundIpcResponse,
@@ -306,8 +307,7 @@ export type {
306
307
  ListGuardianRequestsIpcParams,
307
308
  ListPendingGuardianRequestsByDestinationIpcParams,
308
309
  ListPendingGuardianRequestsByScopeIpcParams,
309
- SweepExpiredGuardianRequestsIpcParams,
310
- SweepExpiredGuardianRequestsIpcResponse,
310
+ ListExpiredPendingGuardianRequestsIpcParams,
311
311
  UpdateGuardianRequestDeliveryIpcParams,
312
312
  UpdateGuardianRequestIpcParams,
313
313
  } from "./guardian-request-contract.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.11.7-dev.202608282003.8ce5421",
3
+ "version": "0.11.7-dev.202608282208.54fd2e3",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -1,7 +1,7 @@
1
1
  import { beforeEach, describe, expect, mock, test } from "bun:test";
2
2
 
3
- const completeSurfaceAndNotify = mock(() => {});
4
- const markSurfaceCompleted = mock(() => {});
3
+ const completeSurfaceAndNotify = mock(() => true);
4
+ const markSurfaceCompleted = mock(() => true);
5
5
  mock.module("../daemon/conversation-surfaces.js", () => ({
6
6
  completeSurfaceAndNotify,
7
7
  markSurfaceCompleted,
@@ -20,7 +20,7 @@ mock.module("../messaging/providers/discord/withdraw.js", () => ({
20
20
  }));
21
21
 
22
22
  const withdrawTelegramApprovalCard = mock(
23
- async (_params: Record<string, unknown>) => {},
23
+ async (_params: Record<string, unknown>) => ({ complete: true }),
24
24
  );
25
25
  mock.module("../messaging/providers/telegram-bot/withdraw.js", () => ({
26
26
  withdrawTelegramApprovalCard,
@@ -355,7 +355,7 @@ describe("withdrawGuardianRequestCards", () => {
355
355
  status: "approved",
356
356
  originChannel: "telegram",
357
357
  }),
358
- ).resolves.toBeUndefined();
358
+ ).resolves.toEqual({ complete: false });
359
359
 
360
360
  // The in-app card was still withdrawn despite the Slack failure.
361
361
  expect(completeSurfaceAndNotify).toHaveBeenCalledTimes(1);
@@ -438,8 +438,131 @@ describe("withdrawGuardianRequestCards", () => {
438
438
  "Denied",
439
439
  );
440
440
  });
441
- });
442
441
 
442
+ test("a Telegram keyboard that stayed live holds the completeness back", async () => {
443
+ // The nested boolean is the whole receipt: clearInlineKeyboard already
444
+ // reports the failed edit, and dropping it once made the sweep confirm
445
+ // an expiry while the card's buttons stayed actionable.
446
+ const req = makeRequest({ sourceChannel: "telegram" });
447
+ bridgeState.seedDelivery({
448
+ requestId: req.id,
449
+ destinationChannel: "telegram",
450
+ destinationChatId: "T1",
451
+ destinationMessageId: "9",
452
+ });
453
+ withdrawTelegramApprovalCard.mockResolvedValueOnce({ complete: false });
454
+
455
+ const result = await withdrawGuardianRequestCards({
456
+ request: req,
457
+ status: "expired",
458
+ });
459
+
460
+ expect(result.complete).toBe(false);
461
+ });
462
+
463
+ test("a failed in-app persistence write holds the completeness back", async () => {
464
+ // markSurfaceCompleted's false means the persisted block reverts to a
465
+ // pending, clickable card on the next reload; the broadcast still goes
466
+ // out, but the caller's receipt must wait for a durable write.
467
+ const req = makeRequest();
468
+ bridgeState.seedDelivery({
469
+ requestId: req.id,
470
+ destinationChannel: "vellum",
471
+ destinationConversationId: "conv-1",
472
+ });
473
+ completeSurfaceAndNotify.mockReturnValueOnce(false);
474
+
475
+ const result = await withdrawGuardianRequestCards({
476
+ request: req,
477
+ status: "expired",
478
+ });
479
+
480
+ expect(result.complete).toBe(false);
481
+ });
482
+
483
+ test("a surface that succeeded on retry reports complete", async () => {
484
+ const req = makeRequest({ sourceChannel: "telegram" });
485
+ bridgeState.seedDelivery({
486
+ requestId: req.id,
487
+ destinationChannel: "telegram",
488
+ destinationChatId: "T1",
489
+ destinationMessageId: "9",
490
+ });
491
+
492
+ const result = await withdrawGuardianRequestCards({
493
+ request: req,
494
+ status: "expired",
495
+ });
496
+
497
+ expect(result.complete).toBe(true);
498
+ });
499
+
500
+ test("each durably withdrawn surface marks its delivery row as the receipt", async () => {
501
+ const req = makeRequest();
502
+ const slack = bridgeState.seedDelivery({
503
+ requestId: req.id,
504
+ destinationChannel: "slack",
505
+ destinationChatId: "C1",
506
+ destinationMessageId: "1.0",
507
+ });
508
+ const vellum = bridgeState.seedDelivery({
509
+ requestId: req.id,
510
+ destinationChannel: "vellum",
511
+ destinationConversationId: "conv-1",
512
+ });
513
+
514
+ const result = await withdrawGuardianRequestCards({
515
+ request: req,
516
+ status: "expired",
517
+ });
518
+
519
+ expect(result.complete).toBe(true);
520
+ const byId = new Map(deliveriesFor(req.id).map((d) => [d.id, d.status]));
521
+ expect(byId.get(slack.id)).toBe("withdrawn");
522
+ expect(byId.get(vellum.id)).toBe("withdrawn");
523
+ });
524
+
525
+ test("a retry skips rows already withdrawn: no re-edits, no re-broadcasts", async () => {
526
+ // The delivery row is the per-surface receipt. When one surface fails,
527
+ // the next round must retry only that surface; re-editing the others
528
+ // would re-broadcast in-app completions and re-run channel edits that
529
+ // already landed.
530
+ const req = makeRequest({ sourceChannel: "telegram" });
531
+ const slack = bridgeState.seedDelivery({
532
+ requestId: req.id,
533
+ destinationChannel: "slack",
534
+ destinationChatId: "C1",
535
+ destinationMessageId: "1.0",
536
+ });
537
+ const telegram = bridgeState.seedDelivery({
538
+ requestId: req.id,
539
+ destinationChannel: "telegram",
540
+ destinationChatId: "T1",
541
+ destinationMessageId: "9",
542
+ });
543
+ withdrawTelegramApprovalCard.mockResolvedValueOnce({ complete: false });
544
+
545
+ const first = await withdrawGuardianRequestCards({
546
+ request: req,
547
+ status: "expired",
548
+ });
549
+ expect(first.complete).toBe(false);
550
+ let byId = new Map(deliveriesFor(req.id).map((d) => [d.id, d.status]));
551
+ expect(byId.get(slack.id)).toBe("withdrawn");
552
+ expect(byId.get(telegram.id)).not.toBe("withdrawn");
553
+
554
+ const second = await withdrawGuardianRequestCards({
555
+ request: req,
556
+ status: "expired",
557
+ });
558
+ expect(second.complete).toBe(true);
559
+ byId = new Map(deliveriesFor(req.id).map((d) => [d.id, d.status]));
560
+ expect(byId.get(telegram.id)).toBe("withdrawn");
561
+ // The already-receipted Slack surface was not re-edited.
562
+ expect(withdrawSlackApprovalCard).toHaveBeenCalledTimes(1);
563
+ expect(withdrawTelegramApprovalCard).toHaveBeenCalledTimes(2);
564
+ });
565
+ });
443
566
  describe("recordApprovalCardDelivery", () => {
444
567
  beforeEach(() => {
445
568
  bridgeState.reset();
@@ -38,35 +38,49 @@ mock.module("../runtime/assistant-event-hub.js", () => ({
38
38
  },
39
39
  }));
40
40
 
41
- // The sweep withdraws cards via this module; we only assert it is invoked, and
42
- // mocking it keeps the sweep import light (no surface/slack transitive deps).
41
+ // The sweep withdraws cards via this module; mocking it keeps the sweep
42
+ // import light (no surface/slack transitive deps). The completeness result
43
+ // gates the sweep's expire confirmation.
43
44
  let withdrawCalls = 0;
45
+ let withdrawIncomplete = false;
44
46
  mock.module("../approvals/guardian-card-withdrawal.js", () => ({
45
47
  withdrawGuardianRequestCards: async () => {
46
48
  withdrawCalls++;
49
+ return { complete: !withdrawIncomplete };
47
50
  },
48
51
  }));
49
52
 
50
- // Gateway guardian-request client — in-memory rows driven by tests. The sweep
51
- // asks the gateway to CAS-expire past-deadline pending rows and fans out
52
- // notifications from the returned rows.
53
+ // Gateway guardian-request client, in-memory rows driven by tests. The
54
+ // sweep lists past-deadline pending rows read-only and confirms each with
55
+ // the per-request expire CAS after its side effects run.
53
56
  const gatewayRequests = new Map<string, GuardianRequestWire>();
57
+ let expireCasFails = false;
58
+ const actualGatewayGuardianRequests =
59
+ await import("../channels/gateway-guardian-requests.js");
54
60
  mock.module("../channels/gateway-guardian-requests.js", () => ({
55
- sweepExpiredGuardianRequests: async () => {
61
+ ...actualGatewayGuardianRequests,
62
+ listExpiredPendingGuardianRequests: async () => {
56
63
  const now = Date.now();
57
- const expired: GuardianRequestWire[] = [];
64
+ const stale: GuardianRequestWire[] = [];
58
65
  for (const row of gatewayRequests.values()) {
59
66
  if (
60
67
  row.status === "pending" &&
61
68
  row.expiresAt !== null &&
62
69
  row.expiresAt <= now
63
70
  ) {
64
- const flipped = { ...row, status: "expired" as const };
65
- gatewayRequests.set(row.id, flipped);
66
- expired.push(flipped);
71
+ stale.push(row);
67
72
  }
68
73
  }
69
- return expired;
74
+ return stale;
75
+ },
76
+ expireGuardianRequest: async (id: string) => {
77
+ if (expireCasFails) {
78
+ throw new Error("simulated IPC timeout");
79
+ }
80
+ const row = gatewayRequests.get(id);
81
+ if (row?.status === "pending") {
82
+ gatewayRequests.set(id, { ...row, status: "expired" as const });
83
+ }
70
84
  },
71
85
  }));
72
86
 
@@ -117,6 +131,9 @@ beforeEach(() => {
117
131
  broadcasts.length = 0;
118
132
  deliveryError = null;
119
133
  withdrawCalls = 0;
134
+ withdrawIncomplete = false;
135
+ expireCasFails = false;
136
+ gatewayRequests.clear();
120
137
  pendingInteractions.clear();
121
138
  });
122
139
 
@@ -229,7 +246,7 @@ describe("notifyExpiredGuardianRequest", () => {
229
246
  expect(deliveredReplies).toHaveLength(0);
230
247
  });
231
248
 
232
- test("delivery failure is swallowed (best-effort)", async () => {
249
+ test("delivery failure never throws, and reports incomplete", async () => {
233
250
  deliveryError = new Error("gateway down");
234
251
 
235
252
  await expect(
@@ -240,7 +257,7 @@ describe("notifyExpiredGuardianRequest", () => {
240
257
  requesterChatId: "tg-chat",
241
258
  }),
242
259
  ),
243
- ).resolves.toBeUndefined();
260
+ ).resolves.toEqual({ complete: false });
244
261
  });
245
262
  });
246
263
 
@@ -291,4 +308,91 @@ describe("sweep integration", () => {
291
308
  expect(gatewayRequests.get("req-fresh")?.status).toBe("pending");
292
309
  expect(deliveredReplies).toHaveLength(0);
293
310
  });
311
+
312
+ test("an incomplete withdrawal defers the request and holds the notice back", async () => {
313
+ // A card edit that failed leaves an actionable control somewhere, so the
314
+ // request must stay pending and retryable. The notice is held back too:
315
+ // sending it only after withdrawal completes means the retry round can
316
+ // never duplicate a delivered notice.
317
+ gatewayRequests.set(
318
+ "req-withdraw-fail",
319
+ makeRequest({
320
+ id: "req-withdraw-fail",
321
+ kind: "access_request",
322
+ status: "pending",
323
+ requesterChatId: "tg-chat",
324
+ requesterExternalUserId: "tg-user",
325
+ expiresAt: Date.now() - 1000,
326
+ }),
327
+ );
328
+
329
+ withdrawIncomplete = true;
330
+ expect(await runGuardianExpirySweep()).toBe(0);
331
+ expect(gatewayRequests.get("req-withdraw-fail")?.status).toBe("pending");
332
+ expect(deliveredReplies).toHaveLength(0);
333
+
334
+ withdrawIncomplete = false;
335
+ expect(await runGuardianExpirySweep()).toBe(1);
336
+ expect(gatewayRequests.get("req-withdraw-fail")?.status).toBe("expired");
337
+ expect(deliveredReplies).toHaveLength(1);
338
+ });
339
+
340
+ test("a failed requester notice defers the request until a retry delivers it", async () => {
341
+ gatewayRequests.set(
342
+ "req-notice-fail",
343
+ makeRequest({
344
+ id: "req-notice-fail",
345
+ kind: "access_request",
346
+ status: "pending",
347
+ requesterChatId: "tg-chat",
348
+ requesterExternalUserId: "tg-user",
349
+ expiresAt: Date.now() - 1000,
350
+ }),
351
+ );
352
+
353
+ deliveryError = new Error("channel briefly unreachable");
354
+ expect(await runGuardianExpirySweep()).toBe(0);
355
+ expect(gatewayRequests.get("req-notice-fail")?.status).toBe("pending");
356
+ expect(deliveredReplies).toHaveLength(0);
357
+
358
+ deliveryError = null;
359
+ expect(await runGuardianExpirySweep()).toBe(1);
360
+ expect(gatewayRequests.get("req-notice-fail")?.status).toBe("expired");
361
+ // The notice lands exactly once: the failed attempt delivered nothing.
362
+ expect(deliveredReplies).toHaveLength(1);
363
+ });
364
+
365
+ test("a lost expire confirmation leaves the row pending, and the next round recovers it", async () => {
366
+ // The status flip is the receipt that side effects ran, not the
367
+ // announcement that they should. When the confirmation is lost, the row
368
+ // must stay in the pending set so the next round re-runs its fan-out;
369
+ // the cost is at-least-once side effects, never their silent loss.
370
+ gatewayRequests.set(
371
+ "req-lost",
372
+ makeRequest({
373
+ id: "req-lost",
374
+ kind: "access_request",
375
+ status: "pending",
376
+ requesterChatId: "tg-chat",
377
+ requesterExternalUserId: "tg-user",
378
+ expiresAt: Date.now() - 1000,
379
+ }),
380
+ );
381
+
382
+ expireCasFails = true;
383
+ expect(await runGuardianExpirySweep()).toBe(0);
384
+ expect(gatewayRequests.get("req-lost")?.status).toBe("pending");
385
+ expect(withdrawCalls).toBe(1);
386
+ expect(deliveredReplies).toHaveLength(1);
387
+
388
+ expireCasFails = false;
389
+ expect(await runGuardianExpirySweep()).toBe(1);
390
+ expect(gatewayRequests.get("req-lost")?.status).toBe("expired");
391
+ // The re-run repeats the side effects (at-least-once); the third round
392
+ // finds nothing.
393
+ expect(withdrawCalls).toBe(2);
394
+ expect(deliveredReplies).toHaveLength(2);
395
+ expect(await runGuardianExpirySweep()).toBe(0);
396
+ expect(withdrawCalls).toBe(2);
397
+ });
294
398
  });