@wirecat/cli-core 0.648.0 → 0.650.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 (85) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/dist/analysis/anthropic.js +2 -1
  3. package/dist/background/daily-archive-timer.d.ts +1 -1
  4. package/dist/cli/account-remove.d.ts +2 -0
  5. package/dist/cli/account-remove.js +46 -10
  6. package/dist/cli/messenger/messages-search-command.js +6 -1
  7. package/dist/cli/messenger/search-answers.d.ts +3 -1
  8. package/dist/cli/messenger/search-answers.js +3 -1
  9. package/dist/cli/steps.js +9 -0
  10. package/dist/cli/unknown-profile.js +1 -0
  11. package/dist/constants/index.d.ts +6 -0
  12. package/dist/constants/index.js +14 -0
  13. package/dist/crm/cli/index.js +30 -5
  14. package/dist/crm/source.d.ts +8 -1
  15. package/dist/crm/stage-tasks.d.ts +3 -1
  16. package/dist/crm/stage-tasks.js +8 -4
  17. package/dist/crm/sync.d.ts +1 -1
  18. package/dist/crm/sync.js +54 -0
  19. package/dist/domain/crm.d.ts +15 -0
  20. package/dist/domain/phones.d.ts +2 -0
  21. package/dist/domain/phones.js +3 -0
  22. package/dist/domain/providers.d.ts +4 -1
  23. package/dist/domain/providers.js +9 -2
  24. package/dist/domain/record-types.d.ts +24 -3
  25. package/dist/domain/record-types.js +23 -2
  26. package/dist/domain/records-table.js +4 -3
  27. package/dist/domain/records.d.ts +1 -1
  28. package/dist/domain/records.js +3 -2
  29. package/dist/entities/contact-context.d.ts +6 -0
  30. package/dist/entities/contact-context.js +3 -0
  31. package/dist/entities/deal.d.ts +4 -0
  32. package/dist/entities/deal.js +3 -0
  33. package/dist/entities/index.d.ts +12 -0
  34. package/dist/entities/recorded-meeting.d.ts +17 -0
  35. package/dist/entities/recorded-meeting.js +15 -0
  36. package/dist/errors/reasons.js +3 -4
  37. package/dist/index.d.ts +1 -1
  38. package/dist/meetings/answers.d.ts +5 -0
  39. package/dist/meetings/answers.js +3 -0
  40. package/dist/meetings/index.d.ts +1 -1
  41. package/dist/meetings/participant-search.d.ts +5 -0
  42. package/dist/meetings/pull.js +2 -1
  43. package/dist/meetings/read-answers.d.ts +4 -0
  44. package/dist/meetings/read-answers.js +1 -0
  45. package/dist/meetings/source.d.ts +5 -0
  46. package/dist/meetings/store.d.ts +10 -1
  47. package/dist/models/ai.js +2 -2
  48. package/dist/models/endpoint.d.ts +7 -0
  49. package/dist/models/endpoint.js +10 -0
  50. package/dist/models/index.js +2 -2
  51. package/dist/oauth/keeper.js +1 -1
  52. package/dist/sends/guard.js +8 -6
  53. package/dist/services/communications.d.ts +2 -2
  54. package/dist/services/communications.js +24 -2
  55. package/dist/services/document-source.js +9 -1
  56. package/dist/services/meeting-model.js +2 -1
  57. package/dist/services/notes-search.d.ts +10 -5
  58. package/dist/services/notes-search.js +19 -7
  59. package/dist/services/person-context.d.ts +3 -0
  60. package/dist/services/person-context.js +9 -1
  61. package/dist/services/person-meetings.d.ts +36 -0
  62. package/dist/services/person-meetings.js +57 -0
  63. package/dist/services/search-all.js +18 -10
  64. package/dist/speech/openai.js +5 -2
  65. package/dist/store/sqlite/added-sources.d.ts +38 -0
  66. package/dist/store/sqlite/added-sources.js +80 -50
  67. package/dist/store/sqlite/crm-settings.d.ts +5 -1
  68. package/dist/store/sqlite/crm-settings.js +8 -0
  69. package/dist/store/sqlite/crm-stage-entries.d.ts +15 -0
  70. package/dist/store/sqlite/crm-stage-entries.js +74 -0
  71. package/dist/store/sqlite/crm.d.ts +8 -1
  72. package/dist/store/sqlite/crm.js +7 -1
  73. package/dist/store/sqlite/identities.js +3 -1
  74. package/dist/store/sqlite/involvements.d.ts +2 -0
  75. package/dist/store/sqlite/involvements.js +4 -1
  76. package/dist/store/sqlite/meeting-participant-search.js +9 -3
  77. package/dist/store/sqlite/meetings.js +7 -2
  78. package/dist/store/sqlite/person-match-scan.js +39 -15
  79. package/dist/store/sqlite/record-projectors-document.d.ts +12 -0
  80. package/dist/store/sqlite/record-projectors-document.js +81 -0
  81. package/dist/store/sqlite/record-projectors.js +2 -0
  82. package/dist/update/index.d.ts +1 -1
  83. package/dist/update/index.js +4 -2
  84. package/package.json +1 -1
  85. package/schemas/records-envelope.v1.schema.json +57 -2
