@happyvertical/smrt-messages 0.62.12 → 0.62.13

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 (47) hide show
  1. package/AGENTS.md +6 -0
  2. package/agents/mail-search.md +40 -0
  3. package/dist/chunks/{AttachmentCollection-gv5YpGPo.js → AttachmentCollection-Dzz2iKjx.js} +4 -4
  4. package/dist/chunks/{AttachmentCollection-gv5YpGPo.js.map → AttachmentCollection-Dzz2iKjx.js.map} +1 -1
  5. package/dist/chunks/{Email---ifczUW.js → Email-DDMgkm_l.js} +11 -6
  6. package/dist/chunks/Email-DDMgkm_l.js.map +1 -0
  7. package/dist/chunks/EmailAccountCollection-CgZE9YAM.js +1992 -0
  8. package/dist/chunks/EmailAccountCollection-CgZE9YAM.js.map +1 -0
  9. package/dist/chunks/{EmailCollection-CHINTmyA.js → EmailCollection-lo8WePl-.js} +18 -3
  10. package/dist/chunks/EmailCollection-lo8WePl-.js.map +1 -0
  11. package/dist/chunks/{EmailFolder-C_H8u6bS.js → EmailFolder-Bu7y8-VX.js} +6 -6
  12. package/dist/chunks/{EmailFolder-C_H8u6bS.js.map → EmailFolder-Bu7y8-VX.js.map} +1 -1
  13. package/dist/chunks/{EmailFolderCollection-B83qLC-c.js → EmailFolderCollection-BpzzKBhM.js} +2 -2
  14. package/dist/chunks/{EmailFolderCollection-B83qLC-c.js.map → EmailFolderCollection-BpzzKBhM.js.map} +1 -1
  15. package/dist/chunks/{Message-Ccqg6BLO.js → Message-BwW51pgG.js} +6 -6
  16. package/dist/chunks/{Message-Ccqg6BLO.js.map → Message-BwW51pgG.js.map} +1 -1
  17. package/dist/chunks/{MessageCollection-BnHCLi1Q.js → MessageCollection-JjZybSMu.js} +2 -2
  18. package/dist/chunks/{MessageCollection-BnHCLi1Q.js.map → MessageCollection-JjZybSMu.js.map} +1 -1
  19. package/dist/chunks/{MessagingEndpointCollection-CHzGhkeL.js → MessagingEndpointCollection-FmbtiFJy.js} +2 -2
  20. package/dist/chunks/{MessagingEndpointCollection-CHzGhkeL.js.map → MessagingEndpointCollection-FmbtiFJy.js.map} +1 -1
  21. package/dist/collections/CorrespondentCollection.d.ts +6 -0
  22. package/dist/collections/CorrespondentCollection.d.ts.map +1 -0
  23. package/dist/collections/EmailCollection.d.ts +14 -0
  24. package/dist/collections/EmailCollection.d.ts.map +1 -1
  25. package/dist/connect.js +1 -1
  26. package/dist/index.d.ts +4 -0
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +843 -12
  29. package/dist/index.js.map +1 -1
  30. package/dist/manifest.json +557 -2
  31. package/dist/models/Correspondent.d.ts +63 -0
  32. package/dist/models/Correspondent.d.ts.map +1 -0
  33. package/dist/models/Email.d.ts.map +1 -1
  34. package/dist/services/CorrespondentService.d.ts +113 -0
  35. package/dist/services/CorrespondentService.d.ts.map +1 -0
  36. package/dist/services/MailSearchService.d.ts +127 -0
  37. package/dist/services/MailSearchService.d.ts.map +1 -0
  38. package/dist/smrt-knowledge.json +184 -9
  39. package/dist/smrt-knowledge.okf.md +9 -3
  40. package/dist/svelte/components/RecipientInput.svelte +54 -0
  41. package/dist/svelte/components/RecipientInput.svelte.d.ts +6 -0
  42. package/dist/svelte/components/RecipientInput.svelte.d.ts.map +1 -1
  43. package/package.json +11 -11
  44. package/dist/chunks/Email---ifczUW.js.map +0 -1
  45. package/dist/chunks/EmailAccountCollection-DkvT4tdP.js +0 -1992
  46. package/dist/chunks/EmailAccountCollection-DkvT4tdP.js.map +0 -1
  47. package/dist/chunks/EmailCollection-CHINTmyA.js.map +0 -1
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Private correspondents (Epic I, I6, #5132).
3
+ *
4
+ * `CorrespondentService` derives and serves one person's correspondents from
5
+ * the mail that person can read:
6
+ *
7
+ * - Private by construction. Every read and write filters on the acting
8
+ * user's id and the explicit tenant; there is no tenant-wide listing and no
9
+ * way to name another owner. A principal with no user id gets nothing.
10
+ * - Derived, never invented. `refresh()` scans the readable accounts' mail
11
+ * (the same decision as search: `listAccounts` with `read`) and stores
12
+ * address, latest display name, counts, first and last contact and the
13
+ * accounts the address was seen in. It never creates or links a
14
+ * smrt-profiles `Profile`.
15
+ * - Access follows the mail. Each row keeps a per-account breakdown, and every
16
+ * view (`list`/`suggest`/`get`) is computed from the accounts the viewer can
17
+ * read right now: counts, dates, name and `accountIds` never include an
18
+ * account that was revoked, and a row with no readable account is hidden.
19
+ * - `refresh()` only touches what it scanned. An empty readable set (no
20
+ * policy, tenant mismatch, no `read` scope) changes nothing; otherwise only
21
+ * the scanned accounts' entries are replaced, so a narrower principal can
22
+ * never erase data from accounts outside its view.
23
+ * - Delegated principals (a host scope or account ceiling, or a principal id
24
+ * that is not the user id, as agent credentials are) get nothing and cannot
25
+ * write unless the host passes `allowDelegated: true`, the explicit owner
26
+ * consent to act on the owner's private rows.
27
+ * - Linking is the owner's choice: `linkProfile()` stores a `Profile` id after
28
+ * checking the profile exists in the tenant; `unlinkProfile()` clears it.
29
+ *
30
+ * @packageDocumentation
31
+ */
32
+ import { type SmrtClassOptions } from '@happyvertical/smrt-core';
33
+ import type { MessagingPrincipal } from '../permissions.js';
34
+ export interface CorrespondentServiceOptions {
35
+ db: SmrtClassOptions['db'];
36
+ tenantId: string;
37
+ principal: MessagingPrincipal;
38
+ /**
39
+ * Let a delegated principal (agent credential with ceilings) use the
40
+ * owner's private correspondents. Off by default; hosts turn it on only
41
+ * with the owner's consent.
42
+ */
43
+ allowDelegated?: boolean;
44
+ }
45
+ export interface CorrespondentView {
46
+ id: string;
47
+ address: string;
48
+ displayName: string;
49
+ messageCount: number;
50
+ sentCount: number;
51
+ receivedCount: number;
52
+ firstContactAt: Date | null;
53
+ lastContactAt: Date | null;
54
+ accountIds: string[];
55
+ profileId: string | null;
56
+ }
57
+ export interface CorrespondentRefreshResult {
58
+ /** Correspondents written (created or updated). */
59
+ upserted: number;
60
+ /** Rows removed because no readable mail mentions them any more. */
61
+ removed: number;
62
+ /** Mail rows examined. */
63
+ scanned: number;
64
+ }
65
+ export interface ListCorrespondentsOptions {
66
+ /** Substring of address or display name (case-insensitive). */
67
+ query?: string;
68
+ /** Page size, 1 to 200. Default 50. */
69
+ limit?: number;
70
+ /** Previous page's `nextCursor`. */
71
+ cursor?: string | null;
72
+ }
73
+ /** Lower-cased, trimmed address, or null when it is not an email address. */
74
+ export declare function normalizeCorrespondentAddress(value: unknown): string | null;
75
+ export declare class CorrespondentService {
76
+ private readonly options;
77
+ constructor(options: CorrespondentServiceOptions);
78
+ private get ownerUserId();
79
+ /** Agent-style principal acting under ceilings or a credential id. */
80
+ private get delegated();
81
+ /** The owner whose rows this principal may use, or null. */
82
+ private get actingOwner();
83
+ private searchOptions;
84
+ private rows;
85
+ private readableIds;
86
+ /**
87
+ * Re-derive this owner's correspondents from readable mail. Idempotent.
88
+ * Only the scanned (readable) accounts' entries are replaced; entries of
89
+ * accounts outside the scan are kept as they are. Nothing changes when no
90
+ * account is readable. Addresses of the scanned accounts are not
91
+ * correspondents. A delegated principal is refused.
92
+ */
93
+ refresh(): Promise<CorrespondentRefreshResult>;
94
+ private ownAddresses;
95
+ /** The owner's correspondents, as seen through the readable accounts. */
96
+ private visible;
97
+ list(options?: ListCorrespondentsOptions): Promise<{
98
+ correspondents: CorrespondentView[];
99
+ nextCursor: string | null;
100
+ }>;
101
+ /**
102
+ * Recipient autocomplete: correspondents whose address or name starts with
103
+ * (or, for names, has a word starting with) `prefix`, best first.
104
+ */
105
+ suggest(prefix: string, limit?: number): Promise<CorrespondentView[]>;
106
+ private owned;
107
+ get(id: string): Promise<CorrespondentView | null>;
108
+ private assertMayWrite;
109
+ /** Link a correspondent to a `Profile` of this tenant (owner's choice). */
110
+ linkProfile(id: string, profileId: string): Promise<CorrespondentView>;
111
+ unlinkProfile(id: string): Promise<CorrespondentView>;
112
+ }
113
+ //# sourceMappingURL=CorrespondentService.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CorrespondentService.d.ts","sourceRoot":"","sources":["../../src/services/CorrespondentService.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,OAAO,EAEL,KAAK,gBAAgB,EACtB,MAAM,0BAA0B,CAAC;AAQlC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAM5D,MAAM,WAAW,2BAA2B;IAC1C,EAAE,EAAE,gBAAgB,CAAC,IAAI,CAAC,CAAC;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,kBAAkB,CAAC;IAC9B;;;;OAIG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,EAAE,MAAM,CAAC;IACtB,cAAc,EAAE,IAAI,GAAG,IAAI,CAAC;IAC5B,aAAa,EAAE,IAAI,GAAG,IAAI,CAAC;IAC3B,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1B;AAED,MAAM,WAAW,0BAA0B;IACzC,mDAAmD;IACnD,QAAQ,EAAE,MAAM,CAAC;IACjB,oEAAoE;IACpE,OAAO,EAAE,MAAM,CAAC;IAChB,0BAA0B;IAC1B,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,yBAAyB;IACxC,+DAA+D;IAC/D,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,uCAAuC;IACvC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,oCAAoC;IACpC,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACxB;AAoCD,6EAA6E;AAC7E,wBAAgB,6BAA6B,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAI3E;AAmED,qBAAa,oBAAoB;IACnB,OAAO,CAAC,QAAQ,CAAC,OAAO;gBAAP,OAAO,EAAE,2BAA2B;IAEjE,OAAO,KAAK,WAAW,GAGtB;IAED,sEAAsE;IACtE,OAAO,KAAK,SAAS,GAOpB;IAED,4DAA4D;IAC5D,OAAO,KAAK,WAAW,GAGtB;IAED,OAAO,CAAC,aAAa;YAIP,IAAI;YAIJ,WAAW;IAMzB;;;;;;OAMG;IACG,OAAO,IAAI,OAAO,CAAC,0BAA0B,CAAC;YAuKtC,YAAY;IAmB1B,yEAAyE;YAC3D,OAAO;IA2Bf,IAAI,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC;QAC3D,cAAc,EAAE,iBAAiB,EAAE,CAAC;QACpC,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;KAC3B,CAAC;IAoBF;;;OAGG;IACG,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,SAAI,GAAG,OAAO,CAAC,iBAAiB,EAAE,CAAC;YAuBxD,KAAK;IAsBb,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC;IAIxD,OAAO,CAAC,cAAc;IAMtB,2EAA2E;IACrE,WAAW,CAAC,EAAE,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAoBtE,aAAa,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC;CAQ5D"}
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Per-account mail search (Epic I, I6, #5132).
3
+ *
4
+ * `MailSearchService` searches the mail a principal may read and nothing else:
5
+ *
6
+ * - The searchable accounts are exactly `MessagingSettingsService.listAccounts`
7
+ * with the `read` scope, so the decision is `decideMailAccess` (owner, grant,
8
+ * tenant ceiling, the host's scope and account ceilings) and fails closed
9
+ * without a principal, on a tenant mismatch or without `configureMailAccess`.
10
+ * An `accountIds` filter can only narrow that set; unreadable ids are dropped.
11
+ * - Every local read is constrained to those account ids in the query itself
12
+ * and then runs as trusted code (`runWithMailSystemAccess`), because the
13
+ * decision was already made here with the explicit principal.
14
+ * - Local search is a keyword scan over a bounded, newest-first candidate
15
+ * window (case-insensitive on every database), with optional semantic
16
+ * ranking through core `semanticSearchIds()` when `Email` embeddings are
17
+ * available. Provider search asks each account's own server through the
18
+ * SDK's `search()` and falls back to the local index, per account, when the
19
+ * provider cannot or does not answer.
20
+ *
21
+ * @packageDocumentation
22
+ */
23
+ import type { SmrtClassOptions } from '@happyvertical/smrt-core';
24
+ import type { MessagingPrincipal } from '../permissions.js';
25
+ import { type MessagingAccountListing } from './MessagingSettingsService.js';
26
+ export interface MailSearchServiceOptions {
27
+ db: SmrtClassOptions['db'];
28
+ tenantId: string;
29
+ /** The acting principal, as for `MessagingSettingsService`. */
30
+ principal: MessagingPrincipal;
31
+ }
32
+ /** Filters shared by local and provider search. */
33
+ export interface MailSearchQuery {
34
+ /** Free text matched against subject, body, sender name and address. */
35
+ text?: string;
36
+ /** Narrow to these accounts; ids the principal cannot read are ignored. */
37
+ accountIds?: readonly string[];
38
+ /** Sender address or name contains. */
39
+ from?: string;
40
+ /** A recipient (to or cc) address or name contains. */
41
+ to?: string;
42
+ subject?: string;
43
+ /** Mailbox label or folder name or path (exact, case-insensitive). */
44
+ label?: string;
45
+ hasAttachment?: boolean;
46
+ isRead?: boolean;
47
+ isFlagged?: boolean;
48
+ /** Sent on or after. */
49
+ since?: Date;
50
+ /** Sent before. */
51
+ before?: Date;
52
+ /** Page size, 1 to 100. Default 25. */
53
+ limit?: number;
54
+ /** The previous page's `nextCursor`. */
55
+ cursor?: string | null;
56
+ /**
57
+ * `keyword` (default) never calls an embedding model. `semantic` ranks by
58
+ * meaning and falls back to keyword when embeddings are unavailable;
59
+ * `semanticUsed` on the result says which happened.
60
+ */
61
+ mode?: 'keyword' | 'semantic';
62
+ }
63
+ export interface MailSearchHit {
64
+ accountId: string;
65
+ /** Local `Email` row id; null for a provider hit not yet synced. */
66
+ emailId: string | null;
67
+ providerMessageId: string;
68
+ threadId: string;
69
+ subject: string;
70
+ fromAddress: string;
71
+ fromName: string;
72
+ date: Date | null;
73
+ snippet: string;
74
+ isRead: boolean;
75
+ isFlagged: boolean;
76
+ hasAttachments: boolean;
77
+ labels: string[];
78
+ /** Where the hit came from. */
79
+ source: 'local' | 'provider';
80
+ /** Similarity in 0..1 when ranked semantically. */
81
+ similarity?: number;
82
+ }
83
+ export interface MailSearchPage {
84
+ hits: MailSearchHit[];
85
+ nextCursor: string | null;
86
+ /** Accounts that were searched (readable and, if given, requested). */
87
+ accountIds: string[];
88
+ /** True when the scan window ended before every candidate was examined. */
89
+ truncated: boolean;
90
+ semanticUsed: boolean;
91
+ }
92
+ export interface MailProviderSearchResult {
93
+ hits: MailSearchHit[];
94
+ /** Accounts answered by the provider. */
95
+ providerAccountIds: string[];
96
+ /** Accounts answered from the local index instead, with the reason. */
97
+ fallbackAccounts: Array<{
98
+ accountId: string;
99
+ reason: string;
100
+ }>;
101
+ accountIds: string[];
102
+ truncated: boolean;
103
+ }
104
+ /** Addresses of a JSON `[{address, name}]` column as lower-cased haystacks. */
105
+ export declare function recipientHaystack(json: string | null | undefined): string;
106
+ export declare class MailSearchService {
107
+ private readonly options;
108
+ constructor(options: MailSearchServiceOptions);
109
+ /** Accounts the principal may search: owner or `read` grant, nothing else. */
110
+ searchableAccounts(): Promise<MessagingAccountListing[]>;
111
+ private scope;
112
+ /** Search the local index across every readable account. */
113
+ search(query?: MailSearchQuery): Promise<MailSearchPage>;
114
+ /**
115
+ * Ask each readable account's own server (SDK `search()`), falling back to
116
+ * the local index for accounts whose provider cannot search or fails. One
117
+ * account's failure never blocks the others. Provider hits that are already
118
+ * synced carry their local `emailId`.
119
+ */
120
+ searchProvider(query?: MailSearchQuery): Promise<MailProviderSearchResult>;
121
+ }
122
+ /**
123
+ * Accounts on which the principal holds `read`, paged out of
124
+ * `listAccounts()` (the one account-discovery decision).
125
+ */
126
+ export declare function readableMailAccounts(options: MailSearchServiceOptions): Promise<MessagingAccountListing[]>;
127
+ //# sourceMappingURL=MailSearchService.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MailSearchService.d.ts","sourceRoot":"","sources":["../../src/services/MailSearchService.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAGH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAOjE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EACL,KAAK,uBAAuB,EAE7B,MAAM,+BAA+B,CAAC;AAEvC,MAAM,WAAW,wBAAwB;IACvC,EAAE,EAAE,gBAAgB,CAAC,IAAI,CAAC,CAAC;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,+DAA+D;IAC/D,SAAS,EAAE,kBAAkB,CAAC;CAC/B;AAED,mDAAmD;AACnD,MAAM,WAAW,eAAe;IAC9B,wEAAwE;IACxE,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,2EAA2E;IAC3E,UAAU,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC/B,uCAAuC;IACvC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,uDAAuD;IACvD,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,sEAAsE;IACtE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,wBAAwB;IACxB,KAAK,CAAC,EAAE,IAAI,CAAC;IACb,mBAAmB;IACnB,MAAM,CAAC,EAAE,IAAI,CAAC;IACd,uCAAuC;IACvC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,wCAAwC;IACxC,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB;;;;OAIG;IACH,IAAI,CAAC,EAAE,SAAS,GAAG,UAAU,CAAC;CAC/B;AAED,MAAM,WAAW,aAAa;IAC5B,SAAS,EAAE,MAAM,CAAC;IAClB,oEAAoE;IACpE,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,IAAI,GAAG,IAAI,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,OAAO,CAAC;IAChB,SAAS,EAAE,OAAO,CAAC;IACnB,cAAc,EAAE,OAAO,CAAC;IACxB,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,+BAA+B;IAC/B,MAAM,EAAE,OAAO,GAAG,UAAU,CAAC;IAC7B,mDAAmD;IACnD,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,aAAa,EAAE,CAAC;IACtB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,uEAAuE;IACvE,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,2EAA2E;IAC3E,SAAS,EAAE,OAAO,CAAC;IACnB,YAAY,EAAE,OAAO,CAAC;CACvB;AAED,MAAM,WAAW,wBAAwB;IACvC,IAAI,EAAE,aAAa,EAAE,CAAC;IACtB,yCAAyC;IACzC,kBAAkB,EAAE,MAAM,EAAE,CAAC;IAC7B,uEAAuE;IACvE,gBAAgB,EAAE,KAAK,CAAC;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC/D,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,SAAS,EAAE,OAAO,CAAC;CACpB;AA4BD,+EAA+E;AAC/E,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,CAczE;AA0FD,qBAAa,iBAAiB;IAChB,OAAO,CAAC,QAAQ,CAAC,OAAO;gBAAP,OAAO,EAAE,wBAAwB;IAE9D,8EAA8E;IACxE,kBAAkB,IAAI,OAAO,CAAC,uBAAuB,EAAE,CAAC;YAIhD,KAAK;IASnB,4DAA4D;IACtD,MAAM,CAAC,KAAK,GAAE,eAAoB,GAAG,OAAO,CAAC,cAAc,CAAC;IA2FlE;;;;;OAKG;IACG,cAAc,CAClB,KAAK,GAAE,eAAoB,GAC1B,OAAO,CAAC,wBAAwB,CAAC;CA2HrC;AAgDD;;;GAGG;AACH,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,wBAAwB,GAChC,OAAO,CAAC,uBAAuB,EAAE,CAAC,CAiBpC"}
@@ -3,13 +3,14 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-messages",
6
- "packageVersion": "0.62.12",
6
+ "packageVersion": "0.62.13",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "d6aa5db1c4b9e75fa72b59aa420c83f5f9ba31cb54cf90a1a9c45c356cc2ee3f",
11
- "packageJson": "726561ec821e7dc5814f87af58d72db6fc8c427aa1c9b528400afde25f68cac8",
12
- "agents": "e1a6ff5dc84ce9958d6a1c7c57e18d715c90705d16f50d0c6b79f7bfdfa51b35",
10
+ "manifest": "b4480434be4a7a4b218e1b0c38a43ac3361d0cee8a418f93baa67240a0a9773e",
11
+ "packageJson": "7609928359f6781025fa37f959e780a8d08c26053f70f8890363f15e261df49b",
12
+ "agents": "9254fbc5f98666cbdd02894f21fb8ff4976e0d6e55f39dbf6cd86e0a4a71001d",
13
+ "moduleDoc:agents/mail-search.md": "9dac1619a1486f2fa94980e141ebc5003851c27cd77ced6d5ff64d348429fdb1",
13
14
  "moduleDoc:agents/notification-outbox.md": "0e9a870c4b2d5f0fec47af0dff6e61d216fb0121d384d99bccfc506beb6e38ad",
14
15
  "moduleDoc:agents/profile-recipients.md": "1b6710bf646ddeafd6836df8270fcbb8e29226dceda716a693d945cc2e914606"
15
16
  },
@@ -86,7 +87,7 @@
86
87
  "typescript"
87
88
  ],
88
89
  "risks": [
89
- "cross-package-refs:16",
90
+ "cross-package-refs:18",
90
91
  "sensitive-fields-excluded",
91
92
  "sti-inheritance"
92
93
  ],
@@ -710,6 +711,23 @@
710
711
  "tags": [],
711
712
  "risks": []
712
713
  },
