@wirecat/cli-core 0.617.0 → 0.619.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 (306) hide show
  1. package/CHANGELOG.md +406 -1
  2. package/README.md +1 -1
  3. package/THIRD_PARTY_NOTICES +3 -0
  4. package/dist/background/backfill.d.ts +21 -0
  5. package/dist/background/backfill.js +41 -0
  6. package/dist/background/daily-archive-timer.d.ts +1 -1
  7. package/dist/background/deliver.d.ts +5 -2
  8. package/dist/background/deliver.js +30 -12
  9. package/dist/background/report/messages.js +4 -1
  10. package/dist/background/report/render.d.ts +3 -1
  11. package/dist/background/report/render.js +3 -1
  12. package/dist/background/report/view.js +4 -1
  13. package/dist/background/schedules.d.ts +17 -0
  14. package/dist/background/schedules.js +21 -8
  15. package/dist/calendar/cli/answers.d.ts +1 -0
  16. package/dist/calendar/cli/answers.js +6 -1
  17. package/dist/calendar/cli/index.js +2 -14
  18. package/dist/calendar/cli/people-link.d.ts +3 -0
  19. package/dist/calendar/cli/people-link.js +23 -0
  20. package/dist/calendar/index.d.ts +1 -1
  21. package/dist/calendar/index.js +1 -1
  22. package/dist/calendar/mcp/index.d.ts +12 -12
  23. package/dist/cli/base-stages-command.d.ts +22 -0
  24. package/dist/cli/base-stages-command.js +174 -0
  25. package/dist/cli/command-runs.d.ts +2 -0
  26. package/dist/cli/command-runs.js +3 -1
  27. package/dist/cli/config-command.js +6 -1
  28. package/dist/cli/context.d.ts +5 -0
  29. package/dist/cli/context.js +1 -0
  30. package/dist/cli/group-lock.d.ts +42 -0
  31. package/dist/cli/group-lock.js +130 -0
  32. package/dist/cli/index.d.ts +10 -4
  33. package/dist/cli/index.js +10 -4
  34. package/dist/cli/messenger/backfill-command.js +27 -15
  35. package/dist/cli/messenger/contacts-command.js +10 -3
  36. package/dist/cli/messenger/context.js +1 -0
  37. package/dist/cli/messenger/doctor-command.js +3 -1
  38. package/dist/cli/messenger/models-command.js +1 -1
  39. package/dist/cli/messenger/serve-command.js +24 -2
  40. package/dist/cli/messenger/serve-outdated.d.ts +22 -0
  41. package/dist/cli/messenger/serve-outdated.js +100 -0
  42. package/dist/cli/messenger/store-maintenance-command.d.ts +22 -2
  43. package/dist/cli/messenger/store-maintenance-command.js +9 -4
  44. package/dist/cli/model-catalogue-command.d.ts +3 -1
  45. package/dist/cli/model-catalogue-command.js +46 -2
  46. package/dist/cli/profile.d.ts +8 -0
  47. package/dist/cli/profile.js +25 -0
  48. package/dist/cli/program.js +2 -0
  49. package/dist/cli/runs/search-query.d.ts +1 -1
  50. package/dist/cli/runs/search-query.js +4 -0
  51. package/dist/cli/runs/search.d.ts +5 -1
  52. package/dist/cli/runs/search.js +12 -1
  53. package/dist/cli/schedule/schedule-command.d.ts +9 -0
  54. package/dist/cli/schedule/schedule-command.js +13 -0
  55. package/dist/cli/search-left-out.d.ts +6 -1
  56. package/dist/cli/search-left-out.js +9 -4
  57. package/dist/cli/settings.d.ts +8 -0
  58. package/dist/cli/settings.js +17 -2
  59. package/dist/cli/shared-command-exports.d.ts +16 -0
  60. package/dist/cli/store-recover.d.ts +3 -3
  61. package/dist/cli/store-recover.js +47 -23
  62. package/dist/cli/store-settings.d.ts +2 -0
  63. package/dist/cli/store-settings.js +37 -9
  64. package/dist/crm/cli/index.js +38 -6
  65. package/dist/crm/group-hint.d.ts +8 -0
  66. package/dist/crm/group-hint.js +13 -0
  67. package/dist/crm/source.d.ts +12 -1
  68. package/dist/crm/sync.d.ts +31 -2
  69. package/dist/crm/sync.js +110 -3
  70. package/dist/crm/testing/acme-scenario.d.ts +40 -0
  71. package/dist/crm/testing/acme-scenario.js +170 -0
  72. package/dist/crm/testing/index.d.ts +1 -0
  73. package/dist/crm/testing/index.js +1 -0
  74. package/dist/crm/testing/source-contract.js +12 -0
  75. package/dist/crm/testing/source.d.ts +2 -0
  76. package/dist/crm/testing/source.js +1 -0
  77. package/dist/domain/addresses.d.ts +13 -0
  78. package/dist/domain/addresses.js +63 -0
  79. package/dist/domain/categories.d.ts +3 -0
  80. package/dist/domain/categories.js +2 -0
  81. package/dist/domain/crm.d.ts +23 -0
  82. package/dist/domain/crm.js +7 -0
  83. package/dist/domain/links.d.ts +17 -4
  84. package/dist/domain/links.js +20 -7
  85. package/dist/domain/mentions.d.ts +2 -12
  86. package/dist/domain/mentions.js +2 -19
  87. package/dist/domain/orders.d.ts +8 -1
  88. package/dist/domain/orders.js +6 -2
  89. package/dist/domain/phones.d.ts +26 -0
  90. package/dist/domain/phones.js +48 -0
  91. package/dist/domain/record-types.d.ts +1 -1
  92. package/dist/domain/record-types.js +1 -0
  93. package/dist/domain/records.d.ts +5 -0
  94. package/dist/domain/ref-summaries.d.ts +39 -0
  95. package/dist/domain/ref-summaries.js +51 -3
  96. package/dist/domain/relations.d.ts +27 -2
  97. package/dist/domain/relations.js +37 -3
  98. package/dist/domain/vcard.d.ts +2 -2
  99. package/dist/domain/vcard.js +4 -10
  100. package/dist/embeddings/models.d.ts +11 -3
  101. package/dist/embeddings/models.js +28 -4
  102. package/dist/entities/business-context.d.ts +149 -0
  103. package/dist/entities/business-context.js +192 -0
  104. package/dist/entities/contact-activity.d.ts +2 -0
  105. package/dist/entities/contact-activity.js +7 -1
  106. package/dist/entities/contact-context.d.ts +157 -0
  107. package/dist/entities/contact-context.js +2 -0
  108. package/dist/entities/deal.d.ts +10 -0
  109. package/dist/entities/deal.js +2 -0
  110. package/dist/entities/index.d.ts +23 -3
  111. package/dist/entities/index.js +5 -0
  112. package/dist/entities/mention.d.ts +4 -3
  113. package/dist/entities/mention.js +2 -1
  114. package/dist/entities/message-transfer.d.ts +4 -2
  115. package/dist/entities/message-transfer.js +2 -2
  116. package/dist/entities/model.d.ts +2 -2
  117. package/dist/entities/model.js +1 -1
  118. package/dist/entities/relationship.d.ts +4 -0
  119. package/dist/entities/relationship.js +4 -0
  120. package/dist/errors/reasons.js +44 -4
  121. package/dist/fetch/page.js +2 -1
  122. package/dist/index.d.ts +4 -3
  123. package/dist/index.js +4 -3
  124. package/dist/meetings/context-store.d.ts +2 -0
  125. package/dist/meetings/findings-rules.d.ts +4 -0
  126. package/dist/meetings/findings-rules.js +5 -2
  127. package/dist/meetings/mcp/index.d.ts +15 -15
  128. package/dist/meetings/result-items.d.ts +1 -0
  129. package/dist/meetings/result-items.js +1 -0
  130. package/dist/models/index.js +22 -5
  131. package/dist/runs/events.d.ts +11 -1
  132. package/dist/runs/events.js +3 -1
  133. package/dist/runs/log-attributes.js +4 -0
  134. package/dist/runs/log-events.js +2 -0
  135. package/dist/runs/recording.d.ts +3 -0
  136. package/dist/runs/recording.js +36 -12
  137. package/dist/runs/run.d.ts +12 -3
  138. package/dist/runs/run.js +32 -13
  139. package/dist/search/account-list.d.ts +6 -0
  140. package/dist/search/account-list.js +9 -3
  141. package/dist/search/groups.d.ts +68 -0
  142. package/dist/search/groups.js +172 -0
  143. package/dist/services/account-groups.d.ts +28 -0
  144. package/dist/services/account-groups.js +89 -0
  145. package/dist/services/archive.d.ts +7 -1
  146. package/dist/services/archive.js +19 -3
  147. package/dist/services/business-context.d.ts +113 -0
  148. package/dist/services/business-context.js +156 -0
  149. package/dist/services/communications.d.ts +50 -0
  150. package/dist/services/communications.js +140 -0
  151. package/dist/services/deal-context.d.ts +90 -0
  152. package/dist/services/deal-context.js +131 -0
  153. package/dist/services/deps.d.ts +2 -0
  154. package/dist/services/enrichment.d.ts +7 -2
  155. package/dist/services/enrichment.js +46 -5
  156. package/dist/services/events-search.js +2 -1
  157. package/dist/services/group-guard.d.ts +28 -0
  158. package/dist/services/group-guard.js +131 -0
  159. package/dist/services/index.d.ts +15 -2
  160. package/dist/services/index.js +9 -2
  161. package/dist/services/ingest.d.ts +12 -0
  162. package/dist/services/ingest.js +4 -0
  163. package/dist/services/link-scorers/chat-senders.js +39 -29
  164. package/dist/services/link-scorers/member-chats.js +4 -3
  165. package/dist/services/link-scorers/member-dialog.js +5 -7
  166. package/dist/services/link-scorers/scan.js +17 -8
  167. package/dist/services/link-scorers/shared.d.ts +6 -2
  168. package/dist/services/link-scorers/shared.js +6 -2
  169. package/dist/services/link-scorers/types.d.ts +2 -0
  170. package/dist/services/meaning-model.d.ts +7 -0
  171. package/dist/services/meaning-model.js +20 -0
  172. package/dist/services/meeting-context.d.ts +6 -1
  173. package/dist/services/meeting-context.js +12 -5
  174. package/dist/services/message-resolution.js +2 -3
  175. package/dist/services/messages-meaning.js +4 -5
  176. package/dist/services/messages-search.d.ts +5 -1
  177. package/dist/services/messages-search.js +1 -1
  178. package/dist/services/model-downloads.d.ts +1 -1
  179. package/dist/services/model-downloads.js +6 -4
  180. package/dist/services/money-context.d.ts +73 -0
  181. package/dist/services/money-context.js +77 -0
  182. package/dist/services/notes-search.d.ts +4 -1
  183. package/dist/services/notes-search.js +19 -7
  184. package/dist/services/organization-context.d.ts +80 -0
  185. package/dist/services/organization-context.js +154 -0
  186. package/dist/services/people.d.ts +22 -6
  187. package/dist/services/people.js +38 -8
  188. package/dist/services/person-business.d.ts +43 -0
  189. package/dist/services/person-business.js +67 -0
  190. package/dist/services/person-context.d.ts +9 -1
  191. package/dist/services/person-context.js +5 -3
  192. package/dist/services/proposals/kinds/identity-link.d.ts +4 -0
  193. package/dist/services/proposals/kinds/identity-link.js +48 -0
  194. package/dist/services/proposals/kinds/orders.js +1 -1
  195. package/dist/services/proposals/registry.js +2 -0
  196. package/dist/services/search-kind.d.ts +12 -5
  197. package/dist/services/search-kind.js +49 -10
  198. package/dist/services/text-model-choice.js +1 -1
  199. package/dist/store/accounts.d.ts +18 -0
  200. package/dist/store/accounts.js +18 -3
  201. package/dist/store/damage.d.ts +43 -10
  202. package/dist/store/damage.js +119 -36
  203. package/dist/store/decisions.js +3 -1
  204. package/dist/store/evidence-findings.d.ts +14 -0
  205. package/dist/store/evidence-findings.js +2 -0
  206. package/dist/store/exports.d.ts +2 -1
  207. package/dist/store/identity-links.d.ts +92 -0
  208. package/dist/store/identity-links.js +6 -0
  209. package/dist/store/index.d.ts +11 -5
  210. package/dist/store/index.js +5 -2
  211. package/dist/store/journal.d.ts +10 -0
  212. package/dist/store/journal.js +33 -0
  213. package/dist/store/marks.d.ts +19 -1
  214. package/dist/store/marks.js +23 -1
  215. package/dist/store/migrations.d.ts +1 -1
  216. package/dist/store/migrations.js +35 -12
  217. package/dist/store/people.d.ts +22 -0
  218. package/dist/store/people.js +15 -1
  219. package/dist/store/recover.d.ts +34 -0
  220. package/dist/store/recover.js +188 -6
  221. package/dist/store/refill.d.ts +28 -0
  222. package/dist/store/refill.js +120 -0
  223. package/dist/store/sqlite/accounts.js +2 -0
  224. package/dist/store/sqlite/base-stages.d.ts +122 -0
  225. package/dist/store/sqlite/base-stages.js +443 -0
  226. package/dist/store/sqlite/base-suggest.d.ts +13 -0
  227. package/dist/store/sqlite/base-suggest.js +62 -0
  228. package/dist/store/sqlite/business-contracts.js +10 -1
  229. package/dist/store/sqlite/clients.d.ts +7 -3
  230. package/dist/store/sqlite/clients.js +11 -7
  231. package/dist/store/sqlite/crm-settings.d.ts +12 -2
  232. package/dist/store/sqlite/crm-settings.js +56 -13
  233. package/dist/store/sqlite/crm.d.ts +13 -1
  234. package/dist/store/sqlite/crm.js +20 -4
  235. package/dist/store/sqlite/deals.d.ts +33 -0
  236. package/dist/store/sqlite/deals.js +42 -4
  237. package/dist/store/sqlite/decision-requests.js +7 -3
  238. package/dist/store/sqlite/email-index.js +17 -15
  239. package/dist/store/sqlite/evidence-findings.js +29 -5
  240. package/dist/store/sqlite/findings-core.js +4 -2
  241. package/dist/store/sqlite/identity-link-rows.d.ts +50 -0
  242. package/dist/store/sqlite/identity-link-rows.js +146 -0
  243. package/dist/store/sqlite/identity-proposals.d.ts +53 -0
  244. package/dist/store/sqlite/identity-proposals.js +234 -0
  245. package/dist/store/sqlite/knowledge.js +5 -3
  246. package/dist/store/sqlite/link-kinds.d.ts +1 -0
  247. package/dist/store/sqlite/link-kinds.js +1 -0
  248. package/dist/store/sqlite/link-row.d.ts +6 -0
  249. package/dist/store/sqlite/link-row.js +35 -0
  250. package/dist/store/sqlite/link-source.d.ts +10 -0
  251. package/dist/store/sqlite/link-source.js +16 -0
  252. package/dist/store/sqlite/manifest.js +1 -0
  253. package/dist/store/sqlite/meeting-context-links.js +9 -6
  254. package/dist/store/sqlite/memories.js +9 -7
  255. package/dist/store/sqlite/mentions.d.ts +4 -1
  256. package/dist/store/sqlite/mentions.js +14 -9
  257. package/dist/store/sqlite/migrations.generated.js +8 -0
  258. package/dist/store/sqlite/note-index.js +9 -7
  259. package/dist/store/sqlite/notes.d.ts +2 -3
  260. package/dist/store/sqlite/notes.js +6 -29
  261. package/dist/store/sqlite/open-store.js +3 -0
  262. package/dist/store/sqlite/open.js +11 -2
  263. package/dist/store/sqlite/orders.d.ts +2 -0
  264. package/dist/store/sqlite/orders.js +9 -3
  265. package/dist/store/sqlite/organization-categories.d.ts +18 -0
  266. package/dist/store/sqlite/organization-categories.js +34 -0
  267. package/dist/store/sqlite/organizations.d.ts +5 -1
  268. package/dist/store/sqlite/organizations.js +14 -4
  269. package/dist/store/sqlite/person-links.d.ts +19 -4
  270. package/dist/store/sqlite/person-links.js +49 -11
  271. package/dist/store/sqlite/person-match-scan.d.ts +13 -0
  272. package/dist/store/sqlite/person-match-scan.js +251 -0
  273. package/dist/store/sqlite/person-matcher.d.ts +16 -0
  274. package/dist/store/sqlite/person-matcher.js +32 -0
  275. package/dist/store/sqlite/proposed-actions.js +6 -0
  276. package/dist/store/sqlite/record-matching.d.ts +2 -8
  277. package/dist/store/sqlite/record-matching.js +8 -40
  278. package/dist/store/sqlite/record-projectors-phone.js +2 -1
  279. package/dist/store/sqlite/record-relationships.d.ts +52 -0
  280. package/dist/store/sqlite/record-relationships.js +243 -0
  281. package/dist/store/sqlite/record-run.d.ts +5 -0
  282. package/dist/store/sqlite/record-run.js +62 -2
  283. package/dist/store/sqlite/record-writes.d.ts +1 -1
  284. package/dist/store/sqlite/record-writes.js +4 -2
  285. package/dist/store/sqlite/records.js +27 -2
  286. package/dist/store/sqlite/ref-accounts.d.ts +13 -0
  287. package/dist/store/sqlite/ref-accounts.js +117 -0
  288. package/dist/store/sqlite/ref-summaries.js +5 -1
  289. package/dist/store/sqlite/relation-list.d.ts +4 -1
  290. package/dist/store/sqlite/relation-list.js +20 -2
  291. package/dist/store/sqlite/relation-proposals.d.ts +18 -1
  292. package/dist/store/sqlite/relation-proposals.js +53 -11
  293. package/dist/store/sqlite/relation-roles.js +12 -6
  294. package/dist/store/sqlite/reported-relations.d.ts +11 -1
  295. package/dist/store/sqlite/reported-relations.js +59 -18
  296. package/dist/store/sqlite/schema.d.ts +32 -0
  297. package/dist/store/sqlite/schema.js +3 -0
  298. package/dist/store/sqlite/transaction.d.ts +13 -0
  299. package/dist/store/sqlite/transaction.js +33 -15
  300. package/dist/store/store.d.ts +3 -0
  301. package/dist/store/store.js +5 -0
  302. package/dist/store/write-events.d.ts +18 -0
  303. package/dist/store/write-events.js +88 -0
  304. package/package.json +3 -3
  305. package/parity.json +11 -4
  306. package/schemas/records-envelope.v1.schema.json +3 -0
