@vellumai/assistant 0.11.4-dev.202608182307.5f98f27 → 0.11.4-dev.202608190019.b94dbf2

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.11.4-dev.202608182307.5f98f27",
3
+ "version": "0.11.4-dev.202608190019.b94dbf2",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -99,7 +99,6 @@ const BASELINE: Record<string, readonly string[]> = {
99
99
  "../../../../../security/untrusted-content.js",
100
100
  "../../../../api/events/memory-recalled.js",
101
101
  "../../../../api/responses/memory-v3-selection-log.js",
102
- "../../../../channels/types.js",
103
102
  "../../../../config/assistant-feature-flags.js",
104
103
  "../../../../config/default-profile-catalog.js",
105
104
  "../../../../config/loader.js",
@@ -99,7 +99,6 @@ const BASELINE: Record<string, readonly string[]> = {
99
99
  "src/daemon/handlers/skills.ts",
100
100
  "src/daemon/skill-memory-refresh.ts",
101
101
  "src/daemon/tool-side-effects.ts",
102
- "src/daemon/trust-context.ts",
103
102
  "src/home/feed-source-enrichment.ts",
104
103
  "src/permissions/checker.ts",
105
104
  "src/persistence/conversation-crud.ts",
@@ -1827,6 +1827,13 @@ export interface ProcessMessageOptions {
1827
1827
  displayContent?: string;
1828
1828
  /** JWT-verified committer principal for turn-scoped host-proxy authorization. */
1829
1829
  sourceActorPrincipalId?: string;
1830
+ /**
1831
+ * The actor this turn is being started for. Stamped onto the conversation
1832
+ * before history is scoped, so the run hydrates as its committer rather
1833
+ * than as whoever last left the resting slot set. Callers with no actor of
1834
+ * their own (internal dispatch) omit it and the resting actor stands.
1835
+ */
1836
+ trustContext?: TrustContext;
1830
1837
  /**
1831
1838
  * True when this turn was auto-sent on the user's behalf rather than typed
1832
1839
  * (see `PersistMessageOptions.scripted`). Forwarded to persistence so the
@@ -1873,7 +1880,11 @@ export async function processMessage(
1873
1880
  sourceActorPrincipalId,
1874
1881
  scripted,
1875
1882
  metadata: callerMetadata,
1883
+ trustContext: committingTrustContext,
1876
1884
  } = options;
1885
+ if (committingTrustContext) {
1886
+ conversation.setTrustContext(committingTrustContext);
1887
+ }
1877
1888
  await conversation.ensureActorScopedHistory();
1878
1889
  // Snapshot persona context at turn start so later tool turns can't pick up
1879
1890
  // a different actor's context if a concurrent request mutates the live fields.
@@ -85,6 +85,8 @@ import type {
85
85
  } from "./message-protocol.js";
86
86
  import { INTERACTIVE_SURFACE_TYPES } from "./message-protocol.js";
87
87
  import { isRowVisibleToUntrustedActor } from "./message-provenance.js";
88
+ import type { TrustContext } from "./trust-context-types.js";
89
+ import { restingTrust } from "./trust-context-types.js";
88
90
  export {
89
91
  buildSurfaceShowPair,
90
92
  type CurrentTurnSurface,
@@ -1904,7 +1906,13 @@ export async function handleSurfaceAction(
1904
1906
  // reconstruct the same-user binding for host proxies (CU / app-control),
1905
1907
  // mirroring the normal message path.
1906
1908
  sourceActorPrincipalId?: string,
1909
+ // Trust of the actor committing this action, resolved by the route from the
1910
+ // verified requester. Passed rather than read back off the conversation so a
1911
+ // click that lands mid-turn is attributed to its clicker instead of to
1912
+ // whoever occupies the resting slot.
1913
+ requesterTrustContext?: TrustContext,
1907
1914
  ): Promise<SurfaceActionResult> {
1915
+ const actionTrustContext = requesterTrustContext ?? restingTrust(ctx);
1908
1916
  // ── Standalone surface interception ──────────────────────────────
1909
1917
  // Daemon-driven surfaces (from `requestInteractiveUi`) register a
1910
1918
  // pending entry in `pendingStandaloneSurfaces`. When the user clicks
@@ -2050,7 +2058,7 @@ export async function handleSurfaceAction(
2050
2058
  // `await` resolves as soon as the conversation is created + titled +
2051
2059
  // published to the event hub. The HTTP POST /v1/surface-actions
2052
2060
  // response returns promptly — the seed turn runs in the background.
2053
- const originTrustContext = ctx.trustContext;
2061
+ const originTrustContext = actionTrustContext;
2054
2062
  const { conversationId } = await launchConversation({
2055
2063
  title,
2056
2064
  seedPrompt,
@@ -2069,14 +2077,11 @@ export async function handleSurfaceAction(
2069
2077
  return { accepted: true, conversationId };
2070
2078
  }
2071
2079
 
2072
- // Trust of the actor committing THIS action. `POST /v1/surface-actions`
2073
- // stamps the verified requester's trust onto the conversation before
2074
- // dispatching here, and `loadFromDb` derives the live history filter from
2075
- // the same value, so the completion path's persisted read stays scoped to
2076
- // exactly what this actor's live view would have held. Unresolvable trust
2077
- // fails closed to the untrusted filter.
2080
+ // Trust of the actor committing THIS action, so the completion path's
2081
+ // persisted read stays scoped to exactly what this actor's live view would
2082
+ // have held. Unresolvable trust fails closed to the untrusted filter.
2078
2083
  const requesterCanAccessMemory = resolveCapabilities(
2079
- ctx.trustContext?.trustClass,
2084
+ actionTrustContext?.trustClass,
2080
2085
  ).canAccessMemory;
2081
2086
 
2082
2087
  const pending = ctx.pendingSurfaceActions.get(surfaceId);
@@ -2222,6 +2227,7 @@ export async function handleSurfaceAction(
2222
2227
  activeSurfaceId: surfaceId,
2223
2228
  displayContent,
2224
2229
  sourceActorPrincipalId,
2230
+ trustContext: actionTrustContext,
2225
2231
  isInteractive: SURFACE_ACTION_TURN_IS_INTERACTIVE,
2226
2232
  // Rides the metadata bag rather than a typed option: the queue
2227
2233
  // round-trips `metadata` but not `PersistMessageOptions`.
@@ -2285,6 +2291,9 @@ export async function handleSurfaceAction(
2285
2291
  activeSurfaceId: surfaceId,
2286
2292
  displayContent,
2287
2293
  sourceActorPrincipalId,
2294
+ // Reached only when `enqueueMessage` declined to queue: the click is
2295
+ // starting this turn, so it is the actor the run belongs to.
2296
+ trustContext: actionTrustContext,
2288
2297
  isInteractive: SURFACE_ACTION_TURN_IS_INTERACTIVE,
2289
2298
  scripted: isSyntheticSurfaceActionContent(content),
2290
2299
  })
@@ -2472,6 +2481,7 @@ export async function handleSurfaceAction(
2472
2481
  activeSurfaceId: surfaceId,
2473
2482
  displayContent,
2474
2483
  sourceActorPrincipalId,
2484
+ trustContext: actionTrustContext,
2475
2485
  isInteractive: SURFACE_ACTION_TURN_IS_INTERACTIVE,
2476
2486
  // Rides the metadata bag rather than a typed option: the queue
2477
2487
  // round-trips `metadata` but not `PersistMessageOptions`.
@@ -2545,6 +2555,9 @@ export async function handleSurfaceAction(
2545
2555
  activeSurfaceId: surfaceId,
2546
2556
  displayContent,
2547
2557
  sourceActorPrincipalId,
2558
+ // Same as the history-restored branch: the enqueue declined, so this
2559
+ // click is the turn about to run.
2560
+ trustContext: actionTrustContext,
2548
2561
  isInteractive: SURFACE_ACTION_TURN_IS_INTERACTIVE,
2549
2562
  scripted: isSyntheticSurfaceActionContent(content),
2550
2563
  })
@@ -2829,6 +2829,7 @@ export class Conversation {
2829
2829
  actionId: string,
2830
2830
  data?: Record<string, unknown>,
2831
2831
  sourceActorPrincipalId?: string,
2832
+ requesterTrustContext?: TrustContext,
2832
2833
  ): Promise<SurfaceActionResult> {
2833
2834
  return handleSurfaceActionImpl(
2834
2835
  this,
@@ -2836,6 +2837,7 @@ export class Conversation {
2836
2837
  actionId,
2837
2838
  data,
2838
2839
  sourceActorPrincipalId,
2840
+ requesterTrustContext,
2839
2841
  );
2840
2842
  }
2841
2843
 
@@ -7,7 +7,7 @@
7
7
  import type { ChannelConversationType } from "@vellumai/gateway-client";
8
8
 
9
9
  import { isHttpAuthDisabled } from "../config/env.js";
10
- import { shouldExposePersonalMemory } from "../plugins/defaults/memory/substrate/static-context.js";
10
+ import { canSeePersonalMemory } from "../runtime/effective-capabilities.js";
11
11
  import type { TrustClass } from "../runtime/trust-class.js";
12
12
  import type { TrustContext } from "./trust-context-types.js";
13
13
 
@@ -67,21 +67,26 @@ export function resolveTrustClass(
67
67
  * Whether personal-memory content may be surfaced for the actor described by
68
68
  * `trustContext`: the gate admits guardian-class actors and internal/local
69
69
  * flows (including turns with no trust context), and blocks remote untrusted
70
- * actors — see {@link shouldExposePersonalMemory} for the rationale.
70
+ * actors.
71
71
  *
72
72
  * This is THE personal-memory trust gate. Every surface that exposes private
73
73
  * user content — the v2 dynamic/static `<memory>` layers, PKB context, NOW.md,
74
74
  * memory-v3 cards/spotlight, and the `loadFromDb` rehydration of persisted
75
75
  * memory blocks — must call this one helper so the exposure rule cannot drift
76
- * between copies. It folds in {@link resolveTrustClass} so the dev-bypass
77
- * (HTTP auth disabled → guardian) applies uniformly at every call site.
76
+ * between copies.
77
+ *
78
+ * The trust-context binding lives here; the policy itself is
79
+ * {@link canSeePersonalMemory}, alongside the other capability-plus-context
80
+ * compositions. This adapter folds in {@link resolveTrustClass} so the
81
+ * dev-bypass (HTTP auth disabled → guardian) applies uniformly at every call
82
+ * site.
78
83
  */
79
84
  export function isPersonalMemoryAllowed(
80
85
  trustContext: TrustContext | undefined,
81
86
  ): boolean {
82
- return shouldExposePersonalMemory({
83
- sourceChannel: trustContext?.sourceChannel,
84
- isTrustedActor: resolveTrustClass(trustContext) === "guardian",
87
+ return canSeePersonalMemory({
88
+ trustClass: resolveTrustClass(trustContext),
89
+ executionChannel: trustContext?.sourceChannel,
85
90
  });
86
91
  }
87
92
 
@@ -151,7 +151,6 @@ const HOST_TIER_IMPORT_ALLOWLIST: readonly HostTierImportExemption[] = [
151
151
  { path: "src/daemon/embedding-reconcile.ts", tiers: ["substrate", "v3"] },
152
152
  { path: "src/daemon/skill-memory-refresh.ts", tiers: ["substrate"] },
153
153
  { path: "src/daemon/tool-side-effects.ts", tiers: ["substrate"] },
154
- { path: "src/daemon/trust-context.ts", tiers: ["substrate"] },
155
154
  { path: "src/persistence/steps.ts", tiers: ["v1"] },
156
155
  { path: "src/runtime/routes/consolidation-routes.ts", tiers: ["substrate"] },
157
156
  {
@@ -50,8 +50,7 @@ mock.module("../../config.js", () => ({
50
50
  }),
51
51
  }));
52
52
 
53
- const { readMemoryV2StaticContent, shouldExposePersonalMemory } =
54
- await import("../static-context.js");
53
+ const { readMemoryV2StaticContent } = await import("../static-context.js");
55
54
 
56
55
  const MEMORY_FILES = [
57
56
  "essentials.md",
@@ -361,62 +360,3 @@ describe("readMemoryV2StaticContent Buffer cap", () => {
361
360
  expect(lines.some((line) => line.endsWith("entry-0"))).toBe(false);
362
361
  });
363
362
  });
364
-
365
- describe("shouldExposePersonalMemory", () => {
366
- test("allows guardian-trusted local conversations", () => {
367
- expect(
368
- shouldExposePersonalMemory({
369
- sourceChannel: "vellum",
370
- isTrustedActor: true,
371
- }),
372
- ).toBe(true);
373
- });
374
-
375
- test("allows local-channel conversations even when trust class is unknown (analyze runs, dev)", () => {
376
- expect(
377
- shouldExposePersonalMemory({
378
- sourceChannel: "vellum",
379
- isTrustedActor: false,
380
- }),
381
- ).toBe(true);
382
- });
383
-
384
- test("allows turns with no trust context (work-item task runs, internal background)", () => {
385
- expect(
386
- shouldExposePersonalMemory({
387
- sourceChannel: undefined,
388
- isTrustedActor: false,
389
- }),
390
- ).toBe(true);
391
- });
392
-
393
- const REMOTE_CHANNELS = [
394
- "phone",
395
- "slack",
396
- "telegram",
397
- "whatsapp",
398
- "email",
399
- ] as const;
400
-
401
- test("allows guardian-trusted remote channels (user's own phone/Slack)", () => {
402
- for (const channel of REMOTE_CHANNELS) {
403
- expect(
404
- shouldExposePersonalMemory({
405
- sourceChannel: channel,
406
- isTrustedActor: true,
407
- }),
408
- ).toBe(true);
409
- }
410
- });
411
-
412
- test("blocks non-guardian remote-channel actors (the leak this gate exists to prevent)", () => {
413
- for (const channel of REMOTE_CHANNELS) {
414
- expect(
415
- shouldExposePersonalMemory({
416
- sourceChannel: channel,
417
- isTrustedActor: false,
418
- }),
419
- ).toBe(false);
420
- }
421
- });
422
- });
@@ -26,7 +26,6 @@
26
26
  // bounded only by how far behind consolidation has fallen. The injected
27
27
  // Buffer section is therefore capped: see `capBufferSection`.
28
28
 
29
- import type { ChannelId } from "../../../../channels/types.js";
30
29
  import { usesConceptPageMemory } from "../../../../config/memory-v3-gate.js";
31
30
  import { readPromptFile } from "../../../../prompts/system-prompt.js";
32
31
  import { type BufferEntryLines, splitBufferEntries } from "../buffer-format.js";
@@ -227,31 +226,3 @@ export function readMemoryV2StaticContent(
227
226
  }
228
227
  return sections.length > 0 ? sections.join("\n\n") : null;
229
228
  }
230
-
231
- /**
232
- * Trust-class predicate for personal-memory injection. Personal memory
233
- * spans v2 static blocks (essentials/threads/recent/buffer), the PKB
234
- * context, and NOW.md — all of which can hold private user content. Block
235
- * injection when a non-guardian actor reaches the assistant over a remote
236
- * channel — otherwise the model can be prompt-injected into reciting
237
- * private memory. Internal flows (`sourceChannel: "vellum"`) and turns
238
- * with no trust context pass through unchanged; this gate exists only to
239
- * keep remote untrusted actors out.
240
- *
241
- * This is the trust-only gate. Cadence (first-turn / post-compaction) is
242
- * applied separately by the caller so that the freshest content remains
243
- * available for re-injection after a mid-turn reducer-triggered compaction
244
- * — the initial-injection turn may not have been a `shouldInjectNowAndPkb`
245
- * turn, but compaction strips the existing personal-memory blocks and we
246
- * still need the freshest content to re-inject.
247
- */
248
- export function shouldExposePersonalMemory(args: {
249
- sourceChannel: ChannelId | undefined;
250
- isTrustedActor: boolean;
251
- }): boolean {
252
- const isRemoteUntrustedActor =
253
- args.sourceChannel !== undefined &&
254
- args.sourceChannel !== "vellum" &&
255
- !args.isTrustedActor;
256
- return !isRemoteUntrustedActor;
257
- }
@@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test";
2
2
 
3
3
  import {
4
4
  canActOnPrivilegedDocuments,
5
+ canSeePersonalMemory,
5
6
  isArchiveBySenderAuthorized,
6
7
  } from "./effective-capabilities.js";
7
8
 
@@ -90,3 +91,45 @@ describe("isArchiveBySenderAuthorized", () => {
90
91
  ).toBe(false);
91
92
  });
92
93
  });