714
+ {
715
+ "name": "CorrespondentCollection",
716
+ "qualifiedName": "@happyvertical/smrt-messages:CorrespondentCollection",
717
+ "collection": "correspondents",
718
+ "tableName": "correspondents",
719
+ "packageName": "@happyvertical/smrt-messages",
720
+ "extends": "SmrtCollection",
721
+ "fields": [],
722
+ "relationships": [],
723
+ "methods": [],
724
+ "surfaces": [],
725
+ "relationshipFeatures": [
726
+ "uuidColumns"
727
+ ],
728
+ "tags": [],
729
+ "risks": []
730
+ },
713
731
  {
714
732
  "name": "EmailAccountCollection",
715
733
  "qualifiedName": "@happyvertical/smrt-messages:EmailAccountCollection",
@@ -1437,7 +1455,8 @@
1437
1455
  "markAllRead",
1438
1456
  "markFolderRead",
1439
1457
  "search",
1440
- "searchEmails"
1458
+ "searchEmails",
1459
+ "semanticMatches"
1441
1460
  ],
1442
1461
  "methodSignatures": [
1443
1462
  {
@@ -1656,6 +1675,16 @@
1656
1675
  "filters?: EmailSearchFilters"
1657
1676
  ],
1658
1677
  "returns": "Promise<Email[]>"
1678
+ },
1679
+ {
1680
+ "name": "semanticMatches",
1681
+ "async": true,
1682
+ "params": [
1683
+ "query: string",
1684
+ "where: Record<string, unknown>",
1685
+ "options?: object"
1686
+ ],
1687
+ "returns": "Promise<Array<object> | null>"
1659
1688
  }
