@vellumai/assistant 0.10.4-dev.202607012234.a9be056 → 0.10.4-dev.202607012335.d6d6958

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 (34) hide show
  1. package/node_modules/@vellumai/gateway-client/src/index.ts +1 -0
  2. package/node_modules/@vellumai/gateway-client/src/trust-verdict-contract.ts +16 -3
  3. package/package.json +1 -1
  4. package/src/__tests__/approval-interception-trust-gates.test.ts +148 -3
  5. package/src/__tests__/context-search-conversations-source.test.ts +26 -49
  6. package/src/__tests__/persona-resolver.test.ts +56 -2
  7. package/src/__tests__/trust-context-guards.test.ts +21 -10
  8. package/src/__tests__/workspace-migration-121-seed-default-user-guardrails.test.ts +118 -0
  9. package/src/channels/channel-verification-sessions.ts +6 -1
  10. package/src/persistence/__tests__/conversation-queries-search.test.ts +22 -17
  11. package/src/persistence/conversation-queries.ts +27 -74
  12. package/src/persistence/job-handlers/cleanup.ts +3 -4
  13. package/src/persistence/migrations/312-drop-inbox-conversation-state-table.ts +15 -0
  14. package/src/persistence/schema/contacts.ts +0 -28
  15. package/src/persistence/steps.ts +2 -0
  16. package/src/plugins/defaults/memory/__tests__/conversation-queries.test.ts +0 -20
  17. package/src/plugins/defaults/memory/context-search/sources/conversations.ts +20 -59
  18. package/src/plugins/defaults/turn-context/unified-turn-context.ts +8 -0
  19. package/src/prompts/__tests__/system-prompt.test.ts +128 -1
  20. package/src/prompts/persona-resolver.ts +13 -9
  21. package/src/prompts/system-prompt.ts +24 -1
  22. package/src/prompts/templates/users/default.md +35 -0
  23. package/src/runtime/__tests__/channel-verification-service.test.ts +2 -2
  24. package/src/runtime/channel-verification-service.ts +3 -1
  25. package/src/runtime/local-actor-identity.test.ts +38 -0
  26. package/src/runtime/local-actor-identity.ts +14 -0
  27. package/src/runtime/routes/guardian-approval-interception.ts +51 -0
  28. package/src/runtime/routes/inbound-stages/acl-enforcement.test.ts +117 -0
  29. package/src/runtime/routes/inbound-stages/acl-enforcement.ts +90 -23
  30. package/src/runtime/routes/inbound-stages/escalation-intercept.test.ts +158 -0
  31. package/src/runtime/routes/inbound-stages/escalation-intercept.ts +22 -1
  32. package/src/runtime/tool-grant-request-helper.ts +17 -1
  33. package/src/workspace/migrations/121-seed-default-user-guardrails.ts +82 -0
  34. package/src/workspace/migrations/registry.ts +2 -0
@@ -77,6 +77,7 @@ export type { AdmissionPolicy } from "./admission-policy-contract.js";
77
77
 
78
78
  // Trust verdict contract (gateway → daemon) — Zod schemas + derived types
