@wirecat/cli-core 0.634.0 → 0.636.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 (66) hide show
  1. package/CHANGELOG.md +112 -0
  2. package/dist/cli/bot/people.js +1 -1
  3. package/dist/cli/messenger/contacts-command.js +6 -2
  4. package/dist/domain/display-names.d.ts +20 -2
  5. package/dist/domain/display-names.js +21 -2
  6. package/dist/entities/contact-activity.d.ts +2 -0
  7. package/dist/entities/contact-activity.js +2 -0
  8. package/dist/entities/contact-context.d.ts +3 -0
  9. package/dist/entities/index.d.ts +3 -0
  10. package/dist/errors/reasons.js +9 -0
  11. package/dist/search/groups.d.ts +2 -0
  12. package/dist/search/groups.js +1 -0
  13. package/dist/services/account-groups.d.ts +30 -1
  14. package/dist/services/account-groups.js +27 -0
  15. package/dist/services/index.d.ts +1 -1
  16. package/dist/services/index.js +1 -1
  17. package/dist/services/metadata.d.ts +1 -1
  18. package/dist/services/people.d.ts +5 -1
  19. package/dist/services/people.js +18 -5
  20. package/dist/services/stored-project-gathering.d.ts +2 -0
  21. package/dist/services/stored-project-gathering.js +1 -1
  22. package/dist/store/accounts.d.ts +10 -1
  23. package/dist/store/accounts.js +3 -2
  24. package/dist/store/chats.d.ts +5 -0
  25. package/dist/store/chats.js +6 -0
  26. package/dist/store/exports.d.ts +1 -1
  27. package/dist/store/identity-links.d.ts +23 -0
  28. package/dist/store/identity-splits.d.ts +2 -0
  29. package/dist/store/index.d.ts +2 -2
  30. package/dist/store/keys.d.ts +1 -1
  31. package/dist/store/keys.js +1 -1
  32. package/dist/store/people.d.ts +17 -5
  33. package/dist/store/people.js +10 -3
  34. package/dist/store/sqlite/accounts.d.ts +12 -2
  35. package/dist/store/sqlite/accounts.js +42 -3
  36. package/dist/store/sqlite/address-organization.d.ts +18 -0
  37. package/dist/store/sqlite/address-organization.js +48 -0
  38. package/dist/store/sqlite/chats.d.ts +3 -1
  39. package/dist/store/sqlite/chats.js +8 -0
  40. package/dist/store/sqlite/identity-link-rows.d.ts +5 -1
  41. package/dist/store/sqlite/identity-link-rows.js +9 -3
  42. package/dist/store/sqlite/identity-proposals.d.ts +5 -3
  43. package/dist/store/sqlite/identity-proposals.js +85 -8
  44. package/dist/store/sqlite/identity-split-proposals.d.ts +5 -0
  45. package/dist/store/sqlite/identity-split-proposals.js +29 -1
  46. package/dist/store/sqlite/mail-findings.js +10 -44
  47. package/dist/store/sqlite/manifest.js +2 -0
  48. package/dist/store/sqlite/migrations.generated.js +14 -0
  49. package/dist/store/sqlite/name-traces.d.ts +5 -2
  50. package/dist/store/sqlite/name-traces.js +8 -5
  51. package/dist/store/sqlite/open-store.js +2 -0
  52. package/dist/store/sqlite/people-list.js +15 -9
  53. package/dist/store/sqlite/person-doubts.d.ts +15 -1
  54. package/dist/store/sqlite/person-doubts.js +51 -9
  55. package/dist/store/sqlite/person-links.d.ts +7 -2
  56. package/dist/store/sqlite/person-links.js +33 -2
  57. package/dist/store/sqlite/person-match-scan.d.ts +14 -0
  58. package/dist/store/sqlite/person-match-scan.js +101 -5
  59. package/dist/store/sqlite/person-merges.d.ts +1 -0
  60. package/dist/store/sqlite/person-merges.js +4 -8
  61. package/dist/store/sqlite/task-titles.d.ts +12 -1
  62. package/dist/store/sqlite/task-titles.js +42 -1
  63. package/dist/store/sqlite/tasks.js +6 -1
  64. package/dist/store/types.d.ts +6 -0
  65. package/package.json +3 -3
  66. package/parity.json +6 -3
