@wirecat/cli-core 1.3.0 → 2.0.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 (134) hide show
  1. package/CHANGELOG.md +145 -0
  2. package/dist/attachments/container.d.ts +1 -1
  3. package/dist/attachments/container.js +16 -7
  4. package/dist/attachments/limits.d.ts +10 -0
  5. package/dist/attachments/limits.js +30 -1
  6. package/dist/attachments/transfer.js +2 -2
  7. package/dist/cli/app-doctor-command.d.ts +61 -7
  8. package/dist/cli/app-doctor-command.js +24 -11
  9. package/dist/cli/documents/file-edit.js +6 -6
  10. package/dist/cli/documents/library.js +4 -2
  11. package/dist/cli/index.d.ts +6 -5
  12. package/dist/cli/index.js +2 -1
  13. package/dist/cli/messenger/context.d.ts +16 -0
  14. package/dist/cli/messenger/doctor-command.js +16 -1
  15. package/dist/cli/messenger/flooded.js +9 -1
  16. package/dist/cli/messenger/serve-relay.d.ts +2 -0
  17. package/dist/cli/oauth-session.d.ts +3 -2
  18. package/dist/cli/oauth-session.js +19 -3
  19. package/dist/cli/profile-store.d.ts +24 -10
  20. package/dist/cli/profile-store.js +43 -28
  21. package/dist/cli/shared-command-exports.d.ts +1 -1
  22. package/dist/cli/token-session.d.ts +21 -2
  23. package/dist/cli/token-session.js +27 -11
  24. package/dist/crm/cli/files.js +7 -7
  25. package/dist/documents.d.ts +1 -1
  26. package/dist/documents.js +1 -1
  27. package/dist/domain/person-kinds.d.ts +7 -3
  28. package/dist/domain/person-kinds.js +7 -3
  29. package/dist/domain/ref-summaries.js +1 -0
  30. package/dist/domain/references.d.ts +3 -2
  31. package/dist/domain/references.js +19 -10
  32. package/dist/entities/deal.d.ts +2 -2
  33. package/dist/entities/deal.js +1 -1
  34. package/dist/entities/fact.d.ts +2 -2
  35. package/dist/entities/fact.js +1 -1
  36. package/dist/entities/fields.d.ts +1 -1
  37. package/dist/entities/fields.js +1 -1
  38. package/dist/entities/index.d.ts +15 -15
  39. package/dist/entities/mail-findings.d.ts +2 -2
  40. package/dist/entities/mail-findings.js +1 -1
  41. package/dist/entities/meeting-findings.d.ts +2 -2
  42. package/dist/entities/meeting-findings.js +1 -1
  43. package/dist/entities/memory.d.ts +1 -1
  44. package/dist/entities/task-results.d.ts +5 -5
  45. package/dist/entities/task-results.js +1 -1
  46. package/dist/entities/task.d.ts +1 -1
  47. package/dist/entities/task.js +1 -1
  48. package/dist/errors/reasons.js +2 -1
  49. package/dist/fetch/page.js +1 -2
  50. package/dist/mail/headers.d.ts +4 -3
  51. package/dist/mail/headers.js +21 -3
  52. package/dist/mail/sort-rules.d.ts +13 -6
  53. package/dist/mail/sort-rules.js +20 -16
  54. package/dist/mail/sync.js +2 -0
  55. package/dist/mcp/tools/attachments.js +1 -1
  56. package/dist/office/zip.js +1 -1
  57. package/dist/ports/messenger.d.ts +31 -1
  58. package/dist/services/archive.js +61 -11
  59. package/dist/services/attachments.js +4 -4
  60. package/dist/services/documents/file-text.js +2 -2
  61. package/dist/services/metadata.d.ts +1 -1
  62. package/dist/services/proposals/kinds/shared.d.ts +1 -1
  63. package/dist/services/proposals/kinds/shared.js +2 -2
  64. package/dist/services/proposals/kinds/task-close.js +1 -1
  65. package/dist/store/areas.d.ts +2 -0
  66. package/dist/store/areas.js +1 -0
  67. package/dist/store/decisions.d.ts +1 -1
  68. package/dist/store/decisions.js +4 -4
  69. package/dist/store/evidence-findings.d.ts +2 -2
  70. package/dist/store/index.d.ts +3 -1
  71. package/dist/store/index.js +2 -1
  72. package/dist/store/mail-findings.d.ts +2 -2
  73. package/dist/store/meeting-findings.d.ts +2 -2
  74. package/dist/store/people.d.ts +4 -4
  75. package/dist/store/people.js +2 -1
  76. package/dist/store/project-transfer/manifest.js +3 -3
  77. package/dist/store/public.d.ts +1 -1
  78. package/dist/store/public.js +1 -1
  79. package/dist/store/sqlite/actors.d.ts +1 -1
  80. package/dist/store/sqlite/actors.js +6 -6
  81. package/dist/store/sqlite/agent-actions.js +2 -2
  82. package/dist/store/sqlite/agent-links.js +1 -1
  83. package/dist/store/sqlite/bot-sends.d.ts +19 -0
  84. package/dist/store/sqlite/bot-sends.js +36 -0
  85. package/dist/store/sqlite/business-contracts.js +1 -1
  86. package/dist/store/sqlite/deals.js +1 -1
  87. package/dist/store/sqlite/document-transfer/plan.js +1 -1
  88. package/dist/store/sqlite/document-transfer/snapshot.js +1 -1
  89. package/dist/store/sqlite/email-index.d.ts +11 -2
  90. package/dist/store/sqlite/email-index.js +56 -5
  91. package/dist/store/sqlite/email-types.d.ts +15 -3
  92. package/dist/store/sqlite/email-types.js +32 -1
  93. package/dist/store/sqlite/emails.d.ts +2 -1
  94. package/dist/store/sqlite/emails.js +6 -1
  95. package/dist/store/sqlite/entity-types.d.ts +1 -1
  96. package/dist/store/sqlite/entity-types.js +1 -1
  97. package/dist/store/sqlite/evidence-findings.js +1 -1
  98. package/dist/store/sqlite/facts.js +1 -1
  99. package/dist/store/sqlite/finance.js +2 -2
  100. package/dist/store/sqlite/knowledge.js +1 -0
  101. package/dist/store/sqlite/mail-findings.js +1 -1
  102. package/dist/store/sqlite/mail-sorting.d.ts +1 -1
  103. package/dist/store/sqlite/mail-sorting.js +96 -60
  104. package/dist/store/sqlite/mail-subscriptions.d.ts +70 -0
  105. package/dist/store/sqlite/mail-subscriptions.js +132 -0
  106. package/dist/store/sqlite/manifest.js +45 -0
  107. package/dist/store/sqlite/meeting-findings.js +1 -1
  108. package/dist/store/sqlite/memories.js +3 -3
  109. package/dist/store/sqlite/migrations.generated.js +80 -0
  110. package/dist/store/sqlite/money-transactions.js +1 -1
  111. package/dist/store/sqlite/note-index.d.ts +4 -1
  112. package/dist/store/sqlite/note-index.js +40 -17
  113. package/dist/store/sqlite/orders.js +1 -1
  114. package/dist/store/sqlite/payment-facts.js +2 -2
  115. package/dist/store/sqlite/products.js +1 -1
  116. package/dist/store/sqlite/project-transfer/sources.js +2 -2
  117. package/dist/store/sqlite/proposed-actions.js +3 -3
  118. package/dist/store/sqlite/record-projection.js +1 -1
  119. package/dist/store/sqlite/ref-summaries.js +2 -1
  120. package/dist/store/sqlite/relation-proposals.js +1 -1
  121. package/dist/store/sqlite/reviewed.d.ts +2 -2
  122. package/dist/store/sqlite/reviewed.js +1 -1
  123. package/dist/store/sqlite/sender-bots.d.ts +19 -4
  124. package/dist/store/sqlite/sender-bots.js +48 -4
  125. package/dist/store/sqlite/subscriptions.js +2 -2
  126. package/dist/store/sqlite/task-close.js +1 -1
  127. package/dist/store/sqlite/task-comments.js +1 -1
  128. package/dist/store/sqlite/things.js +1 -1
  129. package/dist/store/sqlite/transaction.d.ts +5 -0
  130. package/dist/store/sqlite/transaction.js +6 -1
  131. package/dist/store/sqlite/wallets.js +1 -1
  132. package/dist/store/sqlite/work-tasks.js +2 -2
  133. package/dist/tracker/tasks.js +4 -2
  134. package/package.json +7 -5