1660
1689
  ],
1661
1690
  "surfaces": [
@@ -1809,6 +1838,12 @@
1809
1838
  "operation": "searchEmails",
1810
1839
  "objectName": "@happyvertical/smrt-messages:EmailCollection"
1811
1840
  },
1841
+ {
1842
+ "kind": "cli",
1843
+ "name": "emailcollection_semanticMatches",
1844
+ "operation": "semanticMatches",
1845
+ "objectName": "@happyvertical/smrt-messages:EmailCollection"
1846
+ },
1812
1847
  {
1813
1848
  "kind": "cli",
1814
1849
  "name": "emailcollection_markFolderRead",
@@ -2011,6 +2046,13 @@
2011
2046
  "code": "not-included",
2012
2047
  "reason": "not listed in api.include",
2013
2048
  "objectName": "@happyvertical/smrt-messages:EmailCollection"
2049
+ },
2050
+ {
2051
+ "kind": "api",
2052
+ "operation": "semanticMatches",
2053
+ "code": "not-included",
2054
+ "reason": "not listed in api.include",
2055
+ "objectName": "@happyvertical/smrt-messages:EmailCollection"
2014
2056
  }
2015
2057
  ],
2016
2058
  "relationshipFeatures": [
@@ -3964,6 +4006,128 @@
3964
4006
  "tags": [],
3965
4007
  "risks": []
3966
4008
  },
4009
+ {
4010
+ "name": "Correspondent",
4011
+ "qualifiedName": "@happyvertical/smrt-messages:Correspondent",
4012
+ "collection": "correspondents",
4013
+ "description": "Someone one person writes to or hears from, derived from that person's synced mail (#5132).",
4014
+ "tableName": "correspondents",
4015
+ "packageName": "@happyvertical/smrt-messages",
4016
+ "extends": "SmrtObject",
4017
+ "fields": [
4018
+ {
4019
+ "name": "tenantId",
4020
+ "type": "text",
4021
+ "required": true,
4022
+ "columnType": "UUID"
4023
+ },
4024
+ {
4025
+ "name": "ownerUserId",
4026
+ "type": "crossPackageRef",
4027
+ "required": true,
4028
+ "related": "@happyvertical/smrt-users:User",
4029
+ "columnType": "UUID"
4030
+ },
4031
+ {
4032
+ "name": "address",
4033
+ "type": "text",
4034
+ "required": true,
4035
+ "columnType": "TEXT"
4036
+ },
4037
+ {
4038
+ "name": "displayName",
4039
+ "type": "text",
4040
+ "required": false,
4041
+ "columnType": "TEXT"
4042
+ },
4043
+ {
4044
+ "name": "messageCount",
4045
+ "type": "integer",
4046
+ "required": true,
4047
+ "columnType": "INTEGER",
4048
+ "default": 0
4049
+ },
4050
+ {
4051
+ "name": "sentCount",
4052
+ "type": "integer",
4053
+ "required": true,
4054
+ "columnType": "INTEGER",
4055
+ "default": 0
4056
+ },
4057
+ {
4058
+ "name": "receivedCount",
4059
+ "type": "integer",
4060
+ "required": true,
4061
+ "columnType": "INTEGER",
4062
+ "default": 0
4063
+ },
4064
+ {
4065
+ "name": "firstContactAt",
4066
+ "type": "datetime",
4067
+ "required": false,
4068
+ "columnType": "TIMESTAMP"
4069
+ },
4070
+ {
4071
+ "name": "lastContactAt",
4072
+ "type": "datetime",
4073
+ "required": false,
4074
+ "columnType": "TIMESTAMP"
4075
+ },
4076
+ {
4077
+ "name": "accountIds",
4078
+ "type": "text",
4079
+ "required": false,
4080
+ "columnType": "TEXT"
4081
+ },
4082
+ {
4083
+ "name": "accountBreakdown",
4084
+ "type": "text",
4085
+ "required": false,
4086
+ "columnType": "TEXT"
4087
+ },
4088
+ {
4089
+ "name": "profileId",
4090
+ "type": "crossPackageRef",
4091
+ "required": false,
4092
+ "related": "@happyvertical/smrt-profiles:Profile",
4093
+ "columnType": "UUID"
4094
+ }
4095
+ ],
4096
+ "relationships": [
4097
+ {
4098
+ "name": "ownerUserId",
4099
+ "type": "crossPackageRef",
4100
+ "required": true,
4101
+ "related": "@happyvertical/smrt-users:User",
4102
+ "columnType": "UUID"
4103
+ },
4104
+ {
4105
+ "name": "profileId",
4106
+ "type": "crossPackageRef",
4107
+ "required": false,
4108
+ "related": "@happyvertical/smrt-profiles:Profile",
4109
+ "columnType": "UUID"
4110
+ }
4111
+ ],
4112
+ "methods": [],
4113
+ "tenant": {
4114
+ "scoped": true,
4115
+ "mode": "required",
4116
+ "field": "tenantId"
4117
+ },
4118
+ "conflictColumns": [
4119
+ "tenant_id",
4120
+ "owner_user_id",
4121
+ "address"
4122
+ ],
4123
+ "surfaces": [],
4124
+ "relationshipFeatures": [
4125
+ "crossPackageRef",
4126
+ "uuidColumns"
4127
+ ],
4128
+ "tags": [],
4129
+ "risks": []
4130
+ },
3967
4131
  {
3968
4132
  "name": "Email",
3969
4133
  "qualifiedName": "@happyvertical/smrt-messages:Email",
@@ -11793,6 +11957,12 @@
11793
11957
  "operation": "searchEmails",
11794
11958
  "objectName": "@happyvertical/smrt-messages:EmailCollection"
11795
11959
  },
