@happyvertical/smrt-messages 0.70.3 → 0.71.0

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 (50) hide show
  1. package/AGENTS.md +9 -3
  2. package/README.md +4 -2
  3. package/agents/attachment-storage.md +41 -0
  4. package/dist/attachment-storage.d.ts +50 -0
  5. package/dist/attachment-storage.d.ts.map +1 -0
  6. package/dist/chunks/{AttachmentCollection-Di2aRb2k.js → AttachmentCollection-C14dERNK.js} +31 -37
  7. package/dist/chunks/AttachmentCollection-C14dERNK.js.map +1 -0
  8. package/dist/chunks/{Email-tEYH6ZRw.js → Email-Bd1lCLiC.js} +6 -6
  9. package/dist/chunks/{Email-tEYH6ZRw.js.map → Email-Bd1lCLiC.js.map} +1 -1
  10. package/dist/chunks/{EmailAccountCollection-DWo_a-X5.js → EmailAccountCollection-Clv4kruh.js} +108 -37
  11. package/dist/chunks/EmailAccountCollection-Clv4kruh.js.map +1 -0
  12. package/dist/chunks/{EmailCollection-_Z2JY26I.js → EmailCollection-CiZJ5I2l.js} +3 -3
  13. package/dist/chunks/{EmailCollection-_Z2JY26I.js.map → EmailCollection-CiZJ5I2l.js.map} +1 -1
  14. package/dist/chunks/{EmailFolder-TyoFZVcC.js → EmailFolder-Dvb6M-d_.js} +6 -6
  15. package/dist/chunks/{EmailFolder-TyoFZVcC.js.map → EmailFolder-Dvb6M-d_.js.map} +1 -1
  16. package/dist/chunks/{EmailFolderCollection-CFtttkx6.js → EmailFolderCollection-BR3yh7sp.js} +2 -2
  17. package/dist/chunks/{EmailFolderCollection-CFtttkx6.js.map → EmailFolderCollection-BR3yh7sp.js.map} +1 -1
  18. package/dist/chunks/{EmailSender-bHwAYzBO.js → EmailSender-B-c7mxbY.js} +10 -4
  19. package/dist/chunks/EmailSender-B-c7mxbY.js.map +1 -0
  20. package/dist/chunks/{Message-DC877Gl7.js → Message-CGyhd0kh.js} +6 -6
  21. package/dist/chunks/{Message-DC877Gl7.js.map → Message-CGyhd0kh.js.map} +1 -1
  22. package/dist/chunks/{MessageCollection-yZ6RyAtB.js → MessageCollection-DRCtm5z2.js} +2 -2
  23. package/dist/chunks/{MessageCollection-yZ6RyAtB.js.map → MessageCollection-DRCtm5z2.js.map} +1 -1
  24. package/dist/chunks/{MessagingEndpointCollection-CNwpv_ZW.js → MessagingEndpointCollection-Cju_NnJZ.js} +2 -2
  25. package/dist/chunks/{MessagingEndpointCollection-CNwpv_ZW.js.map → MessagingEndpointCollection-Cju_NnJZ.js.map} +1 -1
  26. package/dist/collections/AttachmentCollection.d.ts.map +1 -1
  27. package/dist/connect.js +1 -1
  28. package/dist/host.browser.d.ts +2 -0
  29. package/dist/host.browser.d.ts.map +1 -1
  30. package/dist/host.browser.js +3 -1
  31. package/dist/host.browser.js.map +1 -1
  32. package/dist/host.d.ts +20 -0
  33. package/dist/host.d.ts.map +1 -1
  34. package/dist/host.js +39 -1
  35. package/dist/host.js.map +1 -1
  36. package/dist/index.d.ts +1 -0
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +17 -17
  39. package/dist/index.js.map +1 -1
  40. package/dist/manifest.json +1 -1
  41. package/dist/models/Attachment.d.ts +13 -8
  42. package/dist/models/Attachment.d.ts.map +1 -1
  43. package/dist/send-approval.d.ts.map +1 -1
  44. package/dist/senders/EmailSender.d.ts.map +1 -1
  45. package/dist/smrt-knowledge.json +11 -5
  46. package/dist/smrt-knowledge.okf.md +9 -5
  47. package/package.json +12 -12
  48. package/dist/chunks/AttachmentCollection-Di2aRb2k.js.map +0 -1
  49. package/dist/chunks/EmailAccountCollection-DWo_a-X5.js.map +0 -1
  50. package/dist/chunks/EmailSender-bHwAYzBO.js.map +0 -1