@@ -0,0 +1,36 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { typeWhere } from "./email-types.js";
3
+ /**
4
+ * What a bot sends, as the Bots tab filters it: the mail types that put a bot under each name. `messenger` is a bot
5
+ * with an account in a messenger, whatever it sends. @experimental
6
+ */
7
+ export const BOT_SENDS = {
8
+ alerts: ["security", "system_alert", "account_notice"],
9
+ receipts: ["order", "bill", "shipping"],
10
+ newsletters: ["newsletter"],
11
+ marketing: ["promotion"],
12
+ messenger: null,
13
+ };
14
+ /** Which bots send any of these, over `b`: by the type of their mail, or a messenger account. */
15
+ export const sendsWhere = (database, sends) => {
16
+ const unknown = sends.filter((name) => !Object.hasOwn(BOT_SENDS, name));
17
+ if (unknown.length > 0 || sends.length === 0)
18
+ throw new CliError("validation_error", `a bot sends one of ${Object.keys(BOT_SENDS).join(", ")}, got "${unknown.join(", ")}"`, { reason: "sender-bot.unknown-sends" });
19
+ const types = [...new Set(sends.flatMap((name) => BOT_SENDS[name] ?? []))];
20
+ const typed = types.length === 0 ? undefined : typeWhere(database, { types });
21
+ const any = [
22
+ ...(typed === undefined
23
+ ? []
24
+ : [
25
+ "EXISTS (SELECT 1 FROM sender_bot_identities s JOIN emails e ON e.from_identity_id = s.identity_id " +
26
+ `WHERE s.bot_id = b.id AND e.deleted_at IS NULL AND e.outgoing IS NOT 1 AND ${typed.sql.join(" AND ")})`,
27
+ ]),
28
+ ...(sends.includes("messenger")
29
+ ? [
30
+ "EXISTS (SELECT 1 FROM sender_bot_identities s JOIN identities i ON i.id = s.identity_id " +
31
+ "WHERE s.bot_id = b.id AND i.provider <> 'email')",
32
+ ]
33
+ : []),
34
+ ];
35
+ return { sql: `(${any.join(" OR ")})`, params: typed?.params ?? [] };
36
+ };
@@ -10,7 +10,7 @@ import { pageOfRows } from "./rows-page.js";
10
10
  import { storedThing } from "./things.js";
