@vellumai/assistant 0.10.0-dev.202606220825.1d9ff9a → 0.10.0-dev.202606221405.2fda286

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.
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Tests for the contact read IPC contracts in gateway-ipc-contracts.ts.
3
+ */
4
+
5
+ import { describe, expect, test } from "bun:test";
6
+
7
+ import {
8
+ ContactReadSchema,
9
+ GetContactIpcParamsSchema,
10
+ ListContactsIpcParamsSchema,
11
+ } from "../gateway-ipc-contracts.js";
12
+
13
+ describe("contact read contracts", () => {
14
+ test("ContactReadSchema parses a fully-populated contact", () => {
15
+ const contact = {
16
+ id: "c1",
17
+ displayName: "Example User",
18
+ role: "guardian",
19
+ notes: "primary guardian",
20
+ contactType: "human",
21
+ lastInteraction: 1700000000,
22
+ interactionCount: 12,
23
+ createdAt: 1699000000,
24
+ updatedAt: 1700000000,
25
+ channels: [
26
+ {
27
+ id: "ch1",
28
+ contactId: "c1",
29
+ type: "imessage",
30
+ address: "+15555550100",
31
+ isPrimary: true,
32
+ externalUserId: "+15555550100",
33
+ status: "active",
34
+ policy: "allow",
35
+ verifiedAt: 1699999999,
36
+ verifiedVia: "voice",
37
+ lastSeenAt: 1700000001,
38
+ interactionCount: 12,
39
+ lastInteraction: 1700000000,
40
+ revokedReason: null,
41
+ blockedReason: null,
42
+ },
43
+ ],
44
+ };
45
+
46
+ const parsed = ContactReadSchema.parse(contact);
47
+ expect(parsed.createdAt).toBe(1699000000);
48
+ expect(parsed.updatedAt).toBe(1700000000);
49
+ });
50
+
51
+ test("ContactReadSchema requires createdAt/updatedAt", () => {
52
+ const withoutTimestamps = {
53
+ id: "c1",
54
+ displayName: "Example User",
55
+ role: "contact",
56
+ interactionCount: 0,
57
+ channels: [],
58
+ };
59
+ expect(() => ContactReadSchema.parse(withoutTimestamps)).toThrow();
60
+ });
61
+
62
+ test("ListContactsIpcParamsSchema defaults to {} when given undefined", () => {
63
+ expect(ListContactsIpcParamsSchema.parse(undefined)).toEqual({});
64
+ });
65
+
66
+ test("GetContactIpcParamsSchema rejects an empty object", () => {
67
+ expect(() => GetContactIpcParamsSchema.parse({})).toThrow();
68
+ });
69
+ });
@@ -85,3 +85,85 @@ export const TrustRulesListIpcResponseSchema = z.object({
85
85
  export type TrustRulesListIpcResponse = z.infer<
86
86
  typeof TrustRulesListIpcResponseSchema
87
87
  >;
88
+
89
+ export const ContactReadChannelSchema = z.object({
90
+ id: z.string(),
91
+ contactId: z.string(),
92
+ type: z.string(),
93
+ address: z.string(),
94
+ isPrimary: z.boolean(),
95
+ externalUserId: z.string().nullable(),
96
+ status: z.string(),
97
+ policy: z.string(),
98
+ verifiedAt: z.number().nullable(),
99
+ verifiedVia: z.string().nullable(),
100
+ lastSeenAt: z.number().nullable(),
101
+ interactionCount: z.number(),
102
+ lastInteraction: z.number().nullable(),
103
+ revokedReason: z.string().nullable(),
104
+ blockedReason: z.string().nullable(),
105
+ });
106
+
107
+ export type ContactReadChannel = z.infer<typeof ContactReadChannelSchema>;
108
+
109
+ export const ContactReadSchema = z.object({
110
+ id: z.string(),
111
+ displayName: z.string(),
112
+ role: z.string(),
113
+ notes: z.string().nullable().optional(),
114
+ contactType: z.string().nullable().optional(),
115
+ lastInteraction: z.number().nullable().optional(),
116
+ interactionCount: z.number(),
117
+ createdAt: z.number(),
118
+ updatedAt: z.number(),
119
+ channels: z.array(ContactReadChannelSchema),
120
+ });
121
+
122
+ export type ContactRead = z.infer<typeof ContactReadSchema>;
123
+
124
+ export const AssistantContactMetadataSchema = z.object({
125
+ contactId: z.string(),
126
+ species: z.string(),
127
+ metadata: z.object({}).passthrough().nullable(),
128
+ });
129
+
130
+ export type AssistantContactMetadata = z.infer<
131
+ typeof AssistantContactMetadataSchema
132
+ >;
133
+
134
+ export const ListContactsIpcParamsSchema = z
135
+ .object({
136
+ limit: z.number().optional(),
137
+ role: z.string().optional(),
138
+ })
139
+ .strict()
140
+ .default({});
141
+
142
+ export type ListContactsIpcParams = z.infer<
143
+ typeof ListContactsIpcParamsSchema
144
+ >;
145
+
146
+ export const ListContactsIpcResponseSchema = z.object({
147
+ ok: z.boolean(),
148
+ contacts: z.array(ContactReadSchema),
149
+ });
150
+
151
+ export type ListContactsIpcResponse = z.infer<
152
+ typeof ListContactsIpcResponseSchema
153
+ >;
154
+
155
+ export const GetContactIpcParamsSchema = z
156
+ .object({ contactId: z.string() })
157
+ .strict();
158
+
159
+ export type GetContactIpcParams = z.infer<typeof GetContactIpcParamsSchema>;
160
+
161
+ export const GetContactIpcResponseSchema = z.object({
162
+ ok: z.boolean(),
163
+ contact: ContactReadSchema,
164
+ assistantMetadata: AssistantContactMetadataSchema.optional(),
165
+ });
166
+
167
+ export type GetContactIpcResponse = z.infer<
168
+ typeof GetContactIpcResponseSchema
169
+ >;
package/openapi.yaml CHANGED
@@ -4800,6 +4800,10 @@ paths:
4800
4800
  - type: "null"
4801
4801
  interactionCount:
4802
4802
  type: number
4803
+ createdAt:
4804
+ type: number
4805
+ updatedAt:
4806
+ type: number
4803
4807
  channels:
4804
4808
  type: array
4805
4809
  items:
@@ -4871,6 +4875,8 @@ paths:
4871
4875
  - displayName
4872
4876
  - role
4873
4877
  - interactionCount
4878
+ - createdAt
4879
+ - updatedAt
4874
4880
  - channels
4875
4881
  additionalProperties: false
4876
4882
  required:
@@ -4955,6 +4961,10 @@ paths:
4955
4961
  - type: "null"
4956
4962
  interactionCount:
4957
4963
  type: number
4964
+ createdAt:
4965
+ type: number
4966
+ updatedAt:
4967
+ type: number
4958
4968
  channels:
4959
4969
  type: array
4960
4970
  items:
@@ -5026,6 +5036,8 @@ paths:
5026
5036
  - displayName
5027
5037
  - role
5028
5038
  - interactionCount
5039
+ - createdAt
5040
+ - updatedAt
5029
5041
  - channels
5030
5042
  additionalProperties: false
5031
5043
  description: Contact objects with channels and metadata
@@ -5079,6 +5091,10 @@ paths:
5079
5091
  - type: "null"
5080
5092
  interactionCount:
5081
5093
  type: number
5094
+ createdAt:
5095
+ type: number
5096
+ updatedAt:
5097
+ type: number
5082
5098
  channels:
5083
5099
  type: array
5084
5100
  items:
@@ -5150,6 +5166,8 @@ paths:
5150
5166
  - displayName
5151
5167
  - role
5152
5168
  - interactionCount
5169
+ - createdAt
5170
+ - updatedAt
5153
5171
  - channels
5154
5172
  additionalProperties: false
5155
5173
  assistantMetadata:
@@ -5457,6 +5475,10 @@ paths:
5457
5475
  - type: "null"
5458
5476
  interactionCount:
5459
5477
  type: number
5478
+ createdAt:
5479
+ type: number
5480
+ updatedAt:
5481
+ type: number
5460
5482
  channels:
5461
5483
  type: array
5462
5484
  items:
@@ -5528,6 +5550,8 @@ paths:
5528
5550
  - displayName
5529
5551
  - role
5530
5552
  - interactionCount
5553
+ - createdAt
5554
+ - updatedAt
5531
5555
  - channels
5532
5556
  additionalProperties: false
5533
5557
  description: Merged contact
@@ -5646,6 +5670,10 @@ paths:
5646
5670
  - type: "null"
5647
5671
  interactionCount:
5648
5672
  type: number
5673
+ createdAt:
5674
+ type: number
5675
+ updatedAt:
5676
+ type: number
5649
5677
  channels:
5650
5678
  type: array
5651
5679
  items:
@@ -5717,6 +5745,8 @@ paths:
5717
5745
  - displayName
5718
5746
  - role
5719
5747
  - interactionCount
5748
+ - createdAt
5749
+ - updatedAt
5720
5750
  - channels
5721
5751
  additionalProperties: false
5722
5752
  /v1/content-source:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.0-dev.202606220825.1d9ff9a",
3
+ "version": "0.10.0-dev.202606221405.2fda286",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -0,0 +1,409 @@
1
+ /**
2
+ * Tests for the daemon's contact read relay.
3
+ *
4
+ * handleListContacts (non-search) and handleGetContact relay to the gateway
5
+ * via `ipcCallPersistent`. On the happy path they serve gateway-sourced data
6
+ * and do NOT read the assistant DB. On IPC failure they fall back to the
7
+ * assistant-DB read and log a warning. getContact still 404s for unknown ids.
8
+ */
9
+
10
+ import { beforeEach, describe, expect, mock, test } from "bun:test";
11
+
12
+ // Capture `log.debug(...)` calls so we can assert the daemon-native-search note
13
+ // is emitted on the search path.
14
+ const debugLogs: string[] = [];
15
+ const realLogger = await import("../util/logger.js");
16
+ mock.module("../util/logger.js", () => ({
17
+ ...realLogger,
18
+ getLogger: () =>
19
+ new Proxy({} as Record<string, unknown>, {
20
+ get:
21
+ (_target, prop: string) =>
22
+ (...args: unknown[]) => {
23
+ if (prop === "debug") {
24
+ const msg = args.find((a) => typeof a === "string");
25
+ if (typeof msg === "string") debugLogs.push(msg);
26
+ }
27
+ },
28
+ }),
29
+ }));
30
+
31
+ // Guardian display-name override → deterministic sentinel so we can assert it
32
+ // is applied to relayed payloads.
33
+ const realUserReference = await import("../prompts/user-reference.js");
34
+ mock.module("../prompts/user-reference.js", () => ({
35
+ ...realUserReference,
36
+ resolveGuardianName: () => "Your Guardian",
37
+ }));
38
+
39
+ // IPC relay stub — each test sets the response/behavior.
40
+ type IpcStub = (method: string, params?: Record<string, unknown>) => unknown;
41
+ let ipcStub: IpcStub = () => undefined;
42
+ const ipcCalls: Array<{ method: string; params?: Record<string, unknown> }> =
43
+ [];
44
+
45
+ const realGatewayClient = await import("../ipc/gateway-client.js");
46
+ mock.module("../ipc/gateway-client.js", () => ({
47
+ ...realGatewayClient,
48
+ ipcCallPersistent: async (
49
+ method: string,
50
+ params?: Record<string, unknown>,
51
+ ) => {
52
+ ipcCalls.push({ method, params });
53
+ return ipcStub(method, params);
54
+ },
55
+ }));
56
+
57
+ // Assistant-DB fallback stubs — assert these are NOT hit on the happy path,
58
+ // and that they ARE hit on the IPC-failure fallback path.
59
+ const localCalls: string[] = [];
60
+ const realContactStore = await import("../contacts/contact-store.js");
61
+ // Capture the args passed to the daemon-native listContacts so tests can assert
62
+ // contactType is filtered in SQL (before the limit) rather than relayed.
63
+ const listContactsArgs: Array<{
64
+ limit?: number;
65
+ role?: string;
66
+ contactType?: string;
67
+ }> = [];
68
+ mock.module("../contacts/contact-store.js", () => ({
69
+ ...realContactStore,
70
+ listContacts: (limit?: number, role?: string, contactType?: string) => {
71
+ localCalls.push("listContacts");
72
+ listContactsArgs.push({ limit, role, contactType });
73
+ return [
74
+ {
75
+ id: "local-1",
76
+ displayName: "Local Contact",
77
+ role: role ?? "contact",
78
+ contactType: contactType ?? "human",
79
+ interactionCount: 0,
80
+ channels: [],
81
+ },
82
+ ];
83
+ },
84
+ getContact: (id: string) => {
85
+ localCalls.push("getContact");
86
+ if (id === "missing") return null;
87
+ return {
88
+ id,
89
+ displayName: "Local Contact",
90
+ role: "contact",
91
+ contactType: "human",
92
+ interactionCount: 0,
93
+ channels: [],
94
+ };
95
+ },
96
+ getAssistantContactMetadata: () => {
97
+ localCalls.push("getAssistantContactMetadata");
98
+ return undefined;
99
+ },
100
+ searchContacts: () => {
101
+ localCalls.push("searchContacts");
102
+ return [
103
+ {
104
+ id: "search-1",
105
+ displayName: "Search Contact",
106
+ role: "contact",
107
+ contactType: "human",
108
+ interactionCount: 0,
109
+ channels: [],
110
+ },
111
+ ];
112
+ },
113
+ }));
114
+
115
+ const { handleListContacts, handleGetContact, ROUTES } = (await import(
116
+ "../runtime/routes/contact-routes.js"
117
+ )) as typeof import("../runtime/routes/contact-routes.js") & {
118
+ handleListContacts: (q: Record<string, string>) => Promise<{
119
+ ok: boolean;
120
+ contacts: Array<{ id: string; displayName: string; role: string }>;
121
+ }>;
122
+ handleGetContact: (id: string) => Promise<{
123
+ ok: boolean;
124
+ contact: { id: string; displayName: string; role: string };
125
+ assistantMetadata?: unknown;
126
+ }>;
127
+ };
128
+
129
+ /** Invoke the inline `search_contacts` POST route handler with a request body. */
130
+ function searchContactsRoute(
131
+ body: Record<string, unknown>,
132
+ ): Promise<Array<{ id: string; displayName: string; role: string }>> {
133
+ const route = ROUTES.find((r) => r.operationId === "search_contacts");
134
+ if (!route) throw new Error("search_contacts route not found");
135
+ return route.handler({ body }) as Promise<
136
+ Array<{ id: string; displayName: string; role: string }>
137
+ >;
138
+ }
139
+
140
+ function gatewayContact(overrides: Record<string, unknown> = {}) {
141
+ return {
142
+ id: "gw-1",
143
+ displayName: "Gateway Contact",
144
+ role: "contact",
145
+ notes: null,
146
+ contactType: "human",
147
+ interactionCount: 2,
148
+ lastInteraction: 100,
149
+ createdAt: 1699000000,
150
+ updatedAt: 1700000000,
151
+ channels: [
152
+ {
153
+ id: "ch-1",
154
+ contactId: "gw-1",
155
+ type: "telegram",
156
+ address: "tg-001",
157
+ isPrimary: true,
158
+ // The gateway leaves externalUserId null; the daemon's withChannelCompat
159
+ // re-derives it from address on the relayed payload.
160
+ externalUserId: null,
161
+ status: "active",
162
+ policy: "allow",
163
+ verifiedAt: null,
164
+ verifiedVia: null,
165
+ lastSeenAt: null,
166
+ interactionCount: 2,
167
+ lastInteraction: 100,
168
+ revokedReason: null,
169
+ blockedReason: null,
170
+ },
171
+ ],
172
+ ...overrides,
173
+ };
174
+ }
175
+
176
+ beforeEach(() => {
177
+ ipcStub = () => undefined;
178
+ ipcCalls.length = 0;
179
+ localCalls.length = 0;
180
+ debugLogs.length = 0;
181
+ listContactsArgs.length = 0;
182
+ });
183
+
184
+ describe("handleListContacts relay", () => {
185
+ test("non-search read serves gateway contacts and does NOT read assistant DB", async () => {
186
+ ipcStub = (method) => {
187
+ if (method === "contacts_list_rich") {
188
+ return { ok: true, contacts: [gatewayContact()] };
189
+ }
190
+ return undefined;
191
+ };
192
+
193
+ const result = await handleListContacts({ limit: "50" });
194
+
195
+ expect(ipcCalls.map((c) => c.method)).toEqual(["contacts_list_rich"]);
196
+ expect(localCalls).toEqual([]);
197
+ expect(result.contacts).toHaveLength(1);
198
+ expect(result.contacts[0].id).toBe("gw-1");
199
+ // The daemon's withChannelCompat re-derives externalUserId = address even
200
+ // though the gateway emits null — the client-facing guarantee holds.
201
+ const ch = (result.contacts[0] as { channels: { address: string; externalUserId: string | null }[] })
202
+ .channels[0];
203
+ expect(ch.externalUserId).toBe(ch.address);
204
+ });
205
+
206
+ test("applies guardian display-name override to relayed contacts", async () => {
207
+ ipcStub = () => ({
208
+ ok: true,
209
+ contacts: [gatewayContact({ role: "guardian", displayName: "Real Name" })],
210
+ });
211
+
212
+ const result = await handleListContacts({});
213
+ expect(result.contacts[0].displayName).toBe("Your Guardian");
214
+ });
215
+
216
+ test("falls back to the assistant DB on IPC failure", async () => {
217
+ ipcStub = () => {
218
+ throw new Error("gateway down");
219
+ };
220
+
221
+ const result = await handleListContacts({});
222
+
223
+ expect(ipcCalls.map((c) => c.method)).toEqual(["contacts_list_rich"]);
224
+ expect(localCalls).toContain("listContacts");
225
+ expect(result.contacts[0].id).toBe("local-1");
226
+ });
227
+
228
+ test("search params stay daemon-native and log the boundary note", async () => {
229
+ const result = await handleListContacts({ query: "alice" });
230
+
231
+ expect(ipcCalls).toEqual([]);
232
+ expect(localCalls).toContain("searchContacts");
233
+ expect(result.contacts[0].id).toBe("search-1");
234
+ expect(debugLogs.some((m) => m.includes("daemon-native"))).toBe(true);
235
+ });
236
+
237
+ test("contactType filter stays daemon-native and does NOT relay to the gateway", async () => {
238
+ // If contactType were relayed, the gateway would apply it AFTER its limit
239
+ // and could under-return. We serve it daemon-native instead (SQL filter
240
+ // before the limit). Assert no relay, local read, and the boundary note.
241
+ const result = await handleListContacts({
242
+ contactType: "assistant",
243
+ limit: "50",
244
+ });
245
+
246
+ expect(ipcCalls).toEqual([]);
247
+ expect(localCalls).toEqual(["listContacts"]);
248
+ // contactType + limit are pushed into the SQL-filtered daemon read (the
249
+ // daemon-native listContacts filters contactType BEFORE applying limit).
250
+ expect(listContactsArgs).toEqual([
251
+ { limit: 50, role: undefined, contactType: "assistant" },
252
+ ]);
253
+ expect(result.contacts[0].id).toBe("local-1");
254
+ expect(result.contacts[0].contactType).toBe("assistant");
255
+ expect(debugLogs.some((m) => m.includes("daemon-native"))).toBe(true);
256
+ });
257
+
258
+ test("contactType + role both flow into the daemon-native read", async () => {
259
+ await handleListContacts({ contactType: "human", role: "guardian" });
260
+
261
+ expect(ipcCalls).toEqual([]);
262
+ expect(listContactsArgs).toEqual([
263
+ { limit: 50, role: "guardian", contactType: "human" },
264
+ ]);
265
+ });
266
+ });
267
+
268
+ describe("search_contacts route relay boundary", () => {
269
+ test("real query stays daemon-native and logs the boundary note", async () => {
270
+ const contacts = await searchContactsRoute({ query: "alice" });
271
+
272
+ expect(ipcCalls).toEqual([]);
273
+ expect(localCalls).toContain("searchContacts");
274
+ expect(contacts[0].id).toBe("search-1");
275
+ expect(debugLogs.some((m) => m.includes("daemon-native"))).toBe(true);
276
+ });
277
+
278
+ test("real channelAddress stays daemon-native", async () => {
279
+ const contacts = await searchContactsRoute({ channelAddress: "tg-001" });
280
+
281
+ expect(ipcCalls).toEqual([]);
282
+ expect(localCalls).toContain("searchContacts");
283
+ expect(contacts[0].id).toBe("search-1");
284
+ });
285
+
286
+ test("real channelType stays daemon-native", async () => {
287
+ const contacts = await searchContactsRoute({ channelType: "telegram" });
288
+
289
+ expect(ipcCalls).toEqual([]);
290
+ expect(localCalls).toContain("searchContacts");
291
+ expect(contacts[0].id).toBe("search-1");
292
+ });
293
+
294
+ test("empty/whitespace query with no filters relays through the gateway", async () => {
295
+ ipcStub = (method) => {
296
+ if (method === "contacts_list_rich") {
297
+ return { ok: true, contacts: [gatewayContact()] };
298
+ }
299
+ return undefined;
300
+ };
301
+
302
+ const contacts = await searchContactsRoute({ query: " " });
303
+
304
+ expect(ipcCalls.map((c) => c.method)).toEqual(["contacts_list_rich"]);
305
+ expect(localCalls).toEqual([]);
306
+ expect(contacts[0].id).toBe("gw-1");
307
+ expect(debugLogs.some((m) => m.includes("daemon-native"))).toBe(false);
308
+ });
309
+
310
+ test("no params at all relays through the gateway", async () => {
311
+ ipcStub = (method) => {
312
+ if (method === "contacts_list_rich") {
313
+ return { ok: true, contacts: [gatewayContact()] };
314
+ }
315
+ return undefined;
316
+ };
317
+
318
+ const contacts = await searchContactsRoute({});
319
+
320
+ expect(ipcCalls.map((c) => c.method)).toEqual(["contacts_list_rich"]);
321
+ expect(localCalls).toEqual([]);
322
+ expect(contacts[0].id).toBe("gw-1");
323
+ });
324
+ });
325
+
326
+ describe("handleGetContact relay", () => {
327
+ test("serves the gateway contact and does NOT read the assistant DB", async () => {
328
+ ipcStub = (method) => {
329
+ if (method === "contacts_get_rich") {
330
+ return { ok: true, contact: gatewayContact() };
331
+ }
332
+ return undefined;
333
+ };
334
+
335
+ const result = await handleGetContact("gw-1");
336
+
337
+ expect(ipcCalls.map((c) => c.method)).toEqual(["contacts_get_rich"]);
338
+ expect(localCalls).toEqual([]);
339
+ expect(result.contact.id).toBe("gw-1");
340
+ expect(result.assistantMetadata).toBeUndefined();
341
+ // Relayed reads must carry contact-level timestamps — the CLI's detail
342
+ // formatter calls new Date(createdAt/updatedAt) unconditionally, so dropping
343
+ // them surfaces as a RangeError ("Invalid time value").
344
+ const contact = result.contact as { createdAt?: number; updatedAt?: number };
345
+ expect(contact.createdAt).toBe(1699000000);
346
+ expect(contact.updatedAt).toBe(1700000000);
347
+ });
348
+
349
+ test("applies guardian display-name override", async () => {
350
+ ipcStub = () => ({
351
+ ok: true,
352
+ contact: gatewayContact({ role: "guardian", displayName: "Real Name" }),
353
+ });
354
+
355
+ const result = await handleGetContact("gw-1");
356
+ expect(result.contact.displayName).toBe("Your Guardian");
357
+ });
358
+
359
+ test("returns assistantMetadata when present", async () => {
360
+ ipcStub = () => ({
361
+ ok: true,
362
+ contact: gatewayContact(),
363
+ assistantMetadata: {
364
+ contactId: "gw-1",
365
+ species: "vellum",
366
+ metadata: { model: "opus" },
367
+ },
368
+ });
369
+
370
+ const result = await handleGetContact("gw-1");
371
+ expect(result.assistantMetadata).toEqual({
372
+ contactId: "gw-1",
373
+ species: "vellum",
374
+ metadata: { model: "opus" },
375
+ });
376
+ });
377
+
378
+ test("throws NotFoundError on gateway not-found (no fallback)", async () => {
379
+ ipcStub = () => null;
380
+
381
+ await expect(handleGetContact("nope")).rejects.toThrow(
382
+ 'Contact "nope" not found',
383
+ );
384
+ expect(localCalls).toEqual([]);
385
+ });
386
+
387
+ test("falls back to the assistant DB on IPC transport failure", async () => {
388
+ ipcStub = () => {
389
+ throw new Error("gateway down");
390
+ };
391
+
392
+ const result = await handleGetContact("gw-1");
393
+
394
+ expect(ipcCalls.map((c) => c.method)).toEqual(["contacts_get_rich"]);
395
+ expect(localCalls).toContain("getContact");
396
+ expect(result.contact.id).toBe("gw-1");
397
+ });
398
+
399
+ test("fallback path still 404s for unknown ids", async () => {
400
+ ipcStub = () => {
401
+ throw new Error("gateway down");
402
+ };
403
+
404
+ await expect(handleGetContact("missing")).rejects.toThrow(
405
+ 'Contact "missing" not found',
406
+ );
407
+ expect(localCalls).toContain("getContact");
408
+ });
409
+ });
@@ -245,7 +245,7 @@ describe("contact_search tool", () => {
245
245
  describe("search_contacts route", () => {
246
246
  beforeEach(clearContacts);
247
247
 
248
- test("includes externalUserId (= address) on channels for older clients", () => {
248
+ test("includes externalUserId (= address) on channels for older clients", async () => {
249
249
  const seeded = upsertFixture({
250
250
  display_name: "Dana",
251
251
  channels: [{ type: "slack", address: "U12345ABC" }],
@@ -255,9 +255,9 @@ describe("search_contacts route", () => {
255
255
  const searchRoute = ROUTES.find(
256
256
  (r) => r.operationId === "search_contacts",
257
257
  )!;
258
- const contacts = searchRoute.handler({
258
+ const contacts = (await searchRoute.handler({
259
259
  body: { channelAddress: seededAddress },
260
- }) as unknown as Array<{
260
+ })) as unknown as Array<{
261
261
  channels: Array<{ address: string; externalUserId?: string }>;
262
262
  }>;
263
263
 
@@ -536,4 +536,82 @@ describe("plugin bootstrap", () => {
536
536
  // that snapshot, so its `onShutdown` must never fire.
537
537
  expect(shutdownFired).toBe(false);
538
538
  });
539
+
540
+ // ── .disabled sentinel gating ──────────────────────────────────────────
541
+ //
542
+ // A plugin is disabled when a `.disabled` file exists at
543
+ // <workspace>/plugins/<manifest-name>/.disabled. The bootstrap must
544
+ // skip the plugin entirely — no init, no tools, no routes, no shutdown
545
+ // hook — and remove it from the registry, mirroring the requiresFlag
546
+ // gate.
547
+
548
+ test(".disabled sentinel: init does not fire and plugin is unregistered", async () => {
549
+ let initFired = false;
550
+ const plugin = buildPlugin("sentinel-off", {
551
+ async init() {
552
+ initFired = true;
553
+ },
554
+ });
555
+ registerPlugin(plugin);
556
+
557
+ // Create the .disabled sentinel in the workspace plugins dir.
558
+ const sentinelDir = join(
559
+ TEST_WORKSPACE_DIR,
560
+ "plugins",
561
+ "sentinel-off",
562
+ );
563
+ const { mkdir, writeFile } = await import("node:fs/promises");
564
+ await mkdir(sentinelDir, { recursive: true });
565
+ await writeFile(join(sentinelDir, ".disabled"), "");
566
+
567
+ await bootstrapPlugins();
568
+
569
+ expect(initFired).toBe(false);
570
+ const names = getRegisteredPlugins().map((p) => p.manifest.name);
571
+ expect(names).not.toContain("sentinel-off");
572
+
573
+ await rm(sentinelDir, { recursive: true, force: true });
574
+ });
575
+
576
+ test(".disabled sentinel absent: plugin inits normally", async () => {
577
+ let initFired = false;
578
+ const plugin = buildPlugin("sentinel-ok", {
579
+ async init() {
580
+ initFired = true;
581
+ },
582
+ });
583
+ registerPlugin(plugin);
584
+
585
+ // No .disabled sentinel created — plugin should init normally.
586
+ await bootstrapPlugins();
587
+
588
+ expect(initFired).toBe(true);
589
+ });
590
+
591
+ test(".disabled sentinel: no shutdown hook entry for the skipped plugin", async () => {
592
+ let shutdownFired = false;
593
+ const plugin = buildPlugin("sentinel-shutdown", {
594
+ async init() {},
595
+ async onShutdown() {
596
+ shutdownFired = true;
597
+ },
598
+ });
599
+ registerPlugin(plugin);
600
+
601
+ const sentinelDir = join(
602
+ TEST_WORKSPACE_DIR,
603
+ "plugins",
604
+ "sentinel-shutdown",
605
+ );
606
+ const { mkdir, writeFile } = await import("node:fs/promises");
607
+ await mkdir(sentinelDir, { recursive: true });
608
+ await writeFile(join(sentinelDir, ".disabled"), "");
609
+
610
+ await bootstrapPlugins();
611
+ await runShutdownHooks("test-shutdown");
612
+
613
+ expect(shutdownFired).toBe(false);
614
+
615
+ await rm(sentinelDir, { recursive: true, force: true });
616
+ });
539
617
  });
@@ -854,4 +854,13 @@ describe("sanitizePluginName", () => {
854
854
  expect(sanitizePluginName("plugin_2")).toBe("plugin_2");
855
855
  expect(sanitizePluginName("a")).toBe("a");
856
856
  });
857
+
858
+ test.each([
859
+ "default-advisor",
860
+ "default-memory-retrieval",
861
+ "default-",
862
+ "default-x",
863
+ ])("rejects reserved prefix name %p", (reserved) => {
864
+ expect(() => sanitizePluginName(reserved)).toThrow(InvalidPluginNameError);
865
+ });
857
866
  });
@@ -154,9 +154,11 @@ export interface InstallPluginResult {
154
154
 
155
155
  /** Plugin name failed sanitization. */
156
156
  export class InvalidPluginNameError extends Error {
157
- constructor(name: string) {
157
+ constructor(name: string, reason?: string) {
158
158
  super(
159
- `Invalid plugin name "${name}". Names must match /^[a-z0-9][a-z0-9_-]*$/.`,
159
+ reason
160
+ ? `Invalid plugin name "${name}". ${reason}`
161
+ : `Invalid plugin name "${name}". Names must match /^[a-z0-9][a-z0-9_-]*$/.`,
160
162
  );
161
163
  this.name = "InvalidPluginNameError";
162
164
  }
@@ -289,12 +291,24 @@ async function resolvePluginSource(
289
291
  };
290
292
  }
291
293
 
294
+ /**
295
+ * Prefix reserved for first-party default plugins that ship in the assistant
296
+ * source tree. User-installable plugins must not use it — the `.disabled`
297
+ * sentinel and the plugin registry both key on manifest names, and a
298
+ * user plugin with a `default-` name would shadow or collide with the
299
+ * built-in.
300
+ */
301
+ export const RESERVED_PLUGIN_PREFIX = "default-";
302
+
292
303
  /**
293
304
  * Reject plugin names that could escape the canonical source path or the
294
305
  * install target. The source convention is a flat namespace under
295
306
  * `plugins/`, so a legitimate name is a single path segment
296
307
  * built from kebab-case alphanumerics.
297
308
  *
309
+ * Names prefixed with {@link RESERVED_PLUGIN_PREFIX} (`default-`) are also
310
+ * rejected — that prefix is reserved for first-party default plugins.
311
+ *
298
312
  * Exported so callers (e.g. the CLI input prompt) can validate up front
299
313
  * before invoking {@link installPlugin}.
300
314
  */
@@ -303,6 +317,12 @@ export function sanitizePluginName(name: string): string {
303
317
  if (!/^[a-z0-9][a-z0-9_-]*$/.test(trimmed)) {
304
318
  throw new InvalidPluginNameError(name);
305
319
  }
320
+ if (trimmed.startsWith(RESERVED_PLUGIN_PREFIX)) {
321
+ throw new InvalidPluginNameError(
322
+ name,
323
+ `The "${RESERVED_PLUGIN_PREFIX}" prefix is reserved for first-party default plugins.`,
324
+ );
325
+ }
306
326
  return trimmed;
307
327
  }
308
328
 
@@ -56,7 +56,7 @@
56
56
  * plugin level so the plugin name is attributed.
57
57
  */
58
58
 
59
- import { mkdirSync } from "node:fs";
59
+ import { existsSync, mkdirSync } from "node:fs";
60
60
  import { join } from "node:path";
61
61
 
62
62
  import { isAssistantFeatureFlagEnabled } from "../config/assistant-feature-flags.js";
@@ -82,7 +82,7 @@ import {
82
82
  unregisterPluginTools,
83
83
  } from "../tools/registry.js";
84
84
  import { getLogger } from "../util/logger.js";
85
- import { getWorkspaceDir } from "../util/platform.js";
85
+ import { getWorkspaceDir, getWorkspacePluginsDir } from "../util/platform.js";
86
86
  import { APP_VERSION } from "../version.js";
87
87
  import { registerShutdownHook } from "./shutdown-registry.js";
88
88
 
@@ -263,6 +263,29 @@ export async function bootstrapPlugins(): Promise<void> {
263
263
  continue;
264
264
  }
265
265
 
266
+ // Check for the .disabled sentinel. Both default and user plugins
267
+ // can be disabled by creating a `.disabled` file at
268
+ // <workspace>/plugins/<manifest-name>/.disabled. For user plugins
269
+ // this is the plugin's own directory; for default plugins (which
270
+ // live in the source tree) the workspace directory acts as an
271
+ // out-of-band kill switch — the operator creates a directory named
272
+ // after the plugin's manifest name (e.g. `plugins/default-advisor/`)
273
+ // and drops a `.disabled` file inside it. Runs before init so no
274
+ // hooks, tools, or routes from the disabled plugin are ever wired.
275
+ const disabledSentinelPath = join(
276
+ getWorkspacePluginsDir(),
277
+ name,
278
+ ".disabled",
279
+ );
280
+ if (existsSync(disabledSentinelPath)) {
281
+ log.info(
282
+ { plugin: name, sentinel: disabledSentinelPath },
283
+ `skipping plugin ${name}: disabled via .disabled sentinel`,
284
+ );
285
+ unregisterPlugin(name);
286
+ continue;
287
+ }
288
+
266
289
  try {
267
290
  activePlugins.push(await initializePlugin(plugin, assistantConfig));
268
291
  } catch (err) {
@@ -264,4 +264,126 @@ describe("runMigrationSteps — checkpointing", () => {
264
264
  "flakyAsyncStep",
265
265
  ]);
266
266
  });
267
+
268
+ test("detects and recovers step-level 'started' markers from a prior crash", async () => {
269
+ /**
270
+ * If the process crashes mid-step, the runner leaves a `step:<name>` =
271
+ * 'started' checkpoint. On the next boot, recoverCrashedMigrations
272
+ * detects it, clears it, and the step re-runs.
273
+ */
274
+
275
+ // GIVEN a database with a stalled step: checkpoint left by a crash
276
+ const db = createTestDb();
277
+ const raw = getSqliteFrom(db);
278
+ raw.run(
279
+ `CREATE TABLE IF NOT EXISTS memory_checkpoints (key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at INTEGER NOT NULL)`,
280
+ );
281
+ raw.run(
282
+ `INSERT INTO memory_checkpoints (key, value, updated_at) VALUES ('step:crashedStep', 'started', 0)`,
283
+ );
284
+
285
+ let ran = false;
286
+ const steps: MigrationStep[] = [
287
+ function crashedStep() {
288
+ ran = true;
289
+ },
290
+ ];
291
+
292
+ // WHEN the runner executes — recoverCrashedMigrations should clear
293
+ // the 'started' marker and let the step run.
294
+ await runMigrationSteps(db, steps);
295
+
296
+ // THEN the stalled checkpoint was cleared and the step ran
297
+ expect(ran).toBe(true);
298
+ const stalled = raw
299
+ .query(
300
+ `SELECT 1 FROM memory_checkpoints WHERE key = 'step:crashedStep' AND value = 'started'`,
301
+ )
302
+ .get();
303
+ expect(stalled).toBeNull();
304
+ // And the step was checkpointed as '1' (completed)
305
+ const completed = raw
306
+ .query(
307
+ `SELECT 1 FROM memory_checkpoints WHERE key = 'step:crashedStep' AND value = '1'`,
308
+ )
309
+ .get();
310
+ expect(completed).not.toBeNull();
311
+ });
312
+
313
+ test("does not skip a step whose only checkpoint is 'started' (not '1')", async () => {
314
+ /**
315
+ * The skip query filters for value = '1', so a 'started' marker
316
+ * alone must not cause a step to be skipped — the step should run.
317
+ * (recoverCrashedMigrations clears 'started' markers first, but
318
+ * even if it didn't, the skip logic is independent and correct.)
319
+ */
320
+
321
+ const db = createTestDb();
322
+ const raw = getSqliteFrom(db);
323
+ raw.run(
324
+ `CREATE TABLE IF NOT EXISTS memory_checkpoints (key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at INTEGER NOT NULL)`,
325
+ );
326
+ // Insert a 'started' marker without running recoverCrashedMigrations.
327
+ // We simulate this by inserting directly and checking the applied set.
328
+ raw.run(
329
+ `INSERT INTO memory_checkpoints (key, value, updated_at) VALUES ('step:someStep', 'started', 0)`,
330
+ );
331
+
332
+ let ran = false;
333
+ const steps: MigrationStep[] = [
334
+ function someStep() {
335
+ ran = true;
336
+ },
337
+ ];
338
+
339
+ // WHEN the runner executes, recoverCrashedMigrations clears the
340
+ // 'started' marker, so the step is not in the applied set and runs.
341
+ const result = await runMigrationSteps(db, steps);
342
+
343
+ // THEN the step ran (was not skipped)
344
+ expect(ran).toBe(true);
345
+ expect(result.applied).toEqual(["someStep"]);
346
+ expect(result.skipped).toEqual([]);
347
+ });
348
+
349
+ test("writes 'started' marker for async steps before awaiting", async () => {
350
+ /**
351
+ * For async steps, the runner writes a 'started' marker before
352
+ * awaiting the promise, so a crash between the write and promise
353
+ * resolution leaves a detectable checkpoint. Sync steps don't get
354
+ * a 'started' marker because they complete before the event loop
355
+ * can process the write (a crash during a sync step loses it too).
356
+ */
357
+
358
+ const db = createTestDb();
359
+ const raw = getSqliteFrom(db);
360
+
361
+ const seen: { marker: string | null } = { marker: null };
362
+ const steps: MigrationStep[] = [
363
+ async function asyncWithInspection() {
364
+ // Read the checkpoint while the step is "in flight" — the
365
+ // 'started' marker should already be written.
366
+ const row = raw
367
+ .query<{ value: string }, []>(
368
+ `SELECT value FROM memory_checkpoints WHERE key = 'step:asyncWithInspection'`,
369
+ )
370
+ .get();
371
+ seen.marker = row?.value ?? null;
372
+ await Promise.resolve();
373
+ },
374
+ ];
375
+
376
+ await runMigrationSteps(db, steps);
377
+
378
+ // The 'started' marker was visible during the async step's execution
379
+ expect(seen.marker).toBe("started");
380
+
381
+ // After completion, the checkpoint is '1'
382
+ const final = raw
383
+ .query<{ value: string }, []>(
384
+ `SELECT value FROM memory_checkpoints WHERE key = 'step:asyncWithInspection'`,
385
+ )
386
+ .get();
387
+ expect(final?.value).toBe("1");
388
+ });
267
389
  });
@@ -145,11 +145,14 @@ export async function runMigrationSteps(
145
145
  (
146
146
  raw
147
147
  .query(
148
- `SELECT key FROM memory_checkpoints WHERE key LIKE '${STEP_CHECKPOINT_PREFIX}%'`,
148
+ `SELECT key FROM memory_checkpoints WHERE key LIKE '${STEP_CHECKPOINT_PREFIX}%' AND value = '1'`,
149
149
  )
150
150
  .all() as Array<{ key: string }>
151
151
  ).map((row) => row.key.slice(STEP_CHECKPOINT_PREFIX.length)),
152
152
  );
153
+ const markStarted = raw.query(
154
+ `INSERT OR REPLACE INTO memory_checkpoints (key, value, updated_at) VALUES (?, 'started', ?)`,
155
+ );
153
156
  const markApplied = raw.query(
154
157
  `INSERT OR REPLACE INTO memory_checkpoints (key, value, updated_at) VALUES (?, '1', ?)`,
155
158
  );
@@ -170,6 +173,23 @@ export async function runMigrationSteps(
170
173
 
171
174
  try {
172
175
  log.info({ migration: name }, `Starting migration: ${name}`);
176
+
177
+ // For async steps, write a 'started' marker BEFORE calling the
178
+ // step. An async function starts executing synchronously up to its
179
+ // first `await`, so the 'started' write must happen before we call
180
+ // the step to ensure the marker is visible during the async body.
181
+ // Sync steps don't need a 'started' marker — they complete before
182
+ // the event loop can process the write (a crash during a sync step
183
+ // would lose it too).
184
+ //
185
+ // We detect async-ness by checking if the step's toString() body
186
+ // contains `async` — cheaper than calling it and checking the
187
+ // return type, which would have already started execution.
188
+ const isAsync = step.constructor.name === "AsyncFunction";
189
+ if (checkpointable && isAsync) {
190
+ markStarted.run(`${STEP_CHECKPOINT_PREFIX}${name}`, Date.now());
191
+ }
192
+
173
193
  // Await only steps that actually return a promise, so a list of purely
174
194
  // synchronous steps runs to completion without yielding the thread — and
175
195
  // an async step is fully drained before it is checkpointed below.
@@ -183,6 +203,9 @@ export async function runMigrationSteps(
183
203
  ran.push(name);
184
204
  }
185
205
  } catch (err) {
206
+ // Leave the 'started' marker in place (if one was written) —
207
+ // recoverCrashedMigrations will detect it on the next boot, log
208
+ // a warning, and clear it so the step re-runs.
186
209
  failed.push(name);
187
210
  log.error({ err, migration: name }, `Migration failed: ${name}`);
188
211
  }
@@ -181,6 +181,14 @@ const inflight = new Map<string, Promise<unknown>>();
181
181
  */
182
182
  const discoveredPluginDirs = new Map<string, string>();
183
183
 
184
+ /**
185
+ * Plugin directories that have a `.disabled` sentinel and were logged as
186
+ * disabled. Tracked so we only emit the "plugin disabled" log line once
187
+ * per scan cycle (the scan runs on every hook read). Cleared when a plugin
188
+ * transitions back to active or is evicted entirely.
189
+ */
190
+ const disabledPluginDirs = new Set<string>();
191
+
184
192
  // ─── Mtime helpers ───────────────────────────────────────────────────────────
185
193
 
186
194
  /**
@@ -400,11 +408,32 @@ async function scanPlugins(): Promise<void> {
400
408
  }
401
409
  if (!existsSync(join(pluginDir, "package.json"))) continue;
402
410
 
411
+ // Check for the .disabled sentinel. A plugin is disabled when a file
412
+ // named `.disabled` exists inside its plugin directory. Disabled
413
+ // plugins are skipped entirely — no hooks, no tools, no cache entries.
414
+ // If the plugin was previously active, its cache entries are evicted.
415
+ if (existsSync(join(pluginDir, ".disabled"))) {
416
+ const manifest = await parsePluginManifest(pluginDir);
417
+ const pluginName = manifest?.name ?? entry;
418
+ if (discoveredPluginDirs.has(pluginDir)) {
419
+ await evictPlugin(pluginDir, pluginName);
420
+ }
421
+ if (!disabledPluginDirs.has(pluginDir)) {
422
+ log.info(
423
+ { plugin: pluginName, pluginDir },
424
+ "plugin disabled via .disabled sentinel — skipping",
425
+ );
426
+ disabledPluginDirs.add(pluginDir);
427
+ }
428
+ continue;
429
+ }
430
+
403
431
  const manifest = await parsePluginManifest(pluginDir);
404
432
  if (manifest === undefined) continue;
405
433
  const { name: pluginName } = manifest;
406
434
 
407
435
  currentDirs.set(pluginDir, pluginName);
436
+ disabledPluginDirs.delete(pluginDir);
408
437
 
409
438
  if (!discoveredPluginDirs.has(pluginDir)) {
410
439
  log.info({ plugin: pluginName, pluginDir }, "plugin discovered");
@@ -472,6 +501,7 @@ async function evictAll(): Promise<void> {
472
501
  toolCache.clear();
473
502
  discoveredPluginDirs.clear();
474
503
  installDateCache.clear();
504
+ disabledPluginDirs.clear();
475
505
  }
476
506
 
477
507
  // ─── Import dedup ────────────────────────────────────────────────────────────
@@ -698,6 +728,7 @@ export function resetPluginCacheForTests(): void {
698
728
  discoveredPluginDirs.clear();
699
729
  installDateCache.clear();
700
730
  activatedPlugins.length = 0;
731
+ disabledPluginDirs.clear();
701
732
  }
702
733
 
703
734
  /**
@@ -8,6 +8,10 @@
8
8
  * they don't shadow more-specific sub-paths like contacts/invites.
9
9
  */
10
10
 
11
+ import {
12
+ GetContactIpcResponseSchema,
13
+ ListContactsIpcResponseSchema,
14
+ } from "@vellumai/gateway-client/gateway-ipc-contracts";
11
15
  import { IpcCallError } from "@vellumai/gateway-client/ipc-client";
12
16
  import { z } from "zod";
13
17
 
@@ -28,6 +32,7 @@ import type {
28
32
  } from "../../contacts/types.js";
29
33
  import { ipcCallPersistent } from "../../ipc/gateway-client.js";
30
34
  import { resolveGuardianName } from "../../prompts/user-reference.js";
35
+ import { getLogger } from "../../util/logger.js";
31
36
  import { ACTOR_PRINCIPALS } from "../auth/route-policy.js";
32
37
  import {
33
38
  redeemIngressInvite,
@@ -42,6 +47,8 @@ import {
42
47
  } from "./errors.js";
43
48
  import type { RouteDefinition, RouteHandlerArgs } from "./types.js";
44
49
 
50
+ const log = getLogger("contact-routes");
51
+
45
52
  /**
46
53
  * Re-throw a relayed gateway `IpcCallError` as a `RouteError` so the IPC/HTTP
47
54
  * adapters honor its statusCode/errorCode (4xx surfaces as 4xx, not a generic
@@ -153,6 +160,8 @@ const contactSchema = z.object({
153
160
  contactType: z.string().nullable().optional(),
154
161
  lastInteraction: z.number().nullable().optional(),
155
162
  interactionCount: z.number(),
163
+ createdAt: z.number(),
164
+ updatedAt: z.number(),
156
165
  channels: z.array(contactChannelSchema),
157
166
  });
158
167
 
@@ -160,7 +169,40 @@ const contactSchema = z.object({
160
169
  // Contact handlers (transport-agnostic)
161
170
  // ---------------------------------------------------------------------------
162
171
 
163
- function handleListContacts(queryParams: Record<string, string>) {
172
+ /**
173
+ * Relay a non-search contact list read to the gateway (source of truth for ACL
174
+ * fields), falling back to the assistant DB on IPC failure. Shared by the GET
175
+ * `contacts` list and the `search_contacts` no-filter case so both serve
176
+ * gateway-sourced data consistently.
177
+ */
178
+ async function relayListContacts(
179
+ limit: number,
180
+ role: ContactRole | undefined,
181
+ ) {
182
+ try {
183
+ const result = await ipcCallPersistent("contacts_list_rich", {
184
+ limit,
185
+ ...(role ? { role } : {}),
186
+ });
187
+ const { contacts } = ListContactsIpcResponseSchema.parse(result);
188
+ return {
189
+ ok: true,
190
+ contacts: contacts.map(prepareContactResponse),
191
+ };
192
+ } catch (err) {
193
+ log.warn(
194
+ { err },
195
+ "relayListContacts: gateway relay failed; falling back to assistant DB",
196
+ );
197
+ const contacts = listContacts(limit, role);
198
+ return {
199
+ ok: true,
200
+ contacts: contacts.map(prepareContactResponse),
201
+ };
202
+ }
203
+ }
204
+
205
+ export async function handleListContacts(queryParams: Record<string, string>) {
164
206
  const limit = Number(queryParams.limit ?? 50);
165
207
  const role = (queryParams.role as ContactRole) || undefined;
166
208
  const contactTypeParam = queryParams.contactType;
@@ -178,7 +220,11 @@ function handleListContacts(queryParams: Record<string, string>) {
178
220
  ? (contactTypeParam as ContactType)
179
221
  : undefined;
180
222
 
223
+ // True search stays daemon-native: gateway-native search is design-blocked.
181
224
  if (query || channelAddress || channelType) {
225
+ log.debug(
226
+ "handleListContacts: search served daemon-native (gateway-native search is design-blocked)",
227
+ );
182
228
  const contacts = searchContacts({
183
229
  query,
184
230
  channelAddress,
@@ -193,27 +239,59 @@ function handleListContacts(queryParams: Record<string, string>) {
193
239
  };
194
240
  }
195
241
 
196
- const contacts = listContacts(limit, role, contactType);
197
- return {
198
- ok: true,
199
- contacts: contacts.map(prepareContactResponse),
200
- };
242
+ // contactType is assistant-owned: serve daemon-native so it's filtered in SQL
243
+ // BEFORE the limit. The gateway relay filtered it AFTER its limit, which
244
+ // under-returned (and returned empty on an assistant-DB outage, since the
245
+ // soft-fail map dropped every row). Mirrors the search boundary.
246
+ if (contactType) {
247
+ log.debug(
248
+ "handleListContacts: contactType-filtered read served daemon-native (gateway-native contactType filtering is design-blocked, pending ACL classification)",
249
+ );
250
+ const contacts = listContacts(limit, role, contactType);
251
+ return {
252
+ ok: true,
253
+ contacts: contacts.map(prepareContactResponse),
254
+ };
255
+ }
256
+
257
+ return relayListContacts(limit, role);
201
258
  }
202
259
 
203
- function handleGetContact(contactId: string) {
204
- const contact = getContact(contactId);
205
- if (!contact) {
206
- throw new NotFoundError(`Contact "${contactId}" not found`);
260
+ export async function handleGetContact(contactId: string) {
261
+ try {
262
+ const result = await ipcCallPersistent("contacts_get_rich", { contactId });
263
+ // The gateway returns null (no `contact`) on a clean not-found.
264
+ if (!result || (result as { contact?: unknown }).contact === undefined) {
265
+ throw new NotFoundError(`Contact "${contactId}" not found`);
266
+ }
267
+ const { contact, assistantMetadata } =
268
+ GetContactIpcResponseSchema.parse(result);
269
+ return {
270
+ ok: true,
271
+ contact: prepareContactResponse(contact),
272
+ assistantMetadata: assistantMetadata ?? undefined,
273
+ };
274
+ } catch (err) {
275
+ // A clean not-found is a real 404 — don't fall back or mask it.
276
+ if (err instanceof NotFoundError) throw err;
277
+ log.warn(
278
+ { err, contactId },
279
+ "handleGetContact: gateway relay failed; falling back to assistant DB",
280
+ );
281
+ const contact = getContact(contactId);
282
+ if (!contact) {
283
+ throw new NotFoundError(`Contact "${contactId}" not found`);
284
+ }
285
+ const assistantMeta =
286
+ contact.contactType === "assistant"
287
+ ? getAssistantContactMetadata(contact.id)
288
+ : undefined;
289
+ return {
290
+ ok: true,
291
+ contact: prepareContactResponse(contact),
292
+ assistantMetadata: assistantMeta ?? undefined,
293
+ };
207
294
  }
208
- const assistantMeta =
209
- contact.contactType === "assistant"
210
- ? getAssistantContactMetadata(contact.id)
211
- : undefined;
212
- return {
213
- ok: true,
214
- contact: prepareContactResponse(contact),
215
- assistantMetadata: assistantMeta ?? undefined,
216
- };
217
295
  }
218
296
 
219
297
  // ---------------------------------------------------------------------------
@@ -607,7 +685,7 @@ export const ROUTES: RouteDefinition[] = [
607
685
  limit: z.number().optional(),
608
686
  }),
609
687
  responseBody: z.array(contactSchema),
610
- handler: ({ body = {} }: RouteHandlerArgs) => {
688
+ handler: async ({ body = {} }: RouteHandlerArgs) => {
611
689
  const parsed = z
612
690
  .object({
613
691
  query: z.string().optional(),
@@ -616,6 +694,23 @@ export const ROUTES: RouteDefinition[] = [
616
694
  limit: z.number().optional(),
617
695
  })
618
696
  .parse(body);
697
+
698
+ const hasFilter =
699
+ Boolean(parsed.query?.trim()) ||
700
+ Boolean(parsed.channelAddress) ||
701
+ Boolean(parsed.channelType);
702
+
703
+ // No-filter "search" is a list read — relay to the gateway so it returns
704
+ // the same source-of-truth data as `contacts list`.
705
+ if (!hasFilter) {
706
+ const { contacts } = await relayListContacts(parsed.limit ?? 50, undefined);
707
+ return contacts;
708
+ }
709
+
710
+ // True search stays daemon-native: gateway-native search is design-blocked.
711
+ log.debug(
712
+ "search_contacts: search served daemon-native (gateway-native search is design-blocked)",
713
+ );
619
714
  return searchContacts(parsed).map(prepareContactResponse);
620
715
  },
621
716
  },