@wirecat/cli-core 0.622.0 → 0.624.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 (69) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/dist/background/backfill.d.ts +1 -1
  3. package/dist/background/backfill.js +1 -1
  4. package/dist/background/budget.d.ts +2 -0
  5. package/dist/background/report/stored-templates.d.ts +21 -3
  6. package/dist/background/report/stored-templates.js +34 -6
  7. package/dist/background/schedules.d.ts +10 -27
  8. package/dist/background/schedules.js +8 -167
  9. package/dist/background/timers.d.ts +19 -0
  10. package/dist/background/timers.js +175 -0
  11. package/dist/background/when.d.ts +49 -0
  12. package/dist/background/when.js +84 -0
  13. package/dist/calendar/mcp/index.d.ts +12 -12
  14. package/dist/calendar/prepare.d.ts +14 -0
  15. package/dist/cli/app-doctor-command.js +2 -1
  16. package/dist/cli/envelope.d.ts +28 -0
  17. package/dist/cli/index.d.ts +3 -2
  18. package/dist/cli/index.js +3 -2
  19. package/dist/cli/messenger/messages-search-command.js +4 -0
  20. package/dist/cli/program.js +6 -3
  21. package/dist/cli/schedule/schedule-command.d.ts +100 -3
  22. package/dist/cli/schedule/schedule-command.js +277 -113
  23. package/dist/cli/templates-command.js +45 -20
  24. package/dist/domain/display-names.d.ts +19 -0
  25. package/dist/domain/display-names.js +59 -0
  26. package/dist/domain/person-kinds.d.ts +9 -0
  27. package/dist/domain/person-kinds.js +67 -0
  28. package/dist/entities/index.d.ts +2 -1
  29. package/dist/entities/list-results.d.ts +2 -0
  30. package/dist/entities/list-results.js +2 -0
  31. package/dist/entities/template.d.ts +1 -1
  32. package/dist/entities/template.js +1 -1
  33. package/dist/errors/reasons.js +1 -0
  34. package/dist/index.d.ts +1 -0
  35. package/dist/index.js +1 -0
  36. package/dist/mcp/surface.js +23 -2
  37. package/dist/search/lucene/resolved.d.ts +1 -0
  38. package/dist/search/lucene/types.d.ts +8 -0
  39. package/dist/search/lucene/types.js +7 -0
  40. package/dist/services/index.d.ts +1 -1
  41. package/dist/services/index.js +1 -1
  42. package/dist/services/messages-combined.js +3 -2
  43. package/dist/services/messages-discovery.js +3 -2
  44. package/dist/services/messages-search.js +1 -0
  45. package/dist/services/messages.d.ts +2 -0
  46. package/dist/services/people.js +1 -1
  47. package/dist/services/search-harder.d.ts +6 -1
  48. package/dist/services/search-harder.js +9 -2
  49. package/dist/store/identity-links.d.ts +3 -3
  50. package/dist/store/identity-links.js +3 -3
  51. package/dist/store/index.d.ts +3 -0
  52. package/dist/store/index.js +3 -0
  53. package/dist/store/people.d.ts +21 -2
  54. package/dist/store/people.js +35 -15
  55. package/dist/store/sqlite/lucene.js +12 -11
  56. package/dist/store/sqlite/manifest.js +1 -0
  57. package/dist/store/sqlite/migrations.generated.js +7 -0
  58. package/dist/store/sqlite/name-traces.d.ts +17 -0
  59. package/dist/store/sqlite/name-traces.js +112 -0
  60. package/dist/store/sqlite/notes.js +6 -3
  61. package/dist/store/sqlite/people-list.d.ts +59 -0
  62. package/dist/store/sqlite/people-list.js +275 -0
  63. package/dist/store/sqlite/person-match-scan.js +33 -0
  64. package/dist/store/sqlite/person-ties.d.ts +14 -0
  65. package/dist/store/sqlite/person-ties.js +66 -0
  66. package/dist/store/sqlite/schema.d.ts +16 -0
  67. package/dist/store/sqlite/schema.js +3 -0
  68. package/package.json +3 -3
  69. package/parity.json +29 -0
@@ -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"];
@@ -1,6 +1,7 @@
1
1
  export type { ContextEvidenceItem, ContextEvidencePage, ContextEvidenceReader, ContextEvidenceRequest, ContextEvidenceSender, ContextSource, } from "../context/evidence.js";
2
2
  export { BUSINESS_KINDS, type BusinessKind } from "../domain/business.js";
3
3
  export { FACT_STATUSES, FACT_TYPES, MEMORY_KINDS, MEMORY_SCOPES, MEMORY_STATUSES, TASK_TYPES, WORK_TASK_TYPES, } from "../domain/knowledge.js";
4
+ export { type KindSignal, PERSON_KINDS, type PersonKind } from "../domain/person-kinds.js";
4
5
  export type { RefState, RefSummary, RefSummaryKind, RefsStore } from "../domain/ref-summaries.js";
5
6
  export type { TagConsolidationApplyOptions, TagConsolidationOptions, TagConsolidationPreview, TagConsolidationReceipt, TagConsolidationStore, } from "../domain/tag-consolidation.js";
6
7
  export type { TagRedirectIndex, TagRedirectResolution, TagRedirectSnapshot } from "../domain/tag-redirects.js";