@@ -10,6 +10,61 @@ import { documentOf, folderOf, insertLink, keepRevision, pathParts, requiredThin
10
10
  import { oneOf, textOf } from "./text-input.js";
11
11
  import { write } from "./transaction.js";
12
12
  export const ADDED_KINDS = ["text", "file", "page"];
13
+ const TEXT_COLUMNS = "kind = ?, title = ?, file_name = ?, extension = ?, url = ?, mime = ?, size = ?, content_hash = ?, body = ?, " +
14
+ "extraction = ?, metadata = ?, language = ?";
15
+ const textValues = (document) => [
16
+ document.kind,
17
+ document.title,
18
+ document.fileName,
19
+ document.extension,
20
+ document.url,
21
+ document.mime,
22
+ document.size,
23
+ document.hash,
24
+ document.text,
25
+ document.extraction,
26
+ document.metadata,
27
+ document.language,
28
+ ];
29
+ /**
30
+ * The writes of a document in a given account: the added sources' (`added:owner`) and a records import's (the
31
+ * envelope's own account) go through the same columns.
32
+ */
33
+ export const documentWritesOver = ({ database }) => ({
34
+ insert: (accountId, externalId, document, kept, at) => Number(database
35
+ .prepare("INSERT INTO documents (account_id, external_id, kind, title, file_name, extension, url, mime, size, " +
36
+ "content_hash, body, extraction, metadata, language, storage, local_path, revision, created_at, updated_at) " +
37
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?) RETURNING id")
38
+ .get(accountId, externalId, ...textValues(document), kept.storage, kept.localPath, at, at)?.id),
39
+ /** Its next revision, the text before kept; `revised: false` changes what describes it and keeps the revision. */
40
+ update: (row, document, at, revised = true) => {
41
+ if (revised)
42
+ keepRevision(database, row, at);
43
+ database
44
+ .prepare(`UPDATE documents SET ${TEXT_COLUMNS}, revision = revision + ?, updated_at = ? WHERE id = ?`)
45
+ .run(...textValues(document), revised ? 1 : 0, at, Number(row.id));
46
+ },
47
+ /** A removed document back, as written now. */
48
+ revive: (id, document, kept, at) => {
49
+ database
50
+ .prepare(`UPDATE documents SET ${TEXT_COLUMNS}, storage = ?, local_path = ?, updated_at = ?, deleted_at = NULL WHERE id = ?`)
51
+ .run(...textValues(document), kept.storage, kept.localPath, at, id);
52
+ },
53
+ /** Its `files` row, named as its source names it, not by a hash or a key. */
54
+ place: (id, at, name) => {
55
+ syncFile(database, at, id);
56
+ database
57
+ .prepare("UPDATE files SET name = ?, path = ?, path_folded = ? WHERE document_id = ? AND kind <> 'folder'")
58
+ .run(name, name, fold(name), id);
59
+ },
60
+ /** Its text goes, its row stays as deleted: what a folder file's removal does. */
61
+ remove: (id, at) => {
62
+ database
63
+ .prepare("UPDATE files SET deleted_at = ?, updated_at = ? WHERE document_id = ? AND deleted_at IS NULL")
64
+ .run(at, at, id);
65
+ database.prepare("UPDATE documents SET deleted_at = ?, body = '' WHERE id = ?").run(at, id);
66
+ },
67
+ });
13
68
  const sha256 = (value) => createHash("sha256").update(value).digest("hex");
14
69
  // `sha256:` is the content's own name, so no key may take it.
15
70
  const SOURCE_KEY = /^(?!sha256:)[a-z][a-z0-9-]{0,39}:[A-Za-z0-9._~-]{1,200}$/;
@@ -66,8 +121,23 @@ const checked = (input) => {
66
121
  extension: fileName === null ? null : pathParts(fileName).extension,
67
122
  };
68
123
  };
