@wirecat/cli-core 0.649.0 → 0.651.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 (81) hide show
  1. package/CHANGELOG.md +117 -0
  2. package/dist/analysis/anthropic.js +2 -1
  3. package/dist/cli/account-remove.d.ts +2 -0
  4. package/dist/cli/account-remove.js +54 -13
  5. package/dist/cli/compact.d.ts +5 -0
  6. package/dist/cli/compact.js +7 -3
  7. package/dist/cli/doctor-reports-command.d.ts +11 -0
  8. package/dist/cli/doctor-reports-command.js +57 -5
  9. package/dist/cli/help/first-screen.js +5 -0
  10. package/dist/cli/messenger/messages-search-command.js +6 -1
  11. package/dist/cli/messenger/search-answers.d.ts +3 -1
  12. package/dist/cli/messenger/search-answers.js +3 -1
  13. package/dist/cli/program.js +3 -1
  14. package/dist/cli/schedule/schedule-command.js +9 -3
  15. package/dist/cli/steps.js +9 -0
  16. package/dist/cli/unknown-profile.d.ts +4 -3
  17. package/dist/cli/unknown-profile.js +14 -6
  18. package/dist/constants/index.d.ts +7 -0
  19. package/dist/constants/index.js +16 -0
  20. package/dist/crm/cli/index.js +30 -5
  21. package/dist/crm/source.d.ts +8 -1
  22. package/dist/crm/stage-tasks.d.ts +3 -1
  23. package/dist/crm/stage-tasks.js +8 -4
  24. package/dist/crm/sync.d.ts +1 -1
  25. package/dist/crm/sync.js +54 -0
  26. package/dist/domain/crm.d.ts +15 -0
  27. package/dist/domain/phones.d.ts +2 -0
  28. package/dist/domain/phones.js +3 -0
  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 +9 -5
  37. package/dist/index.d.ts +1 -1
  38. package/dist/kit/own-catalogue.d.ts +1 -1
  39. package/dist/kit/own-catalogue.js +3 -3
  40. package/dist/meetings/answers.d.ts +5 -0
  41. package/dist/meetings/answers.js +3 -0
  42. package/dist/meetings/index.d.ts +1 -1
  43. package/dist/meetings/participant-search.d.ts +5 -0
  44. package/dist/meetings/pull.js +21 -1
  45. package/dist/meetings/read-answers.d.ts +4 -0
  46. package/dist/meetings/read-answers.js +1 -0
  47. package/dist/meetings/source.d.ts +5 -0
  48. package/dist/meetings/store.d.ts +12 -1
  49. package/dist/models/ai.js +2 -2
  50. package/dist/models/endpoint.d.ts +7 -0
  51. package/dist/models/endpoint.js +44 -0
  52. package/dist/models/index.js +2 -2
  53. package/dist/oauth/keeper.js +1 -1
  54. package/dist/sends/guard.js +8 -6
  55. package/dist/services/communications.d.ts +2 -2
  56. package/dist/services/communications.js +24 -2
  57. package/dist/services/meeting-model.js +2 -1
  58. package/dist/services/person-context.d.ts +3 -0
  59. package/dist/services/person-context.js +9 -1
  60. package/dist/services/person-meetings.d.ts +36 -0
  61. package/dist/services/person-meetings.js +57 -0
  62. package/dist/speech/openai.js +5 -2
  63. package/dist/store/path.d.ts +2 -0
  64. package/dist/store/path.js +1 -1
  65. package/dist/store/sqlite/crm-settings.d.ts +5 -1
  66. package/dist/store/sqlite/crm-settings.js +8 -0
  67. package/dist/store/sqlite/crm-stage-entries.d.ts +15 -0
  68. package/dist/store/sqlite/crm-stage-entries.js +74 -0
  69. package/dist/store/sqlite/crm.d.ts +8 -1
  70. package/dist/store/sqlite/crm.js +7 -1
  71. package/dist/store/sqlite/identities.js +3 -1
  72. package/dist/store/sqlite/involvements.d.ts +2 -0
  73. package/dist/store/sqlite/involvements.js +4 -1
  74. package/dist/store/sqlite/meeting-participant-search.js +9 -3
  75. package/dist/store/sqlite/meeting-projects.js +3 -3
  76. package/dist/store/sqlite/meetings.js +16 -2
  77. package/dist/store/sqlite/person-match-scan.d.ts +5 -0
  78. package/dist/store/sqlite/person-match-scan.js +60 -15
  79. package/dist/update/index.d.ts +1 -1
  80. package/dist/update/index.js +4 -2
  81. package/package.json +2 -2