11
11
  import { write } from "./transaction.js";
12
12
  const CONTRACTS = "SELECT k.*, b.name AS author_name, b.kind AS author_kind FROM contracts k " +
13
- "LEFT JOIN bots b ON k.author_type = 'bot' AND b.id = k.author_id";
13
+ "LEFT JOIN bots b ON k.author_type = 'agent' AND b.id = k.author_id";
14
14
  const DAY_MS = 86_400_000;
15
15
  const deadlineOf = (expiration, days) => expiration === null || days === null
16
16
  ? null
@@ -26,7 +26,7 @@ const itemsSql = (kind) => "SELECT d.*, s.name AS stage_name, s.pipeline_id, p.n
26
26
  "b.kind AS author_kind, a.provider AS account_provider, a.external_id AS account_external_id, " +
27
27
  "bs.id AS base_stage_ref_id, bs.name AS base_stage_name " +
28
28
  `FROM ${TABLES[kind]} d JOIN pipeline_stages s ON s.id = d.stage_id JOIN pipelines p ON p.id = s.pipeline_id ` +
29
- "LEFT JOIN bots b ON d.author_type = 'bot' AND b.id = d.author_id LEFT JOIN accounts a ON a.id = d.account_id " +
29
+ "LEFT JOIN bots b ON d.author_type = 'agent' AND b.id = d.author_id LEFT JOIN accounts a ON a.id = d.account_id " +
30
30
  "LEFT JOIN pipeline_stages bs ON s.base_confirmed = 1 AND bs.id = s.base_stage_id";
31
31
  const MAX_STAGES = 30;
32
32
  const MAX_PEOPLE = 20;
