@remit/mailbox-service 0.0.98 → 0.0.100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,345 @@
1
+ import type {
2
+ IAccountConfigRepository,
3
+ IAddressRepository,
4
+ IMessageRepository,
5
+ IThreadMessageRepository,
6
+ ThreadMessageItem,
7
+ } from "@remit/data-ports";
8
+ import { MessageClassificationState } from "@remit/domain-enums";
9
+ import type { StorageService } from "@remit/storage-service";
10
+ import { parseMessageBody } from "./body-parse.js";
11
+ import { extractSnippet } from "./body-sync.js";
12
+ import { classifyParsedMessage } from "./classify-message.js";
13
+ import { extractListId } from "./filters/list-id.js";
14
+ import {
15
+ denormalizeMessageCategory,
16
+ hasDecidedCategory,
17
+ } from "./message-category.js";
18
+
19
+ const DEFAULT_BATCH_SIZE = 200;
20
+
21
+ /**
22
+ * Where the full-corpus pass left off: the identity of the account it was
23
+ * working through, and the page cursor within that account. Resuming looks the
24
+ * account up by id and re-opens it at its saved cursor, rather than re-scanning
25
+ * the whole corpus from the top after an interruption. A checkpoint naming no
26
+ * configured account restarts the pass.
27
+ */
28
+ export interface ClassificationBackfillCheckpoint {
29
+ accountConfigId: string;
30
+ continuationToken?: string;
31
+ }
32
+
33
+ /**
34
+ * Persistence for {@link ClassificationBackfillCheckpoint}, injected so the
35
+ * pass stays testable with an in-memory fake; the real entrypoint backs it
36
+ * with a file. `clear()` runs once the whole corpus has been scanned, so a
37
+ * later run starts fresh rather than reading a stale finished-run checkpoint.
38
+ */
39
+ export interface ClassificationBackfillCheckpointStore {
40
+ load(): Promise<ClassificationBackfillCheckpoint | undefined>;
41
+ save(checkpoint: ClassificationBackfillCheckpoint): Promise<void>;
42
+ clear(): Promise<void>;
43
+ }
44
+
45
+ export interface ClassificationBackfillDeps {
46
+ accountConfigService: Pick<IAccountConfigRepository, "listAll">;
47
+ /** Reads the sender's `Address.flags.category` override (issue #299). */
48
+ addressService: Pick<IAddressRepository, "getAddress">;
49
+ threadMessageService: Pick<
50
+ IThreadMessageRepository,
51
+ "listByAccount" | "findAllByMessageId" | "update"
52
+ >;
53
+ messageService: Pick<IMessageRepository, "get" | "update">;
54
+ storageService: Pick<StorageService, "retrieve">;
55
+ }
56
+
57
+ export interface ClassificationBackfillLogger {
58
+ info(obj: Record<string, unknown>, msg: string): void;
59
+ error?(obj: Record<string, unknown>, msg: string): void;
60
+ }
61
+
62
+ export interface ClassificationBackfillTotals {
63
+ scanned: number;
64
+ alreadyExamined: number;
65
+ alreadyCategorized: number;
66
+ skippedNoBody: number;
67
+ backfilled: number;
68
+ failed: number;
69
+ }
70
+
71
+ export interface ClassificationBackfillResult
72
+ extends ClassificationBackfillTotals {
73
+ failedThreadMessageIds: string[];
74
+ }
75
+
76
+ export interface ClassificationBackfillProgress
77
+ extends ClassificationBackfillTotals {
78
+ accountConfigId: string;
79
+ }
80
+
81
+ export interface ClassificationBackfillOptions {
82
+ /** Rows fetched per `listByAccount` page. */
83
+ batchSize?: number;
84
+ checkpointStore?: ClassificationBackfillCheckpointStore;
85
+ logger?: ClassificationBackfillLogger;
86
+ /** Called once per page, after that page's rows are settled. */
87
+ onProgress?: (progress: ClassificationBackfillProgress) => void;
88
+ }
89
+
90
+ const emptyTotals = (): ClassificationBackfillTotals => ({
91
+ scanned: 0,
92
+ alreadyExamined: 0,
93
+ alreadyCategorized: 0,
94
+ skippedNoBody: 0,
95
+ backfilled: 0,
96
+ failed: 0,
97
+ });
98
+
99
+ /**
100
+ * Read the stored raw source, classify it once, and record that the
101
+ * classifier ran. Kept as its own function (rather than inline in a try/catch)
102
+ * so the caller can contain a failure with `.then(fulfilled, rejected)`
103
+ * instead of a block catch, which keeps the `try` around the one call whose
104
+ * failure this contains.
105
+ *
106
+ * The ThreadMessage rows are denormalized BEFORE the Message update, for the
107
+ * same reason the deleted in-sync backfill did it that way (issue #320): the
108
+ * signal this pass selects by — `classificationState` — is written in the
109
+ * Message update, so a failure between the two writes leaves both undone and
110
+ * the rerun redoes them. Writing the Message first would strand the
111
+ * denormalized rows at `uncategorized` forever — the row reads as examined and
112
+ * the retry returns early.
113
+ */
114
+ const classifyAndApply = async (
115
+ deps: ClassificationBackfillDeps,
116
+ accountConfigId: string,
117
+ row: ThreadMessageItem,
118
+ bodyStorageKey: string,
119
+ ): Promise<void> => {
120
+ const body = await deps.storageService.retrieve(bodyStorageKey);
121
+ const parsed = await parseMessageBody(body);
122
+ const classification = await classifyParsedMessage(
123
+ deps.addressService,
124
+ accountConfigId,
125
+ parsed,
126
+ );
127
+
128
+ // The same denormalized fields the body-store path writes (see
129
+ // `applyPostStoreSteps`), not just the category: the snippet and `List-Id`
130
+ // are derived from the same bytes already in hand, and the rows this pass
131
+ // reaches never got them — the pass that stored the body is the pass that
132
+ // classifies, and it never ran for this cohort.
133
+ await denormalizeMessageCategory(
134
+ { threadMessageService: deps.threadMessageService },
135
+ accountConfigId,
136
+ row.messageId,
137
+ {
138
+ category: classification.category,
139
+ snippet: extractSnippet(parsed),
140
+ listId: extractListId(parsed),
141
+ },
142
+ );
143
+
144
+ await deps.messageService.update(row.messageId, {
145
+ ...classification,
146
+ classificationState: MessageClassificationState.Examined,
147
+ });
148
+ };
149
+
150
+ /**
151
+ * One-time, resumable pass that classifies the stored-body cohort the
152
+ * classifier has never examined (issue #1197): rows whose bodies were synced
153
+ * before the classifier reached them, which carry the `NotExamined` sentinel
154
+ * on `Message.classificationState` and so stay `uncategorized` in the list —
155
+ * the field is what selects the cohort, and nothing on the sync path selects
156
+ * it. Read-only against the stored raw source: it never opens IMAP, and it
157
+ * has no placement or filter side effects — the same bounds the in-sync
158
+ * backfill #1173 removed had. Index-time moves and filter actions are
159
+ * decisions that already ran (or were declined) when the body first landed;
160
+ * re-running them would move mail the user has since filed by hand.
161
+ *
162
+ * A row is a candidate when its Message carries `NotExamined` — the named
163
+ * pending state, never inferred from `category` or from `bodyStorageKey` —
164
+ * and has a `bodyStorageKey`; a candidate without a stored body has nothing
165
+ * local to read, and the ordinary sync path will classify it once the body
166
+ * lands. A candidate whose category is already decided is marked `Examined`
167
+ * without re-deriving anything: those rows were classified by a pass that
168
+ * predates the field, and RFC 034 Decision 3.1's write-once category must not
169
+ * be recomputed (#355). The classification itself is
170
+ * {@link classifyParsedMessage} — the same rule table, and the same sender
171
+ * override, the body-store path classifies with.
172
+ *
173
+ * Chunked by `listByAccount`'s existing keyset pagination, one account at a
174
+ * time in account-id order, so an interrupted run and its resume walk the
175
+ * same sequence. A failure reading, parsing, or classifying one message is
176
+ * contained to that message — logged, counted, and the pass continues: one
177
+ * unreadable object must not strand the rest of the corpus.
178
+ */
179
+ export const backfillClassifications = async (
180
+ deps: ClassificationBackfillDeps,
181
+ options: ClassificationBackfillOptions = {},
182
+ ): Promise<ClassificationBackfillResult> => {
183
+ const batchSize = options.batchSize ?? DEFAULT_BATCH_SIZE;
184
+ const { logger, checkpointStore } = options;
185
+
186
+ const accounts = [...(await deps.accountConfigService.listAll())].sort(
187
+ (left, right) => left.accountConfigId.localeCompare(right.accountConfigId),
188
+ );
189
+ const startingCheckpoint = await checkpointStore?.load();
190
+ const checkpointedIndex = startingCheckpoint
191
+ ? accounts.findIndex(
192
+ (account) =>
193
+ account.accountConfigId === startingCheckpoint.accountConfigId,
194
+ )
195
+ : -1;
196
+
197
+ if (startingCheckpoint && checkpointedIndex === -1) {
198
+ logger?.info(
199
+ { accountConfigId: startingCheckpoint.accountConfigId },
200
+ "Classification backfill checkpoint names no configured account; restarting the pass",
201
+ );
202
+ }
203
+
204
+ const startIndex = checkpointedIndex === -1 ? 0 : checkpointedIndex;
205
+ const startContinuationToken =
206
+ checkpointedIndex === -1
207
+ ? undefined
208
+ : startingCheckpoint?.continuationToken;
209
+
210
+ const totals = emptyTotals();
211
+ const failedThreadMessageIds: string[] = [];
212
+ // Messages settled this run. More than one ThreadMessage row can index one
213
+ // Message, and the candidate fact lives on the Message, so without this a
214
+ // second row would re-read the same body and re-classify it within the
215
+ // same page — idempotent in outcome, wasteful in storage reads.
216
+ const examinedMessageIds = new Set<string>();
217
+
218
+ for (
219
+ let accountIndex = startIndex;
220
+ accountIndex < accounts.length;
221
+ accountIndex++
222
+ ) {
223
+ const account = accounts[accountIndex];
224
+ let continuationToken: string | undefined =
225
+ accountIndex === startIndex ? startContinuationToken : undefined;
226
+
227
+ do {
228
+ const page = await deps.threadMessageService.listByAccount(
229
+ account.accountConfigId,
230
+ { limit: batchSize, continuationToken },
231
+ );
232
+
233
+ totals.scanned += page.items.length;
234
+
235
+ if (page.items.length > 0) {
236
+ const messages = await deps.messageService.get(
237
+ page.items.map((row) => row.messageId),
238
+ );
239
+ const messageByMessageId = new Map(
240
+ messages.map((message) => [message.messageId, message]),
241
+ );
242
+
243
+ for (const row of page.items) {
244
+ const message = messageByMessageId.get(row.messageId);
245
+ if (!message?.bodyStorageKey) {
246
+ totals.skippedNoBody++;
247
+ continue;
248
+ }
249
+
250
+ if (
251
+ message.classificationState !==
252
+ MessageClassificationState.NotExamined ||
253
+ examinedMessageIds.has(row.messageId)
254
+ ) {
255
+ totals.alreadyExamined++;
256
+ continue;
257
+ }
258
+
259
+ // Classified by a pass that predates the field: record that it
260
+ // ran, and touch nothing else — the write-once category is not
261
+ // recomputed (#355), and the derived fields that pass wrote are
262
+ // already on the row.
263
+ if (hasDecidedCategory(message.category)) {
264
+ const outcome = await deps.messageService
265
+ .update(row.messageId, {
266
+ classificationState: MessageClassificationState.Examined,
267
+ })
268
+ .then(
269
+ () => null,
270
+ (error: unknown) => error,
271
+ );
272
+
273
+ if (outcome !== null) {
274
+ totals.failed++;
275
+ failedThreadMessageIds.push(row.threadMessageId);
276
+ logger?.error?.(
277
+ {
278
+ threadMessageId: row.threadMessageId,
279
+ messageId: row.messageId,
280
+ error:
281
+ outcome instanceof Error
282
+ ? outcome.message
283
+ : String(outcome),
284
+ },
285
+ "Classification backfill failed to record an already-categorized message; leaving it for a later pass",
286
+ );
287
+ continue;
288
+ }
289
+
290
+ examinedMessageIds.add(row.messageId);
291
+ totals.alreadyCategorized++;
292
+ continue;
293
+ }
294
+
295
+ const outcome = await classifyAndApply(
296
+ deps,
297
+ account.accountConfigId,
298
+ row,
299
+ message.bodyStorageKey,
300
+ ).then(
301
+ () => null,
302
+ (error: unknown) => error,
303
+ );
304
+
305
+ if (outcome !== null) {
306
+ totals.failed++;
307
+ failedThreadMessageIds.push(row.threadMessageId);
308
+ logger?.error?.(
309
+ {
310
+ threadMessageId: row.threadMessageId,
311
+ messageId: row.messageId,
312
+ error:
313
+ outcome instanceof Error ? outcome.message : String(outcome),
314
+ },
315
+ "Classification backfill failed for a message; leaving it for a later pass",
316
+ );
317
+ continue;
318
+ }
319
+
320
+ examinedMessageIds.add(row.messageId);
321
+ totals.backfilled++;
322
+ }
323
+ }
324
+
325
+ continuationToken = page.continuationToken;
326
+ await checkpointStore?.save({
327
+ accountConfigId: account.accountConfigId,
328
+ continuationToken,
329
+ });
330
+
331
+ logger?.info(
332
+ { accountConfigId: account.accountConfigId, ...totals },
333
+ "Classification backfill progress",
334
+ );
335
+ options.onProgress?.({
336
+ accountConfigId: account.accountConfigId,
337
+ ...totals,
338
+ });
339
+ } while (continuationToken);
340
+ }
341
+
342
+ await checkpointStore?.clear();
343
+
344
+ return { ...totals, failedThreadMessageIds };
345
+ };
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Tests for `classifyParsedMessage` (issue #1197): the one classification
3
+ * implementation shared by the body-store path and the classification
4
+ * backfill, so the two can never classify the same bytes differently. Pins
5
+ * the `Address.flags.category` override contract (issue #299, RFC 039
6
+ * Decision 3) on its own, rather than only through body-sync's public
7
+ * surface: the override wins outright, a genuinely-absent Address is "no
8
+ * override", and any other read failure propagates rather than silently
9
+ * classifying by headers when the user asked for something else.
10
+ */
11
+
12
+ import assert from "node:assert/strict";
13
+ import { describe, it } from "node:test";
14
+ import type { AddressItem, IAddressRepository } from "@remit/data-ports";
15
+ import { NotFoundError } from "@remit/data-ports/errors";
16
+ import { parseMessageBody } from "./body-parse.js";
17
+ import {
18
+ classifyParsedMessage,
19
+ extractPrimaryFromEmail,
20
+ } from "./classify-message.js";
21
+
22
+ const PLAIN_EML = Buffer.from(
23
+ [
24
+ "From: Alice <alice@example.com>",
25
+ "To: me@example.com",
26
+ "Subject: Hi",
27
+ "Content-Type: text/plain",
28
+ "",
29
+ "hi",
30
+ ].join("\r\n"),
31
+ );
32
+
33
+ const LIST_EML = Buffer.from(
34
+ [
35
+ "From: Alice <alice@example.com>",
36
+ "To: me@example.com",
37
+ "Subject: Newsletter",
38
+ "List-Id: <news.example.com>",
39
+ "List-Unsubscribe: <https://example.com/unsub>",
40
+ "Content-Type: text/plain",
41
+ "",
42
+ "this week in news",
43
+ ].join("\r\n"),
44
+ );
45
+
46
+ const addressService = (
47
+ behavior: (accountConfigId: string, addressId: string) => unknown,
48
+ ): Pick<IAddressRepository, "getAddress"> => ({
49
+ getAddress: (async (accountConfigId: string, addressId: string) =>
50
+ behavior(
51
+ accountConfigId,
52
+ addressId,
53
+ )) as unknown as IAddressRepository["getAddress"],
54
+ });
55
+
56
+ const withFlags =
57
+ (flags: AddressItem["flags"]): (() => AddressItem) =>
58
+ () =>
59
+ ({ flags }) as AddressItem;
60
+
61
+ describe("classifyParsedMessage", () => {
62
+ it("answers from the header rule table when the sender has no override", async () => {
63
+ const parsed = await parseMessageBody(LIST_EML);
64
+
65
+ const classification = await classifyParsedMessage(
66
+ addressService(async () => {
67
+ throw new NotFoundError("no Address row");
68
+ }),
69
+ "acc-1",
70
+ parsed,
71
+ );
72
+
73
+ assert.equal(classification.category, "newsletter");
74
+ assert.equal(classification.hasListUnsubscribe, true);
75
+ });
76
+
77
+ it("substitutes the sender's flags.category override outright", async () => {
78
+ const parsed = await parseMessageBody(PLAIN_EML);
79
+
80
+ const classification = await classifyParsedMessage(
81
+ addressService(withFlags({ category: { value: "marketing", setAt: 1 } })),
82
+ "acc-1",
83
+ parsed,
84
+ );
85
+
86
+ // The header table alone would answer `personal`; the override wins
87
+ // without blending (RFC 039 Decision 3).
88
+ assert.equal(classification.category, "marketing");
89
+ });
90
+
91
+ it("propagates an Address read failure rather than classifying by headers", async () => {
92
+ const parsed = await parseMessageBody(PLAIN_EML);
93
+
94
+ await assert.rejects(
95
+ classifyParsedMessage(
96
+ addressService(async () => {
97
+ throw new Error("throttled");
98
+ }),
99
+ "acc-1",
100
+ parsed,
101
+ ),
102
+ /throttled/,
103
+ );
104
+ });
105
+
106
+ it("reads no Address at all when the message has no From address", async () => {
107
+ const parsed = await parseMessageBody(
108
+ Buffer.from(
109
+ [
110
+ "To: me@example.com",
111
+ "Subject: Hi",
112
+ "Content-Type: text/plain",
113
+ "",
114
+ "hi",
115
+ ].join("\r\n"),
116
+ ),
117
+ );
118
+ let reads = 0;
119
+
120
+ const classification = await classifyParsedMessage(
121
+ addressService(async () => {
122
+ reads++;
123
+ throw new NotFoundError("no Address row");
124
+ }),
125
+ "acc-1",
126
+ parsed,
127
+ );
128
+
129
+ assert.equal(reads, 0);
130
+ assert.equal(classification.category, "personal");
131
+ });
132
+ });
133
+
134
+ describe("extractPrimaryFromEmail", () => {
135
+ it("reads the first From address", async () => {
136
+ const parsed = await parseMessageBody(PLAIN_EML);
137
+ assert.equal(extractPrimaryFromEmail(parsed), "alice@example.com");
138
+ });
139
+
140
+ it("answers null when there is no From address to read", async () => {
141
+ const parsed = await parseMessageBody(
142
+ Buffer.from(["To: me@example.com", "", "hi"].join("\r\n")),
143
+ );
144
+ assert.equal(extractPrimaryFromEmail(parsed), null);
145
+ });
146
+ });
@@ -0,0 +1,113 @@
1
+ import type {
2
+ IAddressRepository,
3
+ ThreadMessageItem,
4
+ UpdateMessageInput,
5
+ } from "@remit/data-ports";
6
+ import { NotFoundError } from "@remit/data-ports/errors";
7
+ import { deriveAddressId } from "@remit/data-ports/id";
8
+ import type { ParsedMail } from "mailparser";
9
+ import {
10
+ classifyByHeaders,
11
+ extractAuthenticity,
12
+ extractAuthResult,
13
+ extractHasListUnsubscribe,
14
+ extractProviderSpam,
15
+ } from "./heuristics/classifyByHeaders.js";
16
+ import { extractSenderMismatch } from "./heuristics/senderMismatch.js";
17
+
18
+ type ThreadMessageCategory = ThreadMessageItem["category"];
19
+
20
+ /**
21
+ * The From address the classifier reads, when there is one to read. Shared by
22
+ * every path that classifies or counts a sender (body-sync's classification,
23
+ * inbound counter and placement signals, and the classification backfill) so
24
+ * they all read the same address off the same bytes.
25
+ */
26
+ export const extractPrimaryFromEmail = (parsed: ParsedMail): string | null => {
27
+ const from = parsed.from;
28
+ if (!from || !from.value || from.value.length === 0) return null;
29
+ const address = from.value[0]?.address;
30
+ if (!address) return null;
31
+ return address.toLowerCase();
32
+ };
33
+
34
+ /**
35
+ * The one-sided half of `Address.flags.category` (issue #299, RFC 039
36
+ * Decision 3): a real value here overrides `classifyByHeaders` outright.
37
+ * Only a genuinely-absent Address is "no override" — any other failure
38
+ * (throttle, infra) propagates, because this feeds the write-once
39
+ * `Message.category` at the moment it is decided, where a masked infra
40
+ * failure would silently classify by headers when the user asked for
41
+ * something else.
42
+ */
43
+ const resolveCategoryOverride = async (
44
+ addressService: Pick<IAddressRepository, "getAddress">,
45
+ accountConfigId: string,
46
+ fromEmail: string,
47
+ ): Promise<ThreadMessageCategory | undefined> => {
48
+ try {
49
+ const addressId = deriveAddressId(accountConfigId, fromEmail);
50
+ const address = await addressService.getAddress(accountConfigId, addressId);
51
+ return address.flags?.category?.value;
52
+ } catch (err) {
53
+ if (!(err instanceof NotFoundError)) throw err;
54
+ return undefined;
55
+ }
56
+ };
57
+
58
+ /**
59
+ * Header classification, with the sender's `Address.flags.category` override
60
+ * (issue #299, RFC 039 Decision 3) substituted for the header-derived
61
+ * category when one is set. Returns the subset of the Message update that
62
+ * carries the derived fields; the caller folds it into a single UpdateItem
63
+ * alongside `bodyStorageKey` (body-sync) or `classificationState` (the
64
+ * classification backfill, issue #1197). Optional signals are omitted when
65
+ * absent so we never overwrite an existing value with `undefined`.
66
+ *
67
+ * The override wins outright rather than blending with the heuristic — RFC
68
+ * 039 Decision 3 treats a direct reclassification as final, the same as
69
+ * `flags.blocked`/`vip` already override placement. Every caller gates on
70
+ * `hasDecidedCategory` before this result reaches a write, so a message that
71
+ * already carries a real category is never re-touched regardless of what
72
+ * this returns.
73
+ */
74
+ export const classifyParsedMessage = async (
75
+ addressService: Pick<IAddressRepository, "getAddress">,
76
+ accountConfigId: string,
77
+ parsed: ParsedMail,
78
+ ): Promise<UpdateMessageInput & { category: ThreadMessageCategory }> => {
79
+ const headerCategory = classifyByHeaders(parsed);
80
+ const authenticity = extractAuthenticity(parsed);
81
+ const authResult = extractAuthResult(parsed);
82
+ const providerSpam = extractProviderSpam(parsed);
83
+ const hasListUnsubscribe = extractHasListUnsubscribe(parsed);
84
+
85
+ // A passing SPF/DKIM/DMARC check proves the sending domain, not the
86
+ // identity the message claims — on a shared-tenant host the verified
87
+ // subdomain belongs to whoever signed up. These two comparisons say
88
+ // whether the claim holds, and run only over mail the provider already
89
+ // called spam.
90
+ const senderMismatch =
91
+ authenticity === null
92
+ ? {}
93
+ : extractSenderMismatch(parsed, {
94
+ fromDomain: authenticity.fromDomain,
95
+ spamClassified: providerSpam?.classified === true,
96
+ bulkSender: hasListUnsubscribe,
97
+ });
98
+
99
+ const fromEmail = extractPrimaryFromEmail(parsed);
100
+ const categoryOverride = fromEmail
101
+ ? await resolveCategoryOverride(addressService, accountConfigId, fromEmail)
102
+ : undefined;
103
+
104
+ return {
105
+ category: categoryOverride ?? headerCategory,
106
+ hasListUnsubscribe,
107
+ ...(authenticity !== null
108
+ ? { authenticity: { ...authenticity, ...senderMismatch } }
109
+ : {}),
110
+ ...(authResult !== null ? { authResult } : {}),
111
+ ...(providerSpam !== null ? { providerSpam } : {}),
112
+ };
113
+ };
package/src/index.ts CHANGED
@@ -28,7 +28,7 @@ export {
28
28
  type BodySyncLogger,
29
29
  BodySyncService,
30
30
  type ConnectionGetter,
31
- extractPrimaryFromEmail,
31
+ extractSnippet,
32
32
  type FetchBodyResult,
33
33
  type PlacementConfig,
34
34
  type QuarantineConfig,
@@ -48,6 +48,21 @@ export {
48
48
  type ResolveExhaustedBodySyncResult,
49
49
  resolveExhaustedBodySyncFailures,
50
50
  } from "./body-sync-terminal.js";
51
+ export {
52
+ backfillClassifications,
53
+ type ClassificationBackfillCheckpoint,
54
+ type ClassificationBackfillCheckpointStore,
55
+ type ClassificationBackfillDeps,
56
+ type ClassificationBackfillLogger,
57
+ type ClassificationBackfillOptions,
58
+ type ClassificationBackfillProgress,
59
+ type ClassificationBackfillResult,
60
+ type ClassificationBackfillTotals,
61
+ } from "./classification-backfill.js";
62
+ export {
63
+ classifyParsedMessage,
64
+ extractPrimaryFromEmail,
65
+ } from "./classify-message.js";
51
66
  // Connection factory
52
67
  export {
53
68
  createConnection,
@@ -3,9 +3,27 @@ import type {
3
3
  ThreadMessageItem,
4
4
  } from "@remit/data-ports";
5
5
  import { NotFoundError } from "@remit/data-ports/errors";
6
+ import { MessageCategory } from "@remit/domain-enums";
6
7
 
7
8
  export type MessageCategoryValue = ThreadMessageItem["category"];
8
9
 
10
+ /**
11
+ * RFC 034 Decision 3.1: `Message.category` is written once and never mutated
12
+ * after — RFC 030's message-list GSI sort key depends on it never churning.
13
+ * "Already decided" is any real category, so a message that carries one is
14
+ * never re-categorized by a re-entrant pass.
15
+ *
16
+ * `uncategorized` fails this test whether or not the classifier has run, which
17
+ * is deliberate: this asks what the row holds, not what was done to it. Whether
18
+ * the classifier has run is {@link Message.classificationState}, and it is the
19
+ * skip guard in `BodySyncService.syncBodies` — not this one — that keeps a
20
+ * declined message from being examined twice.
21
+ */
22
+ export const hasDecidedCategory = (
23
+ category: MessageCategoryValue | undefined,
24
+ ): boolean =>
25
+ category !== undefined && category !== MessageCategory.uncategorized;
26
+
9
27
  export interface MessageCategoryDenormalizeDeps {
10
28
  threadMessageService: Pick<
11
29
  IThreadMessageRepository,