79
79
  export {
80
+ isTrustClass,
80
81
  makeResolutionFailedVerdict,
81
82
  ResolveInboundTrustRequestSchema,
82
83
  TRUST_CLASS_VALUES,
@@ -32,6 +32,18 @@ export const TrustClassSchema = z.enum(TRUST_CLASS_VALUES);
32
32
 
33
33
  export type TrustClass = (typeof TRUST_CLASS_VALUES)[number];
34
34
 
35
+ const TRUST_CLASS_SET: ReadonlySet<string> = new Set(TRUST_CLASS_VALUES);
36
+
37
+ /**
38
+ * Type guard for wire-sourced trust classes. Consumers receive verdicts over
39
+ * IPC/HTTP, so a field statically typed {@link TrustClass} can still carry an
40
+ * out-of-contract value (version skew, malformed payload); this narrows it
41
+ * safely without casting.
42
+ */
43
+ export function isTrustClass(value: string): value is TrustClass {
44
+ return TRUST_CLASS_SET.has(value);
45
+ }
46
+
35
47
  /**
36
48
  * Per-actor trust verdict resolved by the gateway from its ACL DB. ACL +
37
49
  * identity keys + minimal labels only. Guardian binding and member
@@ -42,9 +54,10 @@ export const TrustVerdictSchema = z.object({
42
54
  trustClass: TrustClassSchema,
43
55
  canonicalSenderId: z.string().nullable(),
44
56
 
45
- // Present+true ⇒ gateway attempted resolution but failed (DB error);
46
- // consumer treats it as "could not vouch", distinct from a real `unknown`
47
- // stranger.
57
+ // Present+true ⇒ gateway attempted resolution but could not produce a
58
+ // usable verdict (DB error, or a sender who maps to the guardian contact
59
+ // whose principal is unresolved); consumer treats it as "could not vouch",
60
+ // distinct from a real `unknown` stranger.
48
61
  resolutionFailed: z.boolean().optional(),
49
62
 
50
63
  // Guardian binding — present only when a guardian binding matches.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.4-dev.202607012234.a9be056",
3
+ "version": "0.10.4-dev.202607012335.d6d6958",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -24,8 +24,14 @@ mock.module("../daemon/conversation-registry.js", () => ({
24
24
  findConversation: (id: string) => _conversationMocks.get(id),
25
25
  }));
26
26
 
27
+ // Anchored guardian principal, driven per-test to exercise the guardian
28
+ // principal gate (undefined = anchor unresolvable).
29
+ let _anchorPrincipalId: string | undefined;
30
+ mock.module("../runtime/local-actor-identity.js", () => ({
31
+ findLocalGuardianPrincipalId: async () => _anchorPrincipalId,
32
+ }));
33
+
27
34
  import type { Conversation } from "../daemon/conversation.js";
28
- import type { TrustContext } from "../daemon/trust-context.js";
29
35
  import { initializeDb } from "../persistence/db-init.js";
30
36
  import * as approvalMessageComposer from "../runtime/approval-message-composer.js";
31
37
  import * as gatewayClient from "../runtime/gateway-client.js";
@@ -76,6 +82,7 @@ describe("approval interception trust-class gates", () => {
76
82
 
77
83
  beforeEach(() => {
78
84
  pendingInteractions.clear();
85
+ _anchorPrincipalId = undefined;
79
86
  deliverSpy = spyOn(gatewayClient, "deliverChannelReply").mockResolvedValue({
80
87
  ok: true,
81
88
  });
@@ -105,7 +112,7 @@ describe("approval interception trust-class gates", () => {
105
112
  trustClass: "unknown",
106
113
  requesterExternalUserId: "intruder-user-1",
107
114
  guardianExternalUserId: "guardian-1",
108
- } as TrustContext,
115
+ },
109
116
  assistantId: ASSISTANT_ID,
110
117
  });
111
118
 
@@ -117,6 +124,144 @@ describe("approval interception trust-class gates", () => {
117
124
  composeSpy.mockRestore();
118
125
  });
119
126
 
127
+ test("guardian apr: callback with a principal matching the anchor applies the decision", async () => {
128
+ _anchorPrincipalId = "guardian-principal-1";
129
+ const sessionMock = registerPendingInteraction(
130
+ "req-guardian-apply-1",
131
+ CONVERSATION_ID,
132
+ TOOL_NAME,
133
+ TOOL_INPUT,
134
+ );
135
+
136
+ const result = await handleApprovalInterception({
137
+ conversationId: CONVERSATION_ID,
138
+ callbackData: "apr:req-guardian-apply-1:approve_once",
139
+ content: "",
140
+ conversationExternalId: REQUESTER_CHAT,
141
+ sourceChannel: "telegram",
142
+ actorExternalId: "guardian-user-1",
143
+ replyCallbackUrl: "https://gateway.test/deliver",
144
+ trustCtx: {
145
+ sourceChannel: "telegram",
146
+ trustClass: "guardian",
147
+ requesterExternalUserId: "guardian-user-1",
148
+ guardianExternalUserId: "guardian-user-1",
149
+ guardianPrincipalId: "guardian-principal-1",
150
+ },
151
+ assistantId: ASSISTANT_ID,
152
+ });
153
+
154
+ expect(result.handled).toBe(true);
155
+ expect(result.type).toBe("decision_applied");
156
+ expect(sessionMock).toHaveBeenCalled();
157
+ });
158
+
159
+ test("guardian apr: callback with a principal NOT matching the anchor is rejected before any decision", async () => {
160
+ _anchorPrincipalId = "the-real-guardian-principal";
161
+ const sessionMock = registerPendingInteraction(
162
+ "req-guardian-mismatch-1",
163
+ CONVERSATION_ID,
164
+ TOOL_NAME,
165
+ TOOL_INPUT,
166
+ );
167
+
168
+ const result = await handleApprovalInterception({
169
+ conversationId: CONVERSATION_ID,
170
+ callbackData: "apr:req-guardian-mismatch-1:approve_once",
171
+ content: "",
172
+ conversationExternalId: REQUESTER_CHAT,
173
+ sourceChannel: "telegram",
174
+ actorExternalId: "stale-guardian-user",
175
+ replyCallbackUrl: "https://gateway.test/deliver",
176
+ trustCtx: {
177
+ sourceChannel: "telegram",
178
+ trustClass: "guardian",
179
+ requesterExternalUserId: "stale-guardian-user",
180
+ guardianExternalUserId: "stale-guardian-user",
181
+ guardianPrincipalId: "some-other-principal",
182
+ },
183
+ assistantId: ASSISTANT_ID,
184
+ });
185
+
186
+ expect(result.handled).toBe(true);
187
+ expect(result.type).toBe("stale_ignored");
188
+ expect(sessionMock).not.toHaveBeenCalled();
189
+ // Generic failure copy — no oracle about pending requests or permission.
190
+ expect(deliverSpy).toHaveBeenCalledWith(
191
+ "https://gateway.test/deliver",
192
+ expect.objectContaining({
193
+ text: "Sorry, I couldn't process that. Please try again.",
194
+ }),
195
+ );
196
+ });
197
+
198
+ test("guardian without a resolved acting principal is rejected before any decision", async () => {
199
+ // Address-only guardian classification (e.g. a binding row with a null
200
+ // principal) must not authorize decisions.
201
+ _anchorPrincipalId = "the-real-guardian-principal";
202
+ const sessionMock = registerPendingInteraction(
203
+ "req-guardian-no-principal-1",
204
+ CONVERSATION_ID,
205
+ TOOL_NAME,
206
+ TOOL_INPUT,
207
+ );
208
+
209
+ const result = await handleApprovalInterception({
210
+ conversationId: CONVERSATION_ID,
211
+ callbackData: "apr:req-guardian-no-principal-1:approve_once",
212
+ content: "",
213
+ conversationExternalId: REQUESTER_CHAT,
214
+ sourceChannel: "telegram",
215
+ actorExternalId: "guardian-user-1",
216
+ replyCallbackUrl: "https://gateway.test/deliver",
217
+ trustCtx: {
218
+ sourceChannel: "telegram",
219
+ trustClass: "guardian",
220
+ requesterExternalUserId: "guardian-user-1",
221
+ guardianExternalUserId: "guardian-user-1",
222
+ },
223
+ assistantId: ASSISTANT_ID,
224
+ });
225
+
226
+ expect(result.handled).toBe(true);
227
+ expect(result.type).toBe("stale_ignored");
228
+ expect(sessionMock).not.toHaveBeenCalled();
229
+ });
230
+
231
+ test("guardian decision defers to the verdict when the anchor read is unresolvable", async () => {
232
+ // Transient gateway miss on the anchor read: the gateway-stamped verdict
233
+ // (which already classified the actor guardian by principal) wins.
234
+ _anchorPrincipalId = undefined;
235
+ const sessionMock = registerPendingInteraction(
236
+ "req-guardian-anchor-miss-1",
237
+ CONVERSATION_ID,
238
+ TOOL_NAME,
239
+ TOOL_INPUT,
240
+ );
241
+
242
+ const result = await handleApprovalInterception({
243
+ conversationId: CONVERSATION_ID,
244
+ callbackData: "apr:req-guardian-anchor-miss-1:approve_once",
245
+ content: "",
246
+ conversationExternalId: REQUESTER_CHAT,
247
+ sourceChannel: "telegram",
248
+ actorExternalId: "guardian-user-1",
249
+ replyCallbackUrl: "https://gateway.test/deliver",
250
+ trustCtx: {
251
+ sourceChannel: "telegram",
252
+ trustClass: "guardian",
253
+ requesterExternalUserId: "guardian-user-1",
254
+ guardianExternalUserId: "guardian-user-1",
255
+ guardianPrincipalId: "guardian-principal-1",
256
+ },
257
+ assistantId: ASSISTANT_ID,
258
+ });
259
+
260
+ expect(result.handled).toBe(true);
261
+ expect(result.type).toBe("decision_applied");
262
+ expect(sessionMock).toHaveBeenCalled();
263
+ });
264
+
120
265
  test("unverified sender (no identity) auto-denies pending approval", async () => {
121
266
  const sessionMock = registerPendingInteraction(
122
267
  "req-unknown-auto-deny-1",
@@ -135,7 +280,7 @@ describe("approval interception trust-class gates", () => {
135
280
  trustCtx: {
136
281
  sourceChannel: "telegram",
137
282
  trustClass: "unknown",
138
- } as TrustContext,
283
+ },
139
284
  assistantId: ASSISTANT_ID,
140
285
  });
141
286
 
@@ -98,7 +98,10 @@ describe("searchConversationSource", () => {
98
98
  });
99
99
  });
100
100
 
101
- test("uses LIKE fallback for short and non-ASCII queries", async () => {
101
+ test("returns no evidence for short and non-ASCII queries (content matching is index-only)", async () => {
102
+ // Short/punctuation-only and CJK queries produce no usable ≥2-char match
103
+ // shape. There is no content-scan fallback, so such queries yield no
104
+ // conversation evidence even when an exact substring exists.
102
105
  await seedConversation({
103
106
  title: "C++ notes",
104
107
  role: "user",
@@ -116,12 +119,8 @@ describe("searchConversationSource", () => {
116
119
  5,
117
120
  );
118
121
 
119
- expect(shortResult.evidence.map((item) => item.title)).toEqual([
120
- "C++ notes",
121
- ]);
122
- expect(unicodeResult.evidence.map((item) => item.title)).toEqual([
123
- "Unicode notes",
124
- ]);
122
+ expect(shortResult.evidence).toEqual([]);
123
+ expect(unicodeResult.evidence).toEqual([]);
125
124
  });
126
125
 
127
126
  test("does not return derived subagent, auto-analysis, or notification conversations", async () => {
@@ -202,27 +201,6 @@ describe("searchConversationSource", () => {
202
201
  ]);
203
202
  });
204
203
 
205
- test("excludes legacy private conversations through the LIKE fallback", async () => {
206
- const visible = await seedConversation({
207
- title: "Visible non-ASCII conversation",
208
- content: "東京 appears in a normal conversation.",
209
- });
210
- const legacyPrivate = await seedConversation({
211
- title: "Legacy private non-ASCII conversation",
212
- content: "東京 appears in a private conversation.",
213
- });
214
- rawRun(
215
- "UPDATE conversations SET conversation_type = 'private' WHERE id = ?",
216
- legacyPrivate.conversation.id,
217
- );
218
-
219
- const result = await searchConversationSource("東京", makeContext(), 10);
220
-
221
- expect(result.evidence.map((item) => item.locator)).toEqual([
222
- `${visible.conversation.id}#${visible.message.id}`,
223
- ]);
224
- });
225
-
226
204
  test("includes archived, scheduled, and background conversations", async () => {
227
205
  const archived = await seedConversation({
228
206
  title: "Archived conversation",
@@ -478,16 +456,17 @@ describe("searchConversationSource with the qdrant backend", () => {
478
456
  ]);
479
457
  });
480
458
 
481
- test("routes short/punctuation-only queries to the exact LIKE path, not Qdrant", async () => {
482
- const match = await seedConversation({
459
+ test("short/punctuation-only queries return no evidence and never hit Qdrant", async () => {
460
+ await seedConversation({
483
461
  title: "C++ notes",
484
462
  role: "user",
485
463
  content: "Use C++ when the example needs deterministic lifetime notes.",
486
464
  });
487
465
 
488
- // `C++` produces no usable ≥2-char FTS match shape, so the source must use
489
- // the exact LIKE path rather than the sparse encoder (which would still
490
- // emit a noisy 1-char `c` token). The mock throws to prove it never runs.
466
+ // `C++` produces no usable ≥2-char FTS match shape. The sparse encoder
467
+ // would still emit a noisy 1-char `c` token, so the source must return no
468
+ // evidence WITHOUT querying the index. The mock throws to prove it never
469
+ // runs.
491
470
  lexicalMockImpl = async () => {
492
471
  throw new Error("searchMessageIdsLexical must not run for a short query");
493
472
  };
@@ -495,9 +474,7 @@ describe("searchConversationSource with the qdrant backend", () => {
495
474
  const result = await searchConversationSource("C++", makeContext(), 5);
496
475
 
497
476
  expect(lexicalCalls).toHaveLength(0);
498
- expect(result.evidence.map((item) => item.locator)).toEqual([
499
- `${match.conversation.id}#${match.message.id}`,
500
- ]);
477
+ expect(result.evidence).toEqual([]);
501
478
  });
502
479
 
503
480
  test("over-fetches a wide candidate pool from Qdrant, not the FTS prefetch window", async () => {
@@ -620,10 +597,10 @@ describe("searchConversationSource with the qdrant backend", () => {
620
597
  ]);
621
598
  });
622
599
 
623
- test("falls back to LIKE when the Qdrant lookup throws", async () => {
624
- const match = await seedConversation({
625
- title: "Fallback notes",
626
- content: "The likefallbacktoken decision is recorded here.",
600
+ test("returns no evidence when the Qdrant lookup throws", async () => {
601
+ await seedConversation({
602
+ title: "Failure notes",
603
+ content: "The qdranterrortoken decision is recorded here.",
627
604
  });
628
605
 
629
606
  lexicalMockImpl = async () => {
@@ -631,18 +608,18 @@ describe("searchConversationSource with the qdrant backend", () => {
631
608
  };
632
609
 
633
610
  const result = await searchConversationSource(
634
- "likefallbacktoken",
611
+ "qdranterrortoken",
635
612
  makeContext(),
636
613
  5,
637
614
  );
638
615
 
639
- expect(result.evidence.map((item) => item.locator)).toEqual([
640
- `${match.conversation.id}#${match.message.id}`,
641
- ]);
616
+ // Content matching is index-only: the failure is logged and the source
617
+ // yields no conversation evidence — no content-scan recovery.
618
+ expect(result.evidence).toEqual([]);
642
619
  });
643
620
 
644
- test("falls back to LIKE when Qdrant returns no candidates", async () => {
645
- const match = await seedConversation({
621
+ test("returns no evidence when Qdrant returns no candidates", async () => {
622
+ await seedConversation({
646
623
  title: "Empty candidate notes",
647
624
  content: "The emptycandidatetoken decision is recorded here.",
648
625
  });
@@ -655,9 +632,9 @@ describe("searchConversationSource with the qdrant backend", () => {
655
632
  5,
656
633
  );
657
634
 
658
- expect(result.evidence.map((item) => item.locator)).toEqual([
659
- `${match.conversation.id}#${match.message.id}`,
660
- ]);
635
+ // The index is authoritative for content matching — an empty candidate
636
+ // set is an empty result, not a trigger for a table-scan fallback.
637
+ expect(result.evidence).toEqual([]);
661
638
  });
662
639
  });
663
640
 
@@ -132,7 +132,6 @@ afterEach(() => {
132
132
 
133
133
  describe("resolveGuardianPersonaPath", () => {
134
134
  test("returns null when no guardian exists", () => {
135
-
136
135
  expect(resolveGuardianPersonaPath()).toBeNull();
137
136
  });
138
137
 
@@ -206,7 +205,6 @@ describe("ensureGuardianPersonaFile", () => {
206
205
 
207
206
  describe("resolveGuardianPersonaStrict", () => {
208
207
  test("returns null when no guardian contact exists", () => {
209
-
210
208
  expect(resolveGuardianPersonaStrict()).toBeNull();
211
209
  });
212
210
 
@@ -352,3 +350,59 @@ describe("resolveUserSlug (guardian trust, no requester identity)", () => {
352
350
  expect(resolveUserSlug(trustContext)).toBe("alice");
353
351
  });
354
352
  });
353
+
354
+ // ── resolveUserSlug — guardian turns WITH a requester identity ─────
355
+ //
356
+ // A foreground guardian turn (e.g. the local desktop app after hatch) carries
357
+ // both a `requesterExternalUserId` (the principal id) and a
358
+ // `guardianExternalUserId`. The requester lookup can find the guardian's own
359
+ // contact row whose `userFile` column is still null — the normal post-hatch
360
+ // state, since onboarding writes users/guardian.md on disk but not the column.
361
+ // That null must not strand the read on users/default.md: it has to fall
362
+ // through to the guardian file the onboarding profile was written to.
363
+
364
+ describe("resolveUserSlug (guardian trust WITH requester identity)", () => {
365
+ test("null-userFile guardian contact falls through to the guardian file, not default", () => {
366
+ // Guardian contact exists but has no explicit userFile (post-hatch state).
367
+ seedVellumGuardian(null);
368
+ // The requester principal id resolves to that same null-userFile contact.
369
+ mockContactsByAddress["vellum:principal-123"] = { userFile: null };
370
+
371
+ const trustContext = {
372
+ sourceChannel: "vellum",
373
+ trustClass: "guardian",
374
+ requesterExternalUserId: "principal-123",
375
+ guardianExternalUserId: "vellum:self",
376
+ } as TrustContext;
377
+
378
+ expect(resolveUserSlug(trustContext)).toBe("guardian");
379
+ });
380
+
381
+ test("an explicit requester userFile still wins over the guardian fallback", () => {
382
+ seedVellumGuardian(null);
383
+ mockContactsByAddress["vellum:principal-123"] = { userFile: "alice.md" };
384
+
385
+ const trustContext = {
386
+ sourceChannel: "vellum",
387
+ trustClass: "guardian",
388
+ requesterExternalUserId: "principal-123",
389
+ guardianExternalUserId: "vellum:self",
390
+ } as TrustContext;
391
+
392
+ expect(resolveUserSlug(trustContext)).toBe("alice");
393
+ });
394
+
395
+ test("non-guardian turn with a null-userFile contact does not borrow the guardian persona", () => {
396
+ seedVellumGuardian(null);
397
+ mockContactsByAddress["vellum:principal-123"] = { userFile: null };
398
+
399
+ const trustContext = {
400
+ sourceChannel: "vellum",
401
+ trustClass: "trusted_contact",
402
+ requesterExternalUserId: "principal-123",
403
+ guardianExternalUserId: "vellum:self",
404
+ } as TrustContext;
405
+
406
+ expect(resolveUserSlug(trustContext)).toBeNull();
407
+ });
408
+ });
@@ -12,8 +12,9 @@ import { describe, expect, it } from "bun:test";
12
12
  * (optional string), NOT `string | null`.
13
13
  * (b) trustClass in ToolContext must be a required field (no `?`).
14
14
  * (c) The channel retry sweep parser must not reference `actorRole`.
15
- * (d) guardianPrincipalId in GuardianBinding must be `string` (non-null,
16
- * non-optional).
15
+ * (d) guardianPrincipalId in GuardianBinding must be `string | null` —
16
+ * a gateway guardian row with no principal surfaces as UNRESOLVED
17
+ * (null) and is never coerced to a present-but-empty "" (LUM-2665).
17
18
  */
18
19
 
19
20
  const srcDir = join(import.meta.dir, "..");
@@ -163,10 +164,11 @@ describe("trust-context guards", () => {
163
164
  });
164
165
 
165
166
  // -----------------------------------------------------------------------
166
- // (e) guardianPrincipalId is non-null in GuardianBinding
167
+ // (d) guardianPrincipalId is nullable (unresolved-capable) in
168
+ // GuardianBinding
167
169
  // -----------------------------------------------------------------------
168
170
 
169
- it("guardianPrincipalId is typed as string (non-null) in GuardianBinding", () => {
171
+ it("guardianPrincipalId is typed as string | null in GuardianBinding, and reads never coerce null to ''", () => {
170
172
  const source = readFileSync(
171
173
  join(srcDir, "channels", "channel-verification-sessions.ts"),
172
174
  "utf-8",
@@ -197,18 +199,27 @@ describe("trust-context guards", () => {
197
199
  "Expected to find guardianPrincipalId in GuardianBinding",
198
200
  ).toBeDefined();
199
201
 
200
- // Must be `guardianPrincipalId: string` — not optional, not nullable
202
+ // Must be `guardianPrincipalId: string | null` — a gateway guardian row
203
+ // with no principal is UNRESOLVED. Callers repair via the vellum anchor
204
+ // or fail closed; a plain `string` type invites `?? ""` coercion, which
205
+ // creates undecidable canonical requests (LUM-2665).
201
206
  expect(
202
207
  principalLine!.includes("string | null") ||
203
208
  principalLine!.includes("null | string"),
204
- "guardianPrincipalId must not be typed as nullable in GuardianBinding. " +
209
+ "guardianPrincipalId must be typed `string | null` in GuardianBinding " +
210
+ "so a missing gateway principal surfaces as unresolved. " +
205
211
  `Found: "${principalLine!.trim()}"`,
206
- ).toBe(false);
212
+ ).toBe(true);
207
213
 
214
+ // The synthesizing read must never mask a missing principal as "".
215
+ const serviceSource = readFileSync(
216
+ join(srcDir, "runtime", "channel-verification-service.ts"),
217
+ "utf-8",
218
+ );
208
219
  expect(
209
- /guardianPrincipalId\s*\?/.test(principalLine!),
210
- "guardianPrincipalId must not be optional in GuardianBinding. " +
211
- `Found: "${principalLine!.trim()}"`,
220
+ serviceSource.includes('principalId ?? ""'),
221
+ "getGuardianBinding must not coerce a missing gateway principal to " +
222
+ '"" — surface null and let callers repair or fail closed.',
212
223
  ).toBe(false);
213
224
  });
214
225
  });
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Tests for workspace migration `121-seed-default-user-guardrails`.
3
+ *
4
+ * The migration backfills `users/default.md` (the persona rendered for
5
+ * non-guardian actors) with the privacy guardrail. Unlike a plain create-only
6
+ * seed, it also writes over an *empty* file: existing installs seeded an empty
7
+ * `default.md` before the guardrail existed, so blank is the "unmodified"
8
+ * signal we must overwrite. Any real content means the guardian customized the
9
+ * file, so it is left untouched.
10
+ */
11
+
12
+ import {
13
+ existsSync,
14
+ mkdirSync,
15
+ mkdtempSync,
16
+ readFileSync,
17
+ rmSync,
18
+ writeFileSync,
19
+ } from "node:fs";
20
+ import { tmpdir } from "node:os";
21
+ import { join } from "node:path";
22
+ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
23
+
24
+ import { seedDefaultUserGuardrailsMigration } from "../workspace/migrations/121-seed-default-user-guardrails.js";
25
+
26
+ let workspaceDir: string;
27
+
28
+ beforeEach(() => {
29
+ workspaceDir = mkdtempSync(join(tmpdir(), "vellum-migration-121-test-"));
30
+ });
31
+
32
+ afterEach(() => {
33
+ if (existsSync(workspaceDir)) {
34
+ rmSync(workspaceDir, { recursive: true, force: true });
35
+ }
36
+ });
37
+
38
+ function defaultPath(): string {
39
+ return join(workspaceDir, "users", "default.md");
40
+ }
41
+
42
+ function readDefault(): string {
43
+ return readFileSync(defaultPath(), "utf-8");
44
+ }
45
+
46
+ describe("121-seed-default-user-guardrails migration", () => {
47
+ test("has correct id and description", () => {
48
+ expect(seedDefaultUserGuardrailsMigration.id).toBe(
49
+ "121-seed-default-user-guardrails",
50
+ );
51
+ expect(seedDefaultUserGuardrailsMigration.description).toContain(
52
+ "default.md",
53
+ );
54
+ });
55
+
56
+ test("creates users/default.md with the guardrail when absent", () => {
57
+ expect(existsSync(defaultPath())).toBe(false);
58
+
59
+ seedDefaultUserGuardrailsMigration.run(workspaceDir);
60
+
61
+ expect(existsSync(defaultPath())).toBe(true);
62
+ const content = readDefault();
63
+ // Guardrail body + the trust-class mustache gates the renderer resolves.
64
+ expect(content).toContain("Protect your guardian's privacy");
65
+ expect(content).toContain("{{^isGuardian}}");
66
+ expect(content).toContain("{{#isTrustedContact}}");
67
+ expect(content).toContain("{{#isStranger}}");
68
+ });
69
+
70
+ test("backfills an existing EMPTY default.md (the existing-install case)", () => {
71
+ // Older installs seeded a one-byte (newline) default.md.
72
+ mkdirSync(join(workspaceDir, "users"), { recursive: true });
73
+ writeFileSync(defaultPath(), "\n", "utf-8");
74
+
75
+ seedDefaultUserGuardrailsMigration.run(workspaceDir);
76
+
77
+ expect(readDefault()).toContain("Protect your guardian's privacy");
78
+ });
79
+
80
+ test("backfills a whitespace-only default.md", () => {
81
+ mkdirSync(join(workspaceDir, "users"), { recursive: true });
82
+ writeFileSync(defaultPath(), " \n\t\n", "utf-8");
83
+
84
+ seedDefaultUserGuardrailsMigration.run(workspaceDir);
85
+
86
+ expect(readDefault()).toContain("Protect your guardian's privacy");
87
+ });
88
+
89
+ test("does not clobber a customized default.md", () => {
90
+ const existing = "# My contacts\n\nBe extra chatty with everyone.\n";
91
+ mkdirSync(join(workspaceDir, "users"), { recursive: true });
92
+ writeFileSync(defaultPath(), existing, "utf-8");
93
+
94
+ seedDefaultUserGuardrailsMigration.run(workspaceDir);
95
+
96
+ expect(readDefault()).toBe(existing);
97
+ });
98
+
99
+ test("idempotent — second run does not rewrite the seeded file", () => {
100
+ seedDefaultUserGuardrailsMigration.run(workspaceDir);
101
+ const afterFirst = readDefault();
102
+
103
+ seedDefaultUserGuardrailsMigration.run(workspaceDir);
104
+ const afterSecond = readDefault();
105
+
106
+ expect(afterSecond).toBe(afterFirst);
107
+ });
108
+
109
+ test("down() is a no-op — seeded file remains", () => {
110
+ seedDefaultUserGuardrailsMigration.run(workspaceDir);
111
+ const seeded = readDefault();
112
+
113
+ seedDefaultUserGuardrailsMigration.down(workspaceDir);
114
+
115
+ expect(existsSync(defaultPath())).toBe(true);
116
+ expect(readDefault()).toBe(seeded);
117
+ });
118
+ });
@@ -44,7 +44,12 @@ export interface GuardianBinding {
44
44
  channel: string;
45
45
  guardianExternalUserId: string;
46
46
  guardianDeliveryChatId: string;
47
- guardianPrincipalId: string;
47
+ /**
48
+ * Canonical principal from the gateway guardian contact. `null` when the
49
+ * gateway row carries no principal — callers must treat that as UNRESOLVED
50
+ * (repair via the vellum anchor / adopt path), never as an empty principal.
51
+ */
52
+ guardianPrincipalId: string | null;
48
53
  status: BindingStatus;
49
54
  verifiedAt: number;
50
55
  verifiedVia: string;