@@ -78,7 +78,7 @@ export const planTransfer = (database, snapshot, sourceKey, bindings) => {
78
78
  if (bot && bot.kind !== external.bot.kind)
79
79
  conflicts.add(`destination bot kind differs for ${external.reference}`);
80
80
  if (bot)
81
- found = { type: "bot", id: Number(bot.id) };
81
+ found = { type: "agent", id: Number(bot.id) };
82
82
  // A new author handle is created without copying credentials, settings or metadata.
83
83
  else
84
84
  continue;
@@ -158,7 +158,7 @@ export const transferSnapshot = (database, collection) => read(database, () => {
158
158
  if (identity?.person_id != null)
159
159
  depend("person", identity.person_id);
160
160
  }
161
- if (thing.type === "bot") {
161
+ if (thing.type === "agent") {
162
162
  const bot = database.prepare("SELECT name,kind FROM bots WHERE id=?").get(thing.id);
163
163
  if (bot)
164
164
  item.bot = { name: String(bot.name), kind: String(bot.kind) };
@@ -1,6 +1,6 @@
1
1
  import { type Chunk } from "../../conversations/chunks.js";
2
2
  import type { Stemmer, Stemmers } from "../../search/stem.js";
3
- import type { CacheDatabase } from "../driver.js";
3
+ import { type CacheDatabase } from "../driver.js";
4
4
  export declare const titleOf: (subject: string | null) => string | null;
5
5
  /**
6
6
  * Every piece of mail: a stretch of a thread, one email's attachment, or the text a model wrote about one email. A thread piece holds no email of its
@@ -17,4 +17,13 @@ export declare const queueThreads: (database: CacheDatabase, ids: Iterable<numbe
17
17
  export declare const dropAttachmentChunks: (database: CacheDatabase, emailId: number) => string[];
18
18
  /** Each attachment's extracted text, in pieces for search by meaning, as an email's own text is. */
19
19
  export declare const chunkAttachments: (database: CacheDatabase, accountId: number, emailId: number, now: number) => void;
20
- export declare const drainEmailIndex: (database: CacheDatabase, stemmerFor: (stemmers: Stemmers) => Stemmer) => number;
20
+ export declare const drainEmailIndex: (database: CacheDatabase, stemmerFor: (stemmers: Stemmers) => Stemmer, until?: () => boolean) => number;
21
+ /**
22
+ * Indexes and types the mail of these threads inside the save's own write, plus a little of what was queued before,
23
+ * so the first search finds it done. A drain of
24
+ * its own commits every 200 emails, and under a busy disk each commit's sync costs up to a second: 100,000 saved
25
+ * emails took the first search 564 s (cli-testing performance/mail/types).
26
+ */
27
+ export declare const indexSavedMail: (database: CacheDatabase, stemmerFor: (stemmers: Stemmers) => Stemmer, threadIds: readonly number[]) => void;
28
+ /** Every email still waiting for its words, pieces or type, done a short write at a time until `until` answers true. */
29
+ export declare const catchUpMail: (database: CacheDatabase, stemmerFor: (stemmers: Stemmers) => Stemmer, until?: () => boolean) => void;
@@ -1,7 +1,9 @@
1
1
  import { CHUNK_CHARS, chunkHash, cutChunks, splitText } from "../../conversations/chunks.js";
2
2
  import { mailCore } from "../../conversations/mail-text.js";
3
+ import { isQueryOnly } from "../driver.js";
4
+ import { storeMailTypes, typeSavedMail } from "./email-types.js";
3
5
  import { int, str } from "./events.js";
4
- import { CORPORA, drainCorpus } from "./note-index.js";
6
+ import { CORPORA, drainCorpus, indexQueued } from "./note-index.js";
5
7
  import { write } from "./transaction.js";
6
8
  import { dropUnusedVectors } from "./vector-index.js";
7
9
  export const titleOf = (subject) => subject?.replace(/^\s*((re|fwd?|aw|wg)\s*:\s*)+/i, "").trim() || null;
@@ -102,8 +104,8 @@ export const chunkAttachments = (database, accountId, emailId, now) => {
102
104
  const MAIL_CUT = "mail_pieces_cut";
103
105
  // Each change to a piece's text bumps this, so every store cuts its mail again once and re-embeds it.
104
106
  const CUT = "email, sender at the end";
105
- export const drainEmailIndex = (database, stemmerFor) => {
106
- // Mail was once cut without cleaning, then across the emails of a thread, then with its sender before the subject; a store cut any of those ways is cut again.
107
+ // Mail was once cut without cleaning, then across the emails of a thread, then with its sender before the subject; a store cut any of those ways is cut again.
108
+ const cutCurrently = (database) => {
107
109
  if (database.prepare("SELECT value FROM store_settings WHERE key = ?").get(MAIL_CUT)?.value !== CUT)
108
110
  write(database, () => {
109
111
  const single = database
@@ -120,6 +122,13 @@ export const drainEmailIndex = (database, stemmerFor) => {
120
122
  .prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
121
123
  .run(MAIL_CUT, CUT, Date.now());
122
124
  });
125
+ };
126
+ /** How long one write of the word drain may go on taking batches: well inside another writer's 5 s wait. */
127
+ const DRAIN_BUDGET_MS = 250;
128
+ export const drainEmailIndex = (database, stemmerFor, until = () => false) => {
129
+ if (isQueryOnly(database))
130
+ return 0;
131
+ cutCurrently(database);
123
132
  const unqueued = `FROM email_index_pending q JOIN emails e ON e.id = q.id
124
133
  WHERE q.indexable_type = 'email' AND e.email_thread_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM email_index_pending t
125
134
  WHERE t.indexable_type = 'email_thread' AND t.id = e.email_thread_id)`;
@@ -141,11 +150,11 @@ export const drainEmailIndex = (database, stemmerFor) => {
141
150
  dropUnusedVectors(database, before);
142
151
  }
143
152
  });
144
- const emails = drainCorpus(database, CORPORA.email, stemmerFor);
153
+ const emails = drainCorpus(database, CORPORA.email, stemmerFor, { until, budgetMs: DRAIN_BUDGET_MS });
145
154
  const next = database.prepare("SELECT id FROM email_index_pending WHERE indexable_type = 'email_thread' ORDER BY id LIMIT 50");
146
155
  const done = database.prepare("DELETE FROM email_index_pending WHERE indexable_type = 'email_thread' AND id = ?");
147
156
  let threads = 0;
148
- while (next.all().length > 0)
157
+ while (!until() && next.all().length > 0)
149
158
  threads += write(database, () => {
150
159
  const ids = next.all().map(({ id }) => Number(id));
151
160
  for (const id of ids) {
@@ -156,3 +165,45 @@ export const drainEmailIndex = (database, stemmerFor) => {
156
165
  });
157
166
  return emails + threads;
158
167
  };
168
+ /** How many emails, and threads, queued before this save one save also indexes: the queue drains as mail syncs. */
169
+ const EMAIL_BACKLOG_ON_SAVE = 500;
170
+ const THREAD_BACKLOG_ON_SAVE = 50;
171
+ /**
172
+ * Indexes and types the mail of these threads inside the save's own write, plus a little of what was queued before,
173
+ * so the first search finds it done. A drain of
174
+ * its own commits every 200 emails, and under a busy disk each commit's sync costs up to a second: 100,000 saved
175
+ * emails took the first search 564 s (cli-testing performance/mail/types).
176
+ */
177
+ export const indexSavedMail = (database, stemmerFor, threadIds) => {
178
+ cutCurrently(database);
179
+ const ids = (sql, ...params) => database
180
+ .prepare(sql)
181
+ .all(...params)
182
+ .map(({ id }) => Number(id));
183
+ const saved = ids(`SELECT q.id FROM email_index_pending q JOIN emails e ON e.id = q.id
184
+ WHERE q.indexable_type = 'email' AND e.email_thread_id IN (SELECT value FROM json_each(?))`, JSON.stringify(threadIds));
185
+ const backlog = ids("SELECT id FROM email_index_pending WHERE indexable_type = 'email' ORDER BY id LIMIT ?", EMAIL_BACKLOG_ON_SAVE);
186
+ const emails = [...new Set([...saved, ...backlog])];
187
+ // An email's words leave the queue with it, so its thread is queued first, as the drain does.
188
+ database
189
+ .prepare(`INSERT OR IGNORE INTO email_index_pending (indexable_type, id) SELECT DISTINCT 'email_thread', email_thread_id
190
+ FROM emails WHERE id IN (SELECT value FROM json_each(?)) AND email_thread_id IS NOT NULL`)
191
+ .run(JSON.stringify(emails));
192
+ indexQueued(database, CORPORA.email, stemmerFor, emails);
193
+ const threads = new Set([
194
+ ...ids("SELECT id FROM email_index_pending WHERE indexable_type = 'email_thread' AND id IN (SELECT value FROM json_each(?))", JSON.stringify(threadIds)),
195
+ ...ids("SELECT id FROM email_index_pending WHERE indexable_type = 'email_thread' ORDER BY id LIMIT ?", THREAD_BACKLOG_ON_SAVE),
196
+ ]);
197
+ const done = database.prepare("DELETE FROM email_index_pending WHERE indexable_type = 'email_thread' AND id = ?");
198
+ for (const id of threads) {
199
+ chunkThread(database, id, Date.now());
200
+ done.run(id);
201
+ }
202
+ typeSavedMail(database, threadIds);
203
+ };
204
+ /** Every email still waiting for its words, pieces or type, done a short write at a time until `until` answers true. */
205
+ export const catchUpMail = (database, stemmerFor, until = () => false) => {
206
+ drainEmailIndex(database, stemmerFor, until);
207
+ if (!until())
208
+ storeMailTypes(database, until);
209
+ };
@@ -14,7 +14,14 @@ export declare const typesCurrent: (database: CacheDatabase) => boolean;
14
14
  * changed, a batch per write so another process never waits long for the lock. A query-only open keeps nothing.
15
15
  * Answers whether every stored type is current.
16
16
  */
17
- export declare const storeMailTypes: (database: CacheDatabase) => boolean;
17
+ export declare const storeMailTypes: (database: CacheDatabase, until?: () => boolean) => boolean;
18
+ /**
19
+ * Types the mail of these threads inside the save's own write, plus a little of what is untyped from before: a
20
+ * read-only open cannot keep types, so a store typed only by its first search made that search work out every email
21
+ * (1.5–1.8 s of a 2 s limit on 100,000, cli-testing performance/mail/types). Skipped while a rules change waits to
22
+ * clear the stored types: those are typed again in batches by the next filtered read.
23
+ */
24
+ export declare const typeSavedMail: (database: CacheDatabase, threadIds: readonly number[]) => void;
18
25
  /** Each email's stored type, or for one the store has not typed yet, the type worked out for this read. */
19
26
  export declare const withTypes: <T extends {
20
27
  id: number;
@@ -43,7 +50,7 @@ export declare const typeCondition: (database: CacheDatabase, filter: TypeFilter
43
50
  };
44
51
  /** One sender's mail, counted by type and reach: a shop's receipts and its sales side by side. @experimental */
45
52
  export interface SenderMailTypes {
46
- /** `person:<id>`, `sender-bot:<id>`, or `null` when the store links the address to neither. */
53
+ /** `person:<id>`, `bot:<id>`, or `null` when the store links the address to neither. */
47
54
  ref: string | null;
48
55
  /** The addresses it sent from, lower case. */
49
56
  addresses: string[];
@@ -75,6 +82,11 @@ export declare const mailSenders: (database: CacheDatabase, filter: SenderTypesF
75
82
  };
76
83
  /** @experimental */
77
84
  export interface MailTypeStore {
85
+ /**
86
+ * Indexes and types every email still waiting for it, a short write at a time, until `until` answers true. Mail sync
87
+ * calls it once it has saved, so the first search, also on a read-only open, finds the work done.
88
+ */
89
+ catchUp(until?: () => boolean): Promise<void>;
78
90
  /**
79
91
  * Senders of incoming mail with their mail counted by type and reach, most mail first; a sender is listed when any of
80
92
  * its emails passes `types` and `reaches`.
@@ -84,4 +96,4 @@ export interface MailTypeStore {
84
96
  total: number;
85
97
  }>;
86
98
  }
87
- export declare const mailTypeStore: (database: CacheDatabase) => MailTypeStore;
99
+ export declare const mailTypeStore: (database: CacheDatabase) => Omit<MailTypeStore, "catchUp">;
@@ -107,7 +107,7 @@ export const typesCurrent = (database) => rulesOf(database) === TYPE_RULES && !a
107
107
  * changed, a batch per write so another process never waits long for the lock. A query-only open keeps nothing.
108
108
  * Answers whether every stored type is current.
109
109
  */
110
- export const storeMailTypes = (database) => {
110
+ export const storeMailTypes = (database, until = () => false) => {
111
111
  if (isQueryOnly(database))
112
112
  return typesCurrent(database);
113
113
  if (rulesOf(database) !== TYPE_RULES)
@@ -130,6 +130,8 @@ export const storeMailTypes = (database) => {
130
130
  const keep = database.prepare("UPDATE emails SET mail_type = ?, reach = ?, type_signal = ?, sort_checked = 1 WHERE id = ?");
131
131
  const senders = new Map();
132
132
  for (;;) {
133
+ if (until())
134
+ return false;
133
135
  const more = writeBatch(database, () => {
134
136
  const ids = database
135
137
  .prepare("SELECT id FROM emails WHERE mail_type IS NULL LIMIT ?")
@@ -143,6 +145,35 @@ export const storeMailTypes = (database) => {
143
145
  return true;
144
146
  }
145
147
  };
148
+ /** How many emails whose type was cleared before this save one save also types: the rest fill as mail syncs. */
149
+ const BACKLOG_ON_SAVE = 500;
150
+ /**
151
+ * Types the mail of these threads inside the save's own write, plus a little of what is untyped from before: a
152
+ * read-only open cannot keep types, so a store typed only by its first search made that search work out every email
153
+ * (1.5–1.8 s of a 2 s limit on 100,000, cli-testing performance/mail/types). Skipped while a rules change waits to
154
+ * clear the stored types: those are typed again in batches by the next filtered read.
155
+ */
156
+ export const typeSavedMail = (database, threadIds) => {
157
+ if (rulesOf(database) !== TYPE_RULES) {
158
+ if (database.prepare("SELECT 1 FROM emails WHERE mail_type IS NOT NULL LIMIT 1").get() !== undefined)
159
+ return;
160
+ database
161
+ .prepare("INSERT INTO store_settings (key, value, at) VALUES (?, ?, ?) " +
162
+ "ON CONFLICT (key) DO UPDATE SET value = excluded.value, at = excluded.at")
163
+ .run(RULES_KEY, TYPE_RULES, Date.now());
164
+ }
165
+ const ids = (sql, param) => database
166
+ .prepare(sql)
167
+ .all(param)
168
+ .map((row) => Number(row.id));
169
+ const untyped = new Set([
170
+ ...ids("SELECT id FROM emails WHERE email_thread_id IN (SELECT value FROM json_each(?)) AND mail_type IS NULL", JSON.stringify(threadIds)),
171
+ ...ids("SELECT id FROM emails WHERE mail_type IS NULL LIMIT ?", BACKLOG_ON_SAVE),
172
+ ]);
173
+ const keep = database.prepare("UPDATE emails SET mail_type = ?, reach = ?, type_signal = ?, sort_checked = 1 WHERE id = ?");
174
+ for (const [id, { type, reach, signal }] of typesOf(database, [...untyped]))
175
+ keep.run(type, reach, signal, id);
176
+ };
146
177
  /** Each email's stored type, or for one the store has not typed yet, the type worked out for this read. */
147
178
  export const withTypes = (database, emails) => {
148
179
  const missing = emails.filter((email) => email.mailType === null).map((email) => email.id);
@@ -9,6 +9,7 @@ import { type EmailLocationInput, type FolderEmail, type PartialMailStore } from
9
9
  import { type MailTypeStore, type TypeFilter } from "./email-types.js";
10
10
  import { type MailRulesStore } from "./mail-rules.js";
11
11
  import { type MailSorting } from "./mail-sorting.js";
12
+ import { type MailSubscriptionStore } from "./mail-subscriptions.js";
12
13
  import { type AttachmentInput } from "./meetings.js";
13
14
  import type { StoreContext } from "./open.js";
14
15
  import type { Reach } from "./sender-signals.js";
@@ -216,7 +217,7 @@ export interface SenderScore {
216
217
  demoted?: boolean;
217
218
  }
218
219
  /** Mail in tables of its own: threads, emails, recipients and mailboxes, keyed by account and Message-ID. */
219
- export interface MailStore extends PartialMailStore, MailActivityStore, MailTypeStore {
220
+ export interface MailStore extends PartialMailStore, MailActivityStore, MailTypeStore, MailSubscriptionStore {
220
221
  saveThread(input: ThreadSave): Promise<ThreadDetails>;
221
222
  /** Several threads and sync state in one transaction: a slice of mail commits with its resume point, or not at all. */
222
223
  saveThreads(inputs: ThreadSave[], states?: SyncStateSave[]): Promise<ThreadDetails[]>;
@@ -2,7 +2,7 @@ import { formatLocator } from "../../domain/locator.js";
2
2
  import { formatReference } from "../../domain/references.js";
3
3
  import { fold, normalize } from "../normalize.js";
4
4
  import { mailActivity, threadEmailIds } from "./email-activity.js";
5
- import { chunkAttachments, drainEmailIndex, dropAttachmentChunks, MAIL_PIECES, queueThreads, threadPieces, titleOf, } from "./email-index.js";
5
+ import { catchUpMail, chunkAttachments, drainEmailIndex, dropAttachmentChunks, indexSavedMail, MAIL_PIECES, queueThreads, threadPieces, titleOf, } from "./email-index.js";
6
6
  import { backfillSentAt, folderEmails, forgetLocations, locate, partialMail, setLocations, storedWhole, } from "./email-locations.js";
7
7
  import { markEmailsDeleted, markEmailsRestored, markOwnMail, recountEmailThread as recount, setEmailFlags, } from "./email-state.js";
8
8
  import { mailTypeStore, typeWhere, withTypes } from "./email-types.js";
@@ -13,6 +13,7 @@ import { ensurePerson } from "./identities.js";
13
13
  import { nearestMailPieces } from "./mail-nearest.js";
14
14
  import { mailRulesOver } from "./mail-rules.js";
15
15
  import { mailSortingOver, settleThreads } from "./mail-sorting.js";
16
+ import { mailSubscriptionStore } from "./mail-subscriptions.js";
16
17
  import { attachmentOf, saveAttachment, wordsQuery } from "./meetings.js";
17
18
  import { stemmerCache } from "./stems.js";
18
19
  import { writeState } from "./sync.js";
@@ -444,6 +445,7 @@ export const mailStoreOver = ({ database, orm, now }, stemmerFor = stemmerCache(
444
445
  const id = write(database, () => {
445
446
  const saved = saveThread(database, orm, input);
446
447
  settleThreads({ database, orm, now }, [saved]);
448
+ indexSavedMail(database, stemmerFor, [saved]);
447
449
  return saved;
448
450
  });
449
451
  return threadDetails(database, id);
@@ -452,6 +454,7 @@ export const mailStoreOver = ({ database, orm, now }, stemmerFor = stemmerCache(
452
454
  const ids = write(database, () => {
453
455
  const saved = inputs.map((input) => saveThread(database, orm, input));
454
456
  settleThreads({ database, orm, now }, saved);
457
+ indexSavedMail(database, stemmerFor, saved);
455
458
  for (const { accountId, name, value } of states)
456
459
  writeState({ orm, now }, accountId, name, value);
457
460
  return saved;
@@ -497,6 +500,8 @@ export const mailStoreOver = ({ database, orm, now }, stemmerFor = stemmerCache(
497
500
  ...partialMail(database),
498
501
  ...mailActivity(database),
499
502
  ...mailTypeStore(database),
503
+ catchUp: async (until) => catchUpMail(database, stemmerFor, until),
504
+ ...mailSubscriptionStore(database),
500
505
  async emailFacts(filter = {}) {
501
506
  const [where, params] = emailWhere(database, filter);
502
507
  return database
@@ -20,7 +20,7 @@ export declare const ENTITY_TABLES: {
20
20
  readonly pipeline: "pipelines";
21
21
  readonly account: "accounts";
22
22
  readonly attachment: "attachments";
23
- readonly bot: "bots";
23
+ readonly agent: "bots";
24
24
  readonly calendar_entry: "calendar_entries";
25
25
  readonly chat: "chats";
26
26
  readonly conversation: "conversations";
@@ -7,7 +7,7 @@ export const ENTITY_TABLES = {
7
7
  ...RECORD_TABLES,
8
8
  account: "accounts",
9
9
  attachment: "attachments",
10
- bot: "bots",
10
+ agent: "bots",
11
11
  calendar_entry: "calendar_entries",
12
12
  chat: "chats",
13
13
  conversation: "conversations",
@@ -236,7 +236,7 @@ export const evidenceFindingsStoreOver = (context) => {
236
236
  return stale();
237
237
  }
238
238
  }
239
- if (proposal.proposedBy.type !== "bot" || !proposal.proposedBy.name)
239
+ if (proposal.proposedBy.type !== "agent" || !proposal.proposedBy.name)
240
240
  return invalid("a findings author must be an agent");
241
241
  const agent = {
242
242
  bot: proposal.proposedBy.name,
@@ -11,7 +11,7 @@ import { requiredThing } from "./notes.js";
11
11
  import { pageOfRows } from "./rows-page.js";
12
12
  import { closeSourceReviews, eraseSourceReviews, sourceReviewOf } from "./source-review-marks.js";
13
13
  import { write } from "./transaction.js";
14
- const NAMED = "SELECT f.*, b.name AS author_name, b.kind AS author_kind FROM facts f LEFT JOIN bots b ON f.author_type = 'bot' AND b.id = f.author_id";
14
+ const NAMED = "SELECT f.*, b.name AS author_name, b.kind AS author_kind FROM facts f LEFT JOIN bots b ON f.author_type = 'agent' AND b.id = f.author_id";
15
15
  const iso = (value) => new Date(Number(value)).toISOString();
16
16
  const oneOf = (value, allowed, what) => {
17
17
  if (typeof value !== "string" || !allowed.includes(value))
@@ -15,9 +15,9 @@ const isFinanceType = (type) => FINANCE_TYPES.includes(type);
15
15
  /** Money settled by confirmed payments only: a proposed payment promises nothing yet. */
16
16
  const PAID = netPaidSql("i.id");
17
17
  const INVOICES = `SELECT i.*, ${PAID} AS paid, b.name AS author_name, b.kind AS author_kind FROM invoices i ` +
18
- "LEFT JOIN bots b ON i.author_type = 'bot' AND b.id = i.author_id";
18
+ "LEFT JOIN bots b ON i.author_type = 'agent' AND b.id = i.author_id";
19
19
  const PAYMENTS = "SELECT p.*, (SELECT coalesce(sum(amount), 0) FROM payment_allocations WHERE payment_id = p.id) AS allocated, " +
20
- "b.name AS author_name, b.kind AS author_kind FROM payments p LEFT JOIN bots b ON p.author_type = 'bot' AND b.id = p.author_id";
20
+ "b.name AS author_name, b.kind AS author_kind FROM payments p LEFT JOIN bots b ON p.author_type = 'agent' AND b.id = p.author_id";
21
21
  export const financeOperationsOver = (context) => {
22
22
  const { database, now } = context;
23
23
  const { partyOf, partyThing, reviewedOf, written, keepEvidence, ownerOnly, linkedId, decideRow, mayChangeParts } = reviewedRowsOver(context);
@@ -161,6 +161,7 @@ export const knowledgeStoreOver = (context) => {
161
161
  if (parsed.type === "entity" ||
162
162
  parsed.type === "memory" ||
163
163
  parsed.type === "fact" ||
164
+ parsed.type === "agent" ||
164
165
  parsed.type === "bot" ||
165
166
  parsed.type === "event" ||
166
167
  parsed.type === "meeting" ||
@@ -527,7 +527,7 @@ export const mailFindingsStoreOver = (context) => {
527
527
  const chosen = pendingOf(batch.input, input.decided).findings.filter((finding) => accepted.includes(finding.id));
528
528
  if (chosen.length)
529
529
  cite(chosen, account, true);
530
- if (proposal.proposedBy.type !== "bot" || !proposal.proposedBy.name)
530
+ if (proposal.proposedBy.type !== "agent" || !proposal.proposedBy.name)
531
531
  return invalid("a findings author must be an agent");
532
532
  const agent = {
533
533
  bot: proposal.proposedBy.name,
@@ -100,7 +100,7 @@ export interface MailSorting {
100
100
  /** Takes back the owner's newest add or removal not yet undone; `null` when there is none. */
101
101
  undo(by: Decider): Promise<SortUndo | null>;
102
102
  /**
103
- * The owner's manual sorting of one sender, an address or a `person:` or `sender-bot:` ref, removed: its address
103
+ * The owner's manual sorting of one sender, an address or a `person:` or `bot:` ref, removed: its address
104
104
  * rules and its one-mail rules. Domain and list rules stay. Answers the rules removed.
105
105
  */
106
106
  reset(sender: string, by: Decider): Promise<SortRule[]>;