@wirecat/cli-core 0.616.0 → 0.618.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 (57) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/dist/background/backfill.d.ts +21 -0
  3. package/dist/background/backfill.js +41 -0
  4. package/dist/background/report/messages.js +4 -1
  5. package/dist/background/report/view.js +4 -1
  6. package/dist/background/schedules.d.ts +17 -0
  7. package/dist/background/schedules.js +21 -8
  8. package/dist/cli/context.d.ts +5 -0
  9. package/dist/cli/index.d.ts +3 -2
  10. package/dist/cli/index.js +3 -2
  11. package/dist/cli/messenger/serve-command.js +24 -2
  12. package/dist/cli/messenger/serve-outdated.d.ts +22 -0
  13. package/dist/cli/messenger/serve-outdated.js +100 -0
  14. package/dist/cli/schedule/schedule-command.d.ts +9 -0
  15. package/dist/cli/schedule/schedule-command.js +13 -0
  16. package/dist/cli/store-recover.js +26 -2
  17. package/dist/domain/links.d.ts +17 -4
  18. package/dist/domain/links.js +20 -7
  19. package/dist/domain/models.d.ts +6 -0
  20. package/dist/domain/relations.d.ts +15 -0
  21. package/dist/domain/relations.js +23 -0
  22. package/dist/errors/reasons.js +7 -0
  23. package/dist/index.d.ts +2 -2
  24. package/dist/index.js +2 -2
  25. package/dist/meetings/mcp/index.d.ts +15 -15
  26. package/dist/services/link-scorers/chat-senders.js +39 -29
  27. package/dist/services/link-scorers/member-chats.js +4 -3
  28. package/dist/services/link-scorers/member-dialog.js +5 -7
  29. package/dist/services/link-scorers/scan.js +17 -8
  30. package/dist/services/link-scorers/shared.d.ts +6 -2
  31. package/dist/services/link-scorers/shared.js +6 -2
  32. package/dist/services/link-scorers/types.d.ts +2 -0
  33. package/dist/store/migrations.d.ts +1 -1
  34. package/dist/store/migrations.js +35 -12
  35. package/dist/store/recover.d.ts +34 -0
  36. package/dist/store/recover.js +188 -6
  37. package/dist/store/refill.d.ts +28 -0
  38. package/dist/store/refill.js +120 -0
  39. package/dist/store/sqlite/bot-tokens.d.ts +11 -0
  40. package/dist/store/sqlite/bot-tokens.js +57 -0
  41. package/dist/store/sqlite/chats.js +2 -0
  42. package/dist/store/sqlite/clients.d.ts +7 -3
  43. package/dist/store/sqlite/clients.js +11 -7
  44. package/dist/store/sqlite/email-index.js +9 -11
  45. package/dist/store/sqlite/knowledge.js +3 -1
  46. package/dist/store/sqlite/messages.d.ts +1 -1
  47. package/dist/store/sqlite/messages.js +3 -1
  48. package/dist/store/sqlite/note-index.js +9 -7
  49. package/dist/store/sqlite/notes.d.ts +1 -1
  50. package/dist/store/sqlite/notes.js +8 -6
  51. package/dist/store/sqlite/open-store.js +2 -0
  52. package/dist/store/sqlite/relation-list.js +2 -0
  53. package/dist/store/sqlite/relation-proposals.d.ts +12 -1
  54. package/dist/store/sqlite/relation-proposals.js +50 -11
  55. package/dist/store/sqlite/transaction.d.ts +13 -0
  56. package/dist/store/sqlite/transaction.js +25 -17
  57. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  import type { Id } from "../../domain/models.js";
2
2
  import type { MessageStore } from "../../store/store.js";
3
3
  import type { AccountKey } from "../../store/types.js";
4
- import type { ScannedProject } from "./types.js";
4
+ import type { ScannedProject, ScorerInput } from "./types.js";
5
5
  /** A whole-word test, the rule the evidence lanes and meeting candidates use: «Harbour» is not in «Harbourside». */
6
6
  export declare const wholeWords: (term: string) => RegExp;
7
7
  /** The project's name, key and aliases, each once. */
@@ -15,7 +15,7 @@ export declare const sameAccount: (a: AccountKey, b: {
15
15
  account: string;
16
16
  }) => boolean;
17
17
  /** The person an identity is, as `person:<uid>`; `undefined` when the store has no person for it. */
18
- export declare const personRefOf: (store: MessageStore, provider: string, id: Id) => Promise<string | undefined>;
18
+ export declare const personRefOf: (input: Pick<ScorerInput, "store" | "remember">, provider: string, id: Id) => Promise<string | undefined>;
19
19
  /** How many projects a person is a confirmed member of, counting `project` whether confirmed or only found. */
20
20
  export declare const projectsOf: (store: MessageStore, person: string, project: string) => Promise<number>;
21
21
  /** Each confirmed member's identities in one messenger, by member. */
@@ -23,4 +23,8 @@ export declare const identitiesIn: (store: MessageStore, people: readonly string
23
23
  person: string;
24
24
  id: string;
25
25
  }[]>;