124
+ const documentTextOf = (source, input) => ({
125
+ kind: source.kind,
126
+ title: source.title,
127
+ fileName: source.fileName,
128
+ extension: source.extension,
129
+ url: source.url,
130
+ mime: input.mime ?? null,
131
+ size: input.size ?? input.bytes?.byteLength ?? null,
132
+ hash: source.hash,
133
+ text: source.text,
134
+ extraction: source.read === "extracted" ? "text" : "none",
135
+ metadata: encodeDocumentMetadata(input.metadata, input.sections),
136
+ language: languageOf(input.metadata),
137
+ });
69
138
  export const addedSourcesOver = (context) => {
70
139
  const { database, now } = context;
140
+ const writes = documentWritesOver(context);
71
141
  const accountRow = () => database.prepare("SELECT * FROM accounts WHERE provider = ? AND external_id = ?").get(ADDED_PROVIDER, ADDED_ACCOUNT);
72
142
  const documentAt = (id) => documentOf(database.prepare("SELECT * FROM documents WHERE id = ?").get(id));
73
143
  const ownRow = (externalId) => {
@@ -122,13 +192,6 @@ export const addedSourcesOver = (context) => {
122
192
  .get(JSON.stringify(hashes));
123
193
  return row ? Number(row.id) : undefined;
124
194
  };
125
- /** Its `files` row is named as the owner named the source, not by its hash. */
126
- const placeFile = (id, at, name) => {
127
- syncFile(database, at, id);
128
- database
129
- .prepare("UPDATE files SET name = ?, path = ?, path_folded = ? WHERE document_id = ? AND kind <> 'folder'")
130
- .run(name, name, fold(name), id);
131
- };
132
195
  return {
133
196
  addedAccount: async () => {
134
197
  const row = accountRow();
@@ -177,11 +240,7 @@ export const addedSourcesOver = (context) => {
177
240
  .get(id, ADDED_PROVIDER);
178
241
  if (!row)
179
242
  throw new CliError("not_found", `no live added source ${reference} in the local store`);
180
- const at = now();
181
- database
182
- .prepare("UPDATE files SET deleted_at = ?, updated_at = ? WHERE document_id = ? AND deleted_at IS NULL")
183
- .run(at, at, id);
184
- database.prepare("UPDATE documents SET deleted_at = ?, body = '' WHERE id = ?").run(at, id);
243
+ writes.remove(id, now());
185
244
  return {
186
245
  ref: `document:${id}`,
187
246
  removed: true,
@@ -191,7 +250,8 @@ export const addedSourcesOver = (context) => {
191
250
  },
192
251
  saveAddedSource: async (input) => {
193
252
  const source = checked(input);
194
- const metadata = encodeDocumentMetadata(input.metadata, input.sections);
253
+ const document = documentTextOf(source, input);
254
+ const kept = { storage: source.copy === null ? "text" : "copy", localPath: source.copy };
195
255
  const subjects = input.subjects ?? [];
196
256
  return write(database, () => {
197
257
  const at = now();
@@ -200,24 +260,18 @@ export const addedSourcesOver = (context) => {
200
260
  const id = Number(own.id);
201
261
  const revised = input.sourceKey !== undefined && own.content_hash !== source.hash;
202
262
  if (revised) {
203
- keepRevision(database, own, at);
204
- database
205
- .prepare("UPDATE documents SET kind = ?, title = ?, file_name = ?, extension = ?, url = ?, mime = ?, size = ?, " +
206
- "content_hash = ?, body = ?, extraction = ?, metadata = ?, language = ?, revision = revision + 1, " +
207
- "updated_at = ? WHERE id = ?")
208
- .run(source.kind, source.title, source.fileName, source.extension, source.url, input.mime ?? null, input.size ?? input.bytes?.byteLength ?? null, source.hash, source.text, source.read === "extracted" ? "text" : "none", metadata, languageOf(input.metadata), at, id);
209
- placeFile(id, at, source.fileName ?? source.title ?? source.externalId);
263
+ writes.update(own, document, at);
264
+ writes.place(id, at, source.fileName ?? source.title ?? source.externalId);
210
265
  }
211
266
  if (source.copy !== null && own.storage !== "copy")
212
267
  database
213
268
  .prepare("UPDATE documents SET storage = 'copy', local_path = ?, updated_at = ? WHERE id = ?")
214
269
  .run(source.copy, at, id);
215
- const kept = source.copy !== null || own.storage === "copy" ? "copy" : "text";
216
270
  return {
217
271
  note: documentAt(id),
218
272
  created: false,
219
273
  duplicateOf: null,
220
- kept,
274
+ kept: source.copy !== null || own.storage === "copy" ? "copy" : "text",
221
275
  changed: revised,
222
276
  subjects: about(id, subjects, input.by),
223
277
  };
@@ -228,30 +282,10 @@ export const addedSourcesOver = (context) => {
228
282
  const note = documentAt(duplicate);
229
283
  return { note, created: false, duplicateOf: note.ref, kept: null, changed: false, subjects: linked };
230
284
  }
231
- const values = [
232
- source.kind,
233
- source.title,
234
- source.fileName,
235
- source.extension,
236
- source.url,
237
- source.copy === null ? "text" : "copy",
238
- source.copy,
239
- input.mime ?? null,
240
- input.size ?? input.bytes?.byteLength ?? null,
241
- source.hash,
242
- source.text,
243
- source.read === "extracted" ? "text" : "none",
244
- metadata,
245
- languageOf(input.metadata),
246
- ];
247
285
  let id;
248
286
  if (own) {
249
287
  id = Number(own.id);
250
- database
251
- .prepare("UPDATE documents SET kind = ?, title = ?, file_name = ?, extension = ?, url = ?, storage = ?, local_path = ?, " +
252
- "mime = ?, size = ?, content_hash = ?, body = ?, extraction = ?, metadata = ?, language = ?, " +
253
- "updated_at = ?, deleted_at = NULL WHERE id = ?")
254
- .run(...values, at, id);
288
+ writes.revive(id, document, kept, at);
255
289
  }
256
290
  else {
257
291
  const holder = accountRow()?.id ??
@@ -259,18 +293,14 @@ export const addedSourcesOver = (context) => {
259
293
  .prepare("INSERT INTO accounts (provider, external_id, name, settings, created_at, updated_at) " +
260
294
  "VALUES (?, ?, NULL, ?, ?, ?) RETURNING id")
261
295
  .get(ADDED_PROVIDER, ADDED_ACCOUNT, JSON.stringify({ format: "markdown" }), at, at)?.id;
262
- id = Number(database
263
- .prepare("INSERT INTO documents (account_id, external_id, kind, title, file_name, extension, url, storage, local_path, " +
264
- "mime, size, content_hash, body, extraction, metadata, language, revision, created_at, updated_at) " +
265
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?) RETURNING id")
266
- .get(Number(holder), source.externalId, ...values, at, at)?.id);
296
+ id = writes.insert(Number(holder), source.externalId, document, kept, at);
267
297
  }
268
- placeFile(id, at, source.fileName ?? source.title ?? source.externalId);
298
+ writes.place(id, at, source.fileName ?? source.title ?? source.externalId);
269
299
  return {
270
300
  note: documentAt(id),
271
301
  created: !own,
272
302
  duplicateOf: null,
273
- kept: source.copy === null ? "text" : "copy",
303
+ kept: kept.storage,
274
304
  changed: true,
275
305
  subjects: about(id, subjects, input.by),
276
306
  };
@@ -50,15 +50,19 @@ export declare const crmStageMoves: (database: CacheDatabase, key: AccountKey, a
50
50
  through: number;
51
51
  };
52
52
  export interface CrmStageMove {
53
- /** The stage change's own id: one task per entry into a stage, never two. */
53
+ /** The stage change's own id. */
54
54
  id: number;
55
55
  kind: DealKind;
56
56
  ref: string;
57
+ /** What its task is opened from: one task per entry into a stage, never two. */
58
+ source: string;
57
59
  /** The CRM's id of the stage entered. */
58
60
  stage: string;
59
61
  stageName: string;
60
62
  pipelineName: string;
61
63
  }
64
+ /** When stage tasks were last opened, or the rules first set: where the CRM's stage history is first read from. */
65
+ export declare const crmStageTasksSince: (database: CacheDatabase, key: AccountKey) => number | null;
62
66
  export declare const saveStageMovesMark: (database: CacheDatabase, key: AccountKey, through: number, now: number) => void;
63
67
  export declare const parseCrmSettingValue: (name: CrmSettingName, value: string) => unknown;
64
68
  export declare const saveCrmSetting: (database: CacheDatabase, setting: string, value: unknown, now: number) => void;
@@ -148,12 +148,20 @@ export const crmStageMoves = (database, key, accountId) => {
148
148
  id: Number(row.id),
149
149
  kind: row.item_type,
150
150
  ref: `${String(row.item_type)}:${String(row.item_id)}`,
151
+ source: `${String(row.item_type)}:${String(row.item_id)}/move/${String(row.id)}`,
151
152
  stage: String(row.stage),
152
153
  stageName: String(row.stage_name),
153
154
  pipelineName: String(row.pipeline_name),
154
155
  }));
155
156
  return { moves, through };
156
157
  };
158
+ /** When stage tasks were last opened, or the rules first set: where the CRM's stage history is first read from. */
159
+ export const crmStageTasksSince = (database, key) => {
160
+ const row = database
161
+ .prepare("SELECT at FROM store_settings WHERE key = ?")
162
+ .get(stageTasksMark(crmSettingKey(key, "stage-tasks")));
163
+ return row ? Number(row.at) : null;
164
+ };
157
165
  export const saveStageMovesMark = (database, key, through, now) => {
158
166
  database
159
167
  .prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
@@ -0,0 +1,15 @@
1
+ import type { CrmStageEntry } from "../../domain/crm.js";
2
+ import type { AccountKey } from "../types.js";
3
+ import type { CrmStageMove } from "./crm-settings.js";
4
+ import type { StoreContext } from "./open.js";
5
+ export declare const STAGE_ENTRY_RECORD = "crm.stage-entry";
6
+ /**
7
+ * The CRM's own record of each stage a deal or lead entered, kept until its stage task is handled: a run stopped
8
+ * between reading the history and opening the tasks opens them next time. A handled entry stays, marked deleted, so
9
+ * reading the same history again opens nothing.
10
+ */
11
+ export declare const crmStageEntriesOver: (context: StoreContext) => {
12
+ save: (key: AccountKey, entries: readonly CrmStageEntry[]) => number;
13
+ pending: (key: AccountKey) => CrmStageMove[];
14
+ handled: (ids: readonly number[]) => void;
15
+ };
@@ -0,0 +1,74 @@
1
+ import { accountPk, findAccountPk } from "./accounts.js";
2
+ import { SOURCE, TABLES } from "./crm-rows.js";
3
+ import { write } from "./transaction.js";
4
+ export const STAGE_ENTRY_RECORD = "crm.stage-entry";
5
+ /**
6
+ * The CRM's own record of each stage a deal or lead entered, kept until its stage task is handled: a run stopped
7
+ * between reading the history and opening the tasks opens them next time. A handled entry stays, marked deleted, so
8
+ * reading the same history again opens nothing.
9
+ */
10
+ export const crmStageEntriesOver = (context) => {
11
+ const { database, now } = context;
12
+ /** Answers how many were new; an entry on a deal or lead the copy does not hold, or into an unknown stage, is not. */
13
+ const save = (key, entries) => write(database, () => {
14
+ const accountId = accountPk(context, key);
15
+ const at = now();
16
+ let saved = 0;
17
+ for (const entry of entries) {
18
+ const item = database
19
+ .prepare(`SELECT id FROM ${TABLES[entry.kind]} WHERE account_id = ? AND external_id = ? AND deleted_at IS NULL`)
20
+ .get(accountId, entry.item);
21
+ const stage = database
22
+ .prepare("SELECT s.id FROM pipeline_stages s JOIN pipelines p ON p.id = s.pipeline_id " +
23
+ "WHERE p.account_id = ? AND p.kind = ? AND p.external_id = ? AND s.external_id = ?")
24
+ .get(accountId, entry.kind, entry.pipeline, entry.stage);
25
+ if (!item || !stage)
26
+ continue;
27
+ const externalId = `${entry.kind}/${entry.externalId}`;
28
+ const inserted = database
29
+ .prepare("INSERT INTO records (account_id, type, external_id, fields, fingerprint, batch_id, created_at, updated_at) " +
30
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING RETURNING id")
31
+ .get(accountId, STAGE_ENTRY_RECORD, externalId, JSON.stringify({ kind: entry.kind, item_id: Number(item.id), stage_id: Number(stage.id), at: entry.at }), externalId, SOURCE, at, at);
32
+ if (!inserted)
33
+ continue;
34
+ database
35
+ .prepare("INSERT INTO record_relations (record_id, role, target_type, target_external_id, created_at) " +
36
+ "VALUES (?, 'on', ?, ?, ?)")
37
+ .run(Number(inserted.id), entry.kind, entry.item, at);
38
+ saved += 1;
39
+ }
40
+ return saved;
41
+ });
42
+ /** The entries not handled yet, oldest first, as stage moves whose task source names the CRM's history row. */
43
+ const pending = (key) => {
44
+ const accountId = findAccountPk(context, key);
45
+ if (accountId === undefined)
46
+ return [];
47
+ return database
48
+ .prepare("SELECT r.id, r.external_id, json_extract(r.fields, '$.kind') AS kind, " +
49
+ "json_extract(r.fields, '$.item_id') AS item_id, s.external_id AS stage, s.name AS stage_name, " +
50
+ "p.name AS pipeline_name FROM records r " +
51
+ "JOIN pipeline_stages s ON s.id = json_extract(r.fields, '$.stage_id') JOIN pipelines p ON p.id = s.pipeline_id " +
52
+ "WHERE r.account_id = ? AND r.type = ? AND r.deleted_at IS NULL " +
53
+ "ORDER BY json_extract(r.fields, '$.at'), r.id")
54
+ .all(accountId, STAGE_ENTRY_RECORD)
55
+ .map((row) => {
56
+ const ref = `${String(row.kind)}:${String(row.item_id)}`;
57
+ return {
58
+ id: Number(row.id),
59
+ kind: row.kind,
60
+ ref,
61
+ source: `${ref}/history/${String(row.external_id).split("/").at(-1)}`,
62
+ stage: String(row.stage),
63
+ stageName: String(row.stage_name),
64
+ pipelineName: String(row.pipeline_name),
65
+ };
66
+ });
67
+ };
68
+ const handled = (ids) => write(database, () => {
69
+ const at = now();
70
+ for (const id of ids)
71
+ database.prepare("UPDATE records SET deleted_at = ? WHERE id = ?").run(at, id);
72
+ });
73
+ return { save, pending, handled };
74
+ };
@@ -1,4 +1,4 @@
1
- import { type CrmActivity, type CrmDepartment, type CrmField, type CrmItem, type CrmKind, type CrmOrganization, type CrmPerson, type CrmPipeline, type CrmScopeSetting, type CrmUser } from "../../domain/crm.js";
1
+ import { type CrmActivity, type CrmDepartment, type CrmField, type CrmItem, type CrmKind, type CrmOrganization, type CrmPerson, type CrmPipeline, type CrmScopeSetting, type CrmStageEntry, type CrmUser } from "../../domain/crm.js";
2
2
  import { type DealKind } from "../../domain/deals.js";
3
3
  import type { AccountPeople } from "../people.js";
4
4
  import type { AccountKey } from "../types.js";
@@ -95,6 +95,13 @@ export interface CrmCopies {
95
95
  through: number;
96
96
  }>;
97
97
  markStageMoves(key: AccountKey, through: number): Promise<void>;
98
+ /** When stage tasks were last opened, or the rules first set; null without rules. */
99
+ stageTasksSince(key: AccountKey): Promise<number | null>;
100
+ /** Entries from the CRM's stage history on kept deals and leads; answers how many were new. */
101
+ saveStageEntries(key: AccountKey, entries: readonly CrmStageEntry[]): Promise<number>;
102
+ /** The stored history entries whose stage task is not handled yet, oldest first. */
103
+ stageEntries(key: AccountKey): Promise<CrmStageMove[]>;
104
+ handleStageEntries(ids: readonly number[]): Promise<void>;
98
105
  /** Whether the owner turned on reading activities and tasks (`activities` setting). */
99
106
  activitiesOn(key: AccountKey): Promise<boolean>;
100
107
  /** Activities and tasks, each on the kept deals and leads it names; one on none of them is not stored. */
@@ -7,7 +7,8 @@ import { suggestBaseStages } from "./base-suggest.js";
7
7
  import { crmActivitiesOver } from "./crm-activities.js";
8
8
  import { removeCrmContacts } from "./crm-contacts.js";
9
9
  import { crmAccountPrefix, crmIdentityId, crmRowsOver, SOURCE, TABLES, textOf } from "./crm-rows.js";
10
- import { crmActivitiesOn, crmCompanyTypes, crmOwnUser, crmScope, crmScopeUsers, crmSettingKey, crmStageMoves, crmStageTasks, saveCrmSetting, saveStageMovesMark, } from "./crm-settings.js";
10
+ import { crmActivitiesOn, crmCompanyTypes, crmOwnUser, crmScope, crmScopeUsers, crmSettingKey, crmStageMoves, crmStageTasks, crmStageTasksSince, saveCrmSetting, saveStageMovesMark, } from "./crm-settings.js";
11
+ import { crmStageEntriesOver } from "./crm-stage-entries.js";
11
12
  import { syncReportedIn } from "./reported-relations.js";
12
13
  import { clearState, syncStateOf, writeState } from "./sync.js";
13
14
  import { write } from "./transaction.js";
@@ -30,6 +31,7 @@ export const crmCopiesOver = (context, people) => {
30
31
  const { savePipeline, saveItemRow } = crmRowsOver(context);
31
32
  const account = (key) => accountPk(context, key);
32
33
  const activityStore = crmActivitiesOver(context);
34
+ const stageEntryStore = crmStageEntriesOver(context);
33
35
  /**
34
36
  * One kind's whole list: a pipeline it lacks is marked deleted, one listed again comes back. An empty list marks
35
37
  * nothing: a sign-in that lost its CRM rights lists no pipeline at all.
@@ -593,6 +595,10 @@ export const crmCopiesOver = (context, people) => {
593
595
  stageTasks: async (key) => crmStageTasks(database, key),
594
596
  stageMoves: async (key) => crmStageMoves(database, key, findAccountPk(context, key)),
595
597
  markStageMoves: async (key, through) => saveStageMovesMark(database, key, through, now()),
598
+ stageTasksSince: async (key) => crmStageTasksSince(database, key),
599
+ saveStageEntries: async (key, entries) => stageEntryStore.save(key, entries),
600
+ stageEntries: async (key) => stageEntryStore.pending(key),
601
+ handleStageEntries: async (ids) => stageEntryStore.handled(ids),
596
602
  activitiesOn: async (key) => crmActivitiesOn(database, key),
597
603
  saveActivities: async (key, activities) => activityStore.save(key, activities),
598
604
  activitiesOf: async (key, kind, externalId, limit) => activityStore.of(key, kind, externalId, limit),
@@ -1,4 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { e164Of } from "../../domain/phones.js";
2
3
  import { fold } from "../normalize.js";
3
4
  import { and, asc, desc, eq, inArray, isNotNull, isNull, ne, sql } from "./drizzle/core.js";
4
5
  import { folded } from "./folded.js";
@@ -358,7 +359,8 @@ export const meetingIdentityPk = (context, accountId, identity) => {
358
359
  if (!identity.provider || !identity.externalId)
359
360
  throw new CliError("validation_error", "Invalid identity key");
360
361
  const associatePerson = identity.associatePerson === true;
361
- const saved = saveIdentity(context, identity.provider, identity.externalId, identity.name, { metadata: identity.metadata }, false, associatePerson);
362
+ const phone = identity.phone ? e164Of(identity.phone, undefined) : undefined;
363
+ const saved = saveIdentity(context, identity.provider, identity.externalId, identity.name, { metadata: identity.metadata, ...(phone ? { phone } : {}) }, false, associatePerson);
362
364
  if (associatePerson)
363
365
  statementsOf(context.orm).seen.run({ accountId, identityId: saved.pk, createdAt: context.now() });
364
366
  return saved.pk;
@@ -32,6 +32,8 @@ export interface InvolvementStore {
32
32
  */
33
33
  forPerson(personId: number, options?: {
34
34
  scopes?: readonly string[];
35
+ /** Only rows of these subjects, such as `["meeting"]`; left out, every subject. */
36
+ subjectTypes?: readonly string[];
35
37
  since?: number;
36
38
  until?: number;
37
39
  only?: {
@@ -21,13 +21,16 @@ export const involvementStoreOver = ({ database, now }) => ({
21
21
  return { recomputed, pending: pendingInvolvements(database) };
22
22
  },
23
23
  pending: () => pendingInvolvements(database),
24
- forPerson: (personId, { scopes, since, until, only, before, limit = 100 } = {}) => {
24
+ forPerson: (personId, { scopes, subjectTypes, since, until, only, before, limit = 100 } = {}) => {
25
25
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1000)
26
26
  throw new CliError("validation_error", "involvement limit takes 1–1000");
27
27
  const filters = [
28
28
  ...(scopes === undefined
29
29
  ? []
30
30
  : [["AND i.scope IN (SELECT value FROM json_each(?))", JSON.stringify(scopes)]]),
31
+ ...(subjectTypes === undefined
32
+ ? []
33
+ : [["AND i.subject_type IN (SELECT value FROM json_each(?))", JSON.stringify(subjectTypes)]]),
31
34
  ...(since === undefined ? [] : [["AND i.occurred_at>=?", since]]),
32
35
  ...(until === undefined ? [] : [["AND i.occurred_at<=?", until]]),
33
36
  ];
@@ -42,12 +42,16 @@ export const meetingParticipantSearchOver = (context) => ({
42
42
  .get(limits.accountId)?.id);
43
43
  const rows = database
44
44
  .prepare(`SELECT p.id,
45
- coalesce(length(CAST(p.display_name AS BLOB)), 0) + coalesce(length(CAST(p.email AS BLOB)), 0) AS bytes
45
+ coalesce(length(CAST(p.display_name AS BLOB)), 0) + coalesce(length(CAST(p.email AS BLOB)), 0) +
46
+ coalesce(length(CAST(n.name AS BLOB)), 0) AS bytes
46
47
  FROM meeting_participants p JOIN meetings m ON m.id = p.meeting_id
48
+ LEFT JOIN identity_links l ON l.identity_id = p.identity_id LEFT JOIN persons n ON n.id = l.person_id
47
49
  WHERE m.account_id = ? AND m.deleted_at IS NULL AND p.id > ? AND p.id <= ?
48
50
  ORDER BY p.id LIMIT ?`)
49
51
  .all(limits.accountId, previous?.after ?? 0, until, limits.scanLimit + 1);
50
- const read = database.prepare("SELECT id, meeting_id, identity_id, display_name, email FROM meeting_participants WHERE id = ?");
52
+ const read = database.prepare("SELECT p.id, p.meeting_id, p.identity_id, p.display_name, p.email, l.person_id, n.name AS person_name " +
53
+ "FROM meeting_participants p LEFT JOIN identity_links l ON l.identity_id = p.identity_id " +
54
+ "LEFT JOIN persons n ON n.id = l.person_id WHERE p.id = ?");
51
55
  const result = {
52
56
  schema_version: 1,
53
57
  kind: "meeting_participants",
@@ -78,10 +82,11 @@ export const meetingParticipantSearchOver = (context) => ({
78
82
  throw new CliError("invalid_response", "participant observation disappeared within its snapshot");
79
83
  const name = found.display_name === null ? null : String(found.display_name);
80
84
  const email = found.email === null ? null : String(found.email);
85
+ const personName = found.person_name == null ? null : String(found.person_name);
81
86
  after = Number(row.id);
82
87
  result.coverage.scanned++;
83
88
  result.coverage.read_bytes += Number(row.bytes);
84
- if (!normalizeMeetingParticipantQuery(`${name ?? ""} ${email ?? ""}`).includes(limits.query))
89
+ if (!normalizeMeetingParticipantQuery(`${name ?? ""} ${email ?? ""} ${personName ?? ""}`).includes(limits.query))
85
90
  continue;
86
91
  result.items.push({
87
92
  participant_id: after,
@@ -89,6 +94,7 @@ export const meetingParticipantSearchOver = (context) => ({
89
94
  identity_id: Number(found.identity_id),
90
95
  display_name: name,
91
96
  email,
97
+ person: found.person_id == null ? null : { ref: `person:${found.person_id}`, name: personName },
92
98
  });
93
99
  }
94
100
  result.hasMore = result.coverage.truncated_by !== null;
@@ -111,9 +111,14 @@ const details = (database, id) => {
111
111
  meeting,
112
112
  series,
113
113
  participants: database
114
- .prepare("SELECT * FROM meeting_participants WHERE meeting_id = ? ORDER BY id")
114
+ .prepare("SELECT mp.*, l.person_id AS person_uid, p.name AS person_name FROM meeting_participants mp " +
115
+ "LEFT JOIN identity_links l ON l.identity_id = mp.identity_id LEFT JOIN persons p ON p.id = l.person_id " +
116
+ "WHERE mp.meeting_id = ? ORDER BY mp.id")
115
117
  .all(id)
116
- .map(participantOf),
118
+ .map((row) => ({
119
+ ...participantOf(row),
120
+ ...(row.person_uid == null ? {} : { person: { uid: String(row.person_uid), name: str(row.person_name) } }),
121
+ })),
117
122
  transcripts: database
118
123
  .prepare("SELECT * FROM meeting_transcripts WHERE meeting_id = ? ORDER BY id")
119
124
  .all(id)
@@ -1,7 +1,7 @@
1
1
  import { isEmailAddress, isNoReplyAddress, isPersonLikeRoleAddress, isRoleAddress } from "../../domain/addresses.js";
2
2
  import { displayName, isReadable } from "../../domain/display-names.js";
3
3
  import { variantKey } from "../../domain/name-variants.js";
4
- import { BARE_INTERNATIONAL_PROVIDERS, storedPhone } from "../../domain/phones.js";
4
+ import { BARE_INTERNATIONAL_PROVIDERS, isMobilePhone, nationalPhone, storedPhone } from "../../domain/phones.js";
5
5
  import { linkIndex, settleLinks } from "./identity-link-rows.js";
6
6
  import { openIdentityLink } from "./identity-proposals.js";
7
7
  import { peopleByNameKey, sharedTraces } from "./name-traces.js";
@@ -9,6 +9,7 @@ import { isOwner, mergePerson } from "./person-links.js";
9
9
  import { personsByIdentifiers } from "./person-matcher.js";
10
10
  import { resolvePersonLinks } from "./person-resolution.js";
11
11
  import { separated } from "./person-separation.js";
12
+ import { storePhoneCountries } from "./phone-countries.js";
12
13
  import { referenceOfThing } from "./things.js";
13
14
  import { write } from "./transaction.js";
14
15
  /** Who an automatic link is recorded as: never the owner, whose moves count as separations. */
@@ -18,7 +19,7 @@ export const RULE = { bot: "rule", kind: "rule" };
18
19
  const MOST_SHARING = 6;
19
20
  const CURSOR = "people.scan";
20
21
  /** Raised when a rule changes what a pass finds in values nobody touched: the next pass then reads everything once. */
21
- const RULES = 4;
22
+ const RULES = 5;
22
23
  /**
23
24
  * NEED-2526: a shared mailbox says little alone, so its proposal is scored by what else the two people have in common.
24
25
  * The owner's word (2026-11-11): `hr@` is often one person's, so it starts below `info@`.
@@ -43,8 +44,11 @@ export const PROPOSAL_SCORE = {
43
44
  /**
44
45
  * NEED-2445, safe option until the owner rules: a number two people share joins them only when a messenger, which
45
46
  * keeps its user's own number, holds it; a CRM's or a card's number is someone's word and waits as a proposal.
47
+ * NEED-2600: a call's other side, kept as `phone:<number>`, is that number as the phone network gave it, as strong
48
+ * as a messenger's; it joins only on a mobile number, since an office's landline is everyone's who works there.
46
49
  */
47
- const phonePairJoins = (holders) => holders.some(({ provider }) => BARE_INTERNATIONAL_PROVIDERS.includes(provider));
50
+ const phonePairJoins = (phone, holders) => holders.some(({ provider }) => BARE_INTERNATIONAL_PROVIDERS.includes(provider)) ||
51
+ (holders.some(({ externalId }) => externalId === `phone:${phone}`) && isMobilePhone(phone));
48
52
  /** NEED-2446, safe option until the owner rules: an address more than two people have is shared, so it proposes. */
49
53
  const addressGroupJoins = (people) => people <= 2;
50
54
  /** A bot or a service account shares its number or address with whoever runs it; it is nobody's person. */
@@ -99,6 +103,7 @@ const holderOf = (row) => {
99
103
  return {
100
104
  identity: Number(row.id),
101
105
  provider,
106
+ externalId: String(row.external_id),
102
107
  list: `${provider}:${String(row.external_id).replace(/[^/]*$/u, "")}`,
103
108
  company: row.company === 1,
104
109
  };
@@ -111,17 +116,36 @@ const add = (found, key, holder) => {
111
116
  held.push(holder);
112
117
  found.set(key, held);
113
118
  };
119
+ /**
120
+ * NEED-2600: a CRM keeps a number as someone typed it, `8 (912) 345-67-89`; without a `+` it is read in the store's
121
+ * `phone_countries` (Russian by default), so a call from that number finds the contact. A messenger's bare digits stay
122
+ * international (`storedPhone`).
123
+ */
124
+ const phoneKey = (raw, provider, countries) => storedPhone(raw, provider) ??
125
+ (/^\s*(\+|00)/.test(raw) || BARE_INTERNATIONAL_PROVIDERS.includes(provider)
126
+ ? undefined
127
+ : nationalPhone(raw.replace(/\(0\)/, "").replace(/\D/g, ""), countries, { anyType: true })?.value);
128
+ /** The numbers an identity holds: its phone column, and the other numbers a CRM keeps in its metadata's `phones`. */
129
+ const phonesOf = (row) => {
130
+ const raws = [row.provider === "phone" ? row.external_id : row.phone];
131
+ try {
132
+ const more = row.metadata == null ? undefined : JSON.parse(String(row.metadata)).phones;
133
+ if (Array.isArray(more))
134
+ raws.push(...more);
135
+ }
136
+ catch { }
137
+ return raws.filter((raw) => typeof raw === "string" && raw.trim() !== "");
138
+ };
114
139
  const phoneHolders = (database) => {
115
140
  const found = new Map();
141
+ const countries = storePhoneCountries(database);
116
142
  for (const row of database
117
- .prepare(`SELECT i.id, i.provider, i.external_id, i.phone, ${COMPANY} FROM identities i ` +
118
- `JOIN identity_links l ON l.identity_id = i.id WHERE (i.provider = 'phone' OR i.phone IS NOT NULL) AND ${NOT_A_BOT} ` +
119
- "ORDER BY i.id")
120
- .all()) {
121
- const provider = String(row.provider);
122
- const raw = String(provider === "phone" ? row.external_id : row.phone);
123
- add(found, storedPhone(raw, provider), holderOf(row));
124
- }
143
+ .prepare(`SELECT i.id, i.provider, i.external_id, i.phone, i.metadata, ${COMPANY} FROM identities i ` +
144
+ "JOIN identity_links l ON l.identity_id = i.id WHERE (i.provider = 'phone' OR i.phone IS NOT NULL OR " +
145
+ `(json_valid(i.metadata) AND json_extract(i.metadata, '$.phones') IS NOT NULL)) AND ${NOT_A_BOT} ORDER BY i.id`)
146
+ .all())
147
+ for (const raw of phonesOf(row))
148
+ add(found, phoneKey(raw, String(row.provider), countries), holderOf(row));
125
149
  return found;
126
150
  };
127
151
  const addressOf = (value) => {
@@ -243,14 +267,14 @@ const skipShared = (pass, people, signal) => pass.result.skipped.push({ persons:
243
267
  * A number two people have joins them (NEED-2445); one that more share, or that once proposed, proposes. A company's
244
268
  * line does neither.
245
269
  */
246
- const samePhone = (pass, holders) => {
270
+ const samePhone = (pass, phone, holders) => {
247
271
  const people = peopleOf(pass.context, holders);
248
272
  if (people.size < 2 || tooMany(pass, people, "identity.shared-phone", "phone"))
249
273
  return;
250
274
  if (sharedLine(pass.context, holders))
251
275
  return skipShared(pass, people, "phone");
252
276
  const [into, from] = [...people.keys()].sort((a, b) => a - b);
253
- if (people.size === 2 && phonePairJoins(holders) && !pass.index.known(from, into))
277
+ if (people.size === 2 && phonePairJoins(phone, holders) && !pass.index.known(from, into))
254
278
  join(pass, { from, into, identity: people.get(from), with: people.get(into) }, "phone");
255
279
  else
256
280
  proposeEachPair(pass, people, "phone");
@@ -527,9 +551,9 @@ export const scanMatches = (context, { full = false } = {}) => {
527
551
  for (const [address, holders] of emailHolders(database))
528
552
  if (holders.length > 1 && touched(holders))
529
553
  write(database, () => sameEmail(pass, address, holders));
530
- for (const holders of phoneHolders(database).values())
554
+ for (const [phone, holders] of phoneHolders(database))
531
555
  if (holders.length > 1 && touched(holders))
532
- write(database, () => samePhone(pass, holders));
556
+ write(database, () => samePhone(pass, phone, holders));
533
557
  for (const group of pass.shared)
534
558
  write(database, () => proposeShared(pass, group));
535
559
  for (const row of guestRows(database))
@@ -0,0 +1,12 @@
1
+ import { type Projection, type ProjectionTools } from "./record-projection.js";
2
+ /** A document of the envelope's own account under the record's external id: changed text is its next revision. */
3
+ declare const saveDocument: (projection: Projection, { context }: ProjectionTools) => string;
4
+ export declare const DOCUMENT_PROJECTORS: {
5
+ readonly document: {
6
+ readonly create: typeof saveDocument;
7
+ readonly update: (_ref: string, projection: Projection, tools: ProjectionTools) => true;
8
+ readonly remove: (ref: string, { context }: ProjectionTools) => void;
9
+ readonly restore: (_ref: string, projection: Projection, tools: ProjectionTools) => void;
10
+ };
11
+ };
12
+ export {};