@wirecat/cli-core 0.621.0 → 0.623.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 (56) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/dist/background/budget.d.ts +2 -0
  3. package/dist/background/daily-archive-timer.d.ts +1 -1
  4. package/dist/background/schedules.d.ts +2 -9
  5. package/dist/background/schedules.js +10 -15
  6. package/dist/background/when.d.ts +28 -0
  7. package/dist/background/when.js +40 -0
  8. package/dist/calendar/mcp/index.d.ts +12 -12
  9. package/dist/cli/command-server-argv.d.ts +7 -0
  10. package/dist/cli/command-server-argv.js +7 -0
  11. package/dist/cli/command-server-entry.d.ts +12 -0
  12. package/dist/cli/command-server-entry.js +122 -0
  13. package/dist/cli/command-server.d.ts +29 -0
  14. package/dist/cli/command-server.js +100 -0
  15. package/dist/cli/entry.d.ts +2 -0
  16. package/dist/cli/entry.js +24 -18
  17. package/dist/cli/messenger/messages-search-command.js +4 -0
  18. package/dist/cli/program.js +8 -3
  19. package/dist/cli/schedule/schedule-command.js +14 -8
  20. package/dist/domain/display-names.d.ts +16 -0
  21. package/dist/domain/display-names.js +50 -0
  22. package/dist/errors/reasons.js +1 -0
  23. package/dist/index.d.ts +1 -0
  24. package/dist/index.js +1 -0
  25. package/dist/meetings/mcp/index.d.ts +15 -15
  26. package/dist/search/lucene/resolved.d.ts +1 -0
  27. package/dist/search/lucene/types.d.ts +8 -0
  28. package/dist/search/lucene/types.js +7 -0
  29. package/dist/services/messages-combined.js +3 -2
  30. package/dist/services/messages-discovery.js +3 -2
  31. package/dist/services/messages-search.js +1 -0
  32. package/dist/services/messages.d.ts +2 -0
  33. package/dist/services/people.js +1 -1
  34. package/dist/store/driver.d.ts +5 -1
  35. package/dist/store/driver.js +5 -0
  36. package/dist/store/identity-links.d.ts +3 -3
  37. package/dist/store/identity-links.js +3 -3
  38. package/dist/store/index.d.ts +2 -0
  39. package/dist/store/index.js +1 -0
  40. package/dist/store/people.d.ts +21 -2
  41. package/dist/store/people.js +35 -15
  42. package/dist/store/sqlite/lucene.js +12 -11
  43. package/dist/store/sqlite/manifest.js +1 -0
  44. package/dist/store/sqlite/migrations.generated.js +7 -0
  45. package/dist/store/sqlite/name-traces.d.ts +17 -0
  46. package/dist/store/sqlite/name-traces.js +112 -0
  47. package/dist/store/sqlite/notes.js +6 -3
  48. package/dist/store/sqlite/people-list.d.ts +44 -0
  49. package/dist/store/sqlite/people-list.js +151 -0
  50. package/dist/store/sqlite/person-match-scan.js +33 -0
  51. package/dist/store/sqlite/person-ties.d.ts +14 -0
  52. package/dist/store/sqlite/person-ties.js +66 -0
  53. package/dist/store/sqlite/ref-accounts.js +6 -3
  54. package/dist/store/sqlite/schema.d.ts +16 -0
  55. package/dist/store/sqlite/schema.js +3 -0
  56. package/package.json +2 -2