@@ -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
+ };
@@ -2,6 +2,7 @@ import { CliError } from "@wirecat/cli-base";
2
2
  import { and, asc, eq, inArray, sql } from "./drizzle/core.js";
3
3
  import { pointerPairs } from "./entity-types.js";
4
4
  import { forgetDanglingEvidence, forgetEvidenceTo } from "./evidence-signature.js";
5
+ import { forgetErasedLinks } from "./identity-link-rows.js";
5
6
  import { mergeSql } from "./merged-persons.js";
6
7
  import { accountIdentities, accounts, aliases, botUpdates, chatEventPeople, chatEvents, chatMembers, chats, chunks, fetchLeases, involvements, memberCounts, memberObservationMembers, memberObservations, memberStays, messageReactions, messageRevisions, messages, messageTranscripts, pollVotes, projects, syncCursors, syncRanges, syncs, } from "./schema.js";
7
8
  import { dropUnusedVectors } from "./vector-index.js";
@@ -198,6 +199,7 @@ export const dropOrphanPeople = (database, unseenBefore) => {
198
199
  for (const table of ["identity_revisions", "identity_link_events", "identity_links"])
199
200
  database.prepare(`DELETE FROM ${table} WHERE identity_id IN (SELECT value FROM json_each(?))`).run(gone);
200
201
  database.prepare("DELETE FROM identities WHERE id IN (SELECT value FROM json_each(?))").run(gone);
202
+ forgetErasedLinks(database);
201
203
  database
202
204
  .prepare(`DELETE FROM persons WHERE id IN (SELECT value FROM json_each(?)) AND owner = 0
203
205
  AND NOT EXISTS (SELECT 1 FROM identity_links l WHERE l.person_id = persons.id)
@@ -0,0 +1,122 @@
1
+ import { type DealKind, type StageOutcome } from "../../domain/deals.js";
2
+ import type { AccountKey } from "../types.js";
3
+ import type { StoreContext } from "./open.js";
4
+ export interface StageName {
5
+ /** `stage:<id>`: a stage of any pipeline, as these commands name it. */
6
+ ref: string;
7
+ name: string;
8
+ }
9
+ /** One column of a base set: the open deals or leads whose stage maps to it, and how many stages do. */
10
+ export interface BaseColumn extends Omit<StageName, "ref"> {
11
+ /** `null` only in a set read from a read-only store before its first use made it. */
12
+ ref: string | null;
13
+ position: number;
14
+ outcome: StageOutcome;
15
+ open: number;
16
+ /** Stages of other pipelines confirmed onto it. */
17
+ mapped: number;
18
+ }
19
+ export interface BaseSet {
20
+ kind: DealKind;
21
+ /** The owner's own pipeline that holds the set; `null` while a read-only read shows the defaults not made yet. */
22
+ pipeline: string | null;
23
+ stages: BaseColumn[];
24
+ /** What no column holds yet: open rows whose stage is unmapped or only suggested, and those stages. */
25
+ unsorted: {
26
+ open: number;
27
+ stages: number;
28
+ };
29
+ }
30
+ /** A stage of a pipeline outside the base set, and the base stage it maps to. */
31
+ export interface StageMapping extends StageName {
32
+ position: number;
33
+ outcome: StageOutcome;
34
+ /** The CRM's own id of the stage, which a CRM CLI's move matches first; `null` in an own pipeline. */
35
+ externalId: string | null;
36
+ kind: DealKind;
37
+ pipeline: string;
38
+ pipelineName: string;
39
+ account: AccountKey | null;
40
+ /** Suggested or confirmed; `null` until the base set exists or when nothing fits. */
41
+ baseStage: StageName | null;
42
+ confirmed: boolean;
43
+ open: number;
44
+ }
45
+ export interface BaseScope {
46
+ /** Only these CRM accounts' pipelines, with the owner's own; absent, every one. */
47
+ accounts?: readonly AccountKey[];
48
+ }
49
+ export interface MappingFilter extends BaseScope {
50
+ kind?: DealKind;
51
+ /** `pipeline:<id>`, or a name only one pipeline has. */
52
+ pipeline?: string;
53
+ unconfirmed?: boolean;
54
+ }
55
+ /** The base set of each kind, the mapping of every other pipeline's stages onto it, and moves by base stage. */
56
+ export interface BaseStagesStore {
57
+ /** The set with its board counts; the first use makes the default set and suggests every stage's mapping. */
58
+ show(kind: DealKind, scope?: BaseScope): Promise<BaseSet>;
59
+ /** Open stages go before the first won or lost one unless `position` says where. */
60
+ add(kind: DealKind, input: {
61
+ name: string;
62
+ outcome?: StageOutcome;
63
+ position?: number;
64
+ }): Promise<BaseSet>;
65
+ rename(kind: DealKind, stage: string, name: string): Promise<BaseSet>;
66
+ move(kind: DealKind, stage: string, position: number): Promise<BaseSet>;
67
+ /** Refused for the last stage of its outcome and for one the owner's own rows stand or stood in. */
68
+ remove(kind: DealKind, stage: string): Promise<BaseSet>;
69
+ mappings(filter?: MappingFilter): Promise<StageMapping[]>;
70
+ /** Maps `stage:<id>` onto a base stage of its kind, confirmed unless `confirmed: false` (an agent's suggestion). */
71
+ map(stage: string, base: string, scope?: BaseScope, options?: {
72
+ confirmed?: boolean;
73
+ }): Promise<StageMapping>;
74
+ /** Confirms every suggestion of one pipeline, or of all of them in scope; answers how many. */
75
+ confirm(target: {
76
+ pipeline: string;
77
+ } | {
78
+ all: true;
79
+ kind?: DealKind;
80
+ }, scope?: BaseScope): Promise<number>;
81
+ /**
82
+ * The stage of the row's own pipeline confirmed onto `base` (a base stage by `stage:<id>` or name), or `base` itself
83
+ * when it is a `stage:<id>` of that pipeline. Refused with `stage.choice-required` and the candidates when several
84
+ * are confirmed onto it, and with `stage.unmapped` when none is.
85
+ */
86
+ resolve(item: string, base: string): Promise<{
87
+ stage: StageName & {
88
+ externalId: string | null;
89
+ outcome: StageOutcome;
90
+ };
91
+ }>;
92
+ }
93
+ export declare const baseStagesOver: (context: StoreContext) => {
94
+ show: (kind: DealKind, scope?: BaseScope) => BaseSet;
95
+ add: (kind: DealKind, input: {
96
+ name: string;
97
+ outcome?: StageOutcome;
98
+ position?: number;
99
+ }) => BaseSet;
100
+ rename: (kind: DealKind, stage: string, name: string) => BaseSet;
101
+ move: (kind: DealKind, stage: string, position: number) => BaseSet;
102
+ remove: (kind: DealKind, stage: string) => BaseSet;
103
+ mappings: (filter?: MappingFilter) => StageMapping[];
104
+ map: (stage: string, base: string, scope?: BaseScope, { confirmed }?: {
105
+ confirmed?: boolean;
106
+ }) => StageMapping;
107
+ confirm: (target: {
108
+ pipeline: string;
109
+ } | {
110
+ all: true;
111
+ kind?: DealKind;
112
+ }, scope?: BaseScope) => number;
113
+ resolve: (item: string, base: string) => {
114
+ stage: {
115
+ ref: string;
116
+ name: string;
117
+ externalId: string | null;
118
+ outcome: StageOutcome;
119
+ };
120
+ };
121
+ };
122
+ export declare const baseStagesStoreOver: (context: StoreContext) => BaseStagesStore;