@@ -2,7 +2,7 @@
2
2
  "version": "1.0.0",
3
3
  "timestamp": 0,
4
4
  "packageName": "@happyvertical/smrt-messages",
5
- "packageVersion": "0.70.3",
5
+ "packageVersion": "0.71.0",
6
6
  "objects": {
7
7
  "@happyvertical/smrt-messages:AccountCollection": {
8
8
  "name": "accountcollection",
@@ -43,6 +43,11 @@ export declare class Attachment extends SmrtObject {
43
43
  delete(options?: {
44
44
  expectedUpdatedAt?: Date | string;
45
45
  }): Promise<void>;
46
+ /**
47
+ * The account of the message this row is stored on now, read from the
48
+ * stored message (never from the row's own `accountId`), or null.
49
+ */
50
+ private currentAccountId;
46
51
  /**
47
52
  * Trusted system work and non-draft parents pass. Unlike the message check
48
53
  * this runs before the write, not inside its transaction: the attachment
@@ -80,15 +85,15 @@ export declare class Attachment extends SmrtObject {
80
85
  */
81
86
  hasExternalFile(): boolean;
82
87
  /**
83
- * Read file content (if stored externally)
84
- *
85
- * The files SDK is loaded through core's bundler-invisible optional-import
86
- * boundary so it never enters provider-neutral consumer bundles (#1979).
87
- * Absence of the SDK at runtime degrades to the existing null contract.
88
+ * Read the stored file's bytes, or null when the row has no file or the
89
+ * file is missing or unreadable.
88
90
  *
89
- * The local provider joins every path onto its base path (the process cwd
90
- * by default), so an absolute `filePath` is rooted at its own directory, and
91
- * the bytes are read raw: decoding a PDF as UTF-8 corrupts it (#3808).
91
+ * `filePath` is relative to the root set with `configureAttachmentStorage`
92
+ * and must lie under `<accountId>/` of the message's current account.
93
+ * Throws `AttachmentStorageError` when no root is configured, or when the
94
+ * stored path (or a symlink under it) leaves the root or the account's
95
+ * directory; this includes rows stored before the root existed. The bytes are read
96
+ * raw: decoding a PDF as UTF-8 corrupts it (#3808).
92
97
  */
93
98
  readContent(): Promise<Buffer | null>;
94
99
  }
@@ -1 +1 @@
1
- {"version":3,"file":"Attachment.d.ts","sourceRoot":"","sources":["../../src/models/Attachment.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,yBAAyB,CAAC;AACjC,OAAO,EAIL,UAAU,EACV,KAAK,eAAe,EAErB,MAAM,0BAA0B,CAAC;AASlC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAU,CAAC;AAqBlD,qBAMa,UAAW,SAAQ,UAAU;IAExC,QAAQ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,CAAC,MAAM,CAAc;IAC5B,OAAO,CAAC,OAAO,CAAe;gBAElB,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,YAAY;IAKtD,OAAO,IAAI,OAAO;IAIZ,IAAI,CACR,OAAO,EAAE,KAAK,EACd,OAAO,CAAC,EAAE,gBAAgB,GACzB,OAAO,CAAC,iBAAiB,CAAC;IAyE7B;;;;;;;;OAQG;YACW,kBAAkB;CA0EjC;AAkBD;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAmB/D"}
1
+ {"version":3,"file":"EmailSender.d.ts","sourceRoot":"","sources":["../../src/senders/EmailSender.ts"],"names":[],"mappings":"AAKA;;GAEG;AAEH,OAAO,KAAK,EAAc,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAEpE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAiB,CAAC;AAC7C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAAwB,CAAC;AAE3D,OAAO,KAAK,EACV,sBAAsB,EACtB,iBAAiB,EACjB,gBAAgB,EACjB,MAAM,aAAU,CAAC;AAElB,qBAAa,WAAY,YAAW,sBAAsB;IACxD,QAAQ,CAAC,YAAY,WAAW;IAChC,OAAO,CAAC,MAAM,CAAc;IAC5B,OAAO,CAAC,OAAO,CAAe;gBAElB,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,YAAY;IAKtD,OAAO,IAAI,OAAO;IAIZ,IAAI,CACR,OAAO,EAAE,KAAK,EACd,OAAO,CAAC,EAAE,gBAAgB,GACzB,OAAO,CAAC,iBAAiB,CAAC;IAyE7B;;;;;;;;OAQG;YACW,kBAAkB;CAmFjC;AAkBD;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAmB/D"}
@@ -3,15 +3,16 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-messages",
6
- "packageVersion": "0.70.3",
6
+ "packageVersion": "0.71.0",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "a751e45dc7e1de93f144dd2bfbc319cbf97402b8380bd8ced5c8f9b13cd50447",
11
- "packageJson": "fc9de03a0900ef0c99e79c824591413186940b93686465c0a4917bff63361f92",
12
- "agents": "ace12c9bfe2b42588489292b7967e597d9bed8dc6784f61fce7f41ea80b047e7",
10
+ "manifest": "9c4741fb8952e9e8d449a5da7cd578f00392b6eeab352363e6be122a3810abab",
11
+ "packageJson": "ab02f774b606ff67a0d193a8f4d8055aa30726121a5ad54b7515c11d471ef15b",
12
+ "agents": "ac521a736bd1c90433670e4131563b397adb5eb8e5d6aa322b05dc74b82ca724",
13
13
  "moduleDoc:agents/send-approval.md": "a54a3daaf091c9c77e9a1fc6c3dbf04d15403d915ab08833c2ebf57ee1b74ec3",
14
14
  "moduleDoc:agents/mail-search.md": "9dac1619a1486f2fa94980e141ebc5003851c27cd77ced6d5ff64d348429fdb1",
15
+ "moduleDoc:agents/attachment-storage.md": "f08dc3087f883ce0a8ba5eeb08a53ee9f51da8bf705160daa35f15d7b1b32821",
15
16
  "moduleDoc:agents/notification-outbox.md": "0e9a870c4b2d5f0fec47af0dff6e61d216fb0121d384d99bccfc506beb6e38ad",
16
17
  "moduleDoc:agents/profile-recipients.md": "1b6710bf646ddeafd6836df8270fcbb8e29226dceda716a693d945cc2e914606"
17
18
  },
@@ -14280,7 +14281,7 @@
14280
14281
  "polymorphicAssociations": 0,
14281
14282
  "uuidColumns": 138
14282
14283
  },
14283
- "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- Draft writes (and their attachments) need the `draft` scope on an owned\n account, checked in `Message.save()`/`delete()` and\n `Attachment.save()`/`delete()`; rules and bypasses:\n [agents/send-approval.md](agents/send-approval.md#draft-writes).\n- `Message.send()` needs the `send` scope on an owned account. Agent sends\n (principal `kind` other than `person`/`human`) on a mail account are held\n for a person's approval unless the owner opted in to `auto_send`;\n approve / edit-then-approve / reject / release (as an approving person,\n never the agent) through `MailSendApprovalService`,\n drafts through `MailDraftService`, \"handled by\" on every message. Gate,\n binding and bypass rules: [agents/send-approval.md](agents/send-approval.md). 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",
14284
+ "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- Draft writes (and their attachments) need the `draft` scope on an owned\n account, checked in `Message.save()`/`delete()` and\n `Attachment.save()`/`delete()`; rules and bypasses:\n [agents/send-approval.md](agents/send-approval.md#draft-writes).\n- `Message.send()` needs the `send` scope on an owned account. Agent sends\n (principal `kind` other than `person`/`human`) on a mail account are held\n for a person's approval unless the owner opted in to `auto_send`;\n approve / edit-then-approve / reject / release (as an approving person,\n never the agent) through `MailSendApprovalService`,\n drafts through `MailDraftService`, \"handled by\" on every message. Gate,\n binding and bypass rules: [agents/send-approval.md](agents/send-approval.md). 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## Attachment storage root (#5645)\n\n`Attachment.filePath` is `<accountId>/...` relative to the root set once at startup with\n`configureAttachmentStorage({ root })` (beside `configureMailAccess`). Without\nit stored files are never read (fail closed). Rules, send behaviour and the\nupgrade step: [agents/attachment-storage.md](agents/attachment-storage.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()` reads with `node:fs` through `host.ts` (stubbed\n in `host.browser.ts`), not `@happyvertical/files`; see Attachment storage.\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",
14284
14285
  "moduleDocs": [
14285
14286
  {
14286
14287
  "path": "agents/send-approval.md",
@@ -14292,6 +14293,11 @@
14292
14293
  "module": "mail-search",
14293
14294
  "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"
14294
14295
  },
14296
+ {
14297
+ "path": "agents/attachment-storage.md",
14298
+ "module": "attachment-storage",
14299
+ "content": "# Attachment storage root (#5645)\n\n`Attachment.filePath` is a path relative to one root the host sets once at\nstartup with `configureAttachmentStorage({ root })` (`attachment-storage.ts`,\nbeside `configureMailAccess`; `resetAttachmentStorage()` for tests). The root\nmust be an absolute, existing directory; its real path is resolved once.\n\n- **Layout**: a file lives at `<root>/<accountId>/<path>`, and `filePath` is\n stored as `<accountId>/<path>`, where `accountId` is the account of the\n message the attachment is on. Account ids are unique across tenants, so this\n one prefix scopes both tenant and account (an attachment's own `tenantId` is\n optional, but its message always has an account).\n- **Write** (`Attachment.save()`, so also `AttachmentCollection.create` and the\n generated `create` route): refuses an absolute path, a `..` segment, a\n backslash, a control character (NUL included), `%2e`/`%2f`/`%5c` (any case,\n any `%25` nesting) and an empty result, or a path not under `<accountId>/` of the message's current\n account (read from the stored message, never the row's own `accountId`), with\n `AttachmentStorageError`\n (`status` 400); stores the normalised relative path. Needs no root.\n- **Read** (`readContent()`, the only reader): no root configured throws\n `AttachmentStorageError` naming `configureAttachmentStorage` (fail closed);\n the stored path is re-checked against the message's current account, so an\n attachment moved to another account's message loses its file (rows written earlier with an absolute or\n escaping path are refused), the target's real path is resolved, and one\n outside the account's own directory (or the root) throws. Missing or unreadable file stays `null`.\n- **Send / held send**: `EmailSender` turns a refusal into the failed send\n `Attachment \"x\" was not sent: ...` (recorded on `sendError`, nothing reaches\n the transport); `mailSendBindingHash` binds a refused row as `unreadable`.\n- **Upgrade**: a host that stored absolute paths must set the root, move each\n file to `<root>/<accountId>/...` and rewrite its row as the relative path\n `<accountId>/...`, using the account of the row's message; until then those sends fail.\n `backfillAccountIds()` writes the column directly so such rows still fill.\n\n## Trust boundary\n\nReads check the real path just before opening it, so the root must not be\nwritable by untrusted parties (hard links or a symlink swap inside the root between the check and the\nread is not defended). The per-account prefix stops one account naming another\naccount's file; it does not separate writers within one account.\nThe root's layout is the operator's: a symlinked account directory that points at\nanother account's directory inside the root is followed. Do not create one.\n"
14300
+ },
14295
14301
  {
14296
14302
  "path": "agents/notification-outbox.md",
14297
14303
  "module": "notification-outbox",
@@ -5,10 +5,10 @@ description: "Unified multi-channel messaging with STI-based hierarchies"
5
5
  status: "stable"
6
6
  generated:
7
7
  by: "smrt/scripts/generate-knowledge-okf.ts"
8
- at: "2026-11-24T09:42:36Z"
8
+ at: "2026-11-25T22:47:28Z"
9
9
  audience: "internal"
10
10
  evidence_level: "source-inspected"
11
- source_revision: "sha256:ff67afd1fdad7e4675cee768168f4c3a7dc743185ad570e724e9ce2ba6a3e266"
11
+ source_revision: "sha256:ef897e351e6b70630dbee7a0eb9599833e6a3bc29c7b1f35858a3bc24b5bce11"
12
12
  sources:
13
13
  - id: "manifest"
14
14
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/messages/package.json"
@@ -17,15 +17,18 @@ sources:
17
17
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/messages/AGENTS.md"
18
18
  title: "@happyvertical/smrt-messages packages/messages/AGENTS.md"
19
19
  - id: "agents-2"
20
+ resource: "https://github.com/happyvertical/smrt/blob/main/packages/messages/agents/attachment-storage.md"
21
+ title: "@happyvertical/smrt-messages packages/messages/agents/attachment-storage.md"
22
+ - id: "agents-3"
20
23
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/messages/agents/mail-search.md"
21
24
  title: "@happyvertical/smrt-messages packages/messages/agents/mail-search.md"
22
- - id: "agents-3"
25
+ - id: "agents-4"
23
26
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/messages/agents/notification-outbox.md"
24
27
  title: "@happyvertical/smrt-messages packages/messages/agents/notification-outbox.md"
25
- - id: "agents-4"
28
+ - id: "agents-5"
26
29
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/messages/agents/profile-recipients.md"
27
30
  title: "@happyvertical/smrt-messages packages/messages/agents/profile-recipients.md"
28
- - id: "agents-5"
31
+ - id: "agents-6"
29
32
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/messages/agents/send-approval.md"
30
33
  title: "@happyvertical/smrt-messages packages/messages/agents/send-approval.md"
31
34
  ---
@@ -42,6 +45,7 @@ sources:
42
45
  ## Documentation
43
46
 
44
47
  - `packages/messages/AGENTS.md`
48
+ - `packages/messages/agents/attachment-storage.md`
45
49
  - `packages/messages/agents/mail-search.md`
46
50
  - `packages/messages/agents/notification-outbox.md`
47
51
  - `packages/messages/agents/profile-recipients.md`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-messages",
3
- "version": "0.70.3",
3
+ "version": "0.71.0",
4
4
  "smrtJsdoc": "strict",
5
5
  "description": "Unified multi-channel messaging with STI-based hierarchies",
6
6
  "type": "module",
@@ -67,14 +67,14 @@
67
67
  "@happyvertical/files": "^0.116.6",
68
68
  "@happyvertical/logger": "^0.116.6",
69
69
  "@happyvertical/messages": "^0.116.6",
70
- "@happyvertical/smrt-core": "0.70.3",
71
- "@happyvertical/smrt-jobs": "0.70.3",
72
- "@happyvertical/smrt-profiles": "0.70.3",
73
- "@happyvertical/smrt-secrets": "0.70.3",
74
- "@happyvertical/smrt-tenancy": "0.70.3",
75
- "@happyvertical/smrt-types": "0.70.3",
76
- "@happyvertical/smrt-ui": "0.70.3",
77
- "@happyvertical/smrt-users": "0.70.3",
70
+ "@happyvertical/smrt-core": "0.71.0",
71
+ "@happyvertical/smrt-jobs": "0.71.0",
72
+ "@happyvertical/smrt-profiles": "0.71.0",
73
+ "@happyvertical/smrt-secrets": "0.71.0",
74
+ "@happyvertical/smrt-tenancy": "0.71.0",
75
+ "@happyvertical/smrt-types": "0.71.0",
76
+ "@happyvertical/smrt-ui": "0.71.0",
77
+ "@happyvertical/smrt-users": "0.71.0",
78
78
  "@happyvertical/sql": "^0.116.6",
79
79
  "@happyvertical/utils": "^0.116.6"
80
80
  },
@@ -91,9 +91,9 @@
91
91
  }
92
92
  },