@@ -87,8 +87,9 @@ export const searchDiscovery = async (store, account, asked, messenger = {}, mea
87
87
  const check = () => {
88
88
  if (request.signal?.aborted)
89
89
  throw new CliError("validation_error", "search was aborted", { reason: "query.aborted", complete: false });
90
- if (performance.now() - started > QUERY_LIMITS.milliseconds)
91
- outOfTime();
90
+ const limitMs = request.timeLimitMs ?? QUERY_LIMITS.milliseconds;
91
+ if (performance.now() - started > limitMs)
92
+ outOfTime(limitMs);
92
93
  };
93
94
  const union = new Map();
94
95
  let truncated = false;
@@ -141,6 +141,7 @@ export const prepareLucene = async (store, account, request, messenger) => {
141
141
  ...(request.senders === undefined ? {} : { senders: request.senders }),
142
142
  ...(selectedChat ? { chat: selectedChat } : {}),
143
143
  ...(request.signal ? { signal: request.signal } : {}),
144
+ ...(request.timeLimitMs === undefined ? {} : { timeLimitMs: request.timeLimitMs }),
144
145
  newest: request.newest,
145
146
  ...(stemmer ? { stemmer } : {}),
146
147
  ...(unstemmed ? { unstemmed: true } : {}),
@@ -50,6 +50,8 @@ export interface SearchQuery {
50
50
  timezone?: string;
51
51
  ast?: unknown;
52
52
  signal?: AbortSignal;
53
+ /** Longer than the 2 s default when the caller set the run's time limit itself (`searchTimeLimit`). */
54
+ timeLimitMs?: number;
53
55
  chat?: string;
54
56
  /** A messenger the store holds, or `all` — the same as `in:` in the query. The account it runs as when unset. */
55
57
  source?: string;
@@ -139,7 +139,7 @@ export const peopleService = (deps) => {
139
139
  else if (known.name !== person.name || known.username !== person.username)
140
140
  changed += 1;
141
141
  }
142
- await store.people.savePeople(account, people);
142
+ await store.people.saveAddressBook(account, people);
143
143
  return {
144
144
  added,
145
145
  changed,
@@ -44,7 +44,11 @@ export type OpenDatabase = (path: string) => CacheDatabase;
44
44
  * a writer that finds the database busy fails immediately instead of waiting the moment out.
45
45
  *
46
46
  * `foreign_keys` is off by default in SQLite, which surprises everyone once.
47
+ *
48
+ * Without `journal_size_limit` the `-wal` file keeps the size of the biggest write it ever held: a 106k-row CRM
49
+ * sync left 2.2 GB behind. With it, SQLite cuts the file back to the limit each time a checkpoint resets it.
47
50
  */
48
- export declare const PRAGMAS = "\n PRAGMA busy_timeout = 5000;\n PRAGMA journal_mode = WAL;\n PRAGMA foreign_keys = ON;\n";
51
+ export declare const JOURNAL_SIZE_LIMIT: number;
52
+ export declare const PRAGMAS = "\n PRAGMA busy_timeout = 5000;\n PRAGMA journal_mode = WAL;\n PRAGMA journal_size_limit = 67108864;\n PRAGMA foreign_keys = ON;\n";
49
53
  /** A read-only open sets `query_only`: a search over it reads what is indexed and leaves building it to a writable open. */
50
54
  export declare const isQueryOnly: (database: CacheDatabase) => boolean;
@@ -30,10 +30,15 @@ export const beforeTimeLimit = (until) => {
30
30
  * a writer that finds the database busy fails immediately instead of waiting the moment out.
31
31
  *
32
32
  * `foreign_keys` is off by default in SQLite, which surprises everyone once.
33
+ *
34
+ * Without `journal_size_limit` the `-wal` file keeps the size of the biggest write it ever held: a 106k-row CRM
35
+ * sync left 2.2 GB behind. With it, SQLite cuts the file back to the limit each time a checkpoint resets it.
33
36
  */
37
+ export const JOURNAL_SIZE_LIMIT = 64 * 1024 * 1024;
34
38
  export const PRAGMAS = `
35
39
  PRAGMA busy_timeout = 5000;
36
40
  PRAGMA journal_mode = WAL;
41
+ PRAGMA journal_size_limit = ${JOURNAL_SIZE_LIMIT};
37
42
  PRAGMA foreign_keys = ON;
38
43
  `;
39
44
  /** A read-only open sets `query_only`: a search over it reads what is indexed and leaves building it to a writable open. */
@@ -3,10 +3,10 @@ import type { Author } from "./sqlite/memories.js";
3
3
  import type { IdentityRef } from "./types.js";
4
4
  export declare const IDENTITY_LINK_KIND = "identity_link";
5
5
  /**
6
- * Why two people may be one: an agent said so, they share a phone or an address with others, or a meeting guest typed
7
- * an address another person has.
6
+ * Why two people may be one: an agent said so, they share a phone or an address with others, a meeting guest typed
7
+ * an address another person has, or they have one name and share a phone, an address, a chat or a company's domain.
8
8
  */
9
- export declare const IDENTITY_LINK_SIGNALS: readonly ["agent", "phone", "email", "guest-email"];
9
+ export declare const IDENTITY_LINK_SIGNALS: readonly ["agent", "phone", "email", "guest-email", "name"];
10
10
  export type IdentityLinkSignal = (typeof IDENTITY_LINK_SIGNALS)[number];
11
11
  /** An `identity_link` proposal's payload. */
12
12
  export interface IdentityLinkPayload {
@@ -1,6 +1,6 @@
1
1
  export const IDENTITY_LINK_KIND = "identity_link";
2
2
  /**
3
- * Why two people may be one: an agent said so, they share a phone or an address with others, or a meeting guest typed
4
- * an address another person has.
3
+ * Why two people may be one: an agent said so, they share a phone or an address with others, a meeting guest typed
4
+ * an address another person has, or they have one name and share a phone, an address, a chat or a company's domain.
5
5
  */
6
- export const IDENTITY_LINK_SIGNALS = ["agent", "phone", "email", "guest-email"];
6
+ export const IDENTITY_LINK_SIGNALS = ["agent", "phone", "email", "guest-email", "name"];
@@ -77,7 +77,9 @@ export type { FileNoteInput, Link, LinkInput, LinkListFilter, Note, NoteFolder,
77
77
  export type { Order, OrderDetail, OrderFilter, OrderInput, OrdersStore } from "./sqlite/orders.js";
78
78
  export type { OrganizationFilter } from "./sqlite/organization-categories.js";
79
79
  export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
80
+ export type { ListedPerson, PeopleList, PeopleListOptions, SimilarPerson } from "./sqlite/people-list.js";
80
81
  export { mergeId, type PersonMerge, parseMergeId } from "./sqlite/person-merges.js";
82
+ export { ALWAYS_SHOWN, PERSON_TIES, type PersonTie, type ShownBecause, SMALL_GROUP_MEMBERS, } from "./sqlite/person-ties.js";
81
83
  export type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
82
84
  export type { Product, ProductFilter, ProductInput, ProductsStore, ProductUpdate } from "./sqlite/products.js";
83
85
  export { assertGenericAction, PROPOSAL_STATUSES, type ProposalInput, type ProposedAction, type ProposedActionsStore, proposerOfAction, } from "./sqlite/proposed-actions.js";
@@ -39,6 +39,7 @@ export { ORGANIZATION_KINDS, PROJECT_TYPES, SCOPES } from "./sqlite/knowledge.js
39
39
  export { NOTE_FIELDS, } from "./sqlite/note-search.js";
40
40
  export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
41
41
  export { mergeId, parseMergeId } from "./sqlite/person-merges.js";
42
+ export { ALWAYS_SHOWN, PERSON_TIES, SMALL_GROUP_MEMBERS, } from "./sqlite/person-ties.js";
42
43
  export { assertGenericAction, PROPOSAL_STATUSES, proposerOfAction, } from "./sqlite/proposed-actions.js";
43
44
  export { waitingPointer, } from "./sqlite/records.js";
44
45
  export { fillSearchIndex, resetSearchIndex, searchIndexState, } from "./sqlite/search-index.js";
@@ -3,13 +3,20 @@ import type { PeopleLookup } from "../resolve.js";
3
3
  import type { IdentityLinkDecision, IdentityLinkFilter, IdentityLinkInput, IdentityLinkRow, MatchScan } from "./identity-links.js";
4
4
  import type { ContactFilter } from "./sqlite/identities.js";
5
5
  import type { StoreContext } from "./sqlite/open.js";
6
+ import { type PeopleList, type PeopleListOptions, type SimilarPerson } from "./sqlite/people-list.js";
6
7
  import type { PersonMerge } from "./sqlite/person-merges.js";
7
8
  import { type PersonPreparationRead } from "./sqlite/person-preparation.js";
9
+ import { type ShownBecause } from "./sqlite/person-ties.js";
8
10
  import type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
9
11
  import type { ProposedAction } from "./sqlite/proposed-actions.js";
10
12
  import type { AccountKey, IdentityRef, LinkOptions, PersonFacts, PersonRecord, StoredAccount } from "./types.js";
11
13
  export interface AccountPeople {
12
14
  savePeople(key: AccountKey, people: PersonFacts[]): Promise<void>;
15
+ /**
16
+ * The account's whole address book: saves them as `savePeople` does and marks them as in the book, a tie to the
17
+ * owner; someone no longer in it loses the mark.
18
+ */
19
+ saveAddressBook(key: AccountKey, people: PersonFacts[]): Promise<void>;
13
20
  /**
14
21
  * The people this account has a one-to-one chat with — as far as the saved member lists go —
15
22
  * newest conversation first or by name.
@@ -79,8 +86,8 @@ export interface PeopleStore extends AccountPeople {
79
86
  decideLink(id: string, decision: IdentityLinkDecision): Promise<ProposedAction>;
80
87
  /**
81
88
  * One pass of the people matcher: the same address joins people in every scope, a phone exactly two people have
82
- * joins them, a phone more people share, a role address such as `info@` and a meeting guest's typed address become
83
- * proposals. Never over the owner's separation; a pair the owner rejected is proposed again only on new evidence.
89
+ * joins them, a phone more people share, a role address such as `info@`, a meeting guest's typed address, and one
90
+ * name with a shared phone, address, chat or company domain become proposals. Never over the owner's separation; a pair the owner rejected is proposed again only on new evidence.
84
91
  */
85
92
  scanMatches(options?: {
86
93
  full?: boolean;
@@ -96,6 +103,18 @@ export interface PeopleStore extends AccountPeople {
96
103
  add(input: {
97
104
  name: string;
98
105
  }): Promise<PersonRecord>;
106
+ /**
107
+ * People with their shown name, contact and ties to the owner, a page at a time. By default only those with a tie
108
+ * (a one-to-one chat, a small group, mail the owner wrote, a meeting, a CRM, the address book), the owner, people
109
+ * added by hand and people assigned a task; `all` adds the rest.
110
+ */
111
+ list(options: PeopleListOptions): Promise<PeopleList>;
112
+ /** People whose names start like the typed one, the same name first: for a form that adds a person. */
113
+ similar(name: string, options?: {
114
+ limit?: number;
115
+ }): Promise<SimilarPerson[]>;
116
+ /** Why each `person:<uid>` is shown by default, as `list` gives it; an empty list for one with no tie. */
117
+ ties(people: readonly string[]): Promise<Record<string, ShownBecause[]>>;
99
118
  }
100
119
  export declare const accountPeopleOver: (context: StoreContext) => AccountPeople;
101
120
  export declare const peopleStoreOver: (context: StoreContext, keyed: AccountPeople) => PeopleStore;
@@ -4,32 +4,46 @@ import { ownerPerson } from "./sqlite/actors.js";
4
4
  import * as identities from "./sqlite/identities.js";
5
5
  import * as identityProposals from "./sqlite/identity-proposals.js";
6
6
  import { linkToOwner } from "./sqlite/own-identities.js";
7
+ import { listPeople, similarPeople, } from "./sqlite/people-list.js";
7
8
  import * as personLinks from "./sqlite/person-links.js";
8
9
  import { RULE, scanMatches } from "./sqlite/person-match-scan.js";
9
10
  import * as personMerges from "./sqlite/person-merges.js";
10
11
  import { personPreparation } from "./sqlite/person-preparation.js";
11
12
  import { personSeenInAccounts } from "./sqlite/person-scope.js";
13
+ import { shownReasons } from "./sqlite/person-ties.js";
12
14
  import * as privatePeople from "./sqlite/private-people.js";
13
15
  import { write } from "./sqlite/transaction.js";
14
16
  export const accountPeopleOver = (context) => {
15
17
  const { database } = context;
16
18
  const { accountPk, findAccountPk, identityPk } = keysOver(context);
19
+ const save = (key, people) => {
20
+ const accountKey = accountPk(key);
21
+ const saved = [];
22
+ for (const person of people) {
23
+ saved.push(identityPk(accountKey, key.provider, person.id, person.name, person));
24
+ if (person.email)
25
+ personLinks.noteAddress(context, { provider: key.provider, id: person.id }, person.email);
26
+ }
27
+ // Every address of the batch is noted before any joins, so one shared by the whole batch is seen as shared.
28
+ for (const person of people) {
29
+ if (!person.email)
30
+ continue;
31
+ const held = personLinks.joinByAddress(context, { provider: key.provider, id: person.id }, person.email, key.provider);
32
+ if (held)
33
+ identityProposals.openIdentityLink(context, { ...held, joins: "person", signal: "email", by: RULE });
34
+ }
35
+ return saved;
36
+ };
17
37
  return {
18
- savePeople: async (key, people) => write(database, () => {
19
- const accountKey = accountPk(key);
20
- for (const person of people) {
21
- identityPk(accountKey, key.provider, person.id, person.name, person);
22
- if (person.email)
23
- personLinks.noteAddress(context, { provider: key.provider, id: person.id }, person.email);
24
- }
25
- // Every address of the batch is noted before any joins, so one shared by the whole batch is seen as shared.
26
- for (const person of people) {
27
- if (!person.email)
28
- continue;
29
- const held = personLinks.joinByAddress(context, { provider: key.provider, id: person.id }, person.email, key.provider);
30
- if (held)
31
- identityProposals.openIdentityLink(context, { ...held, joins: "person", signal: "email", by: RULE });
32
- }
38
+ savePeople: async (key, people) => {
39
+ write(database, () => save(key, people));
40
+ },
41
+ saveAddressBook: async (key, people) => write(database, () => {
42
+ const saved = JSON.stringify(save(key, people));
43
+ database
44
+ .prepare("UPDATE account_identities SET address_book = CASE WHEN identity_id IN (SELECT value FROM json_each(?)) " +
45
+ "THEN 1 END WHERE account_id = ? AND (address_book = 1 OR identity_id IN (SELECT value FROM json_each(?)))")
46
+ .run(saved, accountPk(key), saved);
33
47
  }),
34
48
  contacts: async (key, options) => {
35
49
  const accountKey = findAccountPk(key);
@@ -110,5 +124,11 @@ export const peopleStoreOver = (context, keyed) => {
110
124
  scanMatches: async (options) => scanMatches(context, options),
111
125
  linkProposals: async (filter) => identityProposals.identityLinkRows(context, filter),
112
126
  linkToOwner: async (identity) => linkToOwner(context, identity),
127
+ list: async (options) => listPeople(database, options),
128
+ similar: async (name, { limit = 8 } = {}) => similarPeople(database, name, limit),
129
+ ties: async (people) => {
130
+ const reasons = shownReasons(database);
131
+ return Object.fromEntries(people.map((ref) => [ref, reasons.get(Number(ref.replace(/^person:/, ""))) ?? []]));
132
+ },
113
133
  };
114
134
  };
@@ -56,18 +56,18 @@ export const matchingPks = (context, execution, cap) => inTime(() => {
56
56
  .all(...ranked.params, ...where.params, cap + 1);
57
57
  check();
58
58
  return rows.map(({ id }) => Number(id));
59
- });
60
- const timeLimited = (error) => {
59
+ }, execution.timeLimitMs);
60
+ const timeLimited = (limitMs) => (error) => {
61
61
  if (error instanceof TimeLimitReached)
62
- outOfTime();
62
+ outOfTime(limitMs);
63
63
  throw error;
64
64
  };
65
- const inTime = (work) => {
65
+ const inTime = (work, limitMs) => {
66
66
  try {
67
67
  return work();
68
68
  }
69
69
  catch (error) {
70
- return timeLimited(error);
70
+ return timeLimited(limitMs)(error);
71
71
  }
72
72
  };
73
73
  const compileQuery = (context, execution, boundedAttachments = false) => {
@@ -77,7 +77,8 @@ const compileQuery = (context, execution, boundedAttachments = false) => {
77
77
  if (mail && (execution.conversationIds || execution.conversationSince !== undefined))
78
78
  throw new CliError("validation_error", "mail has no conversations to search within");
79
79
  const started = context.now();
80
- const until = Date.now() + QUERY_LIMITS.milliseconds;
80
+ const limitMs = execution.timeLimitMs ?? QUERY_LIMITS.milliseconds;
81
+ const until = Date.now() + limitMs;
81
82
  const budget = { work: 0 };
82
83
  let states = 0, expansions = 0;
83
84
  const patterns = new Map();
@@ -85,8 +86,8 @@ const compileQuery = (context, execution, boundedAttachments = false) => {
85
86
  const check = () => {
86
87
  if (execution.signal?.aborted)
87
88
  throw new CliError("validation_error", "search was aborted", { reason: "query.aborted", complete: false });
88
- if (context.now() - started > QUERY_LIMITS.milliseconds)
89
- outOfTime();
89
+ if (context.now() - started > limitMs)
90
+ outOfTime(limitMs);
90
91
  };
91
92
  const patternOf = (pattern, node) => {
92
93
  check();
@@ -455,14 +456,14 @@ export const withQuerySelection = (context, execution, consume) => {
455
456
  throw new Error("query selection consumers must run synchronously");
456
457
  check();
457
458
  return result;
458
- }));
459
+ }), execution.timeLimitMs);
459
460
  };
460
461
  const runQuery = (context, execution, by) => {
461
462
  try {
462
- return runCompiled(context, execution, by).catch(timeLimited);
463
+ return runCompiled(context, execution, by).catch(timeLimited(execution.timeLimitMs));
463
464
  }
464
465
  catch (error) {
465
- return timeLimited(error);
466
+ return timeLimited(execution.timeLimitMs)(error);
466
467
  }
467
468
  };
468
469
  const runCompiled = async (context, execution, by) => {
@@ -124,6 +124,7 @@ export const MANIFEST = [
124
124
  { name: "20261108104701_version-58-enrichments-deletes", version: 58, minCompatible: 56 },
125
125
  { name: "20261108165309_version-59-templates", version: 59, minCompatible: 56 },
126
126
  { name: "20261108190101_version-60-base-stages", version: 60, minCompatible: 56 },
127
+ { name: "20261109170741_version-61-people-ties", version: 61, minCompatible: 56 },
127
128
  ];
128
129
  export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
129
130
  const migrations = [];
@@ -1224,5 +1224,12 @@ export const GENERATED = [
1224
1224
  "ALTER TABLE `pipeline_stages` ADD `base_confirmed` integer DEFAULT 0 NOT NULL;",
1225
1225
  "CREATE INDEX `pipeline_stages_by_base_stage_id` ON `pipeline_stages` (`base_stage_id`);"
1226
1226
  ]
1227
+ },
1228
+ {
1229
+ "name": "20261109170741_version-61-people-ties",
1230
+ "statements": [
1231
+ "ALTER TABLE `account_identities` ADD `address_book` integer;",
1232
+ "CREATE INDEX `account_identities_in_address_book` ON `account_identities` (`identity_id`) WHERE address_book = 1;"
1233
+ ]
1227
1234
  }
1228
1235
  ];
@@ -0,0 +1,17 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ /** People, owner aside, by the name they share once case, quotes and word order are set aside. */
3
+ export declare const peopleByNameKey: (database: CacheDatabase) => Map<string, {
4
+ people: number[];
5
+ name: string;
6
+ }>;
7
+ /** What two people with one name share: the proof that they may be one, named to the owner. */
8
+ export interface SharedTrace {
9
+ /** An identity of each side that holds it. */
10
+ identity: number;
11
+ with: number;
12
+ kind: "chat" | "email" | "email-domain" | "phone";
13
+ evidence: string[];
14
+ reason: string;
15
+ }
16
+ /** The first trace two people share, strongest first: a phone, an address, a chat, a company's domain. */
17
+ export declare const sharedTrace: (database: CacheDatabase, a: number, b: number, name: string) => SharedTrace | undefined;
@@ -0,0 +1,112 @@
1
+ import { isEmailAddress, isNoReplyAddress, isRoleAddress } from "../../domain/addresses.js";
2
+ import { displayName, nameKey } from "../../domain/display-names.js";
3
+ import { storedPhone } from "../../domain/phones.js";
4
+ import { FREE_MAIL } from "../../mail/score.js";
5
+ import { referenceOfThing } from "./things.js";
6
+ /** People, owner aside, by the name they share once case, quotes and word order are set aside. */
7
+ export const peopleByNameKey = (database) => {
8
+ const found = new Map();
9
+ for (const row of database
10
+ .prepare("SELECT p.id, p.name FROM persons p WHERE p.owner = 0 AND p.name IS NOT NULL " +
11
+ "AND EXISTS (SELECT 1 FROM identity_links l WHERE l.person_id = p.id) ORDER BY p.id")
12
+ .all()) {
13
+ const name = String(row.name);
14
+ const key = nameKey(name);
15
+ if (key === null)
16
+ continue;
17
+ const held = found.get(key) ?? { people: [], name: displayName(name) ?? name };
18
+ held.people.push(Number(row.id));
19
+ found.set(key, held);
20
+ }
21
+ return found;
22
+ };
23
+ const addressOf = (value) => {
24
+ const address = typeof value === "string" ? value.trim().toLowerCase() : "";
25
+ return isEmailAddress(address) && !isNoReplyAddress(address) ? address : undefined;
26
+ };
27
+ /** A company's domain: not a free mailbox such as gmail.com, and not from a role address such as `info@`. */
28
+ const companyDomain = (address) => {
29
+ const domain = address.split("@")[1];
30
+ return domain === undefined || FREE_MAIL.has(domain) || isRoleAddress(address) ? undefined : domain;
31
+ };
32
+ const tracesOf = (database, person) => {
33
+ const traces = { phones: [], emails: [], domains: [] };
34
+ for (const row of database
35
+ .prepare("SELECT i.id, i.provider, i.external_id, i.phone, i.email FROM identity_links l " +
36
+ "JOIN identities i ON i.id = l.identity_id WHERE l.person_id = ? AND i.provider <> 'org-email' ORDER BY i.id")
37
+ .all(person)) {
38
+ const identity = Number(row.id);
39
+ const provider = String(row.provider);
40
+ const phone = provider === "phone" ? row.external_id : row.phone;
41
+ const stored = typeof phone === "string" ? storedPhone(phone, provider) : undefined;
42
+ if (stored !== undefined)
43
+ traces.phones.push({ identity, value: stored });
44
+ for (const address of [addressOf(row.email), provider === "email" ? addressOf(row.external_id) : undefined]) {
45
+ if (address === undefined)
46
+ continue;
47
+ traces.emails.push({ identity, value: address });
48
+ const domain = companyDomain(address);
49
+ if (domain !== undefined)
50
+ traces.domains.push({ identity, value: domain });
51
+ }
52
+ }
53
+ return traces;
54
+ };
55
+ const common = (a, b) => {
56
+ for (const one of a) {
57
+ const other = b.find(({ value }) => value === one.value);
58
+ if (other !== undefined)
59
+ return [one, other];
60
+ }
61
+ return undefined;
62
+ };
63
+ const commonChat = (database, a, b) => database
64
+ .prepare("SELECT m1.chat_id, m1.identity_id AS one, m2.identity_id AS other FROM identity_links l1 " +
65
+ "JOIN chat_members m1 ON m1.identity_id = l1.identity_id " +
66
+ "JOIN chat_members m2 ON m2.chat_id = m1.chat_id " +
67
+ "JOIN identity_links l2 ON l2.identity_id = m2.identity_id " +
68
+ "WHERE l1.person_id = ? AND l2.person_id = ? ORDER BY m1.chat_id LIMIT 1")
69
+ .get(a, b);
70
+ /** The first trace two people share, strongest first: a phone, an address, a chat, a company's domain. */
71
+ export const sharedTrace = (database, a, b, name) => {
72
+ const [one, other] = [tracesOf(database, a), tracesOf(database, b)];
73
+ const phone = common(one.phones, other.phones);
74
+ if (phone)
75
+ return {
76
+ identity: phone[0].identity,
77
+ with: phone[1].identity,
78
+ kind: "phone",
79
+ evidence: [],
80
+ reason: `same name «${name}» and the same phone`,
81
+ };
82
+ const email = common(one.emails, other.emails);
83
+ if (email)
84
+ return {
85
+ identity: email[0].identity,
86
+ with: email[1].identity,
87
+ kind: "email",
88
+ evidence: [],
89
+ reason: `same name «${name}» and the same address ${email[0].value}`,
90
+ };
91
+ const chat = commonChat(database, a, b);
92
+ if (chat) {
93
+ const ref = referenceOfThing(database, { type: "chat", id: Number(chat.chat_id) });
94
+ return {
95
+ identity: Number(chat.one),
96
+ with: Number(chat.other),
97
+ kind: "chat",
98
+ evidence: ref === undefined ? [] : [ref],
99
+ reason: `same name «${name}» and a chat they are both in`,
100
+ };
101
+ }
102
+ const domain = common(one.domains, other.domains);
103
+ if (domain)
104
+ return {
105
+ identity: domain[0].identity,
106
+ with: domain[1].identity,
107
+ kind: "email-domain",
108
+ evidence: [],
109
+ reason: `same name «${name}» and mail at the same company, ${domain[0].value}`,
110
+ };
111
+ return undefined;
112
+ };
@@ -650,11 +650,14 @@ export const notesStoreOver = (context) => {
650
650
  const id = Number(documentRow(documentId).id);
651
651
  database.prepare("DELETE FROM links WHERE from_type = 'document' AND from_id = ? AND source = 'file'").run(id);
652
652
  const written = links.map((link) => insertLink(context, { ...link, from: `document:${id}`, origin: "file" }));
653
- // What a file's source says, such as a Drive owner, is reported by its account, not waiting for review.
653
+ // What a file's source says, such as a Drive owner (`google-drive:files.get`), is reported by its account,
654
+ // not waiting for review. A program's guess (`scan`) or an agent's (`agent:…`) still waits.
654
655
  database
655
656
  .prepare("UPDATE links SET account_id = (SELECT account_id FROM documents WHERE id = ?) WHERE from_type = 'document' " +
656
- `AND from_id = ? AND source = 'file' AND confirmed = 0 AND account_id IS NULL AND kind IN (${RELATIONSHIPS})`)
657
- .run(id, id);
657
+ `AND from_id = ? AND source = 'file' AND confirmed = 0 AND account_id IS NULL AND kind IN (${RELATIONSHIPS}) ` +
658
+ "AND (SELECT substr(json_extract(links.metadata, '$.provenance'), 1, length(a.provider) + 1) = " +
659
+ "a.provider || ':' FROM documents d JOIN accounts a ON a.id = d.account_id WHERE d.id = ?)")
660
+ .run(id, id, id);
658
661
  const reread = database.prepare("SELECT * FROM links WHERE id = ?");
659
662
  return written.map((link) => linkOf(database, reread.get(Number(link.id))));
660
663
  }),
@@ -0,0 +1,44 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ import { type ShownBecause } from "./person-ties.js";
3
+ export interface PeopleListOptions {
4
+ /** Part of a name or username, at least 3 characters. */
5
+ query?: string;
6
+ /** Also the people with no tie to the owner. */
7
+ all?: boolean;
8
+ /** `tasks`: the owner, then by how many tasks name them, then by name. */
9
+ sort?: "tasks" | "name";
10
+ limit: number;
11
+ offset?: number;
12
+ }
13
+ export interface ListedPerson {
14
+ person: string;
15
+ /** As stored; `displayName` is what to show. */
16
+ name: string | null;
17
+ displayName: string | null;
18
+ owner: boolean;
19
+ tasks: number;
20
+ username: string | null;
21
+ phone: string | null;
22
+ email: string | null;
23
+ /** Why they are shown; empty for someone hidden by default. */
24
+ ties: ShownBecause[];
25
+ }
26
+ export interface PeopleList {
27
+ items: ListedPerson[];
28
+ hasMore: boolean;
29
+ /** Everyone the list holds over every page. */
30
+ total: number;
31
+ /** The people matching that have no tie to the owner, shown only with `all`. */
32
+ hidden: number;
33
+ }
34
+ export interface SimilarPerson extends ListedPerson {
35
+ /** The same name once case, quotes, punctuation and word order are set aside: maybe the same person. */
36
+ sameName: boolean;
37
+ }
38
+ /** People by name or by task count, the owner first; by default only those with a tie to the owner. */
39
+ export declare const listPeople: (database: CacheDatabase, options: PeopleListOptions) => PeopleList;
40
+ /**
41
+ * People whose name, or a name of one of their identities, has a word starting with each typed word, for a form
42
+ * that adds a person: the same name first (maybe a duplicate), then those with a tie to the owner, then by name.
43
+ */
44
+ export declare const similarPeople: (database: CacheDatabase, typed: string, limit: number) => SimilarPerson[];