94
+
95
+ describe("canSeePersonalMemory", () => {
96
+ test("guardian keeps memory on every channel", () => {
97
+ for (const executionChannel of [undefined, "vellum", "slack", "phone"]) {
98
+ expect(
99
+ canSeePersonalMemory({ trustClass: "guardian", executionChannel }),
100
+ ).toBe(true);
101
+ }
102
+ });
103
+
104
+ test("no channel means no actor was resolved, which is a local/native turn", () => {
105
+ // A resolved actor always carries a channel, so absence is a signal rather
106
+ // than a permissive default.
107
+ expect(canSeePersonalMemory({ trustClass: undefined })).toBe(true);
108
+ expect(canSeePersonalMemory({ trustClass: "unknown" })).toBe(true);
109
+ });
110
+
111
+ test("a non-guardian is denied memory on remote channels", () => {
112
+ for (const executionChannel of ["slack", "phone", "email", "telegram"]) {
113
+ expect(
114
+ canSeePersonalMemory({
115
+ trustClass: "unverified_contact",
116
+ executionChannel,
117
+ }),
118
+ ).toBe(false);
119
+ }
120
+ });
121
+
122
+ test("a non-guardian on the first-party console currently keeps memory", () => {
123
+ // Pins today's channel override so a change to it is a deliberate,
124
+ // visible edit rather than a silent drift.
125
+ for (const trustClass of [
126
+ "trusted_contact",
127
+ "unverified_contact",
128
+ "unknown",
129
+ ]) {
130
+ expect(
131
+ canSeePersonalMemory({ trustClass, executionChannel: "vellum" }),
132
+ ).toBe(true);
133
+ }
134
+ });
135
+ });
@@ -44,6 +44,33 @@ export function canActOnPrivilegedDocuments(actor: {
44
44
  );
45
45
  }