93
93
  "devDependencies": {
94
- "@happyvertical/smrt-approvals": "0.70.3",
95
- "@happyvertical/smrt-ledgers": "0.70.3",
96
- "@happyvertical/smrt-vitest": "0.70.3",
94
+ "@happyvertical/smrt-approvals": "0.71.0",
95
+ "@happyvertical/smrt-ledgers": "0.71.0",
96
+ "@happyvertical/smrt-vitest": "0.71.0",
97
97
  "@sveltejs/package": "^2.5.8",
98
98
  "@sveltejs/vite-plugin-svelte": "^7.3.0",
99
99
  "@types/node": "24.13.6",
@@ -1 +0,0 @@
1
- {"version":3,"file":"AttachmentCollection-Di2aRb2k.js","names":[],"sources":["../../src/models/Attachment.ts","../../src/collections/AttachmentCollection.ts"],"sourcesContent":["/**\n * Attachment model - Generalized attachment for any message type\n *\n * Uses messageId instead of emailId for cross-type support.\n */\n\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport {\n foreignKey,\n importOptionalDependency,\n ObjectRegistry,\n SmrtObject,\n type SmrtSaveOptions,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy/decorators';\nimport {\n assertHydratedMailAccess,\n assertMailDraftWrite,\n inMailSystemAccess,\n isUnsentDraft,\n learnMailAccessOptions,\n} from '../access.js';\nimport type { AttachmentOptions } from '../types';\n\n/**\n * Split an absolute path into its directory and file name, or return null for\n * a relative path. Plain string handling rather than `node:path`: the package\n * root must stay browser-reachable (the bundle-gate forbids `node:*` there).\n */\nfunction splitAbsolutePath(\n filePath: string,\n): { dir: string; base: string } | null {\n // A backslash separates segments only in a Windows path; in a POSIX path it\n // is an ordinary filename character.\n const windows = /^[A-Za-z]:[\\\\/]/.test(filePath);\n if (!windows && !filePath.startsWith('/')) return null;\n const cut = windows\n ? Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\\\'))\n : filePath.lastIndexOf('/');\n const dir = filePath.slice(0, cut) || filePath.slice(0, cut + 1);\n return { dir, base: filePath.slice(cut + 1) };\n}\n\n@TenantScoped({ mode: 'optional' })\n@smrt({\n api: { include: ['list', 'get', 'create', 'delete'] },\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n})\nexport class Attachment extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @tenantId({ nullable: true })\n tenantId: string | null = null;\n\n @foreignKey('Message')\n messageId = '';\n /**\n * The mail account this file belongs to. Copied from its message when the\n * attachment is saved, so per-account mail access can filter attachment\n * reads (lists, projections, counts) without a join. Null for rows saved\n * before the column existed: run `AttachmentCollection.backfillAccountIds()`.\n */\n @foreignKey('Account')\n accountId: string | null = null;\n filename = '';\n contentType = '';\n size = 0;\n contentId = ''; // For inline images (<img src=\"cid:...\">)\n contentDisposition: 'attachment' | 'inline' = 'attachment';\n filePath = ''; // External file storage path\n sourceUrl = ''; // For non-email attachments (media URLs, etc.)\n\n // Timestamps\n createdAt = new Date();\n\n constructor(options: AttachmentOptions = {}) {\n super(options);\n\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.messageId !== undefined) this.messageId = options.messageId;\n if (options.accountId !== undefined)\n this.accountId = options.accountId || null;\n if (options.filename !== undefined) this.filename = options.filename;\n if (options.contentType !== undefined)\n this.contentType = options.contentType;\n if (options.size !== undefined) this.size = options.size;\n if (options.contentId !== undefined) this.contentId = options.contentId;\n if (options.contentDisposition !== undefined)\n this.contentDisposition = options.contentDisposition;\n if (options.filePath !== undefined) this.filePath = options.filePath;\n if (options.sourceUrl !== undefined) this.sourceUrl = options.sourceUrl;\n if (options.createdAt) this.createdAt = options.createdAt;\n }\n\n /**\n * Direct hydration (`new X({ id }).initialize()`, `loadRelated()`) bypasses\n * the collection read hooks, so the per-account mail policy is applied here\n * too: a row of an account closed to the principal never hydrates.\n */\n override async loadFromId() {\n await super.loadFromId();\n await assertHydratedMailAccess(this);\n }\n\n override async loadFromSlug() {\n await super.loadFromSlug();\n await assertHydratedMailAccess(this);\n }\n\n /**\n * An attachment is part of what its message will send, so writing one on an\n * unsent email draft of an owned account needs the same `draft` scope as\n * writing the draft (see `Message.save()`), whichever route the write takes.\n * Both the parent it is saved onto and the parent it is stored on count, so\n * an attachment cannot be moved on or off a draft without the scope.\n */\n override async save(options?: SmrtSaveOptions): Promise<this> {\n await this.assertDraftParentWrite();\n return super.save(options);\n }\n\n override async delete(\n options: { expectedUpdatedAt?: Date | string } = {},\n ): Promise<void> {\n await this.assertDraftParentWrite();\n return super.delete(options);\n }\n\n /**\n * Trusted system work and non-draft parents pass. Unlike the message check\n * this runs before the write, not inside its transaction: the attachment\n * save interceptor builds collections from the instance's options, and\n * inside a transaction those would register the transaction's handle as a\n * policy database.\n */\n private async assertDraftParentWrite(): Promise<void> {\n learnMailAccessOptions(this.options);\n if (inMailSystemAccess()) return;\n const parentIds = new Set<string>();\n if (this.messageId) parentIds.add(this.messageId);\n if (this.id) {\n const stored = await this.getCanonicalPersistedRow({ id: this.id });\n if (typeof stored?.message_id === 'string' && stored.message_id) {\n parentIds.add(stored.message_id);\n }\n }\n // A new attachment is written over the stored row that carries its slug\n // (its own, or the one the save derives from its id): that row's parent is\n // the one it changes.\n const slug = this.isPersisted ? '' : this.slug || (await this.getSlug());\n if (slug) {\n const columns = ObjectRegistry.getConflictColumns(\n this.getResolvedQualifiedName(),\n );\n if (columns.includes('slug')) {\n for (const keyed of await this.getCanonicalPersistedRows({\n slug,\n })) {\n if (typeof keyed.message_id === 'string' && keyed.message_id) {\n parentIds.add(keyed.message_id);\n }\n }\n }\n }\n if (!parentIds.size) return;\n const { MessageCollection } = await import(\n '../collections/MessageCollection.js'\n );\n const messages = await MessageCollection.create(this.options as never);\n const accountIds: Array<string | null> = [];\n for (const id of parentIds) {\n const parent = (await this.db.get(messages.tableName, { id })) as Record<\n string,\n unknown\n > | null;\n if (parent && isUnsentDraft(parent.send_status, parent.is_draft)) {\n accountIds.push((parent.account_id as string | null) ?? null);\n }\n }\n await assertMailDraftWrite(accountIds, this.options);\n }\n\n /**\n * Get the message this attachment belongs to\n */\n async getMessage() {\n if (!this.messageId) return null;\n\n const { MessageCollection } = await import(\n '../collections/MessageCollection'\n );\n const collection = await MessageCollection.create(this.options);\n\n return await collection.get({ id: this.messageId });\n }\n\n /**\n * Check if attachment is an image\n */\n isImage(): boolean {\n return this.contentType.startsWith('image/');\n }\n\n /**\n * Check if attachment is a PDF\n */\n isPdf(): boolean {\n return this.contentType === 'application/pdf';\n }\n\n /**\n * Check if attachment is inline (embedded in message body)\n */\n isInline(): boolean {\n return this.contentDisposition === 'inline';\n }\n\n /**\n * Get file extension from filename\n */\n getExtension(): string {\n if (!this.filename) return '';\n const parts = this.filename.split('.');\n return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : '';\n }\n\n /**\n * Get human-readable file size\n */\n getFormattedSize(): string {\n const units = ['B', 'KB', 'MB', 'GB'];\n let size = this.size;\n let unitIndex = 0;\n\n while (size >= 1024 && unitIndex < units.length - 1) {\n size /= 1024;\n unitIndex++;\n }\n\n return `${size.toFixed(1)} ${units[unitIndex]}`;\n }\n\n /**\n * Check if file is stored externally\n */\n hasExternalFile(): boolean {\n return !!this.filePath;\n }\n\n /**\n * Read file content (if stored externally)\n *\n * The files SDK is loaded through core's bundler-invisible optional-import\n * boundary so it never enters provider-neutral consumer bundles (#1979).\n * Absence of the SDK at runtime degrades to the existing null contract.\n *\n * The local provider joins every path onto its base path (the process cwd\n * by default), so an absolute `filePath` is rooted at its own directory, and\n * the bytes are read raw: decoding a PDF as UTF-8 corrupts it (#3808).\n */\n async readContent(): Promise<Buffer | null> {\n if (!this.filePath) return null;\n\n try {\n const { getFilesystem, initializeProviders } =\n (await importOptionalDependency(\n '@happyvertical/files',\n \"Import '@happyvertical/smrt-core/filesystem' (or '@happyvertical/smrt-assets/filesystem') during server startup to read externally-stored attachments in bundled builds.\",\n )) as typeof import('@happyvertical/files');\n // The SDK registers its providers asynchronously on import; make the\n // local one available before asking for it.\n await initializeProviders?.();\n const split = splitAbsolutePath(this.filePath);\n const files = await getFilesystem(\n split ? { type: 'local', basePath: split.dir } : { type: 'local' },\n );\n const data = await files.read(split ? split.base : this.filePath, {\n raw: true,\n });\n return data instanceof Buffer ? data : Buffer.from(data);\n } catch {\n return null;\n }\n }\n}\n","/**\n * AttachmentCollection - Generalized attachment collection using messageId\n */\n\nimport { SmrtCollection } from '@happyvertical/smrt-core';\nimport { runWithMailSystemAccess } from '../access.js';\nimport { queryGlobal, queryWithGlobals } from '../host.js';\nimport { Attachment } from '../models/Attachment';\n\nexport class AttachmentCollection extends SmrtCollection<Attachment> {\n static readonly _itemClass = Attachment;\n\n /**\n * Fill `accountId` on attachments saved before the column existed, from\n * their message. Run once per tenant after upgrading; safe to repeat.\n * Returns the number of rows updated.\n */\n async backfillAccountIds(): Promise<number> {\n return runWithMailSystemAccess(async () => {\n const { MessageCollection } = await import('./MessageCollection');\n const messages = await MessageCollection.create(this.options);\n let updated = 0;\n for (const attachment of await this.list({\n where: { accountId: null },\n })) {\n if (!attachment.messageId) continue;\n const message = await messages.get({ id: attachment.messageId });\n if (!message?.accountId) continue;\n attachment.accountId = message.accountId;\n await attachment.save();\n updated++;\n }\n return updated;\n });\n }\n\n /**\n * Get attachments for a message\n */\n async getByMessage(messageId: string): Promise<Attachment[]> {\n return await this.list({ where: { messageId } });\n }\n\n /**\n * Get attachments by content type\n */\n async getByContentType(contentType: string): Promise<Attachment[]> {\n return await this.list({ where: { contentType } });\n }\n\n /**\n * Get image attachments\n */\n async getImages(messageId?: string): Promise<Attachment[]> {\n const attachments = messageId\n ? await this.getByMessage(messageId)\n : await this.list({});\n\n return attachments.filter((a) => a.isImage());\n }\n\n /**\n * Get PDF attachments\n */\n async getPdfs(messageId?: string): Promise<Attachment[]> {\n const attachments = messageId\n ? await this.getByMessage(messageId)\n : await this.list({});\n\n return attachments.filter((a) => a.isPdf());\n }\n\n /**\n * Get inline attachments (embedded in message body)\n */\n async getInline(messageId: string): Promise<Attachment[]> {\n const attachments = await this.getByMessage(messageId);\n return attachments.filter((a) => a.isInline());\n }\n\n /**\n * Get regular attachments (not inline)\n */\n async getRegular(messageId: string): Promise<Attachment[]> {\n const attachments = await this.getByMessage(messageId);\n return attachments.filter((a) => !a.isInline());\n }\n\n /**\n * Get attachments with external files\n */\n async getWithExternalFiles(): Promise<Attachment[]> {\n const attachments = await this.list({});\n return attachments.filter((a) => a.hasExternalFile());\n }\n\n /**\n * Get total size of attachments for a message\n */\n async getTotalSize(messageId: string): Promise<number> {\n const attachments = await this.getByMessage(messageId);\n return attachments.reduce((sum, a) => sum + a.size, 0);\n }\n\n /**\n * Get largest attachments\n */\n async getLargest(limit = 10): Promise<Attachment[]> {\n const attachments = await this.list({});\n return attachments.sort((a, b) => b.size - a.size).slice(0, limit);\n }\n\n /**\n * Search attachments by filename\n */\n async searchByFilename(query: string): Promise<Attachment[]> {\n const attachments = await this.list({});\n const lowerQuery = query.toLowerCase();\n\n return attachments.filter((a) =>\n a.filename?.toLowerCase().includes(lowerQuery),\n );\n }\n\n /**\n * Get attachments by extension\n */\n async getByExtension(extension: string): Promise<Attachment[]> {\n const attachments = await this.list({});\n const lowerExt = extension.toLowerCase().replace(/^\\./, '');\n\n return attachments.filter((a) => a.getExtension() === lowerExt);\n }\n\n /**\n * Get attachment statistics\n */\n async getStats(): Promise<{\n total: number;\n totalSize: number;\n byType: Record<string, number>;\n inline: number;\n regular: number;\n }> {\n const attachments = await this.list({});\n\n const byType: Record<string, number> = {};\n for (const attachment of attachments) {\n const type = attachment.contentType.split('/')[0] || 'other';\n byType[type] = (byType[type] || 0) + 1;\n }\n\n return {\n total: attachments.length,\n totalSize: attachments.reduce((sum, a) => sum + a.size, 0),\n byType,\n inline: attachments.filter((a) => a.isInline()).length,\n regular: attachments.filter((a) => !a.isInline()).length,\n };\n }\n\n /**\n * Delete all attachments for a message\n */\n async deleteByMessage(messageId: string): Promise<number> {\n const attachments = await this.getByMessage(messageId);\n let count = 0;\n\n for (const attachment of attachments) {\n await attachment.delete();\n count++;\n }\n\n return count;\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Tenant Helper Methods\n // ─────────────────────────────────────────────────────────────────────────\n\n async findByTenant(tenantId: string): Promise<Attachment[]> {\n return this.list({ where: { tenantId } });\n }\n\n // Attachment is @TenantScoped (CTI, own `attachments` table). Under an active\n // tenant context list({ tenantId: null }) throws and unflagged raw SQL is\n // blocked (#1596); route through the raw helpers.\n async findGlobal(): Promise<Attachment[]> {\n return queryGlobal<Attachment>(this);\n }\n\n async findWithG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