11960
+ {
11961
+ "kind": "cli",
11962
+ "name": "emailcollection_semanticMatches",
11963
+ "operation": "semanticMatches",
11964
+ "objectName": "@happyvertical/smrt-messages:EmailCollection"
11965
+ },
11796
11966
  {
11797
11967
  "kind": "cli",
11798
11968
  "name": "emailcollection_markFolderRead",
@@ -13851,14 +14021,19 @@
13851
14021
  "prompts": [],
13852
14022
  "relationshipsV2": {
13853
14023
  "foreignKeyFields": 21,
13854
- "crossPackageRefFields": 16,
14024
+ "crossPackageRefFields": 18,
13855
14025
  "junctionCollections": 0,
13856
14026
  "hierarchicalObjects": 0,
13857
14027
  "polymorphicAssociations": 0,
13858
- "uuidColumns": 130
14028
+ "uuidColumns": 138
13859
14029
  },
13860
- "agentDoc": "# @happyvertical/smrt-messages\n\nMulti-channel messaging with STI hierarchies for both messages and accounts. Credential encryption via smrt-secrets.\n\n## STI Hierarchies\n\n**Messages** (share `messages` table):\n- `Message` (base): accountId, personaId, endpointId, correlationId, threadId, subject, body, fromAddress, toAddresses (JSON), sendStatus (draft/sending/sent/failed), retryCount\n- `Email`: messageId (RFC 822), inReplyTo, ccAddresses, bccAddresses, htmlBody, textBody, folderId, labels, headers\n- `Tweet`: tweetId, retweetCount, likeCount, mediaUrls, hashtags, mentions\n- `SlackMessage`: channelId, slackTs, slackThreadTs, reactions, blocks\n\n**Accounts** (share `accounts` table):\n- `Account` (base): channelType, providerType, public configuration,\n credentialSecretId, isActive, lastSyncAt, deprecated sensitive settings\n- `EmailAccount`, `TwitterAccount`, `SlackAccount`, `ZulipAccount`,\n `TelegramAccount`: provider-specific identity/sender behavior\n\n## Persona messaging\n\n- `MessagingEndpoint`: tenant-owned, write-only destination JSON with masked\n display helper.\n- `PersonaMessageRoute`: persona → account + endpoint, selected by purpose and\n descending priority.\n- `PersonaMessagingService`: persists and sends through an enabled route.\n- Provider registry: public setup descriptors + optional sender factory. Keep\n channel (`sms`) separate from provider (`twilio`).\n- Permissions: `messages.send`, `messages.manage-routes`,\n `messages.manage-credentials`.\n- `MessagingSettingsService` is the permissioned server boundary;\n its host-supplied `resolvePersonaTenantId` proves cross-package ownership.\n `MessagingSettingsPanel` is the callback-driven Svelte surface.\n- Account, endpoint, and route generated surfaces are read-only. Do not add\n generated mutations around the settings service or make secret fields writable.\n- **Recipe `messages.slack`** (`src/recipes.ts`, help in `src/help/slack.md`): lists Slack messages and workspaces beside the Mailbox and Notifications recipes; workspaces stay read-only and sending goes through the senders, not generated routes. Fields it shows carry `@field({ description })` in plain words; keep them when editing the models.\n\n## Per-account mail access (owner + grants)\n\nOptional by default: `Account.ownerUserId` is nullable, and an account without\nan owner stays tenant-wide. Apps that want private or shared mailboxes set\nowners and call `configureMailAccess({ options, resolvePrincipal })` at startup\n(`access.ts`); smrt never knows the host's credential model, the host returns a\n`MailPrincipal` (`userId` + tenant, optional `scopes` / `accountIds` ceilings).\n\n- Scopes `read`, `triage`, `draft`, `send` are `ResourceGrant` rows (resource\n type `messages:account`, permission `messages.<scope>`) checked by\n `checkResourceOperationPermission`, so the grantee also needs the tenant\n `messages.<scope>` permission (the ceiling). The owner holds every scope\n implicitly. Agents are `User` rows the host maps its credential to; the\n principal ceilings are intersected with the grant, never added to it.\n- `access-enforcement.ts` is a `GlobalInterceptors` entry registered at package\n load. Emails, folders and attachments (matched by STI ancestry) are filtered\n in `beforeList`/`afterList`/`afterGet`; raw `query()` on them is refused while\n any account is closed to the principal. Fail closed: no principal, no\n resolver or a foreign tenant means owned accounts are invisible. No tenant\n admin or super-admin bypass; trusted work (sync, outbox) uses\n `runWithMailSystemAccess()`. `EmailAccount.syncFrom()` does so itself.\n- Attachments carry a denormalized `accountId` (always derived from the message in a\n `beforeSave` interceptor, never caller-supplied) so lists, projections and counts filter in SQL; run\n `AttachmentCollection.backfillAccountIds()` once after upgrading (legacy rows\n without it are hidden from every read until then).\n- `connectMailbox` refuses by default: give the service `allowedMailHosts`\n (and optionally `allowedMailPorts`) or your own `validateMailbox`. The\n built-in validator never connects to private, loopback or link-local\n addresses and returns only a generic error. It checks every target field\n present (`host`, `endpoint`, and the `jmap` provider's `url`): https only, no\n userinfo, listed host and port. The `jmap` provider stays `available: false`\n on purpose (`available` means outbound transport; JMAP is receive and sync\n only), and `connectMailbox` still connects it. Policy lookups use the\n configured db handle, not a caller's transaction.\n- `Message.send()` needs the `send` scope on an owned account. Account rows are\n not filtered (senders, routes and the outbox read them without a principal).\n- `MailAccessService` (`grant`, `revoke`, `list`, `setOwner`) needs tenant\n `messages.manage-access` AND ownership (or delegation); an administrator\n cannot read, self-grant or take over an owned mailbox. Unowned accounts can be\n claimed once with `messages.manage-credentials`.\n- `MessagingSettingsService.listAccounts({ limit, cursor })` is the account\n discovery for a principal: only accounts it owns or holds an active grant on\n (never unowned or foreign accounts), with effective `scopes` and\n `relation: 'owner' | 'shared'`, via `decideMailAccess`. Fail closed with no\n principal user, a tenant mismatch or no `configureMailAccess`.\n- `seedMessagesRolePermissions({ db })` seeds the tenant `messages.*` slugs for\n the system roles (owner/admin: read, triage, draft, send, manage-credentials,\n manage-access; member: the four scopes; viewer: read). Idempotent, additive,\n system roles only; without it grants and `manage-access` fail closed on a\n fresh app. The matrix is `MESSAGES_ROLE_PERMISSION_MATRIX`.\n- Before `configureMailAccess` is called the policy still fails closed on\n owned accounts: every collection operation on a mail class (the core `onCollectionReady`\n interceptor hook, so STI subclasses on a default collection are covered) registers its\n database, per database, and the policy hides every owned account's mail\n through list, count, projections, facets and raw queries; it learns the database from the first mail or account row it\n sees and, with no principal resolver, hides every owned account's mail.\n Direct hydration (`new Email({ id }).initialize()`, `loadRelated()`) is gated\n in the models' `loadFromId`/`loadFromSlug`.\n- `connectionStatus` (`connected` / `needs_reconnect`) and `statusMessage` mark\n an account whose sign-in the server refused; `syncFrom()` sets it.\n\n## Mailbox connect (provider-neutral)\n\nCredentials reach smrt-secrets in two ways; neither writes the plaintext `settings` fallback.\n\n- **Write-only app password**: `MessagingSettingsService.connectMailbox()`\n (permission `messages.manage-credentials`). The candidate credential is\n validated by opening a session first (`validateMailbox` option, default the\n provider's email client); a refusal leaves no account and no secret, and the\n error text has the secret redacted. The connecting user becomes the owner;\n `label` and the per-account endpoint (`configuration`) are stored; reconnect\n replaces the secret and is owner-only. `setAccountActive()` pauses/resumes\n (`isActive`), `removeAccount()` deletes the secret, the synced mail and the\n account. IMAP/POP3 are admitted here (receive-only), not by `saveAccount`.\n- **Generic OAuth 2.0 / OIDC**: `@happyvertical/smrt-messages/connect`\n (`startMailOAuthConnect`, `completeMailOAuthConnect`, `MailOAuthProvider`)\n on the shared kernel `@happyvertical/smrt-secrets/connect` (single-use\n tenant- and user-bound `ConnectState`, PKCE, safe return path, OIDC\n discovery with issuer check). The signed-in user becomes the owner; an\n account owned by someone else or by no one is never taken over. No role\n checks in the flow: authorize before calling.\n- **Reconnect**: `syncFrom()` marks an auth failure `connectionStatus =\n 'needs_reconnect'` (`Account.markNeedsReconnect/markConnected`) instead of\n failing silently.\n- The Google provider is a later step (sdk#1405), not part of this flow.\n\n## In-app notifications (`UserNotification`)\n\nThe in-app channel: one stored row per person, with read state.\n`user_notifications`: `tenantId` (required), `recipientUserId`\n(`@crossPackageRef` smrt-users:User, uuid), `kind`, `title`, `body`, `href`,\n`severity` (info/success/warning/error), `sourceRef`, `occurredAt`, `readAt`,\n`dismissedAt`. Conflict identity `(tenant_id, recipient_user_id, source_ref)`.\n\n- `UserNotificationService` is the only access path: `notify()` /\n `notifyMany()` (dedupe on `sourceRef`, existing row returned untouched;\n a unique ref is generated when omitted), `listForUser()` / `countUnread()`\n across explicit `tenantIds` (each read under `withTenant`), `markRead()`,\n `dismiss()` (also marks read), `markAllRead()`. Every write filters on the\n recipient, so another user's id matches nothing.\n- Generated REST/MCP/CLI are off (`api`/`mcp`/`cli: false`): a tenant-scoped\n list would expose every member's rows. Hosts expose their own routes that\n pass the signed-in user's id, never a request-chosen one.\n- Hosts decide who is told (e.g. `SocialPost.createdByUserId` for a failed\n post). New table: consumers run `db:migrate`.\n\n## Notification email outbox (`NotificationDelivery`)\n\n`NotificationOutboxService` is the external-channel counterpart of\n`UserNotificationService`: `enqueueEmail()` stores one delivery per\n`(tenant, recipient, channel, sourceRef)` after the host resolves the\nrecipient address and same-tenant sender account (callers never choose an\naddress); `dispatchDue()` leases due rows by compare-and-set\n(`NotificationDelivery.transition()`), creates the single outbound `Email`\nunder the lease, and settles sent/retry/failed/uncertain. Never resend an\n`uncertain` row automatically. Contract, retry, and reconciliation policy:\n[agents/notification-outbox.md](agents/notification-outbox.md). New table:\nconsumers run `db:migrate`.\n\n`NotificationOptOut` (`notification_opt_outs`, tenant-required, generated\nsurfaces off) is the per-recipient opt-out ledger for the outbox's\n`isSuppressed` hook, keyed `(tenant, recipient, channel, scope)` with scope `*`\nor `project:<uuid>`-style keys. `NotificationOptOutService`: idempotent\n`optOut`/`optIn` (with a `principal` only `userId === recipientUserId` may\nchange a row, and only in the principal's own `tenantId`, else\n`NotificationOptOutDeniedError`; no principal = trusted host code), trusted `isOptedOut` (a `*` row matches every scope), `listForRecipient`\n(principal required). `optOutSuppression(service, scopeOf)` builds the\n`isSuppressed` function. Details in the outbox doc; consumers run `db:migrate`.\n\n## Credential Security\n\nAccount credentials stored via tenant-bound `credentialSecretId` →\nsmrt-secrets. Use `setCredentials()`/`getCredentials()` — never store passwords\ndirectly. Credential descriptor schemas contain field definitions, never values.\n\n## Send Lifecycle\n\n`message.send()`: resolves account → creates provider sender → updates sendStatus. Retry support with `maxRetries` budget.\nA failure the provider may still have accepted carries\n`MessageSendResult.outcomeUnknown` (set by `EmailSender` unless\n`isDefiniteSendRejection()` proves a refusal, and when a sender throws) and is\npersisted as `metadata.sendOutcomeUnknown`; never auto-resend it.\n`EmailSender` attaches the message's stored `Attachment` rows (read through\n`Attachment.readContent()`, under the message's tenant context) plus\n`SendEmailOptions.attachments` bytes; an unreadable or file-less row fails the\nsend with the error on `sendError`, never a silent drop (#3808).\n`PersonaMessagingService.send({ attachments })` accepts them on email routes only.\n\n## Provider entry points (bundle boundary, #1979)\n\nThe package root is provider-neutral: models, collections, services,\npermissions, and the provider registry carry **zero provider-SDK weight**.\nProvider SDK wrappers (`@happyvertical/email`, `@happyvertical/messages`) are\nreachable only through explicit entry points, imported once at server startup:\n\n```ts\nimport '@happyvertical/smrt-messages/providers/email'; // smtp/imap/pop3/gmail\nimport '@happyvertical/smrt-messages/providers/slack';\nimport '@happyvertical/smrt-messages/providers/twitter';\nimport '@happyvertical/smrt-messages/providers/all'; // all of the above\n```\n\n- Without the matching entry, `EmailAccount.createClient()` (send + mailbox\n sync) throws an actionable error and `SlackSender`/`TweetSender` return a\n failure result naming the entry to import. Telegram and Zulip are\n fetch-based and always work from the root.\n- Builtin registry definitions stay metadata-only (setup fields for UIs); the\n entries upgrade them with `createEmailClient`/`createMessageClient`/\n `createSender` hooks. Never import a provider SDK from any module reachable\n from `src/index.ts` — the consumer bundle gate (`packages/bundle-gate`)\n fails CI when one becomes reachable.\n- `Attachment.readContent()` loads `@happyvertical/files` through core's\n `importOptionalDependency` boundary and keeps its null-on-failure contract\n in builds where the SDK is absent.\n\n## Gotchas\n\n- **Manifest before decorators**: every decorated model imports\n `../__smrt-register__.js`, and `package.json#sideEffects` lists\n `./src/__smrt-register__.ts`. Without both, the library build dropped or\n reordered the self-registration, so dist classes registered with only their\n decorated fields and could adopt smrt-ledgers' same-named `Account` (#3098).\n- **`Account` is not unique**: smrt-ledgers also declares `Account` (on\n `ledger_accounts`). Resolve by constructor or qualified name; the\n coexistence tests (`ledger-account-identity-*`, and the PostgreSQL lane\n `pnpm test:postgres`) load both packages in both orders.\n Both declare the `accounts` collection, so registering the ledgers `Account`\n auto-loads this family from its manifest as STI siblings. Core loads this\n base with them and never takes the ledgers `Account` for it (#4735,\n `ledger-account-identity-sti-siblings.test.ts`).\n- **STI `_meta_type`**: qualified format `@happyvertical/smrt-messages:Email`\n- **JSON fields**: all address/metadata fields are JSON strings with `getX()`/`setX()` helpers\n- **RFC 822 threading**: Email uses `inReplyTo`/`messageId`/`references` — manual management required\n- **Attachment.messageId**: use this field (not `emailId`); old getter/setter mapped via deprecation wrapper\n- **Optional tenancy**: `@TenantScoped({ mode: 'optional' })` on Message, Account, Attachment\n- **Required tenancy**: endpoints and persona routes are always tenant scoped\n- **Secrets are write-only**: never serialize credentials or endpoint.address to an app\n\n## Intake byte snapshots\n\n`EmailAccount.readIntakeMessage(providerLookup, maxBytes, imapIdentity?)` is the authorized host seam for\nopt-in ingestion. It copies full-message attachment bytes from the registered\nemail provider and fails when only attachment metadata is available; it never\nreads provider-supplied paths or advances sync checkpoints. Keep this path\nprovider-neutral and exclude arbitrary headers/credentials from its snapshot.\nIMAP lookup must include folder/UIDVALIDITY/UID verification; sender Message-ID\nis a lookup hint, never the durable delivery identity.\n\nProtected notification Emails carry durable delivery provenance. Their canonical\n`send`/`retrySend`, ordinary save/delete, and default EmailSender handoff are\nconstrained by `protected-notification-handoff.ts` (package-private, never a root\nexport). Only the outbox enters its exact one-use scope after current trusted\npolicy/byte validation. Preserve old-row/constructor identity checks, current\npersisted lease checks at the actual provider boundary, copied byte buffers and\nunknown-outcome marker protection. See the outbox contract and shared protected\nhandoff suite (SQLite and migrated PostgreSQL).\n\n## Protected external contacts\n\nProfile email uses exclusive `recipientProfileId` plus `resolveProfileRecipient`, a reserved `profileNotificationPolicy` and exact current tenant-owned public Profile email. No User account is required. Before activating profiles, run normal framework schema migration and public `planNotificationProfileRecipients` / `migrateNotificationProfileRecipients`; runtime verifies physical constraints and never applies DDL. Legacy User notification and opt-out paths remain User-only. See [profile recipient contract and matrix](agents/profile-recipients.md).\n\n## Incremental mail sync (change feed)\n\n`EmailAccount.syncChanges({ limit?, maxBatches?, since? })` (`mail-sync.ts`) drives\n`EmailClient.getChanges()` (JMAP provider `jmap`; `@happyvertical/email` 0.114+).\n`syncFrom()` stays the polling path for IMAP/POP3.\n\n- `EmailAccount.syncCursor` is the opaque feed cursor (sensitive + readonly, never\n on generated surfaces). It is saved only after its batch is applied; a failure\n anywhere leaves it where it was, so the job just retries.\n- Rows are keyed on `Email.providerMessageId` (the server's own id, per account),\n so applying a batch twice changes nothing. Added/changed messages upsert,\n `removed` deletes, `folders` upserts `EmailFolder` by path and counts are\n recomputed for touched folders. Metadata-only changes keep stored bodies.\n- `resync-required` clears the cursor and runs a full pass in the same run; a\n full pass from no cursor deletes stored messages (with a `providerMessageId`)\n the server no longer has. A second resync request in one run throws.\n- One lane per account: runs queue behind each other in-process, work on the\n stored (revision-guarded) row, and the job is deduplicated per tenant+account.\n Inactive and `needs_reconnect` accounts, and clients without `getChanges`,\n return `{ status: 'skipped' }`. Auth failures call `markNeedsReconnect()` and\n throw with `retryable: false`. The sync runs under `runWithMailSystemAccess()`.\n- Job: `enqueueMailSync(account)` / `enqueueDueMailSyncs(accounts)`\n (`mail-sync-jobs.ts`, queue `mail-sync`, dedupe key `mail-sync:<accountId>`)\n target `EmailAccount.syncChanges` through `@happyvertical/smrt-jobs` (optional\n peer). The host runs the `TaskRunner` and schedules `enqueueDueMailSyncs`.\n- Backfill horizon (#5200): optional `EmailAccount.backfillSince` (null = whole\n mailbox, the default) or per-run `since` (`Date`/ISO string, `null` lifts the\n stored one; `enqueueMailSync({ since })` forwards it as an ISO string). A\n message dated before it is not stored unless it already is; undated mail is\n kept; `MailSyncResult.beforeHorizon` counts the skips. The SDK change feed\n cannot filter by date, so the server still sends the older mail and it is\n dropped here (saves rows, not transfer; a server-side horizon needs an SDK change).\n- Horizon vs cursor: `cursorHorizon` records the horizon the saved cursor was\n built under (null = unbounded, also legacy cursors). If a run's effective\n horizon is earlier than it, or cleared (`since: null`), the cursor is dropped\n and the run does a full pass with prune; narrowing or an unchanged horizon\n keeps the cursor.\n- Persisted health (#5200): `lastSyncError` is set on any failed run (also\n client-build failures and sign-in refusals, which additionally set\n `needs_reconnect`) and cleared by the next successful run; a transient failure\n never changes `connectionStatus`. `backlog` mirrors `MailSyncResult.hasMore`\n of the last successful run. Both are plain optional columns (additive).\n- Known gaps: attachment rows are not created (only `hasAttachments`/`size`);\n a renamed server folder creates a new folder row (stored messages keep the old\n path until they change); `jmap` has no connect-flow validator yet and is not an\n outbound transport.\n\n## Triage write-back\n\n`EmailAccount.triage(action, emailIds)` (and `Email.triage(action)`,\n`mail-triage.ts`) writes mark read/unread, star/unstar, archive, spam/not spam,\nlabel add/remove and move to the server, then updates the local row. Actions are\n`{ kind: 'markRead' | 'markUnread' | 'star' | 'unstar' | 'archive' | 'markSpam' |\n'unmarkSpam' }`, `{ kind: 'addLabels' | 'removeLabels', labels }` and\n`{ kind: 'move', folder }`; ids are local `Email` row ids.\n\n- Access: needs `read` **and** `triage` on the account (`assertMailAccess`, fail\n closed; `MailAccessError`) before any server call or local write.\n- Server first, per message: the result is `{ updated, failed, stale }`. Only ids\n the server accepted are written; refusals (and ids that are missing, on another\n account, or not yet synced) come back in `failed`. A thrown client error\n changes nothing. Auth failures mark the account `needs_reconnect`.\n- Convergence: an accepted message is read back (`getMessage`) and stored through\n `applyServerMessage`, exactly as sync stores it, so the next sync is a no-op.\n If the read-back fails the id is `stale` and sync fixes the row. Triage runs in\n the account's sync lane (`inLane`), so it never interleaves with a sync here.\n- Providers whose `getCapabilities().writeBack` lacks the needed key (`flags`,\n `labels`, `archive`, `spam`) throw `MailWriteBackUnsupportedError` first.\n- `move` removes a message from the mailboxes it is in now (from its stored\n labels) and adds `folder`; pass a path as stored on `EmailFolder`.\n- Every public method on an `@smrt()` class becomes a `<collection>.<method>`\n permission; `Email.triage` is why `messages.triage` in `permissions.ts` carries\n the generated name and description (the catalog rejects two for one slug).\n- Known gaps: drafts and send, the acting principal is not recorded (#5141), and\n a mailbox the server has not reported yet has no `EmailFolder` row until sync.\n",
14030
+ "agentDoc": "# @happyvertical/smrt-messages\n\nMulti-channel messaging with STI hierarchies for both messages and accounts. Credential encryption via smrt-secrets.\n\n## STI Hierarchies\n\n**Messages** (share `messages` table):\n- `Message` (base): accountId, personaId, endpointId, correlationId, threadId, subject, body, fromAddress, toAddresses (JSON), sendStatus (draft/sending/sent/failed), retryCount\n- `Email`: messageId (RFC 822), inReplyTo, ccAddresses, bccAddresses, htmlBody, textBody, folderId, labels, headers\n- `Tweet`: tweetId, retweetCount, likeCount, mediaUrls, hashtags, mentions\n- `SlackMessage`: channelId, slackTs, slackThreadTs, reactions, blocks\n\n**Accounts** (share `accounts` table):\n- `Account` (base): channelType, providerType, public configuration,\n credentialSecretId, isActive, lastSyncAt, deprecated sensitive settings\n- `EmailAccount`, `TwitterAccount`, `SlackAccount`, `ZulipAccount`,\n `TelegramAccount`: provider-specific identity/sender behavior\n\n## Persona messaging\n\n- `MessagingEndpoint`: tenant-owned, write-only destination JSON with masked\n display helper.\n- `PersonaMessageRoute`: persona → account + endpoint, selected by purpose and\n descending priority.\n- `PersonaMessagingService`: persists and sends through an enabled route.\n- Provider registry: public setup descriptors + optional sender factory. Keep\n channel (`sms`) separate from provider (`twilio`).\n- Permissions: `messages.send`, `messages.manage-routes`,\n `messages.manage-credentials`.\n- `MessagingSettingsService` is the permissioned server boundary;\n its host-supplied `resolvePersonaTenantId` proves cross-package ownership.\n `MessagingSettingsPanel` is the callback-driven Svelte surface.\n- Account, endpoint, and route generated surfaces are read-only. Do not add\n generated mutations around the settings service or make secret fields writable.\n- **Recipe `messages.slack`** (`src/recipes.ts`, help in `src/help/slack.md`): lists Slack messages and workspaces beside the Mailbox and Notifications recipes; workspaces stay read-only and sending goes through the senders, not generated routes. Fields it shows carry `@field({ description })` in plain words; keep them when editing the models.\n\n## Per-account mail access (owner + grants)\n\nOptional by default: `Account.ownerUserId` is nullable, and an account without\nan owner stays tenant-wide. Apps that want private or shared mailboxes set\nowners and call `configureMailAccess({ options, resolvePrincipal })` at startup\n(`access.ts`); smrt never knows the host's credential model, the host returns a\n`MailPrincipal` (`userId` + tenant, optional `scopes` / `accountIds` ceilings).\n\n- Scopes `read`, `triage`, `draft`, `send` are `ResourceGrant` rows (resource\n type `messages:account`, permission `messages.<scope>`) checked by\n `checkResourceOperationPermission`, so the grantee also needs the tenant\n `messages.<scope>` permission (the ceiling). The owner holds every scope\n implicitly. Agents are `User` rows the host maps its credential to; the\n principal ceilings are intersected with the grant, never added to it.\n- `access-enforcement.ts` is a `GlobalInterceptors` entry registered at package\n load. Emails, folders and attachments (matched by STI ancestry) are filtered\n in `beforeList`/`afterList`/`afterGet`; raw `query()` on them is refused while\n any account is closed to the principal. Fail closed: no principal, no\n resolver or a foreign tenant means owned accounts are invisible. No tenant\n admin or super-admin bypass; trusted work (sync, outbox) uses\n `runWithMailSystemAccess()`. `EmailAccount.syncFrom()` does so itself.\n- Attachments carry a denormalized `accountId` (always derived from the message in a\n `beforeSave` interceptor, never caller-supplied) so lists, projections and counts filter in SQL; run\n `AttachmentCollection.backfillAccountIds()` once after upgrading (legacy rows\n without it are hidden from every read until then).\n- `connectMailbox` refuses by default: give the service `allowedMailHosts`\n (and optionally `allowedMailPorts`) or your own `validateMailbox`. The\n built-in validator never connects to private, loopback or link-local\n addresses and returns only a generic error. It checks every target field\n present (`host`, `endpoint`, and the `jmap` provider's `url`): https only, no\n userinfo, listed host and port. The `jmap` provider stays `available: false`\n on purpose (`available` means outbound transport; JMAP is receive and sync\n only), and `connectMailbox` still connects it. Policy lookups use the\n configured db handle, not a caller's transaction.\n- `Message.send()` needs the `send` scope on an owned account. Account rows are\n not filtered (senders, routes and the outbox read them without a principal).\n- `MailAccessService` (`grant`, `revoke`, `list`, `setOwner`) needs tenant\n `messages.manage-access` AND ownership (or delegation); an administrator\n cannot read, self-grant or take over an owned mailbox. Unowned accounts can be\n claimed once with `messages.manage-credentials`.\n- `MessagingSettingsService.listAccounts({ limit, cursor })` is the account\n discovery for a principal: only accounts it owns or holds an active grant on\n (never unowned or foreign accounts), with effective `scopes` and\n `relation: 'owner' | 'shared'`, via `decideMailAccess`. Fail closed with no\n principal user, a tenant mismatch or no `configureMailAccess`.\n- `seedMessagesRolePermissions({ db })` seeds the tenant `messages.*` slugs for\n the system roles (owner/admin: read, triage, draft, send, manage-credentials,\n manage-access; member: the four scopes; viewer: read). Idempotent, additive,\n system roles only; without it grants and `manage-access` fail closed on a\n fresh app. The matrix is `MESSAGES_ROLE_PERMISSION_MATRIX`.\n- Before `configureMailAccess` is called the policy still fails closed on\n owned accounts: every collection operation on a mail class (the core `onCollectionReady`\n interceptor hook, so STI subclasses on a default collection are covered) registers its\n database, per database, and the policy hides every owned account's mail\n through list, count, projections, facets and raw queries; it learns the database from the first mail or account row it\n sees and, with no principal resolver, hides every owned account's mail.\n Direct hydration (`new Email({ id }).initialize()`, `loadRelated()`) is gated\n in the models' `loadFromId`/`loadFromSlug`.\n- `connectionStatus` (`connected` / `needs_reconnect`) and `statusMessage` mark\n an account whose sign-in the server refused; `syncFrom()` sets it.\n\n## Mail search and private correspondents (#5132)\n\n`MailSearchService` searches only `read`-scoped accounts from `listAccounts()`;\n`CorrespondentService` derives owner-private contacts (optional `Profile` link).\nBoth fail closed. Details: [agents/mail-search.md](agents/mail-search.md).\n\n## Mailbox connect (provider-neutral)\n\nCredentials reach smrt-secrets in two ways; neither writes the plaintext `settings` fallback.\n\n- **Write-only app password**: `MessagingSettingsService.connectMailbox()`\n (permission `messages.manage-credentials`). The candidate credential is\n validated by opening a session first (`validateMailbox` option, default the\n provider's email client); a refusal leaves no account and no secret, and the\n error text has the secret redacted. The connecting user becomes the owner;\n `label` and the per-account endpoint (`configuration`) are stored; reconnect\n replaces the secret and is owner-only. `setAccountActive()` pauses/resumes\n (`isActive`), `removeAccount()` deletes the secret, the synced mail and the\n account. IMAP/POP3 are admitted here (receive-only), not by `saveAccount`.\n- **Generic OAuth 2.0 / OIDC**: `@happyvertical/smrt-messages/connect`\n (`startMailOAuthConnect`, `completeMailOAuthConnect`, `MailOAuthProvider`)\n on the shared kernel `@happyvertical/smrt-secrets/connect` (single-use\n tenant- and user-bound `ConnectState`, PKCE, safe return path, OIDC\n discovery with issuer check). The signed-in user becomes the owner; an\n account owned by someone else or by no one is never taken over. No role\n checks in the flow: authorize before calling.\n- **Reconnect**: `syncFrom()` marks an auth failure `connectionStatus =\n 'needs_reconnect'` (`Account.markNeedsReconnect/markConnected`) instead of\n failing silently.\n- The Google provider is a later step (sdk#1405), not part of this flow.\n\n## In-app notifications (`UserNotification`)\n\nThe in-app channel: one stored row per person, with read state.\n`user_notifications`: `tenantId` (required), `recipientUserId`\n(`@crossPackageRef` smrt-users:User, uuid), `kind`, `title`, `body`, `href`,\n`severity` (info/success/warning/error), `sourceRef`, `occurredAt`, `readAt`,\n`dismissedAt`. Conflict identity `(tenant_id, recipient_user_id, source_ref)`.\n\n- `UserNotificationService` is the only access path: `notify()` /\n `notifyMany()` (dedupe on `sourceRef`, existing row returned untouched;\n a unique ref is generated when omitted), `listForUser()` / `countUnread()`\n across explicit `tenantIds` (each read under `withTenant`), `markRead()`,\n `dismiss()` (also marks read), `markAllRead()`. Every write filters on the\n recipient, so another user's id matches nothing.\n- Generated REST/MCP/CLI are off (`api`/`mcp`/`cli: false`): a tenant-scoped\n list would expose every member's rows. Hosts expose their own routes that\n pass the signed-in user's id, never a request-chosen one.\n- Hosts decide who is told (e.g. `SocialPost.createdByUserId` for a failed\n post). New table: consumers run `db:migrate`.\n\n## Notification email outbox (`NotificationDelivery`)\n\n`NotificationOutboxService` is the external-channel counterpart of\n`UserNotificationService`: `enqueueEmail()` stores one delivery per\n`(tenant, recipient, channel, sourceRef)` after the host resolves the\nrecipient address and same-tenant sender account (callers never choose an\naddress); `dispatchDue()` leases due rows by compare-and-set\n(`NotificationDelivery.transition()`), creates the single outbound `Email`\nunder the lease, and settles sent/retry/failed/uncertain. Never resend an\n`uncertain` row automatically. Contract, retry, and reconciliation policy:\n[agents/notification-outbox.md](agents/notification-outbox.md). New table:\nconsumers run `db:migrate`.\n\n`NotificationOptOut` (`notification_opt_outs`, tenant-required, generated\nsurfaces off) is the per-recipient opt-out ledger for the outbox's\n`isSuppressed` hook, keyed `(tenant, recipient, channel, scope)` with scope `*`\nor `project:<uuid>`-style keys. `NotificationOptOutService`: idempotent\n`optOut`/`optIn` (with a `principal` only `userId === recipientUserId` may\nchange a row, and only in the principal's own `tenantId`, else\n`NotificationOptOutDeniedError`; no principal = trusted host code), trusted `isOptedOut` (a `*` row matches every scope), `listForRecipient`\n(principal required). `optOutSuppression(service, scopeOf)` builds the\n`isSuppressed` function. Details in the outbox doc; consumers run `db:migrate`.\n\n## Credential Security\n\nAccount credentials stored via tenant-bound `credentialSecretId` →\nsmrt-secrets. Use `setCredentials()`/`getCredentials()` — never store passwords\ndirectly. Credential descriptor schemas contain field definitions, never values.\n\n## Send Lifecycle\n\n`message.send()`: resolves account → creates provider sender → updates sendStatus. Retry support with `maxRetries` budget.\nA failure the provider may still have accepted carries\n`MessageSendResult.outcomeUnknown` (set by `EmailSender` unless\n`isDefiniteSendRejection()` proves a refusal, and when a sender throws) and is\npersisted as `metadata.sendOutcomeUnknown`; never auto-resend it.\n`EmailSender` attaches the message's stored `Attachment` rows (read through\n`Attachment.readContent()`, under the message's tenant context) plus\n`SendEmailOptions.attachments` bytes; an unreadable or file-less row fails the\nsend with the error on `sendError`, never a silent drop (#3808).\n`PersonaMessagingService.send({ attachments })` accepts them on email routes only.\n\n## Provider entry points (bundle boundary, #1979)\n\nThe package root is provider-neutral: models, collections, services,\npermissions, and the provider registry carry **zero provider-SDK weight**.\nProvider SDK wrappers (`@happyvertical/email`, `@happyvertical/messages`) are\nreachable only through explicit entry points, imported once at server startup:\n\n```ts\nimport '@happyvertical/smrt-messages/providers/email'; // smtp/imap/pop3/gmail\nimport '@happyvertical/smrt-messages/providers/slack';\nimport '@happyvertical/smrt-messages/providers/twitter';\nimport '@happyvertical/smrt-messages/providers/all'; // all of the above\n```\n\n- Without the matching entry, `EmailAccount.createClient()` (send + mailbox\n sync) throws an actionable error and `SlackSender`/`TweetSender` return a\n failure result naming the entry to import. Telegram and Zulip are\n fetch-based and always work from the root.\n- Builtin registry definitions stay metadata-only (setup fields for UIs); the\n entries upgrade them with `createEmailClient`/`createMessageClient`/\n `createSender` hooks. Never import a provider SDK from any module reachable\n from `src/index.ts` — the consumer bundle gate (`packages/bundle-gate`)\n fails CI when one becomes reachable.\n- `Attachment.readContent()` loads `@happyvertical/files` through core's\n `importOptionalDependency` boundary and keeps its null-on-failure contract\n in builds where the SDK is absent.\n\n## Gotchas\n\n- **Manifest before decorators**: every decorated model imports\n `../__smrt-register__.js`, and `package.json#sideEffects` lists\n `./src/__smrt-register__.ts`. Without both, the library build dropped or\n reordered the self-registration, so dist classes registered with only their\n decorated fields and could adopt smrt-ledgers' same-named `Account` (#3098).\n- **`Account` is not unique**: smrt-ledgers also declares `Account` (on\n `ledger_accounts`). Resolve by constructor or qualified name; the\n coexistence tests (`ledger-account-identity-*`, and the PostgreSQL lane\n `pnpm test:postgres`) load both packages in both orders.\n Both declare the `accounts` collection, so registering the ledgers `Account`\n auto-loads this family from its manifest as STI siblings. Core loads this\n base with them and never takes the ledgers `Account` for it (#4735,\n `ledger-account-identity-sti-siblings.test.ts`).\n- **STI `_meta_type`**: qualified format `@happyvertical/smrt-messages:Email`\n- **JSON fields**: all address/metadata fields are JSON strings with `getX()`/`setX()` helpers\n- **RFC 822 threading**: Email uses `inReplyTo`/`messageId`/`references` — manual management required\n- **Attachment.messageId**: use this field (not `emailId`); old getter/setter mapped via deprecation wrapper\n- **Optional tenancy**: `@TenantScoped({ mode: 'optional' })` on Message, Account, Attachment\n- **Required tenancy**: endpoints and persona routes are always tenant scoped\n- **Secrets are write-only**: never serialize credentials or endpoint.address to an app\n\n## Intake byte snapshots\n\n`EmailAccount.readIntakeMessage(providerLookup, maxBytes, imapIdentity?)` is the authorized host seam for\nopt-in ingestion. It copies full-message attachment bytes from the registered\nemail provider and fails when only attachment metadata is available; it never\nreads provider-supplied paths or advances sync checkpoints. Keep this path\nprovider-neutral and exclude arbitrary headers/credentials from its snapshot.\nIMAP lookup must include folder/UIDVALIDITY/UID verification; sender Message-ID\nis a lookup hint, never the durable delivery identity.\n\nProtected notification Emails carry durable delivery provenance. Their canonical\n`send`/`retrySend`, ordinary save/delete, and default EmailSender handoff are\nconstrained by `protected-notification-handoff.ts` (package-private, never a root\nexport). Only the outbox enters its exact one-use scope after current trusted\npolicy/byte validation. Preserve old-row/constructor identity checks, current\npersisted lease checks at the actual provider boundary, copied byte buffers and\nunknown-outcome marker protection. See the outbox contract and shared protected\nhandoff suite (SQLite and migrated PostgreSQL).\n\n## Protected external contacts\n\nProfile email uses exclusive `recipientProfileId` plus `resolveProfileRecipient`, a reserved `profileNotificationPolicy` and exact current tenant-owned public Profile email. No User account is required. Before activating profiles, run normal framework schema migration and public `planNotificationProfileRecipients` / `migrateNotificationProfileRecipients`; runtime verifies physical constraints and never applies DDL. Legacy User notification and opt-out paths remain User-only. See [profile recipient contract and matrix](agents/profile-recipients.md).\n\n## Incremental mail sync (change feed)\n\n`EmailAccount.syncChanges({ limit?, maxBatches?, since? })` (`mail-sync.ts`) drives\n`EmailClient.getChanges()` (JMAP provider `jmap`; `@happyvertical/email` 0.114+).\n`syncFrom()` stays the polling path for IMAP/POP3.\n\n- `EmailAccount.syncCursor` is the opaque feed cursor (sensitive + readonly, never\n on generated surfaces). It is saved only after its batch is applied; a failure\n anywhere leaves it where it was, so the job just retries.\n- Rows are keyed on `Email.providerMessageId` (the server's own id, per account),\n so applying a batch twice changes nothing. Added/changed messages upsert,\n `removed` deletes, `folders` upserts `EmailFolder` by path and counts are\n recomputed for touched folders. Metadata-only changes keep stored bodies.\n- `resync-required` clears the cursor and runs a full pass in the same run; a\n full pass from no cursor deletes stored messages (with a `providerMessageId`)\n the server no longer has. A second resync request in one run throws.\n- One lane per account: runs queue behind each other in-process, work on the\n stored (revision-guarded) row, and the job is deduplicated per tenant+account.\n Inactive and `needs_reconnect` accounts, and clients without `getChanges`,\n return `{ status: 'skipped' }`. Auth failures call `markNeedsReconnect()` and\n throw with `retryable: false`. The sync runs under `runWithMailSystemAccess()`.\n- Job: `enqueueMailSync(account)` / `enqueueDueMailSyncs(accounts)`\n (`mail-sync-jobs.ts`, queue `mail-sync`, dedupe key `mail-sync:<accountId>`)\n target `EmailAccount.syncChanges` through `@happyvertical/smrt-jobs` (optional\n peer). The host runs the `TaskRunner` and schedules `enqueueDueMailSyncs`.\n- Backfill horizon (#5200): optional `EmailAccount.backfillSince` (null = whole\n mailbox, the default) or per-run `since` (`Date`/ISO string, `null` lifts the\n stored one; `enqueueMailSync({ since })` forwards it as an ISO string). A\n message dated before it is not stored unless it already is; undated mail is\n kept; `MailSyncResult.beforeHorizon` counts the skips. The SDK change feed\n cannot filter by date, so the server still sends the older mail and it is\n dropped here (saves rows, not transfer; a server-side horizon needs an SDK change).\n- Horizon vs cursor: `cursorHorizon` records the horizon the saved cursor was\n built under (null = unbounded, also legacy cursors). If a run's effective\n horizon is earlier than it, or cleared (`since: null`), the cursor is dropped\n and the run does a full pass with prune; narrowing or an unchanged horizon\n keeps the cursor.\n- Persisted health (#5200): `lastSyncError` is set on any failed run (also\n client-build failures and sign-in refusals, which additionally set\n `needs_reconnect`) and cleared by the next successful run; a transient failure\n never changes `connectionStatus`. `backlog` mirrors `MailSyncResult.hasMore`\n of the last successful run. Both are plain optional columns (additive).\n- Known gaps: attachment rows are not created (only `hasAttachments`/`size`);\n a renamed server folder creates a new folder row (stored messages keep the old\n path until they change); `jmap` has no connect-flow validator yet and is not an\n outbound transport.\n\n## Triage write-back\n\n`EmailAccount.triage(action, emailIds)` (and `Email.triage(action)`,\n`mail-triage.ts`) writes mark read/unread, star/unstar, archive, spam/not spam,\nlabel add/remove and move to the server, then updates the local row. Actions are\n`{ kind: 'markRead' | 'markUnread' | 'star' | 'unstar' | 'archive' | 'markSpam' |\n'unmarkSpam' }`, `{ kind: 'addLabels' | 'removeLabels', labels }` and\n`{ kind: 'move', folder }`; ids are local `Email` row ids.\n\n- Access: needs `read` **and** `triage` on the account (`assertMailAccess`, fail\n closed; `MailAccessError`) before any server call or local write.\n- Server first, per message: the result is `{ updated, failed, stale }`. Only ids\n the server accepted are written; refusals (and ids that are missing, on another\n account, or not yet synced) come back in `failed`. A thrown client error\n changes nothing. Auth failures mark the account `needs_reconnect`.\n- Convergence: an accepted message is read back (`getMessage`) and stored through\n `applyServerMessage`, exactly as sync stores it, so the next sync is a no-op.\n If the read-back fails the id is `stale` and sync fixes the row. Triage runs in\n the account's sync lane (`inLane`), so it never interleaves with a sync here.\n- Providers whose `getCapabilities().writeBack` lacks the needed key (`flags`,\n `labels`, `archive`, `spam`) throw `MailWriteBackUnsupportedError` first.\n- `move` removes a message from the mailboxes it is in now (from its stored\n labels) and adds `folder`; pass a path as stored on `EmailFolder`.\n- Every public method on an `@smrt()` class becomes a `<collection>.<method>`\n permission; `Email.triage` is why `messages.triage` in `permissions.ts` carries\n the generated name and description (the catalog rejects two for one slug).\n- Known gaps: drafts and send, the acting principal is not recorded (#5141), and\n a mailbox the server has not reported yet has no `EmailFolder` row until sync.\n",
13861
14031
  "moduleDocs": [
14032
+ {
14033
+ "path": "agents/mail-search.md",
14034
+ "module": "mail-search",
14035
+ "content": "# Mail search and private correspondents (#5132)\n\n- `MailSearchService({ db, tenantId, principal })` searches only accounts from\n `listAccounts()` with the `read` scope (owner, grant, tenant ceiling, host\n scope/account ceilings; fail closed). `accountIds` only narrows. Local reads\n are bound to those ids in SQL (`accountId in`), then run under\n `runWithMailSystemAccess` because the decision was made here with the explicit\n principal. Unowned accounts are not listed, so they are not searched.\n- `search()`: keyword filters (text, from, to, subject, label, date, flags,\n attachment) are matched case-insensitively in memory over a bounded\n newest-first scan (5000 rows per call; `truncated`/`nextCursor` say more\n exist). SQL `like` is not used for user text (no escaping, case differs\n between SQLite and PostgreSQL). `mode: 'semantic'` ranks with\n `EmailCollection.semanticMatches()` (core `semanticSearchIds`, `where` applied\n before ranking); `Email` embeddings are opt-in (`autoGenerate: false`, hosts\n generate them) and an empty or unavailable ranking falls back to keyword.\n- `searchProvider()` asks each readable account's server through the SDK\n `search()` (needs `@happyvertical/smrt-messages/providers/email`) and falls\n back to the local index per account (`fallbackAccounts` says why; the reason\n is a fixed string, never provider text). Label and flag filters the SDK\n criteria cannot express are applied to provider hits before the page is cut. Synced\n provider hits carry `emailId`.\n- `Correspondent` (`correspondents`, tenant-required, generated surfaces off) is\n owner-private: unique `(tenant, owner_user_id, address)`, only `address` is\n required. `CorrespondentService.refresh()` recomputes counts, latest name and\n first/last contact from the mail the owner can read (the owner's own account\n addresses are skipped); it never creates or links a `Profile`.\n Each row keeps a per-account breakdown (`accountBreakdown`); `list`/`suggest`/\n `get` build counts, dates, name and `accountIds` from the accounts the viewer\n can read now, and hide a row with none, so revoking access removes that\n account's contribution before the next refresh. `refresh()` changes nothing\n when no account is readable and only replaces the scanned accounts' entries,\n so it never erases data it could not see. Delegated principals (host scope or\n account ceiling, or principal id != user id) get nothing and cannot refresh,\n link or unlink unless the host passes `allowDelegated: true` (the owner's\n consent).\n `linkProfile`/`unlinkProfile` are the owner's explicit choice (profile must\n exist in the tenant). `RecipientInput` takes a host `suggest` callback\n (typically `CorrespondentService.suggest()` for the signed-in user).\n New table: consumers run `db:migrate`.\n"
14036
+ },
13862
14037
  {
13863
14038
  "path": "agents/notification-outbox.md",
13864
14039
  "module": "notification-outbox",