@@ -77,7 +78,9 @@ export type { FileNoteInput, Link, LinkInput, LinkListFilter, Note, NoteFolder,
77
78
  export type { Order, OrderDetail, OrderFilter, OrderInput, OrdersStore } from "./sqlite/orders.js";
78
79
  export type { OrganizationFilter } from "./sqlite/organization-categories.js";
79
80
  export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
81
+ export { type ListedPerson, PEOPLE_SORTS, type PeopleList, type PeopleListOptions, type PeopleSort, type SimilarPerson, } from "./sqlite/people-list.js";
80
82
  export { mergeId, type PersonMerge, parseMergeId } from "./sqlite/person-merges.js";
83
+ export { ALWAYS_SHOWN, PERSON_TIES, type PersonTie, type ShownBecause, SMALL_GROUP_MEMBERS, } from "./sqlite/person-ties.js";
81
84
  export type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
82
85
  export type { Product, ProductFilter, ProductInput, ProductsStore, ProductUpdate } from "./sqlite/products.js";
83
86
  export { assertGenericAction, PROPOSAL_STATUSES, type ProposalInput, type ProposedAction, type ProposedActionsStore, proposerOfAction, } from "./sqlite/proposed-actions.js";
@@ -1,5 +1,6 @@
1
1
  export { BUSINESS_KINDS } from "../domain/business.js";
2
2
  export { FACT_STATUSES, FACT_TYPES, MEMORY_KINDS, MEMORY_SCOPES, MEMORY_STATUSES, TASK_TYPES, WORK_TASK_TYPES, } from "../domain/knowledge.js";
3
+ export { PERSON_KINDS } from "../domain/person-kinds.js";
3
4
  export { createTagRedirectIndex } from "../domain/tag-redirects.js";
4
5
  export { note } from "../entities/note.js";
5
6
  export { PAYMENT_DIRECTIONS, PAYMENT_STATES, paymentTitle, validatePayment } from "../meetings/index.js";
@@ -38,7 +39,9 @@ export { IMPORTED_DOCUMENT_QUERY } from "./sqlite/imported-documents.js";
38
39
  export { ORGANIZATION_KINDS, PROJECT_TYPES, SCOPES } from "./sqlite/knowledge.js";
39
40
  export { NOTE_FIELDS, } from "./sqlite/note-search.js";
40
41
  export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
42
+ export { PEOPLE_SORTS, } from "./sqlite/people-list.js";
41
43
  export { mergeId, parseMergeId } from "./sqlite/person-merges.js";
44
+ export { ALWAYS_SHOWN, PERSON_TIES, SMALL_GROUP_MEMBERS, } from "./sqlite/person-ties.js";
42
45
  export { assertGenericAction, PROPOSAL_STATUSES, proposerOfAction, } from "./sqlite/proposed-actions.js";
43
46
  export { waitingPointer, } from "./sqlite/records.js";
44
47
  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 of one kind with their shown name, contact, interactions and ties, a page at a time. `person` (the default)
108
+ * is the owner, people added by hand, task assignees, and named people with a tie (a one-to-one chat, a small group,
109
+ * mail the owner wrote, a meeting, a CRM, the address book); `automated`, `organization` and `unsorted` hold 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,59 @@
1
+ import { type KindSignal, type PersonKind } from "../../domain/person-kinds.js";
2
+ import type { CacheDatabase } from "../driver.js";
3
+ import { type ShownBecause } from "./person-ties.js";
4
+ export declare const PEOPLE_SORTS: readonly ["interactions", "recent", "name", "tasks"];
5
+ export type PeopleSort = (typeof PEOPLE_SORTS)[number];
6
+ export interface PeopleListOptions {
7
+ /** Part of a name or username, at least 3 characters. */
8
+ query?: string;
9
+ /** One kind, `person` by default, or `all`. */
10
+ kind?: PersonKind | "all";
11
+ /**
12
+ * The owner first, then `interactions`: most messages and mail from them; `recent`: newest contact; `name`; `tasks`:
13
+ * how many tasks name them. Equal rows by name.
14
+ */
15
+ sort?: PeopleSort;
16
+ limit: number;
17
+ offset?: number;
18
+ }
19
+ export interface ListedPerson {
20
+ person: string;
21
+ /** As stored; `displayName` is what to show. */
22
+ name: string | null;
23
+ displayName: string | null;
24
+ kind: PersonKind;
25
+ /** What decided the kind: the ties for a `person`, else the signal. */
26
+ kindSignals: (ShownBecause | KindSignal)[];
27
+ owner: boolean;
28
+ tasks: number;
29
+ /** The one to show beside the name: the phone, else the email, else `@username`. */
30
+ contact: string | null;
31
+ username: string | null;
32
+ phone: string | null;
33
+ email: string | null;
34
+ /** Messages and mail this person sent, every account together. */
35
+ messagesFrom: number;
36
+ /** The newest of their messages, their mail and their one-to-one chat's last message, as ISO time. */
37
+ lastContact: string | null;
38
+ /** Why they are shown; empty for someone hidden by default. */
39
+ ties: ShownBecause[];
40
+ }
41
+ export interface PeopleList {
42
+ items: ListedPerson[];
43
+ hasMore: boolean;
44
+ /** The people of the kind asked over every page. */
45
+ total: number;
46
+ /** How many of each kind match the query. */
47
+ counts: Record<PersonKind, number>;
48
+ }
49
+ export interface SimilarPerson extends ListedPerson {
50
+ /** The same name once case, quotes, punctuation and word order are set aside: maybe the same person. */
51
+ sameName: boolean;
52
+ }
53
+ /** People of one kind, the owner first, in the order asked; `counts` says how many each kind holds. */
54
+ export declare const listPeople: (database: CacheDatabase, options: PeopleListOptions) => PeopleList;
55
+ /**
56
+ * People whose name, or a name of one of their identities, has a word starting with each typed word, for a form
57
+ * that adds a person: the same name first (maybe a duplicate), then those with a tie to the owner, then by name.
58
+ */
59
+ export declare const similarPeople: (database: CacheDatabase, typed: string, limit: number) => SimilarPerson[];