46
46
 
47
+ /**
48
+ * Channels whose actors see personal memory regardless of trust class. The
49
+ * `vellum` first-party console is the operator's own surface rather than an
50
+ * external contact channel, mirroring {@link PRIVILEGED_DOCUMENT_CHANNELS}.
51
+ */
52
+ const PERSONAL_MEMORY_CHANNELS = new Set<string>(["vellum"]);
53
+
54
+ /**
55
+ * Whether personal-memory content (memory pages, PKB, matched v3 card
56
+ * sections, the v2 static block) may be surfaced to an actor.
57
+ *
58
+ * True when the trust class grants it, when the request arrived on a personal
59
+ * memory channel, or when no channel is present at all -- a resolved actor
60
+ * always carries one, so its absence means no actor was resolved, which is how
61
+ * local/native turns arrive.
62
+ */
63
+ export function canSeePersonalMemory(actor: {
64
+ trustClass: RawTrustClass;
65
+ executionChannel?: string;
66
+ }): boolean {
67
+ return (
68
+ resolveCapabilities(actor.trustClass).canAccessMemory ||
69
+ actor.executionChannel == null ||
70
+ PERSONAL_MEMORY_CHANNELS.has(actor.executionChannel)
71
+ );
72
+ }
73
+
47
74
  /**
48
75
  * Whether an archive-by-sender invocation is authorized. Any one of a surface
49
76
  * action, a task-batch authorization, or an explicit prompt approval suffices.
@@ -26,6 +26,10 @@ interface StubConversation {
26
26
  handleSurfaceUndoCalled?: boolean;
27
27
  handleSurfaceUndoThrows?: Error;
28
28
  trustContext?: { trustClass: string; sourceChannel: string };
29
+ /** Drives `isProcessing()`; the route must not stamp trust either way. */
30
+ processing?: boolean;
31
+ /** Trust the route threaded into `handleSurfaceAction`. */
32
+ lastRequesterTrustContext?: { trustClass: string; sourceChannel: string };
29
33
  surfaceActionCalls: Array<{
30
34
  surfaceId: string;
31
35
  actionId: string;
@@ -160,7 +164,9 @@ function makeStub(id: string): StubConversation {
160
164
  actionId: string,
161
165
  data: unknown,
162
166
  sourceActorPrincipalId?: string,
167
+ requesterTrustContext?: { trustClass: string; sourceChannel: string },
163
168
  ) => {
169
+ stub.lastRequesterTrustContext = requesterTrustContext;
164
170
  stub.surfaceActionCalls.push({
165
171
  surfaceId,
166
172
  actionId,
@@ -181,6 +187,7 @@ function makeStub(id: string): StubConversation {
181
187
  setTrustContext: (ctx: { trustClass: string; sourceChannel: string }) => {
182
188
  stub.trustContext = ctx;
183
189
  },
190
+ isProcessing: () => stub.processing === true,
184
191
  });
185
192
  return stub;
186
193
  }
@@ -487,8 +494,8 @@ describe("triggerSurfaceAction trust context", () => {
487
494
  headers: { "x-vellum-actor-principal-id": GUARDIAN_PRINCIPAL },
488
495
  });
489
496
 
490
- expect(live.trustContext?.trustClass).toBe("guardian");
491
- expect(live.trustContext?.sourceChannel).toBe("vellum");
497
+ expect(live.lastRequesterTrustContext?.trustClass).toBe("guardian");
498
+ expect(live.lastRequesterTrustContext?.sourceChannel).toBe("vellum");
492
499
  // First-pass resolve already granted guardian, so the drift helper is skipped.
493
500
  expect(reResolveCalls).toEqual([]);
494
501
  });