26
+ /** What `read` gives, once per scan when the scan remembers. */
27
+ export declare const remembered: <T>(input: Pick<ScorerInput, "remember">, key: string, read: () => Promise<T>) => Promise<T>;
28
+ /** A member's chats in one account, read once per scan by every scorer that asks. */
29
+ export declare const chatsWithOf: (input: Pick<ScorerInput, "store" | "remember">, key: AccountKey, id: string) => Promise<import("../../domain/models.js").Chat[]>;
26
30
  export declare const aborted: (signal: AbortSignal | undefined) => void;
@@ -27,8 +27,8 @@ export const chatRef = (key, chat) => formatReference({ type: "chat", provider:
27
27
  export const contactRef = (provider, id) => formatReference({ type: "contact", provider, id: String(id) });
28
28
  export const sameAccount = (a, b) => a.provider === b.provider && String(a.account) === b.account;
29
29
  /** The person an identity is, as `person:<uid>`; `undefined` when the store has no person for it. */
30
- export const personRefOf = async (store, provider, id) => {
31
- const person = await store.people.personOf({ provider, id });
30
+ export const personRefOf = async (input, provider, id) => {
31
+ const person = await remembered(input, `person-of\u0000${provider}\u0000${String(id)}`, () => input.store.people.personOf({ provider, id }));
32
32
  return person ? `person:${person.uid}` : undefined;
33
33
  };
34
34
  /** How many projects a person is a confirmed member of, counting `project` whether confirmed or only found. */
@@ -49,4 +49,8 @@ export const identitiesIn = async (store, people, provider) => {
49
49
  }
50
50
  return found;
51
51
  };
52
+ /** What `read` gives, once per scan when the scan remembers. */
53
+ export const remembered = (input, key, read) => input.remember ? input.remember(key, read) : read();
54
+ /** A member's chats in one account, read once per scan by every scorer that asks. */
55
+ export const chatsWithOf = (input, key, id) => remembered(input, `chats-with\u0000${key.provider}\u0000${key.account}\u0000${id}`, () => input.store.chats.chatsWith(key, id));
52
56
  export const aborted = (signal) => signal?.throwIfAborted();
@@ -45,6 +45,8 @@ export interface ScorerInput {
45
45
  /** The owner's `person:` reference, never a candidate. */
46
46
  owner: string | null;
47
47
  signal?: AbortSignal;
48
+ /** One scan's memory of a read: a spreading scorer runs again each pass and would read the same chats again. */
49
+ remember?: <T>(key: string, read: () => Promise<T>) => Promise<T>;
48
50
  }
49
51
  export interface LinkScorer {
50
52
  readonly id: string;
@@ -27,7 +27,7 @@ export interface Migration {
27
27
  export declare const MIGRATIONS: Migration[];
28
28
  /**
29
29
  * Brings the file up to this version, or opens a newer one it can still write to, or refuses.
30
- * Inside `BEGIN IMMEDIATE`, so two processes opening an old file at once migrate it once. A migration
30
+ * A file that needs work is migrated inside `BEGIN IMMEDIATE`, so two processes opening an old file at once migrate it once. A migration
31
31
  * that fails names `store reset` when the app has one: without it the owner is stuck until a build that can migrate
32
32
  * the file. An app without that command (drive) passes no `command`, and the advice names none.
33
33
  */
@@ -1,7 +1,8 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { lockedOutNotice, recordClient, refusalAdvice, storeClients } from "./sqlite/clients.js";
2
+ import { clientRecorded, lockedOutNotice, recordClient, refusalAdvice, storeClients } from "./sqlite/clients.js";
3
3
  import { generatedMigrations } from "./sqlite/manifest.js";
4
4
  import { discardRollbackCopy, recordRollbackCopy, takeRollbackCopy, } from "./sqlite/rollback-copy.js";
5
+ import { beginImmediate, rollBack } from "./sqlite/transaction.js";
5
6
  /**
6
7
  * Every migration is generated by drizzle-kit and numbered in `sqlite/manifest.ts`. Version 1 creates the whole
7
8
  * schema. **A migration that has reached anyone's file is never edited.** After it: forward-only and additive —
@@ -33,6 +34,30 @@ const fileState = (database) => {
33
34
  .get();
34
35
  return { version: Number(row?.version ?? 0), minCompatible: Number(row?.min_compatible ?? 0) };
35
36
  };
37
+ const refuseForeignOrNewer = (database, file, { ours, ownTable, command }) => {
38
+ if (file.version > 0 && ownTable !== null && !hasTable(database, ownTable)) {
39
+ throw new CliError("configuration_error", `the message store was written by another, incompatible tool (schema ${file.version} by its own numbering, ` +
40
+ "with no meetings table) — this tool will not open or change it; move it aside to start a new store");
41
+ }
42
+ if (file.version > ours && file.minCompatible > ours) {
43
+ throw new CliError("configuration_error", `the message store was written by a newer version (schema ${file.version}, needs at least ` +
44
+ `${file.minCompatible}; this one speaks ${ours}) — ${refusalAdvice(storeClients(database), command, file.version)}`);
45
+ }
46
+ };
47
+ /**
48
+ * Every writable open runs `migrate`, and most find the file current. Taking the write lock just to learn that queues
49
+ * each open behind the sync writers, so a current file is checked without it.
50
+ */
51
+ const current = (database, ours, client, now) => {
52
+ if (!hasTable(database, "schema_migrations"))
53
+ return undefined;
54
+ const file = fileState(database);
55
+ if (file.version < ours)
56
+ return undefined;
57
+ if (client && !clientRecorded(database, { ...client, speaks: ours }, now()))
58
+ return undefined;
59
+ return file;
60
+ };
36
61
  /** The tables every pending migration that raises `minCompatible` names; none for a new file or a foreign one. */
37
62
  const copyBeforeBreaking = (database, migrations, { ownTable, now }, options) => {
38
63
  if (!hasTable(database, "schema_migrations"))
@@ -55,14 +80,19 @@ const copyBeforeBreaking = (database, migrations, { ownTable, now }, options) =>
55
80
  };
56
81
  /**
57
82
  * Brings the file up to this version, or opens a newer one it can still write to, or refuses.
58
- * Inside `BEGIN IMMEDIATE`, so two processes opening an old file at once migrate it once. A migration
83
+ * A file that needs work is migrated inside `BEGIN IMMEDIATE`, so two processes opening an old file at once migrate it once. A migration
59
84
  * that fails names `store reset` when the app has one: without it the owner is stuck until a build that can migrate
60
85
  * the file. An app without that command (drive) passes no `command`, and the advice names none.
61
86
  */
62
87
  export const migrate = (database, { migrations = MIGRATIONS, now = Date.now, command, version, ownTable = OWN_TABLE, rollback, } = {}) => {
63
88
  const ours = latest(migrations);
89
+ const settled = current(database, ours, command && version ? { command, version } : undefined, now);
90
+ if (settled) {
91
+ refuseForeignOrNewer(database, settled, { ours, ownTable, command });
92
+ return undefined;
93
+ }
64
94
  let copy = rollback ? copyBeforeBreaking(database, migrations, { ownTable, now }, rollback) : undefined;
65
- database.exec("BEGIN IMMEDIATE");
95
+ beginImmediate(database);
66
96
  try {
67
97
  database.exec(HISTORY);
68
98
  const file = fileState(database);
@@ -71,14 +101,7 @@ export const migrate = (database, { migrations = MIGRATIONS, now = Date.now, com
71
101
  discardRollbackCopy(copy);
72
102
  copy = undefined;
73
103
  }
74
- if (file.version > 0 && ownTable !== null && !hasTable(database, ownTable)) {
75
- throw new CliError("configuration_error", `the message store was written by another, incompatible tool (schema ${file.version} by its own numbering, ` +
76
- "with no meetings table) — this tool will not open or change it; move it aside to start a new store");
77
- }
78
- if (file.version > ours && file.minCompatible > ours) {
79
- throw new CliError("configuration_error", `the message store was written by a newer version (schema ${file.version}, needs at least ` +
80
- `${file.minCompatible}; this one speaks ${ours}) — ${refusalAdvice(storeClients(database), command, file.version)}`);
81
- }
104
+ refuseForeignOrNewer(database, file, { ours, ownTable, command });
82
105
  const raisedTo = migrations
83
106
  .filter((migration) => migration.version > file.version)
84
107
  .reduce((highest, { minCompatible }) => Math.max(highest, minCompatible), file.minCompatible);
@@ -107,7 +130,7 @@ export const migrate = (database, { migrations = MIGRATIONS, now = Date.now, com
107
130
  return notice;
108
131
  }
109
132
  catch (error) {
110
- database.exec("ROLLBACK");
133
+ rollBack(database);
111
134
  if (error instanceof CliError)
112
135
  throw error;
113
136
  const cause = error instanceof Error ? error.message : String(error);
@@ -1,5 +1,6 @@
1
1
  import type { CacheDatabase } from "./driver.js";
2
2
  import { type InvalidJson, type StoreHealth } from "./health.js";
3
+ import { type Refetch } from "./refill.js";
3
4
  /** `contentless_delete`, which every word index uses, came in SQLite 3.43. */
4
5
  export declare const SQLITE3_MINIMUM: readonly [3, 43, 0];
5
6
  export declare const sqlite3Program: (program?: string) => {
@@ -21,6 +22,23 @@ export declare const storeHolders: (path: string) => {
21
22
  }[] | undefined;
22
23
  /** Rows per table that holds data; `null` where the table cannot be counted. Search shadow tables are left out. */
23
24
  export declare const tableRows: (database: CacheDatabase) => Record<string, number | null>;
25
+ export interface IndexedButGone {
26
+ rows: number;
27
+ index: string;
28
+ }
29
+ /**
30
+ * Per table, the most entries one index of the damaged file holds that its table no longer has: rows, or a later
31
+ * change to them, that were lost before the recovery read the file. A stale page written over a table leaves its
32
+ * indexes as they were; one written over the index too leaves no trace, so this is a lower bound. Partial and
33
+ * expression indexes are left out: a plain scan cannot read them alone.
34
+ */
35
+ export declare const indexedButGone: (database: CacheDatabase) => Record<string, IndexedButGone>;
36
+ /**
37
+ * Puts back each row `.recover` found on a page no table claims into the one data table whose columns its values fit:
38
+ * a stale page copied over a table cuts committed rows off it, still readable. A row that fits no table, or more
39
+ * than one, stays out and is counted with the rest; a row whose key the table already holds leaves the table's row.
40
+ */
41
+ export declare const placeLostRows: (database: CacheDatabase) => Record<string, number>;
24
42
  /**
25
43
  * Copies every row SQLite can still read into a new file with the `sqlite3` program's `.recover`: node:sqlite has
26
44
  * no recovery API. The damaged file is opened read-only. Rows that fit no table go to a table the rebuild counts
@@ -68,6 +86,13 @@ export interface LostRows {
68
86
  before: number | null;
69
87
  read: number;
70
88
  kept: number;
89
+ /**
90
+ * Rows known to be gone after the recovery: an index of the damaged file lists them and its table did not hold
91
+ * them, less the rows put back from pages no table claimed. Rows lost without a trace are not in it.
92
+ */
93
+ goneAtLeast: number;
94
+ /** The index that showed them. */
95
+ seenIn: string | null;
71
96
  }
72
97
  export interface Recovery {
73
98
  path: string;
@@ -78,6 +103,13 @@ export interface Recovery {
78
103
  * `.recover` found, `kept` what fit the table; rows on pages it could not read at all are in none of them.
79
104
  */
80
105
  lost: LostRows[];
106
+ /** Per table, rows found on pages no table claimed and put back. */
107
+ placed: Record<string, number>;
108
+ /**
109
+ * The last deep check that passed before this recovery. A damaged file cannot show every row it lost, so whatever
110
+ * was written since may be gone without a count.
111
+ */
112
+ lastKnownGood: string | null;
81
113
  dangling: DanglingRows[];
82
114
  /** Values that were not valid JSON: set to NULL, or the row dropped where `required`. */
83
115
  invalidJson: InvalidJson[];
@@ -85,6 +117,8 @@ export interface Recovery {
85
117
  account: string;
86
118
  emails: number;
87
119
  }[];
120
+ /** What was marked not fetched, from a day before `lastKnownGood` on, so the next ordinary sync fetches it again. */
121
+ refetch: Refetch;
88
122
  rebuilt: DerivedRebuild;
89
123
  copyErrors: string[];
90
124
  health: StoreHealth;
@@ -7,14 +7,16 @@ import { holdersOf } from "../background/processes.js";
7
7
  import { isStoreDamage } from "../errors/failures.js";
8
8
  import { fileSchemaOf } from "./compatibility.js";
9
9
  import { fts5Tables, invalidJson, storeHealth } from "./health.js";
10
- import { recordDeepCheck } from "./marks.js";
10
+ import { readHealthMark, recordDeepCheck } from "./marks.js";
11
11
  import { migrate } from "./migrations.js";
12
+ import { forgetCoverageSince, REFILL_MARGIN_MS } from "./refill.js";
12
13
  import { resetAttachmentWords } from "./sqlite/attachment-texts.js";
13
14
  import { involvementStoreOver } from "./sqlite/involvements.js";
14
15
  import { drainMeetingIndex } from "./sqlite/meetings.js";
15
16
  import { rebuildMentions } from "./sqlite/mentions.js";
16
17
  import { CORPORA, drainCorpus, fillTrigrams, resetNoteIndex } from "./sqlite/note-index.js";
17
18
  import { openSqlite } from "./sqlite/open.js";
19
+ import { isDerivedTable } from "./sqlite/rollback-copy.js";
18
20
  import { fillSearchIndex, resetSearchIndex } from "./sqlite/search-index.js";
19
21
  import { stemmerCache } from "./sqlite/stems.js";
20
22
  import { fillStems, resetStems } from "./sqlite/stems-fill.js";
@@ -137,15 +139,18 @@ export const storeHolders = (path) => {
137
139
  return { pid, name };
138
140
  });
139
141
  };
140
- /** Rows per table that holds data; `null` where the table cannot be counted. Search shadow tables are left out. */
141
- export const tableRows = (database) => {
142
+ const dataTables = (database) => {
142
143
  const indexes = fts5Tables(database).map((index) => index.name);
143
- const tables = database
144
+ return database
144
145
  .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND rootpage > 0 AND name NOT LIKE 'sqlite_%' " +
145
146
  "AND name NOT LIKE 'vector_index_%' ORDER BY name")
146
147
  .all()
147
148
  .map((row) => String(row.name))
148
149
  .filter((name) => !indexes.some((index) => name.startsWith(`${index}_`)));
150
+ };
151
+ /** Rows per table that holds data; `null` where the table cannot be counted. Search shadow tables are left out. */
152
+ export const tableRows = (database) => {
153
+ const tables = dataTables(database);
149
154
  return Object.fromEntries(tables.map((table) => {
150
155
  try {
151
156
  return [table, Number(database.prepare(`SELECT count(*) AS n FROM "${table}"`).get()?.n)];
@@ -155,6 +160,162 @@ export const tableRows = (database) => {
155
160
  }
156
161
  }));
157
162
  };
163
+ /** The tables that hold the owner's data and have a rowid: the others are rebuilt from them, or keyed otherwise. */
164
+ const sourceTables = (database) => {
165
+ const withoutRowid = new Set(database
166
+ .prepare("SELECT name FROM pragma_table_list WHERE wr = 1")
167
+ .all()
168
+ .map((row) => String(row.name)));
169
+ return dataTables(database).filter((table) => table !== LOST_AND_FOUND && !withoutRowid.has(table) && !isDerivedTable(table));
170
+ };
171
+ /**
172
+ * Per table, the most entries one index of the damaged file holds that its table no longer has: rows, or a later
173
+ * change to them, that were lost before the recovery read the file. A stale page written over a table leaves its
174
+ * indexes as they were; one written over the index too leaves no trace, so this is a lower bound. Partial and
175
+ * expression indexes are left out: a plain scan cannot read them alone.
176
+ */
177
+ export const indexedButGone = (database) => {
178
+ const found = {};
179
+ for (const table of sourceTables(database)) {
180
+ const indexes = database
181
+ .prepare("SELECT name FROM pragma_index_list(?) WHERE partial = 0 ORDER BY name")
182
+ .all(table)
183
+ .map((row) => String(row.name));
184
+ for (const index of indexes) {
185
+ const columns = database
186
+ .prepare("SELECT cid, name FROM pragma_index_xinfo(?) WHERE key = 1 ORDER BY seqno")
187
+ .all(index);
188
+ if (columns.some((column) => Number(column.cid) < 0))
189
+ continue;
190
+ const keys = columns.map((column) => `"${String(column.name)}"`).join(", ");
191
+ const grouped = `${keys}, row_id`;
192
+ let rows;
193
+ try {
194
+ // Not EXCEPT: SQLite may merge it on the index's own order, which a damaged index does not keep.
195
+ rows = Number(database
196
+ .prepare(`SELECT count(*) AS n FROM (SELECT 1 FROM (SELECT ${keys}, rowid AS row_id, 1 AS side FROM "${table}" ` +
197
+ `INDEXED BY "${index}" UNION ALL SELECT ${keys}, rowid, 2 FROM "${table}" NOT INDEXED) ` +
198
+ `GROUP BY ${grouped} HAVING max(side) = 1)`)
199
+ .get()?.n);
200
+ }
201
+ catch {
202
+ continue;
203
+ }
204
+ if (rows > (found[table]?.rows ?? 0))
205
+ found[table] = { rows, index };
206
+ }
207
+ }
208
+ return found;
209
+ };
210
+ /** The storage types a value read back from a column of this declared type can have: SQLite's affinity rules. */
211
+ const storedAs = (declared) => {
212
+ const type = declared.toUpperCase();
213
+ if (type.includes("INT"))
214
+ return ["integer"];
215
+ if (/CHAR|CLOB|TEXT/.test(type))
216
+ return ["text"];
217
+ if (type === "" || type.includes("BLOB"))
218
+ return null;
219
+ if (/REAL|FLOA|DOUB/.test(type))
220
+ return ["real", "integer"];
221
+ return null;
222
+ };
223
+ const columnsOf = (database, table) => {
224
+ const all = database
225
+ .prepare('SELECT name, type, "notnull" AS required, dflt_value, pk FROM pragma_table_info(?)')
226
+ .all(table);
227
+ const keys = all.filter((column) => Number(column.pk) > 0);
228
+ return all.map((column) => ({
229
+ name: String(column.name),
230
+ type: String(column.type),
231
+ required: Number(column.required) === 1,
232
+ hasDefault: column.dflt_value !== null,
233
+ rowid: keys.length === 1 && Number(column.pk) === 1 && String(column.type).toUpperCase() === "INTEGER",
234
+ }));
235
+ };
236
+ /** A row with fewer fields than the table was written before a column was added; the rest take their defaults. */
237
+ const fits = (columns, fields, types) => fields <= columns.length &&
238
+ columns.every((column, at) => {
239
+ if (at >= fields)
240
+ return !column.required || column.hasDefault;
241
+ const type = types[at];
242
+ if (column.rowid)
243
+ return type === "null" || type === "integer";
244
+ if (type === "null")
245
+ return !column.required;
246
+ const allowed = storedAs(column.type);
247
+ return allowed === null || allowed.includes(type);
248
+ });
249
+ /**
250
+ * Puts back each row `.recover` found on a page no table claims into the one data table whose columns its values fit:
251
+ * a stale page copied over a table cuts committed rows off it, still readable. A row that fits no table, or more
252
+ * than one, stays out and is counted with the rest; a row whose key the table already holds leaves the table's row.
253
+ */
254
+ export const placeLostRows = (database) => {
255
+ if (!database.prepare("SELECT 1 FROM sqlite_master WHERE name = ?").get(LOST_AND_FOUND))
256
+ return {};
257
+ const fields = database
258
+ .prepare("SELECT name FROM pragma_table_info(?) WHERE name GLOB 'c[0-9]*'")
259
+ .all(LOST_AND_FOUND)
260
+ .map((row) => String(row.name));
261
+ const tables = sourceTables(database).map((table) => ({ table, columns: columnsOf(database, table) }));
262
+ const rows = database
263
+ .prepare(`SELECT rowid AS at, nfield, ${fields.map((field) => `typeof(${field}) AS "${field}"`).join(", ")} ` +
264
+ `FROM ${LOST_AND_FOUND} WHERE id IS NOT NULL`)
265
+ .all();
266
+ const placed = {};
267
+ // As `.recover` writes rows: before the triggers exist, whose search indexes here are the damaged ones copied.
268
+ const triggers = [];
269
+ const quiet = (table) => {
270
+ if (table in placed)
271
+ return;
272
+ placed[table] = 0;
273
+ for (const row of database
274
+ .prepare("SELECT name, sql FROM sqlite_master WHERE type = 'trigger' AND tbl_name = ?")
275
+ .all(table)) {
276
+ triggers.push(String(row.sql));
277
+ database.exec(`DROP TRIGGER "${String(row.name)}"`);
278
+ }
279
+ };
280
+ database.exec("PRAGMA foreign_keys = OFF");
281
+ database.exec("BEGIN");
282
+ try {
283
+ for (const row of rows) {
284
+ const count = Number(row.nfield);
285
+ const types = fields.slice(0, count).map((field) => String(row[field]));
286
+ const fitting = tables.filter(({ columns }) => fits(columns, count, types));
287
+ if (fitting.length !== 1)
288
+ continue;
289
+ const { table, columns } = fitting[0];
290
+ quiet(table);
291
+ const given = columns.slice(0, count);
292
+ const names = [...(given.some((column) => column.rowid) ? [] : ["rowid"]), ...given.map((column) => column.name)];
293
+ const values = [
294
+ ...(given.some((column) => column.rowid) ? [] : ["id"]),
295
+ ...given.map((column, at) => (column.rowid ? "id" : `c${at}`)),
296
+ ];
297
+ const inserted = database
298
+ .prepare(`INSERT OR IGNORE INTO "${table}" (${names.map((name) => `"${name}"`).join(", ")}) ` +
299
+ `SELECT ${values.join(", ")} FROM ${LOST_AND_FOUND} WHERE rowid = ?`)
300
+ .run(Number(row.at));
301
+ if (Number(inserted.changes) === 0)
302
+ continue;
303
+ placed[table] = (placed[table] ?? 0) + 1;
304
+ database.prepare(`DELETE FROM ${LOST_AND_FOUND} WHERE rowid = ?`).run(Number(row.at));
305
+ }
306
+ for (const sql of triggers)
307
+ database.exec(sql);
308
+ database.exec("COMMIT");
309
+ }
310
+ catch (error) {
311
+ database.exec("ROLLBACK");
312
+ throw error;
313
+ }
314
+ finally {
315
+ database.exec("PRAGMA foreign_keys = ON");
316
+ }
317
+ return Object.fromEntries(Object.entries(placed).filter(([, rows]) => rows > 0));
318
+ };
158
319
  /**
159
320
  * Copies every row SQLite can still read into a new file with the `sqlite3` program's `.recover`: node:sqlite has
160
321
  * no recovery API. The damaged file is opened read-only. Rows that fit no table go to a table the rebuild counts
@@ -406,6 +567,9 @@ const recoverLocked = async ({ path, command, version, sqlite3, now, note, copy,
406
567
  throw new CliError("configuration_error", "the store file's header or schema is damaged, so its tables cannot be listed and it cannot be recovered; " +
407
568
  "the file was left as it was", { reason: "store.unreadable" });
408
569
  }
570
+ note("looking for rows the indexes list and the tables no longer hold");
571
+ const gone = indexedButGone(watch);
572
+ const lastKnownGood = readHealthMark(path)?.last_ok_at ?? null;
409
573
  const before = { data: dataVersion(), inode: statSync(path).ino };
410
574
  const stamp = new Date(now()).toISOString().replace(/[:.]/g, "-");
411
575
  const target = `${path}.recovering-${stamp}`;
@@ -435,7 +599,10 @@ const recoverLocked = async ({ path, command, version, sqlite3, now, note, copy,
435
599
  let json;
436
600
  let fetch;
437
601
  let schema;
602
+ let placed;
603
+ let refetch;
438
604
  try {
605
+ placed = placeLostRows(opened.database);
439
606
  kept = tableRows(opened.database);
440
607
  migrate(opened.database, { command, ...(version ? { version } : {}) });
441
608
  note("clearing values that are not valid JSON");
@@ -444,6 +611,8 @@ const recoverLocked = async ({ path, command, version, sqlite3, now, note, copy,
444
611
  note("looking for rows that point at rows that were lost");
445
612
  dangling = danglingRows(opened.database);
446
613
  fetch = mailToFetch(opened.database);
614
+ const good = lastKnownGood === null ? Number.NaN : Date.parse(lastKnownGood);
615
+ refetch = forgetCoverageSince(opened.database, Number.isNaN(good) ? null : good - REFILL_MARGIN_MS, now());
447
616
  schema = fileSchemaOf(opened.database).version;
448
617
  opened.database.exec("PRAGMA wal_checkpoint(TRUNCATE)");
449
618
  }
@@ -475,17 +644,30 @@ const recoverLocked = async ({ path, command, version, sqlite3, now, note, copy,
475
644
  renameSync(`${target}${suffix}`, `${path}${suffix}`);
476
645
  recordDeepCheck(path, health, { cli: command, ...(version ? { version } : {}), schema, now });
477
646
  const lost = Object.entries(rowsBefore)
478
- .map(([table, before]) => ({ table, before, read: read[table] ?? 0, kept: kept[table] ?? 0 }))
479
- .filter(({ before, read, kept }) => before === null || before > kept || read > kept);
647
+ .map(([table, before]) => {
648
+ const goneAtLeast = Math.max(0, (gone[table]?.rows ?? 0) - (placed[table] ?? 0));
649
+ return {
650
+ table,
651
+ before,
652
+ read: read[table] ?? 0,
653
+ kept: kept[table] ?? 0,
654
+ goneAtLeast,
655
+ seenIn: goneAtLeast > 0 ? (gone[table]?.index ?? null) : null,
656
+ };
657
+ })
658
+ .filter(({ before, read, kept, goneAtLeast }) => before === null || before > kept || read > kept || goneAtLeast > 0);
480
659
  const seconds = (from, to) => Math.round((to - from) / 100) / 10;
481
660
  return {
482
661
  path,
483
662
  keptAt,
484
663
  sqlite3: program.version,
485
664
  lost,
665
+ placed,
666
+ lastKnownGood,
486
667
  dangling,
487
668
  invalidJson: json,
488
669
  mailToFetch: fetch,
670
+ refetch,
489
671
  rebuilt,
490
672
  copyErrors,
491
673
  health,
@@ -0,0 +1,28 @@
1
+ import type { CacheDatabase } from "./driver.js";
2
+ /**
3
+ * How far before the last deep check that passed the coverage is forgotten: a message is written when a sync or a
4
+ * serve gets it, which can be hours after it was sent, and the cut is by send time.
5
+ */
6
+ export declare const REFILL_MARGIN_MS = 86400000;
7
+ export interface Refetch {
8
+ /** What was held from this time on is marked not fetched; `null` when no deep check ever passed: all of it. */
9
+ since: string | null;
10
+ /** Per messenger account, the chats whose held stretches were cut. */
11
+ chats: {
12
+ provider: string;
13
+ account: string;
14
+ chats: number;
15
+ }[];
16
+ /** Per mail account, the folders whose listed mail is to be listed again. */
17
+ mail: {
18
+ account: string;
19
+ folders: number;
20
+ }[];
21
+ }
22
+ /**
23
+ * Marks as not fetched what the store held from `cutoff` on, so the next ordinary sync fetches it again: each chat's
24
+ * held stretches end at its last message sent before `cutoff`, and each mail folder forgets the UIDs it listed past
25
+ * the last email it holds from before then. With `cutoff` `null` every stretch and every listed UID is forgotten.
26
+ * Nothing on any service is asked or changed; a service that only pushes (WhatsApp) refills only by pushing.
27
+ */
28
+ export declare const forgetCoverageSince: (database: CacheDatabase, cutoff: number | null, now?: number) => Refetch;
@@ -0,0 +1,120 @@
1
+ /**
2
+ * How far before the last deep check that passed the coverage is forgotten: a message is written when a sync or a
3
+ * serve gets it, which can be hours after it was sent, and the cut is by send time.
4
+ */
5
+ export const REFILL_MARGIN_MS = 86_400_000;
6
+ /** Stretch keys at or above this are send times in milliseconds (September 2001 on); below it, message ids. */
7
+ const TIME_KEYS = 1e12;
8
+ const integerId = `external_id GLOB '[0-9]*' AND NOT external_id GLOB '*[^0-9]*'`;
9
+ /**
10
+ * Marks as not fetched what the store held from `cutoff` on, so the next ordinary sync fetches it again: each chat's
11
+ * held stretches end at its last message sent before `cutoff`, and each mail folder forgets the UIDs it listed past
12
+ * the last email it holds from before then. With `cutoff` `null` every stretch and every listed UID is forgotten.
13
+ * Nothing on any service is asked or changed; a service that only pushes (WhatsApp) refills only by pushing.
14
+ */
15
+ export const forgetCoverageSince = (database, cutoff, now = Date.now()) => {
16
+ database.exec("BEGIN");
17
+ try {
18
+ const refetch = forget(database, cutoff, now);
19
+ database.exec("COMMIT");
20
+ return refetch;
21
+ }
22
+ catch (error) {
23
+ database.exec("ROLLBACK");
24
+ throw error;
25
+ }
26
+ };
27
+ const forget = (database, cutoff, now) => {
28
+ const chats = new Map();
29
+ const held = database
30
+ .prepare(`SELECT c.id, c.account_id, c.external_id AS chat, a.provider, a.external_id AS account,
31
+ max(r.to_key) AS top FROM sync_ranges r JOIN chats c ON c.id = r.chat_id JOIN accounts a ON a.id = c.account_id
32
+ GROUP BY c.id`)
33
+ .all();
34
+ for (const row of held) {
35
+ const chat = Number(row.id);
36
+ const top = Number(row.top);
37
+ const keepTo = cutoff === null
38
+ ? null
39
+ : top >= TIME_KEYS
40
+ ? cutoff
41
+ : database
42
+ .prepare(`SELECT max(CAST(external_id AS INTEGER)) AS k FROM messages WHERE chat_id = ? AND sent_at < ? AND ${integerId}`)
43
+ .get(chat, cutoff)?.k;
44
+ if (keepTo !== null && top <= keepTo)
45
+ continue;
46
+ if (keepTo === null)
47
+ database.prepare("DELETE FROM sync_ranges WHERE chat_id = ?").run(chat);
48
+ else {
49
+ database.prepare("DELETE FROM sync_ranges WHERE chat_id = ? AND from_key > ?").run(chat, keepTo);
50
+ database
51
+ .prepare("UPDATE sync_ranges SET to_key = ?, updated_at = ? WHERE chat_id = ? AND to_key > ?")
52
+ .run(keepTo, now, chat, keepTo);
53
+ }
54
+ const account = Number(row.account_id);
55
+ const external = String(row.chat);
56
+ database.prepare("DELETE FROM sync_cursors WHERE account_id = ? AND key = ?").run(account, `fetched:${external}`);
57
+ // A start mark with no stretch left that begins at or before it would call the chat complete.
58
+ database
59
+ .prepare(`DELETE FROM sync_cursors WHERE account_id = ? AND key = ? AND NOT EXISTS
60
+ (SELECT 1 FROM sync_ranges WHERE chat_id = ? AND from_key <= CAST(sync_cursors.value AS INTEGER))`)
61
+ .run(account, `history_start:${external}`, chat);
62
+ const key = `${row.provider}\u0000${row.account}`;
63
+ const one = chats.get(key) ?? { provider: String(row.provider), account: String(row.account), chats: 0 };
64
+ one.chats += 1;
65
+ chats.set(key, one);
66
+ }
67
+ return {
68
+ since: cutoff === null ? null : new Date(cutoff).toISOString(),
69
+ chats: [...chats.values()],
70
+ mail: forgetMail(database, cutoff, now),
71
+ };
72
+ };
73
+ const forgetMail = (database, cutoff, now) => {
74
+ const folders = new Map();
75
+ const points = database
76
+ .prepare(`SELECT s.account_id, s.key, s.value, a.external_id AS account FROM sync_cursors s
77
+ JOIN accounts a ON a.id = s.account_id WHERE a.provider = 'email' AND s.key LIKE 'mail_resume:%'`)
78
+ .all();
79
+ for (const row of points) {
80
+ let point;
81
+ try {
82
+ point = JSON.parse(String(row.value));
83
+ }
84
+ catch {
85
+ continue;
86
+ }
87
+ const account = String(row.account);
88
+ if (!Array.isArray(point.done)) {
89
+ // An mbox file's point: read to its end since the cut, the file is read again; it adds what is not stored.
90
+ if (cutoff !== null && Date.parse(point.updatedAt ?? "") < cutoff)
91
+ continue;
92
+ database
93
+ .prepare("DELETE FROM sync_cursors WHERE account_id = ? AND key = ?")
94
+ .run(Number(row.account_id), String(row.key));
95
+ folders.set(account, (folders.get(account) ?? 0) + 1);
96
+ continue;
97
+ }
98
+ const folder = String(row.key).slice("mail_resume:".length);
99
+ const last = cutoff === null
100
+ ? null
101
+ : database
102
+ .prepare(`SELECT max(l.uid) AS uid FROM email_locations l JOIN emails e ON e.id = l.email_id
103
+ WHERE l.mailbox_id = (SELECT id FROM mailboxes WHERE account_id = ? AND external_id = ?)
104
+ AND l.uidvalidity = ? AND coalesce(e.received_at, e.sent_at) < ?`)
105
+ .get(Number(row.account_id), folder, point.validity ?? "", cutoff)?.uid;
106
+ // Without a located email from before the cut no UID tells the time, so the whole listing is forgotten.
107
+ const done = last === null
108
+ ? []
109
+ : point.done
110
+ .filter(([from]) => from <= last)
111
+ .map(([from, to]) => [from, Math.min(to, last)]);
112
+ if (JSON.stringify(done) === JSON.stringify(point.done))
113
+ continue;
114
+ database
115
+ .prepare("UPDATE sync_cursors SET value = ?, updated_at = ? WHERE account_id = ? AND key = ?")
116
+ .run(JSON.stringify({ ...point, done }), now, Number(row.account_id), String(row.key));
117
+ folders.set(account, (folders.get(account) ?? 0) + 1);
118
+ }
119
+ return [...folders].map(([account, count]) => ({ account, folders: count }));
120
+ };
@@ -0,0 +1,11 @@
1
+ import type { Message } from "../../domain/models.js";
2
+ import type { StoreContext } from "./open.js";
3
+ /** A messenger bot's token keeps the bot's id, which is public, and loses its secret half. */
4
+ export declare const withoutBotTokens: (text: string) => string;
5
+ export declare const withoutBotTokensIn: (message: Message) => Message;
6
+ /**
7
+ * Masks the tokens in messages this build did not write: those stored before it, and those an older build saves
8
+ * later. On every open, from the newest message checked last time; a store with nothing new costs two index probes.
9
+ * The scan reads outside a write, so the first one, over the whole archive, does not hold other writers back.
10
+ */
11
+ export declare const maskStoredBotTokens: (context: StoreContext) => number;