@@ -25,6 +25,11 @@ export interface ChatsStore {
25
25
  countChats(key: AccountKey, filter?: StoredChatFilter): Promise<number>;
26
26
  /** The chats a person is in, newest first — as far as the saved member lists go. */
27
27
  chatsWith(key: AccountKey, memberId: Id): Promise<Chat[]>;
28
+ /**
29
+ * The owner pins one chat to a scope, or with `null` lets it follow its account again; `false` when the store does
30
+ * not know the chat. Its conversation pieces and involvements follow; its messages' search pieces keep the account's.
31
+ */
32
+ setChatScope(key: AccountKey, chatId: Id, scope: StoredAccount["scope"] | null): Promise<boolean>;
28
33
  /** Each stored chat's scope, its own or else its account's; a chat the store lacks is left out. */
29
34
  chatScopes(key: AccountKey, chatIds: readonly Id[]): Promise<Map<Id, StoredAccount["scope"]>>;
30
35
  /**
@@ -31,6 +31,12 @@ export const chatsStoreOver = (context) => {
31
31
  const accountKey = findAccountPk(key);
32
32
  return accountKey === undefined ? [] : chatQueries.chatsWith(context, accountKey, key, memberId);
33
33
  },
34
+ setChatScope: async (key, chatId, scope) => {
35
+ const accountKey = findAccountPk(key);
36
+ if (accountKey === undefined)
37
+ return false;
38
+ return write(database, () => chatQueries.setChatScope(context, accountKey, chatId, scope));
39
+ },
34
40
  chatScopes: async (key, chatIds) => {
35
41
  const accountKey = findAccountPk(key);
36
42
  return accountKey === undefined
@@ -70,5 +70,5 @@ export type { MatchPlace, ScoredHit } from "./sqlite/words.js";
70
70
  export type { TaskDetails } from "./sqlite/work-tasks.js";
71
71
  export type { SyncStore } from "./sync.js";
72
72
  export type { TagsStore } from "./tags.js";
73
- export type { AccountKey, AccountMessageFilter, AgentAnswer, BatchMessage, ChatActivity, ChatStats, ConversationBuild, ConversationHit, ConversationSummary, DeletionScope, Delta, IdentityRef, IngestedVia, LinkBatch, LinkedIdentity, LinkOptions, MessageFilter, PersonFacts, PersonRecord, PictureInput, Range, SenderChatStats, StoredAccount, StoredChatFilter, StoredHit, StoredLink, StoredReadiness, TaskAnalysisMark, TaskAnalysisMarkWrite, } from "./types.js";
73
+ export type { AccountKey, AccountMessageFilter, AgentAnswer, BatchMessage, ChatActivity, ChatStats, ConversationBuild, ConversationHit, ConversationSummary, DeletionScope, Delta, IdentityRef, IngestedVia, LinkBatch, LinkedIdentity, LinkOptions, MessageFilter, PersonFacts, PersonRecord, PictureInput, Range, SenderChatStats, StoredAccount, StoredChatFilter, StoredHit, StoredLink, StoredReadiness, TaskAnalysisMark, TaskAnalysisMarkWrite, UnlinkOptions, } from "./types.js";
74
74
  export type { AccountVectors, VectorsStore } from "./vectors.js";
@@ -9,6 +9,8 @@ export declare const IDENTITY_LINK_KIND = "identity_link";
9
9
  */
10
10
  export declare const IDENTITY_LINK_SIGNALS: readonly ["agent", "phone", "email", "guest-email", "name", "account"];
11
11
  export type IdentityLinkSignal = (typeof IDENTITY_LINK_SIGNALS)[number];
12
+ /** A mailbox more than one person reads: a role address such as `info@`, or a company's line (`sharedLine`). */
13
+ export type SharedMailbox = "role" | "line";
12
14
  /** An `identity_link` proposal's payload. */
13
15
  export interface IdentityLinkPayload {
14
16
  /** `provider:id` of the identity that would move. */
@@ -26,6 +28,10 @@ export interface IdentityLinkPayload {
26
28
  /** Every person the signal points at, the two included, when it points at more than two. */
27
29
  candidates?: string[];
28
30
  evidence: string[];
31
+ /** The address both people have is a shared mailbox; absent on proposals made before it was recorded. */
32
+ shared?: SharedMailbox;
33
+ /** The shared mailbox's address, with `shared`. */
34
+ mailbox?: string;
29
35
  }
30
36
  export interface IdentityLinkInput {
31
37
  identity: IdentityRef;
@@ -41,6 +47,17 @@ export interface IdentityLinkDecision {
41
47
  /** `"owner"` only on a path that established the owner decides; an agent is refused whatever the policy says. */
42
48
  by: Decider;
43
49
  reason?: string;
50
+ /**
51
+ * With `confirm: false` on a shared-mailbox proposal: the address is this organization's, not one of the two people.
52
+ * `organization` names one; otherwise the one holding the address or its company domain, or one of `name`, or a new
53
+ * company named `name` or the domain. `all` closes every open proposal on the same mailbox in this one decision;
54
+ * the decided proposal's result lists them all as `closed`.
55
+ */
56
+ company?: {
57
+ organization?: number;
58
+ name?: string;
59
+ all?: boolean;
60
+ };
44
61
  }
45
62
  /** One `identity_link`, naming the people as they are now, not as they were when it was proposed. */
46
63
  export interface IdentityLinkRow {
@@ -53,6 +70,10 @@ export interface IdentityLinkRow {
53
70
  joins: IdentityLinkPayload["joins"];
54
71
  signal: IdentityLinkSignal;
55
72
  score: number | null;
73
+ /** The address the two people share is a role address (`role`) or a company's line (`line`), not one person's. */
74
+ shared: SharedMailbox | null;
75
+ /** That shared address, which `decideLink` with `company` gives to an organization. */
76
+ mailbox: string | null;
56
77
  candidates: string[];
57
78
  reason: string | null;
58
79
  evidence: string[];
@@ -64,6 +85,8 @@ export interface IdentityLinkFilter {
64
85
  person?: string;
65
86
  /** `proposed` unless named. */
66
87
  status?: IdentityLinkRow["status"] | "all";
88
+ /** `score`: highest score first, proposals without one last, each newest first; newest first otherwise. */
89
+ order?: "newest" | "score";
67
90
  limit: number;
68
91
  offset: number;
69
92
  }
@@ -24,6 +24,8 @@ export interface IdentitySplitPayload {
24
24
  /** Either the identities that leave, all of one person, or the merge to undo. */
25
25
  export type IdentitySplitInput = ({
26
26
  identities: IdentityRef[];
27
+ /** The uid of the person they leave; refused when they sit on someone else. */
28
+ from?: string;
27
29
  } | {
28
30
  merge: string;
29
31
  }) & {
@@ -20,7 +20,7 @@ export type { CacheDatabase, CacheStatement, OpenDatabase, SqlValue } from "./dr
20
20
  export { PRAGMAS } from "./driver.js";
21
21
  export { type CitableRecord, EVIDENCE_FINDINGS_KIND, type EvidenceFindingsBatch, type EvidenceFindingsDecider, type EvidenceFindingsReceipt, type EvidenceFindingsStore, validateEvidenceFindings, } from "./evidence-findings.js";
22
22
  export { type DamagedTable, type InvalidJson, QUICK_HEALTH_CHECKS, type SearchIndexHealth, type StoreHealth, storeHealth, } from "./health.js";
23
- export { IDENTITY_LINK_KIND, IDENTITY_LINK_SIGNALS, type IdentityLinkDecision, type IdentityLinkFilter, type IdentityLinkInput, type IdentityLinkPayload, type IdentityLinkRow, type IdentityLinkSignal, type MatchScan, } from "./identity-links.js";
23
+ export { IDENTITY_LINK_KIND, IDENTITY_LINK_SIGNALS, type IdentityLinkDecision, type IdentityLinkFilter, type IdentityLinkInput, type IdentityLinkPayload, type IdentityLinkRow, type IdentityLinkSignal, type MatchScan, type SharedMailbox, } from "./identity-links.js";
24
24
  export { IDENTITY_SPLIT_KIND, type IdentitySplitDecision, type IdentitySplitFilter, type IdentitySplitInput, type IdentitySplitMove, type IdentitySplitPayload, type IdentitySplitRow, } from "./identity-splits.js";
25
25
  export { ORGANIZATIONS_QUERY, organization, PROJECTS_QUERY, project, REMINDERS_QUERY, reminder, } from "./knowledge-query.js";
26
26
  export { MAIL_FINDINGS_KIND, type MailFindingsBatch, type MailFindingsCheck, type MailFindingsStore, } from "./mail-findings.js";
@@ -80,7 +80,7 @@ export type { Order, OrderDetail, OrderFilter, OrderInput, OrdersStore } from ".
80
80
  export type { OrganizationFilter } from "./sqlite/organization-categories.js";
81
81
  export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
82
82
  export { type ListedPerson, PEOPLE_SORTS, type PeopleList, type PeopleListOptions, type PeopleSort, type SimilarPerson, } from "./sqlite/people-list.js";
83
- export { DOUBT_REASONS, type DoubtIdentity, type DoubtMove, type DoubtReason, type PersonDoubt, type PersonDoubts, } from "./sqlite/person-doubts.js";
83
+ export { DOUBT_REASONS, type DoubtIdentity, type DoubtMove, type DoubtReason, type KeptPerson, type PersonDoubt, type PersonDoubts, } from "./sqlite/person-doubts.js";
84
84
  export { mergeId, type PersonMerge, parseMergeId } from "./sqlite/person-merges.js";
85
85
  export { ALWAYS_SHOWN, PERSON_TIES, type PersonTie, type ShownBecause, SMALL_GROUP_MEMBERS, } from "./sqlite/person-ties.js";
86
86
  export type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
@@ -3,7 +3,7 @@ import type { StoreContext } from "./sqlite/open.js";
3
3
  import type { AccountKey, PersonFacts } from "./types.js";
4
4
  /** The row ids behind an account and a chat, and the writes several areas share. */
5
5
  export declare const keysOver: (context: StoreContext) => {
6
- accountPk: (key: AccountKey, name?: string | null) => number;
6
+ accountPk: (key: AccountKey, name?: string | null, startScope?: AccountKey["scope"]) => number;
7
7
  findAccountPk: (key: AccountKey) => number | undefined;
8
8
  findChatPk: (accountKey: number, chatId: Id) => number | undefined;
9
9
  chatKeyOf: (key: AccountKey, chatId: Id) => number | undefined;
@@ -8,7 +8,7 @@ export const keysOver = (context) => {
8
8
  const findAccountPk = (key) => accounts.findAccountPk(context, key);
9
9
  const findChatPk = (accountKey, chatId) => chatQueries.findChatPk(context, accountKey, chatId);
10
10
  return {
11
- accountPk: (key, name = null) => accounts.accountPk(context, key, name),
11
+ accountPk: (key, name = null, startScope) => accounts.accountPk(context, key, name, startScope),
12
12
  findAccountPk,
13
13
  findChatPk,
14
14
  chatKeyOf: (key, chatId) => {
@@ -1,18 +1,19 @@
1
1
  import type { Contact, Id, Page, PersonAlias, Provider } from "../domain/models.js";
2
2
  import type { PersonKind } from "../domain/person-kinds.js";
3
3
  import type { PeopleLookup } from "../resolve.js";
4
+ import type { Decider } from "./decisions.js";
4
5
  import type { IdentityLinkDecision, IdentityLinkFilter, IdentityLinkInput, IdentityLinkRow, MatchScan } from "./identity-links.js";
5
6
  import type { IdentitySplitDecision, IdentitySplitFilter, IdentitySplitInput, IdentitySplitRow } from "./identity-splits.js";
6
7
  import type { ContactFilter } from "./sqlite/identities.js";
7
8
  import type { StoreContext } from "./sqlite/open.js";
8
9
  import { type PeopleList, type PeopleListOptions, type SimilarPerson } from "./sqlite/people-list.js";
9
- import { type PersonDoubts } from "./sqlite/person-doubts.js";
10
+ import { type KeptPerson, type PersonDoubts } from "./sqlite/person-doubts.js";
10
11
  import type { PersonMerge } from "./sqlite/person-merges.js";
11
12
  import { type PersonPreparationRead } from "./sqlite/person-preparation.js";
12
13
  import { type ShownBecause } from "./sqlite/person-ties.js";
13
14
  import type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
14
15
  import type { ProposedAction } from "./sqlite/proposed-actions.js";
15
- import type { AccountKey, IdentityRef, LinkOptions, PersonFacts, PersonRecord, StoredAccount } from "./types.js";
16
+ import type { AccountKey, IdentityRef, LinkOptions, PersonFacts, PersonRecord, StoredAccount, UnlinkOptions } from "./types.js";
16
17
  export interface AccountPeople {
17
18
  savePeople(key: AccountKey, people: PersonFacts[]): Promise<void>;
18
19
  /**
@@ -73,7 +74,7 @@ export interface PeopleStore extends AccountPeople {
73
74
  }): Promise<PersonPreparationRead>;
74
75
  /** Records the decision in `identity_link_events`; `unlinkIdentity` undoes it. */
75
76
  linkIdentities(person: IdentityRef, other: IdentityRef, options: LinkOptions): Promise<PersonRecord>;
76
- unlinkIdentity(identity: IdentityRef, options: LinkOptions): Promise<PersonRecord>;
77
+ unlinkIdentity(identity: IdentityRef, options: UnlinkOptions): Promise<PersonRecord>;
77
78
  /** The people merged into this one, newest first, each with the identities that came from it. */
78
79
  merges(uid: string): Promise<PersonMerge[]>;
79
80
  /** The owner's undo of a merge: the identities that came from `from` go back to it. Gives `from` again. */
@@ -85,7 +86,10 @@ export interface PeopleStore extends AccountPeople {
85
86
  * owner's separation or rejection; an open proposal for the same two people is given back instead of a second.
86
87
  */
87
88
  proposeLink(input: IdentityLinkInput): Promise<ProposedAction>;
88
- /** The owner's decision on an `identity_link`; confirm is refused with `identity.stale` when either person changed. */
89
+ /**
90
+ * The owner's decision on an `identity_link`; confirm is refused with `identity.stale` when either person changed.
91
+ * `company` turns down a shared-mailbox proposal and gives its address to an organization (NEED-2528).
92
+ */
89
93
  decideLink(id: string, decision: IdentityLinkDecision): Promise<ProposedAction>;
90
94
  /**
91
95
  * One pass of the people matcher: the same address joins people in every scope, a phone exactly two people have
@@ -95,7 +99,10 @@ export interface PeopleStore extends AccountPeople {
95
99
  scanMatches(options?: {
96
100
  full?: boolean;
97
101
  }): Promise<MatchScan>;
98
- /** The `identity_link` proposals, newest first, naming the people as they are now; `proposed` unless `status` says. */
102
+ /**
103
+ * The `identity_link` proposals, newest first or by score (`order`), naming the people as they are now; `proposed`
104
+ * unless `status` says.
105
+ */
99
106
  linkProposals(filter: IdentityLinkFilter): Promise<{
100
107
  items: IdentityLinkRow[];
101
108
  hasMore: boolean;
@@ -121,6 +128,11 @@ export interface PeopleStore extends AccountPeople {
121
128
  limit: number;
122
129
  offset: number;
123
130
  }): Promise<PersonDoubts>;
131
+ /**
132
+ * The owner says a person in doubt is right as they are: the identities in doubt stop being listed until one of them
133
+ * moves. The owner's alone; refused with `person.no-doubt` when nothing about the person is in doubt.
134
+ */
135
+ keep(person: string, by: Decider): Promise<KeptPerson>;
124
136
  /** The identity, and everyone linked with it, is the owner. */
125
137
  linkToOwner(identity: IdentityRef): Promise<PersonRecord>;
126
138
  /** A person known by name only, with no identity yet: someone to assign a task to before any message names them. */
@@ -6,9 +6,9 @@ import * as identityProposals from "./sqlite/identity-proposals.js";
6
6
  import * as identitySplits from "./sqlite/identity-split-proposals.js";
7
7
  import { linkToOwner } from "./sqlite/own-identities.js";
8
8
  import { countPeople, listPeople, similarPeople, } from "./sqlite/people-list.js";
9
- import { personDoubts } from "./sqlite/person-doubts.js";
9
+ import { keepPerson, personDoubts } from "./sqlite/person-doubts.js";
10
10
  import * as personLinks from "./sqlite/person-links.js";
11
- import { RULE, scanMatches } from "./sqlite/person-match-scan.js";
11
+ import { PROPOSAL_SCORE, RULE, scanMatches } from "./sqlite/person-match-scan.js";
12
12
  import * as personMerges from "./sqlite/person-merges.js";
13
13
  import { personPreparation } from "./sqlite/person-preparation.js";
14
14
  import { personSeenInAccounts } from "./sqlite/person-scope.js";
@@ -32,7 +32,13 @@ export const accountPeopleOver = (context) => {
32
32
  continue;
33
33
  const held = personLinks.joinByAddress(context, { provider: key.provider, id: person.id }, person.email, key.provider);
34
34
  if (held)
35
- identityProposals.openIdentityLink(context, { ...held, joins: "person", signal: "email", by: RULE });
35
+ identityProposals.openIdentityLink(context, {
36
+ ...held,
37
+ joins: "person",
38
+ signal: "email",
39
+ by: RULE,
40
+ score: PROPOSAL_SCORE.newEvidence,
41
+ });
36
42
  }
37
43
  return saved;
38
44
  };
@@ -129,6 +135,7 @@ export const peopleStoreOver = (context, keyed) => {
129
135
  decideSplit: async (id, decision) => identitySplits.decideIdentitySplit(context, id, decision),
130
136
  splitProposals: async (filter) => identitySplits.identitySplitRows(context, filter),
131
137
  doubts: async (page) => personDoubts(context, page),
138
+ keep: async (person, by) => write(database, () => keepPerson(context, person, by)),
132
139
  linkToOwner: async (identity) => linkToOwner(context, identity),
133
140
  list: async (options) => listPeople(database, options),
134
141
  counts: async (query) => countPeople(database, query),
@@ -1,14 +1,24 @@
1
1
  import type { CacheDatabase } from "../driver.js";
2
2
  import type { AccountKey, StoredAccount } from "../types.js";
3
3
  import type { StoreContext } from "./open.js";
4
- /** An account's row, made on first sight; a name only replaces what was known when there is one. */
5
- export declare const accountPk: ({ orm, now }: StoreContext, { provider, account, scope }: AccountKey, name?: string | null) => number;
4
+ /**
5
+ * An account's row, made on first sight; a name only replaces what was known when there is one. `startScope` is the
6
+ * scope a new row takes; an existing row keeps its own, so a CLI's default never undoes the owner's choice.
7
+ */
8
+ export declare const accountPk: ({ orm, now }: StoreContext, { provider, account, scope }: AccountKey, name?: string | null, startScope?: StoredAccount["scope"]) => number;
6
9
  export declare const findAccountPk: ({ orm }: StoreContext, { provider, account }: AccountKey) => number | undefined;
7
10
  export declare const accountName: ({ orm }: StoreContext, { provider, account }: AccountKey) => string | null;
8
11
  export declare const heldAccounts: ({ orm }: StoreContext) => AccountKey[];
9
12
  export declare const storedAccounts: ({ orm }: StoreContext) => StoredAccount[];
10
13
  /** One account by provider and external id, never created; a missing one is `not_found`. */
11
14
  export declare const storedAccount: ({ orm }: StoreContext, { provider, account }: AccountKey) => StoredAccount;
15
+ /**
16
+ * The owner's word on which side of his life an account is. Triggers move its conversation pieces and involvements;
17
+ * the other search pieces copied the account's scope when they were cut, so they move here, and the word indexes of
18
+ * its documents, mail and calendar events are queued to be built again. A chat with its own scope keeps it; memories
19
+ * and facts carry the scope they were written with.
20
+ */
21
+ export declare const setAccountScope: (context: StoreContext, key: AccountKey, scope: StoredAccount["scope"]) => StoredAccount;
12
22
  /** Everything the account holds, children before parents: the foreign keys are enforced. */
13
23
  export declare const purgeAccount: ({ orm, database, now }: StoreContext, accountKey: number) => void;
14
24
  /** Identity and person rows a person's own record keeps, not evidence that anyone saw them. */
@@ -7,10 +7,20 @@ import { forgetErasedSplits } from "./identity-split-proposals.js";
7
7
  import { mergeSql } from "./merged-persons.js";
8
8
  import { accountIdentities, accounts, aliases, botUpdates, chatEventPeople, chatEvents, chatMembers, chats, chunks, fetchLeases, involvements, memberCounts, memberObservationMembers, memberObservations, memberStays, messageReactions, messageRevisions, messages, messageTranscripts, pollVotes, projects, syncCursors, syncRanges, syncs, } from "./schema.js";
9
9
  import { dropUnusedVectors } from "./vector-index.js";
10
- /** An account's row, made on first sight; a name only replaces what was known when there is one. */
11
- export const accountPk = ({ orm, now }, { provider, account, scope }, name = null) => Number(orm
10
+ /**
11
+ * An account's row, made on first sight; a name only replaces what was known when there is one. `startScope` is the
12
+ * scope a new row takes; an existing row keeps its own, so a CLI's default never undoes the owner's choice.
13
+ */
14
+ export const accountPk = ({ orm, now }, { provider, account, scope }, name = null, startScope) => Number(orm
12
15
  .insert(accounts)
13
- .values({ provider, externalId: account, name, scope: scope ?? "personal", createdAt: now(), updatedAt: now() })
16
+ .values({
17
+ provider,
18
+ externalId: account,
19
+ name,
20
+ scope: scope ?? startScope ?? "personal",
21
+ createdAt: now(),
22
+ updatedAt: now(),
23
+ })
14
24
  .onConflictDoUpdate({
15
25
  target: [accounts.provider, accounts.externalId],
16
26
  set: {
@@ -56,6 +66,35 @@ export const storedAccount = ({ orm }, { provider, account }) => {
56
66
  throw new CliError("not_found", `no ${provider} account ${account} in the store`);
57
67
  return found;
58
68
  };
69
+ /**
70
+ * The owner's word on which side of his life an account is. Triggers move its conversation pieces and involvements;
71
+ * the other search pieces copied the account's scope when they were cut, so they move here, and the word indexes of
72
+ * its documents, mail and calendar events are queued to be built again. A chat with its own scope keeps it; memories
73
+ * and facts carry the scope they were written with.
74
+ */
75
+ export const setAccountScope = (context, key, scope) => {
76
+ const { database, now } = context;
77
+ const held = storedAccount(context, key);
78
+ if (held.scope === scope)
79
+ return held;
80
+ database.prepare("UPDATE accounts SET scope = ?, updated_at = ? WHERE id = ?").run(scope, now(), held.id);
81
+ database
82
+ .prepare("UPDATE chunks SET scope = ? WHERE account_id = ? AND chunkable_type <> 'conversation' AND scope IN ('personal', 'work')")
83
+ .run(scope, held.id);
84
+ for (const [type, ids] of [
85
+ ["document", "SELECT id FROM documents WHERE account_id = ?"],
86
+ ["email", "SELECT id FROM emails WHERE account_id = ?"],
87
+ [
88
+ "event",
89
+ "SELECT DISTINCT ce.event_id AS id FROM calendar_entries ce JOIN calendars c ON c.id = ce.calendar_id " +
90
+ "WHERE c.account_id = ? AND ce.event_id IS NOT NULL",
91
+ ],
92
+ ])
93
+ database
94
+ .prepare(`INSERT OR IGNORE INTO ${type}_index_pending (indexable_type, id) SELECT '${type}', id FROM (${ids})`)
95
+ .run(held.id);
96
+ return { ...held, scope };
97
+ };
59
98
  /** Everything the account holds, children before parents: the foreign keys are enforced. */
60
99
  export const purgeAccount = ({ orm, database, now }, accountKey) => {
61
100
  const unseenBefore = unreferenced(database, "identities");
@@ -0,0 +1,18 @@
1
+ import type { StoreContext } from "./open.js";
2
+ /** Gives the address to the organization, making its `email` identity when the store has none. */
3
+ export declare const holdAddress: ({ database, now }: StoreContext, organization: number, email: string, { method, author }: {
4
+ method: string;
5
+ author: string;
6
+ }) => void;
7
+ /**
8
+ * The organization an address belongs to: the one holding the address, else the one holding its company domain, else
9
+ * the one of exactly this name; else a new company of this name. The address joins it, so the next lookup finds it.
10
+ * More than one match is refused with `reason`, for the caller to name the one meant.
11
+ */
12
+ export declare const organizationOfAddress: (context: StoreContext, { name, email, method, author, reason, }: {
13
+ name: string;
14
+ email?: string;
15
+ method: string;
16
+ author: string;
17
+ reason: string;
18
+ }) => number;
@@ -0,0 +1,48 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { FREE_MAIL } from "../../mail/score.js";
3
+ import { fold } from "../normalize.js";
4
+ const BY_ADDRESS = "SELECT DISTINCT o.id FROM organizations o JOIN organization_identities oi ON oi.organization_id = o.id " +
5
+ "JOIN identities i ON i.id = oi.identity_id WHERE o.deleted_at IS NULL AND i.provider = 'email' AND ";
6
+ const idsOf = (rows) => rows.map((row) => Number(row.id));
7
+ /** Gives the address to the organization, making its `email` identity when the store has none. */
8
+ export const holdAddress = ({ database, now }, organization, email, { method, author }) => {
9
+ const at = now();
10
+ database
11
+ .prepare("INSERT INTO identities (provider, external_id, created_at, updated_at) VALUES ('email', ?, ?, ?) " +
12
+ "ON CONFLICT (provider, external_id) DO NOTHING")
13
+ .run(email, at, at);
14
+ database
15
+ .prepare("INSERT INTO organization_identities (identity_id, organization_id, method, author, created_at, updated_at) " +
16
+ "SELECT id, ?, ?, ?, ?, ? FROM identities WHERE provider = 'email' AND external_id = ? " +
17
+ "ON CONFLICT (identity_id, organization_id) DO NOTHING")
18
+ .run(organization, method, author, at, at, email);
19
+ };
20
+ /**
21
+ * The organization an address belongs to: the one holding the address, else the one holding its company domain, else
22
+ * the one of exactly this name; else a new company of this name. The address joins it, so the next lookup finds it.
23
+ * More than one match is refused with `reason`, for the caller to name the one meant.
24
+ */
25
+ export const organizationOfAddress = (context, { name, email, method, author, reason, }) => {
26
+ const { database, now } = context;
27
+ const domain = email?.split("@")[1];
28
+ let found = email === undefined ? [] : idsOf(database.prepare(`${BY_ADDRESS}lower(i.external_id) = ?`).all(email));
29
+ if (!found.length && domain && !FREE_MAIL.has(domain))
30
+ found = idsOf(database.prepare(`${BY_ADDRESS}substr(lower(i.external_id), -length(?)) = ?`).all(`@${domain}`, `@${domain}`));
31
+ if (!found.length)
32
+ found = database
33
+ .prepare("SELECT id, name FROM organizations WHERE deleted_at IS NULL")
34
+ .all()
35
+ .filter((row) => fold(String(row.name)).trim() === fold(name).trim())
36
+ .map((row) => Number(row.id));
37
+ if (found.length > 1)
38
+ throw new CliError("validation_error", `${found.length} organizations match ${name} (${found.map((id) => `organization:${id}`).join(", ")}); ` +
39
+ "name the one meant as a reference", { reason });
40
+ const at = now();
41
+ const id = found[0] ??
42
+ Number(database
43
+ .prepare("INSERT INTO organizations (kind, name, scope, created_at, updated_at) VALUES ('company', ?, 'work', ?, ?) RETURNING id")
44
+ .get(name, at, at)?.id);
45
+ if (email !== undefined)
46
+ holdAddress(context, id, email, { method, author });
47
+ return id;
48
+ };
@@ -5,10 +5,12 @@ import type { StoreContext } from "./open.js";
5
5
  /** The chat's own id, when the store key is a chat of this account. */
6
6
  export declare const chatOf: ({ orm }: StoreContext, accountKey: number, chatKey: number) => Id | undefined;
7
7
  export declare const findChatPk: ({ orm }: StoreContext, accountKey: number, chatId: Id) => number | undefined;
8
+ /** The owner pins a chat's scope, or with `null` lets it follow its account again; `false` for a chat not stored. */
9
+ export declare const setChatScope: (context: StoreContext, accountKey: number, chatId: Id, scope: string | null) => boolean;
8
10
  /** A chat known only from its messages, until the chat list names it. */
9
11
  export declare const chatPkFor: (context: StoreContext, accountKey: number, chatId: Id) => number;
10
12
  /** The store write a `chat_revisions` row names; a writer that sets none is recorded as NULL. */
11
- export type ChatRevisionSource = "chats" | "delta" | "left" | "rejoin" | "rekey" | "merge" | "send" | "details";
13
+ export type ChatRevisionSource = "chats" | "delta" | "left" | "rejoin" | "rekey" | "merge" | "send" | "details" | "owner";
12
14
  /**
13
15
  * Runs `body` with `source` as what the `chat_revisions` trigger records, inside the caller's transaction. The row is
14
16
  * gone again before the commit, so an older build's write in a later transaction records no source rather than this
@@ -20,6 +20,14 @@ export const findChatPk = ({ orm }, accountKey, chatId) => orm
20
20
  .from(chats)
21
21
  .where(and(eq(chats.accountId, accountKey), eq(chats.externalId, chatId)))
22
22
  .get()?.pk;
23
+ /** The owner pins a chat's scope, or with `null` lets it follow its account again; `false` for a chat not stored. */
24
+ export const setChatScope = (context, accountKey, chatId, scope) => {
25
+ const pk = findChatPk(context, accountKey, chatId);
26
+ if (pk === undefined)
27
+ return false;
28
+ revisedBy(context, "owner", () => context.database.prepare("UPDATE chats SET scope = ?, updated_at = ? WHERE id = ?").run(scope, context.now(), pk));
29
+ return true;
30
+ };
23
31
  /** A chat known only from its messages, until the chat list names it. */
24
32
  export const chatPkFor = (context, accountKey, chatId) => findChatPk(context, accountKey, chatId) ??
25
33
  Number(context.orm
@@ -14,10 +14,14 @@ export declare const pkOf: (database: CacheDatabase, ref: string) => number | un
14
14
  export declare const personOf: (database: CacheDatabase, identity: number | undefined) => number | undefined;
15
15
  /** The people a proposal's identities are on now; merges since may have moved either side. */
16
16
  export declare const currentPairOf: (database: CacheDatabase, payload: IdentityLinkPayload) => [number, number] | undefined;
17
- /** The proposals that still say something: waiting for the owner, or turned down by them; a `page` is newest first. */
17
+ /**
18
+ * The proposals that still say something: waiting for the owner, or turned down by them. A `page` is newest first, or
19
+ * by score with `order: "score"`; without a page, oldest first.
20
+ */
18
21
  export declare const linkRows: (database: CacheDatabase, statuses?: readonly string[], page?: {
19
22
  limit: number;
20
23
  offset: number;
24
+ order?: "newest" | "score";
21
25
  }) => LinkRow[];
22
26
  /**
23
27
  * What a proposal rests on: its signal and the two identities it names, in either order. The owner's rejection
@@ -23,10 +23,16 @@ export const currentPairOf = (database, payload) => {
23
23
  : personOf(database, pkOf(database, payload.with));
24
24
  return from === undefined || to === undefined ? undefined : [from, to];
25
25
  };
26
- /** The proposals that still say something: waiting for the owner, or turned down by them; a `page` is newest first. */
26
+ const BY_SCORE = "json_extract(payload, '$.score') IS NULL, json_extract(payload, '$.score') DESC, id DESC";
27
+ /**
28
+ * The proposals that still say something: waiting for the owner, or turned down by them. A `page` is newest first, or
29
+ * by score with `order: "score"`; without a page, oldest first.
30
+ */
27
31
  export const linkRows = (database, statuses = ["proposed", "rejected"], page) => database
28
- .prepare("SELECT id, status, payload FROM proposed_actions WHERE kind = ? " +
29
- `AND status IN (SELECT value FROM json_each(?)) ORDER BY id${page === undefined ? "" : " DESC LIMIT ? OFFSET ?"}`)
32
+ .prepare("SELECT id, status, payload FROM proposed_actions WHERE kind = ? AND status IN (SELECT value FROM json_each(?)) " +
33
+ (page === undefined
34
+ ? "ORDER BY id"
35
+ : `ORDER BY ${page.order === "score" ? BY_SCORE : "id DESC"} LIMIT ? OFFSET ?`))
30
36
  .all(IDENTITY_LINK_KIND, JSON.stringify(statuses), ...(page === undefined ? [] : [page.limit, page.offset]))
31
37
  .map((row) => {
32
38
  const payload = JSON.parse(String(row.payload));
@@ -1,4 +1,4 @@
1
- import { type IdentityLinkDecision, type IdentityLinkFilter, type IdentityLinkInput, type IdentityLinkPayload, type IdentityLinkRow, type IdentityLinkSignal } from "../identity-links.js";
1
+ import { type IdentityLinkDecision, type IdentityLinkFilter, type IdentityLinkInput, type IdentityLinkPayload, type IdentityLinkRow, type IdentityLinkSignal, type SharedMailbox } from "../identity-links.js";
2
2
  import type { IdentityRef, LinkOptions } from "../types.js";
3
3
  import { type LinkIndex } from "./identity-link-rows.js";
4
4
  import type { Author } from "./memories.js";
@@ -17,6 +17,8 @@ export interface Opening {
17
17
  score?: number | undefined;
18
18
  evidence?: string[] | undefined;
19
19
  candidates?: number[] | undefined;
20
+ shared?: SharedMailbox | undefined;
21
+ mailbox?: string | undefined;
20
22
  }
21
23
  export type Opened = {
22
24
  outcome: "proposed" | "open";
@@ -46,8 +48,8 @@ export declare const linkOrPropose: (context: StoreContext, identity: number, ta
46
48
  * proposes the pair again.
47
49
  */
48
50
  export declare const decideIdentityLink: (context: StoreContext, id: string, decision: IdentityLinkDecision) => ProposedAction;
49
- /** The `identity_link` proposals, newest first, each naming its people as they are now; a page and whether more follow. */
50
- export declare const identityLinkRows: (context: StoreContext, { person, status, limit, offset }: IdentityLinkFilter) => {
51
+ /** The `identity_link` proposals, newest first or by score, each naming its people as they are now; a page and whether more follow. */
52
+ export declare const identityLinkRows: (context: StoreContext, { person, status, order, limit, offset }: IdentityLinkFilter) => {
51
53
  items: IdentityLinkRow[];
52
54
  hasMore: boolean;
53
55
  };