@@ -506,7 +513,7 @@ describe("triggerSurfaceAction trust context", () => {
506
513
  });
507
514
 
508
515
  expect(reResolveCalls).toEqual([VELLUM_PRINCIPAL_OLD]);
509
- expect(live.trustContext?.trustClass).toBe("unknown");
516
+ expect(live.lastRequesterTrustContext?.trustClass).toBe("unknown");
510
517
  });
511
518
 
512
519
  test("reset drift: helper returns guardian → route adopts it", async () => {
@@ -522,7 +529,7 @@ describe("triggerSurfaceAction trust context", () => {
522
529
  });
523
530
 
524
531
  expect(reResolveCalls).toEqual([VELLUM_PRINCIPAL_OLD]);
525
- expect(live.trustContext?.trustClass).toBe("guardian");
532
+ expect(live.lastRequesterTrustContext?.trustClass).toBe("guardian");
526
533
  });
527
534
 
528
535
  test("dev-bypass resolves the real guardian principal from the gateway, helper not called", async () => {
@@ -539,7 +546,7 @@ describe("triggerSurfaceAction trust context", () => {
539
546
 
540
547
  // The synthetic dev-bypass principal is translated to the real guardian,
541
548
  // yielding a guardian trust context without consulting the drift helper.
542
- expect(live.trustContext?.trustClass).toBe("guardian");
549
+ expect(live.lastRequesterTrustContext?.trustClass).toBe("guardian");
543
550
  expect(reResolveCalls).toEqual([]);
544
551
  });
545
552
 
@@ -559,7 +566,49 @@ describe("triggerSurfaceAction trust context", () => {
559
566
  headers: { "x-vellum-actor-principal-id": "dev-bypass" },
560
567
  });
561
568
 
562
- expect(live.trustContext?.trustClass).toBe("unknown");
569
+ expect(live.lastRequesterTrustContext?.trustClass).toBe("unknown");
570
+ });
571
+
572
+ test("idle conversation: the requester is threaded to the action and the slot is left to the dispatch", async () => {
573
+ mockGuardianList = [guardianDelivery(GUARDIAN_PRINCIPAL)];
574
+ const live = makeStub("conv-idle");
575
+ live.processing = false;
576
+ memoryBySurface = live;
577
+
578
+ const handler = findHandler("triggerSurfaceAction");
579
+ await handler({
580
+ body: { surfaceId: "surf-idle", actionId: "act-idle" },
581
+ headers: { "x-vellum-actor-principal-id": GUARDIAN_PRINCIPAL },
582
+ });
583
+
584
+ expect(live.lastRequesterTrustContext?.trustClass).toBe("guardian");
585
+ // The route resolves; `handleSurfaceAction` stamps, and only where it
586
+ // commits to running the turn. Stamping here would repoint the actor of a
587
+ // turn that starts between this call and the dispatch.
588
+ expect(live.trustContext).toBeUndefined();
589
+ });
590
+
591
+ test("busy conversation: the running turn's actor is left alone and the click still travels as its own actor", async () => {
592
+ mockGuardianList = [guardianDelivery(GUARDIAN_PRINCIPAL)];
593
+ const live = makeStub("conv-busy");
594
+ // A turn is already running under a different actor.
595
+ const runningTurnActor = {
596
+ trustClass: "untrusted",
597
+ sourceChannel: "sms",
598
+ };
599
+ live.trustContext = runningTurnActor;
600
+ live.processing = true;
601
+ memoryBySurface = live;
602
+
603
+ const handler = findHandler("triggerSurfaceAction");
604
+ await handler({
605
+ body: { surfaceId: "surf-busy", actionId: "act-busy" },
606
+ headers: { "x-vellum-actor-principal-id": GUARDIAN_PRINCIPAL },
607
+ });
608
+
609
+ // Identical object, so a re-write of an equal value still fails this.
610
+ expect(live.trustContext).toBe(runningTurnActor);
611
+ expect(live.lastRequesterTrustContext?.trustClass).toBe("guardian");
563
612
  });
564
613
  });
565
614
 
@@ -691,17 +691,16 @@ async function handleRetryLastAssistantTurn({
691
691
  const conversation = await getOrCreateConversationInstance(conversationId);
692
692
  touchConversation(conversationId);
693
693
 
694
- // Bind the requesting actor's trust before the turn. A freshly hydrated
695
- // conversation has no trust context, and `loadFromDb` under an unset
696
- // context filters guardian-provenance history — the re-run would see an
697
- // empty transcript.
694
+ // Resolved before the busy gate so the awaits stay outside the
695
+ // check-then-claim window below, but bound only once the claim succeeds: a
696
+ // retry that loses the race is rejected, and a rejected request must not
697
+ // repoint the conversation's actor at its requester.
698
698
  const actorPrincipalId = headers?.["x-vellum-actor-principal-id"];
699
- conversation.setTrustContext(
700
- await resolveVellumActorTrustContext(actorPrincipalId, {
701
- healResetDrift: true,
702
- }),
699
+ const retryTrustContext = await resolveVellumActorTrustContext(
700
+ actorPrincipalId,
701
+ { healResetDrift: true },
703
702
  );
704
- conversation.currentTurnSourceActorPrincipalId =
703
+ const retrySourceActorPrincipalId =
705
704
  await resolveActorPrincipalIdForLocalGuardian(actorPrincipalId);
706
705
 
707
706
  // Synchronous check-then-claim (no await between them) so a concurrent
@@ -714,6 +713,13 @@ async function handleRetryLastAssistantTurn({
714
713
  }
715
714
  conversation.setProcessing(true);
716
715
 
716
+ // Bind the requesting actor's trust for the turn we just claimed. A freshly
717
+ // hydrated conversation has no trust context, and `loadFromDb` under an
718
+ // unset context filters guardian-provenance history — the re-run would see
719
+ // an empty transcript.
720
+ conversation.setTrustContext(retryTrustContext);
721
+ conversation.currentTurnSourceActorPrincipalId = retrySourceActorPrincipalId;
722
+
717
723
  const requestId = uuidv7();
718
724
  const abortController = new AbortController();
719
725
  let discarded: ReturnType<typeof discardLastAssistantDisplayTurn>;
@@ -1849,6 +1849,11 @@ export async function handleSendMessage(
1849
1849
 
1850
1850
  // Resolve guardian context from the AuthContext's actorPrincipalId via the
1851
1851
  // gateway guardian binding: a vellum principal is the guardian or nobody.
1852
+ //
1853
+ // Resolved into a local; the conversation's slot is stamped only where this
1854
+ // request commits to running a turn, since that write is what supplies the
1855
+ // acting actor for a run and must not fire for a send that merely queues.
1856
+ let resolvedTrustCtx: TrustContext;
1852
1857
  if (actorPrincipalId) {
1853
1858
  // Dev bypass (HTTP auth disabled): the synthetic "dev-bypass" principal
1854
1859
  // won't match any guardian binding. Resolve the real guardian principal and
@@ -1874,7 +1879,7 @@ export async function handleSendMessage(
1874
1879
  trustCtx = healed;
1875
1880
  }
1876
1881
  }
1877
- conversation.setTrustContext(trustCtx);
1882
+ resolvedTrustCtx = trustCtx;
1878
1883
  } else {
1879
1884
  let trustCtx = withSourceChannel(
1880
1885
  sourceChannel,
@@ -1907,22 +1912,19 @@ export async function handleSendMessage(
1907
1912
  );
1908
1913
  }
1909
1914
  }
1910
- conversation.setTrustContext(trustCtx);
1915
+ resolvedTrustCtx = trustCtx;
1911
1916
  }
1912
1917
  } else {
1913
1918
  // Service principals (svc_gateway) or tokens without an actor ID
1914
1919
  // get a minimal guardian context so downstream code has something.
1915
- conversation.setTrustContext({ trustClass: "guardian", sourceChannel });
1920
+ resolvedTrustCtx = { trustClass: "guardian", sourceChannel };
1916
1921
  }
1917
1922
 
1918
- // The trust this request's turn runs under, captured here rather than read
1919
- // back at the agent loop below. Every branch above has just written it and
1920
- // nothing awaits in between, so this is the resolved sender. Between here
1921
- // and the loop the conversation slot is writable by paths that do not own
1922
- // this turn (channel ingress for another actor, live-voice hydration,
1923
- // pointer elevation, the voice bridge), and the loop would otherwise
1924
- // re-read it and run this turn as whoever wrote last.
1925
- const turnTrustContext = conversation.trustContext;
1923
+ // The trust this request's turn runs under: the sender resolved above,
1924
+ // never a read of the shared slot. Between here and the loop that slot is
1925
+ // writable by paths that do not own this turn (channel ingress for another
1926
+ // actor, live-voice hydration, pointer elevation, the voice bridge).
1927
+ const turnTrustContext = resolvedTrustCtx;
1926
1928
 
1927
1929
  const isInteractive = isInteractiveInterface(sourceInterface);
1928
1930
  // Translate the dev-bypass actor principal to the real guardian principal
@@ -2053,12 +2055,15 @@ export async function handleSendMessage(
2053
2055
  requestId: uuidv7(),
2054
2056
  metadata: greetingMeta,
2055
2057
  clientMessageId,
2058
+ // This path answers and returns without starting a turn, so it never
2059
+ // reaches the stamp below; name the sender on the row directly.
2060
+ trustContext: resolvedTrustCtx,
2056
2061
  ...(clientOs ? { requestClientOs: clientOs } : {}),
2057
2062
  });
2058
2063
 
2059
2064
  const conversationId = mapping.conversationId;
2060
2065
  const channelMeta = buildChannelMetadata(sourceChannel, sourceInterface, {
2061
- trustContext: conversation.trustContext,
2066
+ trustContext: resolvedTrustCtx,
2062
2067
  });
2063
2068
 
2064
2069
  const assistantMsg = createAssistantMessage(cannedGreeting);
@@ -2165,10 +2170,9 @@ export async function handleSendMessage(
2165
2170
 
2166
2171
  // Resolve the verified actor's external user ID and principal for inline
2167
2172
  // approval routing from the conversation's guardian context.
2168
- const verifiedActorExternalUserId =
2169
- conversation.trustContext?.guardianExternalUserId;
2173
+ const verifiedActorExternalUserId = resolvedTrustCtx.guardianExternalUserId;
2170
2174
  const verifiedActorPrincipalId =
2171
- conversation.trustContext?.guardianPrincipalId ?? undefined;
2175
+ resolvedTrustCtx.guardianPrincipalId ?? undefined;
2172
2176
 
2173
2177
  // Try to consume the message as a guardian approval/rejection reply.
2174
2178
  // On failure, degrade to the existing queue/auto-deny path rather than
@@ -2242,6 +2246,10 @@ export async function handleSendMessage(
2242
2246
  sourceActorPrincipalId,
2243
2247
  transport,
2244
2248
  clientMessageId,
2249
+ // The sender's own trust, so the drain runs this message as the actor
2250
+ // who sent it rather than as whoever the slot happens to hold when the
2251
+ // queue is worked.
2252
+ trustContext: resolvedTrustCtx,
2245
2253
  });
2246
2254
  if (enqueueResult.rejected) {
2247
2255
  return new RouteResponse(
@@ -2340,7 +2348,15 @@ export async function handleSendMessage(
2340
2348
  // matching in-memory pending interaction (e.g. prompter timeouts).
2341
2349
  await expireOrphanedGuardianRequests(mapping.conversationId);
2342
2350
 
2343
- // Conversation is idle — persist and fire agent loop immediately
2351
+ // Conversation is idle — persist and fire agent loop immediately.
2352
+ //
2353
+ // Stamping the sender here rather than at resolution is what keeps the two
2354
+ // in step: the slot hydrates and scopes the turn started just below
2355
+ // (`ensureActorScopedHistory`, persisted provenance, the loop's own trust),
2356
+ // so it must name whoever this request is about to run as. A request that
2357
+ // queues instead returns above without stamping — it is not starting a run,
2358
+ // and its actor rides the queue item to the drain.
2359
+ conversation.setTrustContext(resolvedTrustCtx);
2344
2360
  conversation.setTurnChannelContext({
2345
2361
  userMessageChannel: sourceChannel,
2346
2362
  assistantMessageChannel: sourceChannel,
@@ -37,26 +37,25 @@ const log = getLogger("surface-action-routes");
37
37
 
38
38
  /**
39
39
  * Resolve trust context for the actor principal from the gateway guardian
40
- * binding and set it on the conversation. A vellum principal is the guardian or
41
- * nobody, so the mapper yields guardian or unknown. Resolution (including the
42
- * dev-bypass principal translation and the mutating reset-drift repair) lives
43
- * in the shared {@link resolveVellumActorTrustContext} so the surface content
44
- * route's read-only requester scoping cannot drift from it.
40
+ * binding, and return it for the caller to attribute this action with. A vellum
41
+ * principal is the guardian or nobody, so the mapper yields guardian or
42
+ * unknown. Resolution (including the dev-bypass principal translation and the
43
+ * mutating reset-drift repair) lives in the shared
44
+ * {@link resolveVellumActorTrustContext} so the surface content route's
45
+ * read-only requester scoping cannot drift from it.
46
+ *
47
+ * Resolution only: the requester travels to `handleSurfaceAction` as an
48
+ * argument, and the conversation's slot is stamped there, at the point the
49
+ * click is committed to starting a turn. Stamping here instead would repoint
50
+ * the actor of a turn already in flight, or of a turn that starts between this
51
+ * call and the dispatch.
45
52
  */
46
- async function applyTrustContext(
47
- conversation: {
48
- setTrustContext?(ctx: TrustContext): void;
49
- },
53
+ async function resolveRequesterTrustContext(
50
54
  actorPrincipalId: string | undefined,
51
- ): Promise<void> {
52
- if (!conversation.setTrustContext) {
53
- return;
54
- }
55
- conversation.setTrustContext(
56
- await resolveVellumActorTrustContext(actorPrincipalId, {
57
- healResetDrift: true,
58
- }),
59
- );
55
+ ): Promise<TrustContext> {
56
+ return resolveVellumActorTrustContext(actorPrincipalId, {
57
+ healResetDrift: true,
58
+ });
60
59
  }
61
60
 
62
61
  // ---------------------------------------------------------------------------
@@ -154,7 +153,8 @@ async function handleSurfaceAction({
154
153
  }
155
154
 
156
155
  const actorPrincipalId = headers?.["x-vellum-actor-principal-id"];
157
- await applyTrustContext(conversation, actorPrincipalId);
156
+ const requesterTrustContext =
157
+ await resolveRequesterTrustContext(actorPrincipalId);
158
158
 
159
159
  // Translate dev-bypass → real guardian so the surface turn's principal matches
160
160
  // the SSE host-proxy client's registered principal; otherwise CU/app-control
@@ -170,6 +170,7 @@ async function handleSurfaceAction({
170
170
  actionId,
171
171
  data,
172
172
  resolvedActorPrincipalId,
173
+ requesterTrustContext,
173
174
  );
174
175
  const result =
175
176
  raw && typeof raw === "object" && "accepted" in raw