@@ -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;
@@ -64,7 +64,7 @@ export const meetingProjectsStoreOver = ({ database, now }) => {
64
64
  .get(meeting, project);
65
65
  if (options.expectedFingerprint !== undefined &&
66
66
  (!held || linkOf(held, accountId).fingerprint !== options.expectedFingerprint))
67
- throw new CliError("configuration_error", "meeting membership changed since review", {
67
+ throw new CliError("conflict", "meeting membership changed since review", {
68
68
  reason: "meeting-project.stale",
69
69
  });
70
70
  if (held && (Number(held.confirmed) === 1 || by === "agent"))
@@ -75,8 +75,8 @@ export const meetingProjectsStoreOver = ({ database, now }) => {
75
75
  const at = now();
76
76
  if (held)
77
77
  database
78
- .prepare("UPDATE links SET confirmed=1,source='owner',author='owner',updated_at=? WHERE id=?")
79
- .run(at, Number(held.id));
78
+ .prepare("UPDATE links SET confirmed=1,source='owner',author='owner',evidence=COALESCE(?,evidence),updated_at=? WHERE id=?")
79
+ .run(options.provenance ?? null, at, Number(held.id));
80
80
  else
81
81
  database
82
82
  .prepare("INSERT INTO links (from_type,from_id,to_type,to_id,kind,source,confirmed,evidence,author,created_at,updated_at) VALUES ('meeting',?,'project',?,'member-of',?,?,?,?,?,?)")
@@ -23,6 +23,7 @@ import { meetingSeriesHistoryOver } from "./meeting-series-history.js";
23
23
  import { meetingStatsOver } from "./meeting-stats.js";
24
24
  import { invalidateMeetingStems } from "./meeting-stem-state.js";
25
25
  import { meetingOf, transcriptOf, transcriptRowOf } from "./meeting-values.js";
26
+ import { linkPhones } from "./person-match-scan.js";
26
27
  import { queryFilter } from "./query-filter.js";
27
28
  import { read, write } from "./transaction.js";
28
29
  const CURSOR_KEY = "meetings";
@@ -111,9 +112,14 @@ const details = (database, id) => {
111
112
  meeting,
112
113
  series,
113
114
  participants: database
114
- .prepare("SELECT * FROM meeting_participants WHERE meeting_id = ? ORDER BY id")
115
+ .prepare("SELECT mp.*, l.person_id AS person_uid, p.name AS person_name FROM meeting_participants mp " +
116
+ "LEFT JOIN identity_links l ON l.identity_id = mp.identity_id LEFT JOIN persons p ON p.id = l.person_id " +
117
+ "WHERE mp.meeting_id = ? ORDER BY mp.id")
115
118
  .all(id)
116
- .map(participantOf),
119
+ .map((row) => ({
120
+ ...participantOf(row),
121
+ ...(row.person_uid == null ? {} : { person: { uid: String(row.person_uid), name: str(row.person_name) } }),
122
+ })),
117
123
  transcripts: database
118
124
  .prepare("SELECT * FROM meeting_transcripts WHERE meeting_id = ? ORDER BY id")
119
125
  .all(id)
@@ -606,6 +612,14 @@ export const meetingStoreOver = (context) => {
606
612
  ...meetingHitIndexOver(context),
607
613
  ...meetingContextLinksOver(context),
608
614
  ...meetingLanguagesOver(context),
615
+ async linkCallers(provider, externalIds) {
616
+ const marks = externalIds.map(() => "?").join(", ");
617
+ const ids = database
618
+ .prepare(`SELECT id FROM identities WHERE provider = ? AND external_id IN (${marks})`)
619
+ .all(provider, ...externalIds)
620
+ .map(({ id }) => Number(id));
621
+ linkPhones(context, new Set(ids));
622
+ },
609
623
  async appendTranscriptsWithReceipt(input) {
610
624
  try {
611
625
  return append(context, input);
@@ -27,3 +27,8 @@ export declare const PROPOSAL_SCORE: {
27
27
  export declare const scanMatches: (context: StoreContext, { full }?: {
28
28
  full?: boolean;
29
29
  }) => MatchScan;
30
+ /**
31
+ * The phone rule alone, for the identities named: a meetings sync that saved callers links them to their CRM contact
32
+ * without memo's `people scan`. It moves no cursor, so the next scan still looks at these identities by every rule.
33
+ */
34
+ export declare const linkPhones: (context: StoreContext, identities: ReadonlySet<number>) => MatchScan;
@@ -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))
@@ -548,3 +572,24 @@ export const scanMatches = (context, { full = false } = {}) => {
548
572
  .run(CURSOR, JSON.stringify(started), context.now()));
549
573
  return pass.result;
550
574
  };
575
+ /**
576
+ * The phone rule alone, for the identities named: a meetings sync that saved callers links them to their CRM contact
577
+ * without memo's `people scan`. It moves no cursor, so the next scan still looks at these identities by every rule.
578
+ */
579
+ export const linkPhones = (context, identities) => {
580
+ const { database } = context;
581
+ const people = [...peopleOfIdentities(context, new Set(identities))];
582
+ write(database, () => settleLinks(database, people));
583
+ const pass = {
584
+ context,
585
+ index: linkIndex(database),
586
+ result: { full: false, merged: [], proposed: [], skipped: [] },
587
+ shared: [],
588
+ };
589
+ for (const [phone, holders] of phoneHolders(database))
590
+ if (holders.length > 1 && holders.some(({ identity }) => identities.has(identity)))
591
+ write(database, () => samePhone(pass, phone, holders));
592
+ for (const group of pass.shared)
593
+ write(database, () => proposeShared(pass, group));
594
+ return pass.result;
595
+ };
@@ -1,4 +1,4 @@
1
- import type { FetchLike } from "@wirecat/cli-base/http";
1
+ import { type FetchLike } from "@wirecat/cli-base/http";
2
2
  import { type Installer } from "@wirecat/cli-base/update";
3
3
  /** npm, the clock, the terminal and the package manager as `<app> upgrade` sees them — faked in a test. */
4
4
  export interface UpdateEnvironment {
@@ -1,6 +1,8 @@
1
1
  import { realpathSync } from "node:fs";
2
2
  import { fileURLToPath } from "node:url";
3
+ import { hostFetch } from "@wirecat/cli-base/http";
3
4
  import { installerOf, latestVersion, runUpdate as runPackageManager, updateNotice as sharedNotice, } from "@wirecat/cli-base/update";
5
+ const npmRegistry = () => hostFetch({ hosts: ["registry.npmjs.org"] });
4
6
  /** Words after which a line on stderr would land in a machine's answer, or would only repeat the command. */
5
7
  export const QUIET_WORDS = [
6
8
  "--help",
@@ -27,7 +29,7 @@ export const appUpdate = (app) => {
27
29
  };
28
30
  return {
29
31
  installer,
30
- latest: (environment = {}) => latestVersion(app.packageName, environment.fetch ?? fetch, { timeoutMs: 3000 }),
32
+ latest: (environment = {}) => latestVersion(app.packageName, environment.fetch ?? npmRegistry(), { timeoutMs: 3000 }),
31
33
  /** The package manager's output goes to stderr, so stdout stays one result. */
32
34
  runUpdate: (argv, environment = {}) => environment.spawn ? environment.spawn(argv) : runPackageManager(argv),
33
35
  /**
@@ -48,7 +50,7 @@ export const appUpdate = (app) => {
48
50
  command: app.command,
49
51
  version: app.version,
50
52
  statePath: app.statePath(env),
51
- fetch: environment.fetch ?? fetch,
53
+ fetch: environment.fetch ?? npmRegistry(),
52
54
  ...(environment.now ? { now: environment.now } : {}),
53
55
  format: pretty ? "pretty" : "json",
54
56
  stderrIsTTY: environment.stderrIsTTY ?? process.stderr.isTTY === true,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.649.0",
3
+ "version": "0.651.0",
4
4
  "description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",
@@ -283,7 +283,7 @@
283
283
  "@types/pngjs": "6.0.5",
284
284
  "@types/ssh2": "1.15.5",
285
285
  "@vitest/coverage-v8": "^5.0.5",
286
- "@wirecat/cli-base": "0.98.0",
286
+ "@wirecat/cli-base": "0.99.0",
287
287
  "@wirecat/cli-core-legacy-tags": "npm:@wirecat/cli-core@0.414.0",
288
288
  "ajv": "8.17.1",
289
289
  "